[
  {
    "path": ".codesandbox/ci.json",
    "content": "{\n  \"sandboxes\": [\n    \"vanilla\",\n    \"vanilla-ts\",\n    \"/examples/query/react/basic\",\n    \"/examples/query/react/advanced\",\n    \"/examples/action-listener/counter\",\n    \"/examples/publish-ci/cra5\"\n  ],\n  \"node\": \"20\",\n  \"buildCommand\": \"build:packages\",\n  \"packages\": [\n    \"packages/toolkit\",\n    \"packages/rtk-query-graphql-request-base-query\",\n    \"packages/rtk-query-codegen-openapi\"\n  ],\n  \"publishDirectory\": {\n    \"@reduxjs/toolkit\": \"packages/toolkit\",\n    \"@rtk-query/graphql-request-base-query\": \"packages/rtk-query-graphql-request-base-query\",\n    \"@rtk-query/codegen-openapi\": \"packages/rtk-query-codegen-openapi\"\n  }\n}\n"
  },
  {
    "path": ".eslintrc.js",
    "content": "module.exports = {\n  extends: ['react-app', 'prettier'],\n  parser: '@typescript-eslint/parser',\n  rules: {\n    'jsx-a11y/href-no-hash': 'off',\n    'react/react-in-jsx-scope': 'off',\n    // Taken care of by TypeScript's `noUnusedLocals` / `noUnusedParameters`\n    'no-unused-vars': 'off',\n    '@typescript-eslint/no-unused-vars': 'off',\n    // Silence some bizarre \"rule not found\" TSLint error\n    '@typescript-eslint/no-angle-bracket-type-assertion': 'off',\n    'no-redeclare': 'off',\n    // Silence some bizarre \"rule not found\" TSLint error\n    '@typescript-eslint/no-redeclare': 'off',\n    'no-use-before-define': 'off',\n    '@typescript-eslint/no-use-before-define': ['error', { functions: false }],\n    '@typescript-eslint/consistent-type-imports': [\n      'error',\n      { prefer: 'type-imports', disallowTypeAnnotations: false },\n    ],\n    'react-hooks/exhaustive-deps': [\n      'warn',\n      {\n        additionalHooks: '(usePossiblyImmediateEffect)',\n      },\n    ],\n  },\n  overrides: [\n    // {\n    //   // only add after https://github.com/typescript-eslint/typescript-eslint/pull/3463 is merged\n    //   files: ['src/**/*.ts'],\n    //   excludedFiles: [\n    //     '**/tests/*.ts',\n    //     '**/tests/**/*.ts',\n    //     '**/tests/*.tsx',\n    //     '**/tests/**/*.tsx',\n    //   ],\n    //   parserOptions: {\n    //     project: './tsconfig.json',\n    //   },\n    //   rules: {\n    //     '@typescript-eslint/prefer-readonly-parameter-types': [\n    //       'warn',\n    //       { arraysAndTuplesOnly: true },\n    //     ],\n    //   },\n    // },\n    {\n      files: [\n        'packages/toolkit/src/tests/*.ts',\n        'packages/toolkit/src/**/tests/*.ts',\n        'packages/toolkit/src/**/tests/*.tsx',\n      ],\n      rules: {\n        '@typescript-eslint/no-unused-expressions': 'off',\n        'no-lone-blocks': 'off',\n        'no-sequences': 'off',\n      },\n    },\n  ],\n}\n"
  },
  {
    "path": ".gitattributes",
    "content": "* text=auto eol=lf\n"
  },
  {
    "path": ".github/FUNDING.yml",
    "content": "github: [phryneas, markerikson, EskiMojo14]\n"
  },
  {
    "path": ".github/workflows/publish.yml",
    "content": "name: Publish Package to npmjs\non:\n  # keeping it purely manual for now as to not accidentally trigger a release\n  #release:\n  #  types: [published]\n  workflow_dispatch:\n    inputs:\n      package:\n        description: 'Package'\n        required: true\n        type: choice\n        options:\n          - '@reduxjs/toolkit'\n          - '@rtk-query/codegen-openapi'\n          - '@rtk-query/graphql-request-base-query'\n          - '@reduxjs/rtk-codemods'\n      tag:\n        description: 'NPM dist-tag (latest, alpha, beta, next)'\n        required: true\n        default: 'latest'\n        type: choice\n        options:\n          - latest\n          - next\n          - alpha\n          - beta\n\npermissions: {}\n\njobs:\n  publish:\n    runs-on: ubuntu-latest\n    permissions:\n      id-token: write\n      contents: read\n    steps:\n      - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n        with:\n          persist-credentials: false\n      - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: '24.x'\n          registry-url: 'https://registry.npmjs.org'\n          cache: 'yarn'\n      - run: yarn install --frozen-lockfile\n      - run: yarn workspace ${{ inputs.package }} test\n      - run: yarn workspace ${{ inputs.package }} exec npm publish --access public --provenance --tag ${{ inputs.tag }}\n"
  },
  {
    "path": ".github/workflows/size.yml",
    "content": "name: size\non:\n  pull_request:\n    branches:\n      - master\n      - 'feature/infinite-query-integration'\npermissions:\n  pull-requests: write\njobs:\n  size:\n    runs-on: ubuntu-latest\n    env:\n      CI_JOB_NUMBER: 1\n    steps:\n      - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n      - uses: EskiMojo14/size-limit-action@af0584be5b6cc2d056bd31a314fc2ce9c9c1a929 # v2\n        with:\n          directory: packages/toolkit\n          github_token: ${{ secrets.GITHUB_TOKEN }}\n          build_script: build-only\n          package_manager: yarn\n          size_margin: non-zero\n"
  },
  {
    "path": ".github/workflows/test-codegen.yml",
    "content": "# This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node\n# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions\n\nname: RTKQ OpenAPI Codegen\ndefaults:\n  run:\n    working-directory: ./packages/rtk-query-codegen-openapi\n\non: [push, pull_request]\n\njobs:\n  changes:\n    name: Check for changes\n    runs-on: ubuntu-latest\n    outputs:\n      codegen: ${{ steps.filter.outputs.codegen }}\n    steps:\n      - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n      - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3\n        id: filter\n        with:\n          filters: |\n            codegen:\n              - 'packages/rtk-query-codegen-openapi/**'\n              - 'yarn.lock'\n              - '.github/workflows/test-codegen.yml'\n\n  build:\n    needs: [changes]\n    if: ${{ needs.changes.outputs.codegen == 'true' }}\n\n    defaults:\n      run:\n        working-directory: ./packages/rtk-query-codegen-openapi\n\n    runs-on: ${{ matrix.os }}\n\n    name: 'Build artifact: ${{ matrix.os }} + Node ${{ matrix.node-version }}'\n\n    strategy:\n      matrix:\n        node-version: ['24.x']\n        os: [ubuntu-latest]\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n\n      - name: Setup Node ${{ matrix.node-version }}\n        uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: ${{ matrix.node-version }}\n          cache: 'yarn'\n\n      - name: Install dependencies\n        run: yarn install\n\n      - name: Pack\n        run: yarn pack\n\n      - name: Upload artifact\n        uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4\n        id: artifact-upload-step\n        with:\n          name: package\n          path: ./packages/rtk-query-codegen-openapi/package.tgz\n\n      - name: Did we fail?\n        if: failure()\n        run: ls -lR\n\n  test:\n    needs: build\n    defaults:\n      run:\n        working-directory: ./packages/rtk-query-codegen-openapi\n    name: 'Test build artifact: ${{ matrix.os }} + Node ${{ matrix.node-version }}'\n    runs-on: ${{ matrix.os }}\n    strategy:\n      fail-fast: false\n      matrix:\n        node-version: [24.x]\n        os: [ubuntu-latest]\n\n    steps:\n      - name: Checkout repository\n        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n\n      - name: Setup Node ${{ matrix.node-version }}\n        uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: ${{ matrix.node-version }}\n          cache: 'yarn'\n\n      - name: Download artifact\n        id: download-artifact\n        uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4\n        with:\n          path: ./packages/rtk-query-codegen-openapi\n          name: package\n\n      - name: Install dependencies\n        run: yarn install\n\n      - name: Install build artifact\n        run: yarn add ./package.tgz\n\n      - name: Remove path alias\n        run: sed -i -e /@remap-prod-remove-line/d ./tsconfig.json\n\n      - name: Run tests\n        run: yarn test\n        env:\n          TEST_DIST: true\n\n      - name: Did we fail?\n        if: failure()\n        run: ls -R\n\n  are-the-types-wrong:\n    name: Check package definition with are-the-types-wrong\n\n    needs: [build]\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        node-version: [24.x]\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n\n      - name: Use node ${{ matrix.node-version }}\n        uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: ${{ matrix.node-version }}\n          cache: 'yarn'\n\n      - name: Install deps\n        run: yarn install\n\n      - name: Download artifact\n        id: download-artifact\n        uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4\n        with:\n          path: ./packages/rtk-query-codegen-openapi\n          name: package\n\n      - name: Run are-the-types-wrong\n        run: yarn dlx @arethetypeswrong/cli@latest ./package.tgz --format table --exclude-entrypoints cli\n"
  },
  {
    "path": ".github/workflows/tests.yml",
    "content": "name: CI\non:\n  push:\n    branches: [master]\n  pull_request:\ndefaults:\n  run:\n    working-directory: ./packages/toolkit\n\njobs:\n  changes:\n    name: Check for changes\n    runs-on: ubuntu-latest\n    outputs:\n      toolkit: ${{ steps.filter.outputs.toolkit }}\n    steps:\n      - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n      - uses: dorny/paths-filter@de90cc6fb38fc0963ad72b210f1f284cd68cea36 # v3\n        id: filter\n        with:\n          filters: |\n            toolkit:\n              - 'packages/toolkit/**'\n              - 'examples/publish-ci/**'\n              - '.github/workflows/tests.yml'\n              - 'yarn.lock'\n\n  build:\n    needs: changes\n    if: ${{ needs.changes.outputs.toolkit == 'true' }}\n\n    name: Lint, Test, Build & Pack on Node ${{ matrix.node }}\n\n    runs-on: ubuntu-latest\n    strategy:\n      matrix:\n        node: ['24.x']\n\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n\n      - name: Use node ${{ matrix.node }}\n        uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: ${{ matrix.node }}\n          cache: 'yarn'\n\n      - name: Install deps\n        run: yarn install\n\n      # Read existing version, reuse that, add a Git short hash\n      - name: Set build version to Git commit\n        run: yarn tsx scripts/writeGitVersion.mts $(git rev-parse --short HEAD)\n\n      - name: Check updated version\n        run: jq .version package.json\n\n      - name: Pack\n        run: yarn pack\n\n      - uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4\n        with:\n          name: package\n          path: packages/toolkit/package.tgz\n\n  test-dist:\n    name: Run local tests against build artifact (React ${{ matrix.react.version }})\n    needs: [build]\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        node: ['24.x']\n        react:\n          - version: '^18'\n            types: '^18'\n            react-dom: { version: '^18', types: '^18' }\n          - version: '^19'\n            types: '^19'\n            react-dom: { version: '^19', types: '^19' }\n\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n\n      - name: Use node ${{ matrix.node }}\n        uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: ${{ matrix.node }}\n          cache: 'yarn'\n\n      - name: Install deps\n        run: yarn install\n\n      - name: Download build artifact\n        uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4\n        with:\n          name: package\n          path: packages/toolkit\n\n      - name: Check folder contents\n        run: ls -lah\n\n      - name: Install React ${{ matrix.react.version }} and React-DOM ${{ matrix.react.react-dom.version }}\n        run: yarn up react@${{ matrix.react.version }} react-dom@${{ matrix.react.react-dom.version }} @types/react@${{ matrix.react.types }} @types/react-dom@${{ matrix.react.react-dom.types }}\n\n      - name: Install build artifact\n        run: yarn workspace @reduxjs/toolkit add $(pwd)/package.tgz\n\n      - name: Erase path aliases\n        run: sed -i -e /@remap-prod-remove-line/d ./tsconfig.base.json\n\n      - name: Run type tests with `moduleResolution Bundler`\n        run: rm -rf dist && yarn tsc -p . --moduleResolution Bundler --module ESNext --noEmit false --declaration --emitDeclarationOnly --outDir dist --target ESNext && rm -rf dist\n\n      - name: Ensure there's no dist folder\n        run: rm -rf dist\n\n      - name: Change RTK package name to ensure node_modules is used\n        run: sed -i -e 's|@reduxjs/toolkit|@reduxjs/toolkit-test|' ./package.json\n\n      - name: Run tests, against installed artifact\n        env:\n          TEST_DIST: true\n        working-directory: ./packages/toolkit\n        run: ../../node_modules/.bin/vitest --run --typecheck\n\n  test-types:\n    name: 'Test Types: TS ${{ matrix.ts }} and React ${{ matrix.react.version }}'\n\n    needs: [build]\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        # Sparse matrix: All TS versions with React 19, boundary TS versions with React 18\n        include:\n          # React 19 × all TS versions\n          - node: '24.x'\n            ts: '5.4'\n            react:\n              {\n                version: '^19',\n                types: '^19',\n                react-dom: { version: '^19', types: '^19' },\n              }\n          - node: '24.x'\n            ts: '5.5'\n            react:\n              {\n                version: '^19',\n                types: '^19',\n                react-dom: { version: '^19', types: '^19' },\n              }\n          - node: '24.x'\n            ts: '5.6'\n            react:\n              {\n                version: '^19',\n                types: '^19',\n                react-dom: { version: '^19', types: '^19' },\n              }\n          - node: '24.x'\n            ts: '5.7'\n            react:\n              {\n                version: '^19',\n                types: '^19',\n                react-dom: { version: '^19', types: '^19' },\n              }\n          - node: '24.x'\n            ts: '5.8'\n            react:\n              {\n                version: '^19',\n                types: '^19',\n                react-dom: { version: '^19', types: '^19' },\n              }\n          - node: '24.x'\n            ts: '5.9'\n            react:\n              {\n                version: '^19',\n                types: '^19',\n                react-dom: { version: '^19', types: '^19' },\n              }\n          - node: '24.x'\n            ts: 'next'\n            react:\n              {\n                version: '^19',\n                types: '^19',\n                react-dom: { version: '^19', types: '^19' },\n              }\n          # React 18 × boundary TS versions only (5.4, 5.9, next)\n          - node: '24.x'\n            ts: '5.4'\n            react:\n              {\n                version: '^18',\n                types: '^18',\n                react-dom: { version: '^18', types: '^18' },\n              }\n          - node: '24.x'\n            ts: '5.9'\n            react:\n              {\n                version: '^18',\n                types: '^18',\n                react-dom: { version: '^18', types: '^18' },\n              }\n          - node: '24.x'\n            ts: 'next'\n            react:\n              {\n                version: '^18',\n                types: '^18',\n                react-dom: { version: '^18', types: '^18' },\n              }\n\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n\n      - name: Use node ${{ matrix.node }}\n        uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: ${{ matrix.node }}\n          cache: 'yarn'\n\n      - name: Install deps\n        run: yarn install\n\n      - name: Install React ${{ matrix.react.version }} and React-DOM ${{ matrix.react.react-dom.version }}\n        run: yarn up react@${{ matrix.react.version }} react-dom@${{ matrix.react.react-dom.version }} @types/react@${{ matrix.react.types }} @types/react-dom@${{ matrix.react.react-dom.types }}\n\n      - name: Install TypeScript ${{ matrix.ts }}\n        run: yarn add typescript@${{ matrix.ts }}\n\n      - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4\n        with:\n          name: package\n          path: packages/toolkit\n\n      - name: Install build artifact\n        run: yarn add ./package.tgz\n\n      - name: Show installed RTK versions\n        run: yarn info @reduxjs/toolkit\n\n      - name: Erase path aliases\n        run: sed -i -e /@remap-prod-remove-line/d ./tsconfig.base.json\n\n      - name: Test types (TS 5.x)\n        if: matrix.ts != 'next' && !startsWith(matrix.ts, '6.')\n        env:\n          TEST_DIST: true\n        run: |\n          yarn tsc --version\n          yarn type-tests\n\n      - name: Test types (TS 6.x/next)\n        if: matrix.ts == 'next' || startsWith(matrix.ts, '6.')\n        env:\n          TEST_DIST: true\n        run: |\n          yarn tsc --version\n          yarn tsc -p tsconfig.test.json --noEmit --ignoreDeprecations 6.0\n\n  test-published-artifact:\n    name: Test Published Artifact ${{ matrix.example }}\n\n    needs: [build]\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        node: ['24.x']\n        example:\n          [\n            'cra4',\n            'cra5',\n            'next',\n            'vite',\n            'node-standard',\n            'node-esm',\n            'react-native',\n            'expo',\n          ]\n    defaults:\n      run:\n        working-directory: ./examples/publish-ci/${{ matrix.example }}\n    env:\n      YARN_ENABLE_IMMUTABLE_INSTALLS: false\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n\n      - name: Use node ${{ matrix.node }}\n        uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: ${{ matrix.node }}\n          cache: 'yarn'\n\n      - name: Install deps\n        run: yarn install\n\n      - name: Remove existing RTK\n        run: yarn remove @reduxjs/toolkit\n\n      - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4\n        with:\n          name: package\n          path: ./examples/publish-ci/${{ matrix.example }}\n\n      - name: Check folder contents\n        run: ls -l .\n\n      - name: Install RTK build artifact\n        run: yarn add ./package.tgz\n\n      - name: Show installed RTK versions\n        run: yarn info @reduxjs/toolkit && yarn why @reduxjs/toolkit\n\n      - name: Set up JDK 21 for React Native build\n        if: matrix.example == 'react-native' || matrix.example == 'expo'\n        uses: actions/setup-java@c1e323688fd81a25caa38c78aa6df2d33d3e20d9 # v4\n        with:\n          java-version: '21.x'\n          distribution: 'temurin'\n          cache: 'gradle'\n\n      - name: Build example\n        env:\n          NODE_OPTIONS: --openssl-legacy-provider\n        run: yarn build\n\n      - name: Run test step\n        run: yarn test\n\n  are-the-types-wrong:\n    name: Check package config with are-the-types-wrong\n\n    needs: [build]\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        node: ['24.x']\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n\n      - name: Use node ${{ matrix.node }}\n        uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: ${{ matrix.node }}\n          cache: 'yarn'\n\n      - name: Install deps\n        run: yarn install\n\n      - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4\n        with:\n          name: package\n          path: packages/toolkit\n\n      - name: show folder\n        run: ls -l .\n\n      - name: Run are-the-types-wrong\n        run: yarn attw ./package.tgz --format table\n\n  test-type-portability:\n    name: 'Test Type Portability: TS ${{ matrix.ts }} + Node ${{ matrix.node }}'\n    needs: [build]\n    runs-on: ubuntu-latest\n    strategy:\n      fail-fast: false\n      matrix:\n        # Sparse matrix: All TS versions with bundler, boundary TS versions with nodenext\n        include:\n          # bundler × all TS versions\n          - node: '24.x'\n            ts: '5.4'\n            example: { name: 'bundler', moduleResolution: 'Bundler' }\n          - node: '24.x'\n            ts: '5.5'\n            example: { name: 'bundler', moduleResolution: 'Bundler' }\n          - node: '24.x'\n            ts: '5.6'\n            example: { name: 'bundler', moduleResolution: 'Bundler' }\n          - node: '24.x'\n            ts: '5.7'\n            example: { name: 'bundler', moduleResolution: 'Bundler' }\n          - node: '24.x'\n            ts: '5.8'\n            example: { name: 'bundler', moduleResolution: 'Bundler' }\n          - node: '24.x'\n            ts: '5.9'\n            example: { name: 'bundler', moduleResolution: 'Bundler' }\n          - node: '24.x'\n            ts: 'next'\n            example: { name: 'bundler', moduleResolution: 'Bundler' }\n          # nodenext-cjs × boundary TS versions only (5.4, 5.9, next)\n          - node: '24.x'\n            ts: '5.4'\n            example: { name: 'nodenext-cjs', moduleResolution: 'NodeNext' }\n          - node: '24.x'\n            ts: '5.9'\n            example: { name: 'nodenext-cjs', moduleResolution: 'NodeNext' }\n          - node: '24.x'\n            ts: 'next'\n            example: { name: 'nodenext-cjs', moduleResolution: 'NodeNext' }\n          # nodenext-esm × boundary TS versions only (5.4, 5.9, next)\n          - node: '24.x'\n            ts: '5.4'\n            example: { name: 'nodenext-esm', moduleResolution: 'NodeNext' }\n          - node: '24.x'\n            ts: '5.9'\n            example: { name: 'nodenext-esm', moduleResolution: 'NodeNext' }\n          - node: '24.x'\n            ts: 'next'\n            example: { name: 'nodenext-esm', moduleResolution: 'NodeNext' }\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n\n      - name: Use node ${{ matrix.node }}\n        uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: ${{ matrix.node }}\n          cache: 'yarn'\n\n      - name: Install deps\n        run: yarn install\n\n      - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4\n        with:\n          name: package\n          path: packages/toolkit\n\n      - name: Install build artifact\n        run: yarn workspace @examples-type-portability/${{ matrix.example.name }} add $(pwd)/package.tgz\n\n      - name: Install TypeScript ${{ matrix.ts }}\n        run: yarn workspace @examples-type-portability/${{ matrix.example.name }} add -D typescript@${{ matrix.ts }}\n\n      - name: Test type portability with `moduleResolution ${{ matrix.example.moduleResolution }}`\n        run: yarn workspace @examples-type-portability/${{ matrix.example.name }} run test\n\n      - name: Test type portability with `moduleResolution Node10`\n        if: matrix.ts != 'next' && !startsWith(matrix.ts, '6.')\n        run: yarn workspace @examples-type-portability/${{ matrix.example.name }} run test --module CommonJS --moduleResolution Node10 --preserveSymLinks --verbatimModuleSyntax false\n\n      - name: Test type portability with `moduleResolution Node10` and `type module` in `package.json`\n        if: (matrix.example.name == 'nodenext-esm' || matrix.example.name == 'bundler') && matrix.ts != 'next' && !startsWith(matrix.ts, '6.')\n        run: |\n          npm --workspace=@examples-type-portability/${{ matrix.example.name }} pkg set type=module\n          yarn workspace @examples-type-portability/${{ matrix.example.name }} run test --module ESNext --moduleResolution Node10 --preserveSymLinks --verbatimModuleSyntax false\n\n  test-types-native-preview:\n    if: false # Disabled pending TS 7.0 compatibility fixes\n    name: 'Test Types: TypeScript Native Preview'\n    needs: [build]\n    runs-on: ubuntu-latest\n    continue-on-error: true\n    strategy:\n      matrix:\n        node: ['24.x']\n    steps:\n      - name: Checkout repo\n        uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n\n      - name: Use node ${{ matrix.node }}\n        uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: ${{ matrix.node }}\n          cache: 'yarn'\n\n      - name: Install deps\n        run: yarn install\n\n      - name: Install TypeScript Native Preview\n        run: yarn add @typescript/native-preview\n\n      - uses: actions/download-artifact@d3f86a106a0bac45b974a628896c90dbdf5c8093 # v4\n        with:\n          name: package\n          path: packages/toolkit\n\n      - name: Install build artifact\n        run: yarn add ./package.tgz\n\n      - name: Show installed RTK versions\n        run: yarn info @reduxjs/toolkit\n\n      - name: Erase path aliases\n        run: sed -i -e /@remap-prod-remove-line/d ./tsconfig.base.json\n\n      - name: Test types with tsgo\n        env:\n          TEST_DIST: true\n        run: |\n          yarn tsgo --version\n          yarn tsgo -p tsconfig.test.json --noEmit --moduleResolution Bundler\n\n      - name: Install build artifact for type-portability example\n        run: yarn workspace @examples-type-portability/bundler add $(pwd)/package.tgz\n\n      - name: Install TypeScript Native Preview for type-portability example\n        run: yarn workspace @examples-type-portability/bundler add -D @typescript/native-preview\n\n      - name: Test type portability with tsgo (bundler example)\n        run: yarn workspace @examples-type-portability/bundler exec tsgo --noEmit\n"
  },
  {
    "path": ".gitignore",
    "content": ".DS_Store\n*.log\nnode_modules\n# Dist and query are both build output folders\ndist*/\n# But don't ignore the RTK Query source\nlib\nes\n\n.yalc\nyalc.lock\nyalc.sig\n\n.idea/\n.vscode/\ntemp/\n.tmp-projections\nbuild/\n.rts2*\ncoverage/\n\ntypesversions\n.cache\n.yarnrc\n.yarn/*\n!.yarn/patches\n!.yarn/releases\n!.yarn/plugins\n!.yarn/sdks\n!.yarn/versions\n.pnp.*\n*.tgz\n\ntsconfig.vitest-temp.json\n\n# node version manager files\n.node-version\n.nvmrc\n\n# Assorted local docs\ndocs/dev-plans\n# Perf protobufs\n*.pb.gz"
  },
  {
    "path": ".prettierignore",
    "content": "**/dist/**\n**/etc/**\n**/temp/**\n**/__testfixtures__/**"
  },
  {
    "path": ".prettierrc.json",
    "content": "{\n  \"semi\": false,\n  \"singleQuote\": true\n}\n"
  },
  {
    "path": ".yarn/patches/size-limit-npm-11.0.1-05996e44e7.patch",
    "content": "diff --git a/get-config.js b/get-config.js\nindex 76ebaee5455b2a4bacb986784bd1b53ad89adeb7..1b092e645b258f4a6533ca88b7d36dbcde4eb6de 100644\n--- a/get-config.js\n+++ b/get-config.js\n@@ -132,7 +132,7 @@ export default async function getConfig(plugins, process, args, pkg) {\n         } else if (!check.entry) {\n           if (pkg.packageJson.main) {\n             processed.files = [\n-              require.resolve(join(dirname(pkg.path), pkg.packageJson.main))\n+              import.meta.resolve(join(dirname(pkg.path), pkg.packageJson.main))\n             ]\n           } else {\n             processed.files = [join(dirname(pkg.path), 'index.js')]\n@@ -177,7 +177,7 @@ export default async function getConfig(plugins, process, args, pkg) {\n       for (let i in check.import) {\n         if (peer.includes(i)) {\n           check.ignore = check.ignore.filter(j => j !== i)\n-          imports[require.resolve(i, config.cwd)] = check.import[i]\n+          imports[import.meta.resolve(i, config.cwd)] = check.import[i]\n         } else {\n           imports[toAbsolute(i, config.cwd)] = check.import[i]\n         }\n"
  },
  {
    "path": ".yarn/releases/yarn-4.4.1.cjs",
    "content": "#!/usr/bin/env node\n/* eslint-disable */\n//prettier-ignore\n(()=>{var t_e=Object.create;var vR=Object.defineProperty;var r_e=Object.getOwnPropertyDescriptor;var n_e=Object.getOwnPropertyNames;var i_e=Object.getPrototypeOf,s_e=Object.prototype.hasOwnProperty;var ve=(t=>typeof require<\"u\"?require:typeof Proxy<\"u\"?new Proxy(t,{get:(e,r)=>(typeof require<\"u\"?require:e)[r]}):t)(function(t){if(typeof require<\"u\")return require.apply(this,arguments);throw Error('Dynamic require of \"'+t+'\" is not supported')});var Et=(t,e)=>()=>(t&&(e=t(t=0)),e);var _=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Vt=(t,e)=>{for(var r in e)vR(t,r,{get:e[r],enumerable:!0})},o_e=(t,e,r,o)=>{if(e&&typeof e==\"object\"||typeof e==\"function\")for(let a of n_e(e))!s_e.call(t,a)&&a!==r&&vR(t,a,{get:()=>e[a],enumerable:!(o=r_e(e,a))||o.enumerable});return t};var Ze=(t,e,r)=>(r=t!=null?t_e(i_e(t)):{},o_e(e||!t||!t.__esModule?vR(r,\"default\",{value:t,enumerable:!0}):r,t));var Bi={};Vt(Bi,{SAFE_TIME:()=>D7,S_IFDIR:()=>iD,S_IFLNK:()=>sD,S_IFMT:()=>Uu,S_IFREG:()=>Dw});var Uu,iD,Dw,sD,D7,P7=Et(()=>{Uu=61440,iD=16384,Dw=32768,sD=40960,D7=456789e3});var nr={};Vt(nr,{EBADF:()=>Io,EBUSY:()=>a_e,EEXIST:()=>p_e,EINVAL:()=>c_e,EISDIR:()=>f_e,ENOENT:()=>u_e,ENOSYS:()=>l_e,ENOTDIR:()=>A_e,ENOTEMPTY:()=>g_e,EOPNOTSUPP:()=>d_e,EROFS:()=>h_e,ERR_DIR_CLOSED:()=>DR});function Tl(t,e){return Object.assign(new Error(`${t}: ${e}`),{code:t})}function a_e(t){return Tl(\"EBUSY\",t)}function l_e(t,e){return Tl(\"ENOSYS\",`${t}, ${e}`)}function c_e(t){return Tl(\"EINVAL\",`invalid argument, ${t}`)}function Io(t){return Tl(\"EBADF\",`bad file descriptor, ${t}`)}function u_e(t){return Tl(\"ENOENT\",`no such file or directory, ${t}`)}function A_e(t){return Tl(\"ENOTDIR\",`not a directory, ${t}`)}function f_e(t){return Tl(\"EISDIR\",`illegal operation on a directory, ${t}`)}function p_e(t){return Tl(\"EEXIST\",`file already exists, ${t}`)}function h_e(t){return Tl(\"EROFS\",`read-only filesystem, ${t}`)}function g_e(t){return Tl(\"ENOTEMPTY\",`directory not empty, ${t}`)}function d_e(t){return Tl(\"EOPNOTSUPP\",`operation not supported, ${t}`)}function DR(){return Tl(\"ERR_DIR_CLOSED\",\"Directory handle was closed\")}var oD=Et(()=>{});var wa={};Vt(wa,{BigIntStatsEntry:()=>qd,DEFAULT_MODE:()=>SR,DirEntry:()=>PR,StatEntry:()=>Hd,areStatsEqual:()=>xR,clearStats:()=>aD,convertToBigIntStats:()=>y_e,makeDefaultStats:()=>b7,makeEmptyStats:()=>m_e});function b7(){return new Hd}function m_e(){return aD(b7())}function aD(t){for(let e in t)if(Object.hasOwn(t,e)){let r=t[e];typeof r==\"number\"?t[e]=0:typeof r==\"bigint\"?t[e]=BigInt(0):bR.types.isDate(r)&&(t[e]=new Date(0))}return t}function y_e(t){let e=new qd;for(let r in t)if(Object.hasOwn(t,r)){let o=t[r];typeof o==\"number\"?e[r]=BigInt(o):bR.types.isDate(o)&&(e[r]=new Date(o))}return e.atimeNs=e.atimeMs*BigInt(1e6),e.mtimeNs=e.mtimeMs*BigInt(1e6),e.ctimeNs=e.ctimeMs*BigInt(1e6),e.birthtimeNs=e.birthtimeMs*BigInt(1e6),e}function xR(t,e){if(t.atimeMs!==e.atimeMs||t.birthtimeMs!==e.birthtimeMs||t.blksize!==e.blksize||t.blocks!==e.blocks||t.ctimeMs!==e.ctimeMs||t.dev!==e.dev||t.gid!==e.gid||t.ino!==e.ino||t.isBlockDevice()!==e.isBlockDevice()||t.isCharacterDevice()!==e.isCharacterDevice()||t.isDirectory()!==e.isDirectory()||t.isFIFO()!==e.isFIFO()||t.isFile()!==e.isFile()||t.isSocket()!==e.isSocket()||t.isSymbolicLink()!==e.isSymbolicLink()||t.mode!==e.mode||t.mtimeMs!==e.mtimeMs||t.nlink!==e.nlink||t.rdev!==e.rdev||t.size!==e.size||t.uid!==e.uid)return!1;let r=t,o=e;return!(r.atimeNs!==o.atimeNs||r.mtimeNs!==o.mtimeNs||r.ctimeNs!==o.ctimeNs||r.birthtimeNs!==o.birthtimeNs)}var bR,SR,PR,Hd,qd,kR=Et(()=>{bR=Ze(ve(\"util\")),SR=33188,PR=class{constructor(){this.name=\"\";this.path=\"\";this.mode=0}isBlockDevice(){return!1}isCharacterDevice(){return!1}isDirectory(){return(this.mode&61440)===16384}isFIFO(){return!1}isFile(){return(this.mode&61440)===32768}isSocket(){return!1}isSymbolicLink(){return(this.mode&61440)===40960}},Hd=class{constructor(){this.uid=0;this.gid=0;this.size=0;this.blksize=0;this.atimeMs=0;this.mtimeMs=0;this.ctimeMs=0;this.birthtimeMs=0;this.atime=new Date(0);this.mtime=new Date(0);this.ctime=new Date(0);this.birthtime=new Date(0);this.dev=0;this.ino=0;this.mode=SR;this.nlink=1;this.rdev=0;this.blocks=1}isBlockDevice(){return!1}isCharacterDevice(){return!1}isDirectory(){return(this.mode&61440)===16384}isFIFO(){return!1}isFile(){return(this.mode&61440)===32768}isSocket(){return!1}isSymbolicLink(){return(this.mode&61440)===40960}},qd=class{constructor(){this.uid=BigInt(0);this.gid=BigInt(0);this.size=BigInt(0);this.blksize=BigInt(0);this.atimeMs=BigInt(0);this.mtimeMs=BigInt(0);this.ctimeMs=BigInt(0);this.birthtimeMs=BigInt(0);this.atimeNs=BigInt(0);this.mtimeNs=BigInt(0);this.ctimeNs=BigInt(0);this.birthtimeNs=BigInt(0);this.atime=new Date(0);this.mtime=new Date(0);this.ctime=new Date(0);this.birthtime=new Date(0);this.dev=BigInt(0);this.ino=BigInt(0);this.mode=BigInt(SR);this.nlink=BigInt(1);this.rdev=BigInt(0);this.blocks=BigInt(1)}isBlockDevice(){return!1}isCharacterDevice(){return!1}isDirectory(){return(this.mode&BigInt(61440))===BigInt(16384)}isFIFO(){return!1}isFile(){return(this.mode&BigInt(61440))===BigInt(32768)}isSocket(){return!1}isSymbolicLink(){return(this.mode&BigInt(61440))===BigInt(40960)}}});function B_e(t){let e,r;if(e=t.match(w_e))t=e[1];else if(r=t.match(I_e))t=`\\\\\\\\${r[1]?\".\\\\\":\"\"}${r[2]}`;else return t;return t.replace(/\\//g,\"\\\\\")}function v_e(t){t=t.replace(/\\\\/g,\"/\");let e,r;return(e=t.match(E_e))?t=`/${e[1]}`:(r=t.match(C_e))&&(t=`/unc/${r[1]?\".dot/\":\"\"}${r[2]}`),t}function lD(t,e){return t===ue?x7(e):QR(e)}var Pw,It,dr,ue,V,S7,E_e,C_e,w_e,I_e,QR,x7,Ia=Et(()=>{Pw=Ze(ve(\"path\")),It={root:\"/\",dot:\".\",parent:\"..\"},dr={home:\"~\",nodeModules:\"node_modules\",manifest:\"package.json\",lockfile:\"yarn.lock\",virtual:\"__virtual__\",pnpJs:\".pnp.js\",pnpCjs:\".pnp.cjs\",pnpData:\".pnp.data.json\",pnpEsmLoader:\".pnp.loader.mjs\",rc:\".yarnrc.yml\",env:\".env\"},ue=Object.create(Pw.default),V=Object.create(Pw.default.posix);ue.cwd=()=>process.cwd();V.cwd=process.platform===\"win32\"?()=>QR(process.cwd()):process.cwd;process.platform===\"win32\"&&(V.resolve=(...t)=>t.length>0&&V.isAbsolute(t[0])?Pw.default.posix.resolve(...t):Pw.default.posix.resolve(V.cwd(),...t));S7=function(t,e,r){return e=t.normalize(e),r=t.normalize(r),e===r?\".\":(e.endsWith(t.sep)||(e=e+t.sep),r.startsWith(e)?r.slice(e.length):null)};ue.contains=(t,e)=>S7(ue,t,e);V.contains=(t,e)=>S7(V,t,e);E_e=/^([a-zA-Z]:.*)$/,C_e=/^\\/\\/(\\.\\/)?(.*)$/,w_e=/^\\/([a-zA-Z]:.*)$/,I_e=/^\\/unc\\/(\\.dot\\/)?(.*)$/;QR=process.platform===\"win32\"?v_e:t=>t,x7=process.platform===\"win32\"?B_e:t=>t;ue.fromPortablePath=x7;ue.toPortablePath=QR});async function cD(t,e){let r=\"0123456789abcdef\";await t.mkdirPromise(e.indexPath,{recursive:!0});let o=[];for(let a of r)for(let n of r)o.push(t.mkdirPromise(t.pathUtils.join(e.indexPath,`${a}${n}`),{recursive:!0}));return await Promise.all(o),e.indexPath}async function k7(t,e,r,o,a){let n=t.pathUtils.normalize(e),u=r.pathUtils.normalize(o),A=[],p=[],{atime:h,mtime:E}=a.stableTime?{atime:R0,mtime:R0}:await r.lstatPromise(u);await t.mkdirpPromise(t.pathUtils.dirname(e),{utimes:[h,E]}),await FR(A,p,t,n,r,u,{...a,didParentExist:!0});for(let I of A)await I();await Promise.all(p.map(I=>I()))}async function FR(t,e,r,o,a,n,u){let A=u.didParentExist?await Q7(r,o):null,p=await a.lstatPromise(n),{atime:h,mtime:E}=u.stableTime?{atime:R0,mtime:R0}:p,I;switch(!0){case p.isDirectory():I=await P_e(t,e,r,o,A,a,n,p,u);break;case p.isFile():I=await x_e(t,e,r,o,A,a,n,p,u);break;case p.isSymbolicLink():I=await k_e(t,e,r,o,A,a,n,p,u);break;default:throw new Error(`Unsupported file type (${p.mode})`)}return(u.linkStrategy?.type!==\"HardlinkFromIndex\"||!p.isFile())&&((I||A?.mtime?.getTime()!==E.getTime()||A?.atime?.getTime()!==h.getTime())&&(e.push(()=>r.lutimesPromise(o,h,E)),I=!0),(A===null||(A.mode&511)!==(p.mode&511))&&(e.push(()=>r.chmodPromise(o,p.mode&511)),I=!0)),I}async function Q7(t,e){try{return await t.lstatPromise(e)}catch{return null}}async function P_e(t,e,r,o,a,n,u,A,p){if(a!==null&&!a.isDirectory())if(p.overwrite)t.push(async()=>r.removePromise(o)),a=null;else return!1;let h=!1;a===null&&(t.push(async()=>{try{await r.mkdirPromise(o,{mode:A.mode})}catch(v){if(v.code!==\"EEXIST\")throw v}}),h=!0);let E=await n.readdirPromise(u),I=p.didParentExist&&!a?{...p,didParentExist:!1}:p;if(p.stableSort)for(let v of E.sort())await FR(t,e,r,r.pathUtils.join(o,v),n,n.pathUtils.join(u,v),I)&&(h=!0);else(await Promise.all(E.map(async x=>{await FR(t,e,r,r.pathUtils.join(o,x),n,n.pathUtils.join(u,x),I)}))).some(x=>x)&&(h=!0);return h}async function b_e(t,e,r,o,a,n,u,A,p,h){let E=await n.checksumFilePromise(u,{algorithm:\"sha1\"}),I=420,v=A.mode&511,x=`${E}${v!==I?v.toString(8):\"\"}`,C=r.pathUtils.join(h.indexPath,E.slice(0,2),`${x}.dat`),R;(ce=>(ce[ce.Lock=0]=\"Lock\",ce[ce.Rename=1]=\"Rename\"))(R||={});let L=1,U=await Q7(r,C);if(a){let ae=U&&a.dev===U.dev&&a.ino===U.ino,le=U?.mtimeMs!==D_e;if(ae&&le&&h.autoRepair&&(L=0,U=null),!ae)if(p.overwrite)t.push(async()=>r.removePromise(o)),a=null;else return!1}let z=!U&&L===1?`${C}.${Math.floor(Math.random()*4294967296).toString(16).padStart(8,\"0\")}`:null,te=!1;return t.push(async()=>{if(!U&&(L===0&&await r.lockPromise(C,async()=>{let ae=await n.readFilePromise(u);await r.writeFilePromise(C,ae)}),L===1&&z)){let ae=await n.readFilePromise(u);await r.writeFilePromise(z,ae);try{await r.linkPromise(z,C)}catch(le){if(le.code===\"EEXIST\")te=!0,await r.unlinkPromise(z);else throw le}}a||await r.linkPromise(C,o)}),e.push(async()=>{U||(await r.lutimesPromise(C,R0,R0),v!==I&&await r.chmodPromise(C,v)),z&&!te&&await r.unlinkPromise(z)}),!1}async function S_e(t,e,r,o,a,n,u,A,p){if(a!==null)if(p.overwrite)t.push(async()=>r.removePromise(o)),a=null;else return!1;return t.push(async()=>{let h=await n.readFilePromise(u);await r.writeFilePromise(o,h)}),!0}async function x_e(t,e,r,o,a,n,u,A,p){return p.linkStrategy?.type===\"HardlinkFromIndex\"?b_e(t,e,r,o,a,n,u,A,p,p.linkStrategy):S_e(t,e,r,o,a,n,u,A,p)}async function k_e(t,e,r,o,a,n,u,A,p){if(a!==null)if(p.overwrite)t.push(async()=>r.removePromise(o)),a=null;else return!1;return t.push(async()=>{await r.symlinkPromise(lD(r.pathUtils,await n.readlinkPromise(u)),o)}),!0}var R0,D_e,RR=Et(()=>{Ia();R0=new Date(456789e3*1e3),D_e=R0.getTime()});function uD(t,e,r,o){let a=()=>{let n=r.shift();if(typeof n>\"u\")return null;let u=t.pathUtils.join(e,n);return Object.assign(t.statSync(u),{name:n,path:void 0})};return new bw(e,a,o)}var bw,F7=Et(()=>{oD();bw=class{constructor(e,r,o={}){this.path=e;this.nextDirent=r;this.opts=o;this.closed=!1}throwIfClosed(){if(this.closed)throw DR()}async*[Symbol.asyncIterator](){try{let e;for(;(e=await this.read())!==null;)yield e}finally{await this.close()}}read(e){let r=this.readSync();return typeof e<\"u\"?e(null,r):Promise.resolve(r)}readSync(){return this.throwIfClosed(),this.nextDirent()}close(e){return this.closeSync(),typeof e<\"u\"?e(null):Promise.resolve()}closeSync(){this.throwIfClosed(),this.opts.onClose?.(),this.closed=!0}}});function R7(t,e){if(t!==e)throw new Error(`Invalid StatWatcher status: expected '${e}', got '${t}'`)}var T7,AD,N7=Et(()=>{T7=ve(\"events\");kR();AD=class t extends T7.EventEmitter{constructor(r,o,{bigint:a=!1}={}){super();this.status=\"ready\";this.changeListeners=new Map;this.startTimeout=null;this.fakeFs=r,this.path=o,this.bigint=a,this.lastStats=this.stat()}static create(r,o,a){let n=new t(r,o,a);return n.start(),n}start(){R7(this.status,\"ready\"),this.status=\"running\",this.startTimeout=setTimeout(()=>{this.startTimeout=null,this.fakeFs.existsSync(this.path)||this.emit(\"change\",this.lastStats,this.lastStats)},3)}stop(){R7(this.status,\"running\"),this.status=\"stopped\",this.startTimeout!==null&&(clearTimeout(this.startTimeout),this.startTimeout=null),this.emit(\"stop\")}stat(){try{return this.fakeFs.statSync(this.path,{bigint:this.bigint})}catch{let o=this.bigint?new qd:new Hd;return aD(o)}}makeInterval(r){let o=setInterval(()=>{let a=this.stat(),n=this.lastStats;xR(a,n)||(this.lastStats=a,this.emit(\"change\",a,n))},r.interval);return r.persistent?o:o.unref()}registerChangeListener(r,o){this.addListener(\"change\",r),this.changeListeners.set(r,this.makeInterval(o))}unregisterChangeListener(r){this.removeListener(\"change\",r);let o=this.changeListeners.get(r);typeof o<\"u\"&&clearInterval(o),this.changeListeners.delete(r)}unregisterAllChangeListeners(){for(let r of this.changeListeners.keys())this.unregisterChangeListener(r)}hasChangeListeners(){return this.changeListeners.size>0}ref(){for(let r of this.changeListeners.values())r.ref();return this}unref(){for(let r of this.changeListeners.values())r.unref();return this}}});function jd(t,e,r,o){let a,n,u,A;switch(typeof r){case\"function\":a=!1,n=!0,u=5007,A=r;break;default:({bigint:a=!1,persistent:n=!0,interval:u=5007}=r),A=o;break}let p=fD.get(t);typeof p>\"u\"&&fD.set(t,p=new Map);let h=p.get(e);return typeof h>\"u\"&&(h=AD.create(t,e,{bigint:a}),p.set(e,h)),h.registerChangeListener(A,{persistent:n,interval:u}),h}function T0(t,e,r){let o=fD.get(t);if(typeof o>\"u\")return;let a=o.get(e);typeof a>\"u\"||(typeof r>\"u\"?a.unregisterAllChangeListeners():a.unregisterChangeListener(r),a.hasChangeListeners()||(a.stop(),o.delete(e)))}function N0(t){let e=fD.get(t);if(!(typeof e>\"u\"))for(let r of e.keys())T0(t,r)}var fD,TR=Et(()=>{N7();fD=new WeakMap});function Q_e(t){let e=t.match(/\\r?\\n/g);if(e===null)return M7.EOL;let r=e.filter(a=>a===`\\r\n`).length,o=e.length-r;return r>o?`\\r\n`:`\n`}function L0(t,e){return e.replace(/\\r?\\n/g,Q_e(t))}var L7,M7,hf,_u,M0=Et(()=>{L7=ve(\"crypto\"),M7=ve(\"os\");RR();Ia();hf=class{constructor(e){this.pathUtils=e}async*genTraversePromise(e,{stableSort:r=!1}={}){let o=[e];for(;o.length>0;){let a=o.shift();if((await this.lstatPromise(a)).isDirectory()){let u=await this.readdirPromise(a);if(r)for(let A of u.sort())o.push(this.pathUtils.join(a,A));else throw new Error(\"Not supported\")}else yield a}}async checksumFilePromise(e,{algorithm:r=\"sha512\"}={}){let o=await this.openPromise(e,\"r\");try{let n=Buffer.allocUnsafeSlow(65536),u=(0,L7.createHash)(r),A=0;for(;(A=await this.readPromise(o,n,0,65536))!==0;)u.update(A===65536?n:n.slice(0,A));return u.digest(\"hex\")}finally{await this.closePromise(o)}}async removePromise(e,{recursive:r=!0,maxRetries:o=5}={}){let a;try{a=await this.lstatPromise(e)}catch(n){if(n.code===\"ENOENT\")return;throw n}if(a.isDirectory()){if(r){let n=await this.readdirPromise(e);await Promise.all(n.map(u=>this.removePromise(this.pathUtils.resolve(e,u))))}for(let n=0;n<=o;n++)try{await this.rmdirPromise(e);break}catch(u){if(u.code!==\"EBUSY\"&&u.code!==\"ENOTEMPTY\")throw u;n<o&&await new Promise(A=>setTimeout(A,n*100))}}else await this.unlinkPromise(e)}removeSync(e,{recursive:r=!0}={}){let o;try{o=this.lstatSync(e)}catch(a){if(a.code===\"ENOENT\")return;throw a}if(o.isDirectory()){if(r)for(let a of this.readdirSync(e))this.removeSync(this.pathUtils.resolve(e,a));this.rmdirSync(e)}else this.unlinkSync(e)}async mkdirpPromise(e,{chmod:r,utimes:o}={}){if(e=this.resolve(e),e===this.pathUtils.dirname(e))return;let a=e.split(this.pathUtils.sep),n;for(let u=2;u<=a.length;++u){let A=a.slice(0,u).join(this.pathUtils.sep);if(!this.existsSync(A)){try{await this.mkdirPromise(A)}catch(p){if(p.code===\"EEXIST\")continue;throw p}if(n??=A,r!=null&&await this.chmodPromise(A,r),o!=null)await this.utimesPromise(A,o[0],o[1]);else{let p=await this.statPromise(this.pathUtils.dirname(A));await this.utimesPromise(A,p.atime,p.mtime)}}}return n}mkdirpSync(e,{chmod:r,utimes:o}={}){if(e=this.resolve(e),e===this.pathUtils.dirname(e))return;let a=e.split(this.pathUtils.sep),n;for(let u=2;u<=a.length;++u){let A=a.slice(0,u).join(this.pathUtils.sep);if(!this.existsSync(A)){try{this.mkdirSync(A)}catch(p){if(p.code===\"EEXIST\")continue;throw p}if(n??=A,r!=null&&this.chmodSync(A,r),o!=null)this.utimesSync(A,o[0],o[1]);else{let p=this.statSync(this.pathUtils.dirname(A));this.utimesSync(A,p.atime,p.mtime)}}}return n}async copyPromise(e,r,{baseFs:o=this,overwrite:a=!0,stableSort:n=!1,stableTime:u=!1,linkStrategy:A=null}={}){return await k7(this,e,o,r,{overwrite:a,stableSort:n,stableTime:u,linkStrategy:A})}copySync(e,r,{baseFs:o=this,overwrite:a=!0}={}){let n=o.lstatSync(r),u=this.existsSync(e);if(n.isDirectory()){this.mkdirpSync(e);let p=o.readdirSync(r);for(let h of p)this.copySync(this.pathUtils.join(e,h),o.pathUtils.join(r,h),{baseFs:o,overwrite:a})}else if(n.isFile()){if(!u||a){u&&this.removeSync(e);let p=o.readFileSync(r);this.writeFileSync(e,p)}}else if(n.isSymbolicLink()){if(!u||a){u&&this.removeSync(e);let p=o.readlinkSync(r);this.symlinkSync(lD(this.pathUtils,p),e)}}else throw new Error(`Unsupported file type (file: ${r}, mode: 0o${n.mode.toString(8).padStart(6,\"0\")})`);let A=n.mode&511;this.chmodSync(e,A)}async changeFilePromise(e,r,o={}){return Buffer.isBuffer(r)?this.changeFileBufferPromise(e,r,o):this.changeFileTextPromise(e,r,o)}async changeFileBufferPromise(e,r,{mode:o}={}){let a=Buffer.alloc(0);try{a=await this.readFilePromise(e)}catch{}Buffer.compare(a,r)!==0&&await this.writeFilePromise(e,r,{mode:o})}async changeFileTextPromise(e,r,{automaticNewlines:o,mode:a}={}){let n=\"\";try{n=await this.readFilePromise(e,\"utf8\")}catch{}let u=o?L0(n,r):r;n!==u&&await this.writeFilePromise(e,u,{mode:a})}changeFileSync(e,r,o={}){return Buffer.isBuffer(r)?this.changeFileBufferSync(e,r,o):this.changeFileTextSync(e,r,o)}changeFileBufferSync(e,r,{mode:o}={}){let a=Buffer.alloc(0);try{a=this.readFileSync(e)}catch{}Buffer.compare(a,r)!==0&&this.writeFileSync(e,r,{mode:o})}changeFileTextSync(e,r,{automaticNewlines:o=!1,mode:a}={}){let n=\"\";try{n=this.readFileSync(e,\"utf8\")}catch{}let u=o?L0(n,r):r;n!==u&&this.writeFileSync(e,u,{mode:a})}async movePromise(e,r){try{await this.renamePromise(e,r)}catch(o){if(o.code===\"EXDEV\")await this.copyPromise(r,e),await this.removePromise(e);else throw o}}moveSync(e,r){try{this.renameSync(e,r)}catch(o){if(o.code===\"EXDEV\")this.copySync(r,e),this.removeSync(e);else throw o}}async lockPromise(e,r){let o=`${e}.flock`,a=1e3/60,n=Date.now(),u=null,A=async()=>{let p;try{[p]=await this.readJsonPromise(o)}catch{return Date.now()-n<500}try{return process.kill(p,0),!0}catch{return!1}};for(;u===null;)try{u=await this.openPromise(o,\"wx\")}catch(p){if(p.code===\"EEXIST\"){if(!await A())try{await this.unlinkPromise(o);continue}catch{}if(Date.now()-n<60*1e3)await new Promise(h=>setTimeout(h,a));else throw new Error(`Couldn't acquire a lock in a reasonable time (via ${o})`)}else throw p}await this.writePromise(u,JSON.stringify([process.pid]));try{return await r()}finally{try{await this.closePromise(u),await this.unlinkPromise(o)}catch{}}}async readJsonPromise(e){let r=await this.readFilePromise(e,\"utf8\");try{return JSON.parse(r)}catch(o){throw o.message+=` (in ${e})`,o}}readJsonSync(e){let r=this.readFileSync(e,\"utf8\");try{return JSON.parse(r)}catch(o){throw o.message+=` (in ${e})`,o}}async writeJsonPromise(e,r,{compact:o=!1}={}){let a=o?0:2;return await this.writeFilePromise(e,`${JSON.stringify(r,null,a)}\n`)}writeJsonSync(e,r,{compact:o=!1}={}){let a=o?0:2;return this.writeFileSync(e,`${JSON.stringify(r,null,a)}\n`)}async preserveTimePromise(e,r){let o=await this.lstatPromise(e),a=await r();typeof a<\"u\"&&(e=a),await this.lutimesPromise(e,o.atime,o.mtime)}async preserveTimeSync(e,r){let o=this.lstatSync(e),a=r();typeof a<\"u\"&&(e=a),this.lutimesSync(e,o.atime,o.mtime)}},_u=class extends hf{constructor(){super(V)}}});var Ss,gf=Et(()=>{M0();Ss=class extends hf{getExtractHint(e){return this.baseFs.getExtractHint(e)}resolve(e){return this.mapFromBase(this.baseFs.resolve(this.mapToBase(e)))}getRealPath(){return this.mapFromBase(this.baseFs.getRealPath())}async openPromise(e,r,o){return this.baseFs.openPromise(this.mapToBase(e),r,o)}openSync(e,r,o){return this.baseFs.openSync(this.mapToBase(e),r,o)}async opendirPromise(e,r){return Object.assign(await this.baseFs.opendirPromise(this.mapToBase(e),r),{path:e})}opendirSync(e,r){return Object.assign(this.baseFs.opendirSync(this.mapToBase(e),r),{path:e})}async readPromise(e,r,o,a,n){return await this.baseFs.readPromise(e,r,o,a,n)}readSync(e,r,o,a,n){return this.baseFs.readSync(e,r,o,a,n)}async writePromise(e,r,o,a,n){return typeof r==\"string\"?await this.baseFs.writePromise(e,r,o):await this.baseFs.writePromise(e,r,o,a,n)}writeSync(e,r,o,a,n){return typeof r==\"string\"?this.baseFs.writeSync(e,r,o):this.baseFs.writeSync(e,r,o,a,n)}async closePromise(e){return this.baseFs.closePromise(e)}closeSync(e){this.baseFs.closeSync(e)}createReadStream(e,r){return this.baseFs.createReadStream(e!==null?this.mapToBase(e):e,r)}createWriteStream(e,r){return this.baseFs.createWriteStream(e!==null?this.mapToBase(e):e,r)}async realpathPromise(e){return this.mapFromBase(await this.baseFs.realpathPromise(this.mapToBase(e)))}realpathSync(e){return this.mapFromBase(this.baseFs.realpathSync(this.mapToBase(e)))}async existsPromise(e){return this.baseFs.existsPromise(this.mapToBase(e))}existsSync(e){return this.baseFs.existsSync(this.mapToBase(e))}accessSync(e,r){return this.baseFs.accessSync(this.mapToBase(e),r)}async accessPromise(e,r){return this.baseFs.accessPromise(this.mapToBase(e),r)}async statPromise(e,r){return this.baseFs.statPromise(this.mapToBase(e),r)}statSync(e,r){return this.baseFs.statSync(this.mapToBase(e),r)}async fstatPromise(e,r){return this.baseFs.fstatPromise(e,r)}fstatSync(e,r){return this.baseFs.fstatSync(e,r)}lstatPromise(e,r){return this.baseFs.lstatPromise(this.mapToBase(e),r)}lstatSync(e,r){return this.baseFs.lstatSync(this.mapToBase(e),r)}async fchmodPromise(e,r){return this.baseFs.fchmodPromise(e,r)}fchmodSync(e,r){return this.baseFs.fchmodSync(e,r)}async chmodPromise(e,r){return this.baseFs.chmodPromise(this.mapToBase(e),r)}chmodSync(e,r){return this.baseFs.chmodSync(this.mapToBase(e),r)}async fchownPromise(e,r,o){return this.baseFs.fchownPromise(e,r,o)}fchownSync(e,r,o){return this.baseFs.fchownSync(e,r,o)}async chownPromise(e,r,o){return this.baseFs.chownPromise(this.mapToBase(e),r,o)}chownSync(e,r,o){return this.baseFs.chownSync(this.mapToBase(e),r,o)}async renamePromise(e,r){return this.baseFs.renamePromise(this.mapToBase(e),this.mapToBase(r))}renameSync(e,r){return this.baseFs.renameSync(this.mapToBase(e),this.mapToBase(r))}async copyFilePromise(e,r,o=0){return this.baseFs.copyFilePromise(this.mapToBase(e),this.mapToBase(r),o)}copyFileSync(e,r,o=0){return this.baseFs.copyFileSync(this.mapToBase(e),this.mapToBase(r),o)}async appendFilePromise(e,r,o){return this.baseFs.appendFilePromise(this.fsMapToBase(e),r,o)}appendFileSync(e,r,o){return this.baseFs.appendFileSync(this.fsMapToBase(e),r,o)}async writeFilePromise(e,r,o){return this.baseFs.writeFilePromise(this.fsMapToBase(e),r,o)}writeFileSync(e,r,o){return this.baseFs.writeFileSync(this.fsMapToBase(e),r,o)}async unlinkPromise(e){return this.baseFs.unlinkPromise(this.mapToBase(e))}unlinkSync(e){return this.baseFs.unlinkSync(this.mapToBase(e))}async utimesPromise(e,r,o){return this.baseFs.utimesPromise(this.mapToBase(e),r,o)}utimesSync(e,r,o){return this.baseFs.utimesSync(this.mapToBase(e),r,o)}async lutimesPromise(e,r,o){return this.baseFs.lutimesPromise(this.mapToBase(e),r,o)}lutimesSync(e,r,o){return this.baseFs.lutimesSync(this.mapToBase(e),r,o)}async mkdirPromise(e,r){return this.baseFs.mkdirPromise(this.mapToBase(e),r)}mkdirSync(e,r){return this.baseFs.mkdirSync(this.mapToBase(e),r)}async rmdirPromise(e,r){return this.baseFs.rmdirPromise(this.mapToBase(e),r)}rmdirSync(e,r){return this.baseFs.rmdirSync(this.mapToBase(e),r)}async rmPromise(e,r){return this.baseFs.rmPromise(this.mapToBase(e),r)}rmSync(e,r){return this.baseFs.rmSync(this.mapToBase(e),r)}async linkPromise(e,r){return this.baseFs.linkPromise(this.mapToBase(e),this.mapToBase(r))}linkSync(e,r){return this.baseFs.linkSync(this.mapToBase(e),this.mapToBase(r))}async symlinkPromise(e,r,o){let a=this.mapToBase(r);if(this.pathUtils.isAbsolute(e))return this.baseFs.symlinkPromise(this.mapToBase(e),a,o);let n=this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(r),e)),u=this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(a),n);return this.baseFs.symlinkPromise(u,a,o)}symlinkSync(e,r,o){let a=this.mapToBase(r);if(this.pathUtils.isAbsolute(e))return this.baseFs.symlinkSync(this.mapToBase(e),a,o);let n=this.mapToBase(this.pathUtils.join(this.pathUtils.dirname(r),e)),u=this.baseFs.pathUtils.relative(this.baseFs.pathUtils.dirname(a),n);return this.baseFs.symlinkSync(u,a,o)}async readFilePromise(e,r){return this.baseFs.readFilePromise(this.fsMapToBase(e),r)}readFileSync(e,r){return this.baseFs.readFileSync(this.fsMapToBase(e),r)}readdirPromise(e,r){return this.baseFs.readdirPromise(this.mapToBase(e),r)}readdirSync(e,r){return this.baseFs.readdirSync(this.mapToBase(e),r)}async readlinkPromise(e){return this.mapFromBase(await this.baseFs.readlinkPromise(this.mapToBase(e)))}readlinkSync(e){return this.mapFromBase(this.baseFs.readlinkSync(this.mapToBase(e)))}async truncatePromise(e,r){return this.baseFs.truncatePromise(this.mapToBase(e),r)}truncateSync(e,r){return this.baseFs.truncateSync(this.mapToBase(e),r)}async ftruncatePromise(e,r){return this.baseFs.ftruncatePromise(e,r)}ftruncateSync(e,r){return this.baseFs.ftruncateSync(e,r)}watch(e,r,o){return this.baseFs.watch(this.mapToBase(e),r,o)}watchFile(e,r,o){return this.baseFs.watchFile(this.mapToBase(e),r,o)}unwatchFile(e,r){return this.baseFs.unwatchFile(this.mapToBase(e),r)}fsMapToBase(e){return typeof e==\"number\"?e:this.mapToBase(e)}}});var Hu,O7=Et(()=>{gf();Hu=class extends Ss{constructor(e,{baseFs:r,pathUtils:o}){super(o),this.target=e,this.baseFs=r}getRealPath(){return this.target}getBaseFs(){return this.baseFs}mapFromBase(e){return e}mapToBase(e){return e}}});function U7(t){let e=t;return typeof t.path==\"string\"&&(e.path=ue.toPortablePath(t.path)),e}var _7,Tn,O0=Et(()=>{_7=Ze(ve(\"fs\"));M0();Ia();Tn=class extends _u{constructor(e=_7.default){super(),this.realFs=e}getExtractHint(){return!1}getRealPath(){return It.root}resolve(e){return V.resolve(e)}async openPromise(e,r,o){return await new Promise((a,n)=>{this.realFs.open(ue.fromPortablePath(e),r,o,this.makeCallback(a,n))})}openSync(e,r,o){return this.realFs.openSync(ue.fromPortablePath(e),r,o)}async opendirPromise(e,r){return await new Promise((o,a)=>{typeof r<\"u\"?this.realFs.opendir(ue.fromPortablePath(e),r,this.makeCallback(o,a)):this.realFs.opendir(ue.fromPortablePath(e),this.makeCallback(o,a))}).then(o=>{let a=o;return Object.defineProperty(a,\"path\",{value:e,configurable:!0,writable:!0}),a})}opendirSync(e,r){let a=typeof r<\"u\"?this.realFs.opendirSync(ue.fromPortablePath(e),r):this.realFs.opendirSync(ue.fromPortablePath(e));return Object.defineProperty(a,\"path\",{value:e,configurable:!0,writable:!0}),a}async readPromise(e,r,o=0,a=0,n=-1){return await new Promise((u,A)=>{this.realFs.read(e,r,o,a,n,(p,h)=>{p?A(p):u(h)})})}readSync(e,r,o,a,n){return this.realFs.readSync(e,r,o,a,n)}async writePromise(e,r,o,a,n){return await new Promise((u,A)=>typeof r==\"string\"?this.realFs.write(e,r,o,this.makeCallback(u,A)):this.realFs.write(e,r,o,a,n,this.makeCallback(u,A)))}writeSync(e,r,o,a,n){return typeof r==\"string\"?this.realFs.writeSync(e,r,o):this.realFs.writeSync(e,r,o,a,n)}async closePromise(e){await new Promise((r,o)=>{this.realFs.close(e,this.makeCallback(r,o))})}closeSync(e){this.realFs.closeSync(e)}createReadStream(e,r){let o=e!==null?ue.fromPortablePath(e):e;return this.realFs.createReadStream(o,r)}createWriteStream(e,r){let o=e!==null?ue.fromPortablePath(e):e;return this.realFs.createWriteStream(o,r)}async realpathPromise(e){return await new Promise((r,o)=>{this.realFs.realpath(ue.fromPortablePath(e),{},this.makeCallback(r,o))}).then(r=>ue.toPortablePath(r))}realpathSync(e){return ue.toPortablePath(this.realFs.realpathSync(ue.fromPortablePath(e),{}))}async existsPromise(e){return await new Promise(r=>{this.realFs.exists(ue.fromPortablePath(e),r)})}accessSync(e,r){return this.realFs.accessSync(ue.fromPortablePath(e),r)}async accessPromise(e,r){return await new Promise((o,a)=>{this.realFs.access(ue.fromPortablePath(e),r,this.makeCallback(o,a))})}existsSync(e){return this.realFs.existsSync(ue.fromPortablePath(e))}async statPromise(e,r){return await new Promise((o,a)=>{r?this.realFs.stat(ue.fromPortablePath(e),r,this.makeCallback(o,a)):this.realFs.stat(ue.fromPortablePath(e),this.makeCallback(o,a))})}statSync(e,r){return r?this.realFs.statSync(ue.fromPortablePath(e),r):this.realFs.statSync(ue.fromPortablePath(e))}async fstatPromise(e,r){return await new Promise((o,a)=>{r?this.realFs.fstat(e,r,this.makeCallback(o,a)):this.realFs.fstat(e,this.makeCallback(o,a))})}fstatSync(e,r){return r?this.realFs.fstatSync(e,r):this.realFs.fstatSync(e)}async lstatPromise(e,r){return await new Promise((o,a)=>{r?this.realFs.lstat(ue.fromPortablePath(e),r,this.makeCallback(o,a)):this.realFs.lstat(ue.fromPortablePath(e),this.makeCallback(o,a))})}lstatSync(e,r){return r?this.realFs.lstatSync(ue.fromPortablePath(e),r):this.realFs.lstatSync(ue.fromPortablePath(e))}async fchmodPromise(e,r){return await new Promise((o,a)=>{this.realFs.fchmod(e,r,this.makeCallback(o,a))})}fchmodSync(e,r){return this.realFs.fchmodSync(e,r)}async chmodPromise(e,r){return await new Promise((o,a)=>{this.realFs.chmod(ue.fromPortablePath(e),r,this.makeCallback(o,a))})}chmodSync(e,r){return this.realFs.chmodSync(ue.fromPortablePath(e),r)}async fchownPromise(e,r,o){return await new Promise((a,n)=>{this.realFs.fchown(e,r,o,this.makeCallback(a,n))})}fchownSync(e,r,o){return this.realFs.fchownSync(e,r,o)}async chownPromise(e,r,o){return await new Promise((a,n)=>{this.realFs.chown(ue.fromPortablePath(e),r,o,this.makeCallback(a,n))})}chownSync(e,r,o){return this.realFs.chownSync(ue.fromPortablePath(e),r,o)}async renamePromise(e,r){return await new Promise((o,a)=>{this.realFs.rename(ue.fromPortablePath(e),ue.fromPortablePath(r),this.makeCallback(o,a))})}renameSync(e,r){return this.realFs.renameSync(ue.fromPortablePath(e),ue.fromPortablePath(r))}async copyFilePromise(e,r,o=0){return await new Promise((a,n)=>{this.realFs.copyFile(ue.fromPortablePath(e),ue.fromPortablePath(r),o,this.makeCallback(a,n))})}copyFileSync(e,r,o=0){return this.realFs.copyFileSync(ue.fromPortablePath(e),ue.fromPortablePath(r),o)}async appendFilePromise(e,r,o){return await new Promise((a,n)=>{let u=typeof e==\"string\"?ue.fromPortablePath(e):e;o?this.realFs.appendFile(u,r,o,this.makeCallback(a,n)):this.realFs.appendFile(u,r,this.makeCallback(a,n))})}appendFileSync(e,r,o){let a=typeof e==\"string\"?ue.fromPortablePath(e):e;o?this.realFs.appendFileSync(a,r,o):this.realFs.appendFileSync(a,r)}async writeFilePromise(e,r,o){return await new Promise((a,n)=>{let u=typeof e==\"string\"?ue.fromPortablePath(e):e;o?this.realFs.writeFile(u,r,o,this.makeCallback(a,n)):this.realFs.writeFile(u,r,this.makeCallback(a,n))})}writeFileSync(e,r,o){let a=typeof e==\"string\"?ue.fromPortablePath(e):e;o?this.realFs.writeFileSync(a,r,o):this.realFs.writeFileSync(a,r)}async unlinkPromise(e){return await new Promise((r,o)=>{this.realFs.unlink(ue.fromPortablePath(e),this.makeCallback(r,o))})}unlinkSync(e){return this.realFs.unlinkSync(ue.fromPortablePath(e))}async utimesPromise(e,r,o){return await new Promise((a,n)=>{this.realFs.utimes(ue.fromPortablePath(e),r,o,this.makeCallback(a,n))})}utimesSync(e,r,o){this.realFs.utimesSync(ue.fromPortablePath(e),r,o)}async lutimesPromise(e,r,o){return await new Promise((a,n)=>{this.realFs.lutimes(ue.fromPortablePath(e),r,o,this.makeCallback(a,n))})}lutimesSync(e,r,o){this.realFs.lutimesSync(ue.fromPortablePath(e),r,o)}async mkdirPromise(e,r){return await new Promise((o,a)=>{this.realFs.mkdir(ue.fromPortablePath(e),r,this.makeCallback(o,a))})}mkdirSync(e,r){return this.realFs.mkdirSync(ue.fromPortablePath(e),r)}async rmdirPromise(e,r){return await new Promise((o,a)=>{r?this.realFs.rmdir(ue.fromPortablePath(e),r,this.makeCallback(o,a)):this.realFs.rmdir(ue.fromPortablePath(e),this.makeCallback(o,a))})}rmdirSync(e,r){return this.realFs.rmdirSync(ue.fromPortablePath(e),r)}async rmPromise(e,r){return await new Promise((o,a)=>{r?this.realFs.rm(ue.fromPortablePath(e),r,this.makeCallback(o,a)):this.realFs.rm(ue.fromPortablePath(e),this.makeCallback(o,a))})}rmSync(e,r){return this.realFs.rmSync(ue.fromPortablePath(e),r)}async linkPromise(e,r){return await new Promise((o,a)=>{this.realFs.link(ue.fromPortablePath(e),ue.fromPortablePath(r),this.makeCallback(o,a))})}linkSync(e,r){return this.realFs.linkSync(ue.fromPortablePath(e),ue.fromPortablePath(r))}async symlinkPromise(e,r,o){return await new Promise((a,n)=>{this.realFs.symlink(ue.fromPortablePath(e.replace(/\\/+$/,\"\")),ue.fromPortablePath(r),o,this.makeCallback(a,n))})}symlinkSync(e,r,o){return this.realFs.symlinkSync(ue.fromPortablePath(e.replace(/\\/+$/,\"\")),ue.fromPortablePath(r),o)}async readFilePromise(e,r){return await new Promise((o,a)=>{let n=typeof e==\"string\"?ue.fromPortablePath(e):e;this.realFs.readFile(n,r,this.makeCallback(o,a))})}readFileSync(e,r){let o=typeof e==\"string\"?ue.fromPortablePath(e):e;return this.realFs.readFileSync(o,r)}async readdirPromise(e,r){return await new Promise((o,a)=>{r?r.recursive&&process.platform===\"win32\"?r.withFileTypes?this.realFs.readdir(ue.fromPortablePath(e),r,this.makeCallback(n=>o(n.map(U7)),a)):this.realFs.readdir(ue.fromPortablePath(e),r,this.makeCallback(n=>o(n.map(ue.toPortablePath)),a)):this.realFs.readdir(ue.fromPortablePath(e),r,this.makeCallback(o,a)):this.realFs.readdir(ue.fromPortablePath(e),this.makeCallback(o,a))})}readdirSync(e,r){return r?r.recursive&&process.platform===\"win32\"?r.withFileTypes?this.realFs.readdirSync(ue.fromPortablePath(e),r).map(U7):this.realFs.readdirSync(ue.fromPortablePath(e),r).map(ue.toPortablePath):this.realFs.readdirSync(ue.fromPortablePath(e),r):this.realFs.readdirSync(ue.fromPortablePath(e))}async readlinkPromise(e){return await new Promise((r,o)=>{this.realFs.readlink(ue.fromPortablePath(e),this.makeCallback(r,o))}).then(r=>ue.toPortablePath(r))}readlinkSync(e){return ue.toPortablePath(this.realFs.readlinkSync(ue.fromPortablePath(e)))}async truncatePromise(e,r){return await new Promise((o,a)=>{this.realFs.truncate(ue.fromPortablePath(e),r,this.makeCallback(o,a))})}truncateSync(e,r){return this.realFs.truncateSync(ue.fromPortablePath(e),r)}async ftruncatePromise(e,r){return await new Promise((o,a)=>{this.realFs.ftruncate(e,r,this.makeCallback(o,a))})}ftruncateSync(e,r){return this.realFs.ftruncateSync(e,r)}watch(e,r,o){return this.realFs.watch(ue.fromPortablePath(e),r,o)}watchFile(e,r,o){return this.realFs.watchFile(ue.fromPortablePath(e),r,o)}unwatchFile(e,r){return this.realFs.unwatchFile(ue.fromPortablePath(e),r)}makeCallback(e,r){return(o,a)=>{o?r(o):e(a)}}}});var gn,H7=Et(()=>{O0();gf();Ia();gn=class extends Ss{constructor(e,{baseFs:r=new Tn}={}){super(V),this.target=this.pathUtils.normalize(e),this.baseFs=r}getRealPath(){return this.pathUtils.resolve(this.baseFs.getRealPath(),this.target)}resolve(e){return this.pathUtils.isAbsolute(e)?V.normalize(e):this.baseFs.resolve(V.join(this.target,e))}mapFromBase(e){return e}mapToBase(e){return this.pathUtils.isAbsolute(e)?e:this.pathUtils.join(this.target,e)}}});var q7,qu,j7=Et(()=>{O0();gf();Ia();q7=It.root,qu=class extends Ss{constructor(e,{baseFs:r=new Tn}={}){super(V),this.target=this.pathUtils.resolve(It.root,e),this.baseFs=r}getRealPath(){return this.pathUtils.resolve(this.baseFs.getRealPath(),this.pathUtils.relative(It.root,this.target))}getTarget(){return this.target}getBaseFs(){return this.baseFs}mapToBase(e){let r=this.pathUtils.normalize(e);if(this.pathUtils.isAbsolute(e))return this.pathUtils.resolve(this.target,this.pathUtils.relative(q7,e));if(r.match(/^\\.\\.\\/?/))throw new Error(`Resolving this path (${e}) would escape the jail`);return this.pathUtils.resolve(this.target,e)}mapFromBase(e){return this.pathUtils.resolve(q7,this.pathUtils.relative(this.target,e))}}});var Gd,G7=Et(()=>{gf();Gd=class extends Ss{constructor(r,o){super(o);this.instance=null;this.factory=r}get baseFs(){return this.instance||(this.instance=this.factory()),this.instance}set baseFs(r){this.instance=r}mapFromBase(r){return r}mapToBase(r){return r}}});var U0,Ba,Op,Y7=Et(()=>{U0=ve(\"fs\");M0();O0();TR();oD();Ia();Ba=4278190080,Op=class extends _u{constructor({baseFs:r=new Tn,filter:o=null,magicByte:a=42,maxOpenFiles:n=1/0,useCache:u=!0,maxAge:A=5e3,typeCheck:p=U0.constants.S_IFREG,getMountPoint:h,factoryPromise:E,factorySync:I}){if(Math.floor(a)!==a||!(a>1&&a<=127))throw new Error(\"The magic byte must be set to a round value between 1 and 127 included\");super();this.fdMap=new Map;this.nextFd=3;this.isMount=new Set;this.notMount=new Set;this.realPaths=new Map;this.limitOpenFilesTimeout=null;this.baseFs=r,this.mountInstances=u?new Map:null,this.factoryPromise=E,this.factorySync=I,this.filter=o,this.getMountPoint=h,this.magic=a<<24,this.maxAge=A,this.maxOpenFiles=n,this.typeCheck=p}getExtractHint(r){return this.baseFs.getExtractHint(r)}getRealPath(){return this.baseFs.getRealPath()}saveAndClose(){if(N0(this),this.mountInstances)for(let[r,{childFs:o}]of this.mountInstances.entries())o.saveAndClose?.(),this.mountInstances.delete(r)}discardAndClose(){if(N0(this),this.mountInstances)for(let[r,{childFs:o}]of this.mountInstances.entries())o.discardAndClose?.(),this.mountInstances.delete(r)}resolve(r){return this.baseFs.resolve(r)}remapFd(r,o){let a=this.nextFd++|this.magic;return this.fdMap.set(a,[r,o]),a}async openPromise(r,o,a){return await this.makeCallPromise(r,async()=>await this.baseFs.openPromise(r,o,a),async(n,{subPath:u})=>this.remapFd(n,await n.openPromise(u,o,a)))}openSync(r,o,a){return this.makeCallSync(r,()=>this.baseFs.openSync(r,o,a),(n,{subPath:u})=>this.remapFd(n,n.openSync(u,o,a)))}async opendirPromise(r,o){return await this.makeCallPromise(r,async()=>await this.baseFs.opendirPromise(r,o),async(a,{subPath:n})=>await a.opendirPromise(n,o),{requireSubpath:!1})}opendirSync(r,o){return this.makeCallSync(r,()=>this.baseFs.opendirSync(r,o),(a,{subPath:n})=>a.opendirSync(n,o),{requireSubpath:!1})}async readPromise(r,o,a,n,u){if((r&Ba)!==this.magic)return await this.baseFs.readPromise(r,o,a,n,u);let A=this.fdMap.get(r);if(typeof A>\"u\")throw Io(\"read\");let[p,h]=A;return await p.readPromise(h,o,a,n,u)}readSync(r,o,a,n,u){if((r&Ba)!==this.magic)return this.baseFs.readSync(r,o,a,n,u);let A=this.fdMap.get(r);if(typeof A>\"u\")throw Io(\"readSync\");let[p,h]=A;return p.readSync(h,o,a,n,u)}async writePromise(r,o,a,n,u){if((r&Ba)!==this.magic)return typeof o==\"string\"?await this.baseFs.writePromise(r,o,a):await this.baseFs.writePromise(r,o,a,n,u);let A=this.fdMap.get(r);if(typeof A>\"u\")throw Io(\"write\");let[p,h]=A;return typeof o==\"string\"?await p.writePromise(h,o,a):await p.writePromise(h,o,a,n,u)}writeSync(r,o,a,n,u){if((r&Ba)!==this.magic)return typeof o==\"string\"?this.baseFs.writeSync(r,o,a):this.baseFs.writeSync(r,o,a,n,u);let A=this.fdMap.get(r);if(typeof A>\"u\")throw Io(\"writeSync\");let[p,h]=A;return typeof o==\"string\"?p.writeSync(h,o,a):p.writeSync(h,o,a,n,u)}async closePromise(r){if((r&Ba)!==this.magic)return await this.baseFs.closePromise(r);let o=this.fdMap.get(r);if(typeof o>\"u\")throw Io(\"close\");this.fdMap.delete(r);let[a,n]=o;return await a.closePromise(n)}closeSync(r){if((r&Ba)!==this.magic)return this.baseFs.closeSync(r);let o=this.fdMap.get(r);if(typeof o>\"u\")throw Io(\"closeSync\");this.fdMap.delete(r);let[a,n]=o;return a.closeSync(n)}createReadStream(r,o){return r===null?this.baseFs.createReadStream(r,o):this.makeCallSync(r,()=>this.baseFs.createReadStream(r,o),(a,{archivePath:n,subPath:u})=>{let A=a.createReadStream(u,o);return A.path=ue.fromPortablePath(this.pathUtils.join(n,u)),A})}createWriteStream(r,o){return r===null?this.baseFs.createWriteStream(r,o):this.makeCallSync(r,()=>this.baseFs.createWriteStream(r,o),(a,{subPath:n})=>a.createWriteStream(n,o))}async realpathPromise(r){return await this.makeCallPromise(r,async()=>await this.baseFs.realpathPromise(r),async(o,{archivePath:a,subPath:n})=>{let u=this.realPaths.get(a);return typeof u>\"u\"&&(u=await this.baseFs.realpathPromise(a),this.realPaths.set(a,u)),this.pathUtils.join(u,this.pathUtils.relative(It.root,await o.realpathPromise(n)))})}realpathSync(r){return this.makeCallSync(r,()=>this.baseFs.realpathSync(r),(o,{archivePath:a,subPath:n})=>{let u=this.realPaths.get(a);return typeof u>\"u\"&&(u=this.baseFs.realpathSync(a),this.realPaths.set(a,u)),this.pathUtils.join(u,this.pathUtils.relative(It.root,o.realpathSync(n)))})}async existsPromise(r){return await this.makeCallPromise(r,async()=>await this.baseFs.existsPromise(r),async(o,{subPath:a})=>await o.existsPromise(a))}existsSync(r){return this.makeCallSync(r,()=>this.baseFs.existsSync(r),(o,{subPath:a})=>o.existsSync(a))}async accessPromise(r,o){return await this.makeCallPromise(r,async()=>await this.baseFs.accessPromise(r,o),async(a,{subPath:n})=>await a.accessPromise(n,o))}accessSync(r,o){return this.makeCallSync(r,()=>this.baseFs.accessSync(r,o),(a,{subPath:n})=>a.accessSync(n,o))}async statPromise(r,o){return await this.makeCallPromise(r,async()=>await this.baseFs.statPromise(r,o),async(a,{subPath:n})=>await a.statPromise(n,o))}statSync(r,o){return this.makeCallSync(r,()=>this.baseFs.statSync(r,o),(a,{subPath:n})=>a.statSync(n,o))}async fstatPromise(r,o){if((r&Ba)!==this.magic)return this.baseFs.fstatPromise(r,o);let a=this.fdMap.get(r);if(typeof a>\"u\")throw Io(\"fstat\");let[n,u]=a;return n.fstatPromise(u,o)}fstatSync(r,o){if((r&Ba)!==this.magic)return this.baseFs.fstatSync(r,o);let a=this.fdMap.get(r);if(typeof a>\"u\")throw Io(\"fstatSync\");let[n,u]=a;return n.fstatSync(u,o)}async lstatPromise(r,o){return await this.makeCallPromise(r,async()=>await this.baseFs.lstatPromise(r,o),async(a,{subPath:n})=>await a.lstatPromise(n,o))}lstatSync(r,o){return this.makeCallSync(r,()=>this.baseFs.lstatSync(r,o),(a,{subPath:n})=>a.lstatSync(n,o))}async fchmodPromise(r,o){if((r&Ba)!==this.magic)return this.baseFs.fchmodPromise(r,o);let a=this.fdMap.get(r);if(typeof a>\"u\")throw Io(\"fchmod\");let[n,u]=a;return n.fchmodPromise(u,o)}fchmodSync(r,o){if((r&Ba)!==this.magic)return this.baseFs.fchmodSync(r,o);let a=this.fdMap.get(r);if(typeof a>\"u\")throw Io(\"fchmodSync\");let[n,u]=a;return n.fchmodSync(u,o)}async chmodPromise(r,o){return await this.makeCallPromise(r,async()=>await this.baseFs.chmodPromise(r,o),async(a,{subPath:n})=>await a.chmodPromise(n,o))}chmodSync(r,o){return this.makeCallSync(r,()=>this.baseFs.chmodSync(r,o),(a,{subPath:n})=>a.chmodSync(n,o))}async fchownPromise(r,o,a){if((r&Ba)!==this.magic)return this.baseFs.fchownPromise(r,o,a);let n=this.fdMap.get(r);if(typeof n>\"u\")throw Io(\"fchown\");let[u,A]=n;return u.fchownPromise(A,o,a)}fchownSync(r,o,a){if((r&Ba)!==this.magic)return this.baseFs.fchownSync(r,o,a);let n=this.fdMap.get(r);if(typeof n>\"u\")throw Io(\"fchownSync\");let[u,A]=n;return u.fchownSync(A,o,a)}async chownPromise(r,o,a){return await this.makeCallPromise(r,async()=>await this.baseFs.chownPromise(r,o,a),async(n,{subPath:u})=>await n.chownPromise(u,o,a))}chownSync(r,o,a){return this.makeCallSync(r,()=>this.baseFs.chownSync(r,o,a),(n,{subPath:u})=>n.chownSync(u,o,a))}async renamePromise(r,o){return await this.makeCallPromise(r,async()=>await this.makeCallPromise(o,async()=>await this.baseFs.renamePromise(r,o),async()=>{throw Object.assign(new Error(\"EEXDEV: cross-device link not permitted\"),{code:\"EEXDEV\"})}),async(a,{subPath:n})=>await this.makeCallPromise(o,async()=>{throw Object.assign(new Error(\"EEXDEV: cross-device link not permitted\"),{code:\"EEXDEV\"})},async(u,{subPath:A})=>{if(a!==u)throw Object.assign(new Error(\"EEXDEV: cross-device link not permitted\"),{code:\"EEXDEV\"});return await a.renamePromise(n,A)}))}renameSync(r,o){return this.makeCallSync(r,()=>this.makeCallSync(o,()=>this.baseFs.renameSync(r,o),()=>{throw Object.assign(new Error(\"EEXDEV: cross-device link not permitted\"),{code:\"EEXDEV\"})}),(a,{subPath:n})=>this.makeCallSync(o,()=>{throw Object.assign(new Error(\"EEXDEV: cross-device link not permitted\"),{code:\"EEXDEV\"})},(u,{subPath:A})=>{if(a!==u)throw Object.assign(new Error(\"EEXDEV: cross-device link not permitted\"),{code:\"EEXDEV\"});return a.renameSync(n,A)}))}async copyFilePromise(r,o,a=0){let n=async(u,A,p,h)=>{if(a&U0.constants.COPYFILE_FICLONE_FORCE)throw Object.assign(new Error(`EXDEV: cross-device clone not permitted, copyfile '${A}' -> ${h}'`),{code:\"EXDEV\"});if(a&U0.constants.COPYFILE_EXCL&&await this.existsPromise(A))throw Object.assign(new Error(`EEXIST: file already exists, copyfile '${A}' -> '${h}'`),{code:\"EEXIST\"});let E;try{E=await u.readFilePromise(A)}catch{throw Object.assign(new Error(`EINVAL: invalid argument, copyfile '${A}' -> '${h}'`),{code:\"EINVAL\"})}await p.writeFilePromise(h,E)};return await this.makeCallPromise(r,async()=>await this.makeCallPromise(o,async()=>await this.baseFs.copyFilePromise(r,o,a),async(u,{subPath:A})=>await n(this.baseFs,r,u,A)),async(u,{subPath:A})=>await this.makeCallPromise(o,async()=>await n(u,A,this.baseFs,o),async(p,{subPath:h})=>u!==p?await n(u,A,p,h):await u.copyFilePromise(A,h,a)))}copyFileSync(r,o,a=0){let n=(u,A,p,h)=>{if(a&U0.constants.COPYFILE_FICLONE_FORCE)throw Object.assign(new Error(`EXDEV: cross-device clone not permitted, copyfile '${A}' -> ${h}'`),{code:\"EXDEV\"});if(a&U0.constants.COPYFILE_EXCL&&this.existsSync(A))throw Object.assign(new Error(`EEXIST: file already exists, copyfile '${A}' -> '${h}'`),{code:\"EEXIST\"});let E;try{E=u.readFileSync(A)}catch{throw Object.assign(new Error(`EINVAL: invalid argument, copyfile '${A}' -> '${h}'`),{code:\"EINVAL\"})}p.writeFileSync(h,E)};return this.makeCallSync(r,()=>this.makeCallSync(o,()=>this.baseFs.copyFileSync(r,o,a),(u,{subPath:A})=>n(this.baseFs,r,u,A)),(u,{subPath:A})=>this.makeCallSync(o,()=>n(u,A,this.baseFs,o),(p,{subPath:h})=>u!==p?n(u,A,p,h):u.copyFileSync(A,h,a)))}async appendFilePromise(r,o,a){return await this.makeCallPromise(r,async()=>await this.baseFs.appendFilePromise(r,o,a),async(n,{subPath:u})=>await n.appendFilePromise(u,o,a))}appendFileSync(r,o,a){return this.makeCallSync(r,()=>this.baseFs.appendFileSync(r,o,a),(n,{subPath:u})=>n.appendFileSync(u,o,a))}async writeFilePromise(r,o,a){return await this.makeCallPromise(r,async()=>await this.baseFs.writeFilePromise(r,o,a),async(n,{subPath:u})=>await n.writeFilePromise(u,o,a))}writeFileSync(r,o,a){return this.makeCallSync(r,()=>this.baseFs.writeFileSync(r,o,a),(n,{subPath:u})=>n.writeFileSync(u,o,a))}async unlinkPromise(r){return await this.makeCallPromise(r,async()=>await this.baseFs.unlinkPromise(r),async(o,{subPath:a})=>await o.unlinkPromise(a))}unlinkSync(r){return this.makeCallSync(r,()=>this.baseFs.unlinkSync(r),(o,{subPath:a})=>o.unlinkSync(a))}async utimesPromise(r,o,a){return await this.makeCallPromise(r,async()=>await this.baseFs.utimesPromise(r,o,a),async(n,{subPath:u})=>await n.utimesPromise(u,o,a))}utimesSync(r,o,a){return this.makeCallSync(r,()=>this.baseFs.utimesSync(r,o,a),(n,{subPath:u})=>n.utimesSync(u,o,a))}async lutimesPromise(r,o,a){return await this.makeCallPromise(r,async()=>await this.baseFs.lutimesPromise(r,o,a),async(n,{subPath:u})=>await n.lutimesPromise(u,o,a))}lutimesSync(r,o,a){return this.makeCallSync(r,()=>this.baseFs.lutimesSync(r,o,a),(n,{subPath:u})=>n.lutimesSync(u,o,a))}async mkdirPromise(r,o){return await this.makeCallPromise(r,async()=>await this.baseFs.mkdirPromise(r,o),async(a,{subPath:n})=>await a.mkdirPromise(n,o))}mkdirSync(r,o){return this.makeCallSync(r,()=>this.baseFs.mkdirSync(r,o),(a,{subPath:n})=>a.mkdirSync(n,o))}async rmdirPromise(r,o){return await this.makeCallPromise(r,async()=>await this.baseFs.rmdirPromise(r,o),async(a,{subPath:n})=>await a.rmdirPromise(n,o))}rmdirSync(r,o){return this.makeCallSync(r,()=>this.baseFs.rmdirSync(r,o),(a,{subPath:n})=>a.rmdirSync(n,o))}async rmPromise(r,o){return await this.makeCallPromise(r,async()=>await this.baseFs.rmPromise(r,o),async(a,{subPath:n})=>await a.rmPromise(n,o))}rmSync(r,o){return this.makeCallSync(r,()=>this.baseFs.rmSync(r,o),(a,{subPath:n})=>a.rmSync(n,o))}async linkPromise(r,o){return await this.makeCallPromise(o,async()=>await this.baseFs.linkPromise(r,o),async(a,{subPath:n})=>await a.linkPromise(r,n))}linkSync(r,o){return this.makeCallSync(o,()=>this.baseFs.linkSync(r,o),(a,{subPath:n})=>a.linkSync(r,n))}async symlinkPromise(r,o,a){return await this.makeCallPromise(o,async()=>await this.baseFs.symlinkPromise(r,o,a),async(n,{subPath:u})=>await n.symlinkPromise(r,u))}symlinkSync(r,o,a){return this.makeCallSync(o,()=>this.baseFs.symlinkSync(r,o,a),(n,{subPath:u})=>n.symlinkSync(r,u))}async readFilePromise(r,o){return this.makeCallPromise(r,async()=>await this.baseFs.readFilePromise(r,o),async(a,{subPath:n})=>await a.readFilePromise(n,o))}readFileSync(r,o){return this.makeCallSync(r,()=>this.baseFs.readFileSync(r,o),(a,{subPath:n})=>a.readFileSync(n,o))}async readdirPromise(r,o){return await this.makeCallPromise(r,async()=>await this.baseFs.readdirPromise(r,o),async(a,{subPath:n})=>await a.readdirPromise(n,o),{requireSubpath:!1})}readdirSync(r,o){return this.makeCallSync(r,()=>this.baseFs.readdirSync(r,o),(a,{subPath:n})=>a.readdirSync(n,o),{requireSubpath:!1})}async readlinkPromise(r){return await this.makeCallPromise(r,async()=>await this.baseFs.readlinkPromise(r),async(o,{subPath:a})=>await o.readlinkPromise(a))}readlinkSync(r){return this.makeCallSync(r,()=>this.baseFs.readlinkSync(r),(o,{subPath:a})=>o.readlinkSync(a))}async truncatePromise(r,o){return await this.makeCallPromise(r,async()=>await this.baseFs.truncatePromise(r,o),async(a,{subPath:n})=>await a.truncatePromise(n,o))}truncateSync(r,o){return this.makeCallSync(r,()=>this.baseFs.truncateSync(r,o),(a,{subPath:n})=>a.truncateSync(n,o))}async ftruncatePromise(r,o){if((r&Ba)!==this.magic)return this.baseFs.ftruncatePromise(r,o);let a=this.fdMap.get(r);if(typeof a>\"u\")throw Io(\"ftruncate\");let[n,u]=a;return n.ftruncatePromise(u,o)}ftruncateSync(r,o){if((r&Ba)!==this.magic)return this.baseFs.ftruncateSync(r,o);let a=this.fdMap.get(r);if(typeof a>\"u\")throw Io(\"ftruncateSync\");let[n,u]=a;return n.ftruncateSync(u,o)}watch(r,o,a){return this.makeCallSync(r,()=>this.baseFs.watch(r,o,a),(n,{subPath:u})=>n.watch(u,o,a))}watchFile(r,o,a){return this.makeCallSync(r,()=>this.baseFs.watchFile(r,o,a),()=>jd(this,r,o,a))}unwatchFile(r,o){return this.makeCallSync(r,()=>this.baseFs.unwatchFile(r,o),()=>T0(this,r,o))}async makeCallPromise(r,o,a,{requireSubpath:n=!0}={}){if(typeof r!=\"string\")return await o();let u=this.resolve(r),A=this.findMount(u);return A?n&&A.subPath===\"/\"?await o():await this.getMountPromise(A.archivePath,async p=>await a(p,A)):await o()}makeCallSync(r,o,a,{requireSubpath:n=!0}={}){if(typeof r!=\"string\")return o();let u=this.resolve(r),A=this.findMount(u);return!A||n&&A.subPath===\"/\"?o():this.getMountSync(A.archivePath,p=>a(p,A))}findMount(r){if(this.filter&&!this.filter.test(r))return null;let o=\"\";for(;;){let a=r.substring(o.length),n=this.getMountPoint(a,o);if(!n)return null;if(o=this.pathUtils.join(o,n),!this.isMount.has(o)){if(this.notMount.has(o))continue;try{if(this.typeCheck!==null&&(this.baseFs.lstatSync(o).mode&U0.constants.S_IFMT)!==this.typeCheck){this.notMount.add(o);continue}}catch{return null}this.isMount.add(o)}return{archivePath:o,subPath:this.pathUtils.join(It.root,r.substring(o.length))}}}limitOpenFiles(r){if(this.mountInstances===null)return;let o=Date.now(),a=o+this.maxAge,n=r===null?0:this.mountInstances.size-r;for(let[u,{childFs:A,expiresAt:p,refCount:h}]of this.mountInstances.entries())if(!(h!==0||A.hasOpenFileHandles?.())){if(o>=p){A.saveAndClose?.(),this.mountInstances.delete(u),n-=1;continue}else if(r===null||n<=0){a=p;break}A.saveAndClose?.(),this.mountInstances.delete(u),n-=1}this.limitOpenFilesTimeout===null&&(r===null&&this.mountInstances.size>0||r!==null)&&isFinite(a)&&(this.limitOpenFilesTimeout=setTimeout(()=>{this.limitOpenFilesTimeout=null,this.limitOpenFiles(null)},a-o).unref())}async getMountPromise(r,o){if(this.mountInstances){let a=this.mountInstances.get(r);if(!a){let n=await this.factoryPromise(this.baseFs,r);a=this.mountInstances.get(r),a||(a={childFs:n(),expiresAt:0,refCount:0})}this.mountInstances.delete(r),this.limitOpenFiles(this.maxOpenFiles-1),this.mountInstances.set(r,a),a.expiresAt=Date.now()+this.maxAge,a.refCount+=1;try{return await o(a.childFs)}finally{a.refCount-=1}}else{let a=(await this.factoryPromise(this.baseFs,r))();try{return await o(a)}finally{a.saveAndClose?.()}}}getMountSync(r,o){if(this.mountInstances){let a=this.mountInstances.get(r);return a||(a={childFs:this.factorySync(this.baseFs,r),expiresAt:0,refCount:0}),this.mountInstances.delete(r),this.limitOpenFiles(this.maxOpenFiles-1),this.mountInstances.set(r,a),a.expiresAt=Date.now()+this.maxAge,o(a.childFs)}else{let a=this.factorySync(this.baseFs,r);try{return o(a)}finally{a.saveAndClose?.()}}}}});var Zt,pD,W7=Et(()=>{M0();Ia();Zt=()=>Object.assign(new Error(\"ENOSYS: unsupported filesystem access\"),{code:\"ENOSYS\"}),pD=class t extends hf{static{this.instance=new t}constructor(){super(V)}getExtractHint(){throw Zt()}getRealPath(){throw Zt()}resolve(){throw Zt()}async openPromise(){throw Zt()}openSync(){throw Zt()}async opendirPromise(){throw Zt()}opendirSync(){throw Zt()}async readPromise(){throw Zt()}readSync(){throw Zt()}async writePromise(){throw Zt()}writeSync(){throw Zt()}async closePromise(){throw Zt()}closeSync(){throw Zt()}createWriteStream(){throw Zt()}createReadStream(){throw Zt()}async realpathPromise(){throw Zt()}realpathSync(){throw Zt()}async readdirPromise(){throw Zt()}readdirSync(){throw Zt()}async existsPromise(e){throw Zt()}existsSync(e){throw Zt()}async accessPromise(){throw Zt()}accessSync(){throw Zt()}async statPromise(){throw Zt()}statSync(){throw Zt()}async fstatPromise(e){throw Zt()}fstatSync(e){throw Zt()}async lstatPromise(e){throw Zt()}lstatSync(e){throw Zt()}async fchmodPromise(){throw Zt()}fchmodSync(){throw Zt()}async chmodPromise(){throw Zt()}chmodSync(){throw Zt()}async fchownPromise(){throw Zt()}fchownSync(){throw Zt()}async chownPromise(){throw Zt()}chownSync(){throw Zt()}async mkdirPromise(){throw Zt()}mkdirSync(){throw Zt()}async rmdirPromise(){throw Zt()}rmdirSync(){throw Zt()}async rmPromise(){throw Zt()}rmSync(){throw Zt()}async linkPromise(){throw Zt()}linkSync(){throw Zt()}async symlinkPromise(){throw Zt()}symlinkSync(){throw Zt()}async renamePromise(){throw Zt()}renameSync(){throw Zt()}async copyFilePromise(){throw Zt()}copyFileSync(){throw Zt()}async appendFilePromise(){throw Zt()}appendFileSync(){throw Zt()}async writeFilePromise(){throw Zt()}writeFileSync(){throw Zt()}async unlinkPromise(){throw Zt()}unlinkSync(){throw Zt()}async utimesPromise(){throw Zt()}utimesSync(){throw Zt()}async lutimesPromise(){throw Zt()}lutimesSync(){throw Zt()}async readFilePromise(){throw Zt()}readFileSync(){throw Zt()}async readlinkPromise(){throw Zt()}readlinkSync(){throw Zt()}async truncatePromise(){throw Zt()}truncateSync(){throw Zt()}async ftruncatePromise(e,r){throw Zt()}ftruncateSync(e,r){throw Zt()}watch(){throw Zt()}watchFile(){throw Zt()}unwatchFile(){throw Zt()}}});var Up,K7=Et(()=>{gf();Ia();Up=class extends Ss{constructor(e){super(ue),this.baseFs=e}mapFromBase(e){return ue.fromPortablePath(e)}mapToBase(e){return ue.toPortablePath(e)}}});var F_e,NR,R_e,zs,V7=Et(()=>{O0();gf();Ia();F_e=/^[0-9]+$/,NR=/^(\\/(?:[^/]+\\/)*?(?:\\$\\$virtual|__virtual__))((?:\\/((?:[^/]+-)?[a-f0-9]+)(?:\\/([^/]+))?)?((?:\\/.*)?))$/,R_e=/^([^/]+-)?[a-f0-9]+$/,zs=class t extends Ss{static makeVirtualPath(e,r,o){if(V.basename(e)!==\"__virtual__\")throw new Error('Assertion failed: Virtual folders must be named \"__virtual__\"');if(!V.basename(r).match(R_e))throw new Error(\"Assertion failed: Virtual components must be ended by an hexadecimal hash\");let n=V.relative(V.dirname(e),o).split(\"/\"),u=0;for(;u<n.length&&n[u]===\"..\";)u+=1;let A=n.slice(u);return V.join(e,r,String(u),...A)}static resolveVirtual(e){let r=e.match(NR);if(!r||!r[3]&&r[5])return e;let o=V.dirname(r[1]);if(!r[3]||!r[4])return o;if(!F_e.test(r[4]))return e;let n=Number(r[4]),u=\"../\".repeat(n),A=r[5]||\".\";return t.resolveVirtual(V.join(o,u,A))}constructor({baseFs:e=new Tn}={}){super(V),this.baseFs=e}getExtractHint(e){return this.baseFs.getExtractHint(e)}getRealPath(){return this.baseFs.getRealPath()}realpathSync(e){let r=e.match(NR);if(!r)return this.baseFs.realpathSync(e);if(!r[5])return e;let o=this.baseFs.realpathSync(this.mapToBase(e));return t.makeVirtualPath(r[1],r[3],o)}async realpathPromise(e){let r=e.match(NR);if(!r)return await this.baseFs.realpathPromise(e);if(!r[5])return e;let o=await this.baseFs.realpathPromise(this.mapToBase(e));return t.makeVirtualPath(r[1],r[3],o)}mapToBase(e){if(e===\"\")return e;if(this.pathUtils.isAbsolute(e))return t.resolveVirtual(e);let r=t.resolveVirtual(this.baseFs.resolve(It.dot)),o=t.resolveVirtual(this.baseFs.resolve(e));return V.relative(r,o)||It.dot}mapFromBase(e){return e}}});function T_e(t,e){return typeof LR.default.isUtf8<\"u\"?LR.default.isUtf8(t):Buffer.byteLength(e)===t.byteLength}var LR,z7,J7,hD,X7=Et(()=>{LR=Ze(ve(\"buffer\")),z7=ve(\"url\"),J7=ve(\"util\");gf();Ia();hD=class extends Ss{constructor(e){super(ue),this.baseFs=e}mapFromBase(e){return e}mapToBase(e){if(typeof e==\"string\")return e;if(e instanceof URL)return(0,z7.fileURLToPath)(e);if(Buffer.isBuffer(e)){let r=e.toString();if(!T_e(e,r))throw new Error(\"Non-utf8 buffers are not supported at the moment. Please upvote the following issue if you encounter this error: https://github.com/yarnpkg/berry/issues/4942\");return r}throw new Error(`Unsupported path type: ${(0,J7.inspect)(e)}`)}}});var rY,Bo,df,_p,gD,dD,Yd,Nc,Lc,Z7,$7,eY,tY,Sw,nY=Et(()=>{rY=ve(\"readline\"),Bo=Symbol(\"kBaseFs\"),df=Symbol(\"kFd\"),_p=Symbol(\"kClosePromise\"),gD=Symbol(\"kCloseResolve\"),dD=Symbol(\"kCloseReject\"),Yd=Symbol(\"kRefs\"),Nc=Symbol(\"kRef\"),Lc=Symbol(\"kUnref\"),Sw=class{constructor(e,r){this[tY]=1;this[eY]=void 0;this[$7]=void 0;this[Z7]=void 0;this[Bo]=r,this[df]=e}get fd(){return this[df]}async appendFile(e,r){try{this[Nc](this.appendFile);let o=(typeof r==\"string\"?r:r?.encoding)??void 0;return await this[Bo].appendFilePromise(this.fd,e,o?{encoding:o}:void 0)}finally{this[Lc]()}}async chown(e,r){try{return this[Nc](this.chown),await this[Bo].fchownPromise(this.fd,e,r)}finally{this[Lc]()}}async chmod(e){try{return this[Nc](this.chmod),await this[Bo].fchmodPromise(this.fd,e)}finally{this[Lc]()}}createReadStream(e){return this[Bo].createReadStream(null,{...e,fd:this.fd})}createWriteStream(e){return this[Bo].createWriteStream(null,{...e,fd:this.fd})}datasync(){throw new Error(\"Method not implemented.\")}sync(){throw new Error(\"Method not implemented.\")}async read(e,r,o,a){try{this[Nc](this.read);let n;return Buffer.isBuffer(e)?n=e:(e??={},n=e.buffer??Buffer.alloc(16384),r=e.offset||0,o=e.length??n.byteLength,a=e.position??null),r??=0,o??=0,o===0?{bytesRead:o,buffer:n}:{bytesRead:await this[Bo].readPromise(this.fd,n,r,o,a),buffer:n}}finally{this[Lc]()}}async readFile(e){try{this[Nc](this.readFile);let r=(typeof e==\"string\"?e:e?.encoding)??void 0;return await this[Bo].readFilePromise(this.fd,r)}finally{this[Lc]()}}readLines(e){return(0,rY.createInterface)({input:this.createReadStream(e),crlfDelay:1/0})}async stat(e){try{return this[Nc](this.stat),await this[Bo].fstatPromise(this.fd,e)}finally{this[Lc]()}}async truncate(e){try{return this[Nc](this.truncate),await this[Bo].ftruncatePromise(this.fd,e)}finally{this[Lc]()}}utimes(e,r){throw new Error(\"Method not implemented.\")}async writeFile(e,r){try{this[Nc](this.writeFile);let o=(typeof r==\"string\"?r:r?.encoding)??void 0;await this[Bo].writeFilePromise(this.fd,e,o)}finally{this[Lc]()}}async write(...e){try{if(this[Nc](this.write),ArrayBuffer.isView(e[0])){let[r,o,a,n]=e;return{bytesWritten:await this[Bo].writePromise(this.fd,r,o??void 0,a??void 0,n??void 0),buffer:r}}else{let[r,o,a]=e;return{bytesWritten:await this[Bo].writePromise(this.fd,r,o,a),buffer:r}}}finally{this[Lc]()}}async writev(e,r){try{this[Nc](this.writev);let o=0;if(typeof r<\"u\")for(let a of e){let n=await this.write(a,void 0,void 0,r);o+=n.bytesWritten,r+=n.bytesWritten}else for(let a of e){let n=await this.write(a);o+=n.bytesWritten}return{buffers:e,bytesWritten:o}}finally{this[Lc]()}}readv(e,r){throw new Error(\"Method not implemented.\")}close(){if(this[df]===-1)return Promise.resolve();if(this[_p])return this[_p];if(this[Yd]--,this[Yd]===0){let e=this[df];this[df]=-1,this[_p]=this[Bo].closePromise(e).finally(()=>{this[_p]=void 0})}else this[_p]=new Promise((e,r)=>{this[gD]=e,this[dD]=r}).finally(()=>{this[_p]=void 0,this[dD]=void 0,this[gD]=void 0});return this[_p]}[(Bo,df,tY=Yd,eY=_p,$7=gD,Z7=dD,Nc)](e){if(this[df]===-1){let r=new Error(\"file closed\");throw r.code=\"EBADF\",r.syscall=e.name,r}this[Yd]++}[Lc](){if(this[Yd]--,this[Yd]===0){let e=this[df];this[df]=-1,this[Bo].closePromise(e).then(this[gD],this[dD])}}}});function xw(t,e){e=new hD(e);let r=(o,a,n)=>{let u=o[a];o[a]=n,typeof u?.[Wd.promisify.custom]<\"u\"&&(n[Wd.promisify.custom]=u[Wd.promisify.custom])};{r(t,\"exists\",(o,...a)=>{let u=typeof a[a.length-1]==\"function\"?a.pop():()=>{};process.nextTick(()=>{e.existsPromise(o).then(A=>{u(A)},()=>{u(!1)})})}),r(t,\"read\",(...o)=>{let[a,n,u,A,p,h]=o;if(o.length<=3){let E={};o.length<3?h=o[1]:(E=o[1],h=o[2]),{buffer:n=Buffer.alloc(16384),offset:u=0,length:A=n.byteLength,position:p}=E}if(u==null&&(u=0),A|=0,A===0){process.nextTick(()=>{h(null,0,n)});return}p==null&&(p=-1),process.nextTick(()=>{e.readPromise(a,n,u,A,p).then(E=>{h(null,E,n)},E=>{h(E,0,n)})})});for(let o of iY){let a=o.replace(/Promise$/,\"\");if(typeof t[a]>\"u\")continue;let n=e[o];if(typeof n>\"u\")continue;r(t,a,(...A)=>{let h=typeof A[A.length-1]==\"function\"?A.pop():()=>{};process.nextTick(()=>{n.apply(e,A).then(E=>{h(null,E)},E=>{h(E)})})})}t.realpath.native=t.realpath}{r(t,\"existsSync\",o=>{try{return e.existsSync(o)}catch{return!1}}),r(t,\"readSync\",(...o)=>{let[a,n,u,A,p]=o;return o.length<=3&&({offset:u=0,length:A=n.byteLength,position:p}=o[2]||{}),u==null&&(u=0),A|=0,A===0?0:(p==null&&(p=-1),e.readSync(a,n,u,A,p))});for(let o of N_e){let a=o;if(typeof t[a]>\"u\")continue;let n=e[o];typeof n>\"u\"||r(t,a,n.bind(e))}t.realpathSync.native=t.realpathSync}{let o=t.promises;for(let a of iY){let n=a.replace(/Promise$/,\"\");if(typeof o[n]>\"u\")continue;let u=e[a];typeof u>\"u\"||a!==\"open\"&&r(o,n,(A,...p)=>A instanceof Sw?A[n].apply(A,p):u.call(e,A,...p))}r(o,\"open\",async(...a)=>{let n=await e.openPromise(...a);return new Sw(n,e)})}t.read[Wd.promisify.custom]=async(o,a,...n)=>({bytesRead:await e.readPromise(o,a,...n),buffer:a}),t.write[Wd.promisify.custom]=async(o,a,...n)=>({bytesWritten:await e.writePromise(o,a,...n),buffer:a})}function mD(t,e){let r=Object.create(t);return xw(r,e),r}var Wd,N_e,iY,sY=Et(()=>{Wd=ve(\"util\");X7();nY();N_e=new Set([\"accessSync\",\"appendFileSync\",\"createReadStream\",\"createWriteStream\",\"chmodSync\",\"fchmodSync\",\"chownSync\",\"fchownSync\",\"closeSync\",\"copyFileSync\",\"linkSync\",\"lstatSync\",\"fstatSync\",\"lutimesSync\",\"mkdirSync\",\"openSync\",\"opendirSync\",\"readlinkSync\",\"readFileSync\",\"readdirSync\",\"readlinkSync\",\"realpathSync\",\"renameSync\",\"rmdirSync\",\"rmSync\",\"statSync\",\"symlinkSync\",\"truncateSync\",\"ftruncateSync\",\"unlinkSync\",\"unwatchFile\",\"utimesSync\",\"watch\",\"watchFile\",\"writeFileSync\",\"writeSync\"]),iY=new Set([\"accessPromise\",\"appendFilePromise\",\"fchmodPromise\",\"chmodPromise\",\"fchownPromise\",\"chownPromise\",\"closePromise\",\"copyFilePromise\",\"linkPromise\",\"fstatPromise\",\"lstatPromise\",\"lutimesPromise\",\"mkdirPromise\",\"openPromise\",\"opendirPromise\",\"readdirPromise\",\"realpathPromise\",\"readFilePromise\",\"readdirPromise\",\"readlinkPromise\",\"renamePromise\",\"rmdirPromise\",\"rmPromise\",\"statPromise\",\"symlinkPromise\",\"truncatePromise\",\"ftruncatePromise\",\"unlinkPromise\",\"utimesPromise\",\"writeFilePromise\",\"writeSync\"])});function oY(t){let e=Math.ceil(Math.random()*4294967296).toString(16).padStart(8,\"0\");return`${t}${e}`}function aY(){if(MR)return MR;let t=ue.toPortablePath(lY.default.tmpdir()),e=oe.realpathSync(t);return process.once(\"exit\",()=>{oe.rmtempSync()}),MR={tmpdir:t,realTmpdir:e}}var lY,Mc,MR,oe,cY=Et(()=>{lY=Ze(ve(\"os\"));O0();Ia();Mc=new Set,MR=null;oe=Object.assign(new Tn,{detachTemp(t){Mc.delete(t)},mktempSync(t){let{tmpdir:e,realTmpdir:r}=aY();for(;;){let o=oY(\"xfs-\");try{this.mkdirSync(V.join(e,o))}catch(n){if(n.code===\"EEXIST\")continue;throw n}let a=V.join(r,o);if(Mc.add(a),typeof t>\"u\")return a;try{return t(a)}finally{if(Mc.has(a)){Mc.delete(a);try{this.removeSync(a)}catch{}}}}},async mktempPromise(t){let{tmpdir:e,realTmpdir:r}=aY();for(;;){let o=oY(\"xfs-\");try{await this.mkdirPromise(V.join(e,o))}catch(n){if(n.code===\"EEXIST\")continue;throw n}let a=V.join(r,o);if(Mc.add(a),typeof t>\"u\")return a;try{return await t(a)}finally{if(Mc.has(a)){Mc.delete(a);try{await this.removePromise(a)}catch{}}}}},async rmtempPromise(){await Promise.all(Array.from(Mc.values()).map(async t=>{try{await oe.removePromise(t,{maxRetries:0}),Mc.delete(t)}catch{}}))},rmtempSync(){for(let t of Mc)try{oe.removeSync(t),Mc.delete(t)}catch{}}})});var kw={};Vt(kw,{AliasFS:()=>Hu,BasePortableFakeFS:()=>_u,CustomDir:()=>bw,CwdFS:()=>gn,FakeFS:()=>hf,Filename:()=>dr,JailFS:()=>qu,LazyFS:()=>Gd,MountFS:()=>Op,NoFS:()=>pD,NodeFS:()=>Tn,PortablePath:()=>It,PosixFS:()=>Up,ProxiedFS:()=>Ss,VirtualFS:()=>zs,constants:()=>Bi,errors:()=>nr,extendFs:()=>mD,normalizeLineEndings:()=>L0,npath:()=>ue,opendir:()=>uD,patchFs:()=>xw,ppath:()=>V,setupCopyIndex:()=>cD,statUtils:()=>wa,unwatchAllFiles:()=>N0,unwatchFile:()=>T0,watchFile:()=>jd,xfs:()=>oe});var Pt=Et(()=>{P7();oD();kR();RR();F7();TR();M0();Ia();Ia();O7();M0();H7();j7();G7();Y7();W7();O0();K7();gf();V7();sY();cY()});var hY=_((fSt,pY)=>{pY.exports=fY;fY.sync=M_e;var uY=ve(\"fs\");function L_e(t,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(\";\"),r.indexOf(\"\")!==-1))return!0;for(var o=0;o<r.length;o++){var a=r[o].toLowerCase();if(a&&t.substr(-a.length).toLowerCase()===a)return!0}return!1}function AY(t,e,r){return!t.isSymbolicLink()&&!t.isFile()?!1:L_e(e,r)}function fY(t,e,r){uY.stat(t,function(o,a){r(o,o?!1:AY(a,t,e))})}function M_e(t,e){return AY(uY.statSync(t),t,e)}});var EY=_((pSt,yY)=>{yY.exports=dY;dY.sync=O_e;var gY=ve(\"fs\");function dY(t,e,r){gY.stat(t,function(o,a){r(o,o?!1:mY(a,e))})}function O_e(t,e){return mY(gY.statSync(t),e)}function mY(t,e){return t.isFile()&&U_e(t,e)}function U_e(t,e){var r=t.mode,o=t.uid,a=t.gid,n=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),u=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),A=parseInt(\"100\",8),p=parseInt(\"010\",8),h=parseInt(\"001\",8),E=A|p,I=r&h||r&p&&a===u||r&A&&o===n||r&E&&n===0;return I}});var wY=_((gSt,CY)=>{var hSt=ve(\"fs\"),yD;process.platform===\"win32\"||global.TESTING_WINDOWS?yD=hY():yD=EY();CY.exports=OR;OR.sync=__e;function OR(t,e,r){if(typeof e==\"function\"&&(r=e,e={}),!r){if(typeof Promise!=\"function\")throw new TypeError(\"callback not provided\");return new Promise(function(o,a){OR(t,e||{},function(n,u){n?a(n):o(u)})})}yD(t,e||{},function(o,a){o&&(o.code===\"EACCES\"||e&&e.ignoreErrors)&&(o=null,a=!1),r(o,a)})}function __e(t,e){try{return yD.sync(t,e||{})}catch(r){if(e&&e.ignoreErrors||r.code===\"EACCES\")return!1;throw r}}});var SY=_((dSt,bY)=>{var Kd=process.platform===\"win32\"||process.env.OSTYPE===\"cygwin\"||process.env.OSTYPE===\"msys\",IY=ve(\"path\"),H_e=Kd?\";\":\":\",BY=wY(),vY=t=>Object.assign(new Error(`not found: ${t}`),{code:\"ENOENT\"}),DY=(t,e)=>{let r=e.colon||H_e,o=t.match(/\\//)||Kd&&t.match(/\\\\/)?[\"\"]:[...Kd?[process.cwd()]:[],...(e.path||process.env.PATH||\"\").split(r)],a=Kd?e.pathExt||process.env.PATHEXT||\".EXE;.CMD;.BAT;.COM\":\"\",n=Kd?a.split(r):[\"\"];return Kd&&t.indexOf(\".\")!==-1&&n[0]!==\"\"&&n.unshift(\"\"),{pathEnv:o,pathExt:n,pathExtExe:a}},PY=(t,e,r)=>{typeof e==\"function\"&&(r=e,e={}),e||(e={});let{pathEnv:o,pathExt:a,pathExtExe:n}=DY(t,e),u=[],A=h=>new Promise((E,I)=>{if(h===o.length)return e.all&&u.length?E(u):I(vY(t));let v=o[h],x=/^\".*\"$/.test(v)?v.slice(1,-1):v,C=IY.join(x,t),R=!x&&/^\\.[\\\\\\/]/.test(t)?t.slice(0,2)+C:C;E(p(R,h,0))}),p=(h,E,I)=>new Promise((v,x)=>{if(I===a.length)return v(A(E+1));let C=a[I];BY(h+C,{pathExt:n},(R,L)=>{if(!R&&L)if(e.all)u.push(h+C);else return v(h+C);return v(p(h,E,I+1))})});return r?A(0).then(h=>r(null,h),r):A(0)},q_e=(t,e)=>{e=e||{};let{pathEnv:r,pathExt:o,pathExtExe:a}=DY(t,e),n=[];for(let u=0;u<r.length;u++){let A=r[u],p=/^\".*\"$/.test(A)?A.slice(1,-1):A,h=IY.join(p,t),E=!p&&/^\\.[\\\\\\/]/.test(t)?t.slice(0,2)+h:h;for(let I=0;I<o.length;I++){let v=E+o[I];try{if(BY.sync(v,{pathExt:a}))if(e.all)n.push(v);else return v}catch{}}}if(e.all&&n.length)return n;if(e.nothrow)return null;throw vY(t)};bY.exports=PY;PY.sync=q_e});var kY=_((mSt,UR)=>{\"use strict\";var xY=(t={})=>{let e=t.env||process.env;return(t.platform||process.platform)!==\"win32\"?\"PATH\":Object.keys(e).reverse().find(o=>o.toUpperCase()===\"PATH\")||\"Path\"};UR.exports=xY;UR.exports.default=xY});var TY=_((ySt,RY)=>{\"use strict\";var QY=ve(\"path\"),j_e=SY(),G_e=kY();function FY(t,e){let r=t.options.env||process.env,o=process.cwd(),a=t.options.cwd!=null,n=a&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(t.options.cwd)}catch{}let u;try{u=j_e.sync(t.command,{path:r[G_e({env:r})],pathExt:e?QY.delimiter:void 0})}catch{}finally{n&&process.chdir(o)}return u&&(u=QY.resolve(a?t.options.cwd:\"\",u)),u}function Y_e(t){return FY(t)||FY(t,!0)}RY.exports=Y_e});var NY=_((ESt,HR)=>{\"use strict\";var _R=/([()\\][%!^\"`<>&|;, *?])/g;function W_e(t){return t=t.replace(_R,\"^$1\"),t}function K_e(t,e){return t=`${t}`,t=t.replace(/(\\\\*)\"/g,'$1$1\\\\\"'),t=t.replace(/(\\\\*)$/,\"$1$1\"),t=`\"${t}\"`,t=t.replace(_R,\"^$1\"),e&&(t=t.replace(_R,\"^$1\")),t}HR.exports.command=W_e;HR.exports.argument=K_e});var MY=_((CSt,LY)=>{\"use strict\";LY.exports=/^#!(.*)/});var UY=_((wSt,OY)=>{\"use strict\";var V_e=MY();OY.exports=(t=\"\")=>{let e=t.match(V_e);if(!e)return null;let[r,o]=e[0].replace(/#! ?/,\"\").split(\" \"),a=r.split(\"/\").pop();return a===\"env\"?o:o?`${a} ${o}`:a}});var HY=_((ISt,_Y)=>{\"use strict\";var qR=ve(\"fs\"),z_e=UY();function J_e(t){let r=Buffer.alloc(150),o;try{o=qR.openSync(t,\"r\"),qR.readSync(o,r,0,150,0),qR.closeSync(o)}catch{}return z_e(r.toString())}_Y.exports=J_e});var YY=_((BSt,GY)=>{\"use strict\";var X_e=ve(\"path\"),qY=TY(),jY=NY(),Z_e=HY(),$_e=process.platform===\"win32\",e8e=/\\.(?:com|exe)$/i,t8e=/node_modules[\\\\/].bin[\\\\/][^\\\\/]+\\.cmd$/i;function r8e(t){t.file=qY(t);let e=t.file&&Z_e(t.file);return e?(t.args.unshift(t.file),t.command=e,qY(t)):t.file}function n8e(t){if(!$_e)return t;let e=r8e(t),r=!e8e.test(e);if(t.options.forceShell||r){let o=t8e.test(e);t.command=X_e.normalize(t.command),t.command=jY.command(t.command),t.args=t.args.map(n=>jY.argument(n,o));let a=[t.command].concat(t.args).join(\" \");t.args=[\"/d\",\"/s\",\"/c\",`\"${a}\"`],t.command=process.env.comspec||\"cmd.exe\",t.options.windowsVerbatimArguments=!0}return t}function i8e(t,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let o={command:t,args:e,options:r,file:void 0,original:{command:t,args:e}};return r.shell?o:n8e(o)}GY.exports=i8e});var VY=_((vSt,KY)=>{\"use strict\";var jR=process.platform===\"win32\";function GR(t,e){return Object.assign(new Error(`${e} ${t.command} ENOENT`),{code:\"ENOENT\",errno:\"ENOENT\",syscall:`${e} ${t.command}`,path:t.command,spawnargs:t.args})}function s8e(t,e){if(!jR)return;let r=t.emit;t.emit=function(o,a){if(o===\"exit\"){let n=WY(a,e,\"spawn\");if(n)return r.call(t,\"error\",n)}return r.apply(t,arguments)}}function WY(t,e){return jR&&t===1&&!e.file?GR(e.original,\"spawn\"):null}function o8e(t,e){return jR&&t===1&&!e.file?GR(e.original,\"spawnSync\"):null}KY.exports={hookChildProcess:s8e,verifyENOENT:WY,verifyENOENTSync:o8e,notFoundError:GR}});var KR=_((DSt,Vd)=>{\"use strict\";var zY=ve(\"child_process\"),YR=YY(),WR=VY();function JY(t,e,r){let o=YR(t,e,r),a=zY.spawn(o.command,o.args,o.options);return WR.hookChildProcess(a,o),a}function a8e(t,e,r){let o=YR(t,e,r),a=zY.spawnSync(o.command,o.args,o.options);return a.error=a.error||WR.verifyENOENTSync(a.status,o),a}Vd.exports=JY;Vd.exports.spawn=JY;Vd.exports.sync=a8e;Vd.exports._parse=YR;Vd.exports._enoent=WR});var ZY=_((PSt,XY)=>{\"use strict\";function l8e(t,e){function r(){this.constructor=t}r.prototype=e.prototype,t.prototype=new r}function _0(t,e,r,o){this.message=t,this.expected=e,this.found=r,this.location=o,this.name=\"SyntaxError\",typeof Error.captureStackTrace==\"function\"&&Error.captureStackTrace(this,_0)}l8e(_0,Error);_0.buildMessage=function(t,e){var r={literal:function(h){return'\"'+a(h.text)+'\"'},class:function(h){var E=\"\",I;for(I=0;I<h.parts.length;I++)E+=h.parts[I]instanceof Array?n(h.parts[I][0])+\"-\"+n(h.parts[I][1]):n(h.parts[I]);return\"[\"+(h.inverted?\"^\":\"\")+E+\"]\"},any:function(h){return\"any character\"},end:function(h){return\"end of input\"},other:function(h){return h.description}};function o(h){return h.charCodeAt(0).toString(16).toUpperCase()}function a(h){return h.replace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"').replace(/\\0/g,\"\\\\0\").replace(/\\t/g,\"\\\\t\").replace(/\\n/g,\"\\\\n\").replace(/\\r/g,\"\\\\r\").replace(/[\\x00-\\x0F]/g,function(E){return\"\\\\x0\"+o(E)}).replace(/[\\x10-\\x1F\\x7F-\\x9F]/g,function(E){return\"\\\\x\"+o(E)})}function n(h){return h.replace(/\\\\/g,\"\\\\\\\\\").replace(/\\]/g,\"\\\\]\").replace(/\\^/g,\"\\\\^\").replace(/-/g,\"\\\\-\").replace(/\\0/g,\"\\\\0\").replace(/\\t/g,\"\\\\t\").replace(/\\n/g,\"\\\\n\").replace(/\\r/g,\"\\\\r\").replace(/[\\x00-\\x0F]/g,function(E){return\"\\\\x0\"+o(E)}).replace(/[\\x10-\\x1F\\x7F-\\x9F]/g,function(E){return\"\\\\x\"+o(E)})}function u(h){return r[h.type](h)}function A(h){var E=new Array(h.length),I,v;for(I=0;I<h.length;I++)E[I]=u(h[I]);if(E.sort(),E.length>0){for(I=1,v=1;I<E.length;I++)E[I-1]!==E[I]&&(E[v]=E[I],v++);E.length=v}switch(E.length){case 1:return E[0];case 2:return E[0]+\" or \"+E[1];default:return E.slice(0,-1).join(\", \")+\", or \"+E[E.length-1]}}function p(h){return h?'\"'+a(h)+'\"':\"end of input\"}return\"Expected \"+A(t)+\" but \"+p(e)+\" found.\"};function c8e(t,e){e=e!==void 0?e:{};var r={},o={Start:u0},a=u0,n=function(N){return N||[]},u=function(N,K,re){return[{command:N,type:K}].concat(re||[])},A=function(N,K){return[{command:N,type:K||\";\"}]},p=function(N){return N},h=\";\",E=Br(\";\",!1),I=\"&\",v=Br(\"&\",!1),x=function(N,K){return K?{chain:N,then:K}:{chain:N}},C=function(N,K){return{type:N,line:K}},R=\"&&\",L=Br(\"&&\",!1),U=\"||\",z=Br(\"||\",!1),te=function(N,K){return K?{...N,then:K}:N},ae=function(N,K){return{type:N,chain:K}},le=\"|&\",ce=Br(\"|&\",!1),Ce=\"|\",de=Br(\"|\",!1),Be=\"=\",Ee=Br(\"=\",!1),g=function(N,K){return{name:N,args:[K]}},me=function(N){return{name:N,args:[]}},we=\"(\",Ae=Br(\"(\",!1),ne=\")\",Z=Br(\")\",!1),xe=function(N,K){return{type:\"subshell\",subshell:N,args:K}},Ne=\"{\",ht=Br(\"{\",!1),H=\"}\",rt=Br(\"}\",!1),Te=function(N,K){return{type:\"group\",group:N,args:K}},Fe=function(N,K){return{type:\"command\",args:K,envs:N}},ke=function(N){return{type:\"envs\",envs:N}},Ye=function(N){return N},be=function(N){return N},et=/^[0-9]/,Ue=Is([[\"0\",\"9\"]],!1,!1),S=function(N,K,re){return{type:\"redirection\",subtype:K,fd:N!==null?parseInt(N):null,args:[re]}},w=\">>\",b=Br(\">>\",!1),y=\">&\",F=Br(\">&\",!1),J=\">\",X=Br(\">\",!1),$=\"<<<\",ie=Br(\"<<<\",!1),Se=\"<&\",Re=Br(\"<&\",!1),at=\"<\",dt=Br(\"<\",!1),jt=function(N){return{type:\"argument\",segments:[].concat(...N)}},tr=function(N){return N},bt=\"$'\",ln=Br(\"$'\",!1),kr=\"'\",mr=Br(\"'\",!1),Sr=function(N){return[{type:\"text\",text:N}]},Kr='\"\"',Kn=Br('\"\"',!1),Ms=function(){return{type:\"text\",text:\"\"}},Ri='\"',gs=Br('\"',!1),io=function(N){return N},Pi=function(N){return{type:\"arithmetic\",arithmetic:N,quoted:!0}},Os=function(N){return{type:\"shell\",shell:N,quoted:!0}},so=function(N){return{type:\"variable\",...N,quoted:!0}},uc=function(N){return{type:\"text\",text:N}},Au=function(N){return{type:\"arithmetic\",arithmetic:N,quoted:!1}},sp=function(N){return{type:\"shell\",shell:N,quoted:!1}},op=function(N){return{type:\"variable\",...N,quoted:!1}},Us=function(N){return{type:\"glob\",pattern:N}},Dn=/^[^']/,oo=Is([\"'\"],!0,!1),_s=function(N){return N.join(\"\")},ml=/^[^$\"]/,yl=Is([\"$\",'\"'],!0,!1),ao=`\\\\\n`,Vn=Br(`\\\\\n`,!1),Mn=function(){return\"\"},Ti=\"\\\\\",On=Br(\"\\\\\",!1),_i=/^[\\\\$\"`]/,ir=Is([\"\\\\\",\"$\",'\"',\"`\"],!1,!1),Me=function(N){return N},ii=\"\\\\a\",Ha=Br(\"\\\\a\",!1),hr=function(){return\"a\"},Ac=\"\\\\b\",fu=Br(\"\\\\b\",!1),fc=function(){return\"\\b\"},El=/^[Ee]/,vA=Is([\"E\",\"e\"],!1,!1),pu=function(){return\"\\x1B\"},Ie=\"\\\\f\",Tt=Br(\"\\\\f\",!1),pc=function(){return\"\\f\"},Hi=\"\\\\n\",hu=Br(\"\\\\n\",!1),Yt=function(){return`\n`},Cl=\"\\\\r\",DA=Br(\"\\\\r\",!1),ap=function(){return\"\\r\"},hc=\"\\\\t\",PA=Br(\"\\\\t\",!1),Qn=function(){return\"\t\"},hi=\"\\\\v\",gc=Br(\"\\\\v\",!1),bA=function(){return\"\\v\"},aa=/^[\\\\'\"?]/,Ni=Is([\"\\\\\",\"'\",'\"',\"?\"],!1,!1),_o=function(N){return String.fromCharCode(parseInt(N,16))},Xe=\"\\\\x\",lo=Br(\"\\\\x\",!1),dc=\"\\\\u\",gu=Br(\"\\\\u\",!1),qi=\"\\\\U\",du=Br(\"\\\\U\",!1),SA=function(N){return String.fromCodePoint(parseInt(N,16))},qa=/^[0-7]/,mc=Is([[\"0\",\"7\"]],!1,!1),ds=/^[0-9a-fA-f]/,Ht=Is([[\"0\",\"9\"],[\"a\",\"f\"],[\"A\",\"f\"]],!1,!1),Fn=o0(),Ei=\"{}\",la=Br(\"{}\",!1),co=function(){return\"{}\"},Hs=\"-\",ca=Br(\"-\",!1),ua=\"+\",Ho=Br(\"+\",!1),Ci=\".\",ms=Br(\".\",!1),ys=function(N,K,re){return{type:\"number\",value:(N===\"-\"?-1:1)*parseFloat(K.join(\"\")+\".\"+re.join(\"\"))}},Es=function(N,K){return{type:\"number\",value:(N===\"-\"?-1:1)*parseInt(K.join(\"\"))}},qs=function(N){return{type:\"variable\",...N}},Un=function(N){return{type:\"variable\",name:N}},Pn=function(N){return N},Cs=\"*\",We=Br(\"*\",!1),tt=\"/\",Bt=Br(\"/\",!1),or=function(N,K,re){return{type:K===\"*\"?\"multiplication\":\"division\",right:re}},ee=function(N,K){return K.reduce((re,he)=>({left:re,...he}),N)},ye=function(N,K,re){return{type:K===\"+\"?\"addition\":\"subtraction\",right:re}},Le=\"$((\",ft=Br(\"$((\",!1),pt=\"))\",Nt=Br(\"))\",!1),rr=function(N){return N},$r=\"$(\",ji=Br(\"$(\",!1),rs=function(N){return N},bi=\"${\",qo=Br(\"${\",!1),xA=\":-\",kA=Br(\":-\",!1),lp=function(N,K){return{name:N,defaultValue:K}},e0=\":-}\",mu=Br(\":-}\",!1),t0=function(N){return{name:N,defaultValue:[]}},yu=\":+\",uo=Br(\":+\",!1),QA=function(N,K){return{name:N,alternativeValue:K}},yc=\":+}\",Aa=Br(\":+}\",!1),r0=function(N){return{name:N,alternativeValue:[]}},Ec=function(N){return{name:N}},hd=\"$\",n0=Br(\"$\",!1),$n=function(N){return e.isGlobPattern(N)},cp=function(N){return N},i0=/^[a-zA-Z0-9_]/,FA=Is([[\"a\",\"z\"],[\"A\",\"Z\"],[\"0\",\"9\"],\"_\"],!1,!1),js=function(){return s0()},Eu=/^[$@*?#a-zA-Z0-9_\\-]/,ja=Is([\"$\",\"@\",\"*\",\"?\",\"#\",[\"a\",\"z\"],[\"A\",\"Z\"],[\"0\",\"9\"],\"_\",\"-\"],!1,!1),Gi=/^[()}<>$|&; \\t\"']/,fa=Is([\"(\",\")\",\"}\",\"<\",\">\",\"$\",\"|\",\"&\",\";\",\" \",\"\t\",'\"',\"'\"],!1,!1),Cu=/^[<>&; \\t\"']/,ws=Is([\"<\",\">\",\"&\",\";\",\" \",\"\t\",'\"',\"'\"],!1,!1),Cc=/^[ \\t]/,wc=Is([\" \",\"\t\"],!1,!1),Y=0,Dt=0,wl=[{line:1,column:1}],Si=0,Ic=[],ct=0,wu;if(\"startRule\"in e){if(!(e.startRule in o))throw new Error(`Can't start parsing from rule \"`+e.startRule+'\".');a=o[e.startRule]}function s0(){return t.substring(Dt,Y)}function tw(){return Bc(Dt,Y)}function RA(N,K){throw K=K!==void 0?K:Bc(Dt,Y),c0([l0(N)],t.substring(Dt,Y),K)}function up(N,K){throw K=K!==void 0?K:Bc(Dt,Y),gd(N,K)}function Br(N,K){return{type:\"literal\",text:N,ignoreCase:K}}function Is(N,K,re){return{type:\"class\",parts:N,inverted:K,ignoreCase:re}}function o0(){return{type:\"any\"}}function a0(){return{type:\"end\"}}function l0(N){return{type:\"other\",description:N}}function Ap(N){var K=wl[N],re;if(K)return K;for(re=N-1;!wl[re];)re--;for(K=wl[re],K={line:K.line,column:K.column};re<N;)t.charCodeAt(re)===10?(K.line++,K.column=1):K.column++,re++;return wl[N]=K,K}function Bc(N,K){var re=Ap(N),he=Ap(K);return{start:{offset:N,line:re.line,column:re.column},end:{offset:K,line:he.line,column:he.column}}}function Ct(N){Y<Si||(Y>Si&&(Si=Y,Ic=[]),Ic.push(N))}function gd(N,K){return new _0(N,null,null,K)}function c0(N,K,re){return new _0(_0.buildMessage(N,K),N,K,re)}function u0(){var N,K,re;for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();return K!==r?(re=Iu(),re===r&&(re=null),re!==r?(Dt=N,K=n(re),N=K):(Y=N,N=r)):(Y=N,N=r),N}function Iu(){var N,K,re,he,ze;if(N=Y,K=Bu(),K!==r){for(re=[],he=Qt();he!==r;)re.push(he),he=Qt();re!==r?(he=A0(),he!==r?(ze=dd(),ze===r&&(ze=null),ze!==r?(Dt=N,K=u(K,he,ze),N=K):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r)}else Y=N,N=r;if(N===r)if(N=Y,K=Bu(),K!==r){for(re=[],he=Qt();he!==r;)re.push(he),he=Qt();re!==r?(he=A0(),he===r&&(he=null),he!==r?(Dt=N,K=A(K,he),N=K):(Y=N,N=r)):(Y=N,N=r)}else Y=N,N=r;return N}function dd(){var N,K,re,he,ze;for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();if(K!==r)if(re=Iu(),re!==r){for(he=[],ze=Qt();ze!==r;)he.push(ze),ze=Qt();he!==r?(Dt=N,K=p(re),N=K):(Y=N,N=r)}else Y=N,N=r;else Y=N,N=r;return N}function A0(){var N;return t.charCodeAt(Y)===59?(N=h,Y++):(N=r,ct===0&&Ct(E)),N===r&&(t.charCodeAt(Y)===38?(N=I,Y++):(N=r,ct===0&&Ct(v))),N}function Bu(){var N,K,re;return N=Y,K=pa(),K!==r?(re=rw(),re===r&&(re=null),re!==r?(Dt=N,K=x(K,re),N=K):(Y=N,N=r)):(Y=N,N=r),N}function rw(){var N,K,re,he,ze,mt,fr;for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();if(K!==r)if(re=md(),re!==r){for(he=[],ze=Qt();ze!==r;)he.push(ze),ze=Qt();if(he!==r)if(ze=Bu(),ze!==r){for(mt=[],fr=Qt();fr!==r;)mt.push(fr),fr=Qt();mt!==r?(Dt=N,K=C(re,ze),N=K):(Y=N,N=r)}else Y=N,N=r;else Y=N,N=r}else Y=N,N=r;else Y=N,N=r;return N}function md(){var N;return t.substr(Y,2)===R?(N=R,Y+=2):(N=r,ct===0&&Ct(L)),N===r&&(t.substr(Y,2)===U?(N=U,Y+=2):(N=r,ct===0&&Ct(z))),N}function pa(){var N,K,re;return N=Y,K=f0(),K!==r?(re=vc(),re===r&&(re=null),re!==r?(Dt=N,K=te(K,re),N=K):(Y=N,N=r)):(Y=N,N=r),N}function vc(){var N,K,re,he,ze,mt,fr;for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();if(K!==r)if(re=Il(),re!==r){for(he=[],ze=Qt();ze!==r;)he.push(ze),ze=Qt();if(he!==r)if(ze=pa(),ze!==r){for(mt=[],fr=Qt();fr!==r;)mt.push(fr),fr=Qt();mt!==r?(Dt=N,K=ae(re,ze),N=K):(Y=N,N=r)}else Y=N,N=r;else Y=N,N=r}else Y=N,N=r;else Y=N,N=r;return N}function Il(){var N;return t.substr(Y,2)===le?(N=le,Y+=2):(N=r,ct===0&&Ct(ce)),N===r&&(t.charCodeAt(Y)===124?(N=Ce,Y++):(N=r,ct===0&&Ct(de))),N}function vu(){var N,K,re,he,ze,mt;if(N=Y,K=d0(),K!==r)if(t.charCodeAt(Y)===61?(re=Be,Y++):(re=r,ct===0&&Ct(Ee)),re!==r)if(he=jo(),he!==r){for(ze=[],mt=Qt();mt!==r;)ze.push(mt),mt=Qt();ze!==r?(Dt=N,K=g(K,he),N=K):(Y=N,N=r)}else Y=N,N=r;else Y=N,N=r;else Y=N,N=r;if(N===r)if(N=Y,K=d0(),K!==r)if(t.charCodeAt(Y)===61?(re=Be,Y++):(re=r,ct===0&&Ct(Ee)),re!==r){for(he=[],ze=Qt();ze!==r;)he.push(ze),ze=Qt();he!==r?(Dt=N,K=me(K),N=K):(Y=N,N=r)}else Y=N,N=r;else Y=N,N=r;return N}function f0(){var N,K,re,he,ze,mt,fr,Cr,yn,oi,Li;for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();if(K!==r)if(t.charCodeAt(Y)===40?(re=we,Y++):(re=r,ct===0&&Ct(Ae)),re!==r){for(he=[],ze=Qt();ze!==r;)he.push(ze),ze=Qt();if(he!==r)if(ze=Iu(),ze!==r){for(mt=[],fr=Qt();fr!==r;)mt.push(fr),fr=Qt();if(mt!==r)if(t.charCodeAt(Y)===41?(fr=ne,Y++):(fr=r,ct===0&&Ct(Z)),fr!==r){for(Cr=[],yn=Qt();yn!==r;)Cr.push(yn),yn=Qt();if(Cr!==r){for(yn=[],oi=Ga();oi!==r;)yn.push(oi),oi=Ga();if(yn!==r){for(oi=[],Li=Qt();Li!==r;)oi.push(Li),Li=Qt();oi!==r?(Dt=N,K=xe(ze,yn),N=K):(Y=N,N=r)}else Y=N,N=r}else Y=N,N=r}else Y=N,N=r;else Y=N,N=r}else Y=N,N=r;else Y=N,N=r}else Y=N,N=r;else Y=N,N=r;if(N===r){for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();if(K!==r)if(t.charCodeAt(Y)===123?(re=Ne,Y++):(re=r,ct===0&&Ct(ht)),re!==r){for(he=[],ze=Qt();ze!==r;)he.push(ze),ze=Qt();if(he!==r)if(ze=Iu(),ze!==r){for(mt=[],fr=Qt();fr!==r;)mt.push(fr),fr=Qt();if(mt!==r)if(t.charCodeAt(Y)===125?(fr=H,Y++):(fr=r,ct===0&&Ct(rt)),fr!==r){for(Cr=[],yn=Qt();yn!==r;)Cr.push(yn),yn=Qt();if(Cr!==r){for(yn=[],oi=Ga();oi!==r;)yn.push(oi),oi=Ga();if(yn!==r){for(oi=[],Li=Qt();Li!==r;)oi.push(Li),Li=Qt();oi!==r?(Dt=N,K=Te(ze,yn),N=K):(Y=N,N=r)}else Y=N,N=r}else Y=N,N=r}else Y=N,N=r;else Y=N,N=r}else Y=N,N=r;else Y=N,N=r}else Y=N,N=r;else Y=N,N=r;if(N===r){for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();if(K!==r){for(re=[],he=vu();he!==r;)re.push(he),he=vu();if(re!==r){for(he=[],ze=Qt();ze!==r;)he.push(ze),ze=Qt();if(he!==r){if(ze=[],mt=fp(),mt!==r)for(;mt!==r;)ze.push(mt),mt=fp();else ze=r;if(ze!==r){for(mt=[],fr=Qt();fr!==r;)mt.push(fr),fr=Qt();mt!==r?(Dt=N,K=Fe(re,ze),N=K):(Y=N,N=r)}else Y=N,N=r}else Y=N,N=r}else Y=N,N=r}else Y=N,N=r;if(N===r){for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();if(K!==r){if(re=[],he=vu(),he!==r)for(;he!==r;)re.push(he),he=vu();else re=r;if(re!==r){for(he=[],ze=Qt();ze!==r;)he.push(ze),ze=Qt();he!==r?(Dt=N,K=ke(re),N=K):(Y=N,N=r)}else Y=N,N=r}else Y=N,N=r}}}return N}function TA(){var N,K,re,he,ze;for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();if(K!==r){if(re=[],he=pp(),he!==r)for(;he!==r;)re.push(he),he=pp();else re=r;if(re!==r){for(he=[],ze=Qt();ze!==r;)he.push(ze),ze=Qt();he!==r?(Dt=N,K=Ye(re),N=K):(Y=N,N=r)}else Y=N,N=r}else Y=N,N=r;return N}function fp(){var N,K,re;for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();if(K!==r?(re=Ga(),re!==r?(Dt=N,K=be(re),N=K):(Y=N,N=r)):(Y=N,N=r),N===r){for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();K!==r?(re=pp(),re!==r?(Dt=N,K=be(re),N=K):(Y=N,N=r)):(Y=N,N=r)}return N}function Ga(){var N,K,re,he,ze;for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();return K!==r?(et.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(Ue)),re===r&&(re=null),re!==r?(he=p0(),he!==r?(ze=pp(),ze!==r?(Dt=N,K=S(re,he,ze),N=K):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r),N}function p0(){var N;return t.substr(Y,2)===w?(N=w,Y+=2):(N=r,ct===0&&Ct(b)),N===r&&(t.substr(Y,2)===y?(N=y,Y+=2):(N=r,ct===0&&Ct(F)),N===r&&(t.charCodeAt(Y)===62?(N=J,Y++):(N=r,ct===0&&Ct(X)),N===r&&(t.substr(Y,3)===$?(N=$,Y+=3):(N=r,ct===0&&Ct(ie)),N===r&&(t.substr(Y,2)===Se?(N=Se,Y+=2):(N=r,ct===0&&Ct(Re)),N===r&&(t.charCodeAt(Y)===60?(N=at,Y++):(N=r,ct===0&&Ct(dt))))))),N}function pp(){var N,K,re;for(N=Y,K=[],re=Qt();re!==r;)K.push(re),re=Qt();return K!==r?(re=jo(),re!==r?(Dt=N,K=be(re),N=K):(Y=N,N=r)):(Y=N,N=r),N}function jo(){var N,K,re;if(N=Y,K=[],re=Bs(),re!==r)for(;re!==r;)K.push(re),re=Bs();else K=r;return K!==r&&(Dt=N,K=jt(K)),N=K,N}function Bs(){var N,K;return N=Y,K=wi(),K!==r&&(Dt=N,K=tr(K)),N=K,N===r&&(N=Y,K=yd(),K!==r&&(Dt=N,K=tr(K)),N=K,N===r&&(N=Y,K=Ed(),K!==r&&(Dt=N,K=tr(K)),N=K,N===r&&(N=Y,K=Go(),K!==r&&(Dt=N,K=tr(K)),N=K))),N}function wi(){var N,K,re,he;return N=Y,t.substr(Y,2)===bt?(K=bt,Y+=2):(K=r,ct===0&&Ct(ln)),K!==r?(re=cn(),re!==r?(t.charCodeAt(Y)===39?(he=kr,Y++):(he=r,ct===0&&Ct(mr)),he!==r?(Dt=N,K=Sr(re),N=K):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r),N}function yd(){var N,K,re,he;return N=Y,t.charCodeAt(Y)===39?(K=kr,Y++):(K=r,ct===0&&Ct(mr)),K!==r?(re=gp(),re!==r?(t.charCodeAt(Y)===39?(he=kr,Y++):(he=r,ct===0&&Ct(mr)),he!==r?(Dt=N,K=Sr(re),N=K):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r),N}function Ed(){var N,K,re,he;if(N=Y,t.substr(Y,2)===Kr?(K=Kr,Y+=2):(K=r,ct===0&&Ct(Kn)),K!==r&&(Dt=N,K=Ms()),N=K,N===r)if(N=Y,t.charCodeAt(Y)===34?(K=Ri,Y++):(K=r,ct===0&&Ct(gs)),K!==r){for(re=[],he=NA();he!==r;)re.push(he),he=NA();re!==r?(t.charCodeAt(Y)===34?(he=Ri,Y++):(he=r,ct===0&&Ct(gs)),he!==r?(Dt=N,K=io(re),N=K):(Y=N,N=r)):(Y=N,N=r)}else Y=N,N=r;return N}function Go(){var N,K,re;if(N=Y,K=[],re=hp(),re!==r)for(;re!==r;)K.push(re),re=hp();else K=r;return K!==r&&(Dt=N,K=io(K)),N=K,N}function NA(){var N,K;return N=Y,K=Yr(),K!==r&&(Dt=N,K=Pi(K)),N=K,N===r&&(N=Y,K=dp(),K!==r&&(Dt=N,K=Os(K)),N=K,N===r&&(N=Y,K=Pc(),K!==r&&(Dt=N,K=so(K)),N=K,N===r&&(N=Y,K=h0(),K!==r&&(Dt=N,K=uc(K)),N=K))),N}function hp(){var N,K;return N=Y,K=Yr(),K!==r&&(Dt=N,K=Au(K)),N=K,N===r&&(N=Y,K=dp(),K!==r&&(Dt=N,K=sp(K)),N=K,N===r&&(N=Y,K=Pc(),K!==r&&(Dt=N,K=op(K)),N=K,N===r&&(N=Y,K=nw(),K!==r&&(Dt=N,K=Us(K)),N=K,N===r&&(N=Y,K=ga(),K!==r&&(Dt=N,K=uc(K)),N=K)))),N}function gp(){var N,K,re;for(N=Y,K=[],Dn.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(oo));re!==r;)K.push(re),Dn.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(oo));return K!==r&&(Dt=N,K=_s(K)),N=K,N}function h0(){var N,K,re;if(N=Y,K=[],re=ha(),re===r&&(ml.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(yl))),re!==r)for(;re!==r;)K.push(re),re=ha(),re===r&&(ml.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(yl)));else K=r;return K!==r&&(Dt=N,K=_s(K)),N=K,N}function ha(){var N,K,re;return N=Y,t.substr(Y,2)===ao?(K=ao,Y+=2):(K=r,ct===0&&Ct(Vn)),K!==r&&(Dt=N,K=Mn()),N=K,N===r&&(N=Y,t.charCodeAt(Y)===92?(K=Ti,Y++):(K=r,ct===0&&Ct(On)),K!==r?(_i.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(ir)),re!==r?(Dt=N,K=Me(re),N=K):(Y=N,N=r)):(Y=N,N=r)),N}function cn(){var N,K,re;for(N=Y,K=[],re=Ao(),re===r&&(Dn.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(oo)));re!==r;)K.push(re),re=Ao(),re===r&&(Dn.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(oo)));return K!==r&&(Dt=N,K=_s(K)),N=K,N}function Ao(){var N,K,re;return N=Y,t.substr(Y,2)===ii?(K=ii,Y+=2):(K=r,ct===0&&Ct(Ha)),K!==r&&(Dt=N,K=hr()),N=K,N===r&&(N=Y,t.substr(Y,2)===Ac?(K=Ac,Y+=2):(K=r,ct===0&&Ct(fu)),K!==r&&(Dt=N,K=fc()),N=K,N===r&&(N=Y,t.charCodeAt(Y)===92?(K=Ti,Y++):(K=r,ct===0&&Ct(On)),K!==r?(El.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(vA)),re!==r?(Dt=N,K=pu(),N=K):(Y=N,N=r)):(Y=N,N=r),N===r&&(N=Y,t.substr(Y,2)===Ie?(K=Ie,Y+=2):(K=r,ct===0&&Ct(Tt)),K!==r&&(Dt=N,K=pc()),N=K,N===r&&(N=Y,t.substr(Y,2)===Hi?(K=Hi,Y+=2):(K=r,ct===0&&Ct(hu)),K!==r&&(Dt=N,K=Yt()),N=K,N===r&&(N=Y,t.substr(Y,2)===Cl?(K=Cl,Y+=2):(K=r,ct===0&&Ct(DA)),K!==r&&(Dt=N,K=ap()),N=K,N===r&&(N=Y,t.substr(Y,2)===hc?(K=hc,Y+=2):(K=r,ct===0&&Ct(PA)),K!==r&&(Dt=N,K=Qn()),N=K,N===r&&(N=Y,t.substr(Y,2)===hi?(K=hi,Y+=2):(K=r,ct===0&&Ct(gc)),K!==r&&(Dt=N,K=bA()),N=K,N===r&&(N=Y,t.charCodeAt(Y)===92?(K=Ti,Y++):(K=r,ct===0&&Ct(On)),K!==r?(aa.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(Ni)),re!==r?(Dt=N,K=Me(re),N=K):(Y=N,N=r)):(Y=N,N=r),N===r&&(N=LA()))))))))),N}function LA(){var N,K,re,he,ze,mt,fr,Cr,yn,oi,Li,y0;return N=Y,t.charCodeAt(Y)===92?(K=Ti,Y++):(K=r,ct===0&&Ct(On)),K!==r?(re=Ya(),re!==r?(Dt=N,K=_o(re),N=K):(Y=N,N=r)):(Y=N,N=r),N===r&&(N=Y,t.substr(Y,2)===Xe?(K=Xe,Y+=2):(K=r,ct===0&&Ct(lo)),K!==r?(re=Y,he=Y,ze=Ya(),ze!==r?(mt=si(),mt!==r?(ze=[ze,mt],he=ze):(Y=he,he=r)):(Y=he,he=r),he===r&&(he=Ya()),he!==r?re=t.substring(re,Y):re=he,re!==r?(Dt=N,K=_o(re),N=K):(Y=N,N=r)):(Y=N,N=r),N===r&&(N=Y,t.substr(Y,2)===dc?(K=dc,Y+=2):(K=r,ct===0&&Ct(gu)),K!==r?(re=Y,he=Y,ze=si(),ze!==r?(mt=si(),mt!==r?(fr=si(),fr!==r?(Cr=si(),Cr!==r?(ze=[ze,mt,fr,Cr],he=ze):(Y=he,he=r)):(Y=he,he=r)):(Y=he,he=r)):(Y=he,he=r),he!==r?re=t.substring(re,Y):re=he,re!==r?(Dt=N,K=_o(re),N=K):(Y=N,N=r)):(Y=N,N=r),N===r&&(N=Y,t.substr(Y,2)===qi?(K=qi,Y+=2):(K=r,ct===0&&Ct(du)),K!==r?(re=Y,he=Y,ze=si(),ze!==r?(mt=si(),mt!==r?(fr=si(),fr!==r?(Cr=si(),Cr!==r?(yn=si(),yn!==r?(oi=si(),oi!==r?(Li=si(),Li!==r?(y0=si(),y0!==r?(ze=[ze,mt,fr,Cr,yn,oi,Li,y0],he=ze):(Y=he,he=r)):(Y=he,he=r)):(Y=he,he=r)):(Y=he,he=r)):(Y=he,he=r)):(Y=he,he=r)):(Y=he,he=r)):(Y=he,he=r),he!==r?re=t.substring(re,Y):re=he,re!==r?(Dt=N,K=SA(re),N=K):(Y=N,N=r)):(Y=N,N=r)))),N}function Ya(){var N;return qa.test(t.charAt(Y))?(N=t.charAt(Y),Y++):(N=r,ct===0&&Ct(mc)),N}function si(){var N;return ds.test(t.charAt(Y))?(N=t.charAt(Y),Y++):(N=r,ct===0&&Ct(Ht)),N}function ga(){var N,K,re,he,ze;if(N=Y,K=[],re=Y,t.charCodeAt(Y)===92?(he=Ti,Y++):(he=r,ct===0&&Ct(On)),he!==r?(t.length>Y?(ze=t.charAt(Y),Y++):(ze=r,ct===0&&Ct(Fn)),ze!==r?(Dt=re,he=Me(ze),re=he):(Y=re,re=r)):(Y=re,re=r),re===r&&(re=Y,t.substr(Y,2)===Ei?(he=Ei,Y+=2):(he=r,ct===0&&Ct(la)),he!==r&&(Dt=re,he=co()),re=he,re===r&&(re=Y,he=Y,ct++,ze=Cd(),ct--,ze===r?he=void 0:(Y=he,he=r),he!==r?(t.length>Y?(ze=t.charAt(Y),Y++):(ze=r,ct===0&&Ct(Fn)),ze!==r?(Dt=re,he=Me(ze),re=he):(Y=re,re=r)):(Y=re,re=r))),re!==r)for(;re!==r;)K.push(re),re=Y,t.charCodeAt(Y)===92?(he=Ti,Y++):(he=r,ct===0&&Ct(On)),he!==r?(t.length>Y?(ze=t.charAt(Y),Y++):(ze=r,ct===0&&Ct(Fn)),ze!==r?(Dt=re,he=Me(ze),re=he):(Y=re,re=r)):(Y=re,re=r),re===r&&(re=Y,t.substr(Y,2)===Ei?(he=Ei,Y+=2):(he=r,ct===0&&Ct(la)),he!==r&&(Dt=re,he=co()),re=he,re===r&&(re=Y,he=Y,ct++,ze=Cd(),ct--,ze===r?he=void 0:(Y=he,he=r),he!==r?(t.length>Y?(ze=t.charAt(Y),Y++):(ze=r,ct===0&&Ct(Fn)),ze!==r?(Dt=re,he=Me(ze),re=he):(Y=re,re=r)):(Y=re,re=r)));else K=r;return K!==r&&(Dt=N,K=_s(K)),N=K,N}function Dc(){var N,K,re,he,ze,mt;if(N=Y,t.charCodeAt(Y)===45?(K=Hs,Y++):(K=r,ct===0&&Ct(ca)),K===r&&(t.charCodeAt(Y)===43?(K=ua,Y++):(K=r,ct===0&&Ct(Ho))),K===r&&(K=null),K!==r){if(re=[],et.test(t.charAt(Y))?(he=t.charAt(Y),Y++):(he=r,ct===0&&Ct(Ue)),he!==r)for(;he!==r;)re.push(he),et.test(t.charAt(Y))?(he=t.charAt(Y),Y++):(he=r,ct===0&&Ct(Ue));else re=r;if(re!==r)if(t.charCodeAt(Y)===46?(he=Ci,Y++):(he=r,ct===0&&Ct(ms)),he!==r){if(ze=[],et.test(t.charAt(Y))?(mt=t.charAt(Y),Y++):(mt=r,ct===0&&Ct(Ue)),mt!==r)for(;mt!==r;)ze.push(mt),et.test(t.charAt(Y))?(mt=t.charAt(Y),Y++):(mt=r,ct===0&&Ct(Ue));else ze=r;ze!==r?(Dt=N,K=ys(K,re,ze),N=K):(Y=N,N=r)}else Y=N,N=r;else Y=N,N=r}else Y=N,N=r;if(N===r){if(N=Y,t.charCodeAt(Y)===45?(K=Hs,Y++):(K=r,ct===0&&Ct(ca)),K===r&&(t.charCodeAt(Y)===43?(K=ua,Y++):(K=r,ct===0&&Ct(Ho))),K===r&&(K=null),K!==r){if(re=[],et.test(t.charAt(Y))?(he=t.charAt(Y),Y++):(he=r,ct===0&&Ct(Ue)),he!==r)for(;he!==r;)re.push(he),et.test(t.charAt(Y))?(he=t.charAt(Y),Y++):(he=r,ct===0&&Ct(Ue));else re=r;re!==r?(Dt=N,K=Es(K,re),N=K):(Y=N,N=r)}else Y=N,N=r;if(N===r&&(N=Y,K=Pc(),K!==r&&(Dt=N,K=qs(K)),N=K,N===r&&(N=Y,K=Wa(),K!==r&&(Dt=N,K=Un(K)),N=K,N===r)))if(N=Y,t.charCodeAt(Y)===40?(K=we,Y++):(K=r,ct===0&&Ct(Ae)),K!==r){for(re=[],he=Qt();he!==r;)re.push(he),he=Qt();if(re!==r)if(he=ns(),he!==r){for(ze=[],mt=Qt();mt!==r;)ze.push(mt),mt=Qt();ze!==r?(t.charCodeAt(Y)===41?(mt=ne,Y++):(mt=r,ct===0&&Ct(Z)),mt!==r?(Dt=N,K=Pn(he),N=K):(Y=N,N=r)):(Y=N,N=r)}else Y=N,N=r;else Y=N,N=r}else Y=N,N=r}return N}function Bl(){var N,K,re,he,ze,mt,fr,Cr;if(N=Y,K=Dc(),K!==r){for(re=[],he=Y,ze=[],mt=Qt();mt!==r;)ze.push(mt),mt=Qt();if(ze!==r)if(t.charCodeAt(Y)===42?(mt=Cs,Y++):(mt=r,ct===0&&Ct(We)),mt===r&&(t.charCodeAt(Y)===47?(mt=tt,Y++):(mt=r,ct===0&&Ct(Bt))),mt!==r){for(fr=[],Cr=Qt();Cr!==r;)fr.push(Cr),Cr=Qt();fr!==r?(Cr=Dc(),Cr!==r?(Dt=he,ze=or(K,mt,Cr),he=ze):(Y=he,he=r)):(Y=he,he=r)}else Y=he,he=r;else Y=he,he=r;for(;he!==r;){for(re.push(he),he=Y,ze=[],mt=Qt();mt!==r;)ze.push(mt),mt=Qt();if(ze!==r)if(t.charCodeAt(Y)===42?(mt=Cs,Y++):(mt=r,ct===0&&Ct(We)),mt===r&&(t.charCodeAt(Y)===47?(mt=tt,Y++):(mt=r,ct===0&&Ct(Bt))),mt!==r){for(fr=[],Cr=Qt();Cr!==r;)fr.push(Cr),Cr=Qt();fr!==r?(Cr=Dc(),Cr!==r?(Dt=he,ze=or(K,mt,Cr),he=ze):(Y=he,he=r)):(Y=he,he=r)}else Y=he,he=r;else Y=he,he=r}re!==r?(Dt=N,K=ee(K,re),N=K):(Y=N,N=r)}else Y=N,N=r;return N}function ns(){var N,K,re,he,ze,mt,fr,Cr;if(N=Y,K=Bl(),K!==r){for(re=[],he=Y,ze=[],mt=Qt();mt!==r;)ze.push(mt),mt=Qt();if(ze!==r)if(t.charCodeAt(Y)===43?(mt=ua,Y++):(mt=r,ct===0&&Ct(Ho)),mt===r&&(t.charCodeAt(Y)===45?(mt=Hs,Y++):(mt=r,ct===0&&Ct(ca))),mt!==r){for(fr=[],Cr=Qt();Cr!==r;)fr.push(Cr),Cr=Qt();fr!==r?(Cr=Bl(),Cr!==r?(Dt=he,ze=ye(K,mt,Cr),he=ze):(Y=he,he=r)):(Y=he,he=r)}else Y=he,he=r;else Y=he,he=r;for(;he!==r;){for(re.push(he),he=Y,ze=[],mt=Qt();mt!==r;)ze.push(mt),mt=Qt();if(ze!==r)if(t.charCodeAt(Y)===43?(mt=ua,Y++):(mt=r,ct===0&&Ct(Ho)),mt===r&&(t.charCodeAt(Y)===45?(mt=Hs,Y++):(mt=r,ct===0&&Ct(ca))),mt!==r){for(fr=[],Cr=Qt();Cr!==r;)fr.push(Cr),Cr=Qt();fr!==r?(Cr=Bl(),Cr!==r?(Dt=he,ze=ye(K,mt,Cr),he=ze):(Y=he,he=r)):(Y=he,he=r)}else Y=he,he=r;else Y=he,he=r}re!==r?(Dt=N,K=ee(K,re),N=K):(Y=N,N=r)}else Y=N,N=r;return N}function Yr(){var N,K,re,he,ze,mt;if(N=Y,t.substr(Y,3)===Le?(K=Le,Y+=3):(K=r,ct===0&&Ct(ft)),K!==r){for(re=[],he=Qt();he!==r;)re.push(he),he=Qt();if(re!==r)if(he=ns(),he!==r){for(ze=[],mt=Qt();mt!==r;)ze.push(mt),mt=Qt();ze!==r?(t.substr(Y,2)===pt?(mt=pt,Y+=2):(mt=r,ct===0&&Ct(Nt)),mt!==r?(Dt=N,K=rr(he),N=K):(Y=N,N=r)):(Y=N,N=r)}else Y=N,N=r;else Y=N,N=r}else Y=N,N=r;return N}function dp(){var N,K,re,he;return N=Y,t.substr(Y,2)===$r?(K=$r,Y+=2):(K=r,ct===0&&Ct(ji)),K!==r?(re=Iu(),re!==r?(t.charCodeAt(Y)===41?(he=ne,Y++):(he=r,ct===0&&Ct(Z)),he!==r?(Dt=N,K=rs(re),N=K):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r),N}function Pc(){var N,K,re,he,ze,mt;return N=Y,t.substr(Y,2)===bi?(K=bi,Y+=2):(K=r,ct===0&&Ct(qo)),K!==r?(re=Wa(),re!==r?(t.substr(Y,2)===xA?(he=xA,Y+=2):(he=r,ct===0&&Ct(kA)),he!==r?(ze=TA(),ze!==r?(t.charCodeAt(Y)===125?(mt=H,Y++):(mt=r,ct===0&&Ct(rt)),mt!==r?(Dt=N,K=lp(re,ze),N=K):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r),N===r&&(N=Y,t.substr(Y,2)===bi?(K=bi,Y+=2):(K=r,ct===0&&Ct(qo)),K!==r?(re=Wa(),re!==r?(t.substr(Y,3)===e0?(he=e0,Y+=3):(he=r,ct===0&&Ct(mu)),he!==r?(Dt=N,K=t0(re),N=K):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r),N===r&&(N=Y,t.substr(Y,2)===bi?(K=bi,Y+=2):(K=r,ct===0&&Ct(qo)),K!==r?(re=Wa(),re!==r?(t.substr(Y,2)===yu?(he=yu,Y+=2):(he=r,ct===0&&Ct(uo)),he!==r?(ze=TA(),ze!==r?(t.charCodeAt(Y)===125?(mt=H,Y++):(mt=r,ct===0&&Ct(rt)),mt!==r?(Dt=N,K=QA(re,ze),N=K):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r),N===r&&(N=Y,t.substr(Y,2)===bi?(K=bi,Y+=2):(K=r,ct===0&&Ct(qo)),K!==r?(re=Wa(),re!==r?(t.substr(Y,3)===yc?(he=yc,Y+=3):(he=r,ct===0&&Ct(Aa)),he!==r?(Dt=N,K=r0(re),N=K):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r),N===r&&(N=Y,t.substr(Y,2)===bi?(K=bi,Y+=2):(K=r,ct===0&&Ct(qo)),K!==r?(re=Wa(),re!==r?(t.charCodeAt(Y)===125?(he=H,Y++):(he=r,ct===0&&Ct(rt)),he!==r?(Dt=N,K=Ec(re),N=K):(Y=N,N=r)):(Y=N,N=r)):(Y=N,N=r),N===r&&(N=Y,t.charCodeAt(Y)===36?(K=hd,Y++):(K=r,ct===0&&Ct(n0)),K!==r?(re=Wa(),re!==r?(Dt=N,K=Ec(re),N=K):(Y=N,N=r)):(Y=N,N=r)))))),N}function nw(){var N,K,re;return N=Y,K=g0(),K!==r?(Dt=Y,re=$n(K),re?re=void 0:re=r,re!==r?(Dt=N,K=cp(K),N=K):(Y=N,N=r)):(Y=N,N=r),N}function g0(){var N,K,re,he,ze;if(N=Y,K=[],re=Y,he=Y,ct++,ze=m0(),ct--,ze===r?he=void 0:(Y=he,he=r),he!==r?(t.length>Y?(ze=t.charAt(Y),Y++):(ze=r,ct===0&&Ct(Fn)),ze!==r?(Dt=re,he=Me(ze),re=he):(Y=re,re=r)):(Y=re,re=r),re!==r)for(;re!==r;)K.push(re),re=Y,he=Y,ct++,ze=m0(),ct--,ze===r?he=void 0:(Y=he,he=r),he!==r?(t.length>Y?(ze=t.charAt(Y),Y++):(ze=r,ct===0&&Ct(Fn)),ze!==r?(Dt=re,he=Me(ze),re=he):(Y=re,re=r)):(Y=re,re=r);else K=r;return K!==r&&(Dt=N,K=_s(K)),N=K,N}function d0(){var N,K,re;if(N=Y,K=[],i0.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(FA)),re!==r)for(;re!==r;)K.push(re),i0.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(FA));else K=r;return K!==r&&(Dt=N,K=js()),N=K,N}function Wa(){var N,K,re;if(N=Y,K=[],Eu.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(ja)),re!==r)for(;re!==r;)K.push(re),Eu.test(t.charAt(Y))?(re=t.charAt(Y),Y++):(re=r,ct===0&&Ct(ja));else K=r;return K!==r&&(Dt=N,K=js()),N=K,N}function Cd(){var N;return Gi.test(t.charAt(Y))?(N=t.charAt(Y),Y++):(N=r,ct===0&&Ct(fa)),N}function m0(){var N;return Cu.test(t.charAt(Y))?(N=t.charAt(Y),Y++):(N=r,ct===0&&Ct(ws)),N}function Qt(){var N,K;if(N=[],Cc.test(t.charAt(Y))?(K=t.charAt(Y),Y++):(K=r,ct===0&&Ct(wc)),K!==r)for(;K!==r;)N.push(K),Cc.test(t.charAt(Y))?(K=t.charAt(Y),Y++):(K=r,ct===0&&Ct(wc));else N=r;return N}if(wu=a(),wu!==r&&Y===t.length)return wu;throw wu!==r&&Y<t.length&&Ct(a0()),c0(Ic,Si<t.length?t.charAt(Si):null,Si<t.length?Bc(Si,Si+1):Bc(Si,Si))}XY.exports={SyntaxError:_0,parse:c8e}});function CD(t,e={isGlobPattern:()=>!1}){try{return(0,$Y.parse)(t,e)}catch(r){throw r.location&&(r.message=r.message.replace(/(\\.)?$/,` (line ${r.location.start.line}, column ${r.location.start.column})$1`)),r}}function zd(t,{endSemicolon:e=!1}={}){return t.map(({command:r,type:o},a)=>`${wD(r)}${o===\";\"?a!==t.length-1||e?\";\":\"\":\" &\"}`).join(\" \")}function wD(t){return`${Jd(t.chain)}${t.then?` ${VR(t.then)}`:\"\"}`}function VR(t){return`${t.type} ${wD(t.line)}`}function Jd(t){return`${JR(t)}${t.then?` ${zR(t.then)}`:\"\"}`}function zR(t){return`${t.type} ${Jd(t.chain)}`}function JR(t){switch(t.type){case\"command\":return`${t.envs.length>0?`${t.envs.map(e=>ED(e)).join(\" \")} `:\"\"}${t.args.map(e=>XR(e)).join(\" \")}`;case\"subshell\":return`(${zd(t.subshell)})${t.args.length>0?` ${t.args.map(e=>Qw(e)).join(\" \")}`:\"\"}`;case\"group\":return`{ ${zd(t.group,{endSemicolon:!0})} }${t.args.length>0?` ${t.args.map(e=>Qw(e)).join(\" \")}`:\"\"}`;case\"envs\":return t.envs.map(e=>ED(e)).join(\" \");default:throw new Error(`Unsupported command type:  \"${t.type}\"`)}}function ED(t){return`${t.name}=${t.args[0]?H0(t.args[0]):\"\"}`}function XR(t){switch(t.type){case\"redirection\":return Qw(t);case\"argument\":return H0(t);default:throw new Error(`Unsupported argument type: \"${t.type}\"`)}}function Qw(t){return`${t.subtype} ${t.args.map(e=>H0(e)).join(\" \")}`}function H0(t){return t.segments.map(e=>ZR(e)).join(\"\")}function ZR(t){let e=(o,a)=>a?`\"${o}\"`:o,r=o=>o===\"\"?\"''\":o.match(/[()}<>$|&;\"'\\n\\t ]/)?o.match(/['\\t\\p{C}]/u)?o.match(/'/)?`\"${o.replace(/[\"$\\t\\p{C}]/u,A8e)}\"`:`$'${o.replace(/[\\t\\p{C}]/u,tW)}'`:`'${o}'`:o;switch(t.type){case\"text\":return r(t.text);case\"glob\":return t.pattern;case\"shell\":return e(`$(${zd(t.shell)})`,t.quoted);case\"variable\":return e(typeof t.defaultValue>\"u\"?typeof t.alternativeValue>\"u\"?`\\${${t.name}}`:t.alternativeValue.length===0?`\\${${t.name}:+}`:`\\${${t.name}:+${t.alternativeValue.map(o=>H0(o)).join(\" \")}}`:t.defaultValue.length===0?`\\${${t.name}:-}`:`\\${${t.name}:-${t.defaultValue.map(o=>H0(o)).join(\" \")}}`,t.quoted);case\"arithmetic\":return`$(( ${ID(t.arithmetic)} ))`;default:throw new Error(`Unsupported argument segment type: \"${t.type}\"`)}}function ID(t){let e=a=>{switch(a){case\"addition\":return\"+\";case\"subtraction\":return\"-\";case\"multiplication\":return\"*\";case\"division\":return\"/\";default:throw new Error(`Can't extract operator from arithmetic expression of type \"${a}\"`)}},r=(a,n)=>n?`( ${a} )`:a,o=a=>r(ID(a),![\"number\",\"variable\"].includes(a.type));switch(t.type){case\"number\":return String(t.value);case\"variable\":return t.name;default:return`${o(t.left)} ${e(t.type)} ${o(t.right)}`}}var $Y,eW,u8e,tW,A8e,rW=Et(()=>{$Y=Ze(ZY());eW=new Map([[\"\\f\",\"\\\\f\"],[`\n`,\"\\\\n\"],[\"\\r\",\"\\\\r\"],[\"\t\",\"\\\\t\"],[\"\\v\",\"\\\\v\"],[\"\\0\",\"\\\\0\"]]),u8e=new Map([[\"\\\\\",\"\\\\\\\\\"],[\"$\",\"\\\\$\"],['\"','\\\\\"'],...Array.from(eW,([t,e])=>[t,`\"$'${e}'\"`])]),tW=t=>eW.get(t)??`\\\\x${t.charCodeAt(0).toString(16).padStart(2,\"0\")}`,A8e=t=>u8e.get(t)??`\"$'${tW(t)}'\"`});var iW=_((_St,nW)=>{\"use strict\";function f8e(t,e){function r(){this.constructor=t}r.prototype=e.prototype,t.prototype=new r}function q0(t,e,r,o){this.message=t,this.expected=e,this.found=r,this.location=o,this.name=\"SyntaxError\",typeof Error.captureStackTrace==\"function\"&&Error.captureStackTrace(this,q0)}f8e(q0,Error);q0.buildMessage=function(t,e){var r={literal:function(h){return'\"'+a(h.text)+'\"'},class:function(h){var E=\"\",I;for(I=0;I<h.parts.length;I++)E+=h.parts[I]instanceof Array?n(h.parts[I][0])+\"-\"+n(h.parts[I][1]):n(h.parts[I]);return\"[\"+(h.inverted?\"^\":\"\")+E+\"]\"},any:function(h){return\"any character\"},end:function(h){return\"end of input\"},other:function(h){return h.description}};function o(h){return h.charCodeAt(0).toString(16).toUpperCase()}function a(h){return h.replace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"').replace(/\\0/g,\"\\\\0\").replace(/\\t/g,\"\\\\t\").replace(/\\n/g,\"\\\\n\").replace(/\\r/g,\"\\\\r\").replace(/[\\x00-\\x0F]/g,function(E){return\"\\\\x0\"+o(E)}).replace(/[\\x10-\\x1F\\x7F-\\x9F]/g,function(E){return\"\\\\x\"+o(E)})}function n(h){return h.replace(/\\\\/g,\"\\\\\\\\\").replace(/\\]/g,\"\\\\]\").replace(/\\^/g,\"\\\\^\").replace(/-/g,\"\\\\-\").replace(/\\0/g,\"\\\\0\").replace(/\\t/g,\"\\\\t\").replace(/\\n/g,\"\\\\n\").replace(/\\r/g,\"\\\\r\").replace(/[\\x00-\\x0F]/g,function(E){return\"\\\\x0\"+o(E)}).replace(/[\\x10-\\x1F\\x7F-\\x9F]/g,function(E){return\"\\\\x\"+o(E)})}function u(h){return r[h.type](h)}function A(h){var E=new Array(h.length),I,v;for(I=0;I<h.length;I++)E[I]=u(h[I]);if(E.sort(),E.length>0){for(I=1,v=1;I<E.length;I++)E[I-1]!==E[I]&&(E[v]=E[I],v++);E.length=v}switch(E.length){case 1:return E[0];case 2:return E[0]+\" or \"+E[1];default:return E.slice(0,-1).join(\", \")+\", or \"+E[E.length-1]}}function p(h){return h?'\"'+a(h)+'\"':\"end of input\"}return\"Expected \"+A(t)+\" but \"+p(e)+\" found.\"};function p8e(t,e){e=e!==void 0?e:{};var r={},o={resolution:Fe},a=Fe,n=\"/\",u=we(\"/\",!1),A=function(Ue,S){return{from:Ue,descriptor:S}},p=function(Ue){return{descriptor:Ue}},h=\"@\",E=we(\"@\",!1),I=function(Ue,S){return{fullName:Ue,description:S}},v=function(Ue){return{fullName:Ue}},x=function(){return Be()},C=/^[^\\/@]/,R=Ae([\"/\",\"@\"],!0,!1),L=/^[^\\/]/,U=Ae([\"/\"],!0,!1),z=0,te=0,ae=[{line:1,column:1}],le=0,ce=[],Ce=0,de;if(\"startRule\"in e){if(!(e.startRule in o))throw new Error(`Can't start parsing from rule \"`+e.startRule+'\".');a=o[e.startRule]}function Be(){return t.substring(te,z)}function Ee(){return ht(te,z)}function g(Ue,S){throw S=S!==void 0?S:ht(te,z),Te([xe(Ue)],t.substring(te,z),S)}function me(Ue,S){throw S=S!==void 0?S:ht(te,z),rt(Ue,S)}function we(Ue,S){return{type:\"literal\",text:Ue,ignoreCase:S}}function Ae(Ue,S,w){return{type:\"class\",parts:Ue,inverted:S,ignoreCase:w}}function ne(){return{type:\"any\"}}function Z(){return{type:\"end\"}}function xe(Ue){return{type:\"other\",description:Ue}}function Ne(Ue){var S=ae[Ue],w;if(S)return S;for(w=Ue-1;!ae[w];)w--;for(S=ae[w],S={line:S.line,column:S.column};w<Ue;)t.charCodeAt(w)===10?(S.line++,S.column=1):S.column++,w++;return ae[Ue]=S,S}function ht(Ue,S){var w=Ne(Ue),b=Ne(S);return{start:{offset:Ue,line:w.line,column:w.column},end:{offset:S,line:b.line,column:b.column}}}function H(Ue){z<le||(z>le&&(le=z,ce=[]),ce.push(Ue))}function rt(Ue,S){return new q0(Ue,null,null,S)}function Te(Ue,S,w){return new q0(q0.buildMessage(Ue,S),Ue,S,w)}function Fe(){var Ue,S,w,b;return Ue=z,S=ke(),S!==r?(t.charCodeAt(z)===47?(w=n,z++):(w=r,Ce===0&&H(u)),w!==r?(b=ke(),b!==r?(te=Ue,S=A(S,b),Ue=S):(z=Ue,Ue=r)):(z=Ue,Ue=r)):(z=Ue,Ue=r),Ue===r&&(Ue=z,S=ke(),S!==r&&(te=Ue,S=p(S)),Ue=S),Ue}function ke(){var Ue,S,w,b;return Ue=z,S=Ye(),S!==r?(t.charCodeAt(z)===64?(w=h,z++):(w=r,Ce===0&&H(E)),w!==r?(b=et(),b!==r?(te=Ue,S=I(S,b),Ue=S):(z=Ue,Ue=r)):(z=Ue,Ue=r)):(z=Ue,Ue=r),Ue===r&&(Ue=z,S=Ye(),S!==r&&(te=Ue,S=v(S)),Ue=S),Ue}function Ye(){var Ue,S,w,b,y;return Ue=z,t.charCodeAt(z)===64?(S=h,z++):(S=r,Ce===0&&H(E)),S!==r?(w=be(),w!==r?(t.charCodeAt(z)===47?(b=n,z++):(b=r,Ce===0&&H(u)),b!==r?(y=be(),y!==r?(te=Ue,S=x(),Ue=S):(z=Ue,Ue=r)):(z=Ue,Ue=r)):(z=Ue,Ue=r)):(z=Ue,Ue=r),Ue===r&&(Ue=z,S=be(),S!==r&&(te=Ue,S=x()),Ue=S),Ue}function be(){var Ue,S,w;if(Ue=z,S=[],C.test(t.charAt(z))?(w=t.charAt(z),z++):(w=r,Ce===0&&H(R)),w!==r)for(;w!==r;)S.push(w),C.test(t.charAt(z))?(w=t.charAt(z),z++):(w=r,Ce===0&&H(R));else S=r;return S!==r&&(te=Ue,S=x()),Ue=S,Ue}function et(){var Ue,S,w;if(Ue=z,S=[],L.test(t.charAt(z))?(w=t.charAt(z),z++):(w=r,Ce===0&&H(U)),w!==r)for(;w!==r;)S.push(w),L.test(t.charAt(z))?(w=t.charAt(z),z++):(w=r,Ce===0&&H(U));else S=r;return S!==r&&(te=Ue,S=x()),Ue=S,Ue}if(de=a(),de!==r&&z===t.length)return de;throw de!==r&&z<t.length&&H(Z()),Te(ce,le<t.length?t.charAt(le):null,le<t.length?ht(le,le+1):ht(le,le))}nW.exports={SyntaxError:q0,parse:p8e}});function BD(t){let e=t.match(/^\\*{1,2}\\/(.*)/);if(e)throw new Error(`The override for '${t}' includes a glob pattern. Glob patterns have been removed since their behaviours don't match what you'd expect. Set the override to '${e[1]}' instead.`);try{return(0,sW.parse)(t)}catch(r){throw r.location&&(r.message=r.message.replace(/(\\.)?$/,` (line ${r.location.start.line}, column ${r.location.start.column})$1`)),r}}function vD(t){let e=\"\";return t.from&&(e+=t.from.fullName,t.from.description&&(e+=`@${t.from.description}`),e+=\"/\"),e+=t.descriptor.fullName,t.descriptor.description&&(e+=`@${t.descriptor.description}`),e}var sW,oW=Et(()=>{sW=Ze(iW())});var G0=_((qSt,j0)=>{\"use strict\";function aW(t){return typeof t>\"u\"||t===null}function h8e(t){return typeof t==\"object\"&&t!==null}function g8e(t){return Array.isArray(t)?t:aW(t)?[]:[t]}function d8e(t,e){var r,o,a,n;if(e)for(n=Object.keys(e),r=0,o=n.length;r<o;r+=1)a=n[r],t[a]=e[a];return t}function m8e(t,e){var r=\"\",o;for(o=0;o<e;o+=1)r+=t;return r}function y8e(t){return t===0&&Number.NEGATIVE_INFINITY===1/t}j0.exports.isNothing=aW;j0.exports.isObject=h8e;j0.exports.toArray=g8e;j0.exports.repeat=m8e;j0.exports.isNegativeZero=y8e;j0.exports.extend=d8e});var Xd=_((jSt,lW)=>{\"use strict\";function Fw(t,e){Error.call(this),this.name=\"YAMLException\",this.reason=t,this.mark=e,this.message=(this.reason||\"(unknown reason)\")+(this.mark?\" \"+this.mark.toString():\"\"),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack||\"\"}Fw.prototype=Object.create(Error.prototype);Fw.prototype.constructor=Fw;Fw.prototype.toString=function(e){var r=this.name+\": \";return r+=this.reason||\"(unknown reason)\",!e&&this.mark&&(r+=\" \"+this.mark.toString()),r};lW.exports=Fw});var AW=_((GSt,uW)=>{\"use strict\";var cW=G0();function $R(t,e,r,o,a){this.name=t,this.buffer=e,this.position=r,this.line=o,this.column=a}$R.prototype.getSnippet=function(e,r){var o,a,n,u,A;if(!this.buffer)return null;for(e=e||4,r=r||75,o=\"\",a=this.position;a>0&&`\\0\\r\n\\x85\\u2028\\u2029`.indexOf(this.buffer.charAt(a-1))===-1;)if(a-=1,this.position-a>r/2-1){o=\" ... \",a+=5;break}for(n=\"\",u=this.position;u<this.buffer.length&&`\\0\\r\n\\x85\\u2028\\u2029`.indexOf(this.buffer.charAt(u))===-1;)if(u+=1,u-this.position>r/2-1){n=\" ... \",u-=5;break}return A=this.buffer.slice(a,u),cW.repeat(\" \",e)+o+A+n+`\n`+cW.repeat(\" \",e+this.position-a+o.length)+\"^\"};$R.prototype.toString=function(e){var r,o=\"\";return this.name&&(o+='in \"'+this.name+'\" '),o+=\"at line \"+(this.line+1)+\", column \"+(this.column+1),e||(r=this.getSnippet(),r&&(o+=`:\n`+r)),o};uW.exports=$R});var ls=_((YSt,pW)=>{\"use strict\";var fW=Xd(),E8e=[\"kind\",\"resolve\",\"construct\",\"instanceOf\",\"predicate\",\"represent\",\"defaultStyle\",\"styleAliases\"],C8e=[\"scalar\",\"sequence\",\"mapping\"];function w8e(t){var e={};return t!==null&&Object.keys(t).forEach(function(r){t[r].forEach(function(o){e[String(o)]=r})}),e}function I8e(t,e){if(e=e||{},Object.keys(e).forEach(function(r){if(E8e.indexOf(r)===-1)throw new fW('Unknown option \"'+r+'\" is met in definition of \"'+t+'\" YAML type.')}),this.tag=t,this.kind=e.kind||null,this.resolve=e.resolve||function(){return!0},this.construct=e.construct||function(r){return r},this.instanceOf=e.instanceOf||null,this.predicate=e.predicate||null,this.represent=e.represent||null,this.defaultStyle=e.defaultStyle||null,this.styleAliases=w8e(e.styleAliases||null),C8e.indexOf(this.kind)===-1)throw new fW('Unknown kind \"'+this.kind+'\" is specified for \"'+t+'\" YAML type.')}pW.exports=I8e});var Y0=_((WSt,gW)=>{\"use strict\";var hW=G0(),DD=Xd(),B8e=ls();function eT(t,e,r){var o=[];return t.include.forEach(function(a){r=eT(a,e,r)}),t[e].forEach(function(a){r.forEach(function(n,u){n.tag===a.tag&&n.kind===a.kind&&o.push(u)}),r.push(a)}),r.filter(function(a,n){return o.indexOf(n)===-1})}function v8e(){var t={scalar:{},sequence:{},mapping:{},fallback:{}},e,r;function o(a){t[a.kind][a.tag]=t.fallback[a.tag]=a}for(e=0,r=arguments.length;e<r;e+=1)arguments[e].forEach(o);return t}function Zd(t){this.include=t.include||[],this.implicit=t.implicit||[],this.explicit=t.explicit||[],this.implicit.forEach(function(e){if(e.loadKind&&e.loadKind!==\"scalar\")throw new DD(\"There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.\")}),this.compiledImplicit=eT(this,\"implicit\",[]),this.compiledExplicit=eT(this,\"explicit\",[]),this.compiledTypeMap=v8e(this.compiledImplicit,this.compiledExplicit)}Zd.DEFAULT=null;Zd.create=function(){var e,r;switch(arguments.length){case 1:e=Zd.DEFAULT,r=arguments[0];break;case 2:e=arguments[0],r=arguments[1];break;default:throw new DD(\"Wrong number of arguments for Schema.create function\")}if(e=hW.toArray(e),r=hW.toArray(r),!e.every(function(o){return o instanceof Zd}))throw new DD(\"Specified list of super schemas (or a single Schema object) contains a non-Schema object.\");if(!r.every(function(o){return o instanceof B8e}))throw new DD(\"Specified list of YAML types (or a single Type object) contains a non-Type object.\");return new Zd({include:e,explicit:r})};gW.exports=Zd});var mW=_((KSt,dW)=>{\"use strict\";var D8e=ls();dW.exports=new D8e(\"tag:yaml.org,2002:str\",{kind:\"scalar\",construct:function(t){return t!==null?t:\"\"}})});var EW=_((VSt,yW)=>{\"use strict\";var P8e=ls();yW.exports=new P8e(\"tag:yaml.org,2002:seq\",{kind:\"sequence\",construct:function(t){return t!==null?t:[]}})});var wW=_((zSt,CW)=>{\"use strict\";var b8e=ls();CW.exports=new b8e(\"tag:yaml.org,2002:map\",{kind:\"mapping\",construct:function(t){return t!==null?t:{}}})});var PD=_((JSt,IW)=>{\"use strict\";var S8e=Y0();IW.exports=new S8e({explicit:[mW(),EW(),wW()]})});var vW=_((XSt,BW)=>{\"use strict\";var x8e=ls();function k8e(t){if(t===null)return!0;var e=t.length;return e===1&&t===\"~\"||e===4&&(t===\"null\"||t===\"Null\"||t===\"NULL\")}function Q8e(){return null}function F8e(t){return t===null}BW.exports=new x8e(\"tag:yaml.org,2002:null\",{kind:\"scalar\",resolve:k8e,construct:Q8e,predicate:F8e,represent:{canonical:function(){return\"~\"},lowercase:function(){return\"null\"},uppercase:function(){return\"NULL\"},camelcase:function(){return\"Null\"}},defaultStyle:\"lowercase\"})});var PW=_((ZSt,DW)=>{\"use strict\";var R8e=ls();function T8e(t){if(t===null)return!1;var e=t.length;return e===4&&(t===\"true\"||t===\"True\"||t===\"TRUE\")||e===5&&(t===\"false\"||t===\"False\"||t===\"FALSE\")}function N8e(t){return t===\"true\"||t===\"True\"||t===\"TRUE\"}function L8e(t){return Object.prototype.toString.call(t)===\"[object Boolean]\"}DW.exports=new R8e(\"tag:yaml.org,2002:bool\",{kind:\"scalar\",resolve:T8e,construct:N8e,predicate:L8e,represent:{lowercase:function(t){return t?\"true\":\"false\"},uppercase:function(t){return t?\"TRUE\":\"FALSE\"},camelcase:function(t){return t?\"True\":\"False\"}},defaultStyle:\"lowercase\"})});var SW=_(($St,bW)=>{\"use strict\";var M8e=G0(),O8e=ls();function U8e(t){return 48<=t&&t<=57||65<=t&&t<=70||97<=t&&t<=102}function _8e(t){return 48<=t&&t<=55}function H8e(t){return 48<=t&&t<=57}function q8e(t){if(t===null)return!1;var e=t.length,r=0,o=!1,a;if(!e)return!1;if(a=t[r],(a===\"-\"||a===\"+\")&&(a=t[++r]),a===\"0\"){if(r+1===e)return!0;if(a=t[++r],a===\"b\"){for(r++;r<e;r++)if(a=t[r],a!==\"_\"){if(a!==\"0\"&&a!==\"1\")return!1;o=!0}return o&&a!==\"_\"}if(a===\"x\"){for(r++;r<e;r++)if(a=t[r],a!==\"_\"){if(!U8e(t.charCodeAt(r)))return!1;o=!0}return o&&a!==\"_\"}for(;r<e;r++)if(a=t[r],a!==\"_\"){if(!_8e(t.charCodeAt(r)))return!1;o=!0}return o&&a!==\"_\"}if(a===\"_\")return!1;for(;r<e;r++)if(a=t[r],a!==\"_\"){if(a===\":\")break;if(!H8e(t.charCodeAt(r)))return!1;o=!0}return!o||a===\"_\"?!1:a!==\":\"?!0:/^(:[0-5]?[0-9])+$/.test(t.slice(r))}function j8e(t){var e=t,r=1,o,a,n=[];return e.indexOf(\"_\")!==-1&&(e=e.replace(/_/g,\"\")),o=e[0],(o===\"-\"||o===\"+\")&&(o===\"-\"&&(r=-1),e=e.slice(1),o=e[0]),e===\"0\"?0:o===\"0\"?e[1]===\"b\"?r*parseInt(e.slice(2),2):e[1]===\"x\"?r*parseInt(e,16):r*parseInt(e,8):e.indexOf(\":\")!==-1?(e.split(\":\").forEach(function(u){n.unshift(parseInt(u,10))}),e=0,a=1,n.forEach(function(u){e+=u*a,a*=60}),r*e):r*parseInt(e,10)}function G8e(t){return Object.prototype.toString.call(t)===\"[object Number]\"&&t%1===0&&!M8e.isNegativeZero(t)}bW.exports=new O8e(\"tag:yaml.org,2002:int\",{kind:\"scalar\",resolve:q8e,construct:j8e,predicate:G8e,represent:{binary:function(t){return t>=0?\"0b\"+t.toString(2):\"-0b\"+t.toString(2).slice(1)},octal:function(t){return t>=0?\"0\"+t.toString(8):\"-0\"+t.toString(8).slice(1)},decimal:function(t){return t.toString(10)},hexadecimal:function(t){return t>=0?\"0x\"+t.toString(16).toUpperCase():\"-0x\"+t.toString(16).toUpperCase().slice(1)}},defaultStyle:\"decimal\",styleAliases:{binary:[2,\"bin\"],octal:[8,\"oct\"],decimal:[10,\"dec\"],hexadecimal:[16,\"hex\"]}})});var QW=_((ext,kW)=>{\"use strict\";var xW=G0(),Y8e=ls(),W8e=new RegExp(\"^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?|\\\\.[0-9_]+(?:[eE][-+]?[0-9]+)?|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\\\.[0-9_]*|[-+]?\\\\.(?:inf|Inf|INF)|\\\\.(?:nan|NaN|NAN))$\");function K8e(t){return!(t===null||!W8e.test(t)||t[t.length-1]===\"_\")}function V8e(t){var e,r,o,a;return e=t.replace(/_/g,\"\").toLowerCase(),r=e[0]===\"-\"?-1:1,a=[],\"+-\".indexOf(e[0])>=0&&(e=e.slice(1)),e===\".inf\"?r===1?Number.POSITIVE_INFINITY:Number.NEGATIVE_INFINITY:e===\".nan\"?NaN:e.indexOf(\":\")>=0?(e.split(\":\").forEach(function(n){a.unshift(parseFloat(n,10))}),e=0,o=1,a.forEach(function(n){e+=n*o,o*=60}),r*e):r*parseFloat(e,10)}var z8e=/^[-+]?[0-9]+e/;function J8e(t,e){var r;if(isNaN(t))switch(e){case\"lowercase\":return\".nan\";case\"uppercase\":return\".NAN\";case\"camelcase\":return\".NaN\"}else if(Number.POSITIVE_INFINITY===t)switch(e){case\"lowercase\":return\".inf\";case\"uppercase\":return\".INF\";case\"camelcase\":return\".Inf\"}else if(Number.NEGATIVE_INFINITY===t)switch(e){case\"lowercase\":return\"-.inf\";case\"uppercase\":return\"-.INF\";case\"camelcase\":return\"-.Inf\"}else if(xW.isNegativeZero(t))return\"-0.0\";return r=t.toString(10),z8e.test(r)?r.replace(\"e\",\".e\"):r}function X8e(t){return Object.prototype.toString.call(t)===\"[object Number]\"&&(t%1!==0||xW.isNegativeZero(t))}kW.exports=new Y8e(\"tag:yaml.org,2002:float\",{kind:\"scalar\",resolve:K8e,construct:V8e,predicate:X8e,represent:J8e,defaultStyle:\"lowercase\"})});var tT=_((txt,FW)=>{\"use strict\";var Z8e=Y0();FW.exports=new Z8e({include:[PD()],implicit:[vW(),PW(),SW(),QW()]})});var rT=_((rxt,RW)=>{\"use strict\";var $8e=Y0();RW.exports=new $8e({include:[tT()]})});var MW=_((nxt,LW)=>{\"use strict\";var eHe=ls(),TW=new RegExp(\"^([0-9][0-9][0-9][0-9])-([0-9][0-9])-([0-9][0-9])$\"),NW=new RegExp(\"^([0-9][0-9][0-9][0-9])-([0-9][0-9]?)-([0-9][0-9]?)(?:[Tt]|[ \\\\t]+)([0-9][0-9]?):([0-9][0-9]):([0-9][0-9])(?:\\\\.([0-9]*))?(?:[ \\\\t]*(Z|([-+])([0-9][0-9]?)(?::([0-9][0-9]))?))?$\");function tHe(t){return t===null?!1:TW.exec(t)!==null||NW.exec(t)!==null}function rHe(t){var e,r,o,a,n,u,A,p=0,h=null,E,I,v;if(e=TW.exec(t),e===null&&(e=NW.exec(t)),e===null)throw new Error(\"Date resolve error\");if(r=+e[1],o=+e[2]-1,a=+e[3],!e[4])return new Date(Date.UTC(r,o,a));if(n=+e[4],u=+e[5],A=+e[6],e[7]){for(p=e[7].slice(0,3);p.length<3;)p+=\"0\";p=+p}return e[9]&&(E=+e[10],I=+(e[11]||0),h=(E*60+I)*6e4,e[9]===\"-\"&&(h=-h)),v=new Date(Date.UTC(r,o,a,n,u,A,p)),h&&v.setTime(v.getTime()-h),v}function nHe(t){return t.toISOString()}LW.exports=new eHe(\"tag:yaml.org,2002:timestamp\",{kind:\"scalar\",resolve:tHe,construct:rHe,instanceOf:Date,represent:nHe})});var UW=_((ixt,OW)=>{\"use strict\";var iHe=ls();function sHe(t){return t===\"<<\"||t===null}OW.exports=new iHe(\"tag:yaml.org,2002:merge\",{kind:\"scalar\",resolve:sHe})});var qW=_((sxt,HW)=>{\"use strict\";var W0;try{_W=ve,W0=_W(\"buffer\").Buffer}catch{}var _W,oHe=ls(),nT=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\\r`;function aHe(t){if(t===null)return!1;var e,r,o=0,a=t.length,n=nT;for(r=0;r<a;r++)if(e=n.indexOf(t.charAt(r)),!(e>64)){if(e<0)return!1;o+=6}return o%8===0}function lHe(t){var e,r,o=t.replace(/[\\r\\n=]/g,\"\"),a=o.length,n=nT,u=0,A=[];for(e=0;e<a;e++)e%4===0&&e&&(A.push(u>>16&255),A.push(u>>8&255),A.push(u&255)),u=u<<6|n.indexOf(o.charAt(e));return r=a%4*6,r===0?(A.push(u>>16&255),A.push(u>>8&255),A.push(u&255)):r===18?(A.push(u>>10&255),A.push(u>>2&255)):r===12&&A.push(u>>4&255),W0?W0.from?W0.from(A):new W0(A):A}function cHe(t){var e=\"\",r=0,o,a,n=t.length,u=nT;for(o=0;o<n;o++)o%3===0&&o&&(e+=u[r>>18&63],e+=u[r>>12&63],e+=u[r>>6&63],e+=u[r&63]),r=(r<<8)+t[o];return a=n%3,a===0?(e+=u[r>>18&63],e+=u[r>>12&63],e+=u[r>>6&63],e+=u[r&63]):a===2?(e+=u[r>>10&63],e+=u[r>>4&63],e+=u[r<<2&63],e+=u[64]):a===1&&(e+=u[r>>2&63],e+=u[r<<4&63],e+=u[64],e+=u[64]),e}function uHe(t){return W0&&W0.isBuffer(t)}HW.exports=new oHe(\"tag:yaml.org,2002:binary\",{kind:\"scalar\",resolve:aHe,construct:lHe,predicate:uHe,represent:cHe})});var GW=_((axt,jW)=>{\"use strict\";var AHe=ls(),fHe=Object.prototype.hasOwnProperty,pHe=Object.prototype.toString;function hHe(t){if(t===null)return!0;var e=[],r,o,a,n,u,A=t;for(r=0,o=A.length;r<o;r+=1){if(a=A[r],u=!1,pHe.call(a)!==\"[object Object]\")return!1;for(n in a)if(fHe.call(a,n))if(!u)u=!0;else return!1;if(!u)return!1;if(e.indexOf(n)===-1)e.push(n);else return!1}return!0}function gHe(t){return t!==null?t:[]}jW.exports=new AHe(\"tag:yaml.org,2002:omap\",{kind:\"sequence\",resolve:hHe,construct:gHe})});var WW=_((lxt,YW)=>{\"use strict\";var dHe=ls(),mHe=Object.prototype.toString;function yHe(t){if(t===null)return!0;var e,r,o,a,n,u=t;for(n=new Array(u.length),e=0,r=u.length;e<r;e+=1){if(o=u[e],mHe.call(o)!==\"[object Object]\"||(a=Object.keys(o),a.length!==1))return!1;n[e]=[a[0],o[a[0]]]}return!0}function EHe(t){if(t===null)return[];var e,r,o,a,n,u=t;for(n=new Array(u.length),e=0,r=u.length;e<r;e+=1)o=u[e],a=Object.keys(o),n[e]=[a[0],o[a[0]]];return n}YW.exports=new dHe(\"tag:yaml.org,2002:pairs\",{kind:\"sequence\",resolve:yHe,construct:EHe})});var VW=_((cxt,KW)=>{\"use strict\";var CHe=ls(),wHe=Object.prototype.hasOwnProperty;function IHe(t){if(t===null)return!0;var e,r=t;for(e in r)if(wHe.call(r,e)&&r[e]!==null)return!1;return!0}function BHe(t){return t!==null?t:{}}KW.exports=new CHe(\"tag:yaml.org,2002:set\",{kind:\"mapping\",resolve:IHe,construct:BHe})});var $d=_((uxt,zW)=>{\"use strict\";var vHe=Y0();zW.exports=new vHe({include:[rT()],implicit:[MW(),UW()],explicit:[qW(),GW(),WW(),VW()]})});var XW=_((Axt,JW)=>{\"use strict\";var DHe=ls();function PHe(){return!0}function bHe(){}function SHe(){return\"\"}function xHe(t){return typeof t>\"u\"}JW.exports=new DHe(\"tag:yaml.org,2002:js/undefined\",{kind:\"scalar\",resolve:PHe,construct:bHe,predicate:xHe,represent:SHe})});var $W=_((fxt,ZW)=>{\"use strict\";var kHe=ls();function QHe(t){if(t===null||t.length===0)return!1;var e=t,r=/\\/([gim]*)$/.exec(t),o=\"\";return!(e[0]===\"/\"&&(r&&(o=r[1]),o.length>3||e[e.length-o.length-1]!==\"/\"))}function FHe(t){var e=t,r=/\\/([gim]*)$/.exec(t),o=\"\";return e[0]===\"/\"&&(r&&(o=r[1]),e=e.slice(1,e.length-o.length-1)),new RegExp(e,o)}function RHe(t){var e=\"/\"+t.source+\"/\";return t.global&&(e+=\"g\"),t.multiline&&(e+=\"m\"),t.ignoreCase&&(e+=\"i\"),e}function THe(t){return Object.prototype.toString.call(t)===\"[object RegExp]\"}ZW.exports=new kHe(\"tag:yaml.org,2002:js/regexp\",{kind:\"scalar\",resolve:QHe,construct:FHe,predicate:THe,represent:RHe})});var rK=_((pxt,tK)=>{\"use strict\";var bD;try{eK=ve,bD=eK(\"esprima\")}catch{typeof window<\"u\"&&(bD=window.esprima)}var eK,NHe=ls();function LHe(t){if(t===null)return!1;try{var e=\"(\"+t+\")\",r=bD.parse(e,{range:!0});return!(r.type!==\"Program\"||r.body.length!==1||r.body[0].type!==\"ExpressionStatement\"||r.body[0].expression.type!==\"ArrowFunctionExpression\"&&r.body[0].expression.type!==\"FunctionExpression\")}catch{return!1}}function MHe(t){var e=\"(\"+t+\")\",r=bD.parse(e,{range:!0}),o=[],a;if(r.type!==\"Program\"||r.body.length!==1||r.body[0].type!==\"ExpressionStatement\"||r.body[0].expression.type!==\"ArrowFunctionExpression\"&&r.body[0].expression.type!==\"FunctionExpression\")throw new Error(\"Failed to resolve function\");return r.body[0].expression.params.forEach(function(n){o.push(n.name)}),a=r.body[0].expression.body.range,r.body[0].expression.body.type===\"BlockStatement\"?new Function(o,e.slice(a[0]+1,a[1]-1)):new Function(o,\"return \"+e.slice(a[0],a[1]))}function OHe(t){return t.toString()}function UHe(t){return Object.prototype.toString.call(t)===\"[object Function]\"}tK.exports=new NHe(\"tag:yaml.org,2002:js/function\",{kind:\"scalar\",resolve:LHe,construct:MHe,predicate:UHe,represent:OHe})});var Rw=_((gxt,iK)=>{\"use strict\";var nK=Y0();iK.exports=nK.DEFAULT=new nK({include:[$d()],explicit:[XW(),$W(),rK()]})});var BK=_((dxt,Tw)=>{\"use strict\";var mf=G0(),AK=Xd(),_He=AW(),fK=$d(),HHe=Rw(),qp=Object.prototype.hasOwnProperty,SD=1,pK=2,hK=3,xD=4,iT=1,qHe=2,sK=3,jHe=/[\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x84\\x86-\\x9F\\uFFFE\\uFFFF]|[\\uD800-\\uDBFF](?![\\uDC00-\\uDFFF])|(?:[^\\uD800-\\uDBFF]|^)[\\uDC00-\\uDFFF]/,GHe=/[\\x85\\u2028\\u2029]/,YHe=/[,\\[\\]\\{\\}]/,gK=/^(?:!|!!|![a-z\\-]+!)$/i,dK=/^(?:!|[^,\\[\\]\\{\\}])(?:%[0-9a-f]{2}|[0-9a-z\\-#;\\/\\?:@&=\\+\\$,_\\.!~\\*'\\(\\)\\[\\]])*$/i;function oK(t){return Object.prototype.toString.call(t)}function ju(t){return t===10||t===13}function V0(t){return t===9||t===32}function va(t){return t===9||t===32||t===10||t===13}function em(t){return t===44||t===91||t===93||t===123||t===125}function WHe(t){var e;return 48<=t&&t<=57?t-48:(e=t|32,97<=e&&e<=102?e-97+10:-1)}function KHe(t){return t===120?2:t===117?4:t===85?8:0}function VHe(t){return 48<=t&&t<=57?t-48:-1}function aK(t){return t===48?\"\\0\":t===97?\"\\x07\":t===98?\"\\b\":t===116||t===9?\"\t\":t===110?`\n`:t===118?\"\\v\":t===102?\"\\f\":t===114?\"\\r\":t===101?\"\\x1B\":t===32?\" \":t===34?'\"':t===47?\"/\":t===92?\"\\\\\":t===78?\"\\x85\":t===95?\"\\xA0\":t===76?\"\\u2028\":t===80?\"\\u2029\":\"\"}function zHe(t){return t<=65535?String.fromCharCode(t):String.fromCharCode((t-65536>>10)+55296,(t-65536&1023)+56320)}var mK=new Array(256),yK=new Array(256);for(K0=0;K0<256;K0++)mK[K0]=aK(K0)?1:0,yK[K0]=aK(K0);var K0;function JHe(t,e){this.input=t,this.filename=e.filename||null,this.schema=e.schema||HHe,this.onWarning=e.onWarning||null,this.legacy=e.legacy||!1,this.json=e.json||!1,this.listener=e.listener||null,this.implicitTypes=this.schema.compiledImplicit,this.typeMap=this.schema.compiledTypeMap,this.length=t.length,this.position=0,this.line=0,this.lineStart=0,this.lineIndent=0,this.documents=[]}function EK(t,e){return new AK(e,new _He(t.filename,t.input,t.position,t.line,t.position-t.lineStart))}function br(t,e){throw EK(t,e)}function kD(t,e){t.onWarning&&t.onWarning.call(null,EK(t,e))}var lK={YAML:function(e,r,o){var a,n,u;e.version!==null&&br(e,\"duplication of %YAML directive\"),o.length!==1&&br(e,\"YAML directive accepts exactly one argument\"),a=/^([0-9]+)\\.([0-9]+)$/.exec(o[0]),a===null&&br(e,\"ill-formed argument of the YAML directive\"),n=parseInt(a[1],10),u=parseInt(a[2],10),n!==1&&br(e,\"unacceptable YAML version of the document\"),e.version=o[0],e.checkLineBreaks=u<2,u!==1&&u!==2&&kD(e,\"unsupported YAML version of the document\")},TAG:function(e,r,o){var a,n;o.length!==2&&br(e,\"TAG directive accepts exactly two arguments\"),a=o[0],n=o[1],gK.test(a)||br(e,\"ill-formed tag handle (first argument) of the TAG directive\"),qp.call(e.tagMap,a)&&br(e,'there is a previously declared suffix for \"'+a+'\" tag handle'),dK.test(n)||br(e,\"ill-formed tag prefix (second argument) of the TAG directive\"),e.tagMap[a]=n}};function Hp(t,e,r,o){var a,n,u,A;if(e<r){if(A=t.input.slice(e,r),o)for(a=0,n=A.length;a<n;a+=1)u=A.charCodeAt(a),u===9||32<=u&&u<=1114111||br(t,\"expected valid JSON character\");else jHe.test(A)&&br(t,\"the stream contains non-printable characters\");t.result+=A}}function cK(t,e,r,o){var a,n,u,A;for(mf.isObject(r)||br(t,\"cannot merge mappings; the provided source object is unacceptable\"),a=Object.keys(r),u=0,A=a.length;u<A;u+=1)n=a[u],qp.call(e,n)||(e[n]=r[n],o[n]=!0)}function tm(t,e,r,o,a,n,u,A){var p,h;if(Array.isArray(a))for(a=Array.prototype.slice.call(a),p=0,h=a.length;p<h;p+=1)Array.isArray(a[p])&&br(t,\"nested arrays are not supported inside keys\"),typeof a==\"object\"&&oK(a[p])===\"[object Object]\"&&(a[p]=\"[object Object]\");if(typeof a==\"object\"&&oK(a)===\"[object Object]\"&&(a=\"[object Object]\"),a=String(a),e===null&&(e={}),o===\"tag:yaml.org,2002:merge\")if(Array.isArray(n))for(p=0,h=n.length;p<h;p+=1)cK(t,e,n[p],r);else cK(t,e,n,r);else!t.json&&!qp.call(r,a)&&qp.call(e,a)&&(t.line=u||t.line,t.position=A||t.position,br(t,\"duplicated mapping key\")),e[a]=n,delete r[a];return e}function sT(t){var e;e=t.input.charCodeAt(t.position),e===10?t.position++:e===13?(t.position++,t.input.charCodeAt(t.position)===10&&t.position++):br(t,\"a line break is expected\"),t.line+=1,t.lineStart=t.position}function Wi(t,e,r){for(var o=0,a=t.input.charCodeAt(t.position);a!==0;){for(;V0(a);)a=t.input.charCodeAt(++t.position);if(e&&a===35)do a=t.input.charCodeAt(++t.position);while(a!==10&&a!==13&&a!==0);if(ju(a))for(sT(t),a=t.input.charCodeAt(t.position),o++,t.lineIndent=0;a===32;)t.lineIndent++,a=t.input.charCodeAt(++t.position);else break}return r!==-1&&o!==0&&t.lineIndent<r&&kD(t,\"deficient indentation\"),o}function QD(t){var e=t.position,r;return r=t.input.charCodeAt(e),!!((r===45||r===46)&&r===t.input.charCodeAt(e+1)&&r===t.input.charCodeAt(e+2)&&(e+=3,r=t.input.charCodeAt(e),r===0||va(r)))}function oT(t,e){e===1?t.result+=\" \":e>1&&(t.result+=mf.repeat(`\n`,e-1))}function XHe(t,e,r){var o,a,n,u,A,p,h,E,I=t.kind,v=t.result,x;if(x=t.input.charCodeAt(t.position),va(x)||em(x)||x===35||x===38||x===42||x===33||x===124||x===62||x===39||x===34||x===37||x===64||x===96||(x===63||x===45)&&(a=t.input.charCodeAt(t.position+1),va(a)||r&&em(a)))return!1;for(t.kind=\"scalar\",t.result=\"\",n=u=t.position,A=!1;x!==0;){if(x===58){if(a=t.input.charCodeAt(t.position+1),va(a)||r&&em(a))break}else if(x===35){if(o=t.input.charCodeAt(t.position-1),va(o))break}else{if(t.position===t.lineStart&&QD(t)||r&&em(x))break;if(ju(x))if(p=t.line,h=t.lineStart,E=t.lineIndent,Wi(t,!1,-1),t.lineIndent>=e){A=!0,x=t.input.charCodeAt(t.position);continue}else{t.position=u,t.line=p,t.lineStart=h,t.lineIndent=E;break}}A&&(Hp(t,n,u,!1),oT(t,t.line-p),n=u=t.position,A=!1),V0(x)||(u=t.position+1),x=t.input.charCodeAt(++t.position)}return Hp(t,n,u,!1),t.result?!0:(t.kind=I,t.result=v,!1)}function ZHe(t,e){var r,o,a;if(r=t.input.charCodeAt(t.position),r!==39)return!1;for(t.kind=\"scalar\",t.result=\"\",t.position++,o=a=t.position;(r=t.input.charCodeAt(t.position))!==0;)if(r===39)if(Hp(t,o,t.position,!0),r=t.input.charCodeAt(++t.position),r===39)o=t.position,t.position++,a=t.position;else return!0;else ju(r)?(Hp(t,o,a,!0),oT(t,Wi(t,!1,e)),o=a=t.position):t.position===t.lineStart&&QD(t)?br(t,\"unexpected end of the document within a single quoted scalar\"):(t.position++,a=t.position);br(t,\"unexpected end of the stream within a single quoted scalar\")}function $He(t,e){var r,o,a,n,u,A;if(A=t.input.charCodeAt(t.position),A!==34)return!1;for(t.kind=\"scalar\",t.result=\"\",t.position++,r=o=t.position;(A=t.input.charCodeAt(t.position))!==0;){if(A===34)return Hp(t,r,t.position,!0),t.position++,!0;if(A===92){if(Hp(t,r,t.position,!0),A=t.input.charCodeAt(++t.position),ju(A))Wi(t,!1,e);else if(A<256&&mK[A])t.result+=yK[A],t.position++;else if((u=KHe(A))>0){for(a=u,n=0;a>0;a--)A=t.input.charCodeAt(++t.position),(u=WHe(A))>=0?n=(n<<4)+u:br(t,\"expected hexadecimal character\");t.result+=zHe(n),t.position++}else br(t,\"unknown escape sequence\");r=o=t.position}else ju(A)?(Hp(t,r,o,!0),oT(t,Wi(t,!1,e)),r=o=t.position):t.position===t.lineStart&&QD(t)?br(t,\"unexpected end of the document within a double quoted scalar\"):(t.position++,o=t.position)}br(t,\"unexpected end of the stream within a double quoted scalar\")}function e6e(t,e){var r=!0,o,a=t.tag,n,u=t.anchor,A,p,h,E,I,v={},x,C,R,L;if(L=t.input.charCodeAt(t.position),L===91)p=93,I=!1,n=[];else if(L===123)p=125,I=!0,n={};else return!1;for(t.anchor!==null&&(t.anchorMap[t.anchor]=n),L=t.input.charCodeAt(++t.position);L!==0;){if(Wi(t,!0,e),L=t.input.charCodeAt(t.position),L===p)return t.position++,t.tag=a,t.anchor=u,t.kind=I?\"mapping\":\"sequence\",t.result=n,!0;r||br(t,\"missed comma between flow collection entries\"),C=x=R=null,h=E=!1,L===63&&(A=t.input.charCodeAt(t.position+1),va(A)&&(h=E=!0,t.position++,Wi(t,!0,e))),o=t.line,rm(t,e,SD,!1,!0),C=t.tag,x=t.result,Wi(t,!0,e),L=t.input.charCodeAt(t.position),(E||t.line===o)&&L===58&&(h=!0,L=t.input.charCodeAt(++t.position),Wi(t,!0,e),rm(t,e,SD,!1,!0),R=t.result),I?tm(t,n,v,C,x,R):h?n.push(tm(t,null,v,C,x,R)):n.push(x),Wi(t,!0,e),L=t.input.charCodeAt(t.position),L===44?(r=!0,L=t.input.charCodeAt(++t.position)):r=!1}br(t,\"unexpected end of the stream within a flow collection\")}function t6e(t,e){var r,o,a=iT,n=!1,u=!1,A=e,p=0,h=!1,E,I;if(I=t.input.charCodeAt(t.position),I===124)o=!1;else if(I===62)o=!0;else return!1;for(t.kind=\"scalar\",t.result=\"\";I!==0;)if(I=t.input.charCodeAt(++t.position),I===43||I===45)iT===a?a=I===43?sK:qHe:br(t,\"repeat of a chomping mode identifier\");else if((E=VHe(I))>=0)E===0?br(t,\"bad explicit indentation width of a block scalar; it cannot be less than one\"):u?br(t,\"repeat of an indentation width identifier\"):(A=e+E-1,u=!0);else break;if(V0(I)){do I=t.input.charCodeAt(++t.position);while(V0(I));if(I===35)do I=t.input.charCodeAt(++t.position);while(!ju(I)&&I!==0)}for(;I!==0;){for(sT(t),t.lineIndent=0,I=t.input.charCodeAt(t.position);(!u||t.lineIndent<A)&&I===32;)t.lineIndent++,I=t.input.charCodeAt(++t.position);if(!u&&t.lineIndent>A&&(A=t.lineIndent),ju(I)){p++;continue}if(t.lineIndent<A){a===sK?t.result+=mf.repeat(`\n`,n?1+p:p):a===iT&&n&&(t.result+=`\n`);break}for(o?V0(I)?(h=!0,t.result+=mf.repeat(`\n`,n?1+p:p)):h?(h=!1,t.result+=mf.repeat(`\n`,p+1)):p===0?n&&(t.result+=\" \"):t.result+=mf.repeat(`\n`,p):t.result+=mf.repeat(`\n`,n?1+p:p),n=!0,u=!0,p=0,r=t.position;!ju(I)&&I!==0;)I=t.input.charCodeAt(++t.position);Hp(t,r,t.position,!1)}return!0}function uK(t,e){var r,o=t.tag,a=t.anchor,n=[],u,A=!1,p;for(t.anchor!==null&&(t.anchorMap[t.anchor]=n),p=t.input.charCodeAt(t.position);p!==0&&!(p!==45||(u=t.input.charCodeAt(t.position+1),!va(u)));){if(A=!0,t.position++,Wi(t,!0,-1)&&t.lineIndent<=e){n.push(null),p=t.input.charCodeAt(t.position);continue}if(r=t.line,rm(t,e,hK,!1,!0),n.push(t.result),Wi(t,!0,-1),p=t.input.charCodeAt(t.position),(t.line===r||t.lineIndent>e)&&p!==0)br(t,\"bad indentation of a sequence entry\");else if(t.lineIndent<e)break}return A?(t.tag=o,t.anchor=a,t.kind=\"sequence\",t.result=n,!0):!1}function r6e(t,e,r){var o,a,n,u,A=t.tag,p=t.anchor,h={},E={},I=null,v=null,x=null,C=!1,R=!1,L;for(t.anchor!==null&&(t.anchorMap[t.anchor]=h),L=t.input.charCodeAt(t.position);L!==0;){if(o=t.input.charCodeAt(t.position+1),n=t.line,u=t.position,(L===63||L===58)&&va(o))L===63?(C&&(tm(t,h,E,I,v,null),I=v=x=null),R=!0,C=!0,a=!0):C?(C=!1,a=!0):br(t,\"incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line\"),t.position+=1,L=o;else if(rm(t,r,pK,!1,!0))if(t.line===n){for(L=t.input.charCodeAt(t.position);V0(L);)L=t.input.charCodeAt(++t.position);if(L===58)L=t.input.charCodeAt(++t.position),va(L)||br(t,\"a whitespace character is expected after the key-value separator within a block mapping\"),C&&(tm(t,h,E,I,v,null),I=v=x=null),R=!0,C=!1,a=!1,I=t.tag,v=t.result;else if(R)br(t,\"can not read an implicit mapping pair; a colon is missed\");else return t.tag=A,t.anchor=p,!0}else if(R)br(t,\"can not read a block mapping entry; a multiline key may not be an implicit key\");else return t.tag=A,t.anchor=p,!0;else break;if((t.line===n||t.lineIndent>e)&&(rm(t,e,xD,!0,a)&&(C?v=t.result:x=t.result),C||(tm(t,h,E,I,v,x,n,u),I=v=x=null),Wi(t,!0,-1),L=t.input.charCodeAt(t.position)),t.lineIndent>e&&L!==0)br(t,\"bad indentation of a mapping entry\");else if(t.lineIndent<e)break}return C&&tm(t,h,E,I,v,null),R&&(t.tag=A,t.anchor=p,t.kind=\"mapping\",t.result=h),R}function n6e(t){var e,r=!1,o=!1,a,n,u;if(u=t.input.charCodeAt(t.position),u!==33)return!1;if(t.tag!==null&&br(t,\"duplication of a tag property\"),u=t.input.charCodeAt(++t.position),u===60?(r=!0,u=t.input.charCodeAt(++t.position)):u===33?(o=!0,a=\"!!\",u=t.input.charCodeAt(++t.position)):a=\"!\",e=t.position,r){do u=t.input.charCodeAt(++t.position);while(u!==0&&u!==62);t.position<t.length?(n=t.input.slice(e,t.position),u=t.input.charCodeAt(++t.position)):br(t,\"unexpected end of the stream within a verbatim tag\")}else{for(;u!==0&&!va(u);)u===33&&(o?br(t,\"tag suffix cannot contain exclamation marks\"):(a=t.input.slice(e-1,t.position+1),gK.test(a)||br(t,\"named tag handle cannot contain such characters\"),o=!0,e=t.position+1)),u=t.input.charCodeAt(++t.position);n=t.input.slice(e,t.position),YHe.test(n)&&br(t,\"tag suffix cannot contain flow indicator characters\")}return n&&!dK.test(n)&&br(t,\"tag name cannot contain such characters: \"+n),r?t.tag=n:qp.call(t.tagMap,a)?t.tag=t.tagMap[a]+n:a===\"!\"?t.tag=\"!\"+n:a===\"!!\"?t.tag=\"tag:yaml.org,2002:\"+n:br(t,'undeclared tag handle \"'+a+'\"'),!0}function i6e(t){var e,r;if(r=t.input.charCodeAt(t.position),r!==38)return!1;for(t.anchor!==null&&br(t,\"duplication of an anchor property\"),r=t.input.charCodeAt(++t.position),e=t.position;r!==0&&!va(r)&&!em(r);)r=t.input.charCodeAt(++t.position);return t.position===e&&br(t,\"name of an anchor node must contain at least one character\"),t.anchor=t.input.slice(e,t.position),!0}function s6e(t){var e,r,o;if(o=t.input.charCodeAt(t.position),o!==42)return!1;for(o=t.input.charCodeAt(++t.position),e=t.position;o!==0&&!va(o)&&!em(o);)o=t.input.charCodeAt(++t.position);return t.position===e&&br(t,\"name of an alias node must contain at least one character\"),r=t.input.slice(e,t.position),qp.call(t.anchorMap,r)||br(t,'unidentified alias \"'+r+'\"'),t.result=t.anchorMap[r],Wi(t,!0,-1),!0}function rm(t,e,r,o,a){var n,u,A,p=1,h=!1,E=!1,I,v,x,C,R;if(t.listener!==null&&t.listener(\"open\",t),t.tag=null,t.anchor=null,t.kind=null,t.result=null,n=u=A=xD===r||hK===r,o&&Wi(t,!0,-1)&&(h=!0,t.lineIndent>e?p=1:t.lineIndent===e?p=0:t.lineIndent<e&&(p=-1)),p===1)for(;n6e(t)||i6e(t);)Wi(t,!0,-1)?(h=!0,A=n,t.lineIndent>e?p=1:t.lineIndent===e?p=0:t.lineIndent<e&&(p=-1)):A=!1;if(A&&(A=h||a),(p===1||xD===r)&&(SD===r||pK===r?C=e:C=e+1,R=t.position-t.lineStart,p===1?A&&(uK(t,R)||r6e(t,R,C))||e6e(t,C)?E=!0:(u&&t6e(t,C)||ZHe(t,C)||$He(t,C)?E=!0:s6e(t)?(E=!0,(t.tag!==null||t.anchor!==null)&&br(t,\"alias node should not have any properties\")):XHe(t,C,SD===r)&&(E=!0,t.tag===null&&(t.tag=\"?\")),t.anchor!==null&&(t.anchorMap[t.anchor]=t.result)):p===0&&(E=A&&uK(t,R))),t.tag!==null&&t.tag!==\"!\")if(t.tag===\"?\"){for(t.result!==null&&t.kind!==\"scalar\"&&br(t,'unacceptable node kind for !<?> tag; it should be \"scalar\", not \"'+t.kind+'\"'),I=0,v=t.implicitTypes.length;I<v;I+=1)if(x=t.implicitTypes[I],x.resolve(t.result)){t.result=x.construct(t.result),t.tag=x.tag,t.anchor!==null&&(t.anchorMap[t.anchor]=t.result);break}}else qp.call(t.typeMap[t.kind||\"fallback\"],t.tag)?(x=t.typeMap[t.kind||\"fallback\"][t.tag],t.result!==null&&x.kind!==t.kind&&br(t,\"unacceptable node kind for !<\"+t.tag+'> tag; it should be \"'+x.kind+'\", not \"'+t.kind+'\"'),x.resolve(t.result)?(t.result=x.construct(t.result),t.anchor!==null&&(t.anchorMap[t.anchor]=t.result)):br(t,\"cannot resolve a node with !<\"+t.tag+\"> explicit tag\")):br(t,\"unknown tag !<\"+t.tag+\">\");return t.listener!==null&&t.listener(\"close\",t),t.tag!==null||t.anchor!==null||E}function o6e(t){var e=t.position,r,o,a,n=!1,u;for(t.version=null,t.checkLineBreaks=t.legacy,t.tagMap={},t.anchorMap={};(u=t.input.charCodeAt(t.position))!==0&&(Wi(t,!0,-1),u=t.input.charCodeAt(t.position),!(t.lineIndent>0||u!==37));){for(n=!0,u=t.input.charCodeAt(++t.position),r=t.position;u!==0&&!va(u);)u=t.input.charCodeAt(++t.position);for(o=t.input.slice(r,t.position),a=[],o.length<1&&br(t,\"directive name must not be less than one character in length\");u!==0;){for(;V0(u);)u=t.input.charCodeAt(++t.position);if(u===35){do u=t.input.charCodeAt(++t.position);while(u!==0&&!ju(u));break}if(ju(u))break;for(r=t.position;u!==0&&!va(u);)u=t.input.charCodeAt(++t.position);a.push(t.input.slice(r,t.position))}u!==0&&sT(t),qp.call(lK,o)?lK[o](t,o,a):kD(t,'unknown document directive \"'+o+'\"')}if(Wi(t,!0,-1),t.lineIndent===0&&t.input.charCodeAt(t.position)===45&&t.input.charCodeAt(t.position+1)===45&&t.input.charCodeAt(t.position+2)===45?(t.position+=3,Wi(t,!0,-1)):n&&br(t,\"directives end mark is expected\"),rm(t,t.lineIndent-1,xD,!1,!0),Wi(t,!0,-1),t.checkLineBreaks&&GHe.test(t.input.slice(e,t.position))&&kD(t,\"non-ASCII line breaks are interpreted as content\"),t.documents.push(t.result),t.position===t.lineStart&&QD(t)){t.input.charCodeAt(t.position)===46&&(t.position+=3,Wi(t,!0,-1));return}if(t.position<t.length-1)br(t,\"end of the stream or a document separator is expected\");else return}function CK(t,e){t=String(t),e=e||{},t.length!==0&&(t.charCodeAt(t.length-1)!==10&&t.charCodeAt(t.length-1)!==13&&(t+=`\n`),t.charCodeAt(0)===65279&&(t=t.slice(1)));var r=new JHe(t,e),o=t.indexOf(\"\\0\");for(o!==-1&&(r.position=o,br(r,\"null byte is not allowed in input\")),r.input+=\"\\0\";r.input.charCodeAt(r.position)===32;)r.lineIndent+=1,r.position+=1;for(;r.position<r.length-1;)o6e(r);return r.documents}function wK(t,e,r){e!==null&&typeof e==\"object\"&&typeof r>\"u\"&&(r=e,e=null);var o=CK(t,r);if(typeof e!=\"function\")return o;for(var a=0,n=o.length;a<n;a+=1)e(o[a])}function IK(t,e){var r=CK(t,e);if(r.length!==0){if(r.length===1)return r[0];throw new AK(\"expected a single document in the stream, but found more\")}}function a6e(t,e,r){return typeof e==\"object\"&&e!==null&&typeof r>\"u\"&&(r=e,e=null),wK(t,e,mf.extend({schema:fK},r))}function l6e(t,e){return IK(t,mf.extend({schema:fK},e))}Tw.exports.loadAll=wK;Tw.exports.load=IK;Tw.exports.safeLoadAll=a6e;Tw.exports.safeLoad=l6e});var WK=_((mxt,uT)=>{\"use strict\";var Lw=G0(),Mw=Xd(),c6e=Rw(),u6e=$d(),QK=Object.prototype.toString,FK=Object.prototype.hasOwnProperty,A6e=9,Nw=10,f6e=13,p6e=32,h6e=33,g6e=34,RK=35,d6e=37,m6e=38,y6e=39,E6e=42,TK=44,C6e=45,NK=58,w6e=61,I6e=62,B6e=63,v6e=64,LK=91,MK=93,D6e=96,OK=123,P6e=124,UK=125,vo={};vo[0]=\"\\\\0\";vo[7]=\"\\\\a\";vo[8]=\"\\\\b\";vo[9]=\"\\\\t\";vo[10]=\"\\\\n\";vo[11]=\"\\\\v\";vo[12]=\"\\\\f\";vo[13]=\"\\\\r\";vo[27]=\"\\\\e\";vo[34]='\\\\\"';vo[92]=\"\\\\\\\\\";vo[133]=\"\\\\N\";vo[160]=\"\\\\_\";vo[8232]=\"\\\\L\";vo[8233]=\"\\\\P\";var b6e=[\"y\",\"Y\",\"yes\",\"Yes\",\"YES\",\"on\",\"On\",\"ON\",\"n\",\"N\",\"no\",\"No\",\"NO\",\"off\",\"Off\",\"OFF\"];function S6e(t,e){var r,o,a,n,u,A,p;if(e===null)return{};for(r={},o=Object.keys(e),a=0,n=o.length;a<n;a+=1)u=o[a],A=String(e[u]),u.slice(0,2)===\"!!\"&&(u=\"tag:yaml.org,2002:\"+u.slice(2)),p=t.compiledTypeMap.fallback[u],p&&FK.call(p.styleAliases,A)&&(A=p.styleAliases[A]),r[u]=A;return r}function vK(t){var e,r,o;if(e=t.toString(16).toUpperCase(),t<=255)r=\"x\",o=2;else if(t<=65535)r=\"u\",o=4;else if(t<=4294967295)r=\"U\",o=8;else throw new Mw(\"code point within a string may not be greater than 0xFFFFFFFF\");return\"\\\\\"+r+Lw.repeat(\"0\",o-e.length)+e}function x6e(t){this.schema=t.schema||c6e,this.indent=Math.max(1,t.indent||2),this.noArrayIndent=t.noArrayIndent||!1,this.skipInvalid=t.skipInvalid||!1,this.flowLevel=Lw.isNothing(t.flowLevel)?-1:t.flowLevel,this.styleMap=S6e(this.schema,t.styles||null),this.sortKeys=t.sortKeys||!1,this.lineWidth=t.lineWidth||80,this.noRefs=t.noRefs||!1,this.noCompatMode=t.noCompatMode||!1,this.condenseFlow=t.condenseFlow||!1,this.implicitTypes=this.schema.compiledImplicit,this.explicitTypes=this.schema.compiledExplicit,this.tag=null,this.result=\"\",this.duplicates=[],this.usedDuplicates=null}function DK(t,e){for(var r=Lw.repeat(\" \",e),o=0,a=-1,n=\"\",u,A=t.length;o<A;)a=t.indexOf(`\n`,o),a===-1?(u=t.slice(o),o=A):(u=t.slice(o,a+1),o=a+1),u.length&&u!==`\n`&&(n+=r),n+=u;return n}function aT(t,e){return`\n`+Lw.repeat(\" \",t.indent*e)}function k6e(t,e){var r,o,a;for(r=0,o=t.implicitTypes.length;r<o;r+=1)if(a=t.implicitTypes[r],a.resolve(e))return!0;return!1}function cT(t){return t===p6e||t===A6e}function nm(t){return 32<=t&&t<=126||161<=t&&t<=55295&&t!==8232&&t!==8233||57344<=t&&t<=65533&&t!==65279||65536<=t&&t<=1114111}function Q6e(t){return nm(t)&&!cT(t)&&t!==65279&&t!==f6e&&t!==Nw}function PK(t,e){return nm(t)&&t!==65279&&t!==TK&&t!==LK&&t!==MK&&t!==OK&&t!==UK&&t!==NK&&(t!==RK||e&&Q6e(e))}function F6e(t){return nm(t)&&t!==65279&&!cT(t)&&t!==C6e&&t!==B6e&&t!==NK&&t!==TK&&t!==LK&&t!==MK&&t!==OK&&t!==UK&&t!==RK&&t!==m6e&&t!==E6e&&t!==h6e&&t!==P6e&&t!==w6e&&t!==I6e&&t!==y6e&&t!==g6e&&t!==d6e&&t!==v6e&&t!==D6e}function _K(t){var e=/^\\n* /;return e.test(t)}var HK=1,qK=2,jK=3,GK=4,FD=5;function R6e(t,e,r,o,a){var n,u,A,p=!1,h=!1,E=o!==-1,I=-1,v=F6e(t.charCodeAt(0))&&!cT(t.charCodeAt(t.length-1));if(e)for(n=0;n<t.length;n++){if(u=t.charCodeAt(n),!nm(u))return FD;A=n>0?t.charCodeAt(n-1):null,v=v&&PK(u,A)}else{for(n=0;n<t.length;n++){if(u=t.charCodeAt(n),u===Nw)p=!0,E&&(h=h||n-I-1>o&&t[I+1]!==\" \",I=n);else if(!nm(u))return FD;A=n>0?t.charCodeAt(n-1):null,v=v&&PK(u,A)}h=h||E&&n-I-1>o&&t[I+1]!==\" \"}return!p&&!h?v&&!a(t)?HK:qK:r>9&&_K(t)?FD:h?GK:jK}function T6e(t,e,r,o){t.dump=function(){if(e.length===0)return\"''\";if(!t.noCompatMode&&b6e.indexOf(e)!==-1)return\"'\"+e+\"'\";var a=t.indent*Math.max(1,r),n=t.lineWidth===-1?-1:Math.max(Math.min(t.lineWidth,40),t.lineWidth-a),u=o||t.flowLevel>-1&&r>=t.flowLevel;function A(p){return k6e(t,p)}switch(R6e(e,u,t.indent,n,A)){case HK:return e;case qK:return\"'\"+e.replace(/'/g,\"''\")+\"'\";case jK:return\"|\"+bK(e,t.indent)+SK(DK(e,a));case GK:return\">\"+bK(e,t.indent)+SK(DK(N6e(e,n),a));case FD:return'\"'+L6e(e,n)+'\"';default:throw new Mw(\"impossible error: invalid scalar style\")}}()}function bK(t,e){var r=_K(t)?String(e):\"\",o=t[t.length-1]===`\n`,a=o&&(t[t.length-2]===`\n`||t===`\n`),n=a?\"+\":o?\"\":\"-\";return r+n+`\n`}function SK(t){return t[t.length-1]===`\n`?t.slice(0,-1):t}function N6e(t,e){for(var r=/(\\n+)([^\\n]*)/g,o=function(){var h=t.indexOf(`\n`);return h=h!==-1?h:t.length,r.lastIndex=h,xK(t.slice(0,h),e)}(),a=t[0]===`\n`||t[0]===\" \",n,u;u=r.exec(t);){var A=u[1],p=u[2];n=p[0]===\" \",o+=A+(!a&&!n&&p!==\"\"?`\n`:\"\")+xK(p,e),a=n}return o}function xK(t,e){if(t===\"\"||t[0]===\" \")return t;for(var r=/ [^ ]/g,o,a=0,n,u=0,A=0,p=\"\";o=r.exec(t);)A=o.index,A-a>e&&(n=u>a?u:A,p+=`\n`+t.slice(a,n),a=n+1),u=A;return p+=`\n`,t.length-a>e&&u>a?p+=t.slice(a,u)+`\n`+t.slice(u+1):p+=t.slice(a),p.slice(1)}function L6e(t){for(var e=\"\",r,o,a,n=0;n<t.length;n++){if(r=t.charCodeAt(n),r>=55296&&r<=56319&&(o=t.charCodeAt(n+1),o>=56320&&o<=57343)){e+=vK((r-55296)*1024+o-56320+65536),n++;continue}a=vo[r],e+=!a&&nm(r)?t[n]:a||vK(r)}return e}function M6e(t,e,r){var o=\"\",a=t.tag,n,u;for(n=0,u=r.length;n<u;n+=1)z0(t,e,r[n],!1,!1)&&(n!==0&&(o+=\",\"+(t.condenseFlow?\"\":\" \")),o+=t.dump);t.tag=a,t.dump=\"[\"+o+\"]\"}function O6e(t,e,r,o){var a=\"\",n=t.tag,u,A;for(u=0,A=r.length;u<A;u+=1)z0(t,e+1,r[u],!0,!0)&&((!o||u!==0)&&(a+=aT(t,e)),t.dump&&Nw===t.dump.charCodeAt(0)?a+=\"-\":a+=\"- \",a+=t.dump);t.tag=n,t.dump=a||\"[]\"}function U6e(t,e,r){var o=\"\",a=t.tag,n=Object.keys(r),u,A,p,h,E;for(u=0,A=n.length;u<A;u+=1)E=\"\",u!==0&&(E+=\", \"),t.condenseFlow&&(E+='\"'),p=n[u],h=r[p],z0(t,e,p,!1,!1)&&(t.dump.length>1024&&(E+=\"? \"),E+=t.dump+(t.condenseFlow?'\"':\"\")+\":\"+(t.condenseFlow?\"\":\" \"),z0(t,e,h,!1,!1)&&(E+=t.dump,o+=E));t.tag=a,t.dump=\"{\"+o+\"}\"}function _6e(t,e,r,o){var a=\"\",n=t.tag,u=Object.keys(r),A,p,h,E,I,v;if(t.sortKeys===!0)u.sort();else if(typeof t.sortKeys==\"function\")u.sort(t.sortKeys);else if(t.sortKeys)throw new Mw(\"sortKeys must be a boolean or a function\");for(A=0,p=u.length;A<p;A+=1)v=\"\",(!o||A!==0)&&(v+=aT(t,e)),h=u[A],E=r[h],z0(t,e+1,h,!0,!0,!0)&&(I=t.tag!==null&&t.tag!==\"?\"||t.dump&&t.dump.length>1024,I&&(t.dump&&Nw===t.dump.charCodeAt(0)?v+=\"?\":v+=\"? \"),v+=t.dump,I&&(v+=aT(t,e)),z0(t,e+1,E,!0,I)&&(t.dump&&Nw===t.dump.charCodeAt(0)?v+=\":\":v+=\": \",v+=t.dump,a+=v));t.tag=n,t.dump=a||\"{}\"}function kK(t,e,r){var o,a,n,u,A,p;for(a=r?t.explicitTypes:t.implicitTypes,n=0,u=a.length;n<u;n+=1)if(A=a[n],(A.instanceOf||A.predicate)&&(!A.instanceOf||typeof e==\"object\"&&e instanceof A.instanceOf)&&(!A.predicate||A.predicate(e))){if(t.tag=r?A.tag:\"?\",A.represent){if(p=t.styleMap[A.tag]||A.defaultStyle,QK.call(A.represent)===\"[object Function]\")o=A.represent(e,p);else if(FK.call(A.represent,p))o=A.represent[p](e,p);else throw new Mw(\"!<\"+A.tag+'> tag resolver accepts not \"'+p+'\" style');t.dump=o}return!0}return!1}function z0(t,e,r,o,a,n){t.tag=null,t.dump=r,kK(t,r,!1)||kK(t,r,!0);var u=QK.call(t.dump);o&&(o=t.flowLevel<0||t.flowLevel>e);var A=u===\"[object Object]\"||u===\"[object Array]\",p,h;if(A&&(p=t.duplicates.indexOf(r),h=p!==-1),(t.tag!==null&&t.tag!==\"?\"||h||t.indent!==2&&e>0)&&(a=!1),h&&t.usedDuplicates[p])t.dump=\"*ref_\"+p;else{if(A&&h&&!t.usedDuplicates[p]&&(t.usedDuplicates[p]=!0),u===\"[object Object]\")o&&Object.keys(t.dump).length!==0?(_6e(t,e,t.dump,a),h&&(t.dump=\"&ref_\"+p+t.dump)):(U6e(t,e,t.dump),h&&(t.dump=\"&ref_\"+p+\" \"+t.dump));else if(u===\"[object Array]\"){var E=t.noArrayIndent&&e>0?e-1:e;o&&t.dump.length!==0?(O6e(t,E,t.dump,a),h&&(t.dump=\"&ref_\"+p+t.dump)):(M6e(t,E,t.dump),h&&(t.dump=\"&ref_\"+p+\" \"+t.dump))}else if(u===\"[object String]\")t.tag!==\"?\"&&T6e(t,t.dump,e,n);else{if(t.skipInvalid)return!1;throw new Mw(\"unacceptable kind of an object to dump \"+u)}t.tag!==null&&t.tag!==\"?\"&&(t.dump=\"!<\"+t.tag+\"> \"+t.dump)}return!0}function H6e(t,e){var r=[],o=[],a,n;for(lT(t,r,o),a=0,n=o.length;a<n;a+=1)e.duplicates.push(r[o[a]]);e.usedDuplicates=new Array(n)}function lT(t,e,r){var o,a,n;if(t!==null&&typeof t==\"object\")if(a=e.indexOf(t),a!==-1)r.indexOf(a)===-1&&r.push(a);else if(e.push(t),Array.isArray(t))for(a=0,n=t.length;a<n;a+=1)lT(t[a],e,r);else for(o=Object.keys(t),a=0,n=o.length;a<n;a+=1)lT(t[o[a]],e,r)}function YK(t,e){e=e||{};var r=new x6e(e);return r.noRefs||H6e(t,r),z0(r,0,t,!0,!0)?r.dump+`\n`:\"\"}function q6e(t,e){return YK(t,Lw.extend({schema:u6e},e))}uT.exports.dump=YK;uT.exports.safeDump=q6e});var VK=_((yxt,xi)=>{\"use strict\";var RD=BK(),KK=WK();function TD(t){return function(){throw new Error(\"Function \"+t+\" is deprecated and cannot be used.\")}}xi.exports.Type=ls();xi.exports.Schema=Y0();xi.exports.FAILSAFE_SCHEMA=PD();xi.exports.JSON_SCHEMA=tT();xi.exports.CORE_SCHEMA=rT();xi.exports.DEFAULT_SAFE_SCHEMA=$d();xi.exports.DEFAULT_FULL_SCHEMA=Rw();xi.exports.load=RD.load;xi.exports.loadAll=RD.loadAll;xi.exports.safeLoad=RD.safeLoad;xi.exports.safeLoadAll=RD.safeLoadAll;xi.exports.dump=KK.dump;xi.exports.safeDump=KK.safeDump;xi.exports.YAMLException=Xd();xi.exports.MINIMAL_SCHEMA=PD();xi.exports.SAFE_SCHEMA=$d();xi.exports.DEFAULT_SCHEMA=Rw();xi.exports.scan=TD(\"scan\");xi.exports.parse=TD(\"parse\");xi.exports.compose=TD(\"compose\");xi.exports.addConstructor=TD(\"addConstructor\")});var JK=_((Ext,zK)=>{\"use strict\";var j6e=VK();zK.exports=j6e});var ZK=_((Cxt,XK)=>{\"use strict\";function G6e(t,e){function r(){this.constructor=t}r.prototype=e.prototype,t.prototype=new r}function J0(t,e,r,o){this.message=t,this.expected=e,this.found=r,this.location=o,this.name=\"SyntaxError\",typeof Error.captureStackTrace==\"function\"&&Error.captureStackTrace(this,J0)}G6e(J0,Error);J0.buildMessage=function(t,e){var r={literal:function(h){return'\"'+a(h.text)+'\"'},class:function(h){var E=\"\",I;for(I=0;I<h.parts.length;I++)E+=h.parts[I]instanceof Array?n(h.parts[I][0])+\"-\"+n(h.parts[I][1]):n(h.parts[I]);return\"[\"+(h.inverted?\"^\":\"\")+E+\"]\"},any:function(h){return\"any character\"},end:function(h){return\"end of input\"},other:function(h){return h.description}};function o(h){return h.charCodeAt(0).toString(16).toUpperCase()}function a(h){return h.replace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"').replace(/\\0/g,\"\\\\0\").replace(/\\t/g,\"\\\\t\").replace(/\\n/g,\"\\\\n\").replace(/\\r/g,\"\\\\r\").replace(/[\\x00-\\x0F]/g,function(E){return\"\\\\x0\"+o(E)}).replace(/[\\x10-\\x1F\\x7F-\\x9F]/g,function(E){return\"\\\\x\"+o(E)})}function n(h){return h.replace(/\\\\/g,\"\\\\\\\\\").replace(/\\]/g,\"\\\\]\").replace(/\\^/g,\"\\\\^\").replace(/-/g,\"\\\\-\").replace(/\\0/g,\"\\\\0\").replace(/\\t/g,\"\\\\t\").replace(/\\n/g,\"\\\\n\").replace(/\\r/g,\"\\\\r\").replace(/[\\x00-\\x0F]/g,function(E){return\"\\\\x0\"+o(E)}).replace(/[\\x10-\\x1F\\x7F-\\x9F]/g,function(E){return\"\\\\x\"+o(E)})}function u(h){return r[h.type](h)}function A(h){var E=new Array(h.length),I,v;for(I=0;I<h.length;I++)E[I]=u(h[I]);if(E.sort(),E.length>0){for(I=1,v=1;I<E.length;I++)E[I-1]!==E[I]&&(E[v]=E[I],v++);E.length=v}switch(E.length){case 1:return E[0];case 2:return E[0]+\" or \"+E[1];default:return E.slice(0,-1).join(\", \")+\", or \"+E[E.length-1]}}function p(h){return h?'\"'+a(h)+'\"':\"end of input\"}return\"Expected \"+A(t)+\" but \"+p(e)+\" found.\"};function Y6e(t,e){e=e!==void 0?e:{};var r={},o={Start:gu},a=gu,n=function(ee){return[].concat(...ee)},u=\"-\",A=Qn(\"-\",!1),p=function(ee){return ee},h=function(ee){return Object.assign({},...ee)},E=\"#\",I=Qn(\"#\",!1),v=gc(),x=function(){return{}},C=\":\",R=Qn(\":\",!1),L=function(ee,ye){return{[ee]:ye}},U=\",\",z=Qn(\",\",!1),te=function(ee,ye){return ye},ae=function(ee,ye,Le){return Object.assign({},...[ee].concat(ye).map(ft=>({[ft]:Le})))},le=function(ee){return ee},ce=function(ee){return ee},Ce=aa(\"correct indentation\"),de=\" \",Be=Qn(\" \",!1),Ee=function(ee){return ee.length===or*Bt},g=function(ee){return ee.length===(or+1)*Bt},me=function(){return or++,!0},we=function(){return or--,!0},Ae=function(){return DA()},ne=aa(\"pseudostring\"),Z=/^[^\\r\\n\\t ?:,\\][{}#&*!|>'\"%@`\\-]/,xe=hi([\"\\r\",`\n`,\"\t\",\" \",\"?\",\":\",\",\",\"]\",\"[\",\"{\",\"}\",\"#\",\"&\",\"*\",\"!\",\"|\",\">\",\"'\",'\"',\"%\",\"@\",\"`\",\"-\"],!0,!1),Ne=/^[^\\r\\n\\t ,\\][{}:#\"']/,ht=hi([\"\\r\",`\n`,\"\t\",\" \",\",\",\"]\",\"[\",\"{\",\"}\",\":\",\"#\",'\"',\"'\"],!0,!1),H=function(){return DA().replace(/^ *| *$/g,\"\")},rt=\"--\",Te=Qn(\"--\",!1),Fe=/^[a-zA-Z\\/0-9]/,ke=hi([[\"a\",\"z\"],[\"A\",\"Z\"],\"/\",[\"0\",\"9\"]],!1,!1),Ye=/^[^\\r\\n\\t :,]/,be=hi([\"\\r\",`\n`,\"\t\",\" \",\":\",\",\"],!0,!1),et=\"null\",Ue=Qn(\"null\",!1),S=function(){return null},w=\"true\",b=Qn(\"true\",!1),y=function(){return!0},F=\"false\",J=Qn(\"false\",!1),X=function(){return!1},$=aa(\"string\"),ie='\"',Se=Qn('\"',!1),Re=function(){return\"\"},at=function(ee){return ee},dt=function(ee){return ee.join(\"\")},jt=/^[^\"\\\\\\0-\\x1F\\x7F]/,tr=hi(['\"',\"\\\\\",[\"\\0\",\"\u001f\"],\"\\x7F\"],!0,!1),bt='\\\\\"',ln=Qn('\\\\\"',!1),kr=function(){return'\"'},mr=\"\\\\\\\\\",Sr=Qn(\"\\\\\\\\\",!1),Kr=function(){return\"\\\\\"},Kn=\"\\\\/\",Ms=Qn(\"\\\\/\",!1),Ri=function(){return\"/\"},gs=\"\\\\b\",io=Qn(\"\\\\b\",!1),Pi=function(){return\"\\b\"},Os=\"\\\\f\",so=Qn(\"\\\\f\",!1),uc=function(){return\"\\f\"},Au=\"\\\\n\",sp=Qn(\"\\\\n\",!1),op=function(){return`\n`},Us=\"\\\\r\",Dn=Qn(\"\\\\r\",!1),oo=function(){return\"\\r\"},_s=\"\\\\t\",ml=Qn(\"\\\\t\",!1),yl=function(){return\"\t\"},ao=\"\\\\u\",Vn=Qn(\"\\\\u\",!1),Mn=function(ee,ye,Le,ft){return String.fromCharCode(parseInt(`0x${ee}${ye}${Le}${ft}`))},Ti=/^[0-9a-fA-F]/,On=hi([[\"0\",\"9\"],[\"a\",\"f\"],[\"A\",\"F\"]],!1,!1),_i=aa(\"blank space\"),ir=/^[ \\t]/,Me=hi([\" \",\"\t\"],!1,!1),ii=aa(\"white space\"),Ha=/^[ \\t\\n\\r]/,hr=hi([\" \",\"\t\",`\n`,\"\\r\"],!1,!1),Ac=`\\r\n`,fu=Qn(`\\r\n`,!1),fc=`\n`,El=Qn(`\n`,!1),vA=\"\\r\",pu=Qn(\"\\r\",!1),Ie=0,Tt=0,pc=[{line:1,column:1}],Hi=0,hu=[],Yt=0,Cl;if(\"startRule\"in e){if(!(e.startRule in o))throw new Error(`Can't start parsing from rule \"`+e.startRule+'\".');a=o[e.startRule]}function DA(){return t.substring(Tt,Ie)}function ap(){return _o(Tt,Ie)}function hc(ee,ye){throw ye=ye!==void 0?ye:_o(Tt,Ie),dc([aa(ee)],t.substring(Tt,Ie),ye)}function PA(ee,ye){throw ye=ye!==void 0?ye:_o(Tt,Ie),lo(ee,ye)}function Qn(ee,ye){return{type:\"literal\",text:ee,ignoreCase:ye}}function hi(ee,ye,Le){return{type:\"class\",parts:ee,inverted:ye,ignoreCase:Le}}function gc(){return{type:\"any\"}}function bA(){return{type:\"end\"}}function aa(ee){return{type:\"other\",description:ee}}function Ni(ee){var ye=pc[ee],Le;if(ye)return ye;for(Le=ee-1;!pc[Le];)Le--;for(ye=pc[Le],ye={line:ye.line,column:ye.column};Le<ee;)t.charCodeAt(Le)===10?(ye.line++,ye.column=1):ye.column++,Le++;return pc[ee]=ye,ye}function _o(ee,ye){var Le=Ni(ee),ft=Ni(ye);return{start:{offset:ee,line:Le.line,column:Le.column},end:{offset:ye,line:ft.line,column:ft.column}}}function Xe(ee){Ie<Hi||(Ie>Hi&&(Hi=Ie,hu=[]),hu.push(ee))}function lo(ee,ye){return new J0(ee,null,null,ye)}function dc(ee,ye,Le){return new J0(J0.buildMessage(ee,ye),ee,ye,Le)}function gu(){var ee;return ee=SA(),ee}function qi(){var ee,ye,Le;for(ee=Ie,ye=[],Le=du();Le!==r;)ye.push(Le),Le=du();return ye!==r&&(Tt=ee,ye=n(ye)),ee=ye,ee}function du(){var ee,ye,Le,ft,pt;return ee=Ie,ye=ds(),ye!==r?(t.charCodeAt(Ie)===45?(Le=u,Ie++):(Le=r,Yt===0&&Xe(A)),Le!==r?(ft=Pn(),ft!==r?(pt=mc(),pt!==r?(Tt=ee,ye=p(pt),ee=ye):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r),ee}function SA(){var ee,ye,Le;for(ee=Ie,ye=[],Le=qa();Le!==r;)ye.push(Le),Le=qa();return ye!==r&&(Tt=ee,ye=h(ye)),ee=ye,ee}function qa(){var ee,ye,Le,ft,pt,Nt,rr,$r,ji;if(ee=Ie,ye=Pn(),ye===r&&(ye=null),ye!==r){if(Le=Ie,t.charCodeAt(Ie)===35?(ft=E,Ie++):(ft=r,Yt===0&&Xe(I)),ft!==r){if(pt=[],Nt=Ie,rr=Ie,Yt++,$r=tt(),Yt--,$r===r?rr=void 0:(Ie=rr,rr=r),rr!==r?(t.length>Ie?($r=t.charAt(Ie),Ie++):($r=r,Yt===0&&Xe(v)),$r!==r?(rr=[rr,$r],Nt=rr):(Ie=Nt,Nt=r)):(Ie=Nt,Nt=r),Nt!==r)for(;Nt!==r;)pt.push(Nt),Nt=Ie,rr=Ie,Yt++,$r=tt(),Yt--,$r===r?rr=void 0:(Ie=rr,rr=r),rr!==r?(t.length>Ie?($r=t.charAt(Ie),Ie++):($r=r,Yt===0&&Xe(v)),$r!==r?(rr=[rr,$r],Nt=rr):(Ie=Nt,Nt=r)):(Ie=Nt,Nt=r);else pt=r;pt!==r?(ft=[ft,pt],Le=ft):(Ie=Le,Le=r)}else Ie=Le,Le=r;if(Le===r&&(Le=null),Le!==r){if(ft=[],pt=We(),pt!==r)for(;pt!==r;)ft.push(pt),pt=We();else ft=r;ft!==r?(Tt=ee,ye=x(),ee=ye):(Ie=ee,ee=r)}else Ie=ee,ee=r}else Ie=ee,ee=r;if(ee===r&&(ee=Ie,ye=ds(),ye!==r?(Le=la(),Le!==r?(ft=Pn(),ft===r&&(ft=null),ft!==r?(t.charCodeAt(Ie)===58?(pt=C,Ie++):(pt=r,Yt===0&&Xe(R)),pt!==r?(Nt=Pn(),Nt===r&&(Nt=null),Nt!==r?(rr=mc(),rr!==r?(Tt=ee,ye=L(Le,rr),ee=ye):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r),ee===r&&(ee=Ie,ye=ds(),ye!==r?(Le=co(),Le!==r?(ft=Pn(),ft===r&&(ft=null),ft!==r?(t.charCodeAt(Ie)===58?(pt=C,Ie++):(pt=r,Yt===0&&Xe(R)),pt!==r?(Nt=Pn(),Nt===r&&(Nt=null),Nt!==r?(rr=mc(),rr!==r?(Tt=ee,ye=L(Le,rr),ee=ye):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r),ee===r))){if(ee=Ie,ye=ds(),ye!==r)if(Le=co(),Le!==r)if(ft=Pn(),ft!==r)if(pt=ca(),pt!==r){if(Nt=[],rr=We(),rr!==r)for(;rr!==r;)Nt.push(rr),rr=We();else Nt=r;Nt!==r?(Tt=ee,ye=L(Le,pt),ee=ye):(Ie=ee,ee=r)}else Ie=ee,ee=r;else Ie=ee,ee=r;else Ie=ee,ee=r;else Ie=ee,ee=r;if(ee===r)if(ee=Ie,ye=ds(),ye!==r)if(Le=co(),Le!==r){if(ft=[],pt=Ie,Nt=Pn(),Nt===r&&(Nt=null),Nt!==r?(t.charCodeAt(Ie)===44?(rr=U,Ie++):(rr=r,Yt===0&&Xe(z)),rr!==r?($r=Pn(),$r===r&&($r=null),$r!==r?(ji=co(),ji!==r?(Tt=pt,Nt=te(Le,ji),pt=Nt):(Ie=pt,pt=r)):(Ie=pt,pt=r)):(Ie=pt,pt=r)):(Ie=pt,pt=r),pt!==r)for(;pt!==r;)ft.push(pt),pt=Ie,Nt=Pn(),Nt===r&&(Nt=null),Nt!==r?(t.charCodeAt(Ie)===44?(rr=U,Ie++):(rr=r,Yt===0&&Xe(z)),rr!==r?($r=Pn(),$r===r&&($r=null),$r!==r?(ji=co(),ji!==r?(Tt=pt,Nt=te(Le,ji),pt=Nt):(Ie=pt,pt=r)):(Ie=pt,pt=r)):(Ie=pt,pt=r)):(Ie=pt,pt=r);else ft=r;ft!==r?(pt=Pn(),pt===r&&(pt=null),pt!==r?(t.charCodeAt(Ie)===58?(Nt=C,Ie++):(Nt=r,Yt===0&&Xe(R)),Nt!==r?(rr=Pn(),rr===r&&(rr=null),rr!==r?($r=mc(),$r!==r?(Tt=ee,ye=ae(Le,ft,$r),ee=ye):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)}else Ie=ee,ee=r;else Ie=ee,ee=r}return ee}function mc(){var ee,ye,Le,ft,pt,Nt,rr;if(ee=Ie,ye=Ie,Yt++,Le=Ie,ft=tt(),ft!==r?(pt=Ht(),pt!==r?(t.charCodeAt(Ie)===45?(Nt=u,Ie++):(Nt=r,Yt===0&&Xe(A)),Nt!==r?(rr=Pn(),rr!==r?(ft=[ft,pt,Nt,rr],Le=ft):(Ie=Le,Le=r)):(Ie=Le,Le=r)):(Ie=Le,Le=r)):(Ie=Le,Le=r),Yt--,Le!==r?(Ie=ye,ye=void 0):ye=r,ye!==r?(Le=We(),Le!==r?(ft=Fn(),ft!==r?(pt=qi(),pt!==r?(Nt=Ei(),Nt!==r?(Tt=ee,ye=le(pt),ee=ye):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r),ee===r&&(ee=Ie,ye=tt(),ye!==r?(Le=Fn(),Le!==r?(ft=SA(),ft!==r?(pt=Ei(),pt!==r?(Tt=ee,ye=le(ft),ee=ye):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r),ee===r))if(ee=Ie,ye=Hs(),ye!==r){if(Le=[],ft=We(),ft!==r)for(;ft!==r;)Le.push(ft),ft=We();else Le=r;Le!==r?(Tt=ee,ye=ce(ye),ee=ye):(Ie=ee,ee=r)}else Ie=ee,ee=r;return ee}function ds(){var ee,ye,Le;for(Yt++,ee=Ie,ye=[],t.charCodeAt(Ie)===32?(Le=de,Ie++):(Le=r,Yt===0&&Xe(Be));Le!==r;)ye.push(Le),t.charCodeAt(Ie)===32?(Le=de,Ie++):(Le=r,Yt===0&&Xe(Be));return ye!==r?(Tt=Ie,Le=Ee(ye),Le?Le=void 0:Le=r,Le!==r?(ye=[ye,Le],ee=ye):(Ie=ee,ee=r)):(Ie=ee,ee=r),Yt--,ee===r&&(ye=r,Yt===0&&Xe(Ce)),ee}function Ht(){var ee,ye,Le;for(ee=Ie,ye=[],t.charCodeAt(Ie)===32?(Le=de,Ie++):(Le=r,Yt===0&&Xe(Be));Le!==r;)ye.push(Le),t.charCodeAt(Ie)===32?(Le=de,Ie++):(Le=r,Yt===0&&Xe(Be));return ye!==r?(Tt=Ie,Le=g(ye),Le?Le=void 0:Le=r,Le!==r?(ye=[ye,Le],ee=ye):(Ie=ee,ee=r)):(Ie=ee,ee=r),ee}function Fn(){var ee;return Tt=Ie,ee=me(),ee?ee=void 0:ee=r,ee}function Ei(){var ee;return Tt=Ie,ee=we(),ee?ee=void 0:ee=r,ee}function la(){var ee;return ee=ys(),ee===r&&(ee=ua()),ee}function co(){var ee,ye,Le;if(ee=ys(),ee===r){if(ee=Ie,ye=[],Le=Ho(),Le!==r)for(;Le!==r;)ye.push(Le),Le=Ho();else ye=r;ye!==r&&(Tt=ee,ye=Ae()),ee=ye}return ee}function Hs(){var ee;return ee=Ci(),ee===r&&(ee=ms(),ee===r&&(ee=ys(),ee===r&&(ee=ua()))),ee}function ca(){var ee;return ee=Ci(),ee===r&&(ee=ys(),ee===r&&(ee=Ho())),ee}function ua(){var ee,ye,Le,ft,pt,Nt;if(Yt++,ee=Ie,Z.test(t.charAt(Ie))?(ye=t.charAt(Ie),Ie++):(ye=r,Yt===0&&Xe(xe)),ye!==r){for(Le=[],ft=Ie,pt=Pn(),pt===r&&(pt=null),pt!==r?(Ne.test(t.charAt(Ie))?(Nt=t.charAt(Ie),Ie++):(Nt=r,Yt===0&&Xe(ht)),Nt!==r?(pt=[pt,Nt],ft=pt):(Ie=ft,ft=r)):(Ie=ft,ft=r);ft!==r;)Le.push(ft),ft=Ie,pt=Pn(),pt===r&&(pt=null),pt!==r?(Ne.test(t.charAt(Ie))?(Nt=t.charAt(Ie),Ie++):(Nt=r,Yt===0&&Xe(ht)),Nt!==r?(pt=[pt,Nt],ft=pt):(Ie=ft,ft=r)):(Ie=ft,ft=r);Le!==r?(Tt=ee,ye=H(),ee=ye):(Ie=ee,ee=r)}else Ie=ee,ee=r;return Yt--,ee===r&&(ye=r,Yt===0&&Xe(ne)),ee}function Ho(){var ee,ye,Le,ft,pt;if(ee=Ie,t.substr(Ie,2)===rt?(ye=rt,Ie+=2):(ye=r,Yt===0&&Xe(Te)),ye===r&&(ye=null),ye!==r)if(Fe.test(t.charAt(Ie))?(Le=t.charAt(Ie),Ie++):(Le=r,Yt===0&&Xe(ke)),Le!==r){for(ft=[],Ye.test(t.charAt(Ie))?(pt=t.charAt(Ie),Ie++):(pt=r,Yt===0&&Xe(be));pt!==r;)ft.push(pt),Ye.test(t.charAt(Ie))?(pt=t.charAt(Ie),Ie++):(pt=r,Yt===0&&Xe(be));ft!==r?(Tt=ee,ye=H(),ee=ye):(Ie=ee,ee=r)}else Ie=ee,ee=r;else Ie=ee,ee=r;return ee}function Ci(){var ee,ye;return ee=Ie,t.substr(Ie,4)===et?(ye=et,Ie+=4):(ye=r,Yt===0&&Xe(Ue)),ye!==r&&(Tt=ee,ye=S()),ee=ye,ee}function ms(){var ee,ye;return ee=Ie,t.substr(Ie,4)===w?(ye=w,Ie+=4):(ye=r,Yt===0&&Xe(b)),ye!==r&&(Tt=ee,ye=y()),ee=ye,ee===r&&(ee=Ie,t.substr(Ie,5)===F?(ye=F,Ie+=5):(ye=r,Yt===0&&Xe(J)),ye!==r&&(Tt=ee,ye=X()),ee=ye),ee}function ys(){var ee,ye,Le,ft;return Yt++,ee=Ie,t.charCodeAt(Ie)===34?(ye=ie,Ie++):(ye=r,Yt===0&&Xe(Se)),ye!==r?(t.charCodeAt(Ie)===34?(Le=ie,Ie++):(Le=r,Yt===0&&Xe(Se)),Le!==r?(Tt=ee,ye=Re(),ee=ye):(Ie=ee,ee=r)):(Ie=ee,ee=r),ee===r&&(ee=Ie,t.charCodeAt(Ie)===34?(ye=ie,Ie++):(ye=r,Yt===0&&Xe(Se)),ye!==r?(Le=Es(),Le!==r?(t.charCodeAt(Ie)===34?(ft=ie,Ie++):(ft=r,Yt===0&&Xe(Se)),ft!==r?(Tt=ee,ye=at(Le),ee=ye):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)),Yt--,ee===r&&(ye=r,Yt===0&&Xe($)),ee}function Es(){var ee,ye,Le;if(ee=Ie,ye=[],Le=qs(),Le!==r)for(;Le!==r;)ye.push(Le),Le=qs();else ye=r;return ye!==r&&(Tt=ee,ye=dt(ye)),ee=ye,ee}function qs(){var ee,ye,Le,ft,pt,Nt;return jt.test(t.charAt(Ie))?(ee=t.charAt(Ie),Ie++):(ee=r,Yt===0&&Xe(tr)),ee===r&&(ee=Ie,t.substr(Ie,2)===bt?(ye=bt,Ie+=2):(ye=r,Yt===0&&Xe(ln)),ye!==r&&(Tt=ee,ye=kr()),ee=ye,ee===r&&(ee=Ie,t.substr(Ie,2)===mr?(ye=mr,Ie+=2):(ye=r,Yt===0&&Xe(Sr)),ye!==r&&(Tt=ee,ye=Kr()),ee=ye,ee===r&&(ee=Ie,t.substr(Ie,2)===Kn?(ye=Kn,Ie+=2):(ye=r,Yt===0&&Xe(Ms)),ye!==r&&(Tt=ee,ye=Ri()),ee=ye,ee===r&&(ee=Ie,t.substr(Ie,2)===gs?(ye=gs,Ie+=2):(ye=r,Yt===0&&Xe(io)),ye!==r&&(Tt=ee,ye=Pi()),ee=ye,ee===r&&(ee=Ie,t.substr(Ie,2)===Os?(ye=Os,Ie+=2):(ye=r,Yt===0&&Xe(so)),ye!==r&&(Tt=ee,ye=uc()),ee=ye,ee===r&&(ee=Ie,t.substr(Ie,2)===Au?(ye=Au,Ie+=2):(ye=r,Yt===0&&Xe(sp)),ye!==r&&(Tt=ee,ye=op()),ee=ye,ee===r&&(ee=Ie,t.substr(Ie,2)===Us?(ye=Us,Ie+=2):(ye=r,Yt===0&&Xe(Dn)),ye!==r&&(Tt=ee,ye=oo()),ee=ye,ee===r&&(ee=Ie,t.substr(Ie,2)===_s?(ye=_s,Ie+=2):(ye=r,Yt===0&&Xe(ml)),ye!==r&&(Tt=ee,ye=yl()),ee=ye,ee===r&&(ee=Ie,t.substr(Ie,2)===ao?(ye=ao,Ie+=2):(ye=r,Yt===0&&Xe(Vn)),ye!==r?(Le=Un(),Le!==r?(ft=Un(),ft!==r?(pt=Un(),pt!==r?(Nt=Un(),Nt!==r?(Tt=ee,ye=Mn(Le,ft,pt,Nt),ee=ye):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)):(Ie=ee,ee=r)))))))))),ee}function Un(){var ee;return Ti.test(t.charAt(Ie))?(ee=t.charAt(Ie),Ie++):(ee=r,Yt===0&&Xe(On)),ee}function Pn(){var ee,ye;if(Yt++,ee=[],ir.test(t.charAt(Ie))?(ye=t.charAt(Ie),Ie++):(ye=r,Yt===0&&Xe(Me)),ye!==r)for(;ye!==r;)ee.push(ye),ir.test(t.charAt(Ie))?(ye=t.charAt(Ie),Ie++):(ye=r,Yt===0&&Xe(Me));else ee=r;return Yt--,ee===r&&(ye=r,Yt===0&&Xe(_i)),ee}function Cs(){var ee,ye;if(Yt++,ee=[],Ha.test(t.charAt(Ie))?(ye=t.charAt(Ie),Ie++):(ye=r,Yt===0&&Xe(hr)),ye!==r)for(;ye!==r;)ee.push(ye),Ha.test(t.charAt(Ie))?(ye=t.charAt(Ie),Ie++):(ye=r,Yt===0&&Xe(hr));else ee=r;return Yt--,ee===r&&(ye=r,Yt===0&&Xe(ii)),ee}function We(){var ee,ye,Le,ft,pt,Nt;if(ee=Ie,ye=tt(),ye!==r){for(Le=[],ft=Ie,pt=Pn(),pt===r&&(pt=null),pt!==r?(Nt=tt(),Nt!==r?(pt=[pt,Nt],ft=pt):(Ie=ft,ft=r)):(Ie=ft,ft=r);ft!==r;)Le.push(ft),ft=Ie,pt=Pn(),pt===r&&(pt=null),pt!==r?(Nt=tt(),Nt!==r?(pt=[pt,Nt],ft=pt):(Ie=ft,ft=r)):(Ie=ft,ft=r);Le!==r?(ye=[ye,Le],ee=ye):(Ie=ee,ee=r)}else Ie=ee,ee=r;return ee}function tt(){var ee;return t.substr(Ie,2)===Ac?(ee=Ac,Ie+=2):(ee=r,Yt===0&&Xe(fu)),ee===r&&(t.charCodeAt(Ie)===10?(ee=fc,Ie++):(ee=r,Yt===0&&Xe(El)),ee===r&&(t.charCodeAt(Ie)===13?(ee=vA,Ie++):(ee=r,Yt===0&&Xe(pu)))),ee}let Bt=2,or=0;if(Cl=a(),Cl!==r&&Ie===t.length)return Cl;throw Cl!==r&&Ie<t.length&&Xe(bA()),dc(hu,Hi<t.length?t.charAt(Hi):null,Hi<t.length?_o(Hi,Hi+1):_o(Hi,Hi))}XK.exports={SyntaxError:J0,parse:Y6e}});function eV(t){return t.match(W6e)?t:JSON.stringify(t)}function rV(t){return typeof t>\"u\"?!0:typeof t==\"object\"&&t!==null&&!Array.isArray(t)?Object.keys(t).every(e=>rV(t[e])):!1}function AT(t,e,r){if(t===null)return`null\n`;if(typeof t==\"number\"||typeof t==\"boolean\")return`${t.toString()}\n`;if(typeof t==\"string\")return`${eV(t)}\n`;if(Array.isArray(t)){if(t.length===0)return`[]\n`;let o=\"  \".repeat(e);return`\n${t.map(n=>`${o}- ${AT(n,e+1,!1)}`).join(\"\")}`}if(typeof t==\"object\"&&t){let[o,a]=t instanceof ND?[t.data,!1]:[t,!0],n=\"  \".repeat(e),u=Object.keys(o);a&&u.sort((p,h)=>{let E=$K.indexOf(p),I=$K.indexOf(h);return E===-1&&I===-1?p<h?-1:p>h?1:0:E!==-1&&I===-1?-1:E===-1&&I!==-1?1:E-I});let A=u.filter(p=>!rV(o[p])).map((p,h)=>{let E=o[p],I=eV(p),v=AT(E,e+1,!0),x=h>0||r?n:\"\",C=I.length>1024?`? ${I}\n${x}:`:`${I}:`,R=v.startsWith(`\n`)?v:` ${v}`;return`${x}${C}${R}`}).join(e===0?`\n`:\"\")||`\n`;return r?`\n${A}`:`${A}`}throw new Error(`Unsupported value type (${t})`)}function Da(t){try{let e=AT(t,0,!1);return e!==`\n`?e:\"\"}catch(e){throw e.location&&(e.message=e.message.replace(/(\\.)?$/,` (line ${e.location.start.line}, column ${e.location.start.column})$1`)),e}}function K6e(t){return t.endsWith(`\n`)||(t+=`\n`),(0,tV.parse)(t)}function z6e(t){if(V6e.test(t))return K6e(t);let e=(0,LD.safeLoad)(t,{schema:LD.FAILSAFE_SCHEMA,json:!0});if(e==null)return{};if(typeof e!=\"object\")throw new Error(`Expected an indexed object, got a ${typeof e} instead. Does your file follow Yaml's rules?`);if(Array.isArray(e))throw new Error(\"Expected an indexed object, got an array instead. Does your file follow Yaml's rules?\");return e}function Ki(t){return z6e(t)}var LD,tV,W6e,$K,ND,V6e,nV=Et(()=>{LD=Ze(JK()),tV=Ze(ZK()),W6e=/^(?![-?:,\\][{}#&*!|>'\"%@` \\t\\r\\n]).([ \\t]*(?![,\\][{}:# \\t\\r\\n]).)*$/,$K=[\"__metadata\",\"version\",\"resolution\",\"dependencies\",\"peerDependencies\",\"dependenciesMeta\",\"peerDependenciesMeta\",\"binaries\"],ND=class{constructor(e){this.data=e}};Da.PreserveOrdering=ND;V6e=/^(#.*(\\r?\\n))*?#\\s+yarn\\s+lockfile\\s+v1\\r?\\n/i});var Ow={};Vt(Ow,{parseResolution:()=>BD,parseShell:()=>CD,parseSyml:()=>Ki,stringifyArgument:()=>XR,stringifyArgumentSegment:()=>ZR,stringifyArithmeticExpression:()=>ID,stringifyCommand:()=>JR,stringifyCommandChain:()=>Jd,stringifyCommandChainThen:()=>zR,stringifyCommandLine:()=>wD,stringifyCommandLineThen:()=>VR,stringifyEnvSegment:()=>ED,stringifyRedirectArgument:()=>Qw,stringifyResolution:()=>vD,stringifyShell:()=>zd,stringifyShellLine:()=>zd,stringifySyml:()=>Da,stringifyValueArgument:()=>H0});var Nl=Et(()=>{rW();oW();nV()});var sV=_((Dxt,fT)=>{\"use strict\";var J6e=t=>{let e=!1,r=!1,o=!1;for(let a=0;a<t.length;a++){let n=t[a];e&&/[a-zA-Z]/.test(n)&&n.toUpperCase()===n?(t=t.slice(0,a)+\"-\"+t.slice(a),e=!1,o=r,r=!0,a++):r&&o&&/[a-zA-Z]/.test(n)&&n.toLowerCase()===n?(t=t.slice(0,a-1)+\"-\"+t.slice(a-1),o=r,r=!1,e=!0):(e=n.toLowerCase()===n&&n.toUpperCase()!==n,o=r,r=n.toUpperCase()===n&&n.toLowerCase()!==n)}return t},iV=(t,e)=>{if(!(typeof t==\"string\"||Array.isArray(t)))throw new TypeError(\"Expected the input to be `string | string[]`\");e=Object.assign({pascalCase:!1},e);let r=a=>e.pascalCase?a.charAt(0).toUpperCase()+a.slice(1):a;return Array.isArray(t)?t=t.map(a=>a.trim()).filter(a=>a.length).join(\"-\"):t=t.trim(),t.length===0?\"\":t.length===1?e.pascalCase?t.toUpperCase():t.toLowerCase():(t!==t.toLowerCase()&&(t=J6e(t)),t=t.replace(/^[_.\\- ]+/,\"\").toLowerCase().replace(/[_.\\- ]+(\\w|$)/g,(a,n)=>n.toUpperCase()).replace(/\\d+(\\w|$)/g,a=>a.toUpperCase()),r(t))};fT.exports=iV;fT.exports.default=iV});var oV=_((Pxt,X6e)=>{X6e.exports=[{name:\"Agola CI\",constant:\"AGOLA\",env:\"AGOLA_GIT_REF\",pr:\"AGOLA_PULL_REQUEST_ID\"},{name:\"Appcircle\",constant:\"APPCIRCLE\",env:\"AC_APPCIRCLE\"},{name:\"AppVeyor\",constant:\"APPVEYOR\",env:\"APPVEYOR\",pr:\"APPVEYOR_PULL_REQUEST_NUMBER\"},{name:\"AWS CodeBuild\",constant:\"CODEBUILD\",env:\"CODEBUILD_BUILD_ARN\"},{name:\"Azure Pipelines\",constant:\"AZURE_PIPELINES\",env:\"TF_BUILD\",pr:{BUILD_REASON:\"PullRequest\"}},{name:\"Bamboo\",constant:\"BAMBOO\",env:\"bamboo_planKey\"},{name:\"Bitbucket Pipelines\",constant:\"BITBUCKET\",env:\"BITBUCKET_COMMIT\",pr:\"BITBUCKET_PR_ID\"},{name:\"Bitrise\",constant:\"BITRISE\",env:\"BITRISE_IO\",pr:\"BITRISE_PULL_REQUEST\"},{name:\"Buddy\",constant:\"BUDDY\",env:\"BUDDY_WORKSPACE_ID\",pr:\"BUDDY_EXECUTION_PULL_REQUEST_ID\"},{name:\"Buildkite\",constant:\"BUILDKITE\",env:\"BUILDKITE\",pr:{env:\"BUILDKITE_PULL_REQUEST\",ne:\"false\"}},{name:\"CircleCI\",constant:\"CIRCLE\",env:\"CIRCLECI\",pr:\"CIRCLE_PULL_REQUEST\"},{name:\"Cirrus CI\",constant:\"CIRRUS\",env:\"CIRRUS_CI\",pr:\"CIRRUS_PR\"},{name:\"Codefresh\",constant:\"CODEFRESH\",env:\"CF_BUILD_ID\",pr:{any:[\"CF_PULL_REQUEST_NUMBER\",\"CF_PULL_REQUEST_ID\"]}},{name:\"Codemagic\",constant:\"CODEMAGIC\",env:\"CM_BUILD_ID\",pr:\"CM_PULL_REQUEST\"},{name:\"Codeship\",constant:\"CODESHIP\",env:{CI_NAME:\"codeship\"}},{name:\"Drone\",constant:\"DRONE\",env:\"DRONE\",pr:{DRONE_BUILD_EVENT:\"pull_request\"}},{name:\"dsari\",constant:\"DSARI\",env:\"DSARI\"},{name:\"Earthly\",constant:\"EARTHLY\",env:\"EARTHLY_CI\"},{name:\"Expo Application Services\",constant:\"EAS\",env:\"EAS_BUILD\"},{name:\"Gerrit\",constant:\"GERRIT\",env:\"GERRIT_PROJECT\"},{name:\"Gitea Actions\",constant:\"GITEA_ACTIONS\",env:\"GITEA_ACTIONS\"},{name:\"GitHub Actions\",constant:\"GITHUB_ACTIONS\",env:\"GITHUB_ACTIONS\",pr:{GITHUB_EVENT_NAME:\"pull_request\"}},{name:\"GitLab CI\",constant:\"GITLAB\",env:\"GITLAB_CI\",pr:\"CI_MERGE_REQUEST_ID\"},{name:\"GoCD\",constant:\"GOCD\",env:\"GO_PIPELINE_LABEL\"},{name:\"Google Cloud Build\",constant:\"GOOGLE_CLOUD_BUILD\",env:\"BUILDER_OUTPUT\"},{name:\"Harness CI\",constant:\"HARNESS\",env:\"HARNESS_BUILD_ID\"},{name:\"Heroku\",constant:\"HEROKU\",env:{env:\"NODE\",includes:\"/app/.heroku/node/bin/node\"}},{name:\"Hudson\",constant:\"HUDSON\",env:\"HUDSON_URL\"},{name:\"Jenkins\",constant:\"JENKINS\",env:[\"JENKINS_URL\",\"BUILD_ID\"],pr:{any:[\"ghprbPullId\",\"CHANGE_ID\"]}},{name:\"LayerCI\",constant:\"LAYERCI\",env:\"LAYERCI\",pr:\"LAYERCI_PULL_REQUEST\"},{name:\"Magnum CI\",constant:\"MAGNUM\",env:\"MAGNUM\"},{name:\"Netlify CI\",constant:\"NETLIFY\",env:\"NETLIFY\",pr:{env:\"PULL_REQUEST\",ne:\"false\"}},{name:\"Nevercode\",constant:\"NEVERCODE\",env:\"NEVERCODE\",pr:{env:\"NEVERCODE_PULL_REQUEST\",ne:\"false\"}},{name:\"Prow\",constant:\"PROW\",env:\"PROW_JOB_ID\"},{name:\"ReleaseHub\",constant:\"RELEASEHUB\",env:\"RELEASE_BUILD_ID\"},{name:\"Render\",constant:\"RENDER\",env:\"RENDER\",pr:{IS_PULL_REQUEST:\"true\"}},{name:\"Sail CI\",constant:\"SAIL\",env:\"SAILCI\",pr:\"SAIL_PULL_REQUEST_NUMBER\"},{name:\"Screwdriver\",constant:\"SCREWDRIVER\",env:\"SCREWDRIVER\",pr:{env:\"SD_PULL_REQUEST\",ne:\"false\"}},{name:\"Semaphore\",constant:\"SEMAPHORE\",env:\"SEMAPHORE\",pr:\"PULL_REQUEST_NUMBER\"},{name:\"Sourcehut\",constant:\"SOURCEHUT\",env:{CI_NAME:\"sourcehut\"}},{name:\"Strider CD\",constant:\"STRIDER\",env:\"STRIDER\"},{name:\"TaskCluster\",constant:\"TASKCLUSTER\",env:[\"TASK_ID\",\"RUN_ID\"]},{name:\"TeamCity\",constant:\"TEAMCITY\",env:\"TEAMCITY_VERSION\"},{name:\"Travis CI\",constant:\"TRAVIS\",env:\"TRAVIS\",pr:{env:\"TRAVIS_PULL_REQUEST\",ne:\"false\"}},{name:\"Vela\",constant:\"VELA\",env:\"VELA\",pr:{VELA_PULL_REQUEST:\"1\"}},{name:\"Vercel\",constant:\"VERCEL\",env:{any:[\"NOW_BUILDER\",\"VERCEL\"]},pr:\"VERCEL_GIT_PULL_REQUEST_ID\"},{name:\"Visual Studio App Center\",constant:\"APPCENTER\",env:\"APPCENTER_BUILD_ID\"},{name:\"Woodpecker\",constant:\"WOODPECKER\",env:{CI:\"woodpecker\"},pr:{CI_BUILD_EVENT:\"pull_request\"}},{name:\"Xcode Cloud\",constant:\"XCODE_CLOUD\",env:\"CI_XCODE_PROJECT\",pr:\"CI_PULL_REQUEST_NUMBER\"},{name:\"Xcode Server\",constant:\"XCODE_SERVER\",env:\"XCS\"}]});var X0=_($a=>{\"use strict\";var lV=oV(),cs=process.env;Object.defineProperty($a,\"_vendors\",{value:lV.map(function(t){return t.constant})});$a.name=null;$a.isPR=null;lV.forEach(function(t){let r=(Array.isArray(t.env)?t.env:[t.env]).every(function(o){return aV(o)});if($a[t.constant]=r,!!r)switch($a.name=t.name,typeof t.pr){case\"string\":$a.isPR=!!cs[t.pr];break;case\"object\":\"env\"in t.pr?$a.isPR=t.pr.env in cs&&cs[t.pr.env]!==t.pr.ne:\"any\"in t.pr?$a.isPR=t.pr.any.some(function(o){return!!cs[o]}):$a.isPR=aV(t.pr);break;default:$a.isPR=null}});$a.isCI=!!(cs.CI!==\"false\"&&(cs.BUILD_ID||cs.BUILD_NUMBER||cs.CI||cs.CI_APP_ID||cs.CI_BUILD_ID||cs.CI_BUILD_NUMBER||cs.CI_NAME||cs.CONTINUOUS_INTEGRATION||cs.RUN_ID||$a.name));function aV(t){return typeof t==\"string\"?!!cs[t]:\"env\"in t?cs[t.env]&&cs[t.env].includes(t.includes):\"any\"in t?t.any.some(function(e){return!!cs[e]}):Object.keys(t).every(function(e){return cs[e]===t[e]})}});var Hn,un,Z0,pT,MD,cV,hT,gT,OD=Et(()=>{(function(t){t.StartOfInput=\"\\0\",t.EndOfInput=\"\u0001\",t.EndOfPartialInput=\"\u0002\"})(Hn||(Hn={}));(function(t){t[t.InitialNode=0]=\"InitialNode\",t[t.SuccessNode=1]=\"SuccessNode\",t[t.ErrorNode=2]=\"ErrorNode\",t[t.CustomNode=3]=\"CustomNode\"})(un||(un={}));Z0=-1,pT=/^(-h|--help)(?:=([0-9]+))?$/,MD=/^(--[a-z]+(?:-[a-z]+)*|-[a-zA-Z]+)$/,cV=/^-[a-zA-Z]{2,}$/,hT=/^([^=]+)=([\\s\\S]*)$/,gT=process.env.DEBUG_CLI===\"1\"});var st,im,UD,dT,_D=Et(()=>{OD();st=class extends Error{constructor(e){super(e),this.clipanion={type:\"usage\"},this.name=\"UsageError\"}},im=class extends Error{constructor(e,r){if(super(),this.input=e,this.candidates=r,this.clipanion={type:\"none\"},this.name=\"UnknownSyntaxError\",this.candidates.length===0)this.message=\"Command not found, but we're not sure what's the alternative.\";else if(this.candidates.every(o=>o.reason!==null&&o.reason===r[0].reason)){let[{reason:o}]=this.candidates;this.message=`${o}\n\n${this.candidates.map(({usage:a})=>`$ ${a}`).join(`\n`)}`}else if(this.candidates.length===1){let[{usage:o}]=this.candidates;this.message=`Command not found; did you mean:\n\n$ ${o}\n${dT(e)}`}else this.message=`Command not found; did you mean one of:\n\n${this.candidates.map(({usage:o},a)=>`${`${a}.`.padStart(4)} ${o}`).join(`\n`)}\n\n${dT(e)}`}},UD=class extends Error{constructor(e,r){super(),this.input=e,this.usages=r,this.clipanion={type:\"none\"},this.name=\"AmbiguousSyntaxError\",this.message=`Cannot find which to pick amongst the following alternatives:\n\n${this.usages.map((o,a)=>`${`${a}.`.padStart(4)} ${o}`).join(`\n`)}\n\n${dT(e)}`}},dT=t=>`While running ${t.filter(e=>e!==Hn.EndOfInput&&e!==Hn.EndOfPartialInput).map(e=>{let r=JSON.stringify(e);return e.match(/\\s/)||e.length===0||r!==`\"${e}\"`?r:e}).join(\" \")}`});function Z6e(t){let e=t.split(`\n`),r=e.filter(a=>a.match(/\\S/)),o=r.length>0?r.reduce((a,n)=>Math.min(a,n.length-n.trimStart().length),Number.MAX_VALUE):0;return e.map(a=>a.slice(o).trimRight()).join(`\n`)}function Do(t,{format:e,paragraphs:r}){return t=t.replace(/\\r\\n?/g,`\n`),t=Z6e(t),t=t.replace(/^\\n+|\\n+$/g,\"\"),t=t.replace(/^(\\s*)-([^\\n]*?)\\n+/gm,`$1-$2\n\n`),t=t.replace(/\\n(\\n)?\\n*/g,(o,a)=>a||\" \"),r&&(t=t.split(/\\n/).map(o=>{let a=o.match(/^\\s*[*-][\\t ]+(.*)/);if(!a)return o.match(/(.{1,80})(?: |$)/g).join(`\n`);let n=o.length-o.trimStart().length;return a[1].match(new RegExp(`(.{1,${78-n}})(?: |$)`,\"g\")).map((u,A)=>\" \".repeat(n)+(A===0?\"- \":\"  \")+u).join(`\n`)}).join(`\n\n`)),t=t.replace(/(`+)((?:.|[\\n])*?)\\1/g,(o,a,n)=>e.code(a+n+a)),t=t.replace(/(\\*\\*)((?:.|[\\n])*?)\\1/g,(o,a,n)=>e.bold(a+n+a)),t?`${t}\n`:\"\"}var mT,uV,AV,yT=Et(()=>{mT=Array(80).fill(\"\\u2501\");for(let t=0;t<=24;++t)mT[mT.length-t]=`\\x1B[38;5;${232+t}m\\u2501`;uV={header:t=>`\\x1B[1m\\u2501\\u2501\\u2501 ${t}${t.length<75?` ${mT.slice(t.length+5).join(\"\")}`:\":\"}\\x1B[0m`,bold:t=>`\\x1B[1m${t}\\x1B[22m`,error:t=>`\\x1B[31m\\x1B[1m${t}\\x1B[22m\\x1B[39m`,code:t=>`\\x1B[36m${t}\\x1B[39m`},AV={header:t=>t,bold:t=>t,error:t=>t,code:t=>t}});function Ko(t){return{...t,[Uw]:!0}}function Gu(t,e){return typeof t>\"u\"?[t,e]:typeof t==\"object\"&&t!==null&&!Array.isArray(t)?[void 0,t]:[t,e]}function HD(t,{mergeName:e=!1}={}){let r=t.match(/^([^:]+): (.*)$/m);if(!r)return\"validation failed\";let[,o,a]=r;return e&&(a=a[0].toLowerCase()+a.slice(1)),a=o!==\".\"||!e?`${o.replace(/^\\.(\\[|$)/,\"$1\")}: ${a}`:`: ${a}`,a}function _w(t,e){return e.length===1?new st(`${t}${HD(e[0],{mergeName:!0})}`):new st(`${t}:\n${e.map(r=>`\n- ${HD(r)}`).join(\"\")}`)}function $0(t,e,r){if(typeof r>\"u\")return e;let o=[],a=[],n=A=>{let p=e;return e=A,n.bind(null,p)};if(!r(e,{errors:o,coercions:a,coercion:n}))throw _w(`Invalid value for ${t}`,o);for(let[,A]of a)A();return e}var Uw,yf=Et(()=>{_D();Uw=Symbol(\"clipanion/isOption\")});var Vo={};Vt(Vo,{KeyRelationship:()=>Yu,TypeAssertionError:()=>Gp,applyCascade:()=>jw,as:()=>mqe,assert:()=>hqe,assertWithErrors:()=>gqe,cascade:()=>YD,fn:()=>yqe,hasAtLeastOneKey:()=>DT,hasExactLength:()=>dV,hasForbiddenKeys:()=>Mqe,hasKeyRelationship:()=>Yw,hasMaxLength:()=>Cqe,hasMinLength:()=>Eqe,hasMutuallyExclusiveKeys:()=>Oqe,hasRequiredKeys:()=>Lqe,hasUniqueItems:()=>wqe,isArray:()=>qD,isAtLeast:()=>BT,isAtMost:()=>vqe,isBase64:()=>Fqe,isBoolean:()=>oqe,isDate:()=>lqe,isDict:()=>Aqe,isEnum:()=>Js,isHexColor:()=>Qqe,isISO8601:()=>kqe,isInExclusiveRange:()=>Pqe,isInInclusiveRange:()=>Dqe,isInstanceOf:()=>pqe,isInteger:()=>vT,isJSON:()=>Rqe,isLiteral:()=>pV,isLowerCase:()=>bqe,isMap:()=>uqe,isNegative:()=>Iqe,isNullable:()=>Nqe,isNumber:()=>wT,isObject:()=>hV,isOneOf:()=>IT,isOptional:()=>Tqe,isPartial:()=>fqe,isPayload:()=>aqe,isPositive:()=>Bqe,isRecord:()=>GD,isSet:()=>cqe,isString:()=>om,isTuple:()=>jD,isUUID4:()=>xqe,isUnknown:()=>CT,isUpperCase:()=>Sqe,makeTrait:()=>gV,makeValidator:()=>Hr,matchesRegExp:()=>qw,softAssert:()=>dqe});function qn(t){return t===null?\"null\":t===void 0?\"undefined\":t===\"\"?\"an empty string\":typeof t==\"symbol\"?`<${t.toString()}>`:Array.isArray(t)?\"an array\":JSON.stringify(t)}function sm(t,e){if(t.length===0)return\"nothing\";if(t.length===1)return qn(t[0]);let r=t.slice(0,-1),o=t[t.length-1],a=t.length>2?`, ${e} `:` ${e} `;return`${r.map(n=>qn(n)).join(\", \")}${a}${qn(o)}`}function jp(t,e){var r,o,a;return typeof e==\"number\"?`${(r=t?.p)!==null&&r!==void 0?r:\".\"}[${e}]`:$6e.test(e)?`${(o=t?.p)!==null&&o!==void 0?o:\"\"}.${e}`:`${(a=t?.p)!==null&&a!==void 0?a:\".\"}[${JSON.stringify(e)}]`}function ET(t,e,r){return t===1?e:r}function pr({errors:t,p:e}={},r){return t?.push(`${e??\".\"}: ${r}`),!1}function iqe(t,e){return r=>{t[e]=r}}function Wu(t,e){return r=>{let o=t[e];return t[e]=r,Wu(t,e).bind(null,o)}}function Hw(t,e,r){let o=()=>(t(r()),a),a=()=>(t(e),o);return o}function CT(){return Hr({test:(t,e)=>!0})}function pV(t){return Hr({test:(e,r)=>e!==t?pr(r,`Expected ${qn(t)} (got ${qn(e)})`):!0})}function om(){return Hr({test:(t,e)=>typeof t!=\"string\"?pr(e,`Expected a string (got ${qn(t)})`):!0})}function Js(t){let e=Array.isArray(t)?t:Object.values(t),r=e.every(a=>typeof a==\"string\"||typeof a==\"number\"),o=new Set(e);return o.size===1?pV([...o][0]):Hr({test:(a,n)=>o.has(a)?!0:r?pr(n,`Expected one of ${sm(e,\"or\")} (got ${qn(a)})`):pr(n,`Expected a valid enumeration value (got ${qn(a)})`)})}function oqe(){return Hr({test:(t,e)=>{var r;if(typeof t!=\"boolean\"){if(typeof e?.coercions<\"u\"){if(typeof e?.coercion>\"u\")return pr(e,\"Unbound coercion result\");let o=sqe.get(t);if(typeof o<\"u\")return e.coercions.push([(r=e.p)!==null&&r!==void 0?r:\".\",e.coercion.bind(null,o)]),!0}return pr(e,`Expected a boolean (got ${qn(t)})`)}return!0}})}function wT(){return Hr({test:(t,e)=>{var r;if(typeof t!=\"number\"){if(typeof e?.coercions<\"u\"){if(typeof e?.coercion>\"u\")return pr(e,\"Unbound coercion result\");let o;if(typeof t==\"string\"){let a;try{a=JSON.parse(t)}catch{}if(typeof a==\"number\")if(JSON.stringify(a)===t)o=a;else return pr(e,`Received a number that can't be safely represented by the runtime (${t})`)}if(typeof o<\"u\")return e.coercions.push([(r=e.p)!==null&&r!==void 0?r:\".\",e.coercion.bind(null,o)]),!0}return pr(e,`Expected a number (got ${qn(t)})`)}return!0}})}function aqe(t){return Hr({test:(e,r)=>{var o;if(typeof r?.coercions>\"u\")return pr(r,\"The isPayload predicate can only be used with coercion enabled\");if(typeof r.coercion>\"u\")return pr(r,\"Unbound coercion result\");if(typeof e!=\"string\")return pr(r,`Expected a string (got ${qn(e)})`);let a;try{a=JSON.parse(e)}catch{return pr(r,`Expected a JSON string (got ${qn(e)})`)}let n={value:a};return t(a,Object.assign(Object.assign({},r),{coercion:Wu(n,\"value\")}))?(r.coercions.push([(o=r.p)!==null&&o!==void 0?o:\".\",r.coercion.bind(null,n.value)]),!0):!1}})}function lqe(){return Hr({test:(t,e)=>{var r;if(!(t instanceof Date)){if(typeof e?.coercions<\"u\"){if(typeof e?.coercion>\"u\")return pr(e,\"Unbound coercion result\");let o;if(typeof t==\"string\"&&fV.test(t))o=new Date(t);else{let a;if(typeof t==\"string\"){let n;try{n=JSON.parse(t)}catch{}typeof n==\"number\"&&(a=n)}else typeof t==\"number\"&&(a=t);if(typeof a<\"u\")if(Number.isSafeInteger(a)||!Number.isSafeInteger(a*1e3))o=new Date(a*1e3);else return pr(e,`Received a timestamp that can't be safely represented by the runtime (${t})`)}if(typeof o<\"u\")return e.coercions.push([(r=e.p)!==null&&r!==void 0?r:\".\",e.coercion.bind(null,o)]),!0}return pr(e,`Expected a date (got ${qn(t)})`)}return!0}})}function qD(t,{delimiter:e}={}){return Hr({test:(r,o)=>{var a;let n=r;if(typeof r==\"string\"&&typeof e<\"u\"&&typeof o?.coercions<\"u\"){if(typeof o?.coercion>\"u\")return pr(o,\"Unbound coercion result\");r=r.split(e)}if(!Array.isArray(r))return pr(o,`Expected an array (got ${qn(r)})`);let u=!0;for(let A=0,p=r.length;A<p&&(u=t(r[A],Object.assign(Object.assign({},o),{p:jp(o,A),coercion:Wu(r,A)}))&&u,!(!u&&o?.errors==null));++A);return r!==n&&o.coercions.push([(a=o.p)!==null&&a!==void 0?a:\".\",o.coercion.bind(null,r)]),u}})}function cqe(t,{delimiter:e}={}){let r=qD(t,{delimiter:e});return Hr({test:(o,a)=>{var n,u;if(Object.getPrototypeOf(o).toString()===\"[object Set]\")if(typeof a?.coercions<\"u\"){if(typeof a?.coercion>\"u\")return pr(a,\"Unbound coercion result\");let A=[...o],p=[...o];if(!r(p,Object.assign(Object.assign({},a),{coercion:void 0})))return!1;let h=()=>p.some((E,I)=>E!==A[I])?new Set(p):o;return a.coercions.push([(n=a.p)!==null&&n!==void 0?n:\".\",Hw(a.coercion,o,h)]),!0}else{let A=!0;for(let p of o)if(A=t(p,Object.assign({},a))&&A,!A&&a?.errors==null)break;return A}if(typeof a?.coercions<\"u\"){if(typeof a?.coercion>\"u\")return pr(a,\"Unbound coercion result\");let A={value:o};return r(o,Object.assign(Object.assign({},a),{coercion:Wu(A,\"value\")}))?(a.coercions.push([(u=a.p)!==null&&u!==void 0?u:\".\",Hw(a.coercion,o,()=>new Set(A.value))]),!0):!1}return pr(a,`Expected a set (got ${qn(o)})`)}})}function uqe(t,e){let r=qD(jD([t,e])),o=GD(e,{keys:t});return Hr({test:(a,n)=>{var u,A,p;if(Object.getPrototypeOf(a).toString()===\"[object Map]\")if(typeof n?.coercions<\"u\"){if(typeof n?.coercion>\"u\")return pr(n,\"Unbound coercion result\");let h=[...a],E=[...a];if(!r(E,Object.assign(Object.assign({},n),{coercion:void 0})))return!1;let I=()=>E.some((v,x)=>v[0]!==h[x][0]||v[1]!==h[x][1])?new Map(E):a;return n.coercions.push([(u=n.p)!==null&&u!==void 0?u:\".\",Hw(n.coercion,a,I)]),!0}else{let h=!0;for(let[E,I]of a)if(h=t(E,Object.assign({},n))&&h,!h&&n?.errors==null||(h=e(I,Object.assign(Object.assign({},n),{p:jp(n,E)}))&&h,!h&&n?.errors==null))break;return h}if(typeof n?.coercions<\"u\"){if(typeof n?.coercion>\"u\")return pr(n,\"Unbound coercion result\");let h={value:a};return Array.isArray(a)?r(a,Object.assign(Object.assign({},n),{coercion:void 0}))?(n.coercions.push([(A=n.p)!==null&&A!==void 0?A:\".\",Hw(n.coercion,a,()=>new Map(h.value))]),!0):!1:o(a,Object.assign(Object.assign({},n),{coercion:Wu(h,\"value\")}))?(n.coercions.push([(p=n.p)!==null&&p!==void 0?p:\".\",Hw(n.coercion,a,()=>new Map(Object.entries(h.value)))]),!0):!1}return pr(n,`Expected a map (got ${qn(a)})`)}})}function jD(t,{delimiter:e}={}){let r=dV(t.length);return Hr({test:(o,a)=>{var n;if(typeof o==\"string\"&&typeof e<\"u\"&&typeof a?.coercions<\"u\"){if(typeof a?.coercion>\"u\")return pr(a,\"Unbound coercion result\");o=o.split(e),a.coercions.push([(n=a.p)!==null&&n!==void 0?n:\".\",a.coercion.bind(null,o)])}if(!Array.isArray(o))return pr(a,`Expected a tuple (got ${qn(o)})`);let u=r(o,Object.assign({},a));for(let A=0,p=o.length;A<p&&A<t.length&&(u=t[A](o[A],Object.assign(Object.assign({},a),{p:jp(a,A),coercion:Wu(o,A)}))&&u,!(!u&&a?.errors==null));++A);return u}})}function GD(t,{keys:e=null}={}){let r=qD(jD([e??om(),t]));return Hr({test:(o,a)=>{var n;if(Array.isArray(o)&&typeof a?.coercions<\"u\")return typeof a?.coercion>\"u\"?pr(a,\"Unbound coercion result\"):r(o,Object.assign(Object.assign({},a),{coercion:void 0}))?(o=Object.fromEntries(o),a.coercions.push([(n=a.p)!==null&&n!==void 0?n:\".\",a.coercion.bind(null,o)]),!0):!1;if(typeof o!=\"object\"||o===null)return pr(a,`Expected an object (got ${qn(o)})`);let u=Object.keys(o),A=!0;for(let p=0,h=u.length;p<h&&(A||a?.errors!=null);++p){let E=u[p],I=o[E];if(E===\"__proto__\"||E===\"constructor\"){A=pr(Object.assign(Object.assign({},a),{p:jp(a,E)}),\"Unsafe property name\");continue}if(e!==null&&!e(E,a)){A=!1;continue}if(!t(I,Object.assign(Object.assign({},a),{p:jp(a,E),coercion:Wu(o,E)}))){A=!1;continue}}return A}})}function Aqe(t,e={}){return GD(t,e)}function hV(t,{extra:e=null}={}){let r=Object.keys(t),o=Hr({test:(a,n)=>{if(typeof a!=\"object\"||a===null)return pr(n,`Expected an object (got ${qn(a)})`);let u=new Set([...r,...Object.keys(a)]),A={},p=!0;for(let h of u){if(h===\"constructor\"||h===\"__proto__\")p=pr(Object.assign(Object.assign({},n),{p:jp(n,h)}),\"Unsafe property name\");else{let E=Object.prototype.hasOwnProperty.call(t,h)?t[h]:void 0,I=Object.prototype.hasOwnProperty.call(a,h)?a[h]:void 0;typeof E<\"u\"?p=E(I,Object.assign(Object.assign({},n),{p:jp(n,h),coercion:Wu(a,h)}))&&p:e===null?p=pr(Object.assign(Object.assign({},n),{p:jp(n,h)}),`Extraneous property (got ${qn(I)})`):Object.defineProperty(A,h,{enumerable:!0,get:()=>I,set:iqe(a,h)})}if(!p&&n?.errors==null)break}return e!==null&&(p||n?.errors!=null)&&(p=e(A,n)&&p),p}});return Object.assign(o,{properties:t})}function fqe(t){return hV(t,{extra:GD(CT())})}function gV(t){return()=>t}function Hr({test:t}){return gV(t)()}function hqe(t,e){if(!e(t))throw new Gp}function gqe(t,e){let r=[];if(!e(t,{errors:r}))throw new Gp({errors:r})}function dqe(t,e){}function mqe(t,e,{coerce:r=!1,errors:o,throw:a}={}){let n=o?[]:void 0;if(!r){if(e(t,{errors:n}))return a?t:{value:t,errors:void 0};if(a)throw new Gp({errors:n});return{value:void 0,errors:n??!0}}let u={value:t},A=Wu(u,\"value\"),p=[];if(!e(t,{errors:n,coercion:A,coercions:p})){if(a)throw new Gp({errors:n});return{value:void 0,errors:n??!0}}for(let[,h]of p)h();return a?u.value:{value:u.value,errors:void 0}}function yqe(t,e){let r=jD(t);return(...o)=>{if(!r(o))throw new Gp;return e(...o)}}function Eqe(t){return Hr({test:(e,r)=>e.length>=t?!0:pr(r,`Expected to have a length of at least ${t} elements (got ${e.length})`)})}function Cqe(t){return Hr({test:(e,r)=>e.length<=t?!0:pr(r,`Expected to have a length of at most ${t} elements (got ${e.length})`)})}function dV(t){return Hr({test:(e,r)=>e.length!==t?pr(r,`Expected to have a length of exactly ${t} elements (got ${e.length})`):!0})}function wqe({map:t}={}){return Hr({test:(e,r)=>{let o=new Set,a=new Set;for(let n=0,u=e.length;n<u;++n){let A=e[n],p=typeof t<\"u\"?t(A):A;if(o.has(p)){if(a.has(p))continue;pr(r,`Expected to contain unique elements; got a duplicate with ${qn(e)}`),a.add(p)}else o.add(p)}return a.size===0}})}function Iqe(){return Hr({test:(t,e)=>t<=0?!0:pr(e,`Expected to be negative (got ${t})`)})}function Bqe(){return Hr({test:(t,e)=>t>=0?!0:pr(e,`Expected to be positive (got ${t})`)})}function BT(t){return Hr({test:(e,r)=>e>=t?!0:pr(r,`Expected to be at least ${t} (got ${e})`)})}function vqe(t){return Hr({test:(e,r)=>e<=t?!0:pr(r,`Expected to be at most ${t} (got ${e})`)})}function Dqe(t,e){return Hr({test:(r,o)=>r>=t&&r<=e?!0:pr(o,`Expected to be in the [${t}; ${e}] range (got ${r})`)})}function Pqe(t,e){return Hr({test:(r,o)=>r>=t&&r<e?!0:pr(o,`Expected to be in the [${t}; ${e}[ range (got ${r})`)})}function vT({unsafe:t=!1}={}){return Hr({test:(e,r)=>e!==Math.round(e)?pr(r,`Expected to be an integer (got ${e})`):!t&&!Number.isSafeInteger(e)?pr(r,`Expected to be a safe integer (got ${e})`):!0})}function qw(t){return Hr({test:(e,r)=>t.test(e)?!0:pr(r,`Expected to match the pattern ${t.toString()} (got ${qn(e)})`)})}function bqe(){return Hr({test:(t,e)=>t!==t.toLowerCase()?pr(e,`Expected to be all-lowercase (got ${t})`):!0})}function Sqe(){return Hr({test:(t,e)=>t!==t.toUpperCase()?pr(e,`Expected to be all-uppercase (got ${t})`):!0})}function xqe(){return Hr({test:(t,e)=>nqe.test(t)?!0:pr(e,`Expected to be a valid UUID v4 (got ${qn(t)})`)})}function kqe(){return Hr({test:(t,e)=>fV.test(t)?!0:pr(e,`Expected to be a valid ISO 8601 date string (got ${qn(t)})`)})}function Qqe({alpha:t=!1}){return Hr({test:(e,r)=>(t?eqe.test(e):tqe.test(e))?!0:pr(r,`Expected to be a valid hexadecimal color string (got ${qn(e)})`)})}function Fqe(){return Hr({test:(t,e)=>rqe.test(t)?!0:pr(e,`Expected to be a valid base 64 string (got ${qn(t)})`)})}function Rqe(t=CT()){return Hr({test:(e,r)=>{let o;try{o=JSON.parse(e)}catch{return pr(r,`Expected to be a valid JSON string (got ${qn(e)})`)}return t(o,r)}})}function YD(t,...e){let r=Array.isArray(e[0])?e[0]:e;return Hr({test:(o,a)=>{var n,u;let A={value:o},p=typeof a?.coercions<\"u\"?Wu(A,\"value\"):void 0,h=typeof a?.coercions<\"u\"?[]:void 0;if(!t(o,Object.assign(Object.assign({},a),{coercion:p,coercions:h})))return!1;let E=[];if(typeof h<\"u\")for(let[,I]of h)E.push(I());try{if(typeof a?.coercions<\"u\"){if(A.value!==o){if(typeof a?.coercion>\"u\")return pr(a,\"Unbound coercion result\");a.coercions.push([(n=a.p)!==null&&n!==void 0?n:\".\",a.coercion.bind(null,A.value)])}(u=a?.coercions)===null||u===void 0||u.push(...h)}return r.every(I=>I(A.value,a))}finally{for(let I of E)I()}}})}function jw(t,...e){let r=Array.isArray(e[0])?e[0]:e;return YD(t,r)}function Tqe(t){return Hr({test:(e,r)=>typeof e>\"u\"?!0:t(e,r)})}function Nqe(t){return Hr({test:(e,r)=>e===null?!0:t(e,r)})}function Lqe(t,e){var r;let o=new Set(t),a=Gw[(r=e?.missingIf)!==null&&r!==void 0?r:\"missing\"];return Hr({test:(n,u)=>{let A=new Set(Object.keys(n)),p=[];for(let h of o)a(A,h,n)||p.push(h);return p.length>0?pr(u,`Missing required ${ET(p.length,\"property\",\"properties\")} ${sm(p,\"and\")}`):!0}})}function DT(t,e){var r;let o=new Set(t),a=Gw[(r=e?.missingIf)!==null&&r!==void 0?r:\"missing\"];return Hr({test:(n,u)=>Object.keys(n).some(h=>a(o,h,n))?!0:pr(u,`Missing at least one property from ${sm(Array.from(o),\"or\")}`)})}function Mqe(t,e){var r;let o=new Set(t),a=Gw[(r=e?.missingIf)!==null&&r!==void 0?r:\"missing\"];return Hr({test:(n,u)=>{let A=new Set(Object.keys(n)),p=[];for(let h of o)a(A,h,n)&&p.push(h);return p.length>0?pr(u,`Forbidden ${ET(p.length,\"property\",\"properties\")} ${sm(p,\"and\")}`):!0}})}function Oqe(t,e){var r;let o=new Set(t),a=Gw[(r=e?.missingIf)!==null&&r!==void 0?r:\"missing\"];return Hr({test:(n,u)=>{let A=new Set(Object.keys(n)),p=[];for(let h of o)a(A,h,n)&&p.push(h);return p.length>1?pr(u,`Mutually exclusive properties ${sm(p,\"and\")}`):!0}})}function Yw(t,e,r,o){var a,n;let u=new Set((a=o?.ignore)!==null&&a!==void 0?a:[]),A=Gw[(n=o?.missingIf)!==null&&n!==void 0?n:\"missing\"],p=new Set(r),h=Uqe[e],E=e===Yu.Forbids?\"or\":\"and\";return Hr({test:(I,v)=>{let x=new Set(Object.keys(I));if(!A(x,t,I)||u.has(I[t]))return!0;let C=[];for(let R of p)(A(x,R,I)&&!u.has(I[R]))!==h.expect&&C.push(R);return C.length>=1?pr(v,`Property \"${t}\" ${h.message} ${ET(C.length,\"property\",\"properties\")} ${sm(C,E)}`):!0}})}var $6e,eqe,tqe,rqe,nqe,fV,sqe,pqe,IT,Gp,Gw,Yu,Uqe,el=Et(()=>{$6e=/^[a-zA-Z_][a-zA-Z0-9_]*$/;eqe=/^#[0-9a-f]{6}$/i,tqe=/^#[0-9a-f]{6}([0-9a-f]{2})?$/i,rqe=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/,nqe=/^[a-f0-9]{8}-[a-f0-9]{4}-4[a-f0-9]{3}-[89aAbB][a-f0-9]{3}-[a-f0-9]{12}$/i,fV=/^(?:[1-9]\\d{3}(-?)(?:(?:0[1-9]|1[0-2])\\1(?:0[1-9]|1\\d|2[0-8])|(?:0[13-9]|1[0-2])\\1(?:29|30)|(?:0[13578]|1[02])(?:\\1)31|00[1-9]|0[1-9]\\d|[12]\\d{2}|3(?:[0-5]\\d|6[0-5]))|(?:[1-9]\\d(?:0[48]|[2468][048]|[13579][26])|(?:[2468][048]|[13579][26])00)(?:(-?)02(?:\\2)29|-?366))T(?:[01]\\d|2[0-3])(:?)[0-5]\\d(?:\\3[0-5]\\d)?(?:Z|[+-][01]\\d(?:\\3[0-5]\\d)?)$/;sqe=new Map([[\"true\",!0],[\"True\",!0],[\"1\",!0],[1,!0],[\"false\",!1],[\"False\",!1],[\"0\",!1],[0,!1]]);pqe=t=>Hr({test:(e,r)=>e instanceof t?!0:pr(r,`Expected an instance of ${t.name} (got ${qn(e)})`)}),IT=(t,{exclusive:e=!1}={})=>Hr({test:(r,o)=>{var a,n,u;let A=[],p=typeof o?.errors<\"u\"?[]:void 0;for(let h=0,E=t.length;h<E;++h){let I=typeof o?.errors<\"u\"?[]:void 0,v=typeof o?.coercions<\"u\"?[]:void 0;if(t[h](r,Object.assign(Object.assign({},o),{errors:I,coercions:v,p:`${(a=o?.p)!==null&&a!==void 0?a:\".\"}#${h+1}`}))){if(A.push([`#${h+1}`,v]),!e)break}else p?.push(I[0])}if(A.length===1){let[,h]=A[0];return typeof h<\"u\"&&((n=o?.coercions)===null||n===void 0||n.push(...h)),!0}return A.length>1?pr(o,`Expected to match exactly a single predicate (matched ${A.join(\", \")})`):(u=o?.errors)===null||u===void 0||u.push(...p),!1}});Gp=class extends Error{constructor({errors:e}={}){let r=\"Type mismatch\";if(e&&e.length>0){r+=`\n`;for(let o of e)r+=`\n- ${o}`}super(r)}};Gw={missing:(t,e)=>t.has(e),undefined:(t,e,r)=>t.has(e)&&typeof r[e]<\"u\",nil:(t,e,r)=>t.has(e)&&r[e]!=null,falsy:(t,e,r)=>t.has(e)&&!!r[e]};(function(t){t.Forbids=\"Forbids\",t.Requires=\"Requires\"})(Yu||(Yu={}));Uqe={[Yu.Forbids]:{expect:!1,message:\"forbids using\"},[Yu.Requires]:{expect:!0,message:\"requires using\"}}});var it,Yp=Et(()=>{yf();it=class{constructor(){this.help=!1}static Usage(e){return e}async catch(e){throw e}async validateAndExecute(){let r=this.constructor.schema;if(Array.isArray(r)){let{isDict:a,isUnknown:n,applyCascade:u}=await Promise.resolve().then(()=>(el(),Vo)),A=u(a(n()),r),p=[],h=[];if(!A(this,{errors:p,coercions:h}))throw _w(\"Invalid option schema\",p);for(let[,I]of h)I()}else if(r!=null)throw new Error(\"Invalid command schema\");let o=await this.execute();return typeof o<\"u\"?o:0}};it.isOption=Uw;it.Default=[]});function Pa(t){gT&&console.log(t)}function yV(){let t={nodes:[]};for(let e=0;e<un.CustomNode;++e)t.nodes.push(tl());return t}function _qe(t){let e=yV(),r=[],o=e.nodes.length;for(let a of t){r.push(o);for(let n=0;n<a.nodes.length;++n)CV(n)||e.nodes.push(Vqe(a.nodes[n],o));o+=a.nodes.length-un.CustomNode+1}for(let a of r)am(e,un.InitialNode,a);return e}function Oc(t,e){return t.nodes.push(e),t.nodes.length-1}function Hqe(t){let e=new Set,r=o=>{if(e.has(o))return;e.add(o);let a=t.nodes[o];for(let u of Object.values(a.statics))for(let{to:A}of u)r(A);for(let[,{to:u}]of a.dynamics)r(u);for(let{to:u}of a.shortcuts)r(u);let n=new Set(a.shortcuts.map(({to:u})=>u));for(;a.shortcuts.length>0;){let{to:u}=a.shortcuts.shift(),A=t.nodes[u];for(let[p,h]of Object.entries(A.statics)){let E=Object.prototype.hasOwnProperty.call(a.statics,p)?a.statics[p]:a.statics[p]=[];for(let I of h)E.some(({to:v})=>I.to===v)||E.push(I)}for(let[p,h]of A.dynamics)a.dynamics.some(([E,{to:I}])=>p===E&&h.to===I)||a.dynamics.push([p,h]);for(let p of A.shortcuts)n.has(p.to)||(a.shortcuts.push(p),n.add(p.to))}};r(un.InitialNode)}function qqe(t,{prefix:e=\"\"}={}){if(gT){Pa(`${e}Nodes are:`);for(let r=0;r<t.nodes.length;++r)Pa(`${e}  ${r}: ${JSON.stringify(t.nodes[r])}`)}}function jqe(t,e,r=!1){Pa(`Running a vm on ${JSON.stringify(e)}`);let o=[{node:un.InitialNode,state:{candidateUsage:null,requiredOptions:[],errorMessage:null,ignoreOptions:!1,options:[],path:[],positionals:[],remainder:null,selectedIndex:null,partial:!1,tokens:[]}}];qqe(t,{prefix:\"  \"});let a=[Hn.StartOfInput,...e];for(let n=0;n<a.length;++n){let u=a[n],A=u===Hn.EndOfInput||u===Hn.EndOfPartialInput,p=n-1;Pa(`  Processing ${JSON.stringify(u)}`);let h=[];for(let{node:E,state:I}of o){Pa(`    Current node is ${E}`);let v=t.nodes[E];if(E===un.ErrorNode){h.push({node:E,state:I});continue}console.assert(v.shortcuts.length===0,\"Shortcuts should have been eliminated by now\");let x=Object.prototype.hasOwnProperty.call(v.statics,u);if(!r||n<a.length-1||x)if(x){let C=v.statics[u];for(let{to:R,reducer:L}of C)h.push({node:R,state:typeof L<\"u\"?WD(bT,L,I,u,p):I}),Pa(`      Static transition to ${R} found`)}else Pa(\"      No static transition found\");else{let C=!1;for(let R of Object.keys(v.statics))if(R.startsWith(u)){if(u===R)for(let{to:L,reducer:U}of v.statics[R])h.push({node:L,state:typeof U<\"u\"?WD(bT,U,I,u,p):I}),Pa(`      Static transition to ${L} found`);else for(let{to:L}of v.statics[R])h.push({node:L,state:{...I,remainder:R.slice(u.length)}}),Pa(`      Static transition to ${L} found (partial match)`);C=!0}C||Pa(\"      No partial static transition found\")}if(!A)for(let[C,{to:R,reducer:L}]of v.dynamics)WD(zqe,C,I,u,p)&&(h.push({node:R,state:typeof L<\"u\"?WD(bT,L,I,u,p):I}),Pa(`      Dynamic transition to ${R} found (via ${C})`))}if(h.length===0&&A&&e.length===1)return[{node:un.InitialNode,state:mV}];if(h.length===0)throw new im(e,o.filter(({node:E})=>E!==un.ErrorNode).map(({state:E})=>({usage:E.candidateUsage,reason:null})));if(h.every(({node:E})=>E===un.ErrorNode))throw new im(e,h.map(({state:E})=>({usage:E.candidateUsage,reason:E.errorMessage})));o=Yqe(h)}if(o.length>0){Pa(\"  Results:\");for(let n of o)Pa(`    - ${n.node} -> ${JSON.stringify(n.state)}`)}else Pa(\"  No results\");return o}function Gqe(t,e,{endToken:r=Hn.EndOfInput}={}){let o=jqe(t,[...e,r]);return Wqe(e,o.map(({state:a})=>a))}function Yqe(t){let e=0;for(let{state:r}of t)r.path.length>e&&(e=r.path.length);return t.filter(({state:r})=>r.path.length===e)}function Wqe(t,e){let r=e.filter(v=>v.selectedIndex!==null),o=r.filter(v=>!v.partial);if(o.length>0&&(r=o),r.length===0)throw new Error;let a=r.filter(v=>v.selectedIndex===Z0||v.requiredOptions.every(x=>x.some(C=>v.options.find(R=>R.name===C))));if(a.length===0)throw new im(t,r.map(v=>({usage:v.candidateUsage,reason:null})));let n=0;for(let v of a)v.path.length>n&&(n=v.path.length);let u=a.filter(v=>v.path.length===n),A=v=>v.positionals.filter(({extra:x})=>!x).length+v.options.length,p=u.map(v=>({state:v,positionalCount:A(v)})),h=0;for(let{positionalCount:v}of p)v>h&&(h=v);let E=p.filter(({positionalCount:v})=>v===h).map(({state:v})=>v),I=Kqe(E);if(I.length>1)throw new UD(t,I.map(v=>v.candidateUsage));return I[0]}function Kqe(t){let e=[],r=[];for(let o of t)o.selectedIndex===Z0?r.push(o):e.push(o);return r.length>0&&e.push({...mV,path:EV(...r.map(o=>o.path)),options:r.reduce((o,a)=>o.concat(a.options),[])}),e}function EV(t,e,...r){return e===void 0?Array.from(t):EV(t.filter((o,a)=>o===e[a]),...r)}function tl(){return{dynamics:[],shortcuts:[],statics:{}}}function CV(t){return t===un.SuccessNode||t===un.ErrorNode}function PT(t,e=0){return{to:CV(t.to)?t.to:t.to>=un.CustomNode?t.to+e-un.CustomNode+1:t.to+e,reducer:t.reducer}}function Vqe(t,e=0){let r=tl();for(let[o,a]of t.dynamics)r.dynamics.push([o,PT(a,e)]);for(let o of t.shortcuts)r.shortcuts.push(PT(o,e));for(let[o,a]of Object.entries(t.statics))r.statics[o]=a.map(n=>PT(n,e));return r}function xs(t,e,r,o,a){t.nodes[e].dynamics.push([r,{to:o,reducer:a}])}function am(t,e,r,o){t.nodes[e].shortcuts.push({to:r,reducer:o})}function zo(t,e,r,o,a){(Object.prototype.hasOwnProperty.call(t.nodes[e].statics,r)?t.nodes[e].statics[r]:t.nodes[e].statics[r]=[]).push({to:o,reducer:a})}function WD(t,e,r,o,a){if(Array.isArray(e)){let[n,...u]=e;return t[n](r,o,a,...u)}else return t[e](r,o,a)}var mV,zqe,bT,rl,ST,KD,VD=Et(()=>{OD();_D();mV={candidateUsage:null,requiredOptions:[],errorMessage:null,ignoreOptions:!1,path:[],positionals:[],options:[],remainder:null,selectedIndex:Z0,partial:!1,tokens:[]};zqe={always:()=>!0,isOptionLike:(t,e)=>!t.ignoreOptions&&e!==\"-\"&&e.startsWith(\"-\"),isNotOptionLike:(t,e)=>t.ignoreOptions||e===\"-\"||!e.startsWith(\"-\"),isOption:(t,e,r,o)=>!t.ignoreOptions&&e===o,isBatchOption:(t,e,r,o)=>!t.ignoreOptions&&cV.test(e)&&[...e.slice(1)].every(a=>o.has(`-${a}`)),isBoundOption:(t,e,r,o,a)=>{let n=e.match(hT);return!t.ignoreOptions&&!!n&&MD.test(n[1])&&o.has(n[1])&&a.filter(u=>u.nameSet.includes(n[1])).every(u=>u.allowBinding)},isNegatedOption:(t,e,r,o)=>!t.ignoreOptions&&e===`--no-${o.slice(2)}`,isHelp:(t,e)=>!t.ignoreOptions&&pT.test(e),isUnsupportedOption:(t,e,r,o)=>!t.ignoreOptions&&e.startsWith(\"-\")&&MD.test(e)&&!o.has(e),isInvalidOption:(t,e)=>!t.ignoreOptions&&e.startsWith(\"-\")&&!MD.test(e)},bT={setCandidateState:(t,e,r,o)=>({...t,...o}),setSelectedIndex:(t,e,r,o)=>({...t,selectedIndex:o}),setPartialIndex:(t,e,r,o)=>({...t,selectedIndex:o,partial:!0}),pushBatch:(t,e,r,o)=>{let a=t.options.slice(),n=t.tokens.slice();for(let u=1;u<e.length;++u){let A=o.get(`-${e[u]}`),p=u===1?[0,2]:[u,u+1];a.push({name:A,value:!0}),n.push({segmentIndex:r,type:\"option\",option:A,slice:p})}return{...t,options:a,tokens:n}},pushBound:(t,e,r)=>{let[,o,a]=e.match(hT),n=t.options.concat({name:o,value:a}),u=t.tokens.concat([{segmentIndex:r,type:\"option\",slice:[0,o.length],option:o},{segmentIndex:r,type:\"assign\",slice:[o.length,o.length+1]},{segmentIndex:r,type:\"value\",slice:[o.length+1,o.length+a.length+1]}]);return{...t,options:n,tokens:u}},pushPath:(t,e,r)=>{let o=t.path.concat(e),a=t.tokens.concat({segmentIndex:r,type:\"path\"});return{...t,path:o,tokens:a}},pushPositional:(t,e,r)=>{let o=t.positionals.concat({value:e,extra:!1}),a=t.tokens.concat({segmentIndex:r,type:\"positional\"});return{...t,positionals:o,tokens:a}},pushExtra:(t,e,r)=>{let o=t.positionals.concat({value:e,extra:!0}),a=t.tokens.concat({segmentIndex:r,type:\"positional\"});return{...t,positionals:o,tokens:a}},pushExtraNoLimits:(t,e,r)=>{let o=t.positionals.concat({value:e,extra:rl}),a=t.tokens.concat({segmentIndex:r,type:\"positional\"});return{...t,positionals:o,tokens:a}},pushTrue:(t,e,r,o)=>{let a=t.options.concat({name:o,value:!0}),n=t.tokens.concat({segmentIndex:r,type:\"option\",option:o});return{...t,options:a,tokens:n}},pushFalse:(t,e,r,o)=>{let a=t.options.concat({name:o,value:!1}),n=t.tokens.concat({segmentIndex:r,type:\"option\",option:o});return{...t,options:a,tokens:n}},pushUndefined:(t,e,r,o)=>{let a=t.options.concat({name:e,value:void 0}),n=t.tokens.concat({segmentIndex:r,type:\"option\",option:e});return{...t,options:a,tokens:n}},pushStringValue:(t,e,r)=>{var o;let a=t.options[t.options.length-1],n=t.options.slice(),u=t.tokens.concat({segmentIndex:r,type:\"value\"});return a.value=((o=a.value)!==null&&o!==void 0?o:[]).concat([e]),{...t,options:n,tokens:u}},setStringValue:(t,e,r)=>{let o=t.options[t.options.length-1],a=t.options.slice(),n=t.tokens.concat({segmentIndex:r,type:\"value\"});return o.value=e,{...t,options:a,tokens:n}},inhibateOptions:t=>({...t,ignoreOptions:!0}),useHelp:(t,e,r,o)=>{let[,,a]=e.match(pT);return typeof a<\"u\"?{...t,options:[{name:\"-c\",value:String(o)},{name:\"-i\",value:a}]}:{...t,options:[{name:\"-c\",value:String(o)}]}},setError:(t,e,r,o)=>e===Hn.EndOfInput||e===Hn.EndOfPartialInput?{...t,errorMessage:`${o}.`}:{...t,errorMessage:`${o} (\"${e}\").`},setOptionArityError:(t,e)=>{let r=t.options[t.options.length-1];return{...t,errorMessage:`Not enough arguments to option ${r.name}.`}}},rl=Symbol(),ST=class{constructor(e,r){this.allOptionNames=new Map,this.arity={leading:[],trailing:[],extra:[],proxy:!1},this.options=[],this.paths=[],this.cliIndex=e,this.cliOpts=r}addPath(e){this.paths.push(e)}setArity({leading:e=this.arity.leading,trailing:r=this.arity.trailing,extra:o=this.arity.extra,proxy:a=this.arity.proxy}){Object.assign(this.arity,{leading:e,trailing:r,extra:o,proxy:a})}addPositional({name:e=\"arg\",required:r=!0}={}){if(!r&&this.arity.extra===rl)throw new Error(\"Optional parameters cannot be declared when using .rest() or .proxy()\");if(!r&&this.arity.trailing.length>0)throw new Error(\"Optional parameters cannot be declared after the required trailing positional arguments\");!r&&this.arity.extra!==rl?this.arity.extra.push(e):this.arity.extra!==rl&&this.arity.extra.length===0?this.arity.leading.push(e):this.arity.trailing.push(e)}addRest({name:e=\"arg\",required:r=0}={}){if(this.arity.extra===rl)throw new Error(\"Infinite lists cannot be declared multiple times in the same command\");if(this.arity.trailing.length>0)throw new Error(\"Infinite lists cannot be declared after the required trailing positional arguments\");for(let o=0;o<r;++o)this.addPositional({name:e});this.arity.extra=rl}addProxy({required:e=0}={}){this.addRest({required:e}),this.arity.proxy=!0}addOption({names:e,description:r,arity:o=0,hidden:a=!1,required:n=!1,allowBinding:u=!0}){if(!u&&o>1)throw new Error(\"The arity cannot be higher than 1 when the option only supports the --arg=value syntax\");if(!Number.isInteger(o))throw new Error(`The arity must be an integer, got ${o}`);if(o<0)throw new Error(`The arity must be positive, got ${o}`);let A=e.reduce((p,h)=>h.length>p.length?h:p,\"\");for(let p of e)this.allOptionNames.set(p,A);this.options.push({preferredName:A,nameSet:e,description:r,arity:o,hidden:a,required:n,allowBinding:u})}setContext(e){this.context=e}usage({detailed:e=!0,inlineOptions:r=!0}={}){let o=[this.cliOpts.binaryName],a=[];if(this.paths.length>0&&o.push(...this.paths[0]),e){for(let{preferredName:u,nameSet:A,arity:p,hidden:h,description:E,required:I}of this.options){if(h)continue;let v=[];for(let C=0;C<p;++C)v.push(` #${C}`);let x=`${A.join(\",\")}${v.join(\"\")}`;!r&&E?a.push({preferredName:u,nameSet:A,definition:x,description:E,required:I}):o.push(I?`<${x}>`:`[${x}]`)}o.push(...this.arity.leading.map(u=>`<${u}>`)),this.arity.extra===rl?o.push(\"...\"):o.push(...this.arity.extra.map(u=>`[${u}]`)),o.push(...this.arity.trailing.map(u=>`<${u}>`))}return{usage:o.join(\" \"),options:a}}compile(){if(typeof this.context>\"u\")throw new Error(\"Assertion failed: No context attached\");let e=yV(),r=un.InitialNode,o=this.usage().usage,a=this.options.filter(A=>A.required).map(A=>A.nameSet);r=Oc(e,tl()),zo(e,un.InitialNode,Hn.StartOfInput,r,[\"setCandidateState\",{candidateUsage:o,requiredOptions:a}]);let n=this.arity.proxy?\"always\":\"isNotOptionLike\",u=this.paths.length>0?this.paths:[[]];for(let A of u){let p=r;if(A.length>0){let v=Oc(e,tl());am(e,p,v),this.registerOptions(e,v),p=v}for(let v=0;v<A.length;++v){let x=Oc(e,tl());zo(e,p,A[v],x,\"pushPath\"),p=x}if(this.arity.leading.length>0||!this.arity.proxy){let v=Oc(e,tl());xs(e,p,\"isHelp\",v,[\"useHelp\",this.cliIndex]),xs(e,v,\"always\",v,\"pushExtra\"),zo(e,v,Hn.EndOfInput,un.SuccessNode,[\"setSelectedIndex\",Z0]),this.registerOptions(e,p)}this.arity.leading.length>0&&(zo(e,p,Hn.EndOfInput,un.ErrorNode,[\"setError\",\"Not enough positional arguments\"]),zo(e,p,Hn.EndOfPartialInput,un.SuccessNode,[\"setPartialIndex\",this.cliIndex]));let h=p;for(let v=0;v<this.arity.leading.length;++v){let x=Oc(e,tl());(!this.arity.proxy||v+1!==this.arity.leading.length)&&this.registerOptions(e,x),(this.arity.trailing.length>0||v+1!==this.arity.leading.length)&&(zo(e,x,Hn.EndOfInput,un.ErrorNode,[\"setError\",\"Not enough positional arguments\"]),zo(e,x,Hn.EndOfPartialInput,un.SuccessNode,[\"setPartialIndex\",this.cliIndex])),xs(e,h,\"isNotOptionLike\",x,\"pushPositional\"),h=x}let E=h;if(this.arity.extra===rl||this.arity.extra.length>0){let v=Oc(e,tl());if(am(e,h,v),this.arity.extra===rl){let x=Oc(e,tl());this.arity.proxy||this.registerOptions(e,x),xs(e,h,n,x,\"pushExtraNoLimits\"),xs(e,x,n,x,\"pushExtraNoLimits\"),am(e,x,v)}else for(let x=0;x<this.arity.extra.length;++x){let C=Oc(e,tl());(!this.arity.proxy||x>0)&&this.registerOptions(e,C),xs(e,E,n,C,\"pushExtra\"),am(e,C,v),E=C}E=v}this.arity.trailing.length>0&&(zo(e,E,Hn.EndOfInput,un.ErrorNode,[\"setError\",\"Not enough positional arguments\"]),zo(e,E,Hn.EndOfPartialInput,un.SuccessNode,[\"setPartialIndex\",this.cliIndex]));let I=E;for(let v=0;v<this.arity.trailing.length;++v){let x=Oc(e,tl());this.arity.proxy||this.registerOptions(e,x),v+1<this.arity.trailing.length&&(zo(e,x,Hn.EndOfInput,un.ErrorNode,[\"setError\",\"Not enough positional arguments\"]),zo(e,x,Hn.EndOfPartialInput,un.SuccessNode,[\"setPartialIndex\",this.cliIndex])),xs(e,I,\"isNotOptionLike\",x,\"pushPositional\"),I=x}xs(e,I,n,un.ErrorNode,[\"setError\",\"Extraneous positional argument\"]),zo(e,I,Hn.EndOfInput,un.SuccessNode,[\"setSelectedIndex\",this.cliIndex]),zo(e,I,Hn.EndOfPartialInput,un.SuccessNode,[\"setSelectedIndex\",this.cliIndex])}return{machine:e,context:this.context}}registerOptions(e,r){xs(e,r,[\"isOption\",\"--\"],r,\"inhibateOptions\"),xs(e,r,[\"isBatchOption\",this.allOptionNames],r,[\"pushBatch\",this.allOptionNames]),xs(e,r,[\"isBoundOption\",this.allOptionNames,this.options],r,\"pushBound\"),xs(e,r,[\"isUnsupportedOption\",this.allOptionNames],un.ErrorNode,[\"setError\",\"Unsupported option name\"]),xs(e,r,[\"isInvalidOption\"],un.ErrorNode,[\"setError\",\"Invalid option name\"]);for(let o of this.options)if(o.arity===0)for(let a of o.nameSet)xs(e,r,[\"isOption\",a],r,[\"pushTrue\",o.preferredName]),a.startsWith(\"--\")&&!a.startsWith(\"--no-\")&&xs(e,r,[\"isNegatedOption\",a],r,[\"pushFalse\",o.preferredName]);else{let a=Oc(e,tl());for(let n of o.nameSet)xs(e,r,[\"isOption\",n],a,[\"pushUndefined\",o.preferredName]);for(let n=0;n<o.arity;++n){let u=Oc(e,tl());zo(e,a,Hn.EndOfInput,un.ErrorNode,\"setOptionArityError\"),zo(e,a,Hn.EndOfPartialInput,un.ErrorNode,\"setOptionArityError\"),xs(e,a,\"isOptionLike\",un.ErrorNode,\"setOptionArityError\");let A=o.arity===1?\"setStringValue\":\"pushStringValue\";xs(e,a,\"isNotOptionLike\",u,A),a=u}am(e,a,r)}}},KD=class t{constructor({binaryName:e=\"...\"}={}){this.builders=[],this.opts={binaryName:e}}static build(e,r={}){return new t(r).commands(e).compile()}getBuilderByIndex(e){if(!(e>=0&&e<this.builders.length))throw new Error(`Assertion failed: Out-of-bound command index (${e})`);return this.builders[e]}commands(e){for(let r of e)r(this.command());return this}command(){let e=new ST(this.builders.length,this.opts);return this.builders.push(e),e}compile(){let e=[],r=[];for(let a of this.builders){let{machine:n,context:u}=a.compile();e.push(n),r.push(u)}let o=_qe(e);return Hqe(o),{machine:o,contexts:r,process:(a,{partial:n}={})=>{let u=n?Hn.EndOfPartialInput:Hn.EndOfInput;return Gqe(o,a,{endToken:u})}}}}});function IV(){return zD.default&&\"getColorDepth\"in zD.default.WriteStream.prototype?zD.default.WriteStream.prototype.getColorDepth():process.env.FORCE_COLOR===\"0\"?1:process.env.FORCE_COLOR===\"1\"||typeof process.stdout<\"u\"&&process.stdout.isTTY?8:1}function BV(t){let e=wV;if(typeof e>\"u\"){if(t.stdout===process.stdout&&t.stderr===process.stderr)return null;let{AsyncLocalStorage:r}=ve(\"async_hooks\");e=wV=new r;let o=process.stdout._write;process.stdout._write=function(n,u,A){let p=e.getStore();return typeof p>\"u\"?o.call(this,n,u,A):p.stdout.write(n,u,A)};let a=process.stderr._write;process.stderr._write=function(n,u,A){let p=e.getStore();return typeof p>\"u\"?a.call(this,n,u,A):p.stderr.write(n,u,A)}}return r=>e.run(t,r)}var zD,wV,vV=Et(()=>{zD=Ze(ve(\"tty\"),1)});var JD,DV=Et(()=>{Yp();JD=class t extends it{constructor(e){super(),this.contexts=e,this.commands=[]}static from(e,r){let o=new t(r);o.path=e.path;for(let a of e.options)switch(a.name){case\"-c\":o.commands.push(Number(a.value));break;case\"-i\":o.index=Number(a.value);break}return o}async execute(){let e=this.commands;if(typeof this.index<\"u\"&&this.index>=0&&this.index<e.length&&(e=[e[this.index]]),e.length===0)this.context.stdout.write(this.cli.usage());else if(e.length===1)this.context.stdout.write(this.cli.usage(this.contexts[e[0]].commandClass,{detailed:!0}));else if(e.length>1){this.context.stdout.write(`Multiple commands match your selection:\n`),this.context.stdout.write(`\n`);let r=0;for(let o of this.commands)this.context.stdout.write(this.cli.usage(this.contexts[o].commandClass,{prefix:`${r++}. `.padStart(5)}));this.context.stdout.write(`\n`),this.context.stdout.write(`Run again with -h=<index> to see the longer details of any of those commands.\n`)}}}});async function SV(...t){let{resolvedOptions:e,resolvedCommandClasses:r,resolvedArgv:o,resolvedContext:a}=kV(t);return Jo.from(r,e).runExit(o,a)}async function xV(...t){let{resolvedOptions:e,resolvedCommandClasses:r,resolvedArgv:o,resolvedContext:a}=kV(t);return Jo.from(r,e).run(o,a)}function kV(t){let e,r,o,a;switch(typeof process<\"u\"&&typeof process.argv<\"u\"&&(o=process.argv.slice(2)),t.length){case 1:r=t[0];break;case 2:t[0]&&t[0].prototype instanceof it||Array.isArray(t[0])?(r=t[0],Array.isArray(t[1])?o=t[1]:a=t[1]):(e=t[0],r=t[1]);break;case 3:Array.isArray(t[2])?(e=t[0],r=t[1],o=t[2]):t[0]&&t[0].prototype instanceof it||Array.isArray(t[0])?(r=t[0],o=t[1],a=t[2]):(e=t[0],r=t[1],a=t[2]);break;default:e=t[0],r=t[1],o=t[2],a=t[3];break}if(typeof o>\"u\")throw new Error(\"The argv parameter must be provided when running Clipanion outside of a Node context\");return{resolvedOptions:e,resolvedCommandClasses:r,resolvedArgv:o,resolvedContext:a}}function bV(t){return t()}var PV,Jo,QV=Et(()=>{OD();VD();yT();vV();Yp();DV();PV=Symbol(\"clipanion/errorCommand\");Jo=class t{constructor({binaryLabel:e,binaryName:r=\"...\",binaryVersion:o,enableCapture:a=!1,enableColors:n}={}){this.registrations=new Map,this.builder=new KD({binaryName:r}),this.binaryLabel=e,this.binaryName=r,this.binaryVersion=o,this.enableCapture=a,this.enableColors=n}static from(e,r={}){let o=new t(r),a=Array.isArray(e)?e:[e];for(let n of a)o.register(n);return o}register(e){var r;let o=new Map,a=new e;for(let p in a){let h=a[p];typeof h==\"object\"&&h!==null&&h[it.isOption]&&o.set(p,h)}let n=this.builder.command(),u=n.cliIndex,A=(r=e.paths)!==null&&r!==void 0?r:a.paths;if(typeof A<\"u\")for(let p of A)n.addPath(p);this.registrations.set(e,{specs:o,builder:n,index:u});for(let[p,{definition:h}]of o.entries())h(n,p);n.setContext({commandClass:e})}process(e,r){let{input:o,context:a,partial:n}=typeof e==\"object\"&&Array.isArray(e)?{input:e,context:r}:e,{contexts:u,process:A}=this.builder.compile(),p=A(o,{partial:n}),h={...t.defaultContext,...a};switch(p.selectedIndex){case Z0:{let E=JD.from(p,u);return E.context=h,E.tokens=p.tokens,E}default:{let{commandClass:E}=u[p.selectedIndex],I=this.registrations.get(E);if(typeof I>\"u\")throw new Error(\"Assertion failed: Expected the command class to have been registered.\");let v=new E;v.context=h,v.tokens=p.tokens,v.path=p.path;try{for(let[x,{transformer:C}]of I.specs.entries())v[x]=C(I.builder,x,p,h);return v}catch(x){throw x[PV]=v,x}}break}}async run(e,r){var o,a;let n,u={...t.defaultContext,...r},A=(o=this.enableColors)!==null&&o!==void 0?o:u.colorDepth>1;if(!Array.isArray(e))n=e;else try{n=this.process(e,u)}catch(E){return u.stdout.write(this.error(E,{colored:A})),1}if(n.help)return u.stdout.write(this.usage(n,{colored:A,detailed:!0})),0;n.context=u,n.cli={binaryLabel:this.binaryLabel,binaryName:this.binaryName,binaryVersion:this.binaryVersion,enableCapture:this.enableCapture,enableColors:this.enableColors,definitions:()=>this.definitions(),definition:E=>this.definition(E),error:(E,I)=>this.error(E,I),format:E=>this.format(E),process:(E,I)=>this.process(E,{...u,...I}),run:(E,I)=>this.run(E,{...u,...I}),usage:(E,I)=>this.usage(E,I)};let p=this.enableCapture&&(a=BV(u))!==null&&a!==void 0?a:bV,h;try{h=await p(()=>n.validateAndExecute().catch(E=>n.catch(E).then(()=>0)))}catch(E){return u.stdout.write(this.error(E,{colored:A,command:n})),1}return h}async runExit(e,r){process.exitCode=await this.run(e,r)}definition(e,{colored:r=!1}={}){if(!e.usage)return null;let{usage:o}=this.getUsageByRegistration(e,{detailed:!1}),{usage:a,options:n}=this.getUsageByRegistration(e,{detailed:!0,inlineOptions:!1}),u=typeof e.usage.category<\"u\"?Do(e.usage.category,{format:this.format(r),paragraphs:!1}):void 0,A=typeof e.usage.description<\"u\"?Do(e.usage.description,{format:this.format(r),paragraphs:!1}):void 0,p=typeof e.usage.details<\"u\"?Do(e.usage.details,{format:this.format(r),paragraphs:!0}):void 0,h=typeof e.usage.examples<\"u\"?e.usage.examples.map(([E,I])=>[Do(E,{format:this.format(r),paragraphs:!1}),I.replace(/\\$0/g,this.binaryName)]):void 0;return{path:o,usage:a,category:u,description:A,details:p,examples:h,options:n}}definitions({colored:e=!1}={}){let r=[];for(let o of this.registrations.keys()){let a=this.definition(o,{colored:e});a&&r.push(a)}return r}usage(e=null,{colored:r,detailed:o=!1,prefix:a=\"$ \"}={}){var n;if(e===null){for(let p of this.registrations.keys()){let h=p.paths,E=typeof p.usage<\"u\";if(!h||h.length===0||h.length===1&&h[0].length===0||((n=h?.some(x=>x.length===0))!==null&&n!==void 0?n:!1))if(e){e=null;break}else e=p;else if(E){e=null;continue}}e&&(o=!0)}let u=e!==null&&e instanceof it?e.constructor:e,A=\"\";if(u)if(o){let{description:p=\"\",details:h=\"\",examples:E=[]}=u.usage||{};p!==\"\"&&(A+=Do(p,{format:this.format(r),paragraphs:!1}).replace(/^./,x=>x.toUpperCase()),A+=`\n`),(h!==\"\"||E.length>0)&&(A+=`${this.format(r).header(\"Usage\")}\n`,A+=`\n`);let{usage:I,options:v}=this.getUsageByRegistration(u,{inlineOptions:!1});if(A+=`${this.format(r).bold(a)}${I}\n`,v.length>0){A+=`\n`,A+=`${this.format(r).header(\"Options\")}\n`;let x=v.reduce((C,R)=>Math.max(C,R.definition.length),0);A+=`\n`;for(let{definition:C,description:R}of v)A+=`  ${this.format(r).bold(C.padEnd(x))}    ${Do(R,{format:this.format(r),paragraphs:!1})}`}if(h!==\"\"&&(A+=`\n`,A+=`${this.format(r).header(\"Details\")}\n`,A+=`\n`,A+=Do(h,{format:this.format(r),paragraphs:!0})),E.length>0){A+=`\n`,A+=`${this.format(r).header(\"Examples\")}\n`;for(let[x,C]of E)A+=`\n`,A+=Do(x,{format:this.format(r),paragraphs:!1}),A+=`${C.replace(/^/m,`  ${this.format(r).bold(a)}`).replace(/\\$0/g,this.binaryName)}\n`}}else{let{usage:p}=this.getUsageByRegistration(u);A+=`${this.format(r).bold(a)}${p}\n`}else{let p=new Map;for(let[v,{index:x}]of this.registrations.entries()){if(typeof v.usage>\"u\")continue;let C=typeof v.usage.category<\"u\"?Do(v.usage.category,{format:this.format(r),paragraphs:!1}):null,R=p.get(C);typeof R>\"u\"&&p.set(C,R=[]);let{usage:L}=this.getUsageByIndex(x);R.push({commandClass:v,usage:L})}let h=Array.from(p.keys()).sort((v,x)=>v===null?-1:x===null?1:v.localeCompare(x,\"en\",{usage:\"sort\",caseFirst:\"upper\"})),E=typeof this.binaryLabel<\"u\",I=typeof this.binaryVersion<\"u\";E||I?(E&&I?A+=`${this.format(r).header(`${this.binaryLabel} - ${this.binaryVersion}`)}\n\n`:E?A+=`${this.format(r).header(`${this.binaryLabel}`)}\n`:A+=`${this.format(r).header(`${this.binaryVersion}`)}\n`,A+=`  ${this.format(r).bold(a)}${this.binaryName} <command>\n`):A+=`${this.format(r).bold(a)}${this.binaryName} <command>\n`;for(let v of h){let x=p.get(v).slice().sort((R,L)=>R.usage.localeCompare(L.usage,\"en\",{usage:\"sort\",caseFirst:\"upper\"})),C=v!==null?v.trim():\"General commands\";A+=`\n`,A+=`${this.format(r).header(`${C}`)}\n`;for(let{commandClass:R,usage:L}of x){let U=R.usage.description||\"undocumented\";A+=`\n`,A+=`  ${this.format(r).bold(L)}\n`,A+=`    ${Do(U,{format:this.format(r),paragraphs:!1})}`}}A+=`\n`,A+=Do(\"You can also print more details about any of these commands by calling them with the `-h,--help` flag right after the command name.\",{format:this.format(r),paragraphs:!0})}return A}error(e,r){var o,{colored:a,command:n=(o=e[PV])!==null&&o!==void 0?o:null}=r===void 0?{}:r;(!e||typeof e!=\"object\"||!(\"stack\"in e))&&(e=new Error(`Execution failed with a non-error rejection (rejected value: ${JSON.stringify(e)})`));let u=\"\",A=e.name.replace(/([a-z])([A-Z])/g,\"$1 $2\");A===\"Error\"&&(A=\"Internal Error\"),u+=`${this.format(a).error(A)}: ${e.message}\n`;let p=e.clipanion;return typeof p<\"u\"?p.type===\"usage\"&&(u+=`\n`,u+=this.usage(n)):e.stack&&(u+=`${e.stack.replace(/^.*\\n/,\"\")}\n`),u}format(e){var r;return((r=e??this.enableColors)!==null&&r!==void 0?r:t.defaultContext.colorDepth>1)?uV:AV}getUsageByRegistration(e,r){let o=this.registrations.get(e);if(typeof o>\"u\")throw new Error(\"Assertion failed: Unregistered command\");return this.getUsageByIndex(o.index,r)}getUsageByIndex(e,r){return this.builder.getBuilderByIndex(e).usage(r)}};Jo.defaultContext={env:process.env,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr,colorDepth:IV()}});var Ww,FV=Et(()=>{Yp();Ww=class extends it{async execute(){this.context.stdout.write(`${JSON.stringify(this.cli.definitions(),null,2)}\n`)}};Ww.paths=[[\"--clipanion=definitions\"]]});var Kw,RV=Et(()=>{Yp();Kw=class extends it{async execute(){this.context.stdout.write(this.cli.usage())}};Kw.paths=[[\"-h\"],[\"--help\"]]});function XD(t={}){return Ko({definition(e,r){var o;e.addProxy({name:(o=t.name)!==null&&o!==void 0?o:r,required:t.required})},transformer(e,r,o){return o.positionals.map(({value:a})=>a)}})}var xT=Et(()=>{yf()});var Vw,TV=Et(()=>{Yp();xT();Vw=class extends it{constructor(){super(...arguments),this.args=XD()}async execute(){this.context.stdout.write(`${JSON.stringify(this.cli.process(this.args).tokens,null,2)}\n`)}};Vw.paths=[[\"--clipanion=tokens\"]]});var zw,NV=Et(()=>{Yp();zw=class extends it{async execute(){var e;this.context.stdout.write(`${(e=this.cli.binaryVersion)!==null&&e!==void 0?e:\"<unknown>\"}\n`)}};zw.paths=[[\"-v\"],[\"--version\"]]});var kT={};Vt(kT,{DefinitionsCommand:()=>Ww,HelpCommand:()=>Kw,TokensCommand:()=>Vw,VersionCommand:()=>zw});var LV=Et(()=>{FV();RV();TV();NV()});function MV(t,e,r){let[o,a]=Gu(e,r??{}),{arity:n=1}=a,u=t.split(\",\"),A=new Set(u);return Ko({definition(p){p.addOption({names:u,arity:n,hidden:a?.hidden,description:a?.description,required:a.required})},transformer(p,h,E){let I,v=typeof o<\"u\"?[...o]:void 0;for(let{name:x,value:C}of E.options)A.has(x)&&(I=x,v=v??[],v.push(C));return typeof v<\"u\"?$0(I??h,v,a.validator):v}})}var OV=Et(()=>{yf()});function UV(t,e,r){let[o,a]=Gu(e,r??{}),n=t.split(\",\"),u=new Set(n);return Ko({definition(A){A.addOption({names:n,allowBinding:!1,arity:0,hidden:a.hidden,description:a.description,required:a.required})},transformer(A,p,h){let E=o;for(let{name:I,value:v}of h.options)u.has(I)&&(E=v);return E}})}var _V=Et(()=>{yf()});function HV(t,e,r){let[o,a]=Gu(e,r??{}),n=t.split(\",\"),u=new Set(n);return Ko({definition(A){A.addOption({names:n,allowBinding:!1,arity:0,hidden:a.hidden,description:a.description,required:a.required})},transformer(A,p,h){let E=o;for(let{name:I,value:v}of h.options)u.has(I)&&(E??(E=0),v?E+=1:E=0);return E}})}var qV=Et(()=>{yf()});function jV(t={}){return Ko({definition(e,r){var o;e.addRest({name:(o=t.name)!==null&&o!==void 0?o:r,required:t.required})},transformer(e,r,o){let a=u=>{let A=o.positionals[u];return A.extra===rl||A.extra===!1&&u<e.arity.leading.length},n=0;for(;n<o.positionals.length&&a(n);)n+=1;return o.positionals.splice(0,n).map(({value:u})=>u)}})}var GV=Et(()=>{VD();yf()});function Jqe(t,e,r){let[o,a]=Gu(e,r??{}),{arity:n=1}=a,u=t.split(\",\"),A=new Set(u);return Ko({definition(p){p.addOption({names:u,arity:a.tolerateBoolean?0:n,hidden:a.hidden,description:a.description,required:a.required})},transformer(p,h,E,I){let v,x=o;typeof a.env<\"u\"&&I.env[a.env]&&(v=a.env,x=I.env[a.env]);for(let{name:C,value:R}of E.options)A.has(C)&&(v=C,x=R);return typeof x==\"string\"?$0(v??h,x,a.validator):x}})}function Xqe(t={}){let{required:e=!0}=t;return Ko({definition(r,o){var a;r.addPositional({name:(a=t.name)!==null&&a!==void 0?a:o,required:t.required})},transformer(r,o,a){var n;for(let u=0;u<a.positionals.length;++u){if(a.positionals[u].extra===rl||e&&a.positionals[u].extra===!0||!e&&a.positionals[u].extra===!1)continue;let[A]=a.positionals.splice(u,1);return $0((n=t.name)!==null&&n!==void 0?n:o,A.value,t.validator)}}})}function YV(t,...e){return typeof t==\"string\"?Jqe(t,...e):Xqe(t)}var WV=Et(()=>{VD();yf()});var ge={};Vt(ge,{Array:()=>MV,Boolean:()=>UV,Counter:()=>HV,Proxy:()=>XD,Rest:()=>jV,String:()=>YV,applyValidator:()=>$0,cleanValidationError:()=>HD,formatError:()=>_w,isOptionSymbol:()=>Uw,makeCommandOption:()=>Ko,rerouteArguments:()=>Gu});var KV=Et(()=>{yf();xT();OV();_V();qV();GV();WV()});var Jw={};Vt(Jw,{Builtins:()=>kT,Cli:()=>Jo,Command:()=>it,Option:()=>ge,UsageError:()=>st,formatMarkdownish:()=>Do,run:()=>xV,runExit:()=>SV});var qt=Et(()=>{_D();yT();Yp();QV();LV();KV()});var VV=_((Rkt,Zqe)=>{Zqe.exports={name:\"dotenv\",version:\"16.3.1\",description:\"Loads environment variables from .env file\",main:\"lib/main.js\",types:\"lib/main.d.ts\",exports:{\".\":{types:\"./lib/main.d.ts\",require:\"./lib/main.js\",default:\"./lib/main.js\"},\"./config\":\"./config.js\",\"./config.js\":\"./config.js\",\"./lib/env-options\":\"./lib/env-options.js\",\"./lib/env-options.js\":\"./lib/env-options.js\",\"./lib/cli-options\":\"./lib/cli-options.js\",\"./lib/cli-options.js\":\"./lib/cli-options.js\",\"./package.json\":\"./package.json\"},scripts:{\"dts-check\":\"tsc --project tests/types/tsconfig.json\",lint:\"standard\",\"lint-readme\":\"standard-markdown\",pretest:\"npm run lint && npm run dts-check\",test:\"tap tests/*.js --100 -Rspec\",prerelease:\"npm test\",release:\"standard-version\"},repository:{type:\"git\",url:\"git://github.com/motdotla/dotenv.git\"},funding:\"https://github.com/motdotla/dotenv?sponsor=1\",keywords:[\"dotenv\",\"env\",\".env\",\"environment\",\"variables\",\"config\",\"settings\"],readmeFilename:\"README.md\",license:\"BSD-2-Clause\",devDependencies:{\"@definitelytyped/dtslint\":\"^0.0.133\",\"@types/node\":\"^18.11.3\",decache:\"^4.6.1\",sinon:\"^14.0.1\",standard:\"^17.0.0\",\"standard-markdown\":\"^7.1.0\",\"standard-version\":\"^9.5.0\",tap:\"^16.3.0\",tar:\"^6.1.11\",typescript:\"^4.8.4\"},engines:{node:\">=12\"},browser:{fs:!1}}});var ZV=_((Tkt,Ef)=>{var zV=ve(\"fs\"),FT=ve(\"path\"),$qe=ve(\"os\"),eje=ve(\"crypto\"),tje=VV(),RT=tje.version,rje=/(?:^|^)\\s*(?:export\\s+)?([\\w.-]+)(?:\\s*=\\s*?|:\\s+?)(\\s*'(?:\\\\'|[^'])*'|\\s*\"(?:\\\\\"|[^\"])*\"|\\s*`(?:\\\\`|[^`])*`|[^#\\r\\n]+)?\\s*(?:#.*)?(?:$|$)/mg;function nje(t){let e={},r=t.toString();r=r.replace(/\\r\\n?/mg,`\n`);let o;for(;(o=rje.exec(r))!=null;){let a=o[1],n=o[2]||\"\";n=n.trim();let u=n[0];n=n.replace(/^(['\"`])([\\s\\S]*)\\1$/mg,\"$2\"),u==='\"'&&(n=n.replace(/\\\\n/g,`\n`),n=n.replace(/\\\\r/g,\"\\r\")),e[a]=n}return e}function ije(t){let e=XV(t),r=ks.configDotenv({path:e});if(!r.parsed)throw new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);let o=JV(t).split(\",\"),a=o.length,n;for(let u=0;u<a;u++)try{let A=o[u].trim(),p=aje(r,A);n=ks.decrypt(p.ciphertext,p.key);break}catch(A){if(u+1>=a)throw A}return ks.parse(n)}function sje(t){console.log(`[dotenv@${RT}][INFO] ${t}`)}function oje(t){console.log(`[dotenv@${RT}][WARN] ${t}`)}function QT(t){console.log(`[dotenv@${RT}][DEBUG] ${t}`)}function JV(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:\"\"}function aje(t,e){let r;try{r=new URL(e)}catch(A){throw A.code===\"ERR_INVALID_URL\"?new Error(\"INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenv.org/vault/.env.vault?environment=development\"):A}let o=r.password;if(!o)throw new Error(\"INVALID_DOTENV_KEY: Missing key part\");let a=r.searchParams.get(\"environment\");if(!a)throw new Error(\"INVALID_DOTENV_KEY: Missing environment part\");let n=`DOTENV_VAULT_${a.toUpperCase()}`,u=t.parsed[n];if(!u)throw new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${n} in your .env.vault file.`);return{ciphertext:u,key:o}}function XV(t){let e=FT.resolve(process.cwd(),\".env\");return t&&t.path&&t.path.length>0&&(e=t.path),e.endsWith(\".vault\")?e:`${e}.vault`}function lje(t){return t[0]===\"~\"?FT.join($qe.homedir(),t.slice(1)):t}function cje(t){sje(\"Loading env from encrypted .env.vault\");let e=ks._parseVault(t),r=process.env;return t&&t.processEnv!=null&&(r=t.processEnv),ks.populate(r,e,t),{parsed:e}}function uje(t){let e=FT.resolve(process.cwd(),\".env\"),r=\"utf8\",o=!!(t&&t.debug);t&&(t.path!=null&&(e=lje(t.path)),t.encoding!=null&&(r=t.encoding));try{let a=ks.parse(zV.readFileSync(e,{encoding:r})),n=process.env;return t&&t.processEnv!=null&&(n=t.processEnv),ks.populate(n,a,t),{parsed:a}}catch(a){return o&&QT(`Failed to load ${e} ${a.message}`),{error:a}}}function Aje(t){let e=XV(t);return JV(t).length===0?ks.configDotenv(t):zV.existsSync(e)?ks._configVault(t):(oje(`You set DOTENV_KEY but you are missing a .env.vault file at ${e}. Did you forget to build it?`),ks.configDotenv(t))}function fje(t,e){let r=Buffer.from(e.slice(-64),\"hex\"),o=Buffer.from(t,\"base64\"),a=o.slice(0,12),n=o.slice(-16);o=o.slice(12,-16);try{let u=eje.createDecipheriv(\"aes-256-gcm\",r,a);return u.setAuthTag(n),`${u.update(o)}${u.final()}`}catch(u){let A=u instanceof RangeError,p=u.message===\"Invalid key length\",h=u.message===\"Unsupported state or unable to authenticate data\";if(A||p){let E=\"INVALID_DOTENV_KEY: It must be 64 characters long (or more)\";throw new Error(E)}else if(h){let E=\"DECRYPTION_FAILED: Please check your DOTENV_KEY\";throw new Error(E)}else throw console.error(\"Error: \",u.code),console.error(\"Error: \",u.message),u}}function pje(t,e,r={}){let o=!!(r&&r.debug),a=!!(r&&r.override);if(typeof e!=\"object\")throw new Error(\"OBJECT_REQUIRED: Please check the processEnv argument being passed to populate\");for(let n of Object.keys(e))Object.prototype.hasOwnProperty.call(t,n)?(a===!0&&(t[n]=e[n]),o&&QT(a===!0?`\"${n}\" is already defined and WAS overwritten`:`\"${n}\" is already defined and was NOT overwritten`)):t[n]=e[n]}var ks={configDotenv:uje,_configVault:cje,_parseVault:ije,config:Aje,decrypt:fje,parse:nje,populate:pje};Ef.exports.configDotenv=ks.configDotenv;Ef.exports._configVault=ks._configVault;Ef.exports._parseVault=ks._parseVault;Ef.exports.config=ks.config;Ef.exports.decrypt=ks.decrypt;Ef.exports.parse=ks.parse;Ef.exports.populate=ks.populate;Ef.exports=ks});var ez=_((Nkt,$V)=>{\"use strict\";$V.exports=(t,...e)=>new Promise(r=>{r(t(...e))})});var eg=_((Lkt,TT)=>{\"use strict\";var hje=ez(),tz=t=>{if(t<1)throw new TypeError(\"Expected `concurrency` to be a number from 1 and up\");let e=[],r=0,o=()=>{r--,e.length>0&&e.shift()()},a=(A,p,...h)=>{r++;let E=hje(A,...h);p(E),E.then(o,o)},n=(A,p,...h)=>{r<t?a(A,p,...h):e.push(a.bind(null,A,p,...h))},u=(A,...p)=>new Promise(h=>n(A,h,...p));return Object.defineProperties(u,{activeCount:{get:()=>r},pendingCount:{get:()=>e.length}}),u};TT.exports=tz;TT.exports.default=tz});function Ku(t){return`YN${t.toString(10).padStart(4,\"0\")}`}function ZD(t){let e=Number(t.slice(2));if(typeof wr[e]>\"u\")throw new Error(`Unknown message name: \"${t}\"`);return e}var wr,$D=Et(()=>{wr=(Me=>(Me[Me.UNNAMED=0]=\"UNNAMED\",Me[Me.EXCEPTION=1]=\"EXCEPTION\",Me[Me.MISSING_PEER_DEPENDENCY=2]=\"MISSING_PEER_DEPENDENCY\",Me[Me.CYCLIC_DEPENDENCIES=3]=\"CYCLIC_DEPENDENCIES\",Me[Me.DISABLED_BUILD_SCRIPTS=4]=\"DISABLED_BUILD_SCRIPTS\",Me[Me.BUILD_DISABLED=5]=\"BUILD_DISABLED\",Me[Me.SOFT_LINK_BUILD=6]=\"SOFT_LINK_BUILD\",Me[Me.MUST_BUILD=7]=\"MUST_BUILD\",Me[Me.MUST_REBUILD=8]=\"MUST_REBUILD\",Me[Me.BUILD_FAILED=9]=\"BUILD_FAILED\",Me[Me.RESOLVER_NOT_FOUND=10]=\"RESOLVER_NOT_FOUND\",Me[Me.FETCHER_NOT_FOUND=11]=\"FETCHER_NOT_FOUND\",Me[Me.LINKER_NOT_FOUND=12]=\"LINKER_NOT_FOUND\",Me[Me.FETCH_NOT_CACHED=13]=\"FETCH_NOT_CACHED\",Me[Me.YARN_IMPORT_FAILED=14]=\"YARN_IMPORT_FAILED\",Me[Me.REMOTE_INVALID=15]=\"REMOTE_INVALID\",Me[Me.REMOTE_NOT_FOUND=16]=\"REMOTE_NOT_FOUND\",Me[Me.RESOLUTION_PACK=17]=\"RESOLUTION_PACK\",Me[Me.CACHE_CHECKSUM_MISMATCH=18]=\"CACHE_CHECKSUM_MISMATCH\",Me[Me.UNUSED_CACHE_ENTRY=19]=\"UNUSED_CACHE_ENTRY\",Me[Me.MISSING_LOCKFILE_ENTRY=20]=\"MISSING_LOCKFILE_ENTRY\",Me[Me.WORKSPACE_NOT_FOUND=21]=\"WORKSPACE_NOT_FOUND\",Me[Me.TOO_MANY_MATCHING_WORKSPACES=22]=\"TOO_MANY_MATCHING_WORKSPACES\",Me[Me.CONSTRAINTS_MISSING_DEPENDENCY=23]=\"CONSTRAINTS_MISSING_DEPENDENCY\",Me[Me.CONSTRAINTS_INCOMPATIBLE_DEPENDENCY=24]=\"CONSTRAINTS_INCOMPATIBLE_DEPENDENCY\",Me[Me.CONSTRAINTS_EXTRANEOUS_DEPENDENCY=25]=\"CONSTRAINTS_EXTRANEOUS_DEPENDENCY\",Me[Me.CONSTRAINTS_INVALID_DEPENDENCY=26]=\"CONSTRAINTS_INVALID_DEPENDENCY\",Me[Me.CANT_SUGGEST_RESOLUTIONS=27]=\"CANT_SUGGEST_RESOLUTIONS\",Me[Me.FROZEN_LOCKFILE_EXCEPTION=28]=\"FROZEN_LOCKFILE_EXCEPTION\",Me[Me.CROSS_DRIVE_VIRTUAL_LOCAL=29]=\"CROSS_DRIVE_VIRTUAL_LOCAL\",Me[Me.FETCH_FAILED=30]=\"FETCH_FAILED\",Me[Me.DANGEROUS_NODE_MODULES=31]=\"DANGEROUS_NODE_MODULES\",Me[Me.NODE_GYP_INJECTED=32]=\"NODE_GYP_INJECTED\",Me[Me.AUTHENTICATION_NOT_FOUND=33]=\"AUTHENTICATION_NOT_FOUND\",Me[Me.INVALID_CONFIGURATION_KEY=34]=\"INVALID_CONFIGURATION_KEY\",Me[Me.NETWORK_ERROR=35]=\"NETWORK_ERROR\",Me[Me.LIFECYCLE_SCRIPT=36]=\"LIFECYCLE_SCRIPT\",Me[Me.CONSTRAINTS_MISSING_FIELD=37]=\"CONSTRAINTS_MISSING_FIELD\",Me[Me.CONSTRAINTS_INCOMPATIBLE_FIELD=38]=\"CONSTRAINTS_INCOMPATIBLE_FIELD\",Me[Me.CONSTRAINTS_EXTRANEOUS_FIELD=39]=\"CONSTRAINTS_EXTRANEOUS_FIELD\",Me[Me.CONSTRAINTS_INVALID_FIELD=40]=\"CONSTRAINTS_INVALID_FIELD\",Me[Me.AUTHENTICATION_INVALID=41]=\"AUTHENTICATION_INVALID\",Me[Me.PROLOG_UNKNOWN_ERROR=42]=\"PROLOG_UNKNOWN_ERROR\",Me[Me.PROLOG_SYNTAX_ERROR=43]=\"PROLOG_SYNTAX_ERROR\",Me[Me.PROLOG_EXISTENCE_ERROR=44]=\"PROLOG_EXISTENCE_ERROR\",Me[Me.STACK_OVERFLOW_RESOLUTION=45]=\"STACK_OVERFLOW_RESOLUTION\",Me[Me.AUTOMERGE_FAILED_TO_PARSE=46]=\"AUTOMERGE_FAILED_TO_PARSE\",Me[Me.AUTOMERGE_IMMUTABLE=47]=\"AUTOMERGE_IMMUTABLE\",Me[Me.AUTOMERGE_SUCCESS=48]=\"AUTOMERGE_SUCCESS\",Me[Me.AUTOMERGE_REQUIRED=49]=\"AUTOMERGE_REQUIRED\",Me[Me.DEPRECATED_CLI_SETTINGS=50]=\"DEPRECATED_CLI_SETTINGS\",Me[Me.PLUGIN_NAME_NOT_FOUND=51]=\"PLUGIN_NAME_NOT_FOUND\",Me[Me.INVALID_PLUGIN_REFERENCE=52]=\"INVALID_PLUGIN_REFERENCE\",Me[Me.CONSTRAINTS_AMBIGUITY=53]=\"CONSTRAINTS_AMBIGUITY\",Me[Me.CACHE_OUTSIDE_PROJECT=54]=\"CACHE_OUTSIDE_PROJECT\",Me[Me.IMMUTABLE_INSTALL=55]=\"IMMUTABLE_INSTALL\",Me[Me.IMMUTABLE_CACHE=56]=\"IMMUTABLE_CACHE\",Me[Me.INVALID_MANIFEST=57]=\"INVALID_MANIFEST\",Me[Me.PACKAGE_PREPARATION_FAILED=58]=\"PACKAGE_PREPARATION_FAILED\",Me[Me.INVALID_RANGE_PEER_DEPENDENCY=59]=\"INVALID_RANGE_PEER_DEPENDENCY\",Me[Me.INCOMPATIBLE_PEER_DEPENDENCY=60]=\"INCOMPATIBLE_PEER_DEPENDENCY\",Me[Me.DEPRECATED_PACKAGE=61]=\"DEPRECATED_PACKAGE\",Me[Me.INCOMPATIBLE_OS=62]=\"INCOMPATIBLE_OS\",Me[Me.INCOMPATIBLE_CPU=63]=\"INCOMPATIBLE_CPU\",Me[Me.FROZEN_ARTIFACT_EXCEPTION=64]=\"FROZEN_ARTIFACT_EXCEPTION\",Me[Me.TELEMETRY_NOTICE=65]=\"TELEMETRY_NOTICE\",Me[Me.PATCH_HUNK_FAILED=66]=\"PATCH_HUNK_FAILED\",Me[Me.INVALID_CONFIGURATION_VALUE=67]=\"INVALID_CONFIGURATION_VALUE\",Me[Me.UNUSED_PACKAGE_EXTENSION=68]=\"UNUSED_PACKAGE_EXTENSION\",Me[Me.REDUNDANT_PACKAGE_EXTENSION=69]=\"REDUNDANT_PACKAGE_EXTENSION\",Me[Me.AUTO_NM_SUCCESS=70]=\"AUTO_NM_SUCCESS\",Me[Me.NM_CANT_INSTALL_EXTERNAL_SOFT_LINK=71]=\"NM_CANT_INSTALL_EXTERNAL_SOFT_LINK\",Me[Me.NM_PRESERVE_SYMLINKS_REQUIRED=72]=\"NM_PRESERVE_SYMLINKS_REQUIRED\",Me[Me.UPDATE_LOCKFILE_ONLY_SKIP_LINK=73]=\"UPDATE_LOCKFILE_ONLY_SKIP_LINK\",Me[Me.NM_HARDLINKS_MODE_DOWNGRADED=74]=\"NM_HARDLINKS_MODE_DOWNGRADED\",Me[Me.PROLOG_INSTANTIATION_ERROR=75]=\"PROLOG_INSTANTIATION_ERROR\",Me[Me.INCOMPATIBLE_ARCHITECTURE=76]=\"INCOMPATIBLE_ARCHITECTURE\",Me[Me.GHOST_ARCHITECTURE=77]=\"GHOST_ARCHITECTURE\",Me[Me.RESOLUTION_MISMATCH=78]=\"RESOLUTION_MISMATCH\",Me[Me.PROLOG_LIMIT_EXCEEDED=79]=\"PROLOG_LIMIT_EXCEEDED\",Me[Me.NETWORK_DISABLED=80]=\"NETWORK_DISABLED\",Me[Me.NETWORK_UNSAFE_HTTP=81]=\"NETWORK_UNSAFE_HTTP\",Me[Me.RESOLUTION_FAILED=82]=\"RESOLUTION_FAILED\",Me[Me.AUTOMERGE_GIT_ERROR=83]=\"AUTOMERGE_GIT_ERROR\",Me[Me.CONSTRAINTS_CHECK_FAILED=84]=\"CONSTRAINTS_CHECK_FAILED\",Me[Me.UPDATED_RESOLUTION_RECORD=85]=\"UPDATED_RESOLUTION_RECORD\",Me[Me.EXPLAIN_PEER_DEPENDENCIES_CTA=86]=\"EXPLAIN_PEER_DEPENDENCIES_CTA\",Me[Me.MIGRATION_SUCCESS=87]=\"MIGRATION_SUCCESS\",Me[Me.VERSION_NOTICE=88]=\"VERSION_NOTICE\",Me[Me.TIPS_NOTICE=89]=\"TIPS_NOTICE\",Me[Me.OFFLINE_MODE_ENABLED=90]=\"OFFLINE_MODE_ENABLED\",Me))(wr||{})});var Xw=_((Okt,rz)=>{var gje=\"2.0.0\",dje=Number.MAX_SAFE_INTEGER||9007199254740991,mje=16,yje=250,Eje=[\"major\",\"premajor\",\"minor\",\"preminor\",\"patch\",\"prepatch\",\"prerelease\"];rz.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:mje,MAX_SAFE_BUILD_LENGTH:yje,MAX_SAFE_INTEGER:dje,RELEASE_TYPES:Eje,SEMVER_SPEC_VERSION:gje,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Zw=_((Ukt,nz)=>{var Cje=typeof process==\"object\"&&process.env&&process.env.NODE_DEBUG&&/\\bsemver\\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error(\"SEMVER\",...t):()=>{};nz.exports=Cje});var lm=_((Cf,iz)=>{var{MAX_SAFE_COMPONENT_LENGTH:NT,MAX_SAFE_BUILD_LENGTH:wje,MAX_LENGTH:Ije}=Xw(),Bje=Zw();Cf=iz.exports={};var vje=Cf.re=[],Dje=Cf.safeRe=[],$t=Cf.src=[],er=Cf.t={},Pje=0,LT=\"[a-zA-Z0-9-]\",bje=[[\"\\\\s\",1],[\"\\\\d\",Ije],[LT,wje]],Sje=t=>{for(let[e,r]of bje)t=t.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return t},jr=(t,e,r)=>{let o=Sje(e),a=Pje++;Bje(t,a,e),er[t]=a,$t[a]=e,vje[a]=new RegExp(e,r?\"g\":void 0),Dje[a]=new RegExp(o,r?\"g\":void 0)};jr(\"NUMERICIDENTIFIER\",\"0|[1-9]\\\\d*\");jr(\"NUMERICIDENTIFIERLOOSE\",\"\\\\d+\");jr(\"NONNUMERICIDENTIFIER\",`\\\\d*[a-zA-Z-]${LT}*`);jr(\"MAINVERSION\",`(${$t[er.NUMERICIDENTIFIER]})\\\\.(${$t[er.NUMERICIDENTIFIER]})\\\\.(${$t[er.NUMERICIDENTIFIER]})`);jr(\"MAINVERSIONLOOSE\",`(${$t[er.NUMERICIDENTIFIERLOOSE]})\\\\.(${$t[er.NUMERICIDENTIFIERLOOSE]})\\\\.(${$t[er.NUMERICIDENTIFIERLOOSE]})`);jr(\"PRERELEASEIDENTIFIER\",`(?:${$t[er.NUMERICIDENTIFIER]}|${$t[er.NONNUMERICIDENTIFIER]})`);jr(\"PRERELEASEIDENTIFIERLOOSE\",`(?:${$t[er.NUMERICIDENTIFIERLOOSE]}|${$t[er.NONNUMERICIDENTIFIER]})`);jr(\"PRERELEASE\",`(?:-(${$t[er.PRERELEASEIDENTIFIER]}(?:\\\\.${$t[er.PRERELEASEIDENTIFIER]})*))`);jr(\"PRERELEASELOOSE\",`(?:-?(${$t[er.PRERELEASEIDENTIFIERLOOSE]}(?:\\\\.${$t[er.PRERELEASEIDENTIFIERLOOSE]})*))`);jr(\"BUILDIDENTIFIER\",`${LT}+`);jr(\"BUILD\",`(?:\\\\+(${$t[er.BUILDIDENTIFIER]}(?:\\\\.${$t[er.BUILDIDENTIFIER]})*))`);jr(\"FULLPLAIN\",`v?${$t[er.MAINVERSION]}${$t[er.PRERELEASE]}?${$t[er.BUILD]}?`);jr(\"FULL\",`^${$t[er.FULLPLAIN]}$`);jr(\"LOOSEPLAIN\",`[v=\\\\s]*${$t[er.MAINVERSIONLOOSE]}${$t[er.PRERELEASELOOSE]}?${$t[er.BUILD]}?`);jr(\"LOOSE\",`^${$t[er.LOOSEPLAIN]}$`);jr(\"GTLT\",\"((?:<|>)?=?)\");jr(\"XRANGEIDENTIFIERLOOSE\",`${$t[er.NUMERICIDENTIFIERLOOSE]}|x|X|\\\\*`);jr(\"XRANGEIDENTIFIER\",`${$t[er.NUMERICIDENTIFIER]}|x|X|\\\\*`);jr(\"XRANGEPLAIN\",`[v=\\\\s]*(${$t[er.XRANGEIDENTIFIER]})(?:\\\\.(${$t[er.XRANGEIDENTIFIER]})(?:\\\\.(${$t[er.XRANGEIDENTIFIER]})(?:${$t[er.PRERELEASE]})?${$t[er.BUILD]}?)?)?`);jr(\"XRANGEPLAINLOOSE\",`[v=\\\\s]*(${$t[er.XRANGEIDENTIFIERLOOSE]})(?:\\\\.(${$t[er.XRANGEIDENTIFIERLOOSE]})(?:\\\\.(${$t[er.XRANGEIDENTIFIERLOOSE]})(?:${$t[er.PRERELEASELOOSE]})?${$t[er.BUILD]}?)?)?`);jr(\"XRANGE\",`^${$t[er.GTLT]}\\\\s*${$t[er.XRANGEPLAIN]}$`);jr(\"XRANGELOOSE\",`^${$t[er.GTLT]}\\\\s*${$t[er.XRANGEPLAINLOOSE]}$`);jr(\"COERCEPLAIN\",`(^|[^\\\\d])(\\\\d{1,${NT}})(?:\\\\.(\\\\d{1,${NT}}))?(?:\\\\.(\\\\d{1,${NT}}))?`);jr(\"COERCE\",`${$t[er.COERCEPLAIN]}(?:$|[^\\\\d])`);jr(\"COERCEFULL\",$t[er.COERCEPLAIN]+`(?:${$t[er.PRERELEASE]})?(?:${$t[er.BUILD]})?(?:$|[^\\\\d])`);jr(\"COERCERTL\",$t[er.COERCE],!0);jr(\"COERCERTLFULL\",$t[er.COERCEFULL],!0);jr(\"LONETILDE\",\"(?:~>?)\");jr(\"TILDETRIM\",`(\\\\s*)${$t[er.LONETILDE]}\\\\s+`,!0);Cf.tildeTrimReplace=\"$1~\";jr(\"TILDE\",`^${$t[er.LONETILDE]}${$t[er.XRANGEPLAIN]}$`);jr(\"TILDELOOSE\",`^${$t[er.LONETILDE]}${$t[er.XRANGEPLAINLOOSE]}$`);jr(\"LONECARET\",\"(?:\\\\^)\");jr(\"CARETTRIM\",`(\\\\s*)${$t[er.LONECARET]}\\\\s+`,!0);Cf.caretTrimReplace=\"$1^\";jr(\"CARET\",`^${$t[er.LONECARET]}${$t[er.XRANGEPLAIN]}$`);jr(\"CARETLOOSE\",`^${$t[er.LONECARET]}${$t[er.XRANGEPLAINLOOSE]}$`);jr(\"COMPARATORLOOSE\",`^${$t[er.GTLT]}\\\\s*(${$t[er.LOOSEPLAIN]})$|^$`);jr(\"COMPARATOR\",`^${$t[er.GTLT]}\\\\s*(${$t[er.FULLPLAIN]})$|^$`);jr(\"COMPARATORTRIM\",`(\\\\s*)${$t[er.GTLT]}\\\\s*(${$t[er.LOOSEPLAIN]}|${$t[er.XRANGEPLAIN]})`,!0);Cf.comparatorTrimReplace=\"$1$2$3\";jr(\"HYPHENRANGE\",`^\\\\s*(${$t[er.XRANGEPLAIN]})\\\\s+-\\\\s+(${$t[er.XRANGEPLAIN]})\\\\s*$`);jr(\"HYPHENRANGELOOSE\",`^\\\\s*(${$t[er.XRANGEPLAINLOOSE]})\\\\s+-\\\\s+(${$t[er.XRANGEPLAINLOOSE]})\\\\s*$`);jr(\"STAR\",\"(<|>)?=?\\\\s*\\\\*\");jr(\"GTE0\",\"^\\\\s*>=\\\\s*0\\\\.0\\\\.0\\\\s*$\");jr(\"GTE0PRE\",\"^\\\\s*>=\\\\s*0\\\\.0\\\\.0-0\\\\s*$\")});var eP=_((_kt,sz)=>{var xje=Object.freeze({loose:!0}),kje=Object.freeze({}),Qje=t=>t?typeof t!=\"object\"?xje:t:kje;sz.exports=Qje});var MT=_((Hkt,lz)=>{var oz=/^[0-9]+$/,az=(t,e)=>{let r=oz.test(t),o=oz.test(e);return r&&o&&(t=+t,e=+e),t===e?0:r&&!o?-1:o&&!r?1:t<e?-1:1},Fje=(t,e)=>az(e,t);lz.exports={compareIdentifiers:az,rcompareIdentifiers:Fje}});var Po=_((qkt,fz)=>{var tP=Zw(),{MAX_LENGTH:cz,MAX_SAFE_INTEGER:rP}=Xw(),{safeRe:uz,t:Az}=lm(),Rje=eP(),{compareIdentifiers:cm}=MT(),OT=class t{constructor(e,r){if(r=Rje(r),e instanceof t){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!=\"string\")throw new TypeError(`Invalid version. Must be a string. Got type \"${typeof e}\".`);if(e.length>cz)throw new TypeError(`version is longer than ${cz} characters`);tP(\"SemVer\",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let o=e.trim().match(r.loose?uz[Az.LOOSE]:uz[Az.FULL]);if(!o)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+o[1],this.minor=+o[2],this.patch=+o[3],this.major>rP||this.major<0)throw new TypeError(\"Invalid major version\");if(this.minor>rP||this.minor<0)throw new TypeError(\"Invalid minor version\");if(this.patch>rP||this.patch<0)throw new TypeError(\"Invalid patch version\");o[4]?this.prerelease=o[4].split(\".\").map(a=>{if(/^[0-9]+$/.test(a)){let n=+a;if(n>=0&&n<rP)return n}return a}):this.prerelease=[],this.build=o[5]?o[5].split(\".\"):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(\".\")}`),this.version}toString(){return this.version}compare(e){if(tP(\"SemVer.compare\",this.version,this.options,e),!(e instanceof t)){if(typeof e==\"string\"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),cm(this.major,e.major)||cm(this.minor,e.minor)||cm(this.patch,e.patch)}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let r=0;do{let o=this.prerelease[r],a=e.prerelease[r];if(tP(\"prerelease compare\",r,o,a),o===void 0&&a===void 0)return 0;if(a===void 0)return 1;if(o===void 0)return-1;if(o===a)continue;return cm(o,a)}while(++r)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let r=0;do{let o=this.build[r],a=e.build[r];if(tP(\"prerelease compare\",r,o,a),o===void 0&&a===void 0)return 0;if(a===void 0)return 1;if(o===void 0)return-1;if(o===a)continue;return cm(o,a)}while(++r)}inc(e,r,o){switch(e){case\"premajor\":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc(\"pre\",r,o);break;case\"preminor\":this.prerelease.length=0,this.patch=0,this.minor++,this.inc(\"pre\",r,o);break;case\"prepatch\":this.prerelease.length=0,this.inc(\"patch\",r,o),this.inc(\"pre\",r,o);break;case\"prerelease\":this.prerelease.length===0&&this.inc(\"patch\",r,o),this.inc(\"pre\",r,o);break;case\"major\":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case\"minor\":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case\"patch\":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case\"pre\":{let a=Number(o)?1:0;if(!r&&o===!1)throw new Error(\"invalid increment argument: identifier is empty\");if(this.prerelease.length===0)this.prerelease=[a];else{let n=this.prerelease.length;for(;--n>=0;)typeof this.prerelease[n]==\"number\"&&(this.prerelease[n]++,n=-2);if(n===-1){if(r===this.prerelease.join(\".\")&&o===!1)throw new Error(\"invalid increment argument: identifier already exists\");this.prerelease.push(a)}}if(r){let n=[r,a];o===!1&&(n=[r]),cm(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=n):this.prerelease=n}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(\".\")}`),this}};fz.exports=OT});var tg=_((jkt,hz)=>{var pz=Po(),Tje=(t,e,r=!1)=>{if(t instanceof pz)return t;try{return new pz(t,e)}catch(o){if(!r)return null;throw o}};hz.exports=Tje});var dz=_((Gkt,gz)=>{var Nje=tg(),Lje=(t,e)=>{let r=Nje(t,e);return r?r.version:null};gz.exports=Lje});var yz=_((Ykt,mz)=>{var Mje=tg(),Oje=(t,e)=>{let r=Mje(t.trim().replace(/^[=v]+/,\"\"),e);return r?r.version:null};mz.exports=Oje});var wz=_((Wkt,Cz)=>{var Ez=Po(),Uje=(t,e,r,o,a)=>{typeof r==\"string\"&&(a=o,o=r,r=void 0);try{return new Ez(t instanceof Ez?t.version:t,r).inc(e,o,a).version}catch{return null}};Cz.exports=Uje});var vz=_((Kkt,Bz)=>{var Iz=tg(),_je=(t,e)=>{let r=Iz(t,null,!0),o=Iz(e,null,!0),a=r.compare(o);if(a===0)return null;let n=a>0,u=n?r:o,A=n?o:r,p=!!u.prerelease.length;if(!!A.prerelease.length&&!p)return!A.patch&&!A.minor?\"major\":u.patch?\"patch\":u.minor?\"minor\":\"major\";let E=p?\"pre\":\"\";return r.major!==o.major?E+\"major\":r.minor!==o.minor?E+\"minor\":r.patch!==o.patch?E+\"patch\":\"prerelease\"};Bz.exports=_je});var Pz=_((Vkt,Dz)=>{var Hje=Po(),qje=(t,e)=>new Hje(t,e).major;Dz.exports=qje});var Sz=_((zkt,bz)=>{var jje=Po(),Gje=(t,e)=>new jje(t,e).minor;bz.exports=Gje});var kz=_((Jkt,xz)=>{var Yje=Po(),Wje=(t,e)=>new Yje(t,e).patch;xz.exports=Wje});var Fz=_((Xkt,Qz)=>{var Kje=tg(),Vje=(t,e)=>{let r=Kje(t,e);return r&&r.prerelease.length?r.prerelease:null};Qz.exports=Vje});var Ll=_((Zkt,Tz)=>{var Rz=Po(),zje=(t,e,r)=>new Rz(t,r).compare(new Rz(e,r));Tz.exports=zje});var Lz=_(($kt,Nz)=>{var Jje=Ll(),Xje=(t,e,r)=>Jje(e,t,r);Nz.exports=Xje});var Oz=_((eQt,Mz)=>{var Zje=Ll(),$je=(t,e)=>Zje(t,e,!0);Mz.exports=$je});var nP=_((tQt,_z)=>{var Uz=Po(),e5e=(t,e,r)=>{let o=new Uz(t,r),a=new Uz(e,r);return o.compare(a)||o.compareBuild(a)};_z.exports=e5e});var qz=_((rQt,Hz)=>{var t5e=nP(),r5e=(t,e)=>t.sort((r,o)=>t5e(r,o,e));Hz.exports=r5e});var Gz=_((nQt,jz)=>{var n5e=nP(),i5e=(t,e)=>t.sort((r,o)=>n5e(o,r,e));jz.exports=i5e});var $w=_((iQt,Yz)=>{var s5e=Ll(),o5e=(t,e,r)=>s5e(t,e,r)>0;Yz.exports=o5e});var iP=_((sQt,Wz)=>{var a5e=Ll(),l5e=(t,e,r)=>a5e(t,e,r)<0;Wz.exports=l5e});var UT=_((oQt,Kz)=>{var c5e=Ll(),u5e=(t,e,r)=>c5e(t,e,r)===0;Kz.exports=u5e});var _T=_((aQt,Vz)=>{var A5e=Ll(),f5e=(t,e,r)=>A5e(t,e,r)!==0;Vz.exports=f5e});var sP=_((lQt,zz)=>{var p5e=Ll(),h5e=(t,e,r)=>p5e(t,e,r)>=0;zz.exports=h5e});var oP=_((cQt,Jz)=>{var g5e=Ll(),d5e=(t,e,r)=>g5e(t,e,r)<=0;Jz.exports=d5e});var HT=_((uQt,Xz)=>{var m5e=UT(),y5e=_T(),E5e=$w(),C5e=sP(),w5e=iP(),I5e=oP(),B5e=(t,e,r,o)=>{switch(e){case\"===\":return typeof t==\"object\"&&(t=t.version),typeof r==\"object\"&&(r=r.version),t===r;case\"!==\":return typeof t==\"object\"&&(t=t.version),typeof r==\"object\"&&(r=r.version),t!==r;case\"\":case\"=\":case\"==\":return m5e(t,r,o);case\"!=\":return y5e(t,r,o);case\">\":return E5e(t,r,o);case\">=\":return C5e(t,r,o);case\"<\":return w5e(t,r,o);case\"<=\":return I5e(t,r,o);default:throw new TypeError(`Invalid operator: ${e}`)}};Xz.exports=B5e});var $z=_((AQt,Zz)=>{var v5e=Po(),D5e=tg(),{safeRe:aP,t:lP}=lm(),P5e=(t,e)=>{if(t instanceof v5e)return t;if(typeof t==\"number\"&&(t=String(t)),typeof t!=\"string\")return null;e=e||{};let r=null;if(!e.rtl)r=t.match(e.includePrerelease?aP[lP.COERCEFULL]:aP[lP.COERCE]);else{let p=e.includePrerelease?aP[lP.COERCERTLFULL]:aP[lP.COERCERTL],h;for(;(h=p.exec(t))&&(!r||r.index+r[0].length!==t.length);)(!r||h.index+h[0].length!==r.index+r[0].length)&&(r=h),p.lastIndex=h.index+h[1].length+h[2].length;p.lastIndex=-1}if(r===null)return null;let o=r[2],a=r[3]||\"0\",n=r[4]||\"0\",u=e.includePrerelease&&r[5]?`-${r[5]}`:\"\",A=e.includePrerelease&&r[6]?`+${r[6]}`:\"\";return D5e(`${o}.${a}.${n}${u}${A}`,e)};Zz.exports=P5e});var tJ=_((fQt,eJ)=>{\"use strict\";eJ.exports=function(t){t.prototype[Symbol.iterator]=function*(){for(let e=this.head;e;e=e.next)yield e.value}}});var cP=_((pQt,rJ)=>{\"use strict\";rJ.exports=Cn;Cn.Node=rg;Cn.create=Cn;function Cn(t){var e=this;if(e instanceof Cn||(e=new Cn),e.tail=null,e.head=null,e.length=0,t&&typeof t.forEach==\"function\")t.forEach(function(a){e.push(a)});else if(arguments.length>0)for(var r=0,o=arguments.length;r<o;r++)e.push(arguments[r]);return e}Cn.prototype.removeNode=function(t){if(t.list!==this)throw new Error(\"removing node which does not belong to this list\");var e=t.next,r=t.prev;return e&&(e.prev=r),r&&(r.next=e),t===this.head&&(this.head=e),t===this.tail&&(this.tail=r),t.list.length--,t.next=null,t.prev=null,t.list=null,e};Cn.prototype.unshiftNode=function(t){if(t!==this.head){t.list&&t.list.removeNode(t);var e=this.head;t.list=this,t.next=e,e&&(e.prev=t),this.head=t,this.tail||(this.tail=t),this.length++}};Cn.prototype.pushNode=function(t){if(t!==this.tail){t.list&&t.list.removeNode(t);var e=this.tail;t.list=this,t.prev=e,e&&(e.next=t),this.tail=t,this.head||(this.head=t),this.length++}};Cn.prototype.push=function(){for(var t=0,e=arguments.length;t<e;t++)S5e(this,arguments[t]);return this.length};Cn.prototype.unshift=function(){for(var t=0,e=arguments.length;t<e;t++)x5e(this,arguments[t]);return this.length};Cn.prototype.pop=function(){if(this.tail){var t=this.tail.value;return this.tail=this.tail.prev,this.tail?this.tail.next=null:this.head=null,this.length--,t}};Cn.prototype.shift=function(){if(this.head){var t=this.head.value;return this.head=this.head.next,this.head?this.head.prev=null:this.tail=null,this.length--,t}};Cn.prototype.forEach=function(t,e){e=e||this;for(var r=this.head,o=0;r!==null;o++)t.call(e,r.value,o,this),r=r.next};Cn.prototype.forEachReverse=function(t,e){e=e||this;for(var r=this.tail,o=this.length-1;r!==null;o--)t.call(e,r.value,o,this),r=r.prev};Cn.prototype.get=function(t){for(var e=0,r=this.head;r!==null&&e<t;e++)r=r.next;if(e===t&&r!==null)return r.value};Cn.prototype.getReverse=function(t){for(var e=0,r=this.tail;r!==null&&e<t;e++)r=r.prev;if(e===t&&r!==null)return r.value};Cn.prototype.map=function(t,e){e=e||this;for(var r=new Cn,o=this.head;o!==null;)r.push(t.call(e,o.value,this)),o=o.next;return r};Cn.prototype.mapReverse=function(t,e){e=e||this;for(var r=new Cn,o=this.tail;o!==null;)r.push(t.call(e,o.value,this)),o=o.prev;return r};Cn.prototype.reduce=function(t,e){var r,o=this.head;if(arguments.length>1)r=e;else if(this.head)o=this.head.next,r=this.head.value;else throw new TypeError(\"Reduce of empty list with no initial value\");for(var a=0;o!==null;a++)r=t(r,o.value,a),o=o.next;return r};Cn.prototype.reduceReverse=function(t,e){var r,o=this.tail;if(arguments.length>1)r=e;else if(this.tail)o=this.tail.prev,r=this.tail.value;else throw new TypeError(\"Reduce of empty list with no initial value\");for(var a=this.length-1;o!==null;a--)r=t(r,o.value,a),o=o.prev;return r};Cn.prototype.toArray=function(){for(var t=new Array(this.length),e=0,r=this.head;r!==null;e++)t[e]=r.value,r=r.next;return t};Cn.prototype.toArrayReverse=function(){for(var t=new Array(this.length),e=0,r=this.tail;r!==null;e++)t[e]=r.value,r=r.prev;return t};Cn.prototype.slice=function(t,e){e=e||this.length,e<0&&(e+=this.length),t=t||0,t<0&&(t+=this.length);var r=new Cn;if(e<t||e<0)return r;t<0&&(t=0),e>this.length&&(e=this.length);for(var o=0,a=this.head;a!==null&&o<t;o++)a=a.next;for(;a!==null&&o<e;o++,a=a.next)r.push(a.value);return r};Cn.prototype.sliceReverse=function(t,e){e=e||this.length,e<0&&(e+=this.length),t=t||0,t<0&&(t+=this.length);var r=new Cn;if(e<t||e<0)return r;t<0&&(t=0),e>this.length&&(e=this.length);for(var o=this.length,a=this.tail;a!==null&&o>e;o--)a=a.prev;for(;a!==null&&o>t;o--,a=a.prev)r.push(a.value);return r};Cn.prototype.splice=function(t,e,...r){t>this.length&&(t=this.length-1),t<0&&(t=this.length+t);for(var o=0,a=this.head;a!==null&&o<t;o++)a=a.next;for(var n=[],o=0;a&&o<e;o++)n.push(a.value),a=this.removeNode(a);a===null&&(a=this.tail),a!==this.head&&a!==this.tail&&(a=a.prev);for(var o=0;o<r.length;o++)a=b5e(this,a,r[o]);return n};Cn.prototype.reverse=function(){for(var t=this.head,e=this.tail,r=t;r!==null;r=r.prev){var o=r.prev;r.prev=r.next,r.next=o}return this.head=e,this.tail=t,this};function b5e(t,e,r){var o=e===t.head?new rg(r,null,e,t):new rg(r,e,e.next,t);return o.next===null&&(t.tail=o),o.prev===null&&(t.head=o),t.length++,o}function S5e(t,e){t.tail=new rg(e,t.tail,null,t),t.head||(t.head=t.tail),t.length++}function x5e(t,e){t.head=new rg(e,null,t.head,t),t.tail||(t.tail=t.head),t.length++}function rg(t,e,r,o){if(!(this instanceof rg))return new rg(t,e,r,o);this.list=o,this.value=t,e?(e.next=this,this.prev=e):this.prev=null,r?(r.prev=this,this.next=r):this.next=null}try{tJ()(Cn)}catch{}});var aJ=_((hQt,oJ)=>{\"use strict\";var k5e=cP(),ng=Symbol(\"max\"),If=Symbol(\"length\"),um=Symbol(\"lengthCalculator\"),tI=Symbol(\"allowStale\"),ig=Symbol(\"maxAge\"),wf=Symbol(\"dispose\"),nJ=Symbol(\"noDisposeOnSet\"),Qs=Symbol(\"lruList\"),Uc=Symbol(\"cache\"),sJ=Symbol(\"updateAgeOnGet\"),qT=()=>1,GT=class{constructor(e){if(typeof e==\"number\"&&(e={max:e}),e||(e={}),e.max&&(typeof e.max!=\"number\"||e.max<0))throw new TypeError(\"max must be a non-negative number\");let r=this[ng]=e.max||1/0,o=e.length||qT;if(this[um]=typeof o!=\"function\"?qT:o,this[tI]=e.stale||!1,e.maxAge&&typeof e.maxAge!=\"number\")throw new TypeError(\"maxAge must be a number\");this[ig]=e.maxAge||0,this[wf]=e.dispose,this[nJ]=e.noDisposeOnSet||!1,this[sJ]=e.updateAgeOnGet||!1,this.reset()}set max(e){if(typeof e!=\"number\"||e<0)throw new TypeError(\"max must be a non-negative number\");this[ng]=e||1/0,eI(this)}get max(){return this[ng]}set allowStale(e){this[tI]=!!e}get allowStale(){return this[tI]}set maxAge(e){if(typeof e!=\"number\")throw new TypeError(\"maxAge must be a non-negative number\");this[ig]=e,eI(this)}get maxAge(){return this[ig]}set lengthCalculator(e){typeof e!=\"function\"&&(e=qT),e!==this[um]&&(this[um]=e,this[If]=0,this[Qs].forEach(r=>{r.length=this[um](r.value,r.key),this[If]+=r.length})),eI(this)}get lengthCalculator(){return this[um]}get length(){return this[If]}get itemCount(){return this[Qs].length}rforEach(e,r){r=r||this;for(let o=this[Qs].tail;o!==null;){let a=o.prev;iJ(this,e,o,r),o=a}}forEach(e,r){r=r||this;for(let o=this[Qs].head;o!==null;){let a=o.next;iJ(this,e,o,r),o=a}}keys(){return this[Qs].toArray().map(e=>e.key)}values(){return this[Qs].toArray().map(e=>e.value)}reset(){this[wf]&&this[Qs]&&this[Qs].length&&this[Qs].forEach(e=>this[wf](e.key,e.value)),this[Uc]=new Map,this[Qs]=new k5e,this[If]=0}dump(){return this[Qs].map(e=>uP(this,e)?!1:{k:e.key,v:e.value,e:e.now+(e.maxAge||0)}).toArray().filter(e=>e)}dumpLru(){return this[Qs]}set(e,r,o){if(o=o||this[ig],o&&typeof o!=\"number\")throw new TypeError(\"maxAge must be a number\");let a=o?Date.now():0,n=this[um](r,e);if(this[Uc].has(e)){if(n>this[ng])return Am(this,this[Uc].get(e)),!1;let p=this[Uc].get(e).value;return this[wf]&&(this[nJ]||this[wf](e,p.value)),p.now=a,p.maxAge=o,p.value=r,this[If]+=n-p.length,p.length=n,this.get(e),eI(this),!0}let u=new YT(e,r,n,a,o);return u.length>this[ng]?(this[wf]&&this[wf](e,r),!1):(this[If]+=u.length,this[Qs].unshift(u),this[Uc].set(e,this[Qs].head),eI(this),!0)}has(e){if(!this[Uc].has(e))return!1;let r=this[Uc].get(e).value;return!uP(this,r)}get(e){return jT(this,e,!0)}peek(e){return jT(this,e,!1)}pop(){let e=this[Qs].tail;return e?(Am(this,e),e.value):null}del(e){Am(this,this[Uc].get(e))}load(e){this.reset();let r=Date.now();for(let o=e.length-1;o>=0;o--){let a=e[o],n=a.e||0;if(n===0)this.set(a.k,a.v);else{let u=n-r;u>0&&this.set(a.k,a.v,u)}}}prune(){this[Uc].forEach((e,r)=>jT(this,r,!1))}},jT=(t,e,r)=>{let o=t[Uc].get(e);if(o){let a=o.value;if(uP(t,a)){if(Am(t,o),!t[tI])return}else r&&(t[sJ]&&(o.value.now=Date.now()),t[Qs].unshiftNode(o));return a.value}},uP=(t,e)=>{if(!e||!e.maxAge&&!t[ig])return!1;let r=Date.now()-e.now;return e.maxAge?r>e.maxAge:t[ig]&&r>t[ig]},eI=t=>{if(t[If]>t[ng])for(let e=t[Qs].tail;t[If]>t[ng]&&e!==null;){let r=e.prev;Am(t,e),e=r}},Am=(t,e)=>{if(e){let r=e.value;t[wf]&&t[wf](r.key,r.value),t[If]-=r.length,t[Uc].delete(r.key),t[Qs].removeNode(e)}},YT=class{constructor(e,r,o,a,n){this.key=e,this.value=r,this.length=o,this.now=a,this.maxAge=n||0}},iJ=(t,e,r,o)=>{let a=r.value;uP(t,a)&&(Am(t,r),t[tI]||(a=void 0)),a&&e.call(o,a.value,a.key,t)};oJ.exports=GT});var Ml=_((gQt,AJ)=>{var WT=class t{constructor(e,r){if(r=F5e(r),e instanceof t)return e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease?e:new t(e.raw,r);if(e instanceof KT)return this.raw=e.value,this.set=[[e]],this.format(),this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=e.trim().split(/\\s+/).join(\" \"),this.set=this.raw.split(\"||\").map(o=>this.parseRange(o.trim())).filter(o=>o.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let o=this.set[0];if(this.set=this.set.filter(a=>!cJ(a[0])),this.set.length===0)this.set=[o];else if(this.set.length>1){for(let a of this.set)if(a.length===1&&U5e(a[0])){this.set=[a];break}}}this.format()}format(){return this.range=this.set.map(e=>e.join(\" \").trim()).join(\"||\").trim(),this.range}toString(){return this.range}parseRange(e){let o=((this.options.includePrerelease&&M5e)|(this.options.loose&&O5e))+\":\"+e,a=lJ.get(o);if(a)return a;let n=this.options.loose,u=n?ba[Xo.HYPHENRANGELOOSE]:ba[Xo.HYPHENRANGE];e=e.replace(u,z5e(this.options.includePrerelease)),ci(\"hyphen replace\",e),e=e.replace(ba[Xo.COMPARATORTRIM],T5e),ci(\"comparator trim\",e),e=e.replace(ba[Xo.TILDETRIM],N5e),ci(\"tilde trim\",e),e=e.replace(ba[Xo.CARETTRIM],L5e),ci(\"caret trim\",e);let A=e.split(\" \").map(I=>_5e(I,this.options)).join(\" \").split(/\\s+/).map(I=>V5e(I,this.options));n&&(A=A.filter(I=>(ci(\"loose invalid filter\",I,this.options),!!I.match(ba[Xo.COMPARATORLOOSE])))),ci(\"range list\",A);let p=new Map,h=A.map(I=>new KT(I,this.options));for(let I of h){if(cJ(I))return[I];p.set(I.value,I)}p.size>1&&p.has(\"\")&&p.delete(\"\");let E=[...p.values()];return lJ.set(o,E),E}intersects(e,r){if(!(e instanceof t))throw new TypeError(\"a Range is required\");return this.set.some(o=>uJ(o,r)&&e.set.some(a=>uJ(a,r)&&o.every(n=>a.every(u=>n.intersects(u,r)))))}test(e){if(!e)return!1;if(typeof e==\"string\")try{e=new R5e(e,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(J5e(this.set[r],e,this.options))return!0;return!1}};AJ.exports=WT;var Q5e=aJ(),lJ=new Q5e({max:1e3}),F5e=eP(),KT=rI(),ci=Zw(),R5e=Po(),{safeRe:ba,t:Xo,comparatorTrimReplace:T5e,tildeTrimReplace:N5e,caretTrimReplace:L5e}=lm(),{FLAG_INCLUDE_PRERELEASE:M5e,FLAG_LOOSE:O5e}=Xw(),cJ=t=>t.value===\"<0.0.0-0\",U5e=t=>t.value===\"\",uJ=(t,e)=>{let r=!0,o=t.slice(),a=o.pop();for(;r&&o.length;)r=o.every(n=>a.intersects(n,e)),a=o.pop();return r},_5e=(t,e)=>(ci(\"comp\",t,e),t=j5e(t,e),ci(\"caret\",t),t=H5e(t,e),ci(\"tildes\",t),t=Y5e(t,e),ci(\"xrange\",t),t=K5e(t,e),ci(\"stars\",t),t),Zo=t=>!t||t.toLowerCase()===\"x\"||t===\"*\",H5e=(t,e)=>t.trim().split(/\\s+/).map(r=>q5e(r,e)).join(\" \"),q5e=(t,e)=>{let r=e.loose?ba[Xo.TILDELOOSE]:ba[Xo.TILDE];return t.replace(r,(o,a,n,u,A)=>{ci(\"tilde\",t,o,a,n,u,A);let p;return Zo(a)?p=\"\":Zo(n)?p=`>=${a}.0.0 <${+a+1}.0.0-0`:Zo(u)?p=`>=${a}.${n}.0 <${a}.${+n+1}.0-0`:A?(ci(\"replaceTilde pr\",A),p=`>=${a}.${n}.${u}-${A} <${a}.${+n+1}.0-0`):p=`>=${a}.${n}.${u} <${a}.${+n+1}.0-0`,ci(\"tilde return\",p),p})},j5e=(t,e)=>t.trim().split(/\\s+/).map(r=>G5e(r,e)).join(\" \"),G5e=(t,e)=>{ci(\"caret\",t,e);let r=e.loose?ba[Xo.CARETLOOSE]:ba[Xo.CARET],o=e.includePrerelease?\"-0\":\"\";return t.replace(r,(a,n,u,A,p)=>{ci(\"caret\",t,a,n,u,A,p);let h;return Zo(n)?h=\"\":Zo(u)?h=`>=${n}.0.0${o} <${+n+1}.0.0-0`:Zo(A)?n===\"0\"?h=`>=${n}.${u}.0${o} <${n}.${+u+1}.0-0`:h=`>=${n}.${u}.0${o} <${+n+1}.0.0-0`:p?(ci(\"replaceCaret pr\",p),n===\"0\"?u===\"0\"?h=`>=${n}.${u}.${A}-${p} <${n}.${u}.${+A+1}-0`:h=`>=${n}.${u}.${A}-${p} <${n}.${+u+1}.0-0`:h=`>=${n}.${u}.${A}-${p} <${+n+1}.0.0-0`):(ci(\"no pr\"),n===\"0\"?u===\"0\"?h=`>=${n}.${u}.${A}${o} <${n}.${u}.${+A+1}-0`:h=`>=${n}.${u}.${A}${o} <${n}.${+u+1}.0-0`:h=`>=${n}.${u}.${A} <${+n+1}.0.0-0`),ci(\"caret return\",h),h})},Y5e=(t,e)=>(ci(\"replaceXRanges\",t,e),t.split(/\\s+/).map(r=>W5e(r,e)).join(\" \")),W5e=(t,e)=>{t=t.trim();let r=e.loose?ba[Xo.XRANGELOOSE]:ba[Xo.XRANGE];return t.replace(r,(o,a,n,u,A,p)=>{ci(\"xRange\",t,o,a,n,u,A,p);let h=Zo(n),E=h||Zo(u),I=E||Zo(A),v=I;return a===\"=\"&&v&&(a=\"\"),p=e.includePrerelease?\"-0\":\"\",h?a===\">\"||a===\"<\"?o=\"<0.0.0-0\":o=\"*\":a&&v?(E&&(u=0),A=0,a===\">\"?(a=\">=\",E?(n=+n+1,u=0,A=0):(u=+u+1,A=0)):a===\"<=\"&&(a=\"<\",E?n=+n+1:u=+u+1),a===\"<\"&&(p=\"-0\"),o=`${a+n}.${u}.${A}${p}`):E?o=`>=${n}.0.0${p} <${+n+1}.0.0-0`:I&&(o=`>=${n}.${u}.0${p} <${n}.${+u+1}.0-0`),ci(\"xRange return\",o),o})},K5e=(t,e)=>(ci(\"replaceStars\",t,e),t.trim().replace(ba[Xo.STAR],\"\")),V5e=(t,e)=>(ci(\"replaceGTE0\",t,e),t.trim().replace(ba[e.includePrerelease?Xo.GTE0PRE:Xo.GTE0],\"\")),z5e=t=>(e,r,o,a,n,u,A,p,h,E,I,v,x)=>(Zo(o)?r=\"\":Zo(a)?r=`>=${o}.0.0${t?\"-0\":\"\"}`:Zo(n)?r=`>=${o}.${a}.0${t?\"-0\":\"\"}`:u?r=`>=${r}`:r=`>=${r}${t?\"-0\":\"\"}`,Zo(h)?p=\"\":Zo(E)?p=`<${+h+1}.0.0-0`:Zo(I)?p=`<${h}.${+E+1}.0-0`:v?p=`<=${h}.${E}.${I}-${v}`:t?p=`<${h}.${E}.${+I+1}-0`:p=`<=${p}`,`${r} ${p}`.trim()),J5e=(t,e,r)=>{for(let o=0;o<t.length;o++)if(!t[o].test(e))return!1;if(e.prerelease.length&&!r.includePrerelease){for(let o=0;o<t.length;o++)if(ci(t[o].semver),t[o].semver!==KT.ANY&&t[o].semver.prerelease.length>0){let a=t[o].semver;if(a.major===e.major&&a.minor===e.minor&&a.patch===e.patch)return!0}return!1}return!0}});var rI=_((dQt,mJ)=>{var nI=Symbol(\"SemVer ANY\"),JT=class t{static get ANY(){return nI}constructor(e,r){if(r=fJ(r),e instanceof t){if(e.loose===!!r.loose)return e;e=e.value}e=e.trim().split(/\\s+/).join(\" \"),zT(\"comparator\",e,r),this.options=r,this.loose=!!r.loose,this.parse(e),this.semver===nI?this.value=\"\":this.value=this.operator+this.semver.version,zT(\"comp\",this)}parse(e){let r=this.options.loose?pJ[hJ.COMPARATORLOOSE]:pJ[hJ.COMPARATOR],o=e.match(r);if(!o)throw new TypeError(`Invalid comparator: ${e}`);this.operator=o[1]!==void 0?o[1]:\"\",this.operator===\"=\"&&(this.operator=\"\"),o[2]?this.semver=new gJ(o[2],this.options.loose):this.semver=nI}toString(){return this.value}test(e){if(zT(\"Comparator.test\",e,this.options.loose),this.semver===nI||e===nI)return!0;if(typeof e==\"string\")try{e=new gJ(e,this.options)}catch{return!1}return VT(e,this.operator,this.semver,this.options)}intersects(e,r){if(!(e instanceof t))throw new TypeError(\"a Comparator is required\");return this.operator===\"\"?this.value===\"\"?!0:new dJ(e.value,r).test(this.value):e.operator===\"\"?e.value===\"\"?!0:new dJ(this.value,r).test(e.semver):(r=fJ(r),r.includePrerelease&&(this.value===\"<0.0.0-0\"||e.value===\"<0.0.0-0\")||!r.includePrerelease&&(this.value.startsWith(\"<0.0.0\")||e.value.startsWith(\"<0.0.0\"))?!1:!!(this.operator.startsWith(\">\")&&e.operator.startsWith(\">\")||this.operator.startsWith(\"<\")&&e.operator.startsWith(\"<\")||this.semver.version===e.semver.version&&this.operator.includes(\"=\")&&e.operator.includes(\"=\")||VT(this.semver,\"<\",e.semver,r)&&this.operator.startsWith(\">\")&&e.operator.startsWith(\"<\")||VT(this.semver,\">\",e.semver,r)&&this.operator.startsWith(\"<\")&&e.operator.startsWith(\">\")))}};mJ.exports=JT;var fJ=eP(),{safeRe:pJ,t:hJ}=lm(),VT=HT(),zT=Zw(),gJ=Po(),dJ=Ml()});var iI=_((mQt,yJ)=>{var X5e=Ml(),Z5e=(t,e,r)=>{try{e=new X5e(e,r)}catch{return!1}return e.test(t)};yJ.exports=Z5e});var CJ=_((yQt,EJ)=>{var $5e=Ml(),eGe=(t,e)=>new $5e(t,e).set.map(r=>r.map(o=>o.value).join(\" \").trim().split(\" \"));EJ.exports=eGe});var IJ=_((EQt,wJ)=>{var tGe=Po(),rGe=Ml(),nGe=(t,e,r)=>{let o=null,a=null,n=null;try{n=new rGe(e,r)}catch{return null}return t.forEach(u=>{n.test(u)&&(!o||a.compare(u)===-1)&&(o=u,a=new tGe(o,r))}),o};wJ.exports=nGe});var vJ=_((CQt,BJ)=>{var iGe=Po(),sGe=Ml(),oGe=(t,e,r)=>{let o=null,a=null,n=null;try{n=new sGe(e,r)}catch{return null}return t.forEach(u=>{n.test(u)&&(!o||a.compare(u)===1)&&(o=u,a=new iGe(o,r))}),o};BJ.exports=oGe});var bJ=_((wQt,PJ)=>{var XT=Po(),aGe=Ml(),DJ=$w(),lGe=(t,e)=>{t=new aGe(t,e);let r=new XT(\"0.0.0\");if(t.test(r)||(r=new XT(\"0.0.0-0\"),t.test(r)))return r;r=null;for(let o=0;o<t.set.length;++o){let a=t.set[o],n=null;a.forEach(u=>{let A=new XT(u.semver.version);switch(u.operator){case\">\":A.prerelease.length===0?A.patch++:A.prerelease.push(0),A.raw=A.format();case\"\":case\">=\":(!n||DJ(A,n))&&(n=A);break;case\"<\":case\"<=\":break;default:throw new Error(`Unexpected operation: ${u.operator}`)}}),n&&(!r||DJ(r,n))&&(r=n)}return r&&t.test(r)?r:null};PJ.exports=lGe});var xJ=_((IQt,SJ)=>{var cGe=Ml(),uGe=(t,e)=>{try{return new cGe(t,e).range||\"*\"}catch{return null}};SJ.exports=uGe});var AP=_((BQt,RJ)=>{var AGe=Po(),FJ=rI(),{ANY:fGe}=FJ,pGe=Ml(),hGe=iI(),kJ=$w(),QJ=iP(),gGe=oP(),dGe=sP(),mGe=(t,e,r,o)=>{t=new AGe(t,o),e=new pGe(e,o);let a,n,u,A,p;switch(r){case\">\":a=kJ,n=gGe,u=QJ,A=\">\",p=\">=\";break;case\"<\":a=QJ,n=dGe,u=kJ,A=\"<\",p=\"<=\";break;default:throw new TypeError('Must provide a hilo val of \"<\" or \">\"')}if(hGe(t,e,o))return!1;for(let h=0;h<e.set.length;++h){let E=e.set[h],I=null,v=null;if(E.forEach(x=>{x.semver===fGe&&(x=new FJ(\">=0.0.0\")),I=I||x,v=v||x,a(x.semver,I.semver,o)?I=x:u(x.semver,v.semver,o)&&(v=x)}),I.operator===A||I.operator===p||(!v.operator||v.operator===A)&&n(t,v.semver))return!1;if(v.operator===p&&u(t,v.semver))return!1}return!0};RJ.exports=mGe});var NJ=_((vQt,TJ)=>{var yGe=AP(),EGe=(t,e,r)=>yGe(t,e,\">\",r);TJ.exports=EGe});var MJ=_((DQt,LJ)=>{var CGe=AP(),wGe=(t,e,r)=>CGe(t,e,\"<\",r);LJ.exports=wGe});var _J=_((PQt,UJ)=>{var OJ=Ml(),IGe=(t,e,r)=>(t=new OJ(t,r),e=new OJ(e,r),t.intersects(e,r));UJ.exports=IGe});var qJ=_((bQt,HJ)=>{var BGe=iI(),vGe=Ll();HJ.exports=(t,e,r)=>{let o=[],a=null,n=null,u=t.sort((E,I)=>vGe(E,I,r));for(let E of u)BGe(E,e,r)?(n=E,a||(a=E)):(n&&o.push([a,n]),n=null,a=null);a&&o.push([a,null]);let A=[];for(let[E,I]of o)E===I?A.push(E):!I&&E===u[0]?A.push(\"*\"):I?E===u[0]?A.push(`<=${I}`):A.push(`${E} - ${I}`):A.push(`>=${E}`);let p=A.join(\" || \"),h=typeof e.raw==\"string\"?e.raw:String(e);return p.length<h.length?p:e}});var VJ=_((SQt,KJ)=>{var jJ=Ml(),$T=rI(),{ANY:ZT}=$T,sI=iI(),eN=Ll(),DGe=(t,e,r={})=>{if(t===e)return!0;t=new jJ(t,r),e=new jJ(e,r);let o=!1;e:for(let a of t.set){for(let n of e.set){let u=bGe(a,n,r);if(o=o||u!==null,u)continue e}if(o)return!1}return!0},PGe=[new $T(\">=0.0.0-0\")],GJ=[new $T(\">=0.0.0\")],bGe=(t,e,r)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===ZT){if(e.length===1&&e[0].semver===ZT)return!0;r.includePrerelease?t=PGe:t=GJ}if(e.length===1&&e[0].semver===ZT){if(r.includePrerelease)return!0;e=GJ}let o=new Set,a,n;for(let x of t)x.operator===\">\"||x.operator===\">=\"?a=YJ(a,x,r):x.operator===\"<\"||x.operator===\"<=\"?n=WJ(n,x,r):o.add(x.semver);if(o.size>1)return null;let u;if(a&&n){if(u=eN(a.semver,n.semver,r),u>0)return null;if(u===0&&(a.operator!==\">=\"||n.operator!==\"<=\"))return null}for(let x of o){if(a&&!sI(x,String(a),r)||n&&!sI(x,String(n),r))return null;for(let C of e)if(!sI(x,String(C),r))return!1;return!0}let A,p,h,E,I=n&&!r.includePrerelease&&n.semver.prerelease.length?n.semver:!1,v=a&&!r.includePrerelease&&a.semver.prerelease.length?a.semver:!1;I&&I.prerelease.length===1&&n.operator===\"<\"&&I.prerelease[0]===0&&(I=!1);for(let x of e){if(E=E||x.operator===\">\"||x.operator===\">=\",h=h||x.operator===\"<\"||x.operator===\"<=\",a){if(v&&x.semver.prerelease&&x.semver.prerelease.length&&x.semver.major===v.major&&x.semver.minor===v.minor&&x.semver.patch===v.patch&&(v=!1),x.operator===\">\"||x.operator===\">=\"){if(A=YJ(a,x,r),A===x&&A!==a)return!1}else if(a.operator===\">=\"&&!sI(a.semver,String(x),r))return!1}if(n){if(I&&x.semver.prerelease&&x.semver.prerelease.length&&x.semver.major===I.major&&x.semver.minor===I.minor&&x.semver.patch===I.patch&&(I=!1),x.operator===\"<\"||x.operator===\"<=\"){if(p=WJ(n,x,r),p===x&&p!==n)return!1}else if(n.operator===\"<=\"&&!sI(n.semver,String(x),r))return!1}if(!x.operator&&(n||a)&&u!==0)return!1}return!(a&&h&&!n&&u!==0||n&&E&&!a&&u!==0||v||I)},YJ=(t,e,r)=>{if(!t)return e;let o=eN(t.semver,e.semver,r);return o>0?t:o<0||e.operator===\">\"&&t.operator===\">=\"?e:t},WJ=(t,e,r)=>{if(!t)return e;let o=eN(t.semver,e.semver,r);return o<0?t:o>0||e.operator===\"<\"&&t.operator===\"<=\"?e:t};KJ.exports=DGe});var Jn=_((xQt,XJ)=>{var tN=lm(),zJ=Xw(),SGe=Po(),JJ=MT(),xGe=tg(),kGe=dz(),QGe=yz(),FGe=wz(),RGe=vz(),TGe=Pz(),NGe=Sz(),LGe=kz(),MGe=Fz(),OGe=Ll(),UGe=Lz(),_Ge=Oz(),HGe=nP(),qGe=qz(),jGe=Gz(),GGe=$w(),YGe=iP(),WGe=UT(),KGe=_T(),VGe=sP(),zGe=oP(),JGe=HT(),XGe=$z(),ZGe=rI(),$Ge=Ml(),e9e=iI(),t9e=CJ(),r9e=IJ(),n9e=vJ(),i9e=bJ(),s9e=xJ(),o9e=AP(),a9e=NJ(),l9e=MJ(),c9e=_J(),u9e=qJ(),A9e=VJ();XJ.exports={parse:xGe,valid:kGe,clean:QGe,inc:FGe,diff:RGe,major:TGe,minor:NGe,patch:LGe,prerelease:MGe,compare:OGe,rcompare:UGe,compareLoose:_Ge,compareBuild:HGe,sort:qGe,rsort:jGe,gt:GGe,lt:YGe,eq:WGe,neq:KGe,gte:VGe,lte:zGe,cmp:JGe,coerce:XGe,Comparator:ZGe,Range:$Ge,satisfies:e9e,toComparators:t9e,maxSatisfying:r9e,minSatisfying:n9e,minVersion:i9e,validRange:s9e,outside:o9e,gtr:a9e,ltr:l9e,intersects:c9e,simplifyRange:u9e,subset:A9e,SemVer:SGe,re:tN.re,src:tN.src,tokens:tN.t,SEMVER_SPEC_VERSION:zJ.SEMVER_SPEC_VERSION,RELEASE_TYPES:zJ.RELEASE_TYPES,compareIdentifiers:JJ.compareIdentifiers,rcompareIdentifiers:JJ.rcompareIdentifiers}});var $J=_((kQt,ZJ)=>{\"use strict\";function f9e(t,e){function r(){this.constructor=t}r.prototype=e.prototype,t.prototype=new r}function sg(t,e,r,o){this.message=t,this.expected=e,this.found=r,this.location=o,this.name=\"SyntaxError\",typeof Error.captureStackTrace==\"function\"&&Error.captureStackTrace(this,sg)}f9e(sg,Error);sg.buildMessage=function(t,e){var r={literal:function(h){return'\"'+a(h.text)+'\"'},class:function(h){var E=\"\",I;for(I=0;I<h.parts.length;I++)E+=h.parts[I]instanceof Array?n(h.parts[I][0])+\"-\"+n(h.parts[I][1]):n(h.parts[I]);return\"[\"+(h.inverted?\"^\":\"\")+E+\"]\"},any:function(h){return\"any character\"},end:function(h){return\"end of input\"},other:function(h){return h.description}};function o(h){return h.charCodeAt(0).toString(16).toUpperCase()}function a(h){return h.replace(/\\\\/g,\"\\\\\\\\\").replace(/\"/g,'\\\\\"').replace(/\\0/g,\"\\\\0\").replace(/\\t/g,\"\\\\t\").replace(/\\n/g,\"\\\\n\").replace(/\\r/g,\"\\\\r\").replace(/[\\x00-\\x0F]/g,function(E){return\"\\\\x0\"+o(E)}).replace(/[\\x10-\\x1F\\x7F-\\x9F]/g,function(E){return\"\\\\x\"+o(E)})}function n(h){return h.replace(/\\\\/g,\"\\\\\\\\\").replace(/\\]/g,\"\\\\]\").replace(/\\^/g,\"\\\\^\").replace(/-/g,\"\\\\-\").replace(/\\0/g,\"\\\\0\").replace(/\\t/g,\"\\\\t\").replace(/\\n/g,\"\\\\n\").replace(/\\r/g,\"\\\\r\").replace(/[\\x00-\\x0F]/g,function(E){return\"\\\\x0\"+o(E)}).replace(/[\\x10-\\x1F\\x7F-\\x9F]/g,function(E){return\"\\\\x\"+o(E)})}function u(h){return r[h.type](h)}function A(h){var E=new Array(h.length),I,v;for(I=0;I<h.length;I++)E[I]=u(h[I]);if(E.sort(),E.length>0){for(I=1,v=1;I<E.length;I++)E[I-1]!==E[I]&&(E[v]=E[I],v++);E.length=v}switch(E.length){case 1:return E[0];case 2:return E[0]+\" or \"+E[1];default:return E.slice(0,-1).join(\", \")+\", or \"+E[E.length-1]}}function p(h){return h?'\"'+a(h)+'\"':\"end of input\"}return\"Expected \"+A(t)+\" but \"+p(e)+\" found.\"};function p9e(t,e){e=e!==void 0?e:{};var r={},o={Expression:y},a=y,n=\"|\",u=Te(\"|\",!1),A=\"&\",p=Te(\"&\",!1),h=\"^\",E=Te(\"^\",!1),I=function($,ie){return!!ie.reduce((Se,Re)=>{switch(Re[1]){case\"|\":return Se|Re[3];case\"&\":return Se&Re[3];case\"^\":return Se^Re[3]}},$)},v=\"!\",x=Te(\"!\",!1),C=function($){return!$},R=\"(\",L=Te(\"(\",!1),U=\")\",z=Te(\")\",!1),te=function($){return $},ae=/^[^ \\t\\n\\r()!|&\\^]/,le=Fe([\" \",\"\t\",`\n`,\"\\r\",\"(\",\")\",\"!\",\"|\",\"&\",\"^\"],!0,!1),ce=function($){return e.queryPattern.test($)},Ce=function($){return e.checkFn($)},de=be(\"whitespace\"),Be=/^[ \\t\\n\\r]/,Ee=Fe([\" \",\"\t\",`\n`,\"\\r\"],!1,!1),g=0,me=0,we=[{line:1,column:1}],Ae=0,ne=[],Z=0,xe;if(\"startRule\"in e){if(!(e.startRule in o))throw new Error(`Can't start parsing from rule \"`+e.startRule+'\".');a=o[e.startRule]}function Ne(){return t.substring(me,g)}function ht(){return Ue(me,g)}function H($,ie){throw ie=ie!==void 0?ie:Ue(me,g),b([be($)],t.substring(me,g),ie)}function rt($,ie){throw ie=ie!==void 0?ie:Ue(me,g),w($,ie)}function Te($,ie){return{type:\"literal\",text:$,ignoreCase:ie}}function Fe($,ie,Se){return{type:\"class\",parts:$,inverted:ie,ignoreCase:Se}}function ke(){return{type:\"any\"}}function Ye(){return{type:\"end\"}}function be($){return{type:\"other\",description:$}}function et($){var ie=we[$],Se;if(ie)return ie;for(Se=$-1;!we[Se];)Se--;for(ie=we[Se],ie={line:ie.line,column:ie.column};Se<$;)t.charCodeAt(Se)===10?(ie.line++,ie.column=1):ie.column++,Se++;return we[$]=ie,ie}function Ue($,ie){var Se=et($),Re=et(ie);return{start:{offset:$,line:Se.line,column:Se.column},end:{offset:ie,line:Re.line,column:Re.column}}}function S($){g<Ae||(g>Ae&&(Ae=g,ne=[]),ne.push($))}function w($,ie){return new sg($,null,null,ie)}function b($,ie,Se){return new sg(sg.buildMessage($,ie),$,ie,Se)}function y(){var $,ie,Se,Re,at,dt,jt,tr;if($=g,ie=F(),ie!==r){for(Se=[],Re=g,at=X(),at!==r?(t.charCodeAt(g)===124?(dt=n,g++):(dt=r,Z===0&&S(u)),dt===r&&(t.charCodeAt(g)===38?(dt=A,g++):(dt=r,Z===0&&S(p)),dt===r&&(t.charCodeAt(g)===94?(dt=h,g++):(dt=r,Z===0&&S(E)))),dt!==r?(jt=X(),jt!==r?(tr=F(),tr!==r?(at=[at,dt,jt,tr],Re=at):(g=Re,Re=r)):(g=Re,Re=r)):(g=Re,Re=r)):(g=Re,Re=r);Re!==r;)Se.push(Re),Re=g,at=X(),at!==r?(t.charCodeAt(g)===124?(dt=n,g++):(dt=r,Z===0&&S(u)),dt===r&&(t.charCodeAt(g)===38?(dt=A,g++):(dt=r,Z===0&&S(p)),dt===r&&(t.charCodeAt(g)===94?(dt=h,g++):(dt=r,Z===0&&S(E)))),dt!==r?(jt=X(),jt!==r?(tr=F(),tr!==r?(at=[at,dt,jt,tr],Re=at):(g=Re,Re=r)):(g=Re,Re=r)):(g=Re,Re=r)):(g=Re,Re=r);Se!==r?(me=$,ie=I(ie,Se),$=ie):(g=$,$=r)}else g=$,$=r;return $}function F(){var $,ie,Se,Re,at,dt;return $=g,t.charCodeAt(g)===33?(ie=v,g++):(ie=r,Z===0&&S(x)),ie!==r?(Se=F(),Se!==r?(me=$,ie=C(Se),$=ie):(g=$,$=r)):(g=$,$=r),$===r&&($=g,t.charCodeAt(g)===40?(ie=R,g++):(ie=r,Z===0&&S(L)),ie!==r?(Se=X(),Se!==r?(Re=y(),Re!==r?(at=X(),at!==r?(t.charCodeAt(g)===41?(dt=U,g++):(dt=r,Z===0&&S(z)),dt!==r?(me=$,ie=te(Re),$=ie):(g=$,$=r)):(g=$,$=r)):(g=$,$=r)):(g=$,$=r)):(g=$,$=r),$===r&&($=J())),$}function J(){var $,ie,Se,Re,at;if($=g,ie=X(),ie!==r){if(Se=g,Re=[],ae.test(t.charAt(g))?(at=t.charAt(g),g++):(at=r,Z===0&&S(le)),at!==r)for(;at!==r;)Re.push(at),ae.test(t.charAt(g))?(at=t.charAt(g),g++):(at=r,Z===0&&S(le));else Re=r;Re!==r?Se=t.substring(Se,g):Se=Re,Se!==r?(me=g,Re=ce(Se),Re?Re=void 0:Re=r,Re!==r?(me=$,ie=Ce(Se),$=ie):(g=$,$=r)):(g=$,$=r)}else g=$,$=r;return $}function X(){var $,ie;for(Z++,$=[],Be.test(t.charAt(g))?(ie=t.charAt(g),g++):(ie=r,Z===0&&S(Ee));ie!==r;)$.push(ie),Be.test(t.charAt(g))?(ie=t.charAt(g),g++):(ie=r,Z===0&&S(Ee));return Z--,$===r&&(ie=r,Z===0&&S(de)),$}if(xe=a(),xe!==r&&g===t.length)return xe;throw xe!==r&&g<t.length&&S(Ye()),b(ne,Ae<t.length?t.charAt(Ae):null,Ae<t.length?Ue(Ae,Ae+1):Ue(Ae,Ae))}ZJ.exports={SyntaxError:sg,parse:p9e}});var eX=_(fP=>{var{parse:h9e}=$J();fP.makeParser=(t=/[a-z]+/)=>(e,r)=>h9e(e,{queryPattern:t,checkFn:r});fP.parse=fP.makeParser()});var rX=_((FQt,tX)=>{\"use strict\";tX.exports={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]}});var rN=_((RQt,iX)=>{var oI=rX(),nX={};for(let t of Object.keys(oI))nX[oI[t]]=t;var Ar={rgb:{channels:3,labels:\"rgb\"},hsl:{channels:3,labels:\"hsl\"},hsv:{channels:3,labels:\"hsv\"},hwb:{channels:3,labels:\"hwb\"},cmyk:{channels:4,labels:\"cmyk\"},xyz:{channels:3,labels:\"xyz\"},lab:{channels:3,labels:\"lab\"},lch:{channels:3,labels:\"lch\"},hex:{channels:1,labels:[\"hex\"]},keyword:{channels:1,labels:[\"keyword\"]},ansi16:{channels:1,labels:[\"ansi16\"]},ansi256:{channels:1,labels:[\"ansi256\"]},hcg:{channels:3,labels:[\"h\",\"c\",\"g\"]},apple:{channels:3,labels:[\"r16\",\"g16\",\"b16\"]},gray:{channels:1,labels:[\"gray\"]}};iX.exports=Ar;for(let t of Object.keys(Ar)){if(!(\"channels\"in Ar[t]))throw new Error(\"missing channels property: \"+t);if(!(\"labels\"in Ar[t]))throw new Error(\"missing channel labels property: \"+t);if(Ar[t].labels.length!==Ar[t].channels)throw new Error(\"channel and label counts mismatch: \"+t);let{channels:e,labels:r}=Ar[t];delete Ar[t].channels,delete Ar[t].labels,Object.defineProperty(Ar[t],\"channels\",{value:e}),Object.defineProperty(Ar[t],\"labels\",{value:r})}Ar.rgb.hsl=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,a=Math.min(e,r,o),n=Math.max(e,r,o),u=n-a,A,p;n===a?A=0:e===n?A=(r-o)/u:r===n?A=2+(o-e)/u:o===n&&(A=4+(e-r)/u),A=Math.min(A*60,360),A<0&&(A+=360);let h=(a+n)/2;return n===a?p=0:h<=.5?p=u/(n+a):p=u/(2-n-a),[A,p*100,h*100]};Ar.rgb.hsv=function(t){let e,r,o,a,n,u=t[0]/255,A=t[1]/255,p=t[2]/255,h=Math.max(u,A,p),E=h-Math.min(u,A,p),I=function(v){return(h-v)/6/E+1/2};return E===0?(a=0,n=0):(n=E/h,e=I(u),r=I(A),o=I(p),u===h?a=o-r:A===h?a=1/3+e-o:p===h&&(a=2/3+r-e),a<0?a+=1:a>1&&(a-=1)),[a*360,n*100,h*100]};Ar.rgb.hwb=function(t){let e=t[0],r=t[1],o=t[2],a=Ar.rgb.hsl(t)[0],n=1/255*Math.min(e,Math.min(r,o));return o=1-1/255*Math.max(e,Math.max(r,o)),[a,n*100,o*100]};Ar.rgb.cmyk=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,a=Math.min(1-e,1-r,1-o),n=(1-e-a)/(1-a)||0,u=(1-r-a)/(1-a)||0,A=(1-o-a)/(1-a)||0;return[n*100,u*100,A*100,a*100]};function g9e(t,e){return(t[0]-e[0])**2+(t[1]-e[1])**2+(t[2]-e[2])**2}Ar.rgb.keyword=function(t){let e=nX[t];if(e)return e;let r=1/0,o;for(let a of Object.keys(oI)){let n=oI[a],u=g9e(t,n);u<r&&(r=u,o=a)}return o};Ar.keyword.rgb=function(t){return oI[t]};Ar.rgb.xyz=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255;e=e>.04045?((e+.055)/1.055)**2.4:e/12.92,r=r>.04045?((r+.055)/1.055)**2.4:r/12.92,o=o>.04045?((o+.055)/1.055)**2.4:o/12.92;let a=e*.4124+r*.3576+o*.1805,n=e*.2126+r*.7152+o*.0722,u=e*.0193+r*.1192+o*.9505;return[a*100,n*100,u*100]};Ar.rgb.lab=function(t){let e=Ar.rgb.xyz(t),r=e[0],o=e[1],a=e[2];r/=95.047,o/=100,a/=108.883,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116,a=a>.008856?a**(1/3):7.787*a+16/116;let n=116*o-16,u=500*(r-o),A=200*(o-a);return[n,u,A]};Ar.hsl.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100,a,n,u;if(r===0)return u=o*255,[u,u,u];o<.5?a=o*(1+r):a=o+r-o*r;let A=2*o-a,p=[0,0,0];for(let h=0;h<3;h++)n=e+1/3*-(h-1),n<0&&n++,n>1&&n--,6*n<1?u=A+(a-A)*6*n:2*n<1?u=a:3*n<2?u=A+(a-A)*(2/3-n)*6:u=A,p[h]=u*255;return p};Ar.hsl.hsv=function(t){let e=t[0],r=t[1]/100,o=t[2]/100,a=r,n=Math.max(o,.01);o*=2,r*=o<=1?o:2-o,a*=n<=1?n:2-n;let u=(o+r)/2,A=o===0?2*a/(n+a):2*r/(o+r);return[e,A*100,u*100]};Ar.hsv.rgb=function(t){let e=t[0]/60,r=t[1]/100,o=t[2]/100,a=Math.floor(e)%6,n=e-Math.floor(e),u=255*o*(1-r),A=255*o*(1-r*n),p=255*o*(1-r*(1-n));switch(o*=255,a){case 0:return[o,p,u];case 1:return[A,o,u];case 2:return[u,o,p];case 3:return[u,A,o];case 4:return[p,u,o];case 5:return[o,u,A]}};Ar.hsv.hsl=function(t){let e=t[0],r=t[1]/100,o=t[2]/100,a=Math.max(o,.01),n,u;u=(2-r)*o;let A=(2-r)*a;return n=r*a,n/=A<=1?A:2-A,n=n||0,u/=2,[e,n*100,u*100]};Ar.hwb.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100,a=r+o,n;a>1&&(r/=a,o/=a);let u=Math.floor(6*e),A=1-o;n=6*e-u,u&1&&(n=1-n);let p=r+n*(A-r),h,E,I;switch(u){default:case 6:case 0:h=A,E=p,I=r;break;case 1:h=p,E=A,I=r;break;case 2:h=r,E=A,I=p;break;case 3:h=r,E=p,I=A;break;case 4:h=p,E=r,I=A;break;case 5:h=A,E=r,I=p;break}return[h*255,E*255,I*255]};Ar.cmyk.rgb=function(t){let e=t[0]/100,r=t[1]/100,o=t[2]/100,a=t[3]/100,n=1-Math.min(1,e*(1-a)+a),u=1-Math.min(1,r*(1-a)+a),A=1-Math.min(1,o*(1-a)+a);return[n*255,u*255,A*255]};Ar.xyz.rgb=function(t){let e=t[0]/100,r=t[1]/100,o=t[2]/100,a,n,u;return a=e*3.2406+r*-1.5372+o*-.4986,n=e*-.9689+r*1.8758+o*.0415,u=e*.0557+r*-.204+o*1.057,a=a>.0031308?1.055*a**(1/2.4)-.055:a*12.92,n=n>.0031308?1.055*n**(1/2.4)-.055:n*12.92,u=u>.0031308?1.055*u**(1/2.4)-.055:u*12.92,a=Math.min(Math.max(0,a),1),n=Math.min(Math.max(0,n),1),u=Math.min(Math.max(0,u),1),[a*255,n*255,u*255]};Ar.xyz.lab=function(t){let e=t[0],r=t[1],o=t[2];e/=95.047,r/=100,o/=108.883,e=e>.008856?e**(1/3):7.787*e+16/116,r=r>.008856?r**(1/3):7.787*r+16/116,o=o>.008856?o**(1/3):7.787*o+16/116;let a=116*r-16,n=500*(e-r),u=200*(r-o);return[a,n,u]};Ar.lab.xyz=function(t){let e=t[0],r=t[1],o=t[2],a,n,u;n=(e+16)/116,a=r/500+n,u=n-o/200;let A=n**3,p=a**3,h=u**3;return n=A>.008856?A:(n-16/116)/7.787,a=p>.008856?p:(a-16/116)/7.787,u=h>.008856?h:(u-16/116)/7.787,a*=95.047,n*=100,u*=108.883,[a,n,u]};Ar.lab.lch=function(t){let e=t[0],r=t[1],o=t[2],a;a=Math.atan2(o,r)*360/2/Math.PI,a<0&&(a+=360);let u=Math.sqrt(r*r+o*o);return[e,u,a]};Ar.lch.lab=function(t){let e=t[0],r=t[1],a=t[2]/360*2*Math.PI,n=r*Math.cos(a),u=r*Math.sin(a);return[e,n,u]};Ar.rgb.ansi16=function(t,e=null){let[r,o,a]=t,n=e===null?Ar.rgb.hsv(t)[2]:e;if(n=Math.round(n/50),n===0)return 30;let u=30+(Math.round(a/255)<<2|Math.round(o/255)<<1|Math.round(r/255));return n===2&&(u+=60),u};Ar.hsv.ansi16=function(t){return Ar.rgb.ansi16(Ar.hsv.rgb(t),t[2])};Ar.rgb.ansi256=function(t){let e=t[0],r=t[1],o=t[2];return e===r&&r===o?e<8?16:e>248?231:Math.round((e-8)/247*24)+232:16+36*Math.round(e/255*5)+6*Math.round(r/255*5)+Math.round(o/255*5)};Ar.ansi16.rgb=function(t){let e=t%10;if(e===0||e===7)return t>50&&(e+=3.5),e=e/10.5*255,[e,e,e];let r=(~~(t>50)+1)*.5,o=(e&1)*r*255,a=(e>>1&1)*r*255,n=(e>>2&1)*r*255;return[o,a,n]};Ar.ansi256.rgb=function(t){if(t>=232){let n=(t-232)*10+8;return[n,n,n]}t-=16;let e,r=Math.floor(t/36)/5*255,o=Math.floor((e=t%36)/6)/5*255,a=e%6/5*255;return[r,o,a]};Ar.rgb.hex=function(t){let r=(((Math.round(t[0])&255)<<16)+((Math.round(t[1])&255)<<8)+(Math.round(t[2])&255)).toString(16).toUpperCase();return\"000000\".substring(r.length)+r};Ar.hex.rgb=function(t){let e=t.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i);if(!e)return[0,0,0];let r=e[0];e[0].length===3&&(r=r.split(\"\").map(A=>A+A).join(\"\"));let o=parseInt(r,16),a=o>>16&255,n=o>>8&255,u=o&255;return[a,n,u]};Ar.rgb.hcg=function(t){let e=t[0]/255,r=t[1]/255,o=t[2]/255,a=Math.max(Math.max(e,r),o),n=Math.min(Math.min(e,r),o),u=a-n,A,p;return u<1?A=n/(1-u):A=0,u<=0?p=0:a===e?p=(r-o)/u%6:a===r?p=2+(o-e)/u:p=4+(e-r)/u,p/=6,p%=1,[p*360,u*100,A*100]};Ar.hsl.hcg=function(t){let e=t[1]/100,r=t[2]/100,o=r<.5?2*e*r:2*e*(1-r),a=0;return o<1&&(a=(r-.5*o)/(1-o)),[t[0],o*100,a*100]};Ar.hsv.hcg=function(t){let e=t[1]/100,r=t[2]/100,o=e*r,a=0;return o<1&&(a=(r-o)/(1-o)),[t[0],o*100,a*100]};Ar.hcg.rgb=function(t){let e=t[0]/360,r=t[1]/100,o=t[2]/100;if(r===0)return[o*255,o*255,o*255];let a=[0,0,0],n=e%1*6,u=n%1,A=1-u,p=0;switch(Math.floor(n)){case 0:a[0]=1,a[1]=u,a[2]=0;break;case 1:a[0]=A,a[1]=1,a[2]=0;break;case 2:a[0]=0,a[1]=1,a[2]=u;break;case 3:a[0]=0,a[1]=A,a[2]=1;break;case 4:a[0]=u,a[1]=0,a[2]=1;break;default:a[0]=1,a[1]=0,a[2]=A}return p=(1-r)*o,[(r*a[0]+p)*255,(r*a[1]+p)*255,(r*a[2]+p)*255]};Ar.hcg.hsv=function(t){let e=t[1]/100,r=t[2]/100,o=e+r*(1-e),a=0;return o>0&&(a=e/o),[t[0],a*100,o*100]};Ar.hcg.hsl=function(t){let e=t[1]/100,o=t[2]/100*(1-e)+.5*e,a=0;return o>0&&o<.5?a=e/(2*o):o>=.5&&o<1&&(a=e/(2*(1-o))),[t[0],a*100,o*100]};Ar.hcg.hwb=function(t){let e=t[1]/100,r=t[2]/100,o=e+r*(1-e);return[t[0],(o-e)*100,(1-o)*100]};Ar.hwb.hcg=function(t){let e=t[1]/100,o=1-t[2]/100,a=o-e,n=0;return a<1&&(n=(o-a)/(1-a)),[t[0],a*100,n*100]};Ar.apple.rgb=function(t){return[t[0]/65535*255,t[1]/65535*255,t[2]/65535*255]};Ar.rgb.apple=function(t){return[t[0]/255*65535,t[1]/255*65535,t[2]/255*65535]};Ar.gray.rgb=function(t){return[t[0]/100*255,t[0]/100*255,t[0]/100*255]};Ar.gray.hsl=function(t){return[0,0,t[0]]};Ar.gray.hsv=Ar.gray.hsl;Ar.gray.hwb=function(t){return[0,100,t[0]]};Ar.gray.cmyk=function(t){return[0,0,0,t[0]]};Ar.gray.lab=function(t){return[t[0],0,0]};Ar.gray.hex=function(t){let e=Math.round(t[0]/100*255)&255,o=((e<<16)+(e<<8)+e).toString(16).toUpperCase();return\"000000\".substring(o.length)+o};Ar.rgb.gray=function(t){return[(t[0]+t[1]+t[2])/3/255*100]}});var oX=_((TQt,sX)=>{var pP=rN();function d9e(){let t={},e=Object.keys(pP);for(let r=e.length,o=0;o<r;o++)t[e[o]]={distance:-1,parent:null};return t}function m9e(t){let e=d9e(),r=[t];for(e[t].distance=0;r.length;){let o=r.pop(),a=Object.keys(pP[o]);for(let n=a.length,u=0;u<n;u++){let A=a[u],p=e[A];p.distance===-1&&(p.distance=e[o].distance+1,p.parent=o,r.unshift(A))}}return e}function y9e(t,e){return function(r){return e(t(r))}}function E9e(t,e){let r=[e[t].parent,t],o=pP[e[t].parent][t],a=e[t].parent;for(;e[a].parent;)r.unshift(e[a].parent),o=y9e(pP[e[a].parent][a],o),a=e[a].parent;return o.conversion=r,o}sX.exports=function(t){let e=m9e(t),r={},o=Object.keys(e);for(let a=o.length,n=0;n<a;n++){let u=o[n];e[u].parent!==null&&(r[u]=E9e(u,e))}return r}});var lX=_((NQt,aX)=>{var nN=rN(),C9e=oX(),fm={},w9e=Object.keys(nN);function I9e(t){let e=function(...r){let o=r[0];return o==null?o:(o.length>1&&(r=o),t(r))};return\"conversion\"in t&&(e.conversion=t.conversion),e}function B9e(t){let e=function(...r){let o=r[0];if(o==null)return o;o.length>1&&(r=o);let a=t(r);if(typeof a==\"object\")for(let n=a.length,u=0;u<n;u++)a[u]=Math.round(a[u]);return a};return\"conversion\"in t&&(e.conversion=t.conversion),e}w9e.forEach(t=>{fm[t]={},Object.defineProperty(fm[t],\"channels\",{value:nN[t].channels}),Object.defineProperty(fm[t],\"labels\",{value:nN[t].labels});let e=C9e(t);Object.keys(e).forEach(o=>{let a=e[o];fm[t][o]=B9e(a),fm[t][o].raw=I9e(a)})});aX.exports=fm});var aI=_((LQt,pX)=>{\"use strict\";var cX=(t,e)=>(...r)=>`\\x1B[${t(...r)+e}m`,uX=(t,e)=>(...r)=>{let o=t(...r);return`\\x1B[${38+e};5;${o}m`},AX=(t,e)=>(...r)=>{let o=t(...r);return`\\x1B[${38+e};2;${o[0]};${o[1]};${o[2]}m`},hP=t=>t,fX=(t,e,r)=>[t,e,r],pm=(t,e,r)=>{Object.defineProperty(t,e,{get:()=>{let o=r();return Object.defineProperty(t,e,{value:o,enumerable:!0,configurable:!0}),o},enumerable:!0,configurable:!0})},iN,hm=(t,e,r,o)=>{iN===void 0&&(iN=lX());let a=o?10:0,n={};for(let[u,A]of Object.entries(iN)){let p=u===\"ansi16\"?\"ansi\":u;u===e?n[p]=t(r,a):typeof A==\"object\"&&(n[p]=t(A[e],a))}return n};function v9e(){let t=new Map,e={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};e.color.gray=e.color.blackBright,e.bgColor.bgGray=e.bgColor.bgBlackBright,e.color.grey=e.color.blackBright,e.bgColor.bgGrey=e.bgColor.bgBlackBright;for(let[r,o]of Object.entries(e)){for(let[a,n]of Object.entries(o))e[a]={open:`\\x1B[${n[0]}m`,close:`\\x1B[${n[1]}m`},o[a]=e[a],t.set(n[0],n[1]);Object.defineProperty(e,r,{value:o,enumerable:!1})}return Object.defineProperty(e,\"codes\",{value:t,enumerable:!1}),e.color.close=\"\\x1B[39m\",e.bgColor.close=\"\\x1B[49m\",pm(e.color,\"ansi\",()=>hm(cX,\"ansi16\",hP,!1)),pm(e.color,\"ansi256\",()=>hm(uX,\"ansi256\",hP,!1)),pm(e.color,\"ansi16m\",()=>hm(AX,\"rgb\",fX,!1)),pm(e.bgColor,\"ansi\",()=>hm(cX,\"ansi16\",hP,!0)),pm(e.bgColor,\"ansi256\",()=>hm(uX,\"ansi256\",hP,!0)),pm(e.bgColor,\"ansi16m\",()=>hm(AX,\"rgb\",fX,!0)),e}Object.defineProperty(pX,\"exports\",{enumerable:!0,get:v9e})});var gX=_((MQt,hX)=>{\"use strict\";hX.exports=(t,e=process.argv)=>{let r=t.startsWith(\"-\")?\"\":t.length===1?\"-\":\"--\",o=e.indexOf(r+t),a=e.indexOf(\"--\");return o!==-1&&(a===-1||o<a)}});var aN=_((OQt,mX)=>{\"use strict\";var D9e=ve(\"os\"),dX=ve(\"tty\"),Ol=gX(),{env:us}=process,Wp;Ol(\"no-color\")||Ol(\"no-colors\")||Ol(\"color=false\")||Ol(\"color=never\")?Wp=0:(Ol(\"color\")||Ol(\"colors\")||Ol(\"color=true\")||Ol(\"color=always\"))&&(Wp=1);\"FORCE_COLOR\"in us&&(us.FORCE_COLOR===\"true\"?Wp=1:us.FORCE_COLOR===\"false\"?Wp=0:Wp=us.FORCE_COLOR.length===0?1:Math.min(parseInt(us.FORCE_COLOR,10),3));function sN(t){return t===0?!1:{level:t,hasBasic:!0,has256:t>=2,has16m:t>=3}}function oN(t,e){if(Wp===0)return 0;if(Ol(\"color=16m\")||Ol(\"color=full\")||Ol(\"color=truecolor\"))return 3;if(Ol(\"color=256\"))return 2;if(t&&!e&&Wp===void 0)return 0;let r=Wp||0;if(us.TERM===\"dumb\")return r;if(process.platform===\"win32\"){let o=D9e.release().split(\".\");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if(\"CI\"in us)return[\"TRAVIS\",\"CIRCLECI\",\"APPVEYOR\",\"GITLAB_CI\"].some(o=>o in us)||us.CI_NAME===\"codeship\"?1:r;if(\"TEAMCITY_VERSION\"in us)return/^(9\\.(0*[1-9]\\d*)\\.|\\d{2,}\\.)/.test(us.TEAMCITY_VERSION)?1:0;if(\"GITHUB_ACTIONS\"in us)return 1;if(us.COLORTERM===\"truecolor\")return 3;if(\"TERM_PROGRAM\"in us){let o=parseInt((us.TERM_PROGRAM_VERSION||\"\").split(\".\")[0],10);switch(us.TERM_PROGRAM){case\"iTerm.app\":return o>=3?3:2;case\"Apple_Terminal\":return 2}}return/-256(color)?$/i.test(us.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(us.TERM)||\"COLORTERM\"in us?1:r}function P9e(t){let e=oN(t,t&&t.isTTY);return sN(e)}mX.exports={supportsColor:P9e,stdout:sN(oN(!0,dX.isatty(1))),stderr:sN(oN(!0,dX.isatty(2)))}});var EX=_((UQt,yX)=>{\"use strict\";var b9e=(t,e,r)=>{let o=t.indexOf(e);if(o===-1)return t;let a=e.length,n=0,u=\"\";do u+=t.substr(n,o-n)+e+r,n=o+a,o=t.indexOf(e,n);while(o!==-1);return u+=t.substr(n),u},S9e=(t,e,r,o)=>{let a=0,n=\"\";do{let u=t[o-1]===\"\\r\";n+=t.substr(a,(u?o-1:o)-a)+e+(u?`\\r\n`:`\n`)+r,a=o+1,o=t.indexOf(`\n`,a)}while(o!==-1);return n+=t.substr(a),n};yX.exports={stringReplaceAll:b9e,stringEncaseCRLFWithFirstIndex:S9e}});var vX=_((_Qt,BX)=>{\"use strict\";var x9e=/(?:\\\\(u(?:[a-f\\d]{4}|\\{[a-f\\d]{1,6}\\})|x[a-f\\d]{2}|.))|(?:\\{(~)?(\\w+(?:\\([^)]*\\))?(?:\\.\\w+(?:\\([^)]*\\))?)*)(?:[ \\t]|(?=\\r?\\n)))|(\\})|((?:.|[\\r\\n\\f])+?)/gi,CX=/(?:^|\\.)(\\w+)(?:\\(([^)]*)\\))?/g,k9e=/^(['\"])((?:\\\\.|(?!\\1)[^\\\\])*)\\1$/,Q9e=/\\\\(u(?:[a-f\\d]{4}|\\{[a-f\\d]{1,6}\\})|x[a-f\\d]{2}|.)|([^\\\\])/gi,F9e=new Map([[\"n\",`\n`],[\"r\",\"\\r\"],[\"t\",\"\t\"],[\"b\",\"\\b\"],[\"f\",\"\\f\"],[\"v\",\"\\v\"],[\"0\",\"\\0\"],[\"\\\\\",\"\\\\\"],[\"e\",\"\\x1B\"],[\"a\",\"\\x07\"]]);function IX(t){let e=t[0]===\"u\",r=t[1]===\"{\";return e&&!r&&t.length===5||t[0]===\"x\"&&t.length===3?String.fromCharCode(parseInt(t.slice(1),16)):e&&r?String.fromCodePoint(parseInt(t.slice(2,-1),16)):F9e.get(t)||t}function R9e(t,e){let r=[],o=e.trim().split(/\\s*,\\s*/g),a;for(let n of o){let u=Number(n);if(!Number.isNaN(u))r.push(u);else if(a=n.match(k9e))r.push(a[2].replace(Q9e,(A,p,h)=>p?IX(p):h));else throw new Error(`Invalid Chalk template style argument: ${n} (in style '${t}')`)}return r}function T9e(t){CX.lastIndex=0;let e=[],r;for(;(r=CX.exec(t))!==null;){let o=r[1];if(r[2]){let a=R9e(o,r[2]);e.push([o].concat(a))}else e.push([o])}return e}function wX(t,e){let r={};for(let a of e)for(let n of a.styles)r[n[0]]=a.inverse?null:n.slice(1);let o=t;for(let[a,n]of Object.entries(r))if(Array.isArray(n)){if(!(a in o))throw new Error(`Unknown Chalk style: ${a}`);o=n.length>0?o[a](...n):o[a]}return o}BX.exports=(t,e)=>{let r=[],o=[],a=[];if(e.replace(x9e,(n,u,A,p,h,E)=>{if(u)a.push(IX(u));else if(p){let I=a.join(\"\");a=[],o.push(r.length===0?I:wX(t,r)(I)),r.push({inverse:A,styles:T9e(p)})}else if(h){if(r.length===0)throw new Error(\"Found extraneous } in Chalk template literal\");o.push(wX(t,r)(a.join(\"\"))),a=[],r.pop()}else a.push(E)}),o.push(a.join(\"\")),r.length>0){let n=`Chalk template literal is missing ${r.length} closing bracket${r.length===1?\"\":\"s\"} (\\`}\\`)`;throw new Error(n)}return o.join(\"\")}});var pN=_((HQt,SX)=>{\"use strict\";var lI=aI(),{stdout:cN,stderr:uN}=aN(),{stringReplaceAll:N9e,stringEncaseCRLFWithFirstIndex:L9e}=EX(),DX=[\"ansi\",\"ansi\",\"ansi256\",\"ansi16m\"],gm=Object.create(null),M9e=(t,e={})=>{if(e.level>3||e.level<0)throw new Error(\"The `level` option should be an integer from 0 to 3\");let r=cN?cN.level:0;t.level=e.level===void 0?r:e.level},AN=class{constructor(e){return PX(e)}},PX=t=>{let e={};return M9e(e,t),e.template=(...r)=>_9e(e.template,...r),Object.setPrototypeOf(e,gP.prototype),Object.setPrototypeOf(e.template,e),e.template.constructor=()=>{throw new Error(\"`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.\")},e.template.Instance=AN,e.template};function gP(t){return PX(t)}for(let[t,e]of Object.entries(lI))gm[t]={get(){let r=dP(this,fN(e.open,e.close,this._styler),this._isEmpty);return Object.defineProperty(this,t,{value:r}),r}};gm.visible={get(){let t=dP(this,this._styler,!0);return Object.defineProperty(this,\"visible\",{value:t}),t}};var bX=[\"rgb\",\"hex\",\"keyword\",\"hsl\",\"hsv\",\"hwb\",\"ansi\",\"ansi256\"];for(let t of bX)gm[t]={get(){let{level:e}=this;return function(...r){let o=fN(lI.color[DX[e]][t](...r),lI.color.close,this._styler);return dP(this,o,this._isEmpty)}}};for(let t of bX){let e=\"bg\"+t[0].toUpperCase()+t.slice(1);gm[e]={get(){let{level:r}=this;return function(...o){let a=fN(lI.bgColor[DX[r]][t](...o),lI.bgColor.close,this._styler);return dP(this,a,this._isEmpty)}}}}var O9e=Object.defineProperties(()=>{},{...gm,level:{enumerable:!0,get(){return this._generator.level},set(t){this._generator.level=t}}}),fN=(t,e,r)=>{let o,a;return r===void 0?(o=t,a=e):(o=r.openAll+t,a=e+r.closeAll),{open:t,close:e,openAll:o,closeAll:a,parent:r}},dP=(t,e,r)=>{let o=(...a)=>U9e(o,a.length===1?\"\"+a[0]:a.join(\" \"));return o.__proto__=O9e,o._generator=t,o._styler=e,o._isEmpty=r,o},U9e=(t,e)=>{if(t.level<=0||!e)return t._isEmpty?\"\":e;let r=t._styler;if(r===void 0)return e;let{openAll:o,closeAll:a}=r;if(e.indexOf(\"\\x1B\")!==-1)for(;r!==void 0;)e=N9e(e,r.close,r.open),r=r.parent;let n=e.indexOf(`\n`);return n!==-1&&(e=L9e(e,a,o,n)),o+e+a},lN,_9e=(t,...e)=>{let[r]=e;if(!Array.isArray(r))return e.join(\" \");let o=e.slice(1),a=[r.raw[0]];for(let n=1;n<r.length;n++)a.push(String(o[n-1]).replace(/[{}\\\\]/g,\"\\\\$&\"),String(r.raw[n]));return lN===void 0&&(lN=vX()),lN(t,a.join(\"\"))};Object.defineProperties(gP.prototype,gm);var cI=gP();cI.supportsColor=cN;cI.stderr=gP({level:uN?uN.level:0});cI.stderr.supportsColor=uN;cI.Level={None:0,Basic:1,Ansi256:2,TrueColor:3,0:\"None\",1:\"Basic\",2:\"Ansi256\",3:\"TrueColor\"};SX.exports=cI});var mP=_(Ul=>{\"use strict\";Ul.isInteger=t=>typeof t==\"number\"?Number.isInteger(t):typeof t==\"string\"&&t.trim()!==\"\"?Number.isInteger(Number(t)):!1;Ul.find=(t,e)=>t.nodes.find(r=>r.type===e);Ul.exceedsLimit=(t,e,r=1,o)=>o===!1||!Ul.isInteger(t)||!Ul.isInteger(e)?!1:(Number(e)-Number(t))/Number(r)>=o;Ul.escapeNode=(t,e=0,r)=>{let o=t.nodes[e];o&&(r&&o.type===r||o.type===\"open\"||o.type===\"close\")&&o.escaped!==!0&&(o.value=\"\\\\\"+o.value,o.escaped=!0)};Ul.encloseBrace=t=>t.type!==\"brace\"||t.commas>>0+t.ranges>>0?!1:(t.invalid=!0,!0);Ul.isInvalidBrace=t=>t.type!==\"brace\"?!1:t.invalid===!0||t.dollar?!0:!(t.commas>>0+t.ranges>>0)||t.open!==!0||t.close!==!0?(t.invalid=!0,!0):!1;Ul.isOpenOrClose=t=>t.type===\"open\"||t.type===\"close\"?!0:t.open===!0||t.close===!0;Ul.reduce=t=>t.reduce((e,r)=>(r.type===\"text\"&&e.push(r.value),r.type===\"range\"&&(r.type=\"text\"),e),[]);Ul.flatten=(...t)=>{let e=[],r=o=>{for(let a=0;a<o.length;a++){let n=o[a];Array.isArray(n)?r(n,e):n!==void 0&&e.push(n)}return e};return r(t),e}});var yP=_((jQt,kX)=>{\"use strict\";var xX=mP();kX.exports=(t,e={})=>{let r=(o,a={})=>{let n=e.escapeInvalid&&xX.isInvalidBrace(a),u=o.invalid===!0&&e.escapeInvalid===!0,A=\"\";if(o.value)return(n||u)&&xX.isOpenOrClose(o)?\"\\\\\"+o.value:o.value;if(o.value)return o.value;if(o.nodes)for(let p of o.nodes)A+=r(p);return A};return r(t)}});var FX=_((GQt,QX)=>{\"use strict\";QX.exports=function(t){return typeof t==\"number\"?t-t===0:typeof t==\"string\"&&t.trim()!==\"\"?Number.isFinite?Number.isFinite(+t):isFinite(+t):!1}});var HX=_((YQt,_X)=>{\"use strict\";var RX=FX(),og=(t,e,r)=>{if(RX(t)===!1)throw new TypeError(\"toRegexRange: expected the first argument to be a number\");if(e===void 0||t===e)return String(t);if(RX(e)===!1)throw new TypeError(\"toRegexRange: expected the second argument to be a number.\");let o={relaxZeros:!0,...r};typeof o.strictZeros==\"boolean\"&&(o.relaxZeros=o.strictZeros===!1);let a=String(o.relaxZeros),n=String(o.shorthand),u=String(o.capture),A=String(o.wrap),p=t+\":\"+e+\"=\"+a+n+u+A;if(og.cache.hasOwnProperty(p))return og.cache[p].result;let h=Math.min(t,e),E=Math.max(t,e);if(Math.abs(h-E)===1){let R=t+\"|\"+e;return o.capture?`(${R})`:o.wrap===!1?R:`(?:${R})`}let I=UX(t)||UX(e),v={min:t,max:e,a:h,b:E},x=[],C=[];if(I&&(v.isPadded=I,v.maxLen=String(v.max).length),h<0){let R=E<0?Math.abs(E):1;C=TX(R,Math.abs(h),v,o),h=v.a=0}return E>=0&&(x=TX(h,E,v,o)),v.negatives=C,v.positives=x,v.result=H9e(C,x,o),o.capture===!0?v.result=`(${v.result})`:o.wrap!==!1&&x.length+C.length>1&&(v.result=`(?:${v.result})`),og.cache[p]=v,v.result};function H9e(t,e,r){let o=hN(t,e,\"-\",!1,r)||[],a=hN(e,t,\"\",!1,r)||[],n=hN(t,e,\"-?\",!0,r)||[];return o.concat(n).concat(a).join(\"|\")}function q9e(t,e){let r=1,o=1,a=LX(t,r),n=new Set([e]);for(;t<=a&&a<=e;)n.add(a),r+=1,a=LX(t,r);for(a=MX(e+1,o)-1;t<a&&a<=e;)n.add(a),o+=1,a=MX(e+1,o)-1;return n=[...n],n.sort(Y9e),n}function j9e(t,e,r){if(t===e)return{pattern:t,count:[],digits:0};let o=G9e(t,e),a=o.length,n=\"\",u=0;for(let A=0;A<a;A++){let[p,h]=o[A];p===h?n+=p:p!==\"0\"||h!==\"9\"?n+=W9e(p,h,r):u++}return u&&(n+=r.shorthand===!0?\"\\\\d\":\"[0-9]\"),{pattern:n,count:[u],digits:a}}function TX(t,e,r,o){let a=q9e(t,e),n=[],u=t,A;for(let p=0;p<a.length;p++){let h=a[p],E=j9e(String(u),String(h),o),I=\"\";if(!r.isPadded&&A&&A.pattern===E.pattern){A.count.length>1&&A.count.pop(),A.count.push(E.count[0]),A.string=A.pattern+OX(A.count),u=h+1;continue}r.isPadded&&(I=K9e(h,r,o)),E.string=I+E.pattern+OX(E.count),n.push(E),u=h+1,A=E}return n}function hN(t,e,r,o,a){let n=[];for(let u of t){let{string:A}=u;!o&&!NX(e,\"string\",A)&&n.push(r+A),o&&NX(e,\"string\",A)&&n.push(r+A)}return n}function G9e(t,e){let r=[];for(let o=0;o<t.length;o++)r.push([t[o],e[o]]);return r}function Y9e(t,e){return t>e?1:e>t?-1:0}function NX(t,e,r){return t.some(o=>o[e]===r)}function LX(t,e){return Number(String(t).slice(0,-e)+\"9\".repeat(e))}function MX(t,e){return t-t%Math.pow(10,e)}function OX(t){let[e=0,r=\"\"]=t;return r||e>1?`{${e+(r?\",\"+r:\"\")}}`:\"\"}function W9e(t,e,r){return`[${t}${e-t===1?\"\":\"-\"}${e}]`}function UX(t){return/^-?(0+)\\d/.test(t)}function K9e(t,e,r){if(!e.isPadded)return t;let o=Math.abs(e.maxLen-String(t).length),a=r.relaxZeros!==!1;switch(o){case 0:return\"\";case 1:return a?\"0?\":\"0\";case 2:return a?\"0{0,2}\":\"00\";default:return a?`0{0,${o}}`:`0{${o}}`}}og.cache={};og.clearCache=()=>og.cache={};_X.exports=og});var mN=_((WQt,zX)=>{\"use strict\";var V9e=ve(\"util\"),GX=HX(),qX=t=>t!==null&&typeof t==\"object\"&&!Array.isArray(t),z9e=t=>e=>t===!0?Number(e):String(e),gN=t=>typeof t==\"number\"||typeof t==\"string\"&&t!==\"\",uI=t=>Number.isInteger(+t),dN=t=>{let e=`${t}`,r=-1;if(e[0]===\"-\"&&(e=e.slice(1)),e===\"0\")return!1;for(;e[++r]===\"0\";);return r>0},J9e=(t,e,r)=>typeof t==\"string\"||typeof e==\"string\"?!0:r.stringify===!0,X9e=(t,e,r)=>{if(e>0){let o=t[0]===\"-\"?\"-\":\"\";o&&(t=t.slice(1)),t=o+t.padStart(o?e-1:e,\"0\")}return r===!1?String(t):t},jX=(t,e)=>{let r=t[0]===\"-\"?\"-\":\"\";for(r&&(t=t.slice(1),e--);t.length<e;)t=\"0\"+t;return r?\"-\"+t:t},Z9e=(t,e)=>{t.negatives.sort((u,A)=>u<A?-1:u>A?1:0),t.positives.sort((u,A)=>u<A?-1:u>A?1:0);let r=e.capture?\"\":\"?:\",o=\"\",a=\"\",n;return t.positives.length&&(o=t.positives.join(\"|\")),t.negatives.length&&(a=`-(${r}${t.negatives.join(\"|\")})`),o&&a?n=`${o}|${a}`:n=o||a,e.wrap?`(${r}${n})`:n},YX=(t,e,r,o)=>{if(r)return GX(t,e,{wrap:!1,...o});let a=String.fromCharCode(t);if(t===e)return a;let n=String.fromCharCode(e);return`[${a}-${n}]`},WX=(t,e,r)=>{if(Array.isArray(t)){let o=r.wrap===!0,a=r.capture?\"\":\"?:\";return o?`(${a}${t.join(\"|\")})`:t.join(\"|\")}return GX(t,e,r)},KX=(...t)=>new RangeError(\"Invalid range arguments: \"+V9e.inspect(...t)),VX=(t,e,r)=>{if(r.strictRanges===!0)throw KX([t,e]);return[]},$9e=(t,e)=>{if(e.strictRanges===!0)throw new TypeError(`Expected step \"${t}\" to be a number`);return[]},e7e=(t,e,r=1,o={})=>{let a=Number(t),n=Number(e);if(!Number.isInteger(a)||!Number.isInteger(n)){if(o.strictRanges===!0)throw KX([t,e]);return[]}a===0&&(a=0),n===0&&(n=0);let u=a>n,A=String(t),p=String(e),h=String(r);r=Math.max(Math.abs(r),1);let E=dN(A)||dN(p)||dN(h),I=E?Math.max(A.length,p.length,h.length):0,v=E===!1&&J9e(t,e,o)===!1,x=o.transform||z9e(v);if(o.toRegex&&r===1)return YX(jX(t,I),jX(e,I),!0,o);let C={negatives:[],positives:[]},R=z=>C[z<0?\"negatives\":\"positives\"].push(Math.abs(z)),L=[],U=0;for(;u?a>=n:a<=n;)o.toRegex===!0&&r>1?R(a):L.push(X9e(x(a,U),I,v)),a=u?a-r:a+r,U++;return o.toRegex===!0?r>1?Z9e(C,o):WX(L,null,{wrap:!1,...o}):L},t7e=(t,e,r=1,o={})=>{if(!uI(t)&&t.length>1||!uI(e)&&e.length>1)return VX(t,e,o);let a=o.transform||(v=>String.fromCharCode(v)),n=`${t}`.charCodeAt(0),u=`${e}`.charCodeAt(0),A=n>u,p=Math.min(n,u),h=Math.max(n,u);if(o.toRegex&&r===1)return YX(p,h,!1,o);let E=[],I=0;for(;A?n>=u:n<=u;)E.push(a(n,I)),n=A?n-r:n+r,I++;return o.toRegex===!0?WX(E,null,{wrap:!1,options:o}):E},EP=(t,e,r,o={})=>{if(e==null&&gN(t))return[t];if(!gN(t)||!gN(e))return VX(t,e,o);if(typeof r==\"function\")return EP(t,e,1,{transform:r});if(qX(r))return EP(t,e,0,r);let a={...o};return a.capture===!0&&(a.wrap=!0),r=r||a.step||1,uI(r)?uI(t)&&uI(e)?e7e(t,e,r,a):t7e(t,e,Math.max(Math.abs(r),1),a):r!=null&&!qX(r)?$9e(r,a):EP(t,e,1,r)};zX.exports=EP});var ZX=_((KQt,XX)=>{\"use strict\";var r7e=mN(),JX=mP(),n7e=(t,e={})=>{let r=(o,a={})=>{let n=JX.isInvalidBrace(a),u=o.invalid===!0&&e.escapeInvalid===!0,A=n===!0||u===!0,p=e.escapeInvalid===!0?\"\\\\\":\"\",h=\"\";if(o.isOpen===!0||o.isClose===!0)return p+o.value;if(o.type===\"open\")return A?p+o.value:\"(\";if(o.type===\"close\")return A?p+o.value:\")\";if(o.type===\"comma\")return o.prev.type===\"comma\"?\"\":A?o.value:\"|\";if(o.value)return o.value;if(o.nodes&&o.ranges>0){let E=JX.reduce(o.nodes),I=r7e(...E,{...e,wrap:!1,toRegex:!0});if(I.length!==0)return E.length>1&&I.length>1?`(${I})`:I}if(o.nodes)for(let E of o.nodes)h+=r(E,o);return h};return r(t)};XX.exports=n7e});var tZ=_((VQt,eZ)=>{\"use strict\";var i7e=mN(),$X=yP(),dm=mP(),ag=(t=\"\",e=\"\",r=!1)=>{let o=[];if(t=[].concat(t),e=[].concat(e),!e.length)return t;if(!t.length)return r?dm.flatten(e).map(a=>`{${a}}`):e;for(let a of t)if(Array.isArray(a))for(let n of a)o.push(ag(n,e,r));else for(let n of e)r===!0&&typeof n==\"string\"&&(n=`{${n}}`),o.push(Array.isArray(n)?ag(a,n,r):a+n);return dm.flatten(o)},s7e=(t,e={})=>{let r=e.rangeLimit===void 0?1e3:e.rangeLimit,o=(a,n={})=>{a.queue=[];let u=n,A=n.queue;for(;u.type!==\"brace\"&&u.type!==\"root\"&&u.parent;)u=u.parent,A=u.queue;if(a.invalid||a.dollar){A.push(ag(A.pop(),$X(a,e)));return}if(a.type===\"brace\"&&a.invalid!==!0&&a.nodes.length===2){A.push(ag(A.pop(),[\"{}\"]));return}if(a.nodes&&a.ranges>0){let I=dm.reduce(a.nodes);if(dm.exceedsLimit(...I,e.step,r))throw new RangeError(\"expanded array length exceeds range limit. Use options.rangeLimit to increase or disable the limit.\");let v=i7e(...I,e);v.length===0&&(v=$X(a,e)),A.push(ag(A.pop(),v)),a.nodes=[];return}let p=dm.encloseBrace(a),h=a.queue,E=a;for(;E.type!==\"brace\"&&E.type!==\"root\"&&E.parent;)E=E.parent,h=E.queue;for(let I=0;I<a.nodes.length;I++){let v=a.nodes[I];if(v.type===\"comma\"&&a.type===\"brace\"){I===1&&h.push(\"\"),h.push(\"\");continue}if(v.type===\"close\"){A.push(ag(A.pop(),h,p));continue}if(v.value&&v.type!==\"open\"){h.push(ag(h.pop(),v.value));continue}v.nodes&&o(v,a)}return h};return dm.flatten(o(t))};eZ.exports=s7e});var nZ=_((zQt,rZ)=>{\"use strict\";rZ.exports={MAX_LENGTH:1024*64,CHAR_0:\"0\",CHAR_9:\"9\",CHAR_UPPERCASE_A:\"A\",CHAR_LOWERCASE_A:\"a\",CHAR_UPPERCASE_Z:\"Z\",CHAR_LOWERCASE_Z:\"z\",CHAR_LEFT_PARENTHESES:\"(\",CHAR_RIGHT_PARENTHESES:\")\",CHAR_ASTERISK:\"*\",CHAR_AMPERSAND:\"&\",CHAR_AT:\"@\",CHAR_BACKSLASH:\"\\\\\",CHAR_BACKTICK:\"`\",CHAR_CARRIAGE_RETURN:\"\\r\",CHAR_CIRCUMFLEX_ACCENT:\"^\",CHAR_COLON:\":\",CHAR_COMMA:\",\",CHAR_DOLLAR:\"$\",CHAR_DOT:\".\",CHAR_DOUBLE_QUOTE:'\"',CHAR_EQUAL:\"=\",CHAR_EXCLAMATION_MARK:\"!\",CHAR_FORM_FEED:\"\\f\",CHAR_FORWARD_SLASH:\"/\",CHAR_HASH:\"#\",CHAR_HYPHEN_MINUS:\"-\",CHAR_LEFT_ANGLE_BRACKET:\"<\",CHAR_LEFT_CURLY_BRACE:\"{\",CHAR_LEFT_SQUARE_BRACKET:\"[\",CHAR_LINE_FEED:`\n`,CHAR_NO_BREAK_SPACE:\"\\xA0\",CHAR_PERCENT:\"%\",CHAR_PLUS:\"+\",CHAR_QUESTION_MARK:\"?\",CHAR_RIGHT_ANGLE_BRACKET:\">\",CHAR_RIGHT_CURLY_BRACE:\"}\",CHAR_RIGHT_SQUARE_BRACKET:\"]\",CHAR_SEMICOLON:\";\",CHAR_SINGLE_QUOTE:\"'\",CHAR_SPACE:\" \",CHAR_TAB:\"\t\",CHAR_UNDERSCORE:\"_\",CHAR_VERTICAL_LINE:\"|\",CHAR_ZERO_WIDTH_NOBREAK_SPACE:\"\\uFEFF\"}});var lZ=_((JQt,aZ)=>{\"use strict\";var o7e=yP(),{MAX_LENGTH:iZ,CHAR_BACKSLASH:yN,CHAR_BACKTICK:a7e,CHAR_COMMA:l7e,CHAR_DOT:c7e,CHAR_LEFT_PARENTHESES:u7e,CHAR_RIGHT_PARENTHESES:A7e,CHAR_LEFT_CURLY_BRACE:f7e,CHAR_RIGHT_CURLY_BRACE:p7e,CHAR_LEFT_SQUARE_BRACKET:sZ,CHAR_RIGHT_SQUARE_BRACKET:oZ,CHAR_DOUBLE_QUOTE:h7e,CHAR_SINGLE_QUOTE:g7e,CHAR_NO_BREAK_SPACE:d7e,CHAR_ZERO_WIDTH_NOBREAK_SPACE:m7e}=nZ(),y7e=(t,e={})=>{if(typeof t!=\"string\")throw new TypeError(\"Expected a string\");let r=e||{},o=typeof r.maxLength==\"number\"?Math.min(iZ,r.maxLength):iZ;if(t.length>o)throw new SyntaxError(`Input length (${t.length}), exceeds max characters (${o})`);let a={type:\"root\",input:t,nodes:[]},n=[a],u=a,A=a,p=0,h=t.length,E=0,I=0,v,x={},C=()=>t[E++],R=L=>{if(L.type===\"text\"&&A.type===\"dot\"&&(A.type=\"text\"),A&&A.type===\"text\"&&L.type===\"text\"){A.value+=L.value;return}return u.nodes.push(L),L.parent=u,L.prev=A,A=L,L};for(R({type:\"bos\"});E<h;)if(u=n[n.length-1],v=C(),!(v===m7e||v===d7e)){if(v===yN){R({type:\"text\",value:(e.keepEscaping?v:\"\")+C()});continue}if(v===oZ){R({type:\"text\",value:\"\\\\\"+v});continue}if(v===sZ){p++;let L=!0,U;for(;E<h&&(U=C());){if(v+=U,U===sZ){p++;continue}if(U===yN){v+=C();continue}if(U===oZ&&(p--,p===0))break}R({type:\"text\",value:v});continue}if(v===u7e){u=R({type:\"paren\",nodes:[]}),n.push(u),R({type:\"text\",value:v});continue}if(v===A7e){if(u.type!==\"paren\"){R({type:\"text\",value:v});continue}u=n.pop(),R({type:\"text\",value:v}),u=n[n.length-1];continue}if(v===h7e||v===g7e||v===a7e){let L=v,U;for(e.keepQuotes!==!0&&(v=\"\");E<h&&(U=C());){if(U===yN){v+=U+C();continue}if(U===L){e.keepQuotes===!0&&(v+=U);break}v+=U}R({type:\"text\",value:v});continue}if(v===f7e){I++;let U={type:\"brace\",open:!0,close:!1,dollar:A.value&&A.value.slice(-1)===\"$\"||u.dollar===!0,depth:I,commas:0,ranges:0,nodes:[]};u=R(U),n.push(u),R({type:\"open\",value:v});continue}if(v===p7e){if(u.type!==\"brace\"){R({type:\"text\",value:v});continue}let L=\"close\";u=n.pop(),u.close=!0,R({type:L,value:v}),I--,u=n[n.length-1];continue}if(v===l7e&&I>0){if(u.ranges>0){u.ranges=0;let L=u.nodes.shift();u.nodes=[L,{type:\"text\",value:o7e(u)}]}R({type:\"comma\",value:v}),u.commas++;continue}if(v===c7e&&I>0&&u.commas===0){let L=u.nodes;if(I===0||L.length===0){R({type:\"text\",value:v});continue}if(A.type===\"dot\"){if(u.range=[],A.value+=v,A.type=\"range\",u.nodes.length!==3&&u.nodes.length!==5){u.invalid=!0,u.ranges=0,A.type=\"text\";continue}u.ranges++,u.args=[];continue}if(A.type===\"range\"){L.pop();let U=L[L.length-1];U.value+=A.value+v,A=U,u.ranges--;continue}R({type:\"dot\",value:v});continue}R({type:\"text\",value:v})}do if(u=n.pop(),u.type!==\"root\"){u.nodes.forEach(z=>{z.nodes||(z.type===\"open\"&&(z.isOpen=!0),z.type===\"close\"&&(z.isClose=!0),z.nodes||(z.type=\"text\"),z.invalid=!0)});let L=n[n.length-1],U=L.nodes.indexOf(u);L.nodes.splice(U,1,...u.nodes)}while(n.length>0);return R({type:\"eos\"}),a};aZ.exports=y7e});var AZ=_((XQt,uZ)=>{\"use strict\";var cZ=yP(),E7e=ZX(),C7e=tZ(),w7e=lZ(),nl=(t,e={})=>{let r=[];if(Array.isArray(t))for(let o of t){let a=nl.create(o,e);Array.isArray(a)?r.push(...a):r.push(a)}else r=[].concat(nl.create(t,e));return e&&e.expand===!0&&e.nodupes===!0&&(r=[...new Set(r)]),r};nl.parse=(t,e={})=>w7e(t,e);nl.stringify=(t,e={})=>cZ(typeof t==\"string\"?nl.parse(t,e):t,e);nl.compile=(t,e={})=>(typeof t==\"string\"&&(t=nl.parse(t,e)),E7e(t,e));nl.expand=(t,e={})=>{typeof t==\"string\"&&(t=nl.parse(t,e));let r=C7e(t,e);return e.noempty===!0&&(r=r.filter(Boolean)),e.nodupes===!0&&(r=[...new Set(r)]),r};nl.create=(t,e={})=>t===\"\"||t.length<3?[t]:e.expand!==!0?nl.compile(t,e):nl.expand(t,e);uZ.exports=nl});var AI=_((ZQt,dZ)=>{\"use strict\";var I7e=ve(\"path\"),Vu=\"\\\\\\\\/\",fZ=`[^${Vu}]`,Bf=\"\\\\.\",B7e=\"\\\\+\",v7e=\"\\\\?\",CP=\"\\\\/\",D7e=\"(?=.)\",pZ=\"[^/]\",EN=`(?:${CP}|$)`,hZ=`(?:^|${CP})`,CN=`${Bf}{1,2}${EN}`,P7e=`(?!${Bf})`,b7e=`(?!${hZ}${CN})`,S7e=`(?!${Bf}{0,1}${EN})`,x7e=`(?!${CN})`,k7e=`[^.${CP}]`,Q7e=`${pZ}*?`,gZ={DOT_LITERAL:Bf,PLUS_LITERAL:B7e,QMARK_LITERAL:v7e,SLASH_LITERAL:CP,ONE_CHAR:D7e,QMARK:pZ,END_ANCHOR:EN,DOTS_SLASH:CN,NO_DOT:P7e,NO_DOTS:b7e,NO_DOT_SLASH:S7e,NO_DOTS_SLASH:x7e,QMARK_NO_DOT:k7e,STAR:Q7e,START_ANCHOR:hZ},F7e={...gZ,SLASH_LITERAL:`[${Vu}]`,QMARK:fZ,STAR:`${fZ}*?`,DOTS_SLASH:`${Bf}{1,2}(?:[${Vu}]|$)`,NO_DOT:`(?!${Bf})`,NO_DOTS:`(?!(?:^|[${Vu}])${Bf}{1,2}(?:[${Vu}]|$))`,NO_DOT_SLASH:`(?!${Bf}{0,1}(?:[${Vu}]|$))`,NO_DOTS_SLASH:`(?!${Bf}{1,2}(?:[${Vu}]|$))`,QMARK_NO_DOT:`[^.${Vu}]`,START_ANCHOR:`(?:^|[${Vu}])`,END_ANCHOR:`(?:[${Vu}]|$)`},R7e={alnum:\"a-zA-Z0-9\",alpha:\"a-zA-Z\",ascii:\"\\\\x00-\\\\x7F\",blank:\" \\\\t\",cntrl:\"\\\\x00-\\\\x1F\\\\x7F\",digit:\"0-9\",graph:\"\\\\x21-\\\\x7E\",lower:\"a-z\",print:\"\\\\x20-\\\\x7E \",punct:\"\\\\-!\\\"#$%&'()\\\\*+,./:;<=>?@[\\\\]^_`{|}~\",space:\" \\\\t\\\\r\\\\n\\\\v\\\\f\",upper:\"A-Z\",word:\"A-Za-z0-9_\",xdigit:\"A-Fa-f0-9\"};dZ.exports={MAX_LENGTH:1024*64,POSIX_REGEX_SOURCE:R7e,REGEX_BACKSLASH:/\\\\(?![*+?^${}(|)[\\]])/g,REGEX_NON_SPECIAL_CHARS:/^[^@![\\].,$*+?^{}()|\\\\/]+/,REGEX_SPECIAL_CHARS:/[-*+?.^${}(|)[\\]]/,REGEX_SPECIAL_CHARS_BACKREF:/(\\\\?)((\\W)(\\3*))/g,REGEX_SPECIAL_CHARS_GLOBAL:/([-*+?.^${}(|)[\\]])/g,REGEX_REMOVE_BACKSLASH:/(?:\\[.*?[^\\\\]\\]|\\\\(?=.))/g,REPLACEMENTS:{\"***\":\"*\",\"**/**\":\"**\",\"**/**/**\":\"**\"},CHAR_0:48,CHAR_9:57,CHAR_UPPERCASE_A:65,CHAR_LOWERCASE_A:97,CHAR_UPPERCASE_Z:90,CHAR_LOWERCASE_Z:122,CHAR_LEFT_PARENTHESES:40,CHAR_RIGHT_PARENTHESES:41,CHAR_ASTERISK:42,CHAR_AMPERSAND:38,CHAR_AT:64,CHAR_BACKWARD_SLASH:92,CHAR_CARRIAGE_RETURN:13,CHAR_CIRCUMFLEX_ACCENT:94,CHAR_COLON:58,CHAR_COMMA:44,CHAR_DOT:46,CHAR_DOUBLE_QUOTE:34,CHAR_EQUAL:61,CHAR_EXCLAMATION_MARK:33,CHAR_FORM_FEED:12,CHAR_FORWARD_SLASH:47,CHAR_GRAVE_ACCENT:96,CHAR_HASH:35,CHAR_HYPHEN_MINUS:45,CHAR_LEFT_ANGLE_BRACKET:60,CHAR_LEFT_CURLY_BRACE:123,CHAR_LEFT_SQUARE_BRACKET:91,CHAR_LINE_FEED:10,CHAR_NO_BREAK_SPACE:160,CHAR_PERCENT:37,CHAR_PLUS:43,CHAR_QUESTION_MARK:63,CHAR_RIGHT_ANGLE_BRACKET:62,CHAR_RIGHT_CURLY_BRACE:125,CHAR_RIGHT_SQUARE_BRACKET:93,CHAR_SEMICOLON:59,CHAR_SINGLE_QUOTE:39,CHAR_SPACE:32,CHAR_TAB:9,CHAR_UNDERSCORE:95,CHAR_VERTICAL_LINE:124,CHAR_ZERO_WIDTH_NOBREAK_SPACE:65279,SEP:I7e.sep,extglobChars(t){return{\"!\":{type:\"negate\",open:\"(?:(?!(?:\",close:`))${t.STAR})`},\"?\":{type:\"qmark\",open:\"(?:\",close:\")?\"},\"+\":{type:\"plus\",open:\"(?:\",close:\")+\"},\"*\":{type:\"star\",open:\"(?:\",close:\")*\"},\"@\":{type:\"at\",open:\"(?:\",close:\")\"}}},globChars(t){return t===!0?F7e:gZ}}});var fI=_(Sa=>{\"use strict\";var T7e=ve(\"path\"),N7e=process.platform===\"win32\",{REGEX_BACKSLASH:L7e,REGEX_REMOVE_BACKSLASH:M7e,REGEX_SPECIAL_CHARS:O7e,REGEX_SPECIAL_CHARS_GLOBAL:U7e}=AI();Sa.isObject=t=>t!==null&&typeof t==\"object\"&&!Array.isArray(t);Sa.hasRegexChars=t=>O7e.test(t);Sa.isRegexChar=t=>t.length===1&&Sa.hasRegexChars(t);Sa.escapeRegex=t=>t.replace(U7e,\"\\\\$1\");Sa.toPosixSlashes=t=>t.replace(L7e,\"/\");Sa.removeBackslashes=t=>t.replace(M7e,e=>e===\"\\\\\"?\"\":e);Sa.supportsLookbehinds=()=>{let t=process.version.slice(1).split(\".\").map(Number);return t.length===3&&t[0]>=9||t[0]===8&&t[1]>=10};Sa.isWindows=t=>t&&typeof t.windows==\"boolean\"?t.windows:N7e===!0||T7e.sep===\"\\\\\";Sa.escapeLast=(t,e,r)=>{let o=t.lastIndexOf(e,r);return o===-1?t:t[o-1]===\"\\\\\"?Sa.escapeLast(t,e,o-1):`${t.slice(0,o)}\\\\${t.slice(o)}`};Sa.removePrefix=(t,e={})=>{let r=t;return r.startsWith(\"./\")&&(r=r.slice(2),e.prefix=\"./\"),r};Sa.wrapOutput=(t,e={},r={})=>{let o=r.contains?\"\":\"^\",a=r.contains?\"\":\"$\",n=`${o}(?:${t})${a}`;return e.negated===!0&&(n=`(?:^(?!${n}).*$)`),n}});var vZ=_((eFt,BZ)=>{\"use strict\";var mZ=fI(),{CHAR_ASTERISK:wN,CHAR_AT:_7e,CHAR_BACKWARD_SLASH:pI,CHAR_COMMA:H7e,CHAR_DOT:IN,CHAR_EXCLAMATION_MARK:BN,CHAR_FORWARD_SLASH:IZ,CHAR_LEFT_CURLY_BRACE:vN,CHAR_LEFT_PARENTHESES:DN,CHAR_LEFT_SQUARE_BRACKET:q7e,CHAR_PLUS:j7e,CHAR_QUESTION_MARK:yZ,CHAR_RIGHT_CURLY_BRACE:G7e,CHAR_RIGHT_PARENTHESES:EZ,CHAR_RIGHT_SQUARE_BRACKET:Y7e}=AI(),CZ=t=>t===IZ||t===pI,wZ=t=>{t.isPrefix!==!0&&(t.depth=t.isGlobstar?1/0:1)},W7e=(t,e)=>{let r=e||{},o=t.length-1,a=r.parts===!0||r.scanToEnd===!0,n=[],u=[],A=[],p=t,h=-1,E=0,I=0,v=!1,x=!1,C=!1,R=!1,L=!1,U=!1,z=!1,te=!1,ae=!1,le=!1,ce=0,Ce,de,Be={value:\"\",depth:0,isGlob:!1},Ee=()=>h>=o,g=()=>p.charCodeAt(h+1),me=()=>(Ce=de,p.charCodeAt(++h));for(;h<o;){de=me();let xe;if(de===pI){z=Be.backslashes=!0,de=me(),de===vN&&(U=!0);continue}if(U===!0||de===vN){for(ce++;Ee()!==!0&&(de=me());){if(de===pI){z=Be.backslashes=!0,me();continue}if(de===vN){ce++;continue}if(U!==!0&&de===IN&&(de=me())===IN){if(v=Be.isBrace=!0,C=Be.isGlob=!0,le=!0,a===!0)continue;break}if(U!==!0&&de===H7e){if(v=Be.isBrace=!0,C=Be.isGlob=!0,le=!0,a===!0)continue;break}if(de===G7e&&(ce--,ce===0)){U=!1,v=Be.isBrace=!0,le=!0;break}}if(a===!0)continue;break}if(de===IZ){if(n.push(h),u.push(Be),Be={value:\"\",depth:0,isGlob:!1},le===!0)continue;if(Ce===IN&&h===E+1){E+=2;continue}I=h+1;continue}if(r.noext!==!0&&(de===j7e||de===_7e||de===wN||de===yZ||de===BN)===!0&&g()===DN){if(C=Be.isGlob=!0,R=Be.isExtglob=!0,le=!0,de===BN&&h===E&&(ae=!0),a===!0){for(;Ee()!==!0&&(de=me());){if(de===pI){z=Be.backslashes=!0,de=me();continue}if(de===EZ){C=Be.isGlob=!0,le=!0;break}}continue}break}if(de===wN){if(Ce===wN&&(L=Be.isGlobstar=!0),C=Be.isGlob=!0,le=!0,a===!0)continue;break}if(de===yZ){if(C=Be.isGlob=!0,le=!0,a===!0)continue;break}if(de===q7e){for(;Ee()!==!0&&(xe=me());){if(xe===pI){z=Be.backslashes=!0,me();continue}if(xe===Y7e){x=Be.isBracket=!0,C=Be.isGlob=!0,le=!0;break}}if(a===!0)continue;break}if(r.nonegate!==!0&&de===BN&&h===E){te=Be.negated=!0,E++;continue}if(r.noparen!==!0&&de===DN){if(C=Be.isGlob=!0,a===!0){for(;Ee()!==!0&&(de=me());){if(de===DN){z=Be.backslashes=!0,de=me();continue}if(de===EZ){le=!0;break}}continue}break}if(C===!0){if(le=!0,a===!0)continue;break}}r.noext===!0&&(R=!1,C=!1);let we=p,Ae=\"\",ne=\"\";E>0&&(Ae=p.slice(0,E),p=p.slice(E),I-=E),we&&C===!0&&I>0?(we=p.slice(0,I),ne=p.slice(I)):C===!0?(we=\"\",ne=p):we=p,we&&we!==\"\"&&we!==\"/\"&&we!==p&&CZ(we.charCodeAt(we.length-1))&&(we=we.slice(0,-1)),r.unescape===!0&&(ne&&(ne=mZ.removeBackslashes(ne)),we&&z===!0&&(we=mZ.removeBackslashes(we)));let Z={prefix:Ae,input:t,start:E,base:we,glob:ne,isBrace:v,isBracket:x,isGlob:C,isExtglob:R,isGlobstar:L,negated:te,negatedExtglob:ae};if(r.tokens===!0&&(Z.maxDepth=0,CZ(de)||u.push(Be),Z.tokens=u),r.parts===!0||r.tokens===!0){let xe;for(let Ne=0;Ne<n.length;Ne++){let ht=xe?xe+1:E,H=n[Ne],rt=t.slice(ht,H);r.tokens&&(Ne===0&&E!==0?(u[Ne].isPrefix=!0,u[Ne].value=Ae):u[Ne].value=rt,wZ(u[Ne]),Z.maxDepth+=u[Ne].depth),(Ne!==0||rt!==\"\")&&A.push(rt),xe=H}if(xe&&xe+1<t.length){let Ne=t.slice(xe+1);A.push(Ne),r.tokens&&(u[u.length-1].value=Ne,wZ(u[u.length-1]),Z.maxDepth+=u[u.length-1].depth)}Z.slashes=n,Z.parts=A}return Z};BZ.exports=W7e});var bZ=_((tFt,PZ)=>{\"use strict\";var wP=AI(),il=fI(),{MAX_LENGTH:IP,POSIX_REGEX_SOURCE:K7e,REGEX_NON_SPECIAL_CHARS:V7e,REGEX_SPECIAL_CHARS_BACKREF:z7e,REPLACEMENTS:DZ}=wP,J7e=(t,e)=>{if(typeof e.expandRange==\"function\")return e.expandRange(...t,e);t.sort();let r=`[${t.join(\"-\")}]`;try{new RegExp(r)}catch{return t.map(a=>il.escapeRegex(a)).join(\"..\")}return r},mm=(t,e)=>`Missing ${t}: \"${e}\" - use \"\\\\\\\\${e}\" to match literal characters`,PN=(t,e)=>{if(typeof t!=\"string\")throw new TypeError(\"Expected a string\");t=DZ[t]||t;let r={...e},o=typeof r.maxLength==\"number\"?Math.min(IP,r.maxLength):IP,a=t.length;if(a>o)throw new SyntaxError(`Input length: ${a}, exceeds maximum allowed length: ${o}`);let n={type:\"bos\",value:\"\",output:r.prepend||\"\"},u=[n],A=r.capture?\"\":\"?:\",p=il.isWindows(e),h=wP.globChars(p),E=wP.extglobChars(h),{DOT_LITERAL:I,PLUS_LITERAL:v,SLASH_LITERAL:x,ONE_CHAR:C,DOTS_SLASH:R,NO_DOT:L,NO_DOT_SLASH:U,NO_DOTS_SLASH:z,QMARK:te,QMARK_NO_DOT:ae,STAR:le,START_ANCHOR:ce}=h,Ce=S=>`(${A}(?:(?!${ce}${S.dot?R:I}).)*?)`,de=r.dot?\"\":L,Be=r.dot?te:ae,Ee=r.bash===!0?Ce(r):le;r.capture&&(Ee=`(${Ee})`),typeof r.noext==\"boolean\"&&(r.noextglob=r.noext);let g={input:t,index:-1,start:0,dot:r.dot===!0,consumed:\"\",output:\"\",prefix:\"\",backtrack:!1,negated:!1,brackets:0,braces:0,parens:0,quotes:0,globstar:!1,tokens:u};t=il.removePrefix(t,g),a=t.length;let me=[],we=[],Ae=[],ne=n,Z,xe=()=>g.index===a-1,Ne=g.peek=(S=1)=>t[g.index+S],ht=g.advance=()=>t[++g.index]||\"\",H=()=>t.slice(g.index+1),rt=(S=\"\",w=0)=>{g.consumed+=S,g.index+=w},Te=S=>{g.output+=S.output!=null?S.output:S.value,rt(S.value)},Fe=()=>{let S=1;for(;Ne()===\"!\"&&(Ne(2)!==\"(\"||Ne(3)===\"?\");)ht(),g.start++,S++;return S%2===0?!1:(g.negated=!0,g.start++,!0)},ke=S=>{g[S]++,Ae.push(S)},Ye=S=>{g[S]--,Ae.pop()},be=S=>{if(ne.type===\"globstar\"){let w=g.braces>0&&(S.type===\"comma\"||S.type===\"brace\"),b=S.extglob===!0||me.length&&(S.type===\"pipe\"||S.type===\"paren\");S.type!==\"slash\"&&S.type!==\"paren\"&&!w&&!b&&(g.output=g.output.slice(0,-ne.output.length),ne.type=\"star\",ne.value=\"*\",ne.output=Ee,g.output+=ne.output)}if(me.length&&S.type!==\"paren\"&&(me[me.length-1].inner+=S.value),(S.value||S.output)&&Te(S),ne&&ne.type===\"text\"&&S.type===\"text\"){ne.value+=S.value,ne.output=(ne.output||\"\")+S.value;return}S.prev=ne,u.push(S),ne=S},et=(S,w)=>{let b={...E[w],conditions:1,inner:\"\"};b.prev=ne,b.parens=g.parens,b.output=g.output;let y=(r.capture?\"(\":\"\")+b.open;ke(\"parens\"),be({type:S,value:w,output:g.output?\"\":C}),be({type:\"paren\",extglob:!0,value:ht(),output:y}),me.push(b)},Ue=S=>{let w=S.close+(r.capture?\")\":\"\"),b;if(S.type===\"negate\"){let y=Ee;if(S.inner&&S.inner.length>1&&S.inner.includes(\"/\")&&(y=Ce(r)),(y!==Ee||xe()||/^\\)+$/.test(H()))&&(w=S.close=`)$))${y}`),S.inner.includes(\"*\")&&(b=H())&&/^\\.[^\\\\/.]+$/.test(b)){let F=PN(b,{...e,fastpaths:!1}).output;w=S.close=`)${F})${y})`}S.prev.type===\"bos\"&&(g.negatedExtglob=!0)}be({type:\"paren\",extglob:!0,value:Z,output:w}),Ye(\"parens\")};if(r.fastpaths!==!1&&!/(^[*!]|[/()[\\]{}\"])/.test(t)){let S=!1,w=t.replace(z7e,(b,y,F,J,X,$)=>J===\"\\\\\"?(S=!0,b):J===\"?\"?y?y+J+(X?te.repeat(X.length):\"\"):$===0?Be+(X?te.repeat(X.length):\"\"):te.repeat(F.length):J===\".\"?I.repeat(F.length):J===\"*\"?y?y+J+(X?Ee:\"\"):Ee:y?b:`\\\\${b}`);return S===!0&&(r.unescape===!0?w=w.replace(/\\\\/g,\"\"):w=w.replace(/\\\\+/g,b=>b.length%2===0?\"\\\\\\\\\":b?\"\\\\\":\"\")),w===t&&r.contains===!0?(g.output=t,g):(g.output=il.wrapOutput(w,g,e),g)}for(;!xe();){if(Z=ht(),Z===\"\\0\")continue;if(Z===\"\\\\\"){let b=Ne();if(b===\"/\"&&r.bash!==!0||b===\".\"||b===\";\")continue;if(!b){Z+=\"\\\\\",be({type:\"text\",value:Z});continue}let y=/^\\\\+/.exec(H()),F=0;if(y&&y[0].length>2&&(F=y[0].length,g.index+=F,F%2!==0&&(Z+=\"\\\\\")),r.unescape===!0?Z=ht():Z+=ht(),g.brackets===0){be({type:\"text\",value:Z});continue}}if(g.brackets>0&&(Z!==\"]\"||ne.value===\"[\"||ne.value===\"[^\")){if(r.posix!==!1&&Z===\":\"){let b=ne.value.slice(1);if(b.includes(\"[\")&&(ne.posix=!0,b.includes(\":\"))){let y=ne.value.lastIndexOf(\"[\"),F=ne.value.slice(0,y),J=ne.value.slice(y+2),X=K7e[J];if(X){ne.value=F+X,g.backtrack=!0,ht(),!n.output&&u.indexOf(ne)===1&&(n.output=C);continue}}}(Z===\"[\"&&Ne()!==\":\"||Z===\"-\"&&Ne()===\"]\")&&(Z=`\\\\${Z}`),Z===\"]\"&&(ne.value===\"[\"||ne.value===\"[^\")&&(Z=`\\\\${Z}`),r.posix===!0&&Z===\"!\"&&ne.value===\"[\"&&(Z=\"^\"),ne.value+=Z,Te({value:Z});continue}if(g.quotes===1&&Z!=='\"'){Z=il.escapeRegex(Z),ne.value+=Z,Te({value:Z});continue}if(Z==='\"'){g.quotes=g.quotes===1?0:1,r.keepQuotes===!0&&be({type:\"text\",value:Z});continue}if(Z===\"(\"){ke(\"parens\"),be({type:\"paren\",value:Z});continue}if(Z===\")\"){if(g.parens===0&&r.strictBrackets===!0)throw new SyntaxError(mm(\"opening\",\"(\"));let b=me[me.length-1];if(b&&g.parens===b.parens+1){Ue(me.pop());continue}be({type:\"paren\",value:Z,output:g.parens?\")\":\"\\\\)\"}),Ye(\"parens\");continue}if(Z===\"[\"){if(r.nobracket===!0||!H().includes(\"]\")){if(r.nobracket!==!0&&r.strictBrackets===!0)throw new SyntaxError(mm(\"closing\",\"]\"));Z=`\\\\${Z}`}else ke(\"brackets\");be({type:\"bracket\",value:Z});continue}if(Z===\"]\"){if(r.nobracket===!0||ne&&ne.type===\"bracket\"&&ne.value.length===1){be({type:\"text\",value:Z,output:`\\\\${Z}`});continue}if(g.brackets===0){if(r.strictBrackets===!0)throw new SyntaxError(mm(\"opening\",\"[\"));be({type:\"text\",value:Z,output:`\\\\${Z}`});continue}Ye(\"brackets\");let b=ne.value.slice(1);if(ne.posix!==!0&&b[0]===\"^\"&&!b.includes(\"/\")&&(Z=`/${Z}`),ne.value+=Z,Te({value:Z}),r.literalBrackets===!1||il.hasRegexChars(b))continue;let y=il.escapeRegex(ne.value);if(g.output=g.output.slice(0,-ne.value.length),r.literalBrackets===!0){g.output+=y,ne.value=y;continue}ne.value=`(${A}${y}|${ne.value})`,g.output+=ne.value;continue}if(Z===\"{\"&&r.nobrace!==!0){ke(\"braces\");let b={type:\"brace\",value:Z,output:\"(\",outputIndex:g.output.length,tokensIndex:g.tokens.length};we.push(b),be(b);continue}if(Z===\"}\"){let b=we[we.length-1];if(r.nobrace===!0||!b){be({type:\"text\",value:Z,output:Z});continue}let y=\")\";if(b.dots===!0){let F=u.slice(),J=[];for(let X=F.length-1;X>=0&&(u.pop(),F[X].type!==\"brace\");X--)F[X].type!==\"dots\"&&J.unshift(F[X].value);y=J7e(J,r),g.backtrack=!0}if(b.comma!==!0&&b.dots!==!0){let F=g.output.slice(0,b.outputIndex),J=g.tokens.slice(b.tokensIndex);b.value=b.output=\"\\\\{\",Z=y=\"\\\\}\",g.output=F;for(let X of J)g.output+=X.output||X.value}be({type:\"brace\",value:Z,output:y}),Ye(\"braces\"),we.pop();continue}if(Z===\"|\"){me.length>0&&me[me.length-1].conditions++,be({type:\"text\",value:Z});continue}if(Z===\",\"){let b=Z,y=we[we.length-1];y&&Ae[Ae.length-1]===\"braces\"&&(y.comma=!0,b=\"|\"),be({type:\"comma\",value:Z,output:b});continue}if(Z===\"/\"){if(ne.type===\"dot\"&&g.index===g.start+1){g.start=g.index+1,g.consumed=\"\",g.output=\"\",u.pop(),ne=n;continue}be({type:\"slash\",value:Z,output:x});continue}if(Z===\".\"){if(g.braces>0&&ne.type===\"dot\"){ne.value===\".\"&&(ne.output=I);let b=we[we.length-1];ne.type=\"dots\",ne.output+=Z,ne.value+=Z,b.dots=!0;continue}if(g.braces+g.parens===0&&ne.type!==\"bos\"&&ne.type!==\"slash\"){be({type:\"text\",value:Z,output:I});continue}be({type:\"dot\",value:Z,output:I});continue}if(Z===\"?\"){if(!(ne&&ne.value===\"(\")&&r.noextglob!==!0&&Ne()===\"(\"&&Ne(2)!==\"?\"){et(\"qmark\",Z);continue}if(ne&&ne.type===\"paren\"){let y=Ne(),F=Z;if(y===\"<\"&&!il.supportsLookbehinds())throw new Error(\"Node.js v10 or higher is required for regex lookbehinds\");(ne.value===\"(\"&&!/[!=<:]/.test(y)||y===\"<\"&&!/<([!=]|\\w+>)/.test(H()))&&(F=`\\\\${Z}`),be({type:\"text\",value:Z,output:F});continue}if(r.dot!==!0&&(ne.type===\"slash\"||ne.type===\"bos\")){be({type:\"qmark\",value:Z,output:ae});continue}be({type:\"qmark\",value:Z,output:te});continue}if(Z===\"!\"){if(r.noextglob!==!0&&Ne()===\"(\"&&(Ne(2)!==\"?\"||!/[!=<:]/.test(Ne(3)))){et(\"negate\",Z);continue}if(r.nonegate!==!0&&g.index===0){Fe();continue}}if(Z===\"+\"){if(r.noextglob!==!0&&Ne()===\"(\"&&Ne(2)!==\"?\"){et(\"plus\",Z);continue}if(ne&&ne.value===\"(\"||r.regex===!1){be({type:\"plus\",value:Z,output:v});continue}if(ne&&(ne.type===\"bracket\"||ne.type===\"paren\"||ne.type===\"brace\")||g.parens>0){be({type:\"plus\",value:Z});continue}be({type:\"plus\",value:v});continue}if(Z===\"@\"){if(r.noextglob!==!0&&Ne()===\"(\"&&Ne(2)!==\"?\"){be({type:\"at\",extglob:!0,value:Z,output:\"\"});continue}be({type:\"text\",value:Z});continue}if(Z!==\"*\"){(Z===\"$\"||Z===\"^\")&&(Z=`\\\\${Z}`);let b=V7e.exec(H());b&&(Z+=b[0],g.index+=b[0].length),be({type:\"text\",value:Z});continue}if(ne&&(ne.type===\"globstar\"||ne.star===!0)){ne.type=\"star\",ne.star=!0,ne.value+=Z,ne.output=Ee,g.backtrack=!0,g.globstar=!0,rt(Z);continue}let S=H();if(r.noextglob!==!0&&/^\\([^?]/.test(S)){et(\"star\",Z);continue}if(ne.type===\"star\"){if(r.noglobstar===!0){rt(Z);continue}let b=ne.prev,y=b.prev,F=b.type===\"slash\"||b.type===\"bos\",J=y&&(y.type===\"star\"||y.type===\"globstar\");if(r.bash===!0&&(!F||S[0]&&S[0]!==\"/\")){be({type:\"star\",value:Z,output:\"\"});continue}let X=g.braces>0&&(b.type===\"comma\"||b.type===\"brace\"),$=me.length&&(b.type===\"pipe\"||b.type===\"paren\");if(!F&&b.type!==\"paren\"&&!X&&!$){be({type:\"star\",value:Z,output:\"\"});continue}for(;S.slice(0,3)===\"/**\";){let ie=t[g.index+4];if(ie&&ie!==\"/\")break;S=S.slice(3),rt(\"/**\",3)}if(b.type===\"bos\"&&xe()){ne.type=\"globstar\",ne.value+=Z,ne.output=Ce(r),g.output=ne.output,g.globstar=!0,rt(Z);continue}if(b.type===\"slash\"&&b.prev.type!==\"bos\"&&!J&&xe()){g.output=g.output.slice(0,-(b.output+ne.output).length),b.output=`(?:${b.output}`,ne.type=\"globstar\",ne.output=Ce(r)+(r.strictSlashes?\")\":\"|$)\"),ne.value+=Z,g.globstar=!0,g.output+=b.output+ne.output,rt(Z);continue}if(b.type===\"slash\"&&b.prev.type!==\"bos\"&&S[0]===\"/\"){let ie=S[1]!==void 0?\"|$\":\"\";g.output=g.output.slice(0,-(b.output+ne.output).length),b.output=`(?:${b.output}`,ne.type=\"globstar\",ne.output=`${Ce(r)}${x}|${x}${ie})`,ne.value+=Z,g.output+=b.output+ne.output,g.globstar=!0,rt(Z+ht()),be({type:\"slash\",value:\"/\",output:\"\"});continue}if(b.type===\"bos\"&&S[0]===\"/\"){ne.type=\"globstar\",ne.value+=Z,ne.output=`(?:^|${x}|${Ce(r)}${x})`,g.output=ne.output,g.globstar=!0,rt(Z+ht()),be({type:\"slash\",value:\"/\",output:\"\"});continue}g.output=g.output.slice(0,-ne.output.length),ne.type=\"globstar\",ne.output=Ce(r),ne.value+=Z,g.output+=ne.output,g.globstar=!0,rt(Z);continue}let w={type:\"star\",value:Z,output:Ee};if(r.bash===!0){w.output=\".*?\",(ne.type===\"bos\"||ne.type===\"slash\")&&(w.output=de+w.output),be(w);continue}if(ne&&(ne.type===\"bracket\"||ne.type===\"paren\")&&r.regex===!0){w.output=Z,be(w);continue}(g.index===g.start||ne.type===\"slash\"||ne.type===\"dot\")&&(ne.type===\"dot\"?(g.output+=U,ne.output+=U):r.dot===!0?(g.output+=z,ne.output+=z):(g.output+=de,ne.output+=de),Ne()!==\"*\"&&(g.output+=C,ne.output+=C)),be(w)}for(;g.brackets>0;){if(r.strictBrackets===!0)throw new SyntaxError(mm(\"closing\",\"]\"));g.output=il.escapeLast(g.output,\"[\"),Ye(\"brackets\")}for(;g.parens>0;){if(r.strictBrackets===!0)throw new SyntaxError(mm(\"closing\",\")\"));g.output=il.escapeLast(g.output,\"(\"),Ye(\"parens\")}for(;g.braces>0;){if(r.strictBrackets===!0)throw new SyntaxError(mm(\"closing\",\"}\"));g.output=il.escapeLast(g.output,\"{\"),Ye(\"braces\")}if(r.strictSlashes!==!0&&(ne.type===\"star\"||ne.type===\"bracket\")&&be({type:\"maybe_slash\",value:\"\",output:`${x}?`}),g.backtrack===!0){g.output=\"\";for(let S of g.tokens)g.output+=S.output!=null?S.output:S.value,S.suffix&&(g.output+=S.suffix)}return g};PN.fastpaths=(t,e)=>{let r={...e},o=typeof r.maxLength==\"number\"?Math.min(IP,r.maxLength):IP,a=t.length;if(a>o)throw new SyntaxError(`Input length: ${a}, exceeds maximum allowed length: ${o}`);t=DZ[t]||t;let n=il.isWindows(e),{DOT_LITERAL:u,SLASH_LITERAL:A,ONE_CHAR:p,DOTS_SLASH:h,NO_DOT:E,NO_DOTS:I,NO_DOTS_SLASH:v,STAR:x,START_ANCHOR:C}=wP.globChars(n),R=r.dot?I:E,L=r.dot?v:E,U=r.capture?\"\":\"?:\",z={negated:!1,prefix:\"\"},te=r.bash===!0?\".*?\":x;r.capture&&(te=`(${te})`);let ae=de=>de.noglobstar===!0?te:`(${U}(?:(?!${C}${de.dot?h:u}).)*?)`,le=de=>{switch(de){case\"*\":return`${R}${p}${te}`;case\".*\":return`${u}${p}${te}`;case\"*.*\":return`${R}${te}${u}${p}${te}`;case\"*/*\":return`${R}${te}${A}${p}${L}${te}`;case\"**\":return R+ae(r);case\"**/*\":return`(?:${R}${ae(r)}${A})?${L}${p}${te}`;case\"**/*.*\":return`(?:${R}${ae(r)}${A})?${L}${te}${u}${p}${te}`;case\"**/.*\":return`(?:${R}${ae(r)}${A})?${u}${p}${te}`;default:{let Be=/^(.*?)\\.(\\w+)$/.exec(de);if(!Be)return;let Ee=le(Be[1]);return Ee?Ee+u+Be[2]:void 0}}},ce=il.removePrefix(t,z),Ce=le(ce);return Ce&&r.strictSlashes!==!0&&(Ce+=`${A}?`),Ce};PZ.exports=PN});var xZ=_((rFt,SZ)=>{\"use strict\";var X7e=ve(\"path\"),Z7e=vZ(),bN=bZ(),SN=fI(),$7e=AI(),eYe=t=>t&&typeof t==\"object\"&&!Array.isArray(t),Mi=(t,e,r=!1)=>{if(Array.isArray(t)){let E=t.map(v=>Mi(v,e,r));return v=>{for(let x of E){let C=x(v);if(C)return C}return!1}}let o=eYe(t)&&t.tokens&&t.input;if(t===\"\"||typeof t!=\"string\"&&!o)throw new TypeError(\"Expected pattern to be a non-empty string\");let a=e||{},n=SN.isWindows(e),u=o?Mi.compileRe(t,e):Mi.makeRe(t,e,!1,!0),A=u.state;delete u.state;let p=()=>!1;if(a.ignore){let E={...e,ignore:null,onMatch:null,onResult:null};p=Mi(a.ignore,E,r)}let h=(E,I=!1)=>{let{isMatch:v,match:x,output:C}=Mi.test(E,u,e,{glob:t,posix:n}),R={glob:t,state:A,regex:u,posix:n,input:E,output:C,match:x,isMatch:v};return typeof a.onResult==\"function\"&&a.onResult(R),v===!1?(R.isMatch=!1,I?R:!1):p(E)?(typeof a.onIgnore==\"function\"&&a.onIgnore(R),R.isMatch=!1,I?R:!1):(typeof a.onMatch==\"function\"&&a.onMatch(R),I?R:!0)};return r&&(h.state=A),h};Mi.test=(t,e,r,{glob:o,posix:a}={})=>{if(typeof t!=\"string\")throw new TypeError(\"Expected input to be a string\");if(t===\"\")return{isMatch:!1,output:\"\"};let n=r||{},u=n.format||(a?SN.toPosixSlashes:null),A=t===o,p=A&&u?u(t):t;return A===!1&&(p=u?u(t):t,A=p===o),(A===!1||n.capture===!0)&&(n.matchBase===!0||n.basename===!0?A=Mi.matchBase(t,e,r,a):A=e.exec(p)),{isMatch:!!A,match:A,output:p}};Mi.matchBase=(t,e,r,o=SN.isWindows(r))=>(e instanceof RegExp?e:Mi.makeRe(e,r)).test(X7e.basename(t));Mi.isMatch=(t,e,r)=>Mi(e,r)(t);Mi.parse=(t,e)=>Array.isArray(t)?t.map(r=>Mi.parse(r,e)):bN(t,{...e,fastpaths:!1});Mi.scan=(t,e)=>Z7e(t,e);Mi.compileRe=(t,e,r=!1,o=!1)=>{if(r===!0)return t.output;let a=e||{},n=a.contains?\"\":\"^\",u=a.contains?\"\":\"$\",A=`${n}(?:${t.output})${u}`;t&&t.negated===!0&&(A=`^(?!${A}).*$`);let p=Mi.toRegex(A,e);return o===!0&&(p.state=t),p};Mi.makeRe=(t,e={},r=!1,o=!1)=>{if(!t||typeof t!=\"string\")throw new TypeError(\"Expected a non-empty string\");let a={negated:!1,fastpaths:!0};return e.fastpaths!==!1&&(t[0]===\".\"||t[0]===\"*\")&&(a.output=bN.fastpaths(t,e)),a.output||(a=bN(t,e)),Mi.compileRe(a,e,r,o)};Mi.toRegex=(t,e)=>{try{let r=e||{};return new RegExp(t,r.flags||(r.nocase?\"i\":\"\"))}catch(r){if(e&&e.debug===!0)throw r;return/$^/}};Mi.constants=$7e;SZ.exports=Mi});var QZ=_((nFt,kZ)=>{\"use strict\";kZ.exports=xZ()});var $o=_((iFt,NZ)=>{\"use strict\";var RZ=ve(\"util\"),TZ=AZ(),zu=QZ(),xN=fI(),FZ=t=>t===\"\"||t===\"./\",mi=(t,e,r)=>{e=[].concat(e),t=[].concat(t);let o=new Set,a=new Set,n=new Set,u=0,A=E=>{n.add(E.output),r&&r.onResult&&r.onResult(E)};for(let E=0;E<e.length;E++){let I=zu(String(e[E]),{...r,onResult:A},!0),v=I.state.negated||I.state.negatedExtglob;v&&u++;for(let x of t){let C=I(x,!0);(v?!C.isMatch:C.isMatch)&&(v?o.add(C.output):(o.delete(C.output),a.add(C.output)))}}let h=(u===e.length?[...n]:[...a]).filter(E=>!o.has(E));if(r&&h.length===0){if(r.failglob===!0)throw new Error(`No matches found for \"${e.join(\", \")}\"`);if(r.nonull===!0||r.nullglob===!0)return r.unescape?e.map(E=>E.replace(/\\\\/g,\"\")):e}return h};mi.match=mi;mi.matcher=(t,e)=>zu(t,e);mi.isMatch=(t,e,r)=>zu(e,r)(t);mi.any=mi.isMatch;mi.not=(t,e,r={})=>{e=[].concat(e).map(String);let o=new Set,a=[],n=A=>{r.onResult&&r.onResult(A),a.push(A.output)},u=new Set(mi(t,e,{...r,onResult:n}));for(let A of a)u.has(A)||o.add(A);return[...o]};mi.contains=(t,e,r)=>{if(typeof t!=\"string\")throw new TypeError(`Expected a string: \"${RZ.inspect(t)}\"`);if(Array.isArray(e))return e.some(o=>mi.contains(t,o,r));if(typeof e==\"string\"){if(FZ(t)||FZ(e))return!1;if(t.includes(e)||t.startsWith(\"./\")&&t.slice(2).includes(e))return!0}return mi.isMatch(t,e,{...r,contains:!0})};mi.matchKeys=(t,e,r)=>{if(!xN.isObject(t))throw new TypeError(\"Expected the first argument to be an object\");let o=mi(Object.keys(t),e,r),a={};for(let n of o)a[n]=t[n];return a};mi.some=(t,e,r)=>{let o=[].concat(t);for(let a of[].concat(e)){let n=zu(String(a),r);if(o.some(u=>n(u)))return!0}return!1};mi.every=(t,e,r)=>{let o=[].concat(t);for(let a of[].concat(e)){let n=zu(String(a),r);if(!o.every(u=>n(u)))return!1}return!0};mi.all=(t,e,r)=>{if(typeof t!=\"string\")throw new TypeError(`Expected a string: \"${RZ.inspect(t)}\"`);return[].concat(e).every(o=>zu(o,r)(t))};mi.capture=(t,e,r)=>{let o=xN.isWindows(r),n=zu.makeRe(String(t),{...r,capture:!0}).exec(o?xN.toPosixSlashes(e):e);if(n)return n.slice(1).map(u=>u===void 0?\"\":u)};mi.makeRe=(...t)=>zu.makeRe(...t);mi.scan=(...t)=>zu.scan(...t);mi.parse=(t,e)=>{let r=[];for(let o of[].concat(t||[]))for(let a of TZ(String(o),e))r.push(zu.parse(a,e));return r};mi.braces=(t,e)=>{if(typeof t!=\"string\")throw new TypeError(\"Expected a string\");return e&&e.nobrace===!0||!/\\{.*\\}/.test(t)?[t]:TZ(t,e)};mi.braceExpand=(t,e)=>{if(typeof t!=\"string\")throw new TypeError(\"Expected a string\");return mi.braces(t,{...e,expand:!0})};NZ.exports=mi});var MZ=_((sFt,LZ)=>{\"use strict\";LZ.exports=({onlyFirst:t=!1}={})=>{let e=[\"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]+)*|[a-zA-Z\\\\d]+(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)\",\"(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~]))\"].join(\"|\");return new RegExp(e,t?void 0:\"g\")}});var BP=_((oFt,OZ)=>{\"use strict\";var tYe=MZ();OZ.exports=t=>typeof t==\"string\"?t.replace(tYe(),\"\"):t});var _Z=_((aFt,UZ)=>{function rYe(){this.__data__=[],this.size=0}UZ.exports=rYe});var ym=_((lFt,HZ)=>{function nYe(t,e){return t===e||t!==t&&e!==e}HZ.exports=nYe});var hI=_((cFt,qZ)=>{var iYe=ym();function sYe(t,e){for(var r=t.length;r--;)if(iYe(t[r][0],e))return r;return-1}qZ.exports=sYe});var GZ=_((uFt,jZ)=>{var oYe=hI(),aYe=Array.prototype,lYe=aYe.splice;function cYe(t){var e=this.__data__,r=oYe(e,t);if(r<0)return!1;var o=e.length-1;return r==o?e.pop():lYe.call(e,r,1),--this.size,!0}jZ.exports=cYe});var WZ=_((AFt,YZ)=>{var uYe=hI();function AYe(t){var e=this.__data__,r=uYe(e,t);return r<0?void 0:e[r][1]}YZ.exports=AYe});var VZ=_((fFt,KZ)=>{var fYe=hI();function pYe(t){return fYe(this.__data__,t)>-1}KZ.exports=pYe});var JZ=_((pFt,zZ)=>{var hYe=hI();function gYe(t,e){var r=this.__data__,o=hYe(r,t);return o<0?(++this.size,r.push([t,e])):r[o][1]=e,this}zZ.exports=gYe});var gI=_((hFt,XZ)=>{var dYe=_Z(),mYe=GZ(),yYe=WZ(),EYe=VZ(),CYe=JZ();function Em(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var o=t[e];this.set(o[0],o[1])}}Em.prototype.clear=dYe;Em.prototype.delete=mYe;Em.prototype.get=yYe;Em.prototype.has=EYe;Em.prototype.set=CYe;XZ.exports=Em});var $Z=_((gFt,ZZ)=>{var wYe=gI();function IYe(){this.__data__=new wYe,this.size=0}ZZ.exports=IYe});var t$=_((dFt,e$)=>{function BYe(t){var e=this.__data__,r=e.delete(t);return this.size=e.size,r}e$.exports=BYe});var n$=_((mFt,r$)=>{function vYe(t){return this.__data__.get(t)}r$.exports=vYe});var s$=_((yFt,i$)=>{function DYe(t){return this.__data__.has(t)}i$.exports=DYe});var kN=_((EFt,o$)=>{var PYe=typeof global==\"object\"&&global&&global.Object===Object&&global;o$.exports=PYe});var _l=_((CFt,a$)=>{var bYe=kN(),SYe=typeof self==\"object\"&&self&&self.Object===Object&&self,xYe=bYe||SYe||Function(\"return this\")();a$.exports=xYe});var lg=_((wFt,l$)=>{var kYe=_l(),QYe=kYe.Symbol;l$.exports=QYe});var f$=_((IFt,A$)=>{var c$=lg(),u$=Object.prototype,FYe=u$.hasOwnProperty,RYe=u$.toString,dI=c$?c$.toStringTag:void 0;function TYe(t){var e=FYe.call(t,dI),r=t[dI];try{t[dI]=void 0;var o=!0}catch{}var a=RYe.call(t);return o&&(e?t[dI]=r:delete t[dI]),a}A$.exports=TYe});var h$=_((BFt,p$)=>{var NYe=Object.prototype,LYe=NYe.toString;function MYe(t){return LYe.call(t)}p$.exports=MYe});var cg=_((vFt,m$)=>{var g$=lg(),OYe=f$(),UYe=h$(),_Ye=\"[object Null]\",HYe=\"[object Undefined]\",d$=g$?g$.toStringTag:void 0;function qYe(t){return t==null?t===void 0?HYe:_Ye:d$&&d$ in Object(t)?OYe(t):UYe(t)}m$.exports=qYe});var sl=_((DFt,y$)=>{function jYe(t){var e=typeof t;return t!=null&&(e==\"object\"||e==\"function\")}y$.exports=jYe});var vP=_((PFt,E$)=>{var GYe=cg(),YYe=sl(),WYe=\"[object AsyncFunction]\",KYe=\"[object Function]\",VYe=\"[object GeneratorFunction]\",zYe=\"[object Proxy]\";function JYe(t){if(!YYe(t))return!1;var e=GYe(t);return e==KYe||e==VYe||e==WYe||e==zYe}E$.exports=JYe});var w$=_((bFt,C$)=>{var XYe=_l(),ZYe=XYe[\"__core-js_shared__\"];C$.exports=ZYe});var v$=_((SFt,B$)=>{var QN=w$(),I$=function(){var t=/[^.]+$/.exec(QN&&QN.keys&&QN.keys.IE_PROTO||\"\");return t?\"Symbol(src)_1.\"+t:\"\"}();function $Ye(t){return!!I$&&I$ in t}B$.exports=$Ye});var FN=_((xFt,D$)=>{var eWe=Function.prototype,tWe=eWe.toString;function rWe(t){if(t!=null){try{return tWe.call(t)}catch{}try{return t+\"\"}catch{}}return\"\"}D$.exports=rWe});var b$=_((kFt,P$)=>{var nWe=vP(),iWe=v$(),sWe=sl(),oWe=FN(),aWe=/[\\\\^$.*+?()[\\]{}|]/g,lWe=/^\\[object .+?Constructor\\]$/,cWe=Function.prototype,uWe=Object.prototype,AWe=cWe.toString,fWe=uWe.hasOwnProperty,pWe=RegExp(\"^\"+AWe.call(fWe).replace(aWe,\"\\\\$&\").replace(/hasOwnProperty|(function).*?(?=\\\\\\()| for .+?(?=\\\\\\])/g,\"$1.*?\")+\"$\");function hWe(t){if(!sWe(t)||iWe(t))return!1;var e=nWe(t)?pWe:lWe;return e.test(oWe(t))}P$.exports=hWe});var x$=_((QFt,S$)=>{function gWe(t,e){return t?.[e]}S$.exports=gWe});var Kp=_((FFt,k$)=>{var dWe=b$(),mWe=x$();function yWe(t,e){var r=mWe(t,e);return dWe(r)?r:void 0}k$.exports=yWe});var DP=_((RFt,Q$)=>{var EWe=Kp(),CWe=_l(),wWe=EWe(CWe,\"Map\");Q$.exports=wWe});var mI=_((TFt,F$)=>{var IWe=Kp(),BWe=IWe(Object,\"create\");F$.exports=BWe});var N$=_((NFt,T$)=>{var R$=mI();function vWe(){this.__data__=R$?R$(null):{},this.size=0}T$.exports=vWe});var M$=_((LFt,L$)=>{function DWe(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}L$.exports=DWe});var U$=_((MFt,O$)=>{var PWe=mI(),bWe=\"__lodash_hash_undefined__\",SWe=Object.prototype,xWe=SWe.hasOwnProperty;function kWe(t){var e=this.__data__;if(PWe){var r=e[t];return r===bWe?void 0:r}return xWe.call(e,t)?e[t]:void 0}O$.exports=kWe});var H$=_((OFt,_$)=>{var QWe=mI(),FWe=Object.prototype,RWe=FWe.hasOwnProperty;function TWe(t){var e=this.__data__;return QWe?e[t]!==void 0:RWe.call(e,t)}_$.exports=TWe});var j$=_((UFt,q$)=>{var NWe=mI(),LWe=\"__lodash_hash_undefined__\";function MWe(t,e){var r=this.__data__;return this.size+=this.has(t)?0:1,r[t]=NWe&&e===void 0?LWe:e,this}q$.exports=MWe});var Y$=_((_Ft,G$)=>{var OWe=N$(),UWe=M$(),_We=U$(),HWe=H$(),qWe=j$();function Cm(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var o=t[e];this.set(o[0],o[1])}}Cm.prototype.clear=OWe;Cm.prototype.delete=UWe;Cm.prototype.get=_We;Cm.prototype.has=HWe;Cm.prototype.set=qWe;G$.exports=Cm});var V$=_((HFt,K$)=>{var W$=Y$(),jWe=gI(),GWe=DP();function YWe(){this.size=0,this.__data__={hash:new W$,map:new(GWe||jWe),string:new W$}}K$.exports=YWe});var J$=_((qFt,z$)=>{function WWe(t){var e=typeof t;return e==\"string\"||e==\"number\"||e==\"symbol\"||e==\"boolean\"?t!==\"__proto__\":t===null}z$.exports=WWe});var yI=_((jFt,X$)=>{var KWe=J$();function VWe(t,e){var r=t.__data__;return KWe(e)?r[typeof e==\"string\"?\"string\":\"hash\"]:r.map}X$.exports=VWe});var $$=_((GFt,Z$)=>{var zWe=yI();function JWe(t){var e=zWe(this,t).delete(t);return this.size-=e?1:0,e}Z$.exports=JWe});var tee=_((YFt,eee)=>{var XWe=yI();function ZWe(t){return XWe(this,t).get(t)}eee.exports=ZWe});var nee=_((WFt,ree)=>{var $We=yI();function eKe(t){return $We(this,t).has(t)}ree.exports=eKe});var see=_((KFt,iee)=>{var tKe=yI();function rKe(t,e){var r=tKe(this,t),o=r.size;return r.set(t,e),this.size+=r.size==o?0:1,this}iee.exports=rKe});var PP=_((VFt,oee)=>{var nKe=V$(),iKe=$$(),sKe=tee(),oKe=nee(),aKe=see();function wm(t){var e=-1,r=t==null?0:t.length;for(this.clear();++e<r;){var o=t[e];this.set(o[0],o[1])}}wm.prototype.clear=nKe;wm.prototype.delete=iKe;wm.prototype.get=sKe;wm.prototype.has=oKe;wm.prototype.set=aKe;oee.exports=wm});var lee=_((zFt,aee)=>{var lKe=gI(),cKe=DP(),uKe=PP(),AKe=200;function fKe(t,e){var r=this.__data__;if(r instanceof lKe){var o=r.__data__;if(!cKe||o.length<AKe-1)return o.push([t,e]),this.size=++r.size,this;r=this.__data__=new uKe(o)}return r.set(t,e),this.size=r.size,this}aee.exports=fKe});var bP=_((JFt,cee)=>{var pKe=gI(),hKe=$Z(),gKe=t$(),dKe=n$(),mKe=s$(),yKe=lee();function Im(t){var e=this.__data__=new pKe(t);this.size=e.size}Im.prototype.clear=hKe;Im.prototype.delete=gKe;Im.prototype.get=dKe;Im.prototype.has=mKe;Im.prototype.set=yKe;cee.exports=Im});var Aee=_((XFt,uee)=>{var EKe=\"__lodash_hash_undefined__\";function CKe(t){return this.__data__.set(t,EKe),this}uee.exports=CKe});var pee=_((ZFt,fee)=>{function wKe(t){return this.__data__.has(t)}fee.exports=wKe});var gee=_(($Ft,hee)=>{var IKe=PP(),BKe=Aee(),vKe=pee();function SP(t){var e=-1,r=t==null?0:t.length;for(this.__data__=new IKe;++e<r;)this.add(t[e])}SP.prototype.add=SP.prototype.push=BKe;SP.prototype.has=vKe;hee.exports=SP});var mee=_((eRt,dee)=>{function DKe(t,e){for(var r=-1,o=t==null?0:t.length;++r<o;)if(e(t[r],r,t))return!0;return!1}dee.exports=DKe});var Eee=_((tRt,yee)=>{function PKe(t,e){return t.has(e)}yee.exports=PKe});var RN=_((rRt,Cee)=>{var bKe=gee(),SKe=mee(),xKe=Eee(),kKe=1,QKe=2;function FKe(t,e,r,o,a,n){var u=r&kKe,A=t.length,p=e.length;if(A!=p&&!(u&&p>A))return!1;var h=n.get(t),E=n.get(e);if(h&&E)return h==e&&E==t;var I=-1,v=!0,x=r&QKe?new bKe:void 0;for(n.set(t,e),n.set(e,t);++I<A;){var C=t[I],R=e[I];if(o)var L=u?o(R,C,I,e,t,n):o(C,R,I,t,e,n);if(L!==void 0){if(L)continue;v=!1;break}if(x){if(!SKe(e,function(U,z){if(!xKe(x,z)&&(C===U||a(C,U,r,o,n)))return x.push(z)})){v=!1;break}}else if(!(C===R||a(C,R,r,o,n))){v=!1;break}}return n.delete(t),n.delete(e),v}Cee.exports=FKe});var TN=_((nRt,wee)=>{var RKe=_l(),TKe=RKe.Uint8Array;wee.exports=TKe});var Bee=_((iRt,Iee)=>{function NKe(t){var e=-1,r=Array(t.size);return t.forEach(function(o,a){r[++e]=[a,o]}),r}Iee.exports=NKe});var Dee=_((sRt,vee)=>{function LKe(t){var e=-1,r=Array(t.size);return t.forEach(function(o){r[++e]=o}),r}vee.exports=LKe});var kee=_((oRt,xee)=>{var Pee=lg(),bee=TN(),MKe=ym(),OKe=RN(),UKe=Bee(),_Ke=Dee(),HKe=1,qKe=2,jKe=\"[object Boolean]\",GKe=\"[object Date]\",YKe=\"[object Error]\",WKe=\"[object Map]\",KKe=\"[object Number]\",VKe=\"[object RegExp]\",zKe=\"[object Set]\",JKe=\"[object String]\",XKe=\"[object Symbol]\",ZKe=\"[object ArrayBuffer]\",$Ke=\"[object DataView]\",See=Pee?Pee.prototype:void 0,NN=See?See.valueOf:void 0;function eVe(t,e,r,o,a,n,u){switch(r){case $Ke:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case ZKe:return!(t.byteLength!=e.byteLength||!n(new bee(t),new bee(e)));case jKe:case GKe:case KKe:return MKe(+t,+e);case YKe:return t.name==e.name&&t.message==e.message;case VKe:case JKe:return t==e+\"\";case WKe:var A=UKe;case zKe:var p=o&HKe;if(A||(A=_Ke),t.size!=e.size&&!p)return!1;var h=u.get(t);if(h)return h==e;o|=qKe,u.set(t,e);var E=OKe(A(t),A(e),o,a,n,u);return u.delete(t),E;case XKe:if(NN)return NN.call(t)==NN.call(e)}return!1}xee.exports=eVe});var xP=_((aRt,Qee)=>{function tVe(t,e){for(var r=-1,o=e.length,a=t.length;++r<o;)t[a+r]=e[r];return t}Qee.exports=tVe});var Hl=_((lRt,Fee)=>{var rVe=Array.isArray;Fee.exports=rVe});var LN=_((cRt,Ree)=>{var nVe=xP(),iVe=Hl();function sVe(t,e,r){var o=e(t);return iVe(t)?o:nVe(o,r(t))}Ree.exports=sVe});var Nee=_((uRt,Tee)=>{function oVe(t,e){for(var r=-1,o=t==null?0:t.length,a=0,n=[];++r<o;){var u=t[r];e(u,r,t)&&(n[a++]=u)}return n}Tee.exports=oVe});var MN=_((ARt,Lee)=>{function aVe(){return[]}Lee.exports=aVe});var kP=_((fRt,Oee)=>{var lVe=Nee(),cVe=MN(),uVe=Object.prototype,AVe=uVe.propertyIsEnumerable,Mee=Object.getOwnPropertySymbols,fVe=Mee?function(t){return t==null?[]:(t=Object(t),lVe(Mee(t),function(e){return AVe.call(t,e)}))}:cVe;Oee.exports=fVe});var _ee=_((pRt,Uee)=>{function pVe(t,e){for(var r=-1,o=Array(t);++r<t;)o[r]=e(r);return o}Uee.exports=pVe});var Ju=_((hRt,Hee)=>{function hVe(t){return t!=null&&typeof t==\"object\"}Hee.exports=hVe});var jee=_((gRt,qee)=>{var gVe=cg(),dVe=Ju(),mVe=\"[object Arguments]\";function yVe(t){return dVe(t)&&gVe(t)==mVe}qee.exports=yVe});var EI=_((dRt,Wee)=>{var Gee=jee(),EVe=Ju(),Yee=Object.prototype,CVe=Yee.hasOwnProperty,wVe=Yee.propertyIsEnumerable,IVe=Gee(function(){return arguments}())?Gee:function(t){return EVe(t)&&CVe.call(t,\"callee\")&&!wVe.call(t,\"callee\")};Wee.exports=IVe});var Vee=_((mRt,Kee)=>{function BVe(){return!1}Kee.exports=BVe});var wI=_((CI,Bm)=>{var vVe=_l(),DVe=Vee(),Xee=typeof CI==\"object\"&&CI&&!CI.nodeType&&CI,zee=Xee&&typeof Bm==\"object\"&&Bm&&!Bm.nodeType&&Bm,PVe=zee&&zee.exports===Xee,Jee=PVe?vVe.Buffer:void 0,bVe=Jee?Jee.isBuffer:void 0,SVe=bVe||DVe;Bm.exports=SVe});var II=_((yRt,Zee)=>{var xVe=9007199254740991,kVe=/^(?:0|[1-9]\\d*)$/;function QVe(t,e){var r=typeof t;return e=e??xVe,!!e&&(r==\"number\"||r!=\"symbol\"&&kVe.test(t))&&t>-1&&t%1==0&&t<e}Zee.exports=QVe});var QP=_((ERt,$ee)=>{var FVe=9007199254740991;function RVe(t){return typeof t==\"number\"&&t>-1&&t%1==0&&t<=FVe}$ee.exports=RVe});var tte=_((CRt,ete)=>{var TVe=cg(),NVe=QP(),LVe=Ju(),MVe=\"[object Arguments]\",OVe=\"[object Array]\",UVe=\"[object Boolean]\",_Ve=\"[object Date]\",HVe=\"[object Error]\",qVe=\"[object Function]\",jVe=\"[object Map]\",GVe=\"[object Number]\",YVe=\"[object Object]\",WVe=\"[object RegExp]\",KVe=\"[object Set]\",VVe=\"[object String]\",zVe=\"[object WeakMap]\",JVe=\"[object ArrayBuffer]\",XVe=\"[object DataView]\",ZVe=\"[object Float32Array]\",$Ve=\"[object Float64Array]\",eze=\"[object Int8Array]\",tze=\"[object Int16Array]\",rze=\"[object Int32Array]\",nze=\"[object Uint8Array]\",ize=\"[object Uint8ClampedArray]\",sze=\"[object Uint16Array]\",oze=\"[object Uint32Array]\",ui={};ui[ZVe]=ui[$Ve]=ui[eze]=ui[tze]=ui[rze]=ui[nze]=ui[ize]=ui[sze]=ui[oze]=!0;ui[MVe]=ui[OVe]=ui[JVe]=ui[UVe]=ui[XVe]=ui[_Ve]=ui[HVe]=ui[qVe]=ui[jVe]=ui[GVe]=ui[YVe]=ui[WVe]=ui[KVe]=ui[VVe]=ui[zVe]=!1;function aze(t){return LVe(t)&&NVe(t.length)&&!!ui[TVe(t)]}ete.exports=aze});var FP=_((wRt,rte)=>{function lze(t){return function(e){return t(e)}}rte.exports=lze});var RP=_((BI,vm)=>{var cze=kN(),nte=typeof BI==\"object\"&&BI&&!BI.nodeType&&BI,vI=nte&&typeof vm==\"object\"&&vm&&!vm.nodeType&&vm,uze=vI&&vI.exports===nte,ON=uze&&cze.process,Aze=function(){try{var t=vI&&vI.require&&vI.require(\"util\").types;return t||ON&&ON.binding&&ON.binding(\"util\")}catch{}}();vm.exports=Aze});var TP=_((IRt,ote)=>{var fze=tte(),pze=FP(),ite=RP(),ste=ite&&ite.isTypedArray,hze=ste?pze(ste):fze;ote.exports=hze});var UN=_((BRt,ate)=>{var gze=_ee(),dze=EI(),mze=Hl(),yze=wI(),Eze=II(),Cze=TP(),wze=Object.prototype,Ize=wze.hasOwnProperty;function Bze(t,e){var r=mze(t),o=!r&&dze(t),a=!r&&!o&&yze(t),n=!r&&!o&&!a&&Cze(t),u=r||o||a||n,A=u?gze(t.length,String):[],p=A.length;for(var h in t)(e||Ize.call(t,h))&&!(u&&(h==\"length\"||a&&(h==\"offset\"||h==\"parent\")||n&&(h==\"buffer\"||h==\"byteLength\"||h==\"byteOffset\")||Eze(h,p)))&&A.push(h);return A}ate.exports=Bze});var NP=_((vRt,lte)=>{var vze=Object.prototype;function Dze(t){var e=t&&t.constructor,r=typeof e==\"function\"&&e.prototype||vze;return t===r}lte.exports=Dze});var _N=_((DRt,cte)=>{function Pze(t,e){return function(r){return t(e(r))}}cte.exports=Pze});var Ate=_((PRt,ute)=>{var bze=_N(),Sze=bze(Object.keys,Object);ute.exports=Sze});var pte=_((bRt,fte)=>{var xze=NP(),kze=Ate(),Qze=Object.prototype,Fze=Qze.hasOwnProperty;function Rze(t){if(!xze(t))return kze(t);var e=[];for(var r in Object(t))Fze.call(t,r)&&r!=\"constructor\"&&e.push(r);return e}fte.exports=Rze});var DI=_((SRt,hte)=>{var Tze=vP(),Nze=QP();function Lze(t){return t!=null&&Nze(t.length)&&!Tze(t)}hte.exports=Lze});var LP=_((xRt,gte)=>{var Mze=UN(),Oze=pte(),Uze=DI();function _ze(t){return Uze(t)?Mze(t):Oze(t)}gte.exports=_ze});var HN=_((kRt,dte)=>{var Hze=LN(),qze=kP(),jze=LP();function Gze(t){return Hze(t,jze,qze)}dte.exports=Gze});var Ete=_((QRt,yte)=>{var mte=HN(),Yze=1,Wze=Object.prototype,Kze=Wze.hasOwnProperty;function Vze(t,e,r,o,a,n){var u=r&Yze,A=mte(t),p=A.length,h=mte(e),E=h.length;if(p!=E&&!u)return!1;for(var I=p;I--;){var v=A[I];if(!(u?v in e:Kze.call(e,v)))return!1}var x=n.get(t),C=n.get(e);if(x&&C)return x==e&&C==t;var R=!0;n.set(t,e),n.set(e,t);for(var L=u;++I<p;){v=A[I];var U=t[v],z=e[v];if(o)var te=u?o(z,U,v,e,t,n):o(U,z,v,t,e,n);if(!(te===void 0?U===z||a(U,z,r,o,n):te)){R=!1;break}L||(L=v==\"constructor\")}if(R&&!L){var ae=t.constructor,le=e.constructor;ae!=le&&\"constructor\"in t&&\"constructor\"in e&&!(typeof ae==\"function\"&&ae instanceof ae&&typeof le==\"function\"&&le instanceof le)&&(R=!1)}return n.delete(t),n.delete(e),R}yte.exports=Vze});var wte=_((FRt,Cte)=>{var zze=Kp(),Jze=_l(),Xze=zze(Jze,\"DataView\");Cte.exports=Xze});var Bte=_((RRt,Ite)=>{var Zze=Kp(),$ze=_l(),eJe=Zze($ze,\"Promise\");Ite.exports=eJe});var Dte=_((TRt,vte)=>{var tJe=Kp(),rJe=_l(),nJe=tJe(rJe,\"Set\");vte.exports=nJe});var bte=_((NRt,Pte)=>{var iJe=Kp(),sJe=_l(),oJe=iJe(sJe,\"WeakMap\");Pte.exports=oJe});var PI=_((LRt,Tte)=>{var qN=wte(),jN=DP(),GN=Bte(),YN=Dte(),WN=bte(),Rte=cg(),Dm=FN(),Ste=\"[object Map]\",aJe=\"[object Object]\",xte=\"[object Promise]\",kte=\"[object Set]\",Qte=\"[object WeakMap]\",Fte=\"[object DataView]\",lJe=Dm(qN),cJe=Dm(jN),uJe=Dm(GN),AJe=Dm(YN),fJe=Dm(WN),ug=Rte;(qN&&ug(new qN(new ArrayBuffer(1)))!=Fte||jN&&ug(new jN)!=Ste||GN&&ug(GN.resolve())!=xte||YN&&ug(new YN)!=kte||WN&&ug(new WN)!=Qte)&&(ug=function(t){var e=Rte(t),r=e==aJe?t.constructor:void 0,o=r?Dm(r):\"\";if(o)switch(o){case lJe:return Fte;case cJe:return Ste;case uJe:return xte;case AJe:return kte;case fJe:return Qte}return e});Tte.exports=ug});var qte=_((MRt,Hte)=>{var KN=bP(),pJe=RN(),hJe=kee(),gJe=Ete(),Nte=PI(),Lte=Hl(),Mte=wI(),dJe=TP(),mJe=1,Ote=\"[object Arguments]\",Ute=\"[object Array]\",MP=\"[object Object]\",yJe=Object.prototype,_te=yJe.hasOwnProperty;function EJe(t,e,r,o,a,n){var u=Lte(t),A=Lte(e),p=u?Ute:Nte(t),h=A?Ute:Nte(e);p=p==Ote?MP:p,h=h==Ote?MP:h;var E=p==MP,I=h==MP,v=p==h;if(v&&Mte(t)){if(!Mte(e))return!1;u=!0,E=!1}if(v&&!E)return n||(n=new KN),u||dJe(t)?pJe(t,e,r,o,a,n):hJe(t,e,p,r,o,a,n);if(!(r&mJe)){var x=E&&_te.call(t,\"__wrapped__\"),C=I&&_te.call(e,\"__wrapped__\");if(x||C){var R=x?t.value():t,L=C?e.value():e;return n||(n=new KN),a(R,L,r,o,n)}}return v?(n||(n=new KN),gJe(t,e,r,o,a,n)):!1}Hte.exports=EJe});var Wte=_((ORt,Yte)=>{var CJe=qte(),jte=Ju();function Gte(t,e,r,o,a){return t===e?!0:t==null||e==null||!jte(t)&&!jte(e)?t!==t&&e!==e:CJe(t,e,r,o,Gte,a)}Yte.exports=Gte});var Vte=_((URt,Kte)=>{var wJe=Wte();function IJe(t,e){return wJe(t,e)}Kte.exports=IJe});var VN=_((_Rt,zte)=>{var BJe=Kp(),vJe=function(){try{var t=BJe(Object,\"defineProperty\");return t({},\"\",{}),t}catch{}}();zte.exports=vJe});var OP=_((HRt,Xte)=>{var Jte=VN();function DJe(t,e,r){e==\"__proto__\"&&Jte?Jte(t,e,{configurable:!0,enumerable:!0,value:r,writable:!0}):t[e]=r}Xte.exports=DJe});var zN=_((qRt,Zte)=>{var PJe=OP(),bJe=ym();function SJe(t,e,r){(r!==void 0&&!bJe(t[e],r)||r===void 0&&!(e in t))&&PJe(t,e,r)}Zte.exports=SJe});var ere=_((jRt,$te)=>{function xJe(t){return function(e,r,o){for(var a=-1,n=Object(e),u=o(e),A=u.length;A--;){var p=u[t?A:++a];if(r(n[p],p,n)===!1)break}return e}}$te.exports=xJe});var rre=_((GRt,tre)=>{var kJe=ere(),QJe=kJe();tre.exports=QJe});var JN=_((bI,Pm)=>{var FJe=_l(),ore=typeof bI==\"object\"&&bI&&!bI.nodeType&&bI,nre=ore&&typeof Pm==\"object\"&&Pm&&!Pm.nodeType&&Pm,RJe=nre&&nre.exports===ore,ire=RJe?FJe.Buffer:void 0,sre=ire?ire.allocUnsafe:void 0;function TJe(t,e){if(e)return t.slice();var r=t.length,o=sre?sre(r):new t.constructor(r);return t.copy(o),o}Pm.exports=TJe});var UP=_((YRt,lre)=>{var are=TN();function NJe(t){var e=new t.constructor(t.byteLength);return new are(e).set(new are(t)),e}lre.exports=NJe});var XN=_((WRt,cre)=>{var LJe=UP();function MJe(t,e){var r=e?LJe(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.length)}cre.exports=MJe});var _P=_((KRt,ure)=>{function OJe(t,e){var r=-1,o=t.length;for(e||(e=Array(o));++r<o;)e[r]=t[r];return e}ure.exports=OJe});var pre=_((VRt,fre)=>{var UJe=sl(),Are=Object.create,_Je=function(){function t(){}return function(e){if(!UJe(e))return{};if(Are)return Are(e);t.prototype=e;var r=new t;return t.prototype=void 0,r}}();fre.exports=_Je});var HP=_((zRt,hre)=>{var HJe=_N(),qJe=HJe(Object.getPrototypeOf,Object);hre.exports=qJe});var ZN=_((JRt,gre)=>{var jJe=pre(),GJe=HP(),YJe=NP();function WJe(t){return typeof t.constructor==\"function\"&&!YJe(t)?jJe(GJe(t)):{}}gre.exports=WJe});var mre=_((XRt,dre)=>{var KJe=DI(),VJe=Ju();function zJe(t){return VJe(t)&&KJe(t)}dre.exports=zJe});var $N=_((ZRt,Ere)=>{var JJe=cg(),XJe=HP(),ZJe=Ju(),$Je=\"[object Object]\",eXe=Function.prototype,tXe=Object.prototype,yre=eXe.toString,rXe=tXe.hasOwnProperty,nXe=yre.call(Object);function iXe(t){if(!ZJe(t)||JJe(t)!=$Je)return!1;var e=XJe(t);if(e===null)return!0;var r=rXe.call(e,\"constructor\")&&e.constructor;return typeof r==\"function\"&&r instanceof r&&yre.call(r)==nXe}Ere.exports=iXe});var eL=_(($Rt,Cre)=>{function sXe(t,e){if(!(e===\"constructor\"&&typeof t[e]==\"function\")&&e!=\"__proto__\")return t[e]}Cre.exports=sXe});var qP=_((eTt,wre)=>{var oXe=OP(),aXe=ym(),lXe=Object.prototype,cXe=lXe.hasOwnProperty;function uXe(t,e,r){var o=t[e];(!(cXe.call(t,e)&&aXe(o,r))||r===void 0&&!(e in t))&&oXe(t,e,r)}wre.exports=uXe});var Ag=_((tTt,Ire)=>{var AXe=qP(),fXe=OP();function pXe(t,e,r,o){var a=!r;r||(r={});for(var n=-1,u=e.length;++n<u;){var A=e[n],p=o?o(r[A],t[A],A,r,t):void 0;p===void 0&&(p=t[A]),a?fXe(r,A,p):AXe(r,A,p)}return r}Ire.exports=pXe});var vre=_((rTt,Bre)=>{function hXe(t){var e=[];if(t!=null)for(var r in Object(t))e.push(r);return e}Bre.exports=hXe});var Pre=_((nTt,Dre)=>{var gXe=sl(),dXe=NP(),mXe=vre(),yXe=Object.prototype,EXe=yXe.hasOwnProperty;function CXe(t){if(!gXe(t))return mXe(t);var e=dXe(t),r=[];for(var o in t)o==\"constructor\"&&(e||!EXe.call(t,o))||r.push(o);return r}Dre.exports=CXe});var bm=_((iTt,bre)=>{var wXe=UN(),IXe=Pre(),BXe=DI();function vXe(t){return BXe(t)?wXe(t,!0):IXe(t)}bre.exports=vXe});var xre=_((sTt,Sre)=>{var DXe=Ag(),PXe=bm();function bXe(t){return DXe(t,PXe(t))}Sre.exports=bXe});var Nre=_((oTt,Tre)=>{var kre=zN(),SXe=JN(),xXe=XN(),kXe=_P(),QXe=ZN(),Qre=EI(),Fre=Hl(),FXe=mre(),RXe=wI(),TXe=vP(),NXe=sl(),LXe=$N(),MXe=TP(),Rre=eL(),OXe=xre();function UXe(t,e,r,o,a,n,u){var A=Rre(t,r),p=Rre(e,r),h=u.get(p);if(h){kre(t,r,h);return}var E=n?n(A,p,r+\"\",t,e,u):void 0,I=E===void 0;if(I){var v=Fre(p),x=!v&&RXe(p),C=!v&&!x&&MXe(p);E=p,v||x||C?Fre(A)?E=A:FXe(A)?E=kXe(A):x?(I=!1,E=SXe(p,!0)):C?(I=!1,E=xXe(p,!0)):E=[]:LXe(p)||Qre(p)?(E=A,Qre(A)?E=OXe(A):(!NXe(A)||TXe(A))&&(E=QXe(p))):I=!1}I&&(u.set(p,E),a(E,p,o,n,u),u.delete(p)),kre(t,r,E)}Tre.exports=UXe});var Ore=_((aTt,Mre)=>{var _Xe=bP(),HXe=zN(),qXe=rre(),jXe=Nre(),GXe=sl(),YXe=bm(),WXe=eL();function Lre(t,e,r,o,a){t!==e&&qXe(e,function(n,u){if(a||(a=new _Xe),GXe(n))jXe(t,e,u,r,Lre,o,a);else{var A=o?o(WXe(t,u),n,u+\"\",t,e,a):void 0;A===void 0&&(A=n),HXe(t,u,A)}},YXe)}Mre.exports=Lre});var tL=_((lTt,Ure)=>{function KXe(t){return t}Ure.exports=KXe});var Hre=_((cTt,_re)=>{function VXe(t,e,r){switch(r.length){case 0:return t.call(e);case 1:return t.call(e,r[0]);case 2:return t.call(e,r[0],r[1]);case 3:return t.call(e,r[0],r[1],r[2])}return t.apply(e,r)}_re.exports=VXe});var rL=_((uTt,jre)=>{var zXe=Hre(),qre=Math.max;function JXe(t,e,r){return e=qre(e===void 0?t.length-1:e,0),function(){for(var o=arguments,a=-1,n=qre(o.length-e,0),u=Array(n);++a<n;)u[a]=o[e+a];a=-1;for(var A=Array(e+1);++a<e;)A[a]=o[a];return A[e]=r(u),zXe(t,this,A)}}jre.exports=JXe});var Yre=_((ATt,Gre)=>{function XXe(t){return function(){return t}}Gre.exports=XXe});var Vre=_((fTt,Kre)=>{var ZXe=Yre(),Wre=VN(),$Xe=tL(),eZe=Wre?function(t,e){return Wre(t,\"toString\",{configurable:!0,enumerable:!1,value:ZXe(e),writable:!0})}:$Xe;Kre.exports=eZe});var Jre=_((pTt,zre)=>{var tZe=800,rZe=16,nZe=Date.now;function iZe(t){var e=0,r=0;return function(){var o=nZe(),a=rZe-(o-r);if(r=o,a>0){if(++e>=tZe)return arguments[0]}else e=0;return t.apply(void 0,arguments)}}zre.exports=iZe});var nL=_((hTt,Xre)=>{var sZe=Vre(),oZe=Jre(),aZe=oZe(sZe);Xre.exports=aZe});var $re=_((gTt,Zre)=>{var lZe=tL(),cZe=rL(),uZe=nL();function AZe(t,e){return uZe(cZe(t,e,lZe),t+\"\")}Zre.exports=AZe});var tne=_((dTt,ene)=>{var fZe=ym(),pZe=DI(),hZe=II(),gZe=sl();function dZe(t,e,r){if(!gZe(r))return!1;var o=typeof e;return(o==\"number\"?pZe(r)&&hZe(e,r.length):o==\"string\"&&e in r)?fZe(r[e],t):!1}ene.exports=dZe});var nne=_((mTt,rne)=>{var mZe=$re(),yZe=tne();function EZe(t){return mZe(function(e,r){var o=-1,a=r.length,n=a>1?r[a-1]:void 0,u=a>2?r[2]:void 0;for(n=t.length>3&&typeof n==\"function\"?(a--,n):void 0,u&&yZe(r[0],r[1],u)&&(n=a<3?void 0:n,a=1),e=Object(e);++o<a;){var A=r[o];A&&t(e,A,o,n)}return e})}rne.exports=EZe});var sne=_((yTt,ine)=>{var CZe=Ore(),wZe=nne(),IZe=wZe(function(t,e,r,o){CZe(t,e,r,o)});ine.exports=IZe});var He={};Vt(He,{AsyncActions:()=>oL,BufferStream:()=>sL,CachingStrategy:()=>mne,DefaultStream:()=>aL,allSettledSafe:()=>_c,assertNever:()=>cL,bufferStream:()=>km,buildIgnorePattern:()=>xZe,convertMapsToIndexableObjects:()=>GP,dynamicRequire:()=>vf,escapeRegExp:()=>vZe,getArrayWithDefault:()=>xI,getFactoryWithDefault:()=>al,getMapWithDefault:()=>kI,getSetWithDefault:()=>Sm,groupBy:()=>FZe,isIndexableObject:()=>iL,isPathLike:()=>kZe,isTaggedYarnVersion:()=>BZe,makeDeferred:()=>hne,mapAndFilter:()=>ol,mapAndFind:()=>Vp,mergeIntoTarget:()=>Ene,overrideType:()=>DZe,parseBoolean:()=>QI,parseInt:()=>Qm,parseOptionalBoolean:()=>yne,plural:()=>jP,prettifyAsyncErrors:()=>xm,prettifySyncErrors:()=>uL,releaseAfterUseAsync:()=>bZe,replaceEnvVariables:()=>YP,sortMap:()=>Fs,toMerged:()=>QZe,tryParseOptionalBoolean:()=>AL,validateEnum:()=>PZe});function BZe(t){return!!(Ane.default.valid(t)&&t.match(/^[^-]+(-rc\\.[0-9]+)?$/))}function jP(t,{one:e,more:r,zero:o=r}){return t===0?o:t===1?e:r}function vZe(t){return t.replace(/[.*+?^${}()|[\\]\\\\]/g,\"\\\\$&\")}function DZe(t){}function cL(t){throw new Error(`Assertion failed: Unexpected object '${t}'`)}function PZe(t,e){let r=Object.values(t);if(!r.includes(e))throw new st(`Invalid value for enumeration: ${JSON.stringify(e)} (expected one of ${r.map(o=>JSON.stringify(o)).join(\", \")})`);return e}function ol(t,e){let r=[];for(let o of t){let a=e(o);a!==fne&&r.push(a)}return r}function Vp(t,e){for(let r of t){let o=e(r);if(o!==pne)return o}}function iL(t){return typeof t==\"object\"&&t!==null}async function _c(t){let e=await Promise.allSettled(t),r=[];for(let o of e){if(o.status===\"rejected\")throw o.reason;r.push(o.value)}return r}function GP(t){if(t instanceof Map&&(t=Object.fromEntries(t)),iL(t))for(let e of Object.keys(t)){let r=t[e];iL(r)&&(t[e]=GP(r))}return t}function al(t,e,r){let o=t.get(e);return typeof o>\"u\"&&t.set(e,o=r()),o}function xI(t,e){let r=t.get(e);return typeof r>\"u\"&&t.set(e,r=[]),r}function Sm(t,e){let r=t.get(e);return typeof r>\"u\"&&t.set(e,r=new Set),r}function kI(t,e){let r=t.get(e);return typeof r>\"u\"&&t.set(e,r=new Map),r}async function bZe(t,e){if(e==null)return await t();try{return await t()}finally{await e()}}async function xm(t,e){try{return await t()}catch(r){throw r.message=e(r.message),r}}function uL(t,e){try{return t()}catch(r){throw r.message=e(r.message),r}}async function km(t){return await new Promise((e,r)=>{let o=[];t.on(\"error\",a=>{r(a)}),t.on(\"data\",a=>{o.push(a)}),t.on(\"end\",()=>{e(Buffer.concat(o))})})}function hne(){let t,e;return{promise:new Promise((o,a)=>{t=o,e=a}),resolve:t,reject:e}}function gne(t){return SI(ue.fromPortablePath(t))}function dne(path){let physicalPath=ue.fromPortablePath(path),currentCacheEntry=SI.cache[physicalPath];delete SI.cache[physicalPath];let result;try{result=gne(physicalPath);let freshCacheEntry=SI.cache[physicalPath],dynamicModule=eval(\"module\"),freshCacheIndex=dynamicModule.children.indexOf(freshCacheEntry);freshCacheIndex!==-1&&dynamicModule.children.splice(freshCacheIndex,1)}finally{SI.cache[physicalPath]=currentCacheEntry}return result}function SZe(t){let e=one.get(t),r=oe.statSync(t);if(e?.mtime===r.mtimeMs)return e.instance;let o=dne(t);return one.set(t,{mtime:r.mtimeMs,instance:o}),o}function vf(t,{cachingStrategy:e=2}={}){switch(e){case 0:return dne(t);case 1:return SZe(t);case 2:return gne(t);default:throw new Error(\"Unsupported caching strategy\")}}function Fs(t,e){let r=Array.from(t);Array.isArray(e)||(e=[e]);let o=[];for(let n of e)o.push(r.map(u=>n(u)));let a=r.map((n,u)=>u);return a.sort((n,u)=>{for(let A of o){let p=A[n]<A[u]?-1:A[n]>A[u]?1:0;if(p!==0)return p}return 0}),a.map(n=>r[n])}function xZe(t){return t.length===0?null:t.map(e=>`(${cne.default.makeRe(e,{windows:!1,dot:!0}).source})`).join(\"|\")}function YP(t,{env:e}){let r=/\\${(?<variableName>[\\d\\w_]+)(?<colon>:)?(?:-(?<fallback>[^}]*))?}/g;return t.replace(r,(...o)=>{let{variableName:a,colon:n,fallback:u}=o[o.length-1],A=Object.hasOwn(e,a),p=e[a];if(p||A&&!n)return p;if(u!=null)return u;throw new st(`Environment variable not found (${a})`)})}function QI(t){switch(t){case\"true\":case\"1\":case 1:case!0:return!0;case\"false\":case\"0\":case 0:case!1:return!1;default:throw new Error(`Couldn't parse \"${t}\" as a boolean`)}}function yne(t){return typeof t>\"u\"?t:QI(t)}function AL(t){try{return yne(t)}catch{return null}}function kZe(t){return!!(ue.isAbsolute(t)||t.match(/^(\\.{1,2}|~)\\//))}function Ene(t,...e){let r=u=>({value:u}),o=r(t),a=e.map(u=>r(u)),{value:n}=(0,lne.default)(o,...a,(u,A)=>{if(Array.isArray(u)&&Array.isArray(A)){for(let p of A)u.find(h=>(0,ane.default)(h,p))||u.push(p);return u}});return n}function QZe(...t){return Ene({},...t)}function FZe(t,e){let r=Object.create(null);for(let o of t){let a=o[e];r[a]??=[],r[a].push(o)}return r}function Qm(t){return typeof t==\"string\"?Number.parseInt(t,10):t}var ane,lne,cne,une,Ane,lL,fne,pne,sL,oL,aL,SI,one,mne,ql=Et(()=>{Pt();qt();ane=Ze(Vte()),lne=Ze(sne()),cne=Ze($o()),une=Ze(eg()),Ane=Ze(Jn()),lL=ve(\"stream\");fne=Symbol();ol.skip=fne;pne=Symbol();Vp.skip=pne;sL=class extends lL.Transform{constructor(){super(...arguments);this.chunks=[]}_transform(r,o,a){if(o!==\"buffer\"||!Buffer.isBuffer(r))throw new Error(\"Assertion failed: BufferStream only accept buffers\");this.chunks.push(r),a(null,null)}_flush(r){r(null,Buffer.concat(this.chunks))}};oL=class{constructor(e){this.deferred=new Map;this.promises=new Map;this.limit=(0,une.default)(e)}set(e,r){let o=this.deferred.get(e);typeof o>\"u\"&&this.deferred.set(e,o=hne());let a=this.limit(()=>r());return this.promises.set(e,a),a.then(()=>{this.promises.get(e)===a&&o.resolve()},n=>{this.promises.get(e)===a&&o.reject(n)}),o.promise}reduce(e,r){let o=this.promises.get(e)??Promise.resolve();this.set(e,()=>r(o))}async wait(){await Promise.all(this.promises.values())}},aL=class extends lL.Transform{constructor(r=Buffer.alloc(0)){super();this.active=!0;this.ifEmpty=r}_transform(r,o,a){if(o!==\"buffer\"||!Buffer.isBuffer(r))throw new Error(\"Assertion failed: DefaultStream only accept buffers\");this.active=!1,a(null,r)}_flush(r){this.active&&this.ifEmpty.length>0?r(null,this.ifEmpty):r(null)}},SI=eval(\"require\");one=new Map;mne=(o=>(o[o.NoCache=0]=\"NoCache\",o[o.FsTime=1]=\"FsTime\",o[o.Node=2]=\"Node\",o))(mne||{})});var Fm,fL,pL,Cne=Et(()=>{Fm=(r=>(r.HARD=\"HARD\",r.SOFT=\"SOFT\",r))(Fm||{}),fL=(o=>(o.Dependency=\"Dependency\",o.PeerDependency=\"PeerDependency\",o.PeerDependencyMeta=\"PeerDependencyMeta\",o))(fL||{}),pL=(o=>(o.Inactive=\"inactive\",o.Redundant=\"redundant\",o.Active=\"active\",o))(pL||{})});var pe={};Vt(pe,{LogLevel:()=>JP,Style:()=>KP,Type:()=>yt,addLogFilterSupport:()=>TI,applyColor:()=>Xs,applyHyperlink:()=>Tm,applyStyle:()=>fg,json:()=>pg,jsonOrPretty:()=>NZe,mark:()=>yL,pretty:()=>Ot,prettyField:()=>Xu,prettyList:()=>mL,prettyTruncatedLocatorList:()=>zP,stripAnsi:()=>Rm.default,supportsColor:()=>VP,supportsHyperlinks:()=>dL,tuple:()=>Hc});function wne(t){let e=[\"KiB\",\"MiB\",\"GiB\",\"TiB\"],r=e.length;for(;r>1&&t<1024**r;)r-=1;let o=1024**r;return`${Math.floor(t*100/o)/100} ${e[r-1]}`}function Hc(t,e){return[e,t]}function fg(t,e,r){return t.get(\"enableColors\")&&r&2&&(e=RI.default.bold(e)),e}function Xs(t,e,r){if(!t.get(\"enableColors\"))return e;let o=RZe.get(r);if(o===null)return e;let a=typeof o>\"u\"?r:gL.level>=3?o[0]:o[1],n=typeof a==\"number\"?hL.ansi256(a):a.startsWith(\"#\")?hL.hex(a):hL[a];if(typeof n!=\"function\")throw new Error(`Invalid format type ${a}`);return n(e)}function Tm(t,e,r){return t.get(\"enableHyperlinks\")?TZe?`\\x1B]8;;${r}\\x1B\\\\${e}\\x1B]8;;\\x1B\\\\`:`\\x1B]8;;${r}\\x07${e}\\x1B]8;;\\x07`:e}function Ot(t,e,r){if(e===null)return Xs(t,\"null\",yt.NULL);if(Object.hasOwn(WP,r))return WP[r].pretty(t,e);if(typeof e!=\"string\")throw new Error(`Assertion failed: Expected the value to be a string, got ${typeof e}`);return Xs(t,e,r)}function mL(t,e,r,{separator:o=\", \"}={}){return[...e].map(a=>Ot(t,a,r)).join(o)}function pg(t,e){if(t===null)return null;if(Object.hasOwn(WP,e))return WP[e].json(t);if(typeof t!=\"string\")throw new Error(`Assertion failed: Expected the value to be a string, got ${typeof t}`);return t}function NZe(t,e,[r,o]){return t?pg(r,o):Ot(e,r,o)}function yL(t){return{Check:Xs(t,\"\\u2713\",\"green\"),Cross:Xs(t,\"\\u2718\",\"red\"),Question:Xs(t,\"?\",\"cyan\")}}function Xu(t,{label:e,value:[r,o]}){return`${Ot(t,e,yt.CODE)}: ${Ot(t,r,o)}`}function zP(t,e,r){let o=[],a=[...e],n=r;for(;a.length>0;){let h=a[0],E=`${qr(t,h)}, `,I=EL(h).length+2;if(o.length>0&&n<I)break;o.push([E,I]),n-=I,a.shift()}if(a.length===0)return o.map(([h])=>h).join(\"\").slice(0,-2);let u=\"X\".repeat(a.length.toString().length),A=`and ${u} more.`,p=a.length;for(;o.length>1&&n<A.length;)n+=o[o.length-1][1],p+=1,o.pop();return[o.map(([h])=>h).join(\"\"),A.replace(u,Ot(t,p,yt.NUMBER))].join(\"\")}function TI(t,{configuration:e}){let r=e.get(\"logFilters\"),o=new Map,a=new Map,n=[];for(let I of r){let v=I.get(\"level\");if(typeof v>\"u\")continue;let x=I.get(\"code\");typeof x<\"u\"&&o.set(x,v);let C=I.get(\"text\");typeof C<\"u\"&&a.set(C,v);let R=I.get(\"pattern\");typeof R<\"u\"&&n.push([Ine.default.matcher(R,{contains:!0}),v])}n.reverse();let u=(I,v,x)=>{if(I===null||I===0)return x;let C=a.size>0||n.length>0?(0,Rm.default)(v):v;if(a.size>0){let R=a.get(C);if(typeof R<\"u\")return R??x}if(n.length>0){for(let[R,L]of n)if(R(C))return L??x}if(o.size>0){let R=o.get(Ku(I));if(typeof R<\"u\")return R??x}return x},A=t.reportInfo,p=t.reportWarning,h=t.reportError,E=function(I,v,x,C){switch(u(v,x,C)){case\"info\":A.call(I,v,x);break;case\"warning\":p.call(I,v??0,x);break;case\"error\":h.call(I,v??0,x);break}};t.reportInfo=function(...I){return E(this,...I,\"info\")},t.reportWarning=function(...I){return E(this,...I,\"warning\")},t.reportError=function(...I){return E(this,...I,\"error\")}}var RI,FI,Ine,Rm,Bne,yt,KP,gL,VP,dL,hL,RZe,bo,WP,TZe,JP,jl=Et(()=>{Pt();RI=Ze(pN()),FI=Ze(X0());qt();Ine=Ze($o()),Rm=Ze(BP()),Bne=ve(\"util\");$D();So();yt={NO_HINT:\"NO_HINT\",ID:\"ID\",NULL:\"NULL\",SCOPE:\"SCOPE\",NAME:\"NAME\",RANGE:\"RANGE\",REFERENCE:\"REFERENCE\",NUMBER:\"NUMBER\",PATH:\"PATH\",URL:\"URL\",ADDED:\"ADDED\",REMOVED:\"REMOVED\",CODE:\"CODE\",INSPECT:\"INSPECT\",DURATION:\"DURATION\",SIZE:\"SIZE\",SIZE_DIFF:\"SIZE_DIFF\",IDENT:\"IDENT\",DESCRIPTOR:\"DESCRIPTOR\",LOCATOR:\"LOCATOR\",RESOLUTION:\"RESOLUTION\",DEPENDENT:\"DEPENDENT\",PACKAGE_EXTENSION:\"PACKAGE_EXTENSION\",SETTING:\"SETTING\",MARKDOWN:\"MARKDOWN\",MARKDOWN_INLINE:\"MARKDOWN_INLINE\"},KP=(e=>(e[e.BOLD=2]=\"BOLD\",e))(KP||{}),gL=FI.default.GITHUB_ACTIONS?{level:2}:RI.default.supportsColor?{level:RI.default.supportsColor.level}:{level:0},VP=gL.level!==0,dL=VP&&!FI.default.GITHUB_ACTIONS&&!FI.default.CIRCLE&&!FI.default.GITLAB,hL=new RI.default.Instance(gL),RZe=new Map([[yt.NO_HINT,null],[yt.NULL,[\"#a853b5\",129]],[yt.SCOPE,[\"#d75f00\",166]],[yt.NAME,[\"#d7875f\",173]],[yt.RANGE,[\"#00afaf\",37]],[yt.REFERENCE,[\"#87afff\",111]],[yt.NUMBER,[\"#ffd700\",220]],[yt.PATH,[\"#d75fd7\",170]],[yt.URL,[\"#d75fd7\",170]],[yt.ADDED,[\"#5faf00\",70]],[yt.REMOVED,[\"#ff3131\",160]],[yt.CODE,[\"#87afff\",111]],[yt.SIZE,[\"#ffd700\",220]]]),bo=t=>t;WP={[yt.ID]:bo({pretty:(t,e)=>typeof e==\"number\"?Xs(t,`${e}`,yt.NUMBER):Xs(t,e,yt.CODE),json:t=>t}),[yt.INSPECT]:bo({pretty:(t,e)=>(0,Bne.inspect)(e,{depth:1/0,colors:t.get(\"enableColors\"),compact:!0,breakLength:1/0}),json:t=>t}),[yt.NUMBER]:bo({pretty:(t,e)=>Xs(t,`${e}`,yt.NUMBER),json:t=>t}),[yt.IDENT]:bo({pretty:(t,e)=>Oi(t,e),json:t=>rn(t)}),[yt.LOCATOR]:bo({pretty:(t,e)=>qr(t,e),json:t=>ka(t)}),[yt.DESCRIPTOR]:bo({pretty:(t,e)=>jn(t,e),json:t=>xa(t)}),[yt.RESOLUTION]:bo({pretty:(t,{descriptor:e,locator:r})=>NI(t,e,r),json:({descriptor:t,locator:e})=>({descriptor:xa(t),locator:e!==null?ka(e):null})}),[yt.DEPENDENT]:bo({pretty:(t,{locator:e,descriptor:r})=>CL(t,e,r),json:({locator:t,descriptor:e})=>({locator:ka(t),descriptor:xa(e)})}),[yt.PACKAGE_EXTENSION]:bo({pretty:(t,e)=>{switch(e.type){case\"Dependency\":return`${Oi(t,e.parentDescriptor)} \\u27A4 ${Xs(t,\"dependencies\",yt.CODE)} \\u27A4 ${Oi(t,e.descriptor)}`;case\"PeerDependency\":return`${Oi(t,e.parentDescriptor)} \\u27A4 ${Xs(t,\"peerDependencies\",yt.CODE)} \\u27A4 ${Oi(t,e.descriptor)}`;case\"PeerDependencyMeta\":return`${Oi(t,e.parentDescriptor)} \\u27A4 ${Xs(t,\"peerDependenciesMeta\",yt.CODE)} \\u27A4 ${Oi(t,ea(e.selector))} \\u27A4 ${Xs(t,e.key,yt.CODE)}`;default:throw new Error(`Assertion failed: Unsupported package extension type: ${e.type}`)}},json:t=>{switch(t.type){case\"Dependency\":return`${rn(t.parentDescriptor)} > ${rn(t.descriptor)}`;case\"PeerDependency\":return`${rn(t.parentDescriptor)} >> ${rn(t.descriptor)}`;case\"PeerDependencyMeta\":return`${rn(t.parentDescriptor)} >> ${t.selector} / ${t.key}`;default:throw new Error(`Assertion failed: Unsupported package extension type: ${t.type}`)}}}),[yt.SETTING]:bo({pretty:(t,e)=>(t.get(e),Tm(t,Xs(t,e,yt.CODE),`https://yarnpkg.com/configuration/yarnrc#${e}`)),json:t=>t}),[yt.DURATION]:bo({pretty:(t,e)=>{if(e>1e3*60){let r=Math.floor(e/1e3/60),o=Math.ceil((e-r*60*1e3)/1e3);return o===0?`${r}m`:`${r}m ${o}s`}else{let r=Math.floor(e/1e3),o=e-r*1e3;return o===0?`${r}s`:`${r}s ${o}ms`}},json:t=>t}),[yt.SIZE]:bo({pretty:(t,e)=>Xs(t,wne(e),yt.NUMBER),json:t=>t}),[yt.SIZE_DIFF]:bo({pretty:(t,e)=>{let r=e>=0?\"+\":\"-\",o=r===\"+\"?yt.REMOVED:yt.ADDED;return Xs(t,`${r} ${wne(Math.max(Math.abs(e),1))}`,o)},json:t=>t}),[yt.PATH]:bo({pretty:(t,e)=>Xs(t,ue.fromPortablePath(e),yt.PATH),json:t=>ue.fromPortablePath(t)}),[yt.MARKDOWN]:bo({pretty:(t,{text:e,format:r,paragraphs:o})=>Do(e,{format:r,paragraphs:o}),json:({text:t})=>t}),[yt.MARKDOWN_INLINE]:bo({pretty:(t,e)=>(e=e.replace(/(`+)((?:.|[\\n])*?)\\1/g,(r,o,a)=>Ot(t,o+a+o,yt.CODE)),e=e.replace(/(\\*\\*)((?:.|[\\n])*?)\\1/g,(r,o,a)=>fg(t,a,2)),e),json:t=>t})};TZe=!!process.env.KONSOLE_VERSION;JP=(a=>(a.Error=\"error\",a.Warning=\"warning\",a.Info=\"info\",a.Discard=\"discard\",a))(JP||{})});var vne=_(Nm=>{\"use strict\";Object.defineProperty(Nm,\"__esModule\",{value:!0});Nm.splitWhen=Nm.flatten=void 0;function LZe(t){return t.reduce((e,r)=>[].concat(e,r),[])}Nm.flatten=LZe;function MZe(t,e){let r=[[]],o=0;for(let a of t)e(a)?(o++,r[o]=[]):r[o].push(a);return r}Nm.splitWhen=MZe});var Dne=_(XP=>{\"use strict\";Object.defineProperty(XP,\"__esModule\",{value:!0});XP.isEnoentCodeError=void 0;function OZe(t){return t.code===\"ENOENT\"}XP.isEnoentCodeError=OZe});var Pne=_(ZP=>{\"use strict\";Object.defineProperty(ZP,\"__esModule\",{value:!0});ZP.createDirentFromStats=void 0;var wL=class{constructor(e,r){this.name=e,this.isBlockDevice=r.isBlockDevice.bind(r),this.isCharacterDevice=r.isCharacterDevice.bind(r),this.isDirectory=r.isDirectory.bind(r),this.isFIFO=r.isFIFO.bind(r),this.isFile=r.isFile.bind(r),this.isSocket=r.isSocket.bind(r),this.isSymbolicLink=r.isSymbolicLink.bind(r)}};function UZe(t,e){return new wL(t,e)}ZP.createDirentFromStats=UZe});var kne=_(Vi=>{\"use strict\";Object.defineProperty(Vi,\"__esModule\",{value:!0});Vi.convertPosixPathToPattern=Vi.convertWindowsPathToPattern=Vi.convertPathToPattern=Vi.escapePosixPath=Vi.escapeWindowsPath=Vi.escape=Vi.removeLeadingDotSegment=Vi.makeAbsolute=Vi.unixify=void 0;var _Ze=ve(\"os\"),HZe=ve(\"path\"),bne=_Ze.platform()===\"win32\",qZe=2,jZe=/(\\\\?)([()*?[\\]{|}]|^!|[!+@](?=\\()|\\\\(?![!()*+?@[\\]{|}]))/g,GZe=/(\\\\?)([()[\\]{}]|^!|[!+@](?=\\())/g,YZe=/^\\\\\\\\([.?])/,WZe=/\\\\(?![!()+@[\\]{}])/g;function KZe(t){return t.replace(/\\\\/g,\"/\")}Vi.unixify=KZe;function VZe(t,e){return HZe.resolve(t,e)}Vi.makeAbsolute=VZe;function zZe(t){if(t.charAt(0)===\".\"){let e=t.charAt(1);if(e===\"/\"||e===\"\\\\\")return t.slice(qZe)}return t}Vi.removeLeadingDotSegment=zZe;Vi.escape=bne?IL:BL;function IL(t){return t.replace(GZe,\"\\\\$2\")}Vi.escapeWindowsPath=IL;function BL(t){return t.replace(jZe,\"\\\\$2\")}Vi.escapePosixPath=BL;Vi.convertPathToPattern=bne?Sne:xne;function Sne(t){return IL(t).replace(YZe,\"//$1\").replace(WZe,\"/\")}Vi.convertWindowsPathToPattern=Sne;function xne(t){return BL(t)}Vi.convertPosixPathToPattern=xne});var Fne=_((RTt,Qne)=>{Qne.exports=function(e){if(typeof e!=\"string\"||e===\"\")return!1;for(var r;r=/(\\\\).|([@?!+*]\\(.*\\))/g.exec(e);){if(r[2])return!0;e=e.slice(r.index+r[0].length)}return!1}});var Nne=_((TTt,Tne)=>{var JZe=Fne(),Rne={\"{\":\"}\",\"(\":\")\",\"[\":\"]\"},XZe=function(t){if(t[0]===\"!\")return!0;for(var e=0,r=-2,o=-2,a=-2,n=-2,u=-2;e<t.length;){if(t[e]===\"*\"||t[e+1]===\"?\"&&/[\\].+)]/.test(t[e])||o!==-1&&t[e]===\"[\"&&t[e+1]!==\"]\"&&(o<e&&(o=t.indexOf(\"]\",e)),o>e&&(u===-1||u>o||(u=t.indexOf(\"\\\\\",e),u===-1||u>o)))||a!==-1&&t[e]===\"{\"&&t[e+1]!==\"}\"&&(a=t.indexOf(\"}\",e),a>e&&(u=t.indexOf(\"\\\\\",e),u===-1||u>a))||n!==-1&&t[e]===\"(\"&&t[e+1]===\"?\"&&/[:!=]/.test(t[e+2])&&t[e+3]!==\")\"&&(n=t.indexOf(\")\",e),n>e&&(u=t.indexOf(\"\\\\\",e),u===-1||u>n))||r!==-1&&t[e]===\"(\"&&t[e+1]!==\"|\"&&(r<e&&(r=t.indexOf(\"|\",e)),r!==-1&&t[r+1]!==\")\"&&(n=t.indexOf(\")\",r),n>r&&(u=t.indexOf(\"\\\\\",r),u===-1||u>n))))return!0;if(t[e]===\"\\\\\"){var A=t[e+1];e+=2;var p=Rne[A];if(p){var h=t.indexOf(p,e);h!==-1&&(e=h+1)}if(t[e]===\"!\")return!0}else e++}return!1},ZZe=function(t){if(t[0]===\"!\")return!0;for(var e=0;e<t.length;){if(/[*?{}()[\\]]/.test(t[e]))return!0;if(t[e]===\"\\\\\"){var r=t[e+1];e+=2;var o=Rne[r];if(o){var a=t.indexOf(o,e);a!==-1&&(e=a+1)}if(t[e]===\"!\")return!0}else e++}return!1};Tne.exports=function(e,r){if(typeof e!=\"string\"||e===\"\")return!1;if(JZe(e))return!0;var o=XZe;return r&&r.strict===!1&&(o=ZZe),o(e)}});var Mne=_((NTt,Lne)=>{\"use strict\";var $Ze=Nne(),e$e=ve(\"path\").posix.dirname,t$e=ve(\"os\").platform()===\"win32\",vL=\"/\",r$e=/\\\\/g,n$e=/[\\{\\[].*[\\}\\]]$/,i$e=/(^|[^\\\\])([\\{\\[]|\\([^\\)]+$)/,s$e=/\\\\([\\!\\*\\?\\|\\[\\]\\(\\)\\{\\}])/g;Lne.exports=function(e,r){var o=Object.assign({flipBackslashes:!0},r);o.flipBackslashes&&t$e&&e.indexOf(vL)<0&&(e=e.replace(r$e,vL)),n$e.test(e)&&(e+=vL),e+=\"a\";do e=e$e(e);while($Ze(e)||i$e.test(e));return e.replace(s$e,\"$1\")}});var Yne=_(Nr=>{\"use strict\";Object.defineProperty(Nr,\"__esModule\",{value:!0});Nr.removeDuplicateSlashes=Nr.matchAny=Nr.convertPatternsToRe=Nr.makeRe=Nr.getPatternParts=Nr.expandBraceExpansion=Nr.expandPatternsWithBraceExpansion=Nr.isAffectDepthOfReadingPattern=Nr.endsWithSlashGlobStar=Nr.hasGlobStar=Nr.getBaseDirectory=Nr.isPatternRelatedToParentDirectory=Nr.getPatternsOutsideCurrentDirectory=Nr.getPatternsInsideCurrentDirectory=Nr.getPositivePatterns=Nr.getNegativePatterns=Nr.isPositivePattern=Nr.isNegativePattern=Nr.convertToNegativePattern=Nr.convertToPositivePattern=Nr.isDynamicPattern=Nr.isStaticPattern=void 0;var o$e=ve(\"path\"),a$e=Mne(),DL=$o(),One=\"**\",l$e=\"\\\\\",c$e=/[*?]|^!/,u$e=/\\[[^[]*]/,A$e=/(?:^|[^!*+?@])\\([^(]*\\|[^|]*\\)/,f$e=/[!*+?@]\\([^(]*\\)/,p$e=/,|\\.\\./,h$e=/(?!^)\\/{2,}/g;function Une(t,e={}){return!_ne(t,e)}Nr.isStaticPattern=Une;function _ne(t,e={}){return t===\"\"?!1:!!(e.caseSensitiveMatch===!1||t.includes(l$e)||c$e.test(t)||u$e.test(t)||A$e.test(t)||e.extglob!==!1&&f$e.test(t)||e.braceExpansion!==!1&&g$e(t))}Nr.isDynamicPattern=_ne;function g$e(t){let e=t.indexOf(\"{\");if(e===-1)return!1;let r=t.indexOf(\"}\",e+1);if(r===-1)return!1;let o=t.slice(e,r);return p$e.test(o)}function d$e(t){return $P(t)?t.slice(1):t}Nr.convertToPositivePattern=d$e;function m$e(t){return\"!\"+t}Nr.convertToNegativePattern=m$e;function $P(t){return t.startsWith(\"!\")&&t[1]!==\"(\"}Nr.isNegativePattern=$P;function Hne(t){return!$P(t)}Nr.isPositivePattern=Hne;function y$e(t){return t.filter($P)}Nr.getNegativePatterns=y$e;function E$e(t){return t.filter(Hne)}Nr.getPositivePatterns=E$e;function C$e(t){return t.filter(e=>!PL(e))}Nr.getPatternsInsideCurrentDirectory=C$e;function w$e(t){return t.filter(PL)}Nr.getPatternsOutsideCurrentDirectory=w$e;function PL(t){return t.startsWith(\"..\")||t.startsWith(\"./..\")}Nr.isPatternRelatedToParentDirectory=PL;function I$e(t){return a$e(t,{flipBackslashes:!1})}Nr.getBaseDirectory=I$e;function B$e(t){return t.includes(One)}Nr.hasGlobStar=B$e;function qne(t){return t.endsWith(\"/\"+One)}Nr.endsWithSlashGlobStar=qne;function v$e(t){let e=o$e.basename(t);return qne(t)||Une(e)}Nr.isAffectDepthOfReadingPattern=v$e;function D$e(t){return t.reduce((e,r)=>e.concat(jne(r)),[])}Nr.expandPatternsWithBraceExpansion=D$e;function jne(t){let e=DL.braces(t,{expand:!0,nodupes:!0,keepEscaping:!0});return e.sort((r,o)=>r.length-o.length),e.filter(r=>r!==\"\")}Nr.expandBraceExpansion=jne;function P$e(t,e){let{parts:r}=DL.scan(t,Object.assign(Object.assign({},e),{parts:!0}));return r.length===0&&(r=[t]),r[0].startsWith(\"/\")&&(r[0]=r[0].slice(1),r.unshift(\"\")),r}Nr.getPatternParts=P$e;function Gne(t,e){return DL.makeRe(t,e)}Nr.makeRe=Gne;function b$e(t,e){return t.map(r=>Gne(r,e))}Nr.convertPatternsToRe=b$e;function S$e(t,e){return e.some(r=>r.test(t))}Nr.matchAny=S$e;function x$e(t){return t.replace(h$e,\"/\")}Nr.removeDuplicateSlashes=x$e});var zne=_((MTt,Vne)=>{\"use strict\";var k$e=ve(\"stream\"),Wne=k$e.PassThrough,Q$e=Array.prototype.slice;Vne.exports=F$e;function F$e(){let t=[],e=Q$e.call(arguments),r=!1,o=e[e.length-1];o&&!Array.isArray(o)&&o.pipe==null?e.pop():o={};let a=o.end!==!1,n=o.pipeError===!0;o.objectMode==null&&(o.objectMode=!0),o.highWaterMark==null&&(o.highWaterMark=64*1024);let u=Wne(o);function A(){for(let E=0,I=arguments.length;E<I;E++)t.push(Kne(arguments[E],o));return p(),this}function p(){if(r)return;r=!0;let E=t.shift();if(!E){process.nextTick(h);return}Array.isArray(E)||(E=[E]);let I=E.length+1;function v(){--I>0||(r=!1,p())}function x(C){function R(){C.removeListener(\"merge2UnpipeEnd\",R),C.removeListener(\"end\",R),n&&C.removeListener(\"error\",L),v()}function L(U){u.emit(\"error\",U)}if(C._readableState.endEmitted)return v();C.on(\"merge2UnpipeEnd\",R),C.on(\"end\",R),n&&C.on(\"error\",L),C.pipe(u,{end:!1}),C.resume()}for(let C=0;C<E.length;C++)x(E[C]);v()}function h(){r=!1,u.emit(\"queueDrain\"),a&&u.end()}return u.setMaxListeners(0),u.add=A,u.on(\"unpipe\",function(E){E.emit(\"merge2UnpipeEnd\")}),e.length&&A.apply(null,e),u}function Kne(t,e){if(Array.isArray(t))for(let r=0,o=t.length;r<o;r++)t[r]=Kne(t[r],e);else{if(!t._readableState&&t.pipe&&(t=t.pipe(Wne(e))),!t._readableState||!t.pause||!t.pipe)throw new Error(\"Only readable stream can be merged.\");t.pause()}return t}});var Xne=_(eb=>{\"use strict\";Object.defineProperty(eb,\"__esModule\",{value:!0});eb.merge=void 0;var R$e=zne();function T$e(t){let e=R$e(t);return t.forEach(r=>{r.once(\"error\",o=>e.emit(\"error\",o))}),e.once(\"close\",()=>Jne(t)),e.once(\"end\",()=>Jne(t)),e}eb.merge=T$e;function Jne(t){t.forEach(e=>e.emit(\"close\"))}});var Zne=_(Lm=>{\"use strict\";Object.defineProperty(Lm,\"__esModule\",{value:!0});Lm.isEmpty=Lm.isString=void 0;function N$e(t){return typeof t==\"string\"}Lm.isString=N$e;function L$e(t){return t===\"\"}Lm.isEmpty=L$e});var Df=_(xo=>{\"use strict\";Object.defineProperty(xo,\"__esModule\",{value:!0});xo.string=xo.stream=xo.pattern=xo.path=xo.fs=xo.errno=xo.array=void 0;var M$e=vne();xo.array=M$e;var O$e=Dne();xo.errno=O$e;var U$e=Pne();xo.fs=U$e;var _$e=kne();xo.path=_$e;var H$e=Yne();xo.pattern=H$e;var q$e=Xne();xo.stream=q$e;var j$e=Zne();xo.string=j$e});var rie=_(ko=>{\"use strict\";Object.defineProperty(ko,\"__esModule\",{value:!0});ko.convertPatternGroupToTask=ko.convertPatternGroupsToTasks=ko.groupPatternsByBaseDirectory=ko.getNegativePatternsAsPositive=ko.getPositivePatterns=ko.convertPatternsToTasks=ko.generate=void 0;var qc=Df();function G$e(t,e){let r=$ne(t,e),o=$ne(e.ignore,e),a=eie(r),n=tie(r,o),u=a.filter(E=>qc.pattern.isStaticPattern(E,e)),A=a.filter(E=>qc.pattern.isDynamicPattern(E,e)),p=bL(u,n,!1),h=bL(A,n,!0);return p.concat(h)}ko.generate=G$e;function $ne(t,e){let r=t;return e.braceExpansion&&(r=qc.pattern.expandPatternsWithBraceExpansion(r)),e.baseNameMatch&&(r=r.map(o=>o.includes(\"/\")?o:`**/${o}`)),r.map(o=>qc.pattern.removeDuplicateSlashes(o))}function bL(t,e,r){let o=[],a=qc.pattern.getPatternsOutsideCurrentDirectory(t),n=qc.pattern.getPatternsInsideCurrentDirectory(t),u=SL(a),A=SL(n);return o.push(...xL(u,e,r)),\".\"in A?o.push(kL(\".\",n,e,r)):o.push(...xL(A,e,r)),o}ko.convertPatternsToTasks=bL;function eie(t){return qc.pattern.getPositivePatterns(t)}ko.getPositivePatterns=eie;function tie(t,e){return qc.pattern.getNegativePatterns(t).concat(e).map(qc.pattern.convertToPositivePattern)}ko.getNegativePatternsAsPositive=tie;function SL(t){let e={};return t.reduce((r,o)=>{let a=qc.pattern.getBaseDirectory(o);return a in r?r[a].push(o):r[a]=[o],r},e)}ko.groupPatternsByBaseDirectory=SL;function xL(t,e,r){return Object.keys(t).map(o=>kL(o,t[o],e,r))}ko.convertPatternGroupsToTasks=xL;function kL(t,e,r,o){return{dynamic:o,positive:e,negative:r,base:t,patterns:[].concat(e,r.map(qc.pattern.convertToNegativePattern))}}ko.convertPatternGroupToTask=kL});var iie=_(tb=>{\"use strict\";Object.defineProperty(tb,\"__esModule\",{value:!0});tb.read=void 0;function Y$e(t,e,r){e.fs.lstat(t,(o,a)=>{if(o!==null){nie(r,o);return}if(!a.isSymbolicLink()||!e.followSymbolicLink){QL(r,a);return}e.fs.stat(t,(n,u)=>{if(n!==null){if(e.throwErrorOnBrokenSymbolicLink){nie(r,n);return}QL(r,a);return}e.markSymbolicLink&&(u.isSymbolicLink=()=>!0),QL(r,u)})})}tb.read=Y$e;function nie(t,e){t(e)}function QL(t,e){t(null,e)}});var sie=_(rb=>{\"use strict\";Object.defineProperty(rb,\"__esModule\",{value:!0});rb.read=void 0;function W$e(t,e){let r=e.fs.lstatSync(t);if(!r.isSymbolicLink()||!e.followSymbolicLink)return r;try{let o=e.fs.statSync(t);return e.markSymbolicLink&&(o.isSymbolicLink=()=>!0),o}catch(o){if(!e.throwErrorOnBrokenSymbolicLink)return r;throw o}}rb.read=W$e});var oie=_(zp=>{\"use strict\";Object.defineProperty(zp,\"__esModule\",{value:!0});zp.createFileSystemAdapter=zp.FILE_SYSTEM_ADAPTER=void 0;var nb=ve(\"fs\");zp.FILE_SYSTEM_ADAPTER={lstat:nb.lstat,stat:nb.stat,lstatSync:nb.lstatSync,statSync:nb.statSync};function K$e(t){return t===void 0?zp.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},zp.FILE_SYSTEM_ADAPTER),t)}zp.createFileSystemAdapter=K$e});var aie=_(RL=>{\"use strict\";Object.defineProperty(RL,\"__esModule\",{value:!0});var V$e=oie(),FL=class{constructor(e={}){this._options=e,this.followSymbolicLink=this._getValue(this._options.followSymbolicLink,!0),this.fs=V$e.createFileSystemAdapter(this._options.fs),this.markSymbolicLink=this._getValue(this._options.markSymbolicLink,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0)}_getValue(e,r){return e??r}};RL.default=FL});var hg=_(Jp=>{\"use strict\";Object.defineProperty(Jp,\"__esModule\",{value:!0});Jp.statSync=Jp.stat=Jp.Settings=void 0;var lie=iie(),z$e=sie(),TL=aie();Jp.Settings=TL.default;function J$e(t,e,r){if(typeof e==\"function\"){lie.read(t,NL(),e);return}lie.read(t,NL(e),r)}Jp.stat=J$e;function X$e(t,e){let r=NL(e);return z$e.read(t,r)}Jp.statSync=X$e;function NL(t={}){return t instanceof TL.default?t:new TL.default(t)}});var Aie=_((KTt,uie)=>{var cie;uie.exports=typeof queueMicrotask==\"function\"?queueMicrotask.bind(typeof window<\"u\"?window:global):t=>(cie||(cie=Promise.resolve())).then(t).catch(e=>setTimeout(()=>{throw e},0))});var pie=_((VTt,fie)=>{fie.exports=$$e;var Z$e=Aie();function $$e(t,e){let r,o,a,n=!0;Array.isArray(t)?(r=[],o=t.length):(a=Object.keys(t),r={},o=a.length);function u(p){function h(){e&&e(p,r),e=null}n?Z$e(h):h()}function A(p,h,E){r[p]=E,(--o===0||h)&&u(h)}o?a?a.forEach(function(p){t[p](function(h,E){A(p,h,E)})}):t.forEach(function(p,h){p(function(E,I){A(h,E,I)})}):u(null),n=!1}});var LL=_(sb=>{\"use strict\";Object.defineProperty(sb,\"__esModule\",{value:!0});sb.IS_SUPPORT_READDIR_WITH_FILE_TYPES=void 0;var ib=process.versions.node.split(\".\");if(ib[0]===void 0||ib[1]===void 0)throw new Error(`Unexpected behavior. The 'process.versions.node' variable has invalid value: ${process.versions.node}`);var hie=Number.parseInt(ib[0],10),eet=Number.parseInt(ib[1],10),gie=10,tet=10,ret=hie>gie,net=hie===gie&&eet>=tet;sb.IS_SUPPORT_READDIR_WITH_FILE_TYPES=ret||net});var die=_(ob=>{\"use strict\";Object.defineProperty(ob,\"__esModule\",{value:!0});ob.createDirentFromStats=void 0;var ML=class{constructor(e,r){this.name=e,this.isBlockDevice=r.isBlockDevice.bind(r),this.isCharacterDevice=r.isCharacterDevice.bind(r),this.isDirectory=r.isDirectory.bind(r),this.isFIFO=r.isFIFO.bind(r),this.isFile=r.isFile.bind(r),this.isSocket=r.isSocket.bind(r),this.isSymbolicLink=r.isSymbolicLink.bind(r)}};function iet(t,e){return new ML(t,e)}ob.createDirentFromStats=iet});var OL=_(ab=>{\"use strict\";Object.defineProperty(ab,\"__esModule\",{value:!0});ab.fs=void 0;var set=die();ab.fs=set});var UL=_(lb=>{\"use strict\";Object.defineProperty(lb,\"__esModule\",{value:!0});lb.joinPathSegments=void 0;function oet(t,e,r){return t.endsWith(r)?t+e:t+r+e}lb.joinPathSegments=oet});var Iie=_(Xp=>{\"use strict\";Object.defineProperty(Xp,\"__esModule\",{value:!0});Xp.readdir=Xp.readdirWithFileTypes=Xp.read=void 0;var aet=hg(),mie=pie(),cet=LL(),yie=OL(),Eie=UL();function uet(t,e,r){if(!e.stats&&cet.IS_SUPPORT_READDIR_WITH_FILE_TYPES){Cie(t,e,r);return}wie(t,e,r)}Xp.read=uet;function Cie(t,e,r){e.fs.readdir(t,{withFileTypes:!0},(o,a)=>{if(o!==null){ub(r,o);return}let n=a.map(A=>({dirent:A,name:A.name,path:Eie.joinPathSegments(t,A.name,e.pathSegmentSeparator)}));if(!e.followSymbolicLinks){_L(r,n);return}let u=n.map(A=>Aet(A,e));mie(u,(A,p)=>{if(A!==null){ub(r,A);return}_L(r,p)})})}Xp.readdirWithFileTypes=Cie;function Aet(t,e){return r=>{if(!t.dirent.isSymbolicLink()){r(null,t);return}e.fs.stat(t.path,(o,a)=>{if(o!==null){if(e.throwErrorOnBrokenSymbolicLink){r(o);return}r(null,t);return}t.dirent=yie.fs.createDirentFromStats(t.name,a),r(null,t)})}}function wie(t,e,r){e.fs.readdir(t,(o,a)=>{if(o!==null){ub(r,o);return}let n=a.map(u=>{let A=Eie.joinPathSegments(t,u,e.pathSegmentSeparator);return p=>{aet.stat(A,e.fsStatSettings,(h,E)=>{if(h!==null){p(h);return}let I={name:u,path:A,dirent:yie.fs.createDirentFromStats(u,E)};e.stats&&(I.stats=E),p(null,I)})}});mie(n,(u,A)=>{if(u!==null){ub(r,u);return}_L(r,A)})})}Xp.readdir=wie;function ub(t,e){t(e)}function _L(t,e){t(null,e)}});var bie=_(Zp=>{\"use strict\";Object.defineProperty(Zp,\"__esModule\",{value:!0});Zp.readdir=Zp.readdirWithFileTypes=Zp.read=void 0;var fet=hg(),pet=LL(),Bie=OL(),vie=UL();function het(t,e){return!e.stats&&pet.IS_SUPPORT_READDIR_WITH_FILE_TYPES?Die(t,e):Pie(t,e)}Zp.read=het;function Die(t,e){return e.fs.readdirSync(t,{withFileTypes:!0}).map(o=>{let a={dirent:o,name:o.name,path:vie.joinPathSegments(t,o.name,e.pathSegmentSeparator)};if(a.dirent.isSymbolicLink()&&e.followSymbolicLinks)try{let n=e.fs.statSync(a.path);a.dirent=Bie.fs.createDirentFromStats(a.name,n)}catch(n){if(e.throwErrorOnBrokenSymbolicLink)throw n}return a})}Zp.readdirWithFileTypes=Die;function Pie(t,e){return e.fs.readdirSync(t).map(o=>{let a=vie.joinPathSegments(t,o,e.pathSegmentSeparator),n=fet.statSync(a,e.fsStatSettings),u={name:o,path:a,dirent:Bie.fs.createDirentFromStats(o,n)};return e.stats&&(u.stats=n),u})}Zp.readdir=Pie});var Sie=_($p=>{\"use strict\";Object.defineProperty($p,\"__esModule\",{value:!0});$p.createFileSystemAdapter=$p.FILE_SYSTEM_ADAPTER=void 0;var Mm=ve(\"fs\");$p.FILE_SYSTEM_ADAPTER={lstat:Mm.lstat,stat:Mm.stat,lstatSync:Mm.lstatSync,statSync:Mm.statSync,readdir:Mm.readdir,readdirSync:Mm.readdirSync};function get(t){return t===void 0?$p.FILE_SYSTEM_ADAPTER:Object.assign(Object.assign({},$p.FILE_SYSTEM_ADAPTER),t)}$p.createFileSystemAdapter=get});var xie=_(qL=>{\"use strict\";Object.defineProperty(qL,\"__esModule\",{value:!0});var det=ve(\"path\"),met=hg(),yet=Sie(),HL=class{constructor(e={}){this._options=e,this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!1),this.fs=yet.createFileSystemAdapter(this._options.fs),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,det.sep),this.stats=this._getValue(this._options.stats,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!0),this.fsStatSettings=new met.Settings({followSymbolicLink:this.followSymbolicLinks,fs:this.fs,throwErrorOnBrokenSymbolicLink:this.throwErrorOnBrokenSymbolicLink})}_getValue(e,r){return e??r}};qL.default=HL});var Ab=_(eh=>{\"use strict\";Object.defineProperty(eh,\"__esModule\",{value:!0});eh.Settings=eh.scandirSync=eh.scandir=void 0;var kie=Iie(),Eet=bie(),jL=xie();eh.Settings=jL.default;function Cet(t,e,r){if(typeof e==\"function\"){kie.read(t,YL(),e);return}kie.read(t,YL(e),r)}eh.scandir=Cet;function wet(t,e){let r=YL(e);return Eet.read(t,r)}eh.scandirSync=wet;function YL(t={}){return t instanceof jL.default?t:new jL.default(t)}});var Fie=_((iNt,Qie)=>{\"use strict\";function Iet(t){var e=new t,r=e;function o(){var n=e;return n.next?e=n.next:(e=new t,r=e),n.next=null,n}function a(n){r.next=n,r=n}return{get:o,release:a}}Qie.exports=Iet});var Tie=_((sNt,WL)=>{\"use strict\";var Bet=Fie();function Rie(t,e,r){if(typeof t==\"function\"&&(r=e,e=t,t=null),!(r>=1))throw new Error(\"fastqueue concurrency must be equal to or greater than 1\");var o=Bet(vet),a=null,n=null,u=0,A=null,p={push:R,drain:Gl,saturated:Gl,pause:E,paused:!1,get concurrency(){return r},set concurrency(le){if(!(le>=1))throw new Error(\"fastqueue concurrency must be equal to or greater than 1\");if(r=le,!p.paused)for(;a&&u<r;)u++,U()},running:h,resume:x,idle:C,length:I,getQueue:v,unshift:L,empty:Gl,kill:z,killAndDrain:te,error:ae};return p;function h(){return u}function E(){p.paused=!0}function I(){for(var le=a,ce=0;le;)le=le.next,ce++;return ce}function v(){for(var le=a,ce=[];le;)ce.push(le.value),le=le.next;return ce}function x(){if(p.paused){if(p.paused=!1,a===null){u++,U();return}for(;a&&u<r;)u++,U()}}function C(){return u===0&&p.length()===0}function R(le,ce){var Ce=o.get();Ce.context=t,Ce.release=U,Ce.value=le,Ce.callback=ce||Gl,Ce.errorHandler=A,u>=r||p.paused?n?(n.next=Ce,n=Ce):(a=Ce,n=Ce,p.saturated()):(u++,e.call(t,Ce.value,Ce.worked))}function L(le,ce){var Ce=o.get();Ce.context=t,Ce.release=U,Ce.value=le,Ce.callback=ce||Gl,Ce.errorHandler=A,u>=r||p.paused?a?(Ce.next=a,a=Ce):(a=Ce,n=Ce,p.saturated()):(u++,e.call(t,Ce.value,Ce.worked))}function U(le){le&&o.release(le);var ce=a;ce&&u<=r?p.paused?u--:(n===a&&(n=null),a=ce.next,ce.next=null,e.call(t,ce.value,ce.worked),n===null&&p.empty()):--u===0&&p.drain()}function z(){a=null,n=null,p.drain=Gl}function te(){a=null,n=null,p.drain(),p.drain=Gl}function ae(le){A=le}}function Gl(){}function vet(){this.value=null,this.callback=Gl,this.next=null,this.release=Gl,this.context=null,this.errorHandler=null;var t=this;this.worked=function(r,o){var a=t.callback,n=t.errorHandler,u=t.value;t.value=null,t.callback=Gl,t.errorHandler&&n(r,u),a.call(t.context,r,o),t.release(t)}}function Det(t,e,r){typeof t==\"function\"&&(r=e,e=t,t=null);function o(E,I){e.call(this,E).then(function(v){I(null,v)},I)}var a=Rie(t,o,r),n=a.push,u=a.unshift;return a.push=A,a.unshift=p,a.drained=h,a;function A(E){var I=new Promise(function(v,x){n(E,function(C,R){if(C){x(C);return}v(R)})});return I.catch(Gl),I}function p(E){var I=new Promise(function(v,x){u(E,function(C,R){if(C){x(C);return}v(R)})});return I.catch(Gl),I}function h(){if(a.idle())return new Promise(function(v){v()});var E=a.drain,I=new Promise(function(v){a.drain=function(){E(),v()}});return I}}WL.exports=Rie;WL.exports.promise=Det});var fb=_(Zu=>{\"use strict\";Object.defineProperty(Zu,\"__esModule\",{value:!0});Zu.joinPathSegments=Zu.replacePathSegmentSeparator=Zu.isAppliedFilter=Zu.isFatalError=void 0;function Pet(t,e){return t.errorFilter===null?!0:!t.errorFilter(e)}Zu.isFatalError=Pet;function bet(t,e){return t===null||t(e)}Zu.isAppliedFilter=bet;function xet(t,e){return t.split(/[/\\\\]/).join(e)}Zu.replacePathSegmentSeparator=xet;function ket(t,e,r){return t===\"\"?e:t.endsWith(r)?t+e:t+r+e}Zu.joinPathSegments=ket});var zL=_(VL=>{\"use strict\";Object.defineProperty(VL,\"__esModule\",{value:!0});var Qet=fb(),KL=class{constructor(e,r){this._root=e,this._settings=r,this._root=Qet.replacePathSegmentSeparator(e,r.pathSegmentSeparator)}};VL.default=KL});var ZL=_(XL=>{\"use strict\";Object.defineProperty(XL,\"__esModule\",{value:!0});var Fet=ve(\"events\"),Ret=Ab(),Tet=Tie(),pb=fb(),Net=zL(),JL=class extends Net.default{constructor(e,r){super(e,r),this._settings=r,this._scandir=Ret.scandir,this._emitter=new Fet.EventEmitter,this._queue=Tet(this._worker.bind(this),this._settings.concurrency),this._isFatalError=!1,this._isDestroyed=!1,this._queue.drain=()=>{this._isFatalError||this._emitter.emit(\"end\")}}read(){return this._isFatalError=!1,this._isDestroyed=!1,setImmediate(()=>{this._pushToQueue(this._root,this._settings.basePath)}),this._emitter}get isDestroyed(){return this._isDestroyed}destroy(){if(this._isDestroyed)throw new Error(\"The reader is already destroyed\");this._isDestroyed=!0,this._queue.killAndDrain()}onEntry(e){this._emitter.on(\"entry\",e)}onError(e){this._emitter.once(\"error\",e)}onEnd(e){this._emitter.once(\"end\",e)}_pushToQueue(e,r){let o={directory:e,base:r};this._queue.push(o,a=>{a!==null&&this._handleError(a)})}_worker(e,r){this._scandir(e.directory,this._settings.fsScandirSettings,(o,a)=>{if(o!==null){r(o,void 0);return}for(let n of a)this._handleEntry(n,e.base);r(null,void 0)})}_handleError(e){this._isDestroyed||!pb.isFatalError(this._settings,e)||(this._isFatalError=!0,this._isDestroyed=!0,this._emitter.emit(\"error\",e))}_handleEntry(e,r){if(this._isDestroyed||this._isFatalError)return;let o=e.path;r!==void 0&&(e.path=pb.joinPathSegments(r,e.name,this._settings.pathSegmentSeparator)),pb.isAppliedFilter(this._settings.entryFilter,e)&&this._emitEntry(e),e.dirent.isDirectory()&&pb.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(o,r===void 0?void 0:e.path)}_emitEntry(e){this._emitter.emit(\"entry\",e)}};XL.default=JL});var Nie=_(eM=>{\"use strict\";Object.defineProperty(eM,\"__esModule\",{value:!0});var Let=ZL(),$L=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new Let.default(this._root,this._settings),this._storage=[]}read(e){this._reader.onError(r=>{Met(e,r)}),this._reader.onEntry(r=>{this._storage.push(r)}),this._reader.onEnd(()=>{Oet(e,this._storage)}),this._reader.read()}};eM.default=$L;function Met(t,e){t(e)}function Oet(t,e){t(null,e)}});var Lie=_(rM=>{\"use strict\";Object.defineProperty(rM,\"__esModule\",{value:!0});var Uet=ve(\"stream\"),_et=ZL(),tM=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new _et.default(this._root,this._settings),this._stream=new Uet.Readable({objectMode:!0,read:()=>{},destroy:()=>{this._reader.isDestroyed||this._reader.destroy()}})}read(){return this._reader.onError(e=>{this._stream.emit(\"error\",e)}),this._reader.onEntry(e=>{this._stream.push(e)}),this._reader.onEnd(()=>{this._stream.push(null)}),this._reader.read(),this._stream}};rM.default=tM});var Mie=_(iM=>{\"use strict\";Object.defineProperty(iM,\"__esModule\",{value:!0});var Het=Ab(),hb=fb(),qet=zL(),nM=class extends qet.default{constructor(){super(...arguments),this._scandir=Het.scandirSync,this._storage=[],this._queue=new Set}read(){return this._pushToQueue(this._root,this._settings.basePath),this._handleQueue(),this._storage}_pushToQueue(e,r){this._queue.add({directory:e,base:r})}_handleQueue(){for(let e of this._queue.values())this._handleDirectory(e.directory,e.base)}_handleDirectory(e,r){try{let o=this._scandir(e,this._settings.fsScandirSettings);for(let a of o)this._handleEntry(a,r)}catch(o){this._handleError(o)}}_handleError(e){if(hb.isFatalError(this._settings,e))throw e}_handleEntry(e,r){let o=e.path;r!==void 0&&(e.path=hb.joinPathSegments(r,e.name,this._settings.pathSegmentSeparator)),hb.isAppliedFilter(this._settings.entryFilter,e)&&this._pushToStorage(e),e.dirent.isDirectory()&&hb.isAppliedFilter(this._settings.deepFilter,e)&&this._pushToQueue(o,r===void 0?void 0:e.path)}_pushToStorage(e){this._storage.push(e)}};iM.default=nM});var Oie=_(oM=>{\"use strict\";Object.defineProperty(oM,\"__esModule\",{value:!0});var jet=Mie(),sM=class{constructor(e,r){this._root=e,this._settings=r,this._reader=new jet.default(this._root,this._settings)}read(){return this._reader.read()}};oM.default=sM});var Uie=_(lM=>{\"use strict\";Object.defineProperty(lM,\"__esModule\",{value:!0});var Get=ve(\"path\"),Yet=Ab(),aM=class{constructor(e={}){this._options=e,this.basePath=this._getValue(this._options.basePath,void 0),this.concurrency=this._getValue(this._options.concurrency,Number.POSITIVE_INFINITY),this.deepFilter=this._getValue(this._options.deepFilter,null),this.entryFilter=this._getValue(this._options.entryFilter,null),this.errorFilter=this._getValue(this._options.errorFilter,null),this.pathSegmentSeparator=this._getValue(this._options.pathSegmentSeparator,Get.sep),this.fsScandirSettings=new Yet.Settings({followSymbolicLinks:this._options.followSymbolicLinks,fs:this._options.fs,pathSegmentSeparator:this._options.pathSegmentSeparator,stats:this._options.stats,throwErrorOnBrokenSymbolicLink:this._options.throwErrorOnBrokenSymbolicLink})}_getValue(e,r){return e??r}};lM.default=aM});var db=_($u=>{\"use strict\";Object.defineProperty($u,\"__esModule\",{value:!0});$u.Settings=$u.walkStream=$u.walkSync=$u.walk=void 0;var _ie=Nie(),Wet=Lie(),Ket=Oie(),cM=Uie();$u.Settings=cM.default;function Vet(t,e,r){if(typeof e==\"function\"){new _ie.default(t,gb()).read(e);return}new _ie.default(t,gb(e)).read(r)}$u.walk=Vet;function zet(t,e){let r=gb(e);return new Ket.default(t,r).read()}$u.walkSync=zet;function Jet(t,e){let r=gb(e);return new Wet.default(t,r).read()}$u.walkStream=Jet;function gb(t={}){return t instanceof cM.default?t:new cM.default(t)}});var mb=_(AM=>{\"use strict\";Object.defineProperty(AM,\"__esModule\",{value:!0});var Xet=ve(\"path\"),Zet=hg(),Hie=Df(),uM=class{constructor(e){this._settings=e,this._fsStatSettings=new Zet.Settings({followSymbolicLink:this._settings.followSymbolicLinks,fs:this._settings.fs,throwErrorOnBrokenSymbolicLink:this._settings.followSymbolicLinks})}_getFullEntryPath(e){return Xet.resolve(this._settings.cwd,e)}_makeEntry(e,r){let o={name:r,path:r,dirent:Hie.fs.createDirentFromStats(r,e)};return this._settings.stats&&(o.stats=e),o}_isFatalError(e){return!Hie.errno.isEnoentCodeError(e)&&!this._settings.suppressErrors}};AM.default=uM});var hM=_(pM=>{\"use strict\";Object.defineProperty(pM,\"__esModule\",{value:!0});var $et=ve(\"stream\"),ett=hg(),ttt=db(),rtt=mb(),fM=class extends rtt.default{constructor(){super(...arguments),this._walkStream=ttt.walkStream,this._stat=ett.stat}dynamic(e,r){return this._walkStream(e,r)}static(e,r){let o=e.map(this._getFullEntryPath,this),a=new $et.PassThrough({objectMode:!0});a._write=(n,u,A)=>this._getEntry(o[n],e[n],r).then(p=>{p!==null&&r.entryFilter(p)&&a.push(p),n===o.length-1&&a.end(),A()}).catch(A);for(let n=0;n<o.length;n++)a.write(n);return a}_getEntry(e,r,o){return this._getStat(e).then(a=>this._makeEntry(a,r)).catch(a=>{if(o.errorFilter(a))return null;throw a})}_getStat(e){return new Promise((r,o)=>{this._stat(e,this._fsStatSettings,(a,n)=>a===null?r(n):o(a))})}};pM.default=fM});var qie=_(dM=>{\"use strict\";Object.defineProperty(dM,\"__esModule\",{value:!0});var ntt=db(),itt=mb(),stt=hM(),gM=class extends itt.default{constructor(){super(...arguments),this._walkAsync=ntt.walk,this._readerStream=new stt.default(this._settings)}dynamic(e,r){return new Promise((o,a)=>{this._walkAsync(e,r,(n,u)=>{n===null?o(u):a(n)})})}async static(e,r){let o=[],a=this._readerStream.static(e,r);return new Promise((n,u)=>{a.once(\"error\",u),a.on(\"data\",A=>o.push(A)),a.once(\"end\",()=>n(o))})}};dM.default=gM});var jie=_(yM=>{\"use strict\";Object.defineProperty(yM,\"__esModule\",{value:!0});var LI=Df(),mM=class{constructor(e,r,o){this._patterns=e,this._settings=r,this._micromatchOptions=o,this._storage=[],this._fillStorage()}_fillStorage(){for(let e of this._patterns){let r=this._getPatternSegments(e),o=this._splitSegmentsIntoSections(r);this._storage.push({complete:o.length<=1,pattern:e,segments:r,sections:o})}}_getPatternSegments(e){return LI.pattern.getPatternParts(e,this._micromatchOptions).map(o=>LI.pattern.isDynamicPattern(o,this._settings)?{dynamic:!0,pattern:o,patternRe:LI.pattern.makeRe(o,this._micromatchOptions)}:{dynamic:!1,pattern:o})}_splitSegmentsIntoSections(e){return LI.array.splitWhen(e,r=>r.dynamic&&LI.pattern.hasGlobStar(r.pattern))}};yM.default=mM});var Gie=_(CM=>{\"use strict\";Object.defineProperty(CM,\"__esModule\",{value:!0});var ott=jie(),EM=class extends ott.default{match(e){let r=e.split(\"/\"),o=r.length,a=this._storage.filter(n=>!n.complete||n.segments.length>o);for(let n of a){let u=n.sections[0];if(!n.complete&&o>u.length||r.every((p,h)=>{let E=n.segments[h];return!!(E.dynamic&&E.patternRe.test(p)||!E.dynamic&&E.pattern===p)}))return!0}return!1}};CM.default=EM});var Yie=_(IM=>{\"use strict\";Object.defineProperty(IM,\"__esModule\",{value:!0});var yb=Df(),att=Gie(),wM=class{constructor(e,r){this._settings=e,this._micromatchOptions=r}getFilter(e,r,o){let a=this._getMatcher(r),n=this._getNegativePatternsRe(o);return u=>this._filter(e,u,a,n)}_getMatcher(e){return new att.default(e,this._settings,this._micromatchOptions)}_getNegativePatternsRe(e){let r=e.filter(yb.pattern.isAffectDepthOfReadingPattern);return yb.pattern.convertPatternsToRe(r,this._micromatchOptions)}_filter(e,r,o,a){if(this._isSkippedByDeep(e,r.path)||this._isSkippedSymbolicLink(r))return!1;let n=yb.path.removeLeadingDotSegment(r.path);return this._isSkippedByPositivePatterns(n,o)?!1:this._isSkippedByNegativePatterns(n,a)}_isSkippedByDeep(e,r){return this._settings.deep===1/0?!1:this._getEntryLevel(e,r)>=this._settings.deep}_getEntryLevel(e,r){let o=r.split(\"/\").length;if(e===\"\")return o;let a=e.split(\"/\").length;return o-a}_isSkippedSymbolicLink(e){return!this._settings.followSymbolicLinks&&e.dirent.isSymbolicLink()}_isSkippedByPositivePatterns(e,r){return!this._settings.baseNameMatch&&!r.match(e)}_isSkippedByNegativePatterns(e,r){return!yb.pattern.matchAny(e,r)}};IM.default=wM});var Wie=_(vM=>{\"use strict\";Object.defineProperty(vM,\"__esModule\",{value:!0});var gg=Df(),BM=class{constructor(e,r){this._settings=e,this._micromatchOptions=r,this.index=new Map}getFilter(e,r){let o=gg.pattern.convertPatternsToRe(e,this._micromatchOptions),a=gg.pattern.convertPatternsToRe(r,Object.assign(Object.assign({},this._micromatchOptions),{dot:!0}));return n=>this._filter(n,o,a)}_filter(e,r,o){let a=gg.path.removeLeadingDotSegment(e.path);if(this._settings.unique&&this._isDuplicateEntry(a)||this._onlyFileFilter(e)||this._onlyDirectoryFilter(e)||this._isSkippedByAbsoluteNegativePatterns(a,o))return!1;let n=e.dirent.isDirectory(),u=this._isMatchToPatterns(a,r,n)&&!this._isMatchToPatterns(a,o,n);return this._settings.unique&&u&&this._createIndexRecord(a),u}_isDuplicateEntry(e){return this.index.has(e)}_createIndexRecord(e){this.index.set(e,void 0)}_onlyFileFilter(e){return this._settings.onlyFiles&&!e.dirent.isFile()}_onlyDirectoryFilter(e){return this._settings.onlyDirectories&&!e.dirent.isDirectory()}_isSkippedByAbsoluteNegativePatterns(e,r){if(!this._settings.absolute)return!1;let o=gg.path.makeAbsolute(this._settings.cwd,e);return gg.pattern.matchAny(o,r)}_isMatchToPatterns(e,r,o){let a=gg.pattern.matchAny(e,r);return!a&&o?gg.pattern.matchAny(e+\"/\",r):a}};vM.default=BM});var Kie=_(PM=>{\"use strict\";Object.defineProperty(PM,\"__esModule\",{value:!0});var ltt=Df(),DM=class{constructor(e){this._settings=e}getFilter(){return e=>this._isNonFatalError(e)}_isNonFatalError(e){return ltt.errno.isEnoentCodeError(e)||this._settings.suppressErrors}};PM.default=DM});var zie=_(SM=>{\"use strict\";Object.defineProperty(SM,\"__esModule\",{value:!0});var Vie=Df(),bM=class{constructor(e){this._settings=e}getTransformer(){return e=>this._transform(e)}_transform(e){let r=e.path;return this._settings.absolute&&(r=Vie.path.makeAbsolute(this._settings.cwd,r),r=Vie.path.unixify(r)),this._settings.markDirectories&&e.dirent.isDirectory()&&(r+=\"/\"),this._settings.objectMode?Object.assign(Object.assign({},e),{path:r}):r}};SM.default=bM});var Eb=_(kM=>{\"use strict\";Object.defineProperty(kM,\"__esModule\",{value:!0});var ctt=ve(\"path\"),utt=Yie(),Att=Wie(),ftt=Kie(),ptt=zie(),xM=class{constructor(e){this._settings=e,this.errorFilter=new ftt.default(this._settings),this.entryFilter=new Att.default(this._settings,this._getMicromatchOptions()),this.deepFilter=new utt.default(this._settings,this._getMicromatchOptions()),this.entryTransformer=new ptt.default(this._settings)}_getRootDirectory(e){return ctt.resolve(this._settings.cwd,e.base)}_getReaderOptions(e){let r=e.base===\".\"?\"\":e.base;return{basePath:r,pathSegmentSeparator:\"/\",concurrency:this._settings.concurrency,deepFilter:this.deepFilter.getFilter(r,e.positive,e.negative),entryFilter:this.entryFilter.getFilter(e.positive,e.negative),errorFilter:this.errorFilter.getFilter(),followSymbolicLinks:this._settings.followSymbolicLinks,fs:this._settings.fs,stats:this._settings.stats,throwErrorOnBrokenSymbolicLink:this._settings.throwErrorOnBrokenSymbolicLink,transform:this.entryTransformer.getTransformer()}}_getMicromatchOptions(){return{dot:this._settings.dot,matchBase:this._settings.baseNameMatch,nobrace:!this._settings.braceExpansion,nocase:!this._settings.caseSensitiveMatch,noext:!this._settings.extglob,noglobstar:!this._settings.globstar,posix:!0,strictSlashes:!1}}};kM.default=xM});var Jie=_(FM=>{\"use strict\";Object.defineProperty(FM,\"__esModule\",{value:!0});var htt=qie(),gtt=Eb(),QM=class extends gtt.default{constructor(){super(...arguments),this._reader=new htt.default(this._settings)}async read(e){let r=this._getRootDirectory(e),o=this._getReaderOptions(e);return(await this.api(r,e,o)).map(n=>o.transform(n))}api(e,r,o){return r.dynamic?this._reader.dynamic(e,o):this._reader.static(r.patterns,o)}};FM.default=QM});var Xie=_(TM=>{\"use strict\";Object.defineProperty(TM,\"__esModule\",{value:!0});var dtt=ve(\"stream\"),mtt=hM(),ytt=Eb(),RM=class extends ytt.default{constructor(){super(...arguments),this._reader=new mtt.default(this._settings)}read(e){let r=this._getRootDirectory(e),o=this._getReaderOptions(e),a=this.api(r,e,o),n=new dtt.Readable({objectMode:!0,read:()=>{}});return a.once(\"error\",u=>n.emit(\"error\",u)).on(\"data\",u=>n.emit(\"data\",o.transform(u))).once(\"end\",()=>n.emit(\"end\")),n.once(\"close\",()=>a.destroy()),n}api(e,r,o){return r.dynamic?this._reader.dynamic(e,o):this._reader.static(r.patterns,o)}};TM.default=RM});var Zie=_(LM=>{\"use strict\";Object.defineProperty(LM,\"__esModule\",{value:!0});var Ett=hg(),Ctt=db(),wtt=mb(),NM=class extends wtt.default{constructor(){super(...arguments),this._walkSync=Ctt.walkSync,this._statSync=Ett.statSync}dynamic(e,r){return this._walkSync(e,r)}static(e,r){let o=[];for(let a of e){let n=this._getFullEntryPath(a),u=this._getEntry(n,a,r);u===null||!r.entryFilter(u)||o.push(u)}return o}_getEntry(e,r,o){try{let a=this._getStat(e);return this._makeEntry(a,r)}catch(a){if(o.errorFilter(a))return null;throw a}}_getStat(e){return this._statSync(e,this._fsStatSettings)}};LM.default=NM});var $ie=_(OM=>{\"use strict\";Object.defineProperty(OM,\"__esModule\",{value:!0});var Itt=Zie(),Btt=Eb(),MM=class extends Btt.default{constructor(){super(...arguments),this._reader=new Itt.default(this._settings)}read(e){let r=this._getRootDirectory(e),o=this._getReaderOptions(e);return this.api(r,e,o).map(o.transform)}api(e,r,o){return r.dynamic?this._reader.dynamic(e,o):this._reader.static(r.patterns,o)}};OM.default=MM});var ese=_(Um=>{\"use strict\";Object.defineProperty(Um,\"__esModule\",{value:!0});Um.DEFAULT_FILE_SYSTEM_ADAPTER=void 0;var Om=ve(\"fs\"),vtt=ve(\"os\"),Dtt=Math.max(vtt.cpus().length,1);Um.DEFAULT_FILE_SYSTEM_ADAPTER={lstat:Om.lstat,lstatSync:Om.lstatSync,stat:Om.stat,statSync:Om.statSync,readdir:Om.readdir,readdirSync:Om.readdirSync};var UM=class{constructor(e={}){this._options=e,this.absolute=this._getValue(this._options.absolute,!1),this.baseNameMatch=this._getValue(this._options.baseNameMatch,!1),this.braceExpansion=this._getValue(this._options.braceExpansion,!0),this.caseSensitiveMatch=this._getValue(this._options.caseSensitiveMatch,!0),this.concurrency=this._getValue(this._options.concurrency,Dtt),this.cwd=this._getValue(this._options.cwd,process.cwd()),this.deep=this._getValue(this._options.deep,1/0),this.dot=this._getValue(this._options.dot,!1),this.extglob=this._getValue(this._options.extglob,!0),this.followSymbolicLinks=this._getValue(this._options.followSymbolicLinks,!0),this.fs=this._getFileSystemMethods(this._options.fs),this.globstar=this._getValue(this._options.globstar,!0),this.ignore=this._getValue(this._options.ignore,[]),this.markDirectories=this._getValue(this._options.markDirectories,!1),this.objectMode=this._getValue(this._options.objectMode,!1),this.onlyDirectories=this._getValue(this._options.onlyDirectories,!1),this.onlyFiles=this._getValue(this._options.onlyFiles,!0),this.stats=this._getValue(this._options.stats,!1),this.suppressErrors=this._getValue(this._options.suppressErrors,!1),this.throwErrorOnBrokenSymbolicLink=this._getValue(this._options.throwErrorOnBrokenSymbolicLink,!1),this.unique=this._getValue(this._options.unique,!0),this.onlyDirectories&&(this.onlyFiles=!1),this.stats&&(this.objectMode=!0),this.ignore=[].concat(this.ignore)}_getValue(e,r){return e===void 0?r:e}_getFileSystemMethods(e={}){return Object.assign(Object.assign({},Um.DEFAULT_FILE_SYSTEM_ADAPTER),e)}};Um.default=UM});var Cb=_((kNt,rse)=>{\"use strict\";var tse=rie(),Ptt=Jie(),btt=Xie(),Stt=$ie(),_M=ese(),Yl=Df();async function HM(t,e){jc(t);let r=qM(t,Ptt.default,e),o=await Promise.all(r);return Yl.array.flatten(o)}(function(t){t.glob=t,t.globSync=e,t.globStream=r,t.async=t;function e(h,E){jc(h);let I=qM(h,Stt.default,E);return Yl.array.flatten(I)}t.sync=e;function r(h,E){jc(h);let I=qM(h,btt.default,E);return Yl.stream.merge(I)}t.stream=r;function o(h,E){jc(h);let I=[].concat(h),v=new _M.default(E);return tse.generate(I,v)}t.generateTasks=o;function a(h,E){jc(h);let I=new _M.default(E);return Yl.pattern.isDynamicPattern(h,I)}t.isDynamicPattern=a;function n(h){return jc(h),Yl.path.escape(h)}t.escapePath=n;function u(h){return jc(h),Yl.path.convertPathToPattern(h)}t.convertPathToPattern=u;let A;(function(h){function E(v){return jc(v),Yl.path.escapePosixPath(v)}h.escapePath=E;function I(v){return jc(v),Yl.path.convertPosixPathToPattern(v)}h.convertPathToPattern=I})(A=t.posix||(t.posix={}));let p;(function(h){function E(v){return jc(v),Yl.path.escapeWindowsPath(v)}h.escapePath=E;function I(v){return jc(v),Yl.path.convertWindowsPathToPattern(v)}h.convertPathToPattern=I})(p=t.win32||(t.win32={}))})(HM||(HM={}));function qM(t,e,r){let o=[].concat(t),a=new _M.default(r),n=tse.generate(o,a),u=new e(a);return n.map(u.read,u)}function jc(t){if(![].concat(t).every(o=>Yl.string.isString(o)&&!Yl.string.isEmpty(o)))throw new TypeError(\"Patterns must be a string (non empty) or an array of strings\")}rse.exports=HM});var wn={};Vt(wn,{checksumFile:()=>Ib,checksumPattern:()=>Bb,makeHash:()=>zi});function zi(...t){let e=(0,wb.createHash)(\"sha512\"),r=\"\";for(let o of t)typeof o==\"string\"?r+=o:o&&(r&&(e.update(r),r=\"\"),e.update(o));return r&&e.update(r),e.digest(\"hex\")}async function Ib(t,{baseFs:e,algorithm:r}={baseFs:oe,algorithm:\"sha512\"}){let o=await e.openPromise(t,\"r\");try{let n=Buffer.allocUnsafeSlow(65536),u=(0,wb.createHash)(r),A=0;for(;(A=await e.readPromise(o,n,0,65536))!==0;)u.update(A===65536?n:n.slice(0,A));return u.digest(\"hex\")}finally{await e.closePromise(o)}}async function Bb(t,{cwd:e}){let o=(await(0,jM.default)(t,{cwd:ue.fromPortablePath(e),onlyDirectories:!0})).map(A=>`${A}/**/*`),a=await(0,jM.default)([t,...o],{cwd:ue.fromPortablePath(e),onlyFiles:!1});a.sort();let n=await Promise.all(a.map(async A=>{let p=[Buffer.from(A)],h=V.join(e,ue.toPortablePath(A)),E=await oe.lstatPromise(h);return E.isSymbolicLink()?p.push(Buffer.from(await oe.readlinkPromise(h))):E.isFile()&&p.push(await oe.readFilePromise(h)),p.join(\"\\0\")})),u=(0,wb.createHash)(\"sha512\");for(let A of n)u.update(A);return u.digest(\"hex\")}var wb,jM,th=Et(()=>{Pt();wb=ve(\"crypto\"),jM=Ze(Cb())});var G={};Vt(G,{allPeerRequests:()=>WI,areDescriptorsEqual:()=>ase,areIdentsEqual:()=>HI,areLocatorsEqual:()=>qI,areVirtualPackagesEquivalent:()=>Mtt,bindDescriptor:()=>Ntt,bindLocator:()=>Ltt,convertDescriptorToLocator:()=>vb,convertLocatorToDescriptor:()=>YM,convertPackageToLocator:()=>Ftt,convertToIdent:()=>Qtt,convertToManifestRange:()=>Ktt,copyPackage:()=>OI,devirtualizeDescriptor:()=>UI,devirtualizeLocator:()=>_I,ensureDevirtualizedDescriptor:()=>Rtt,ensureDevirtualizedLocator:()=>Ttt,getIdentVendorPath:()=>zM,isPackageCompatible:()=>xb,isVirtualDescriptor:()=>Pf,isVirtualLocator:()=>Gc,makeDescriptor:()=>In,makeIdent:()=>eA,makeLocator:()=>Rs,makeRange:()=>bb,parseDescriptor:()=>rh,parseFileStyleRange:()=>Ytt,parseIdent:()=>ea,parseLocator:()=>bf,parseRange:()=>dg,prettyDependent:()=>CL,prettyDescriptor:()=>jn,prettyIdent:()=>Oi,prettyLocator:()=>qr,prettyLocatorNoColors:()=>EL,prettyRange:()=>qm,prettyReference:()=>GI,prettyResolution:()=>NI,prettyWorkspace:()=>YI,renamePackage:()=>WM,slugifyIdent:()=>GM,slugifyLocator:()=>Hm,sortDescriptors:()=>jm,stringifyDescriptor:()=>xa,stringifyIdent:()=>rn,stringifyLocator:()=>ka,tryParseDescriptor:()=>jI,tryParseIdent:()=>lse,tryParseLocator:()=>Pb,tryParseRange:()=>Gtt,virtualizeDescriptor:()=>KM,virtualizePackage:()=>VM});function eA(t,e){if(t?.startsWith(\"@\"))throw new Error(\"Invalid scope: don't prefix it with '@'\");return{identHash:zi(t,e),scope:t,name:e}}function In(t,e){return{identHash:t.identHash,scope:t.scope,name:t.name,descriptorHash:zi(t.identHash,e),range:e}}function Rs(t,e){return{identHash:t.identHash,scope:t.scope,name:t.name,locatorHash:zi(t.identHash,e),reference:e}}function Qtt(t){return{identHash:t.identHash,scope:t.scope,name:t.name}}function vb(t){return{identHash:t.identHash,scope:t.scope,name:t.name,locatorHash:t.descriptorHash,reference:t.range}}function YM(t){return{identHash:t.identHash,scope:t.scope,name:t.name,descriptorHash:t.locatorHash,range:t.reference}}function Ftt(t){return{identHash:t.identHash,scope:t.scope,name:t.name,locatorHash:t.locatorHash,reference:t.reference}}function WM(t,e){return{identHash:e.identHash,scope:e.scope,name:e.name,locatorHash:e.locatorHash,reference:e.reference,version:t.version,languageName:t.languageName,linkType:t.linkType,conditions:t.conditions,dependencies:new Map(t.dependencies),peerDependencies:new Map(t.peerDependencies),dependenciesMeta:new Map(t.dependenciesMeta),peerDependenciesMeta:new Map(t.peerDependenciesMeta),bin:new Map(t.bin)}}function OI(t){return WM(t,t)}function KM(t,e){if(e.includes(\"#\"))throw new Error(\"Invalid entropy\");return In(t,`virtual:${e}#${t.range}`)}function VM(t,e){if(e.includes(\"#\"))throw new Error(\"Invalid entropy\");return WM(t,Rs(t,`virtual:${e}#${t.reference}`))}function Pf(t){return t.range.startsWith(MI)}function Gc(t){return t.reference.startsWith(MI)}function UI(t){if(!Pf(t))throw new Error(\"Not a virtual descriptor\");return In(t,t.range.replace(Db,\"\"))}function _I(t){if(!Gc(t))throw new Error(\"Not a virtual descriptor\");return Rs(t,t.reference.replace(Db,\"\"))}function Rtt(t){return Pf(t)?In(t,t.range.replace(Db,\"\")):t}function Ttt(t){return Gc(t)?Rs(t,t.reference.replace(Db,\"\")):t}function Ntt(t,e){return t.range.includes(\"::\")?t:In(t,`${t.range}::${_m.default.stringify(e)}`)}function Ltt(t,e){return t.reference.includes(\"::\")?t:Rs(t,`${t.reference}::${_m.default.stringify(e)}`)}function HI(t,e){return t.identHash===e.identHash}function ase(t,e){return t.descriptorHash===e.descriptorHash}function qI(t,e){return t.locatorHash===e.locatorHash}function Mtt(t,e){if(!Gc(t))throw new Error(\"Invalid package type\");if(!Gc(e))throw new Error(\"Invalid package type\");if(!HI(t,e)||t.dependencies.size!==e.dependencies.size)return!1;for(let r of t.dependencies.values()){let o=e.dependencies.get(r.identHash);if(!o||!ase(r,o))return!1}return!0}function ea(t){let e=lse(t);if(!e)throw new Error(`Invalid ident (${t})`);return e}function lse(t){let e=t.match(Ott);if(!e)return null;let[,r,o]=e;return eA(typeof r<\"u\"?r:null,o)}function rh(t,e=!1){let r=jI(t,e);if(!r)throw new Error(`Invalid descriptor (${t})`);return r}function jI(t,e=!1){let r=e?t.match(Utt):t.match(_tt);if(!r)return null;let[,o,a,n]=r;if(n===\"unknown\")throw new Error(`Invalid range (${t})`);let u=typeof o<\"u\"?o:null,A=typeof n<\"u\"?n:\"unknown\";return In(eA(u,a),A)}function bf(t,e=!1){let r=Pb(t,e);if(!r)throw new Error(`Invalid locator (${t})`);return r}function Pb(t,e=!1){let r=e?t.match(Htt):t.match(qtt);if(!r)return null;let[,o,a,n]=r;if(n===\"unknown\")throw new Error(`Invalid reference (${t})`);let u=typeof o<\"u\"?o:null,A=typeof n<\"u\"?n:\"unknown\";return Rs(eA(u,a),A)}function dg(t,e){let r=t.match(jtt);if(r===null)throw new Error(`Invalid range (${t})`);let o=typeof r[1]<\"u\"?r[1]:null;if(typeof e?.requireProtocol==\"string\"&&o!==e.requireProtocol)throw new Error(`Invalid protocol (${o})`);if(e?.requireProtocol&&o===null)throw new Error(`Missing protocol (${o})`);let a=typeof r[3]<\"u\"?decodeURIComponent(r[2]):null;if(e?.requireSource&&a===null)throw new Error(`Missing source (${t})`);let n=typeof r[3]<\"u\"?decodeURIComponent(r[3]):decodeURIComponent(r[2]),u=e?.parseSelector?_m.default.parse(n):n,A=typeof r[4]<\"u\"?_m.default.parse(r[4]):null;return{protocol:o,source:a,selector:u,params:A}}function Gtt(t,e){try{return dg(t,e)}catch{return null}}function Ytt(t,{protocol:e}){let{selector:r,params:o}=dg(t,{requireProtocol:e,requireBindings:!0});if(typeof o.locator!=\"string\")throw new Error(`Assertion failed: Invalid bindings for ${t}`);return{parentLocator:bf(o.locator,!0),path:r}}function nse(t){return t=t.replaceAll(\"%\",\"%25\"),t=t.replaceAll(\":\",\"%3A\"),t=t.replaceAll(\"#\",\"%23\"),t}function Wtt(t){return t===null?!1:Object.entries(t).length>0}function bb({protocol:t,source:e,selector:r,params:o}){let a=\"\";return t!==null&&(a+=`${t}`),e!==null&&(a+=`${nse(e)}#`),a+=nse(r),Wtt(o)&&(a+=`::${_m.default.stringify(o)}`),a}function Ktt(t){let{params:e,protocol:r,source:o,selector:a}=dg(t);for(let n in e)n.startsWith(\"__\")&&delete e[n];return bb({protocol:r,source:o,params:e,selector:a})}function rn(t){return t.scope?`@${t.scope}/${t.name}`:`${t.name}`}function xa(t){return t.scope?`@${t.scope}/${t.name}@${t.range}`:`${t.name}@${t.range}`}function ka(t){return t.scope?`@${t.scope}/${t.name}@${t.reference}`:`${t.name}@${t.reference}`}function GM(t){return t.scope!==null?`@${t.scope}-${t.name}`:t.name}function Hm(t){let{protocol:e,selector:r}=dg(t.reference),o=e!==null?e.replace(Vtt,\"\"):\"exotic\",a=ise.default.valid(r),n=a!==null?`${o}-${a}`:`${o}`,u=10;return t.scope?`${GM(t)}-${n}-${t.locatorHash.slice(0,u)}`:`${GM(t)}-${n}-${t.locatorHash.slice(0,u)}`}function Oi(t,e){return e.scope?`${Ot(t,`@${e.scope}/`,yt.SCOPE)}${Ot(t,e.name,yt.NAME)}`:`${Ot(t,e.name,yt.NAME)}`}function Sb(t){if(t.startsWith(MI)){let e=Sb(t.substring(t.indexOf(\"#\")+1)),r=t.substring(MI.length,MI.length+xtt);return`${e} [${r}]`}else return t.replace(ztt,\"?[...]\")}function qm(t,e){return`${Ot(t,Sb(e),yt.RANGE)}`}function jn(t,e){return`${Oi(t,e)}${Ot(t,\"@\",yt.RANGE)}${qm(t,e.range)}`}function GI(t,e){return`${Ot(t,Sb(e),yt.REFERENCE)}`}function qr(t,e){return`${Oi(t,e)}${Ot(t,\"@\",yt.REFERENCE)}${GI(t,e.reference)}`}function EL(t){return`${rn(t)}@${Sb(t.reference)}`}function jm(t){return Fs(t,[e=>rn(e),e=>e.range])}function YI(t,e){return Oi(t,e.anchoredLocator)}function NI(t,e,r){let o=Pf(e)?UI(e):e;return r===null?`${jn(t,o)} \\u2192 ${yL(t).Cross}`:o.identHash===r.identHash?`${jn(t,o)} \\u2192 ${GI(t,r.reference)}`:`${jn(t,o)} \\u2192 ${qr(t,r)}`}function CL(t,e,r){return r===null?`${qr(t,e)}`:`${qr(t,e)} (via ${qm(t,r.range)})`}function zM(t){return`node_modules/${rn(t)}`}function xb(t,e){return t.conditions?ktt(t.conditions,r=>{let[,o,a]=r.match(ose),n=e[o];return n?n.includes(a):!0}):!0}function WI(t){let e=new Set;if(\"children\"in t)e.add(t);else for(let r of t.requests.values())e.add(r);for(let r of e)for(let o of r.children.values())e.add(o);return e}var _m,ise,sse,MI,xtt,ose,ktt,Db,Ott,Utt,_tt,Htt,qtt,jtt,Vtt,ztt,So=Et(()=>{_m=Ze(ve(\"querystring\")),ise=Ze(Jn()),sse=Ze(eX());jl();th();ql();So();MI=\"virtual:\",xtt=5,ose=/(os|cpu|libc)=([a-z0-9_-]+)/,ktt=(0,sse.makeParser)(ose);Db=/^[^#]*#/;Ott=/^(?:@([^/]+?)\\/)?([^@/]+)$/;Utt=/^(?:@([^/]+?)\\/)?([^@/]+?)(?:@(.+))$/,_tt=/^(?:@([^/]+?)\\/)?([^@/]+?)(?:@(.+))?$/;Htt=/^(?:@([^/]+?)\\/)?([^@/]+?)(?:@(.+))$/,qtt=/^(?:@([^/]+?)\\/)?([^@/]+?)(?:@(.+))?$/;jtt=/^([^#:]*:)?((?:(?!::)[^#])*)(?:#((?:(?!::).)*))?(?:::(.*))?$/;Vtt=/:$/;ztt=/\\?.*/});var cse,use=Et(()=>{So();cse={hooks:{reduceDependency:(t,e,r,o,{resolver:a,resolveOptions:n})=>{for(let{pattern:u,reference:A}of e.topLevelWorkspace.manifest.resolutions){if(u.from&&(u.from.fullName!==rn(r)||e.configuration.normalizeLocator(Rs(ea(u.from.fullName),u.from.description??r.reference)).locatorHash!==r.locatorHash)||u.descriptor.fullName!==rn(t)||e.configuration.normalizeDependency(In(bf(u.descriptor.fullName),u.descriptor.description??t.range)).descriptorHash!==t.descriptorHash)continue;return a.bindDescriptor(e.configuration.normalizeDependency(In(t,A)),e.topLevelWorkspace.anchoredLocator,n)}return t},validateProject:async(t,e)=>{for(let r of t.workspaces){let o=YI(t.configuration,r);await t.configuration.triggerHook(a=>a.validateWorkspace,r,{reportWarning:(a,n)=>e.reportWarning(a,`${o}: ${n}`),reportError:(a,n)=>e.reportError(a,`${o}: ${n}`)})}},validateWorkspace:async(t,e)=>{let{manifest:r}=t;r.resolutions.length&&t.cwd!==t.project.cwd&&r.errors.push(new Error(\"Resolutions field will be ignored\"));for(let o of r.errors)e.reportWarning(57,o.message)}}}});var ei,mg=Et(()=>{ei=class t{static{this.protocol=\"workspace:\"}supportsDescriptor(e,r){return!!(e.range.startsWith(t.protocol)||r.project.tryWorkspaceByDescriptor(e)!==null)}supportsLocator(e,r){return!!e.reference.startsWith(t.protocol)}shouldPersistResolution(e,r){return!1}bindDescriptor(e,r,o){return e}getResolutionDependencies(e,r){return{}}async getCandidates(e,r,o){return[o.project.getWorkspaceByDescriptor(e).anchoredLocator]}async getSatisfying(e,r,o,a){let[n]=await this.getCandidates(e,r,a);return{locators:o.filter(u=>u.locatorHash===n.locatorHash),sorted:!1}}async resolve(e,r){let o=r.project.getWorkspaceByCwd(e.reference.slice(t.protocol.length));return{...e,version:o.manifest.version||\"0.0.0\",languageName:\"unknown\",linkType:\"SOFT\",conditions:null,dependencies:r.project.configuration.normalizeDependencyMap(new Map([...o.manifest.dependencies,...o.manifest.devDependencies])),peerDependencies:new Map([...o.manifest.peerDependencies]),dependenciesMeta:o.manifest.dependenciesMeta,peerDependenciesMeta:o.manifest.peerDependenciesMeta,bin:o.manifest.bin}}}});var Lr={};Vt(Lr,{SemVer:()=>gse.SemVer,clean:()=>Xtt,getComparator:()=>pse,mergeComparators:()=>JM,satisfiesWithPrereleases:()=>tA,simplifyRanges:()=>XM,stringifyComparator:()=>hse,validRange:()=>Qa});function tA(t,e,r=!1){if(!t)return!1;let o=`${e}${r}`,a=Ase.get(o);if(typeof a>\"u\")try{a=new nh.default.Range(e,{includePrerelease:!0,loose:r})}catch{return!1}finally{Ase.set(o,a||null)}else if(a===null)return!1;let n;try{n=new nh.default.SemVer(t,a)}catch{return!1}return a.test(n)?!0:(n.prerelease&&(n.prerelease=[]),a.set.some(u=>{for(let A of u)A.semver.prerelease&&(A.semver.prerelease=[]);return u.every(A=>A.test(n))}))}function Qa(t){if(t.indexOf(\":\")!==-1)return null;let e=fse.get(t);if(typeof e<\"u\")return e;try{e=new nh.default.Range(t)}catch{e=null}return fse.set(t,e),e}function Xtt(t){let e=Jtt.exec(t);return e?e[1]:null}function pse(t){if(t.semver===nh.default.Comparator.ANY)return{gt:null,lt:null};switch(t.operator){case\"\":return{gt:[\">=\",t.semver],lt:[\"<=\",t.semver]};case\">\":case\">=\":return{gt:[t.operator,t.semver],lt:null};case\"<\":case\"<=\":return{gt:null,lt:[t.operator,t.semver]};default:throw new Error(`Assertion failed: Unexpected comparator operator (${t.operator})`)}}function JM(t){if(t.length===0)return null;let e=null,r=null;for(let o of t){if(o.gt){let a=e!==null?nh.default.compare(o.gt[1],e[1]):null;(a===null||a>0||a===0&&o.gt[0]===\">\")&&(e=o.gt)}if(o.lt){let a=r!==null?nh.default.compare(o.lt[1],r[1]):null;(a===null||a<0||a===0&&o.lt[0]===\"<\")&&(r=o.lt)}}if(e&&r){let o=nh.default.compare(e[1],r[1]);if(o===0&&(e[0]===\">\"||r[0]===\"<\")||o>0)return null}return{gt:e,lt:r}}function hse(t){if(t.gt&&t.lt){if(t.gt[0]===\">=\"&&t.lt[0]===\"<=\"&&t.gt[1].version===t.lt[1].version)return t.gt[1].version;if(t.gt[0]===\">=\"&&t.lt[0]===\"<\"){if(t.lt[1].version===`${t.gt[1].major+1}.0.0-0`)return`^${t.gt[1].version}`;if(t.lt[1].version===`${t.gt[1].major}.${t.gt[1].minor+1}.0-0`)return`~${t.gt[1].version}`}}let e=[];return t.gt&&e.push(t.gt[0]+t.gt[1].version),t.lt&&e.push(t.lt[0]+t.lt[1].version),e.length?e.join(\" \"):\"*\"}function XM(t){let e=t.map(o=>Qa(o).set.map(a=>a.map(n=>pse(n)))),r=e.shift().map(o=>JM(o)).filter(o=>o!==null);for(let o of e){let a=[];for(let n of r)for(let u of o){let A=JM([n,...u]);A!==null&&a.push(A)}r=a}return r.length===0?null:r.map(o=>hse(o)).join(\" || \")}var nh,gse,Ase,fse,Jtt,Sf=Et(()=>{nh=Ze(Jn()),gse=Ze(Jn()),Ase=new Map;fse=new Map;Jtt=/^(?:[\\sv=]*?)((0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(?:-((?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\\.(?:0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\\+([0-9a-zA-Z-]+(?:\\.[0-9a-zA-Z-]+)*))?)(?:\\s*)$/});function dse(t){let e=t.match(/^[ \\t]+/m);return e?e[0]:\"  \"}function mse(t){return t.charCodeAt(0)===65279?t.slice(1):t}function ta(t){return t.replace(/\\\\/g,\"/\")}function kb(t,{yamlCompatibilityMode:e}){return e?AL(t):typeof t>\"u\"||typeof t==\"boolean\"?t:null}function yse(t,e){let r=e.search(/[^!]/);if(r===-1)return\"invalid\";let o=r%2===0?\"\":\"!\",a=e.slice(r);return`${o}${t}=${a}`}function ZM(t,e){return e.length===1?yse(t,e[0]):`(${e.map(r=>yse(t,r)).join(\" | \")})`}var Ese,Ut,Gm=Et(()=>{Pt();Nl();Ese=Ze(Jn());mg();ql();Sf();So();Ut=class t{constructor(){this.indent=\"  \";this.name=null;this.version=null;this.os=null;this.cpu=null;this.libc=null;this.type=null;this.packageManager=null;this.private=!1;this.license=null;this.main=null;this.module=null;this.browser=null;this.languageName=null;this.bin=new Map;this.scripts=new Map;this.dependencies=new Map;this.devDependencies=new Map;this.peerDependencies=new Map;this.workspaceDefinitions=[];this.dependenciesMeta=new Map;this.peerDependenciesMeta=new Map;this.resolutions=[];this.files=null;this.publishConfig=null;this.installConfig=null;this.preferUnplugged=null;this.raw={};this.errors=[]}static{this.fileName=\"package.json\"}static{this.allDependencies=[\"dependencies\",\"devDependencies\",\"peerDependencies\"]}static{this.hardDependencies=[\"dependencies\",\"devDependencies\"]}static async tryFind(e,{baseFs:r=new Tn}={}){let o=V.join(e,\"package.json\");try{return await t.fromFile(o,{baseFs:r})}catch(a){if(a.code===\"ENOENT\")return null;throw a}}static async find(e,{baseFs:r}={}){let o=await t.tryFind(e,{baseFs:r});if(o===null)throw new Error(\"Manifest not found\");return o}static async fromFile(e,{baseFs:r=new Tn}={}){let o=new t;return await o.loadFile(e,{baseFs:r}),o}static fromText(e){let r=new t;return r.loadFromText(e),r}loadFromText(e){let r;try{r=JSON.parse(mse(e)||\"{}\")}catch(o){throw o.message+=` (when parsing ${e})`,o}this.load(r),this.indent=dse(e)}async loadFile(e,{baseFs:r=new Tn}){let o=await r.readFilePromise(e,\"utf8\"),a;try{a=JSON.parse(mse(o)||\"{}\")}catch(n){throw n.message+=` (when parsing ${e})`,n}this.load(a),this.indent=dse(o)}load(e,{yamlCompatibilityMode:r=!1}={}){if(typeof e!=\"object\"||e===null)throw new Error(`Utterly invalid manifest data (${e})`);this.raw=e;let o=[];if(this.name=null,typeof e.name==\"string\")try{this.name=ea(e.name)}catch{o.push(new Error(\"Parsing failed for the 'name' field\"))}if(typeof e.version==\"string\"?this.version=e.version:this.version=null,Array.isArray(e.os)){let n=[];this.os=n;for(let u of e.os)typeof u!=\"string\"?o.push(new Error(\"Parsing failed for the 'os' field\")):n.push(u)}else this.os=null;if(Array.isArray(e.cpu)){let n=[];this.cpu=n;for(let u of e.cpu)typeof u!=\"string\"?o.push(new Error(\"Parsing failed for the 'cpu' field\")):n.push(u)}else this.cpu=null;if(Array.isArray(e.libc)){let n=[];this.libc=n;for(let u of e.libc)typeof u!=\"string\"?o.push(new Error(\"Parsing failed for the 'libc' field\")):n.push(u)}else this.libc=null;if(typeof e.type==\"string\"?this.type=e.type:this.type=null,typeof e.packageManager==\"string\"?this.packageManager=e.packageManager:this.packageManager=null,typeof e.private==\"boolean\"?this.private=e.private:this.private=!1,typeof e.license==\"string\"?this.license=e.license:this.license=null,typeof e.languageName==\"string\"?this.languageName=e.languageName:this.languageName=null,typeof e.main==\"string\"?this.main=ta(e.main):this.main=null,typeof e.module==\"string\"?this.module=ta(e.module):this.module=null,e.browser!=null)if(typeof e.browser==\"string\")this.browser=ta(e.browser);else{this.browser=new Map;for(let[n,u]of Object.entries(e.browser))this.browser.set(ta(n),typeof u==\"string\"?ta(u):u)}else this.browser=null;if(this.bin=new Map,typeof e.bin==\"string\")e.bin.trim()===\"\"?o.push(new Error(\"Invalid bin field\")):this.name!==null?this.bin.set(this.name.name,ta(e.bin)):o.push(new Error(\"String bin field, but no attached package name\"));else if(typeof e.bin==\"object\"&&e.bin!==null)for(let[n,u]of Object.entries(e.bin)){if(typeof u!=\"string\"||u.trim()===\"\"){o.push(new Error(`Invalid bin definition for '${n}'`));continue}let A=ea(n);this.bin.set(A.name,ta(u))}if(this.scripts=new Map,typeof e.scripts==\"object\"&&e.scripts!==null)for(let[n,u]of Object.entries(e.scripts)){if(typeof u!=\"string\"){o.push(new Error(`Invalid script definition for '${n}'`));continue}this.scripts.set(n,u)}if(this.dependencies=new Map,typeof e.dependencies==\"object\"&&e.dependencies!==null)for(let[n,u]of Object.entries(e.dependencies)){if(typeof u!=\"string\"){o.push(new Error(`Invalid dependency range for '${n}'`));continue}let A;try{A=ea(n)}catch{o.push(new Error(`Parsing failed for the dependency name '${n}'`));continue}let p=In(A,u);this.dependencies.set(p.identHash,p)}if(this.devDependencies=new Map,typeof e.devDependencies==\"object\"&&e.devDependencies!==null)for(let[n,u]of Object.entries(e.devDependencies)){if(typeof u!=\"string\"){o.push(new Error(`Invalid dependency range for '${n}'`));continue}let A;try{A=ea(n)}catch{o.push(new Error(`Parsing failed for the dependency name '${n}'`));continue}let p=In(A,u);this.devDependencies.set(p.identHash,p)}if(this.peerDependencies=new Map,typeof e.peerDependencies==\"object\"&&e.peerDependencies!==null)for(let[n,u]of Object.entries(e.peerDependencies)){let A;try{A=ea(n)}catch{o.push(new Error(`Parsing failed for the dependency name '${n}'`));continue}(typeof u!=\"string\"||!u.startsWith(ei.protocol)&&!Qa(u))&&(o.push(new Error(`Invalid dependency range for '${n}'`)),u=\"*\");let p=In(A,u);this.peerDependencies.set(p.identHash,p)}typeof e.workspaces==\"object\"&&e.workspaces!==null&&e.workspaces.nohoist&&o.push(new Error(\"'nohoist' is deprecated, please use 'installConfig.hoistingLimits' instead\"));let a=Array.isArray(e.workspaces)?e.workspaces:typeof e.workspaces==\"object\"&&e.workspaces!==null&&Array.isArray(e.workspaces.packages)?e.workspaces.packages:[];this.workspaceDefinitions=[];for(let n of a){if(typeof n!=\"string\"){o.push(new Error(`Invalid workspace definition for '${n}'`));continue}this.workspaceDefinitions.push({pattern:n})}if(this.dependenciesMeta=new Map,typeof e.dependenciesMeta==\"object\"&&e.dependenciesMeta!==null)for(let[n,u]of Object.entries(e.dependenciesMeta)){if(typeof u!=\"object\"||u===null){o.push(new Error(`Invalid meta field for '${n}`));continue}let A=rh(n),p=this.ensureDependencyMeta(A),h=kb(u.built,{yamlCompatibilityMode:r});if(h===null){o.push(new Error(`Invalid built meta field for '${n}'`));continue}let E=kb(u.optional,{yamlCompatibilityMode:r});if(E===null){o.push(new Error(`Invalid optional meta field for '${n}'`));continue}let I=kb(u.unplugged,{yamlCompatibilityMode:r});if(I===null){o.push(new Error(`Invalid unplugged meta field for '${n}'`));continue}Object.assign(p,{built:h,optional:E,unplugged:I})}if(this.peerDependenciesMeta=new Map,typeof e.peerDependenciesMeta==\"object\"&&e.peerDependenciesMeta!==null)for(let[n,u]of Object.entries(e.peerDependenciesMeta)){if(typeof u!=\"object\"||u===null){o.push(new Error(`Invalid meta field for '${n}'`));continue}let A=rh(n),p=this.ensurePeerDependencyMeta(A),h=kb(u.optional,{yamlCompatibilityMode:r});if(h===null){o.push(new Error(`Invalid optional meta field for '${n}'`));continue}Object.assign(p,{optional:h})}if(this.resolutions=[],typeof e.resolutions==\"object\"&&e.resolutions!==null)for(let[n,u]of Object.entries(e.resolutions)){if(typeof u!=\"string\"){o.push(new Error(`Invalid resolution entry for '${n}'`));continue}try{this.resolutions.push({pattern:BD(n),reference:u})}catch(A){o.push(A);continue}}if(Array.isArray(e.files)){this.files=new Set;for(let n of e.files){if(typeof n!=\"string\"){o.push(new Error(`Invalid files entry for '${n}'`));continue}this.files.add(n)}}else this.files=null;if(typeof e.publishConfig==\"object\"&&e.publishConfig!==null){if(this.publishConfig={},typeof e.publishConfig.access==\"string\"&&(this.publishConfig.access=e.publishConfig.access),typeof e.publishConfig.main==\"string\"&&(this.publishConfig.main=ta(e.publishConfig.main)),typeof e.publishConfig.module==\"string\"&&(this.publishConfig.module=ta(e.publishConfig.module)),e.publishConfig.browser!=null)if(typeof e.publishConfig.browser==\"string\")this.publishConfig.browser=ta(e.publishConfig.browser);else{this.publishConfig.browser=new Map;for(let[n,u]of Object.entries(e.publishConfig.browser))this.publishConfig.browser.set(ta(n),typeof u==\"string\"?ta(u):u)}if(typeof e.publishConfig.registry==\"string\"&&(this.publishConfig.registry=e.publishConfig.registry),typeof e.publishConfig.bin==\"string\")this.name!==null?this.publishConfig.bin=new Map([[this.name.name,ta(e.publishConfig.bin)]]):o.push(new Error(\"String bin field, but no attached package name\"));else if(typeof e.publishConfig.bin==\"object\"&&e.publishConfig.bin!==null){this.publishConfig.bin=new Map;for(let[n,u]of Object.entries(e.publishConfig.bin)){if(typeof u!=\"string\"){o.push(new Error(`Invalid bin definition for '${n}'`));continue}this.publishConfig.bin.set(n,ta(u))}}if(Array.isArray(e.publishConfig.executableFiles)){this.publishConfig.executableFiles=new Set;for(let n of e.publishConfig.executableFiles){if(typeof n!=\"string\"){o.push(new Error(\"Invalid executable file definition\"));continue}this.publishConfig.executableFiles.add(ta(n))}}}else this.publishConfig=null;if(typeof e.installConfig==\"object\"&&e.installConfig!==null){this.installConfig={};for(let n of Object.keys(e.installConfig))n===\"hoistingLimits\"?typeof e.installConfig.hoistingLimits==\"string\"?this.installConfig.hoistingLimits=e.installConfig.hoistingLimits:o.push(new Error(\"Invalid hoisting limits definition\")):n==\"selfReferences\"?typeof e.installConfig.selfReferences==\"boolean\"?this.installConfig.selfReferences=e.installConfig.selfReferences:o.push(new Error(\"Invalid selfReferences definition, must be a boolean value\")):o.push(new Error(`Unrecognized installConfig key: ${n}`))}else this.installConfig=null;if(typeof e.optionalDependencies==\"object\"&&e.optionalDependencies!==null)for(let[n,u]of Object.entries(e.optionalDependencies)){if(typeof u!=\"string\"){o.push(new Error(`Invalid dependency range for '${n}'`));continue}let A;try{A=ea(n)}catch{o.push(new Error(`Parsing failed for the dependency name '${n}'`));continue}let p=In(A,u);this.dependencies.set(p.identHash,p);let h=In(A,\"unknown\"),E=this.ensureDependencyMeta(h);Object.assign(E,{optional:!0})}typeof e.preferUnplugged==\"boolean\"?this.preferUnplugged=e.preferUnplugged:this.preferUnplugged=null,this.errors=o}getForScope(e){switch(e){case\"dependencies\":return this.dependencies;case\"devDependencies\":return this.devDependencies;case\"peerDependencies\":return this.peerDependencies;default:throw new Error(`Unsupported value (\"${e}\")`)}}hasConsumerDependency(e){return!!(this.dependencies.has(e.identHash)||this.peerDependencies.has(e.identHash))}hasHardDependency(e){return!!(this.dependencies.has(e.identHash)||this.devDependencies.has(e.identHash))}hasSoftDependency(e){return!!this.peerDependencies.has(e.identHash)}hasDependency(e){return!!(this.hasHardDependency(e)||this.hasSoftDependency(e))}getConditions(){let e=[];return this.os&&this.os.length>0&&e.push(ZM(\"os\",this.os)),this.cpu&&this.cpu.length>0&&e.push(ZM(\"cpu\",this.cpu)),this.libc&&this.libc.length>0&&e.push(ZM(\"libc\",this.libc)),e.length>0?e.join(\" & \"):null}ensureDependencyMeta(e){if(e.range!==\"unknown\"&&!Ese.default.valid(e.range))throw new Error(`Invalid meta field range for '${xa(e)}'`);let r=rn(e),o=e.range!==\"unknown\"?e.range:null,a=this.dependenciesMeta.get(r);a||this.dependenciesMeta.set(r,a=new Map);let n=a.get(o);return n||a.set(o,n={}),n}ensurePeerDependencyMeta(e){if(e.range!==\"unknown\")throw new Error(`Invalid meta field range for '${xa(e)}'`);let r=rn(e),o=this.peerDependenciesMeta.get(r);return o||this.peerDependenciesMeta.set(r,o={}),o}setRawField(e,r,{after:o=[]}={}){let a=new Set(o.filter(n=>Object.hasOwn(this.raw,n)));if(a.size===0||Object.hasOwn(this.raw,e))this.raw[e]=r;else{let n=this.raw,u=this.raw={},A=!1;for(let p of Object.keys(n))u[p]=n[p],A||(a.delete(p),a.size===0&&(u[e]=r,A=!0))}}exportTo(e,{compatibilityMode:r=!0}={}){if(Object.assign(e,this.raw),this.name!==null?e.name=rn(this.name):delete e.name,this.version!==null?e.version=this.version:delete e.version,this.os!==null?e.os=this.os:delete e.os,this.cpu!==null?e.cpu=this.cpu:delete e.cpu,this.type!==null?e.type=this.type:delete e.type,this.packageManager!==null?e.packageManager=this.packageManager:delete e.packageManager,this.private?e.private=!0:delete e.private,this.license!==null?e.license=this.license:delete e.license,this.languageName!==null?e.languageName=this.languageName:delete e.languageName,this.main!==null?e.main=this.main:delete e.main,this.module!==null?e.module=this.module:delete e.module,this.browser!==null){let n=this.browser;typeof n==\"string\"?e.browser=n:n instanceof Map&&(e.browser=Object.assign({},...Array.from(n.keys()).sort().map(u=>({[u]:n.get(u)}))))}else delete e.browser;this.bin.size===1&&this.name!==null&&this.bin.has(this.name.name)?e.bin=this.bin.get(this.name.name):this.bin.size>0?e.bin=Object.assign({},...Array.from(this.bin.keys()).sort().map(n=>({[n]:this.bin.get(n)}))):delete e.bin,this.workspaceDefinitions.length>0?this.raw.workspaces&&!Array.isArray(this.raw.workspaces)?e.workspaces={...this.raw.workspaces,packages:this.workspaceDefinitions.map(({pattern:n})=>n)}:e.workspaces=this.workspaceDefinitions.map(({pattern:n})=>n):this.raw.workspaces&&!Array.isArray(this.raw.workspaces)&&Object.keys(this.raw.workspaces).length>0?e.workspaces=this.raw.workspaces:delete e.workspaces;let o=[],a=[];for(let n of this.dependencies.values()){let u=this.dependenciesMeta.get(rn(n)),A=!1;if(r&&u){let p=u.get(null);p&&p.optional&&(A=!0)}A?a.push(n):o.push(n)}o.length>0?e.dependencies=Object.assign({},...jm(o).map(n=>({[rn(n)]:n.range}))):delete e.dependencies,a.length>0?e.optionalDependencies=Object.assign({},...jm(a).map(n=>({[rn(n)]:n.range}))):delete e.optionalDependencies,this.devDependencies.size>0?e.devDependencies=Object.assign({},...jm(this.devDependencies.values()).map(n=>({[rn(n)]:n.range}))):delete e.devDependencies,this.peerDependencies.size>0?e.peerDependencies=Object.assign({},...jm(this.peerDependencies.values()).map(n=>({[rn(n)]:n.range}))):delete e.peerDependencies,e.dependenciesMeta={};for(let[n,u]of Fs(this.dependenciesMeta.entries(),([A,p])=>A))for(let[A,p]of Fs(u.entries(),([h,E])=>h!==null?`0${h}`:\"1\")){let h=A!==null?xa(In(ea(n),A)):n,E={...p};r&&A===null&&delete E.optional,Object.keys(E).length!==0&&(e.dependenciesMeta[h]=E)}if(Object.keys(e.dependenciesMeta).length===0&&delete e.dependenciesMeta,this.peerDependenciesMeta.size>0?e.peerDependenciesMeta=Object.assign({},...Fs(this.peerDependenciesMeta.entries(),([n,u])=>n).map(([n,u])=>({[n]:u}))):delete e.peerDependenciesMeta,this.resolutions.length>0?e.resolutions=Object.assign({},...this.resolutions.map(({pattern:n,reference:u})=>({[vD(n)]:u}))):delete e.resolutions,this.files!==null?e.files=Array.from(this.files):delete e.files,this.preferUnplugged!==null?e.preferUnplugged=this.preferUnplugged:delete e.preferUnplugged,this.scripts!==null&&this.scripts.size>0){e.scripts??={};for(let n of Object.keys(e.scripts))this.scripts.has(n)||delete e.scripts[n];for(let[n,u]of this.scripts.entries())e.scripts[n]=u}else delete e.scripts;return e}}});var wse=_((YNt,Cse)=>{var Ztt=_l(),$tt=function(){return Ztt.Date.now()};Cse.exports=$tt});var Bse=_((WNt,Ise)=>{var ert=/\\s/;function trt(t){for(var e=t.length;e--&&ert.test(t.charAt(e)););return e}Ise.exports=trt});var Dse=_((KNt,vse)=>{var rrt=Bse(),nrt=/^\\s+/;function irt(t){return t&&t.slice(0,rrt(t)+1).replace(nrt,\"\")}vse.exports=irt});var Ym=_((VNt,Pse)=>{var srt=cg(),ort=Ju(),art=\"[object Symbol]\";function lrt(t){return typeof t==\"symbol\"||ort(t)&&srt(t)==art}Pse.exports=lrt});var kse=_((zNt,xse)=>{var crt=Dse(),bse=sl(),urt=Ym(),Sse=NaN,Art=/^[-+]0x[0-9a-f]+$/i,frt=/^0b[01]+$/i,prt=/^0o[0-7]+$/i,hrt=parseInt;function grt(t){if(typeof t==\"number\")return t;if(urt(t))return Sse;if(bse(t)){var e=typeof t.valueOf==\"function\"?t.valueOf():t;t=bse(e)?e+\"\":e}if(typeof t!=\"string\")return t===0?t:+t;t=crt(t);var r=frt.test(t);return r||prt.test(t)?hrt(t.slice(2),r?2:8):Art.test(t)?Sse:+t}xse.exports=grt});var Rse=_((JNt,Fse)=>{var drt=sl(),$M=wse(),Qse=kse(),mrt=\"Expected a function\",yrt=Math.max,Ert=Math.min;function Crt(t,e,r){var o,a,n,u,A,p,h=0,E=!1,I=!1,v=!0;if(typeof t!=\"function\")throw new TypeError(mrt);e=Qse(e)||0,drt(r)&&(E=!!r.leading,I=\"maxWait\"in r,n=I?yrt(Qse(r.maxWait)||0,e):n,v=\"trailing\"in r?!!r.trailing:v);function x(ce){var Ce=o,de=a;return o=a=void 0,h=ce,u=t.apply(de,Ce),u}function C(ce){return h=ce,A=setTimeout(U,e),E?x(ce):u}function R(ce){var Ce=ce-p,de=ce-h,Be=e-Ce;return I?Ert(Be,n-de):Be}function L(ce){var Ce=ce-p,de=ce-h;return p===void 0||Ce>=e||Ce<0||I&&de>=n}function U(){var ce=$M();if(L(ce))return z(ce);A=setTimeout(U,R(ce))}function z(ce){return A=void 0,v&&o?x(ce):(o=a=void 0,u)}function te(){A!==void 0&&clearTimeout(A),h=0,o=p=a=A=void 0}function ae(){return A===void 0?u:z($M())}function le(){var ce=$M(),Ce=L(ce);if(o=arguments,a=this,p=ce,Ce){if(A===void 0)return C(p);if(I)return clearTimeout(A),A=setTimeout(U,e),x(p)}return A===void 0&&(A=setTimeout(U,e)),u}return le.cancel=te,le.flush=ae,le}Fse.exports=Crt});var eO=_((XNt,Tse)=>{var wrt=Rse(),Irt=sl(),Brt=\"Expected a function\";function vrt(t,e,r){var o=!0,a=!0;if(typeof t!=\"function\")throw new TypeError(Brt);return Irt(r)&&(o=\"leading\"in r?!!r.leading:o,a=\"trailing\"in r?!!r.trailing:a),wrt(t,e,{leading:o,maxWait:e,trailing:a})}Tse.exports=vrt});function Prt(t){return typeof t.reportCode<\"u\"}var Nse,Lse,Mse,Drt,Jt,Zs,Wl=Et(()=>{Nse=Ze(eO()),Lse=ve(\"stream\"),Mse=ve(\"string_decoder\"),Drt=15,Jt=class extends Error{constructor(r,o,a){super(o);this.reportExtra=a;this.reportCode=r}};Zs=class{constructor(){this.cacheHits=new Set;this.cacheMisses=new Set;this.reportedInfos=new Set;this.reportedWarnings=new Set;this.reportedErrors=new Set}getRecommendedLength(){return 180}reportCacheHit(e){this.cacheHits.add(e.locatorHash)}reportCacheMiss(e,r){this.cacheMisses.add(e.locatorHash)}static progressViaCounter(e){let r=0,o,a=new Promise(p=>{o=p}),n=p=>{let h=o;a=new Promise(E=>{o=E}),r=p,h()},u=(p=0)=>{n(r+1)},A=async function*(){for(;r<e;)await a,yield{progress:r/e}}();return{[Symbol.asyncIterator](){return A},hasProgress:!0,hasTitle:!1,set:n,tick:u}}static progressViaTitle(){let e,r,o=new Promise(u=>{r=u}),a=(0,Nse.default)(u=>{let A=r;o=new Promise(p=>{r=p}),e=u,A()},1e3/Drt),n=async function*(){for(;;)await o,yield{title:e}}();return{[Symbol.asyncIterator](){return n},hasProgress:!1,hasTitle:!0,setTitle:a}}async startProgressPromise(e,r){let o=this.reportProgress(e);try{return await r(e)}finally{o.stop()}}startProgressSync(e,r){let o=this.reportProgress(e);try{return r(e)}finally{o.stop()}}reportInfoOnce(e,r,o){let a=o&&o.key?o.key:r;this.reportedInfos.has(a)||(this.reportedInfos.add(a),this.reportInfo(e,r),o?.reportExtra?.(this))}reportWarningOnce(e,r,o){let a=o&&o.key?o.key:r;this.reportedWarnings.has(a)||(this.reportedWarnings.add(a),this.reportWarning(e,r),o?.reportExtra?.(this))}reportErrorOnce(e,r,o){let a=o&&o.key?o.key:r;this.reportedErrors.has(a)||(this.reportedErrors.add(a),this.reportError(e,r),o?.reportExtra?.(this))}reportExceptionOnce(e){Prt(e)?this.reportErrorOnce(e.reportCode,e.message,{key:e,reportExtra:e.reportExtra}):this.reportErrorOnce(1,e.stack||e.message,{key:e})}createStreamReporter(e=null){let r=new Lse.PassThrough,o=new Mse.StringDecoder,a=\"\";return r.on(\"data\",n=>{let u=o.write(n),A;do if(A=u.indexOf(`\n`),A!==-1){let p=a+u.substring(0,A);u=u.substring(A+1),a=\"\",e!==null?this.reportInfo(null,`${e} ${p}`):this.reportInfo(null,p)}while(A!==-1);a+=u}),r.on(\"end\",()=>{let n=o.end();n!==\"\"&&(e!==null?this.reportInfo(null,`${e} ${n}`):this.reportInfo(null,n))}),r}}});var Wm,tO=Et(()=>{Wl();So();Wm=class{constructor(e){this.fetchers=e}supports(e,r){return!!this.tryFetcher(e,r)}getLocalPath(e,r){return this.getFetcher(e,r).getLocalPath(e,r)}async fetch(e,r){return await this.getFetcher(e,r).fetch(e,r)}tryFetcher(e,r){let o=this.fetchers.find(a=>a.supports(e,r));return o||null}getFetcher(e,r){let o=this.fetchers.find(a=>a.supports(e,r));if(!o)throw new Jt(11,`${qr(r.project.configuration,e)} isn't supported by any available fetcher`);return o}}});var yg,rO=Et(()=>{So();yg=class{constructor(e){this.resolvers=e.filter(r=>r)}supportsDescriptor(e,r){return!!this.tryResolverByDescriptor(e,r)}supportsLocator(e,r){return!!this.tryResolverByLocator(e,r)}shouldPersistResolution(e,r){return this.getResolverByLocator(e,r).shouldPersistResolution(e,r)}bindDescriptor(e,r,o){return this.getResolverByDescriptor(e,o).bindDescriptor(e,r,o)}getResolutionDependencies(e,r){return this.getResolverByDescriptor(e,r).getResolutionDependencies(e,r)}async getCandidates(e,r,o){return await this.getResolverByDescriptor(e,o).getCandidates(e,r,o)}async getSatisfying(e,r,o,a){return this.getResolverByDescriptor(e,a).getSatisfying(e,r,o,a)}async resolve(e,r){return await this.getResolverByLocator(e,r).resolve(e,r)}tryResolverByDescriptor(e,r){let o=this.resolvers.find(a=>a.supportsDescriptor(e,r));return o||null}getResolverByDescriptor(e,r){let o=this.resolvers.find(a=>a.supportsDescriptor(e,r));if(!o)throw new Error(`${jn(r.project.configuration,e)} isn't supported by any available resolver`);return o}tryResolverByLocator(e,r){let o=this.resolvers.find(a=>a.supportsLocator(e,r));return o||null}getResolverByLocator(e,r){let o=this.resolvers.find(a=>a.supportsLocator(e,r));if(!o)throw new Error(`${qr(r.project.configuration,e)} isn't supported by any available resolver`);return o}}});var Km,nO=Et(()=>{Pt();So();Km=class{supports(e){return!!e.reference.startsWith(\"virtual:\")}getLocalPath(e,r){let o=e.reference.indexOf(\"#\");if(o===-1)throw new Error(\"Invalid virtual package reference\");let a=e.reference.slice(o+1),n=Rs(e,a);return r.fetcher.getLocalPath(n,r)}async fetch(e,r){let o=e.reference.indexOf(\"#\");if(o===-1)throw new Error(\"Invalid virtual package reference\");let a=e.reference.slice(o+1),n=Rs(e,a),u=await r.fetcher.fetch(n,r);return await this.ensureVirtualLink(e,u,r)}getLocatorFilename(e){return Hm(e)}async ensureVirtualLink(e,r,o){let a=r.packageFs.getRealPath(),n=o.project.configuration.get(\"virtualFolder\"),u=this.getLocatorFilename(e),A=zs.makeVirtualPath(n,u,a),p=new Hu(A,{baseFs:r.packageFs,pathUtils:V});return{...r,packageFs:p}}}});var Qb,Ose=Et(()=>{Qb=class t{static{this.protocol=\"virtual:\"}static isVirtualDescriptor(e){return!!e.range.startsWith(t.protocol)}static isVirtualLocator(e){return!!e.reference.startsWith(t.protocol)}supportsDescriptor(e,r){return t.isVirtualDescriptor(e)}supportsLocator(e,r){return t.isVirtualLocator(e)}shouldPersistResolution(e,r){return!1}bindDescriptor(e,r,o){throw new Error('Assertion failed: calling \"bindDescriptor\" on a virtual descriptor is unsupported')}getResolutionDependencies(e,r){throw new Error('Assertion failed: calling \"getResolutionDependencies\" on a virtual descriptor is unsupported')}async getCandidates(e,r,o){throw new Error('Assertion failed: calling \"getCandidates\" on a virtual descriptor is unsupported')}async getSatisfying(e,r,o,a){throw new Error('Assertion failed: calling \"getSatisfying\" on a virtual descriptor is unsupported')}async resolve(e,r){throw new Error('Assertion failed: calling \"resolve\" on a virtual locator is unsupported')}}});var Vm,iO=Et(()=>{Pt();mg();Vm=class{supports(e){return!!e.reference.startsWith(ei.protocol)}getLocalPath(e,r){return this.getWorkspace(e,r).cwd}async fetch(e,r){let o=this.getWorkspace(e,r).cwd;return{packageFs:new gn(o),prefixPath:It.dot,localPath:o}}getWorkspace(e,r){return r.project.getWorkspaceByCwd(e.reference.slice(ei.protocol.length))}}});function KI(t){return typeof t==\"object\"&&t!==null&&!Array.isArray(t)}function Use(t){return typeof t>\"u\"?3:KI(t)?0:Array.isArray(t)?1:2}function aO(t,e){return Object.hasOwn(t,e)}function Srt(t){return KI(t)&&aO(t,\"onConflict\")&&typeof t.onConflict==\"string\"}function xrt(t){if(typeof t>\"u\")return{onConflict:\"default\",value:t};if(!Srt(t))return{onConflict:\"default\",value:t};if(aO(t,\"value\"))return t;let{onConflict:e,...r}=t;return{onConflict:e,value:r}}function _se(t,e){let r=KI(t)&&aO(t,e)?t[e]:void 0;return xrt(r)}function zm(t,e){return[t,e,Hse]}function lO(t){return Array.isArray(t)?t[2]===Hse:!1}function sO(t,e){if(KI(t)){let r={};for(let o of Object.keys(t))r[o]=sO(t[o],e);return zm(e,r)}return Array.isArray(t)?zm(e,t.map(r=>sO(r,e))):zm(e,t)}function oO(t,e,r,o,a){let n,u=[],A=a,p=0;for(let E=a-1;E>=o;--E){let[I,v]=t[E],{onConflict:x,value:C}=_se(v,r),R=Use(C);if(R!==3){if(n??=R,R!==n||x===\"hardReset\"){p=A;break}if(R===2)return zm(I,C);if(u.unshift([I,C]),x===\"reset\"){p=E;break}x===\"extend\"&&E===o&&(o=0),A=E}}if(typeof n>\"u\")return null;let h=u.map(([E])=>E).join(\", \");switch(n){case 1:return zm(h,new Array().concat(...u.map(([E,I])=>I.map(v=>sO(v,E)))));case 0:{let E=Object.assign({},...u.map(([,R])=>R)),I=Object.keys(E),v={},x=t.map(([R,L])=>[R,_se(L,r).value]),C=brt(x,([R,L])=>{let U=Use(L);return U!==0&&U!==3});if(C!==-1){let R=x.slice(C+1);for(let L of I)v[L]=oO(R,e,L,0,R.length)}else for(let R of I)v[R]=oO(x,e,R,p,x.length);return zm(h,v)}default:throw new Error(\"Assertion failed: Non-extendable value type\")}}function qse(t){return oO(t.map(([e,r])=>[e,{\".\":r}]),[],\".\",0,t.length)}function VI(t){return lO(t)?t[1]:t}function Fb(t){let e=lO(t)?t[1]:t;if(Array.isArray(e))return e.map(r=>Fb(r));if(KI(e)){let r={};for(let[o,a]of Object.entries(e))r[o]=Fb(a);return r}return e}function cO(t){return lO(t)?t[0]:null}var brt,Hse,jse=Et(()=>{brt=(t,e,r)=>{let o=[...t];return o.reverse(),o.findIndex(e,r)};Hse=Symbol()});var Rb={};Vt(Rb,{getDefaultGlobalFolder:()=>AO,getHomeFolder:()=>Jm,isFolderInside:()=>fO});function AO(){if(process.platform===\"win32\"){let t=ue.toPortablePath(process.env.LOCALAPPDATA||ue.join((0,uO.homedir)(),\"AppData\",\"Local\"));return V.resolve(t,\"Yarn/Berry\")}if(process.env.XDG_DATA_HOME){let t=ue.toPortablePath(process.env.XDG_DATA_HOME);return V.resolve(t,\"yarn/berry\")}return V.resolve(Jm(),\".yarn/berry\")}function Jm(){return ue.toPortablePath((0,uO.homedir)()||\"/usr/local/share\")}function fO(t,e){let r=V.relative(e,t);return r&&!r.startsWith(\"..\")&&!V.isAbsolute(r)}var uO,Tb=Et(()=>{Pt();uO=ve(\"os\")});var Kse=_(Xm=>{\"use strict\";var uLt=ve(\"net\"),Qrt=ve(\"tls\"),pO=ve(\"http\"),Gse=ve(\"https\"),Frt=ve(\"events\"),ALt=ve(\"assert\"),Rrt=ve(\"util\");Xm.httpOverHttp=Trt;Xm.httpsOverHttp=Nrt;Xm.httpOverHttps=Lrt;Xm.httpsOverHttps=Mrt;function Trt(t){var e=new xf(t);return e.request=pO.request,e}function Nrt(t){var e=new xf(t);return e.request=pO.request,e.createSocket=Yse,e.defaultPort=443,e}function Lrt(t){var e=new xf(t);return e.request=Gse.request,e}function Mrt(t){var e=new xf(t);return e.request=Gse.request,e.createSocket=Yse,e.defaultPort=443,e}function xf(t){var e=this;e.options=t||{},e.proxyOptions=e.options.proxy||{},e.maxSockets=e.options.maxSockets||pO.Agent.defaultMaxSockets,e.requests=[],e.sockets=[],e.on(\"free\",function(o,a,n,u){for(var A=Wse(a,n,u),p=0,h=e.requests.length;p<h;++p){var E=e.requests[p];if(E.host===A.host&&E.port===A.port){e.requests.splice(p,1),E.request.onSocket(o);return}}o.destroy(),e.removeSocket(o)})}Rrt.inherits(xf,Frt.EventEmitter);xf.prototype.addRequest=function(e,r,o,a){var n=this,u=hO({request:e},n.options,Wse(r,o,a));if(n.sockets.length>=this.maxSockets){n.requests.push(u);return}n.createSocket(u,function(A){A.on(\"free\",p),A.on(\"close\",h),A.on(\"agentRemove\",h),e.onSocket(A);function p(){n.emit(\"free\",A,u)}function h(E){n.removeSocket(A),A.removeListener(\"free\",p),A.removeListener(\"close\",h),A.removeListener(\"agentRemove\",h)}})};xf.prototype.createSocket=function(e,r){var o=this,a={};o.sockets.push(a);var n=hO({},o.proxyOptions,{method:\"CONNECT\",path:e.host+\":\"+e.port,agent:!1,headers:{host:e.host+\":\"+e.port}});e.localAddress&&(n.localAddress=e.localAddress),n.proxyAuth&&(n.headers=n.headers||{},n.headers[\"Proxy-Authorization\"]=\"Basic \"+new Buffer(n.proxyAuth).toString(\"base64\")),ih(\"making CONNECT request\");var u=o.request(n);u.useChunkedEncodingByDefault=!1,u.once(\"response\",A),u.once(\"upgrade\",p),u.once(\"connect\",h),u.once(\"error\",E),u.end();function A(I){I.upgrade=!0}function p(I,v,x){process.nextTick(function(){h(I,v,x)})}function h(I,v,x){if(u.removeAllListeners(),v.removeAllListeners(),I.statusCode!==200){ih(\"tunneling socket could not be established, statusCode=%d\",I.statusCode),v.destroy();var C=new Error(\"tunneling socket could not be established, statusCode=\"+I.statusCode);C.code=\"ECONNRESET\",e.request.emit(\"error\",C),o.removeSocket(a);return}if(x.length>0){ih(\"got illegal response body from proxy\"),v.destroy();var C=new Error(\"got illegal response body from proxy\");C.code=\"ECONNRESET\",e.request.emit(\"error\",C),o.removeSocket(a);return}return ih(\"tunneling connection has established\"),o.sockets[o.sockets.indexOf(a)]=v,r(v)}function E(I){u.removeAllListeners(),ih(`tunneling socket could not be established, cause=%s\n`,I.message,I.stack);var v=new Error(\"tunneling socket could not be established, cause=\"+I.message);v.code=\"ECONNRESET\",e.request.emit(\"error\",v),o.removeSocket(a)}};xf.prototype.removeSocket=function(e){var r=this.sockets.indexOf(e);if(r!==-1){this.sockets.splice(r,1);var o=this.requests.shift();o&&this.createSocket(o,function(a){o.request.onSocket(a)})}};function Yse(t,e){var r=this;xf.prototype.createSocket.call(r,t,function(o){var a=t.request.getHeader(\"host\"),n=hO({},r.options,{socket:o,servername:a?a.replace(/:.*$/,\"\"):t.host}),u=Qrt.connect(0,n);r.sockets[r.sockets.indexOf(o)]=u,e(u)})}function Wse(t,e,r){return typeof t==\"string\"?{host:t,port:e,localAddress:r}:t}function hO(t){for(var e=1,r=arguments.length;e<r;++e){var o=arguments[e];if(typeof o==\"object\")for(var a=Object.keys(o),n=0,u=a.length;n<u;++n){var A=a[n];o[A]!==void 0&&(t[A]=o[A])}}return t}var ih;process.env.NODE_DEBUG&&/\\btunnel\\b/.test(process.env.NODE_DEBUG)?ih=function(){var t=Array.prototype.slice.call(arguments);typeof t[0]==\"string\"?t[0]=\"TUNNEL: \"+t[0]:t.unshift(\"TUNNEL:\"),console.error.apply(console,t)}:ih=function(){};Xm.debug=ih});var zse=_((pLt,Vse)=>{Vse.exports=Kse()});var Qf=_((kf,Nb)=>{\"use strict\";Object.defineProperty(kf,\"__esModule\",{value:!0});var Jse=[\"Int8Array\",\"Uint8Array\",\"Uint8ClampedArray\",\"Int16Array\",\"Uint16Array\",\"Int32Array\",\"Uint32Array\",\"Float32Array\",\"Float64Array\",\"BigInt64Array\",\"BigUint64Array\"];function Ort(t){return Jse.includes(t)}var Urt=[\"Function\",\"Generator\",\"AsyncGenerator\",\"GeneratorFunction\",\"AsyncGeneratorFunction\",\"AsyncFunction\",\"Observable\",\"Array\",\"Buffer\",\"Blob\",\"Object\",\"RegExp\",\"Date\",\"Error\",\"Map\",\"Set\",\"WeakMap\",\"WeakSet\",\"ArrayBuffer\",\"SharedArrayBuffer\",\"DataView\",\"Promise\",\"URL\",\"FormData\",\"URLSearchParams\",\"HTMLElement\",...Jse];function _rt(t){return Urt.includes(t)}var Hrt=[\"null\",\"undefined\",\"string\",\"number\",\"bigint\",\"boolean\",\"symbol\"];function qrt(t){return Hrt.includes(t)}function Zm(t){return e=>typeof e===t}var{toString:Xse}=Object.prototype,zI=t=>{let e=Xse.call(t).slice(8,-1);if(/HTML\\w+Element/.test(e)&&Pe.domElement(t))return\"HTMLElement\";if(_rt(e))return e},Xn=t=>e=>zI(e)===t;function Pe(t){if(t===null)return\"null\";switch(typeof t){case\"undefined\":return\"undefined\";case\"string\":return\"string\";case\"number\":return\"number\";case\"boolean\":return\"boolean\";case\"function\":return\"Function\";case\"bigint\":return\"bigint\";case\"symbol\":return\"symbol\";default:}if(Pe.observable(t))return\"Observable\";if(Pe.array(t))return\"Array\";if(Pe.buffer(t))return\"Buffer\";let e=zI(t);if(e)return e;if(t instanceof String||t instanceof Boolean||t instanceof Number)throw new TypeError(\"Please don't use object wrappers for primitive types\");return\"Object\"}Pe.undefined=Zm(\"undefined\");Pe.string=Zm(\"string\");var jrt=Zm(\"number\");Pe.number=t=>jrt(t)&&!Pe.nan(t);Pe.bigint=Zm(\"bigint\");Pe.function_=Zm(\"function\");Pe.null_=t=>t===null;Pe.class_=t=>Pe.function_(t)&&t.toString().startsWith(\"class \");Pe.boolean=t=>t===!0||t===!1;Pe.symbol=Zm(\"symbol\");Pe.numericString=t=>Pe.string(t)&&!Pe.emptyStringOrWhitespace(t)&&!Number.isNaN(Number(t));Pe.array=(t,e)=>Array.isArray(t)?Pe.function_(e)?t.every(e):!0:!1;Pe.buffer=t=>{var e,r,o,a;return(a=(o=(r=(e=t)===null||e===void 0?void 0:e.constructor)===null||r===void 0?void 0:r.isBuffer)===null||o===void 0?void 0:o.call(r,t))!==null&&a!==void 0?a:!1};Pe.blob=t=>Xn(\"Blob\")(t);Pe.nullOrUndefined=t=>Pe.null_(t)||Pe.undefined(t);Pe.object=t=>!Pe.null_(t)&&(typeof t==\"object\"||Pe.function_(t));Pe.iterable=t=>{var e;return Pe.function_((e=t)===null||e===void 0?void 0:e[Symbol.iterator])};Pe.asyncIterable=t=>{var e;return Pe.function_((e=t)===null||e===void 0?void 0:e[Symbol.asyncIterator])};Pe.generator=t=>{var e,r;return Pe.iterable(t)&&Pe.function_((e=t)===null||e===void 0?void 0:e.next)&&Pe.function_((r=t)===null||r===void 0?void 0:r.throw)};Pe.asyncGenerator=t=>Pe.asyncIterable(t)&&Pe.function_(t.next)&&Pe.function_(t.throw);Pe.nativePromise=t=>Xn(\"Promise\")(t);var Grt=t=>{var e,r;return Pe.function_((e=t)===null||e===void 0?void 0:e.then)&&Pe.function_((r=t)===null||r===void 0?void 0:r.catch)};Pe.promise=t=>Pe.nativePromise(t)||Grt(t);Pe.generatorFunction=Xn(\"GeneratorFunction\");Pe.asyncGeneratorFunction=t=>zI(t)===\"AsyncGeneratorFunction\";Pe.asyncFunction=t=>zI(t)===\"AsyncFunction\";Pe.boundFunction=t=>Pe.function_(t)&&!t.hasOwnProperty(\"prototype\");Pe.regExp=Xn(\"RegExp\");Pe.date=Xn(\"Date\");Pe.error=Xn(\"Error\");Pe.map=t=>Xn(\"Map\")(t);Pe.set=t=>Xn(\"Set\")(t);Pe.weakMap=t=>Xn(\"WeakMap\")(t);Pe.weakSet=t=>Xn(\"WeakSet\")(t);Pe.int8Array=Xn(\"Int8Array\");Pe.uint8Array=Xn(\"Uint8Array\");Pe.uint8ClampedArray=Xn(\"Uint8ClampedArray\");Pe.int16Array=Xn(\"Int16Array\");Pe.uint16Array=Xn(\"Uint16Array\");Pe.int32Array=Xn(\"Int32Array\");Pe.uint32Array=Xn(\"Uint32Array\");Pe.float32Array=Xn(\"Float32Array\");Pe.float64Array=Xn(\"Float64Array\");Pe.bigInt64Array=Xn(\"BigInt64Array\");Pe.bigUint64Array=Xn(\"BigUint64Array\");Pe.arrayBuffer=Xn(\"ArrayBuffer\");Pe.sharedArrayBuffer=Xn(\"SharedArrayBuffer\");Pe.dataView=Xn(\"DataView\");Pe.enumCase=(t,e)=>Object.values(e).includes(t);Pe.directInstanceOf=(t,e)=>Object.getPrototypeOf(t)===e.prototype;Pe.urlInstance=t=>Xn(\"URL\")(t);Pe.urlString=t=>{if(!Pe.string(t))return!1;try{return new URL(t),!0}catch{return!1}};Pe.truthy=t=>!!t;Pe.falsy=t=>!t;Pe.nan=t=>Number.isNaN(t);Pe.primitive=t=>Pe.null_(t)||qrt(typeof t);Pe.integer=t=>Number.isInteger(t);Pe.safeInteger=t=>Number.isSafeInteger(t);Pe.plainObject=t=>{if(Xse.call(t)!==\"[object Object]\")return!1;let e=Object.getPrototypeOf(t);return e===null||e===Object.getPrototypeOf({})};Pe.typedArray=t=>Ort(zI(t));var Yrt=t=>Pe.safeInteger(t)&&t>=0;Pe.arrayLike=t=>!Pe.nullOrUndefined(t)&&!Pe.function_(t)&&Yrt(t.length);Pe.inRange=(t,e)=>{if(Pe.number(e))return t>=Math.min(0,e)&&t<=Math.max(e,0);if(Pe.array(e)&&e.length===2)return t>=Math.min(...e)&&t<=Math.max(...e);throw new TypeError(`Invalid range: ${JSON.stringify(e)}`)};var Wrt=1,Krt=[\"innerHTML\",\"ownerDocument\",\"style\",\"attributes\",\"nodeValue\"];Pe.domElement=t=>Pe.object(t)&&t.nodeType===Wrt&&Pe.string(t.nodeName)&&!Pe.plainObject(t)&&Krt.every(e=>e in t);Pe.observable=t=>{var e,r,o,a;return t?t===((r=(e=t)[Symbol.observable])===null||r===void 0?void 0:r.call(e))||t===((a=(o=t)[\"@@observable\"])===null||a===void 0?void 0:a.call(o)):!1};Pe.nodeStream=t=>Pe.object(t)&&Pe.function_(t.pipe)&&!Pe.observable(t);Pe.infinite=t=>t===1/0||t===-1/0;var Zse=t=>e=>Pe.integer(e)&&Math.abs(e%2)===t;Pe.evenInteger=Zse(0);Pe.oddInteger=Zse(1);Pe.emptyArray=t=>Pe.array(t)&&t.length===0;Pe.nonEmptyArray=t=>Pe.array(t)&&t.length>0;Pe.emptyString=t=>Pe.string(t)&&t.length===0;var Vrt=t=>Pe.string(t)&&!/\\S/.test(t);Pe.emptyStringOrWhitespace=t=>Pe.emptyString(t)||Vrt(t);Pe.nonEmptyString=t=>Pe.string(t)&&t.length>0;Pe.nonEmptyStringAndNotWhitespace=t=>Pe.string(t)&&!Pe.emptyStringOrWhitespace(t);Pe.emptyObject=t=>Pe.object(t)&&!Pe.map(t)&&!Pe.set(t)&&Object.keys(t).length===0;Pe.nonEmptyObject=t=>Pe.object(t)&&!Pe.map(t)&&!Pe.set(t)&&Object.keys(t).length>0;Pe.emptySet=t=>Pe.set(t)&&t.size===0;Pe.nonEmptySet=t=>Pe.set(t)&&t.size>0;Pe.emptyMap=t=>Pe.map(t)&&t.size===0;Pe.nonEmptyMap=t=>Pe.map(t)&&t.size>0;Pe.propertyKey=t=>Pe.any([Pe.string,Pe.number,Pe.symbol],t);Pe.formData=t=>Xn(\"FormData\")(t);Pe.urlSearchParams=t=>Xn(\"URLSearchParams\")(t);var $se=(t,e,r)=>{if(!Pe.function_(e))throw new TypeError(`Invalid predicate: ${JSON.stringify(e)}`);if(r.length===0)throw new TypeError(\"Invalid number of values\");return t.call(r,e)};Pe.any=(t,...e)=>(Pe.array(t)?t:[t]).some(o=>$se(Array.prototype.some,o,e));Pe.all=(t,...e)=>$se(Array.prototype.every,t,e);var Mt=(t,e,r,o={})=>{if(!t){let{multipleValues:a}=o,n=a?`received values of types ${[...new Set(r.map(u=>`\\`${Pe(u)}\\``))].join(\", \")}`:`received value of type \\`${Pe(r)}\\``;throw new TypeError(`Expected value which is \\`${e}\\`, ${n}.`)}};kf.assert={undefined:t=>Mt(Pe.undefined(t),\"undefined\",t),string:t=>Mt(Pe.string(t),\"string\",t),number:t=>Mt(Pe.number(t),\"number\",t),bigint:t=>Mt(Pe.bigint(t),\"bigint\",t),function_:t=>Mt(Pe.function_(t),\"Function\",t),null_:t=>Mt(Pe.null_(t),\"null\",t),class_:t=>Mt(Pe.class_(t),\"Class\",t),boolean:t=>Mt(Pe.boolean(t),\"boolean\",t),symbol:t=>Mt(Pe.symbol(t),\"symbol\",t),numericString:t=>Mt(Pe.numericString(t),\"string with a number\",t),array:(t,e)=>{Mt(Pe.array(t),\"Array\",t),e&&t.forEach(e)},buffer:t=>Mt(Pe.buffer(t),\"Buffer\",t),blob:t=>Mt(Pe.blob(t),\"Blob\",t),nullOrUndefined:t=>Mt(Pe.nullOrUndefined(t),\"null or undefined\",t),object:t=>Mt(Pe.object(t),\"Object\",t),iterable:t=>Mt(Pe.iterable(t),\"Iterable\",t),asyncIterable:t=>Mt(Pe.asyncIterable(t),\"AsyncIterable\",t),generator:t=>Mt(Pe.generator(t),\"Generator\",t),asyncGenerator:t=>Mt(Pe.asyncGenerator(t),\"AsyncGenerator\",t),nativePromise:t=>Mt(Pe.nativePromise(t),\"native Promise\",t),promise:t=>Mt(Pe.promise(t),\"Promise\",t),generatorFunction:t=>Mt(Pe.generatorFunction(t),\"GeneratorFunction\",t),asyncGeneratorFunction:t=>Mt(Pe.asyncGeneratorFunction(t),\"AsyncGeneratorFunction\",t),asyncFunction:t=>Mt(Pe.asyncFunction(t),\"AsyncFunction\",t),boundFunction:t=>Mt(Pe.boundFunction(t),\"Function\",t),regExp:t=>Mt(Pe.regExp(t),\"RegExp\",t),date:t=>Mt(Pe.date(t),\"Date\",t),error:t=>Mt(Pe.error(t),\"Error\",t),map:t=>Mt(Pe.map(t),\"Map\",t),set:t=>Mt(Pe.set(t),\"Set\",t),weakMap:t=>Mt(Pe.weakMap(t),\"WeakMap\",t),weakSet:t=>Mt(Pe.weakSet(t),\"WeakSet\",t),int8Array:t=>Mt(Pe.int8Array(t),\"Int8Array\",t),uint8Array:t=>Mt(Pe.uint8Array(t),\"Uint8Array\",t),uint8ClampedArray:t=>Mt(Pe.uint8ClampedArray(t),\"Uint8ClampedArray\",t),int16Array:t=>Mt(Pe.int16Array(t),\"Int16Array\",t),uint16Array:t=>Mt(Pe.uint16Array(t),\"Uint16Array\",t),int32Array:t=>Mt(Pe.int32Array(t),\"Int32Array\",t),uint32Array:t=>Mt(Pe.uint32Array(t),\"Uint32Array\",t),float32Array:t=>Mt(Pe.float32Array(t),\"Float32Array\",t),float64Array:t=>Mt(Pe.float64Array(t),\"Float64Array\",t),bigInt64Array:t=>Mt(Pe.bigInt64Array(t),\"BigInt64Array\",t),bigUint64Array:t=>Mt(Pe.bigUint64Array(t),\"BigUint64Array\",t),arrayBuffer:t=>Mt(Pe.arrayBuffer(t),\"ArrayBuffer\",t),sharedArrayBuffer:t=>Mt(Pe.sharedArrayBuffer(t),\"SharedArrayBuffer\",t),dataView:t=>Mt(Pe.dataView(t),\"DataView\",t),enumCase:(t,e)=>Mt(Pe.enumCase(t,e),\"EnumCase\",t),urlInstance:t=>Mt(Pe.urlInstance(t),\"URL\",t),urlString:t=>Mt(Pe.urlString(t),\"string with a URL\",t),truthy:t=>Mt(Pe.truthy(t),\"truthy\",t),falsy:t=>Mt(Pe.falsy(t),\"falsy\",t),nan:t=>Mt(Pe.nan(t),\"NaN\",t),primitive:t=>Mt(Pe.primitive(t),\"primitive\",t),integer:t=>Mt(Pe.integer(t),\"integer\",t),safeInteger:t=>Mt(Pe.safeInteger(t),\"integer\",t),plainObject:t=>Mt(Pe.plainObject(t),\"plain object\",t),typedArray:t=>Mt(Pe.typedArray(t),\"TypedArray\",t),arrayLike:t=>Mt(Pe.arrayLike(t),\"array-like\",t),domElement:t=>Mt(Pe.domElement(t),\"HTMLElement\",t),observable:t=>Mt(Pe.observable(t),\"Observable\",t),nodeStream:t=>Mt(Pe.nodeStream(t),\"Node.js Stream\",t),infinite:t=>Mt(Pe.infinite(t),\"infinite number\",t),emptyArray:t=>Mt(Pe.emptyArray(t),\"empty array\",t),nonEmptyArray:t=>Mt(Pe.nonEmptyArray(t),\"non-empty array\",t),emptyString:t=>Mt(Pe.emptyString(t),\"empty string\",t),emptyStringOrWhitespace:t=>Mt(Pe.emptyStringOrWhitespace(t),\"empty string or whitespace\",t),nonEmptyString:t=>Mt(Pe.nonEmptyString(t),\"non-empty string\",t),nonEmptyStringAndNotWhitespace:t=>Mt(Pe.nonEmptyStringAndNotWhitespace(t),\"non-empty string and not whitespace\",t),emptyObject:t=>Mt(Pe.emptyObject(t),\"empty object\",t),nonEmptyObject:t=>Mt(Pe.nonEmptyObject(t),\"non-empty object\",t),emptySet:t=>Mt(Pe.emptySet(t),\"empty set\",t),nonEmptySet:t=>Mt(Pe.nonEmptySet(t),\"non-empty set\",t),emptyMap:t=>Mt(Pe.emptyMap(t),\"empty map\",t),nonEmptyMap:t=>Mt(Pe.nonEmptyMap(t),\"non-empty map\",t),propertyKey:t=>Mt(Pe.propertyKey(t),\"PropertyKey\",t),formData:t=>Mt(Pe.formData(t),\"FormData\",t),urlSearchParams:t=>Mt(Pe.urlSearchParams(t),\"URLSearchParams\",t),evenInteger:t=>Mt(Pe.evenInteger(t),\"even integer\",t),oddInteger:t=>Mt(Pe.oddInteger(t),\"odd integer\",t),directInstanceOf:(t,e)=>Mt(Pe.directInstanceOf(t,e),\"T\",t),inRange:(t,e)=>Mt(Pe.inRange(t,e),\"in range\",t),any:(t,...e)=>Mt(Pe.any(t,...e),\"predicate returns truthy for any value\",e,{multipleValues:!0}),all:(t,...e)=>Mt(Pe.all(t,...e),\"predicate returns truthy for all values\",e,{multipleValues:!0})};Object.defineProperties(Pe,{class:{value:Pe.class_},function:{value:Pe.function_},null:{value:Pe.null_}});Object.defineProperties(kf.assert,{class:{value:kf.assert.class_},function:{value:kf.assert.function_},null:{value:kf.assert.null_}});kf.default=Pe;Nb.exports=Pe;Nb.exports.default=Pe;Nb.exports.assert=kf.assert});var eoe=_((hLt,gO)=>{\"use strict\";var Lb=class extends Error{constructor(e){super(e||\"Promise was canceled\"),this.name=\"CancelError\"}get isCanceled(){return!0}},Mb=class t{static fn(e){return(...r)=>new t((o,a,n)=>{r.push(n),e(...r).then(o,a)})}constructor(e){this._cancelHandlers=[],this._isPending=!0,this._isCanceled=!1,this._rejectOnCancel=!0,this._promise=new Promise((r,o)=>{this._reject=o;let a=A=>{this._isPending=!1,r(A)},n=A=>{this._isPending=!1,o(A)},u=A=>{if(!this._isPending)throw new Error(\"The `onCancel` handler was attached after the promise settled.\");this._cancelHandlers.push(A)};return Object.defineProperties(u,{shouldReject:{get:()=>this._rejectOnCancel,set:A=>{this._rejectOnCancel=A}}}),e(a,n,u)})}then(e,r){return this._promise.then(e,r)}catch(e){return this._promise.catch(e)}finally(e){return this._promise.finally(e)}cancel(e){if(!(!this._isPending||this._isCanceled)){if(this._cancelHandlers.length>0)try{for(let r of this._cancelHandlers)r()}catch(r){this._reject(r)}this._isCanceled=!0,this._rejectOnCancel&&this._reject(new Lb(e))}}get isCanceled(){return this._isCanceled}};Object.setPrototypeOf(Mb.prototype,Promise.prototype);gO.exports=Mb;gO.exports.CancelError=Lb});var toe=_((mO,yO)=>{\"use strict\";Object.defineProperty(mO,\"__esModule\",{value:!0});function zrt(t){return t.encrypted}var dO=(t,e)=>{let r;typeof e==\"function\"?r={connect:e}:r=e;let o=typeof r.connect==\"function\",a=typeof r.secureConnect==\"function\",n=typeof r.close==\"function\",u=()=>{o&&r.connect(),zrt(t)&&a&&(t.authorized?r.secureConnect():t.authorizationError||t.once(\"secureConnect\",r.secureConnect)),n&&t.once(\"close\",r.close)};t.writable&&!t.connecting?u():t.connecting?t.once(\"connect\",u):t.destroyed&&n&&r.close(t._hadError)};mO.default=dO;yO.exports=dO;yO.exports.default=dO});var roe=_((CO,wO)=>{\"use strict\";Object.defineProperty(CO,\"__esModule\",{value:!0});var Jrt=toe(),Xrt=Number(process.versions.node.split(\".\")[0]),EO=t=>{let e={start:Date.now(),socket:void 0,lookup:void 0,connect:void 0,secureConnect:void 0,upload:void 0,response:void 0,end:void 0,error:void 0,abort:void 0,phases:{wait:void 0,dns:void 0,tcp:void 0,tls:void 0,request:void 0,firstByte:void 0,download:void 0,total:void 0}};t.timings=e;let r=u=>{let A=u.emit.bind(u);u.emit=(p,...h)=>(p===\"error\"&&(e.error=Date.now(),e.phases.total=e.error-e.start,u.emit=A),A(p,...h))};r(t),t.prependOnceListener(\"abort\",()=>{e.abort=Date.now(),(!e.response||Xrt>=13)&&(e.phases.total=Date.now()-e.start)});let o=u=>{e.socket=Date.now(),e.phases.wait=e.socket-e.start;let A=()=>{e.lookup=Date.now(),e.phases.dns=e.lookup-e.socket};u.prependOnceListener(\"lookup\",A),Jrt.default(u,{connect:()=>{e.connect=Date.now(),e.lookup===void 0&&(u.removeListener(\"lookup\",A),e.lookup=e.connect,e.phases.dns=e.lookup-e.socket),e.phases.tcp=e.connect-e.lookup},secureConnect:()=>{e.secureConnect=Date.now(),e.phases.tls=e.secureConnect-e.connect}})};t.socket?o(t.socket):t.prependOnceListener(\"socket\",o);let a=()=>{var u;e.upload=Date.now(),e.phases.request=e.upload-(u=e.secureConnect,u??e.connect)};return(typeof t.writableFinished==\"boolean\"?t.writableFinished:t.finished&&t.outputSize===0&&(!t.socket||t.socket.writableLength===0))?a():t.prependOnceListener(\"finish\",a),t.prependOnceListener(\"response\",u=>{e.response=Date.now(),e.phases.firstByte=e.response-e.upload,u.timings=e,r(u),u.prependOnceListener(\"end\",()=>{e.end=Date.now(),e.phases.download=e.end-e.response,e.phases.total=e.end-e.start})}),e};CO.default=EO;wO.exports=EO;wO.exports.default=EO});var coe=_((gLt,vO)=>{\"use strict\";var{V4MAPPED:Zrt,ADDRCONFIG:$rt,ALL:loe,promises:{Resolver:noe},lookup:ent}=ve(\"dns\"),{promisify:IO}=ve(\"util\"),tnt=ve(\"os\"),$m=Symbol(\"cacheableLookupCreateConnection\"),BO=Symbol(\"cacheableLookupInstance\"),ioe=Symbol(\"expires\"),rnt=typeof loe==\"number\",soe=t=>{if(!(t&&typeof t.createConnection==\"function\"))throw new Error(\"Expected an Agent instance as the first argument\")},nnt=t=>{for(let e of t)e.family!==6&&(e.address=`::ffff:${e.address}`,e.family=6)},ooe=()=>{let t=!1,e=!1;for(let r of Object.values(tnt.networkInterfaces()))for(let o of r)if(!o.internal&&(o.family===\"IPv6\"?e=!0:t=!0,t&&e))return{has4:t,has6:e};return{has4:t,has6:e}},int=t=>Symbol.iterator in t,aoe={ttl:!0},snt={all:!0},Ob=class{constructor({cache:e=new Map,maxTtl:r=1/0,fallbackDuration:o=3600,errorTtl:a=.15,resolver:n=new noe,lookup:u=ent}={}){if(this.maxTtl=r,this.errorTtl=a,this._cache=e,this._resolver=n,this._dnsLookup=IO(u),this._resolver instanceof noe?(this._resolve4=this._resolver.resolve4.bind(this._resolver),this._resolve6=this._resolver.resolve6.bind(this._resolver)):(this._resolve4=IO(this._resolver.resolve4.bind(this._resolver)),this._resolve6=IO(this._resolver.resolve6.bind(this._resolver))),this._iface=ooe(),this._pending={},this._nextRemovalTime=!1,this._hostnamesToFallback=new Set,o<1)this._fallback=!1;else{this._fallback=!0;let A=setInterval(()=>{this._hostnamesToFallback.clear()},o*1e3);A.unref&&A.unref()}this.lookup=this.lookup.bind(this),this.lookupAsync=this.lookupAsync.bind(this)}set servers(e){this.clear(),this._resolver.setServers(e)}get servers(){return this._resolver.getServers()}lookup(e,r,o){if(typeof r==\"function\"?(o=r,r={}):typeof r==\"number\"&&(r={family:r}),!o)throw new Error(\"Callback must be a function.\");this.lookupAsync(e,r).then(a=>{r.all?o(null,a):o(null,a.address,a.family,a.expires,a.ttl)},o)}async lookupAsync(e,r={}){typeof r==\"number\"&&(r={family:r});let o=await this.query(e);if(r.family===6){let a=o.filter(n=>n.family===6);r.hints&Zrt&&(rnt&&r.hints&loe||a.length===0)?nnt(o):o=a}else r.family===4&&(o=o.filter(a=>a.family===4));if(r.hints&$rt){let{_iface:a}=this;o=o.filter(n=>n.family===6?a.has6:a.has4)}if(o.length===0){let a=new Error(`cacheableLookup ENOTFOUND ${e}`);throw a.code=\"ENOTFOUND\",a.hostname=e,a}return r.all?o:o[0]}async query(e){let r=await this._cache.get(e);if(!r){let o=this._pending[e];if(o)r=await o;else{let a=this.queryAndCache(e);this._pending[e]=a,r=await a}}return r=r.map(o=>({...o})),r}async _resolve(e){let r=async h=>{try{return await h}catch(E){if(E.code===\"ENODATA\"||E.code===\"ENOTFOUND\")return[];throw E}},[o,a]=await Promise.all([this._resolve4(e,aoe),this._resolve6(e,aoe)].map(h=>r(h))),n=0,u=0,A=0,p=Date.now();for(let h of o)h.family=4,h.expires=p+h.ttl*1e3,n=Math.max(n,h.ttl);for(let h of a)h.family=6,h.expires=p+h.ttl*1e3,u=Math.max(u,h.ttl);return o.length>0?a.length>0?A=Math.min(n,u):A=n:A=u,{entries:[...o,...a],cacheTtl:A}}async _lookup(e){try{return{entries:await this._dnsLookup(e,{all:!0}),cacheTtl:0}}catch{return{entries:[],cacheTtl:0}}}async _set(e,r,o){if(this.maxTtl>0&&o>0){o=Math.min(o,this.maxTtl)*1e3,r[ioe]=Date.now()+o;try{await this._cache.set(e,r,o)}catch(a){this.lookupAsync=async()=>{let n=new Error(\"Cache Error. Please recreate the CacheableLookup instance.\");throw n.cause=a,n}}int(this._cache)&&this._tick(o)}}async queryAndCache(e){if(this._hostnamesToFallback.has(e))return this._dnsLookup(e,snt);try{let r=await this._resolve(e);r.entries.length===0&&this._fallback&&(r=await this._lookup(e),r.entries.length!==0&&this._hostnamesToFallback.add(e));let o=r.entries.length===0?this.errorTtl:r.cacheTtl;return await this._set(e,r.entries,o),delete this._pending[e],r.entries}catch(r){throw delete this._pending[e],r}}_tick(e){let r=this._nextRemovalTime;(!r||e<r)&&(clearTimeout(this._removalTimeout),this._nextRemovalTime=e,this._removalTimeout=setTimeout(()=>{this._nextRemovalTime=!1;let o=1/0,a=Date.now();for(let[n,u]of this._cache){let A=u[ioe];a>=A?this._cache.delete(n):A<o&&(o=A)}o!==1/0&&this._tick(o-a)},e),this._removalTimeout.unref&&this._removalTimeout.unref())}install(e){if(soe(e),$m in e)throw new Error(\"CacheableLookup has been already installed\");e[$m]=e.createConnection,e[BO]=this,e.createConnection=(r,o)=>(\"lookup\"in r||(r.lookup=this.lookup),e[$m](r,o))}uninstall(e){if(soe(e),e[$m]){if(e[BO]!==this)throw new Error(\"The agent is not owned by this CacheableLookup instance\");e.createConnection=e[$m],delete e[$m],delete e[BO]}}updateInterfaceInfo(){let{_iface:e}=this;this._iface=ooe(),(e.has4&&!this._iface.has4||e.has6&&!this._iface.has6)&&this._cache.clear()}clear(e){if(e){this._cache.delete(e);return}this._cache.clear()}};vO.exports=Ob;vO.exports.default=Ob});var foe=_((dLt,DO)=>{\"use strict\";var ont=typeof URL>\"u\"?ve(\"url\").URL:URL,ant=\"text/plain\",lnt=\"us-ascii\",uoe=(t,e)=>e.some(r=>r instanceof RegExp?r.test(t):r===t),cnt=(t,{stripHash:e})=>{let r=t.match(/^data:([^,]*?),([^#]*?)(?:#(.*))?$/);if(!r)throw new Error(`Invalid URL: ${t}`);let o=r[1].split(\";\"),a=r[2],n=e?\"\":r[3],u=!1;o[o.length-1]===\"base64\"&&(o.pop(),u=!0);let A=(o.shift()||\"\").toLowerCase(),h=[...o.map(E=>{let[I,v=\"\"]=E.split(\"=\").map(x=>x.trim());return I===\"charset\"&&(v=v.toLowerCase(),v===lnt)?\"\":`${I}${v?`=${v}`:\"\"}`}).filter(Boolean)];return u&&h.push(\"base64\"),(h.length!==0||A&&A!==ant)&&h.unshift(A),`data:${h.join(\";\")},${u?a.trim():a}${n?`#${n}`:\"\"}`},Aoe=(t,e)=>{if(e={defaultProtocol:\"http:\",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripWWW:!0,removeQueryParameters:[/^utm_\\w+/i],removeTrailingSlash:!0,removeDirectoryIndex:!1,sortQueryParameters:!0,...e},Reflect.has(e,\"normalizeHttps\"))throw new Error(\"options.normalizeHttps is renamed to options.forceHttp\");if(Reflect.has(e,\"normalizeHttp\"))throw new Error(\"options.normalizeHttp is renamed to options.forceHttps\");if(Reflect.has(e,\"stripFragment\"))throw new Error(\"options.stripFragment is renamed to options.stripHash\");if(t=t.trim(),/^data:/i.test(t))return cnt(t,e);let r=t.startsWith(\"//\");!r&&/^\\.*\\//.test(t)||(t=t.replace(/^(?!(?:\\w+:)?\\/\\/)|^\\/\\//,e.defaultProtocol));let a=new ont(t);if(e.forceHttp&&e.forceHttps)throw new Error(\"The `forceHttp` and `forceHttps` options cannot be used together\");if(e.forceHttp&&a.protocol===\"https:\"&&(a.protocol=\"http:\"),e.forceHttps&&a.protocol===\"http:\"&&(a.protocol=\"https:\"),e.stripAuthentication&&(a.username=\"\",a.password=\"\"),e.stripHash&&(a.hash=\"\"),a.pathname&&(a.pathname=a.pathname.replace(/((?!:).|^)\\/{2,}/g,(n,u)=>/^(?!\\/)/g.test(u)?`${u}/`:\"/\")),a.pathname&&(a.pathname=decodeURI(a.pathname)),e.removeDirectoryIndex===!0&&(e.removeDirectoryIndex=[/^index\\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let n=a.pathname.split(\"/\"),u=n[n.length-1];uoe(u,e.removeDirectoryIndex)&&(n=n.slice(0,n.length-1),a.pathname=n.slice(1).join(\"/\")+\"/\")}if(a.hostname&&(a.hostname=a.hostname.replace(/\\.$/,\"\"),e.stripWWW&&/^www\\.([a-z\\-\\d]{2,63})\\.([a-z.]{2,5})$/.test(a.hostname)&&(a.hostname=a.hostname.replace(/^www\\./,\"\"))),Array.isArray(e.removeQueryParameters))for(let n of[...a.searchParams.keys()])uoe(n,e.removeQueryParameters)&&a.searchParams.delete(n);return e.sortQueryParameters&&a.searchParams.sort(),e.removeTrailingSlash&&(a.pathname=a.pathname.replace(/\\/$/,\"\")),t=a.toString(),(e.removeTrailingSlash||a.pathname===\"/\")&&a.hash===\"\"&&(t=t.replace(/\\/$/,\"\")),r&&!e.normalizeProtocol&&(t=t.replace(/^http:\\/\\//,\"//\")),e.stripProtocol&&(t=t.replace(/^(?:https?:)?\\/\\//,\"\")),t};DO.exports=Aoe;DO.exports.default=Aoe});var goe=_((mLt,hoe)=>{hoe.exports=poe;function poe(t,e){if(t&&e)return poe(t)(e);if(typeof t!=\"function\")throw new TypeError(\"need wrapper function\");return Object.keys(t).forEach(function(o){r[o]=t[o]}),r;function r(){for(var o=new Array(arguments.length),a=0;a<o.length;a++)o[a]=arguments[a];var n=t.apply(this,o),u=o[o.length-1];return typeof n==\"function\"&&n!==u&&Object.keys(u).forEach(function(A){n[A]=u[A]}),n}}});var bO=_((yLt,PO)=>{var doe=goe();PO.exports=doe(Ub);PO.exports.strict=doe(moe);Ub.proto=Ub(function(){Object.defineProperty(Function.prototype,\"once\",{value:function(){return Ub(this)},configurable:!0}),Object.defineProperty(Function.prototype,\"onceStrict\",{value:function(){return moe(this)},configurable:!0})});function Ub(t){var e=function(){return e.called?e.value:(e.called=!0,e.value=t.apply(this,arguments))};return e.called=!1,e}function moe(t){var e=function(){if(e.called)throw new Error(e.onceError);return e.called=!0,e.value=t.apply(this,arguments)},r=t.name||\"Function wrapped with `once`\";return e.onceError=r+\" shouldn't be called more than once\",e.called=!1,e}});var SO=_((ELt,Eoe)=>{var unt=bO(),Ant=function(){},fnt=function(t){return t.setHeader&&typeof t.abort==\"function\"},pnt=function(t){return t.stdio&&Array.isArray(t.stdio)&&t.stdio.length===3},yoe=function(t,e,r){if(typeof e==\"function\")return yoe(t,null,e);e||(e={}),r=unt(r||Ant);var o=t._writableState,a=t._readableState,n=e.readable||e.readable!==!1&&t.readable,u=e.writable||e.writable!==!1&&t.writable,A=function(){t.writable||p()},p=function(){u=!1,n||r.call(t)},h=function(){n=!1,u||r.call(t)},E=function(C){r.call(t,C?new Error(\"exited with error code: \"+C):null)},I=function(C){r.call(t,C)},v=function(){if(n&&!(a&&a.ended))return r.call(t,new Error(\"premature close\"));if(u&&!(o&&o.ended))return r.call(t,new Error(\"premature close\"))},x=function(){t.req.on(\"finish\",p)};return fnt(t)?(t.on(\"complete\",p),t.on(\"abort\",v),t.req?x():t.on(\"request\",x)):u&&!o&&(t.on(\"end\",A),t.on(\"close\",A)),pnt(t)&&t.on(\"exit\",E),t.on(\"end\",h),t.on(\"finish\",p),e.error!==!1&&t.on(\"error\",I),t.on(\"close\",v),function(){t.removeListener(\"complete\",p),t.removeListener(\"abort\",v),t.removeListener(\"request\",x),t.req&&t.req.removeListener(\"finish\",p),t.removeListener(\"end\",A),t.removeListener(\"close\",A),t.removeListener(\"finish\",p),t.removeListener(\"exit\",E),t.removeListener(\"end\",h),t.removeListener(\"error\",I),t.removeListener(\"close\",v)}};Eoe.exports=yoe});var Ioe=_((CLt,woe)=>{var hnt=bO(),gnt=SO(),xO=ve(\"fs\"),JI=function(){},dnt=/^v?\\.0/.test(process.version),_b=function(t){return typeof t==\"function\"},mnt=function(t){return!dnt||!xO?!1:(t instanceof(xO.ReadStream||JI)||t instanceof(xO.WriteStream||JI))&&_b(t.close)},ynt=function(t){return t.setHeader&&_b(t.abort)},Ent=function(t,e,r,o){o=hnt(o);var a=!1;t.on(\"close\",function(){a=!0}),gnt(t,{readable:e,writable:r},function(u){if(u)return o(u);a=!0,o()});var n=!1;return function(u){if(!a&&!n){if(n=!0,mnt(t))return t.close(JI);if(ynt(t))return t.abort();if(_b(t.destroy))return t.destroy();o(u||new Error(\"stream was destroyed\"))}}},Coe=function(t){t()},Cnt=function(t,e){return t.pipe(e)},wnt=function(){var t=Array.prototype.slice.call(arguments),e=_b(t[t.length-1]||JI)&&t.pop()||JI;if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new Error(\"pump requires two streams per minimum\");var r,o=t.map(function(a,n){var u=n<t.length-1,A=n>0;return Ent(a,u,A,function(p){r||(r=p),p&&o.forEach(Coe),!u&&(o.forEach(Coe),e(r))})});return t.reduce(Cnt)};woe.exports=wnt});var voe=_((wLt,Boe)=>{\"use strict\";var{PassThrough:Int}=ve(\"stream\");Boe.exports=t=>{t={...t};let{array:e}=t,{encoding:r}=t,o=r===\"buffer\",a=!1;e?a=!(r||o):r=r||\"utf8\",o&&(r=null);let n=new Int({objectMode:a});r&&n.setEncoding(r);let u=0,A=[];return n.on(\"data\",p=>{A.push(p),a?u=A.length:u+=p.length}),n.getBufferedValue=()=>e?A:o?Buffer.concat(A,u):A.join(\"\"),n.getBufferedLength=()=>u,n}});var Doe=_((ILt,ey)=>{\"use strict\";var Bnt=Ioe(),vnt=voe(),Hb=class extends Error{constructor(){super(\"maxBuffer exceeded\"),this.name=\"MaxBufferError\"}};async function qb(t,e){if(!t)return Promise.reject(new Error(\"Expected a stream\"));e={maxBuffer:1/0,...e};let{maxBuffer:r}=e,o;return await new Promise((a,n)=>{let u=A=>{A&&(A.bufferedData=o.getBufferedValue()),n(A)};o=Bnt(t,vnt(e),A=>{if(A){u(A);return}a()}),o.on(\"data\",()=>{o.getBufferedLength()>r&&u(new Hb)})}),o.getBufferedValue()}ey.exports=qb;ey.exports.default=qb;ey.exports.buffer=(t,e)=>qb(t,{...e,encoding:\"buffer\"});ey.exports.array=(t,e)=>qb(t,{...e,array:!0});ey.exports.MaxBufferError=Hb});var boe=_((vLt,Poe)=>{\"use strict\";var Dnt=new Set([200,203,204,206,300,301,308,404,405,410,414,501]),Pnt=new Set([200,203,204,300,301,302,303,307,308,404,405,410,414,501]),bnt=new Set([500,502,503,504]),Snt={date:!0,connection:!0,\"keep-alive\":!0,\"proxy-authenticate\":!0,\"proxy-authorization\":!0,te:!0,trailer:!0,\"transfer-encoding\":!0,upgrade:!0},xnt={\"content-length\":!0,\"content-encoding\":!0,\"transfer-encoding\":!0,\"content-range\":!0};function Eg(t){let e=parseInt(t,10);return isFinite(e)?e:0}function knt(t){return t?bnt.has(t.status):!0}function kO(t){let e={};if(!t)return e;let r=t.trim().split(/,/);for(let o of r){let[a,n]=o.split(/=/,2);e[a.trim()]=n===void 0?!0:n.trim().replace(/^\"|\"$/g,\"\")}return e}function Qnt(t){let e=[];for(let r in t){let o=t[r];e.push(o===!0?r:r+\"=\"+o)}if(e.length)return e.join(\", \")}Poe.exports=class{constructor(e,r,{shared:o,cacheHeuristic:a,immutableMinTimeToLive:n,ignoreCargoCult:u,_fromObject:A}={}){if(A){this._fromObject(A);return}if(!r||!r.headers)throw Error(\"Response headers missing\");this._assertRequestHasHeaders(e),this._responseTime=this.now(),this._isShared=o!==!1,this._cacheHeuristic=a!==void 0?a:.1,this._immutableMinTtl=n!==void 0?n:24*3600*1e3,this._status=\"status\"in r?r.status:200,this._resHeaders=r.headers,this._rescc=kO(r.headers[\"cache-control\"]),this._method=\"method\"in e?e.method:\"GET\",this._url=e.url,this._host=e.headers.host,this._noAuthorization=!e.headers.authorization,this._reqHeaders=r.headers.vary?e.headers:null,this._reqcc=kO(e.headers[\"cache-control\"]),u&&\"pre-check\"in this._rescc&&\"post-check\"in this._rescc&&(delete this._rescc[\"pre-check\"],delete this._rescc[\"post-check\"],delete this._rescc[\"no-cache\"],delete this._rescc[\"no-store\"],delete this._rescc[\"must-revalidate\"],this._resHeaders=Object.assign({},this._resHeaders,{\"cache-control\":Qnt(this._rescc)}),delete this._resHeaders.expires,delete this._resHeaders.pragma),r.headers[\"cache-control\"]==null&&/no-cache/.test(r.headers.pragma)&&(this._rescc[\"no-cache\"]=!0)}now(){return Date.now()}storable(){return!!(!this._reqcc[\"no-store\"]&&(this._method===\"GET\"||this._method===\"HEAD\"||this._method===\"POST\"&&this._hasExplicitExpiration())&&Pnt.has(this._status)&&!this._rescc[\"no-store\"]&&(!this._isShared||!this._rescc.private)&&(!this._isShared||this._noAuthorization||this._allowsStoringAuthenticated())&&(this._resHeaders.expires||this._rescc[\"max-age\"]||this._isShared&&this._rescc[\"s-maxage\"]||this._rescc.public||Dnt.has(this._status)))}_hasExplicitExpiration(){return this._isShared&&this._rescc[\"s-maxage\"]||this._rescc[\"max-age\"]||this._resHeaders.expires}_assertRequestHasHeaders(e){if(!e||!e.headers)throw Error(\"Request headers missing\")}satisfiesWithoutRevalidation(e){this._assertRequestHasHeaders(e);let r=kO(e.headers[\"cache-control\"]);return r[\"no-cache\"]||/no-cache/.test(e.headers.pragma)||r[\"max-age\"]&&this.age()>r[\"max-age\"]||r[\"min-fresh\"]&&this.timeToLive()<1e3*r[\"min-fresh\"]||this.stale()&&!(r[\"max-stale\"]&&!this._rescc[\"must-revalidate\"]&&(r[\"max-stale\"]===!0||r[\"max-stale\"]>this.age()-this.maxAge()))?!1:this._requestMatches(e,!1)}_requestMatches(e,r){return(!this._url||this._url===e.url)&&this._host===e.headers.host&&(!e.method||this._method===e.method||r&&e.method===\"HEAD\")&&this._varyMatches(e)}_allowsStoringAuthenticated(){return this._rescc[\"must-revalidate\"]||this._rescc.public||this._rescc[\"s-maxage\"]}_varyMatches(e){if(!this._resHeaders.vary)return!0;if(this._resHeaders.vary===\"*\")return!1;let r=this._resHeaders.vary.trim().toLowerCase().split(/\\s*,\\s*/);for(let o of r)if(e.headers[o]!==this._reqHeaders[o])return!1;return!0}_copyWithoutHopByHopHeaders(e){let r={};for(let o in e)Snt[o]||(r[o]=e[o]);if(e.connection){let o=e.connection.trim().split(/\\s*,\\s*/);for(let a of o)delete r[a]}if(r.warning){let o=r.warning.split(/,/).filter(a=>!/^\\s*1[0-9][0-9]/.test(a));o.length?r.warning=o.join(\",\").trim():delete r.warning}return r}responseHeaders(){let e=this._copyWithoutHopByHopHeaders(this._resHeaders),r=this.age();return r>3600*24&&!this._hasExplicitExpiration()&&this.maxAge()>3600*24&&(e.warning=(e.warning?`${e.warning}, `:\"\")+'113 - \"rfc7234 5.5.4\"'),e.age=`${Math.round(r)}`,e.date=new Date(this.now()).toUTCString(),e}date(){let e=Date.parse(this._resHeaders.date);return isFinite(e)?e:this._responseTime}age(){let e=this._ageValue(),r=(this.now()-this._responseTime)/1e3;return e+r}_ageValue(){return Eg(this._resHeaders.age)}maxAge(){if(!this.storable()||this._rescc[\"no-cache\"]||this._isShared&&this._resHeaders[\"set-cookie\"]&&!this._rescc.public&&!this._rescc.immutable||this._resHeaders.vary===\"*\")return 0;if(this._isShared){if(this._rescc[\"proxy-revalidate\"])return 0;if(this._rescc[\"s-maxage\"])return Eg(this._rescc[\"s-maxage\"])}if(this._rescc[\"max-age\"])return Eg(this._rescc[\"max-age\"]);let e=this._rescc.immutable?this._immutableMinTtl:0,r=this.date();if(this._resHeaders.expires){let o=Date.parse(this._resHeaders.expires);return Number.isNaN(o)||o<r?0:Math.max(e,(o-r)/1e3)}if(this._resHeaders[\"last-modified\"]){let o=Date.parse(this._resHeaders[\"last-modified\"]);if(isFinite(o)&&r>o)return Math.max(e,(r-o)/1e3*this._cacheHeuristic)}return e}timeToLive(){let e=this.maxAge()-this.age(),r=e+Eg(this._rescc[\"stale-if-error\"]),o=e+Eg(this._rescc[\"stale-while-revalidate\"]);return Math.max(0,e,r,o)*1e3}stale(){return this.maxAge()<=this.age()}_useStaleIfError(){return this.maxAge()+Eg(this._rescc[\"stale-if-error\"])>this.age()}useStaleWhileRevalidate(){return this.maxAge()+Eg(this._rescc[\"stale-while-revalidate\"])>this.age()}static fromObject(e){return new this(void 0,void 0,{_fromObject:e})}_fromObject(e){if(this._responseTime)throw Error(\"Reinitialized\");if(!e||e.v!==1)throw Error(\"Invalid serialization\");this._responseTime=e.t,this._isShared=e.sh,this._cacheHeuristic=e.ch,this._immutableMinTtl=e.imm!==void 0?e.imm:24*3600*1e3,this._status=e.st,this._resHeaders=e.resh,this._rescc=e.rescc,this._method=e.m,this._url=e.u,this._host=e.h,this._noAuthorization=e.a,this._reqHeaders=e.reqh,this._reqcc=e.reqcc}toObject(){return{v:1,t:this._responseTime,sh:this._isShared,ch:this._cacheHeuristic,imm:this._immutableMinTtl,st:this._status,resh:this._resHeaders,rescc:this._rescc,m:this._method,u:this._url,h:this._host,a:this._noAuthorization,reqh:this._reqHeaders,reqcc:this._reqcc}}revalidationHeaders(e){this._assertRequestHasHeaders(e);let r=this._copyWithoutHopByHopHeaders(e.headers);if(delete r[\"if-range\"],!this._requestMatches(e,!0)||!this.storable())return delete r[\"if-none-match\"],delete r[\"if-modified-since\"],r;if(this._resHeaders.etag&&(r[\"if-none-match\"]=r[\"if-none-match\"]?`${r[\"if-none-match\"]}, ${this._resHeaders.etag}`:this._resHeaders.etag),r[\"accept-ranges\"]||r[\"if-match\"]||r[\"if-unmodified-since\"]||this._method&&this._method!=\"GET\"){if(delete r[\"if-modified-since\"],r[\"if-none-match\"]){let a=r[\"if-none-match\"].split(/,/).filter(n=>!/^\\s*W\\//.test(n));a.length?r[\"if-none-match\"]=a.join(\",\").trim():delete r[\"if-none-match\"]}}else this._resHeaders[\"last-modified\"]&&!r[\"if-modified-since\"]&&(r[\"if-modified-since\"]=this._resHeaders[\"last-modified\"]);return r}revalidatedPolicy(e,r){if(this._assertRequestHasHeaders(e),this._useStaleIfError()&&knt(r))return{modified:!1,matches:!1,policy:this};if(!r||!r.headers)throw Error(\"Response headers missing\");let o=!1;if(r.status!==void 0&&r.status!=304?o=!1:r.headers.etag&&!/^\\s*W\\//.test(r.headers.etag)?o=this._resHeaders.etag&&this._resHeaders.etag.replace(/^\\s*W\\//,\"\")===r.headers.etag:this._resHeaders.etag&&r.headers.etag?o=this._resHeaders.etag.replace(/^\\s*W\\//,\"\")===r.headers.etag.replace(/^\\s*W\\//,\"\"):this._resHeaders[\"last-modified\"]?o=this._resHeaders[\"last-modified\"]===r.headers[\"last-modified\"]:!this._resHeaders.etag&&!this._resHeaders[\"last-modified\"]&&!r.headers.etag&&!r.headers[\"last-modified\"]&&(o=!0),!o)return{policy:new this.constructor(e,r),modified:r.status!=304,matches:!1};let a={};for(let u in this._resHeaders)a[u]=u in r.headers&&!xnt[u]?r.headers[u]:this._resHeaders[u];let n=Object.assign({},r,{status:this._status,method:this._method,headers:a});return{policy:new this.constructor(e,n,{shared:this._isShared,cacheHeuristic:this._cacheHeuristic,immutableMinTimeToLive:this._immutableMinTtl}),modified:!1,matches:!0}}}});var jb=_((DLt,Soe)=>{\"use strict\";Soe.exports=t=>{let e={};for(let[r,o]of Object.entries(t))e[r.toLowerCase()]=o;return e}});var koe=_((PLt,xoe)=>{\"use strict\";var Fnt=ve(\"stream\").Readable,Rnt=jb(),QO=class extends Fnt{constructor(e,r,o,a){if(typeof e!=\"number\")throw new TypeError(\"Argument `statusCode` should be a number\");if(typeof r!=\"object\")throw new TypeError(\"Argument `headers` should be an object\");if(!(o instanceof Buffer))throw new TypeError(\"Argument `body` should be a buffer\");if(typeof a!=\"string\")throw new TypeError(\"Argument `url` should be a string\");super(),this.statusCode=e,this.headers=Rnt(r),this.body=o,this.url=a}_read(){this.push(this.body),this.push(null)}};xoe.exports=QO});var Foe=_((bLt,Qoe)=>{\"use strict\";var Tnt=[\"destroy\",\"setTimeout\",\"socket\",\"headers\",\"trailers\",\"rawHeaders\",\"statusCode\",\"httpVersion\",\"httpVersionMinor\",\"httpVersionMajor\",\"rawTrailers\",\"statusMessage\"];Qoe.exports=(t,e)=>{let r=new Set(Object.keys(t).concat(Tnt));for(let o of r)o in e||(e[o]=typeof t[o]==\"function\"?t[o].bind(t):t[o])}});var Toe=_((SLt,Roe)=>{\"use strict\";var Nnt=ve(\"stream\").PassThrough,Lnt=Foe(),Mnt=t=>{if(!(t&&t.pipe))throw new TypeError(\"Parameter `response` must be a response stream.\");let e=new Nnt;return Lnt(t,e),t.pipe(e)};Roe.exports=Mnt});var Noe=_(FO=>{FO.stringify=function t(e){if(typeof e>\"u\")return e;if(e&&Buffer.isBuffer(e))return JSON.stringify(\":base64:\"+e.toString(\"base64\"));if(e&&e.toJSON&&(e=e.toJSON()),e&&typeof e==\"object\"){var r=\"\",o=Array.isArray(e);r=o?\"[\":\"{\";var a=!0;for(var n in e){var u=typeof e[n]==\"function\"||!o&&typeof e[n]>\"u\";Object.hasOwnProperty.call(e,n)&&!u&&(a||(r+=\",\"),a=!1,o?e[n]==null?r+=\"null\":r+=t(e[n]):e[n]!==void 0&&(r+=t(n)+\":\"+t(e[n])))}return r+=o?\"]\":\"}\",r}else return typeof e==\"string\"?JSON.stringify(/^:/.test(e)?\":\"+e:e):typeof e>\"u\"?\"null\":JSON.stringify(e)};FO.parse=function(t){return JSON.parse(t,function(e,r){return typeof r==\"string\"?/^:base64:/.test(r)?Buffer.from(r.substring(8),\"base64\"):/^:/.test(r)?r.substring(1):r:r})}});var Uoe=_((kLt,Ooe)=>{\"use strict\";var Ont=ve(\"events\"),Loe=Noe(),Unt=t=>{let e={redis:\"@keyv/redis\",rediss:\"@keyv/redis\",mongodb:\"@keyv/mongo\",mongo:\"@keyv/mongo\",sqlite:\"@keyv/sqlite\",postgresql:\"@keyv/postgres\",postgres:\"@keyv/postgres\",mysql:\"@keyv/mysql\",etcd:\"@keyv/etcd\",offline:\"@keyv/offline\",tiered:\"@keyv/tiered\"};if(t.adapter||t.uri){let r=t.adapter||/^[^:+]*/.exec(t.uri)[0];return new(ve(e[r]))(t)}return new Map},Moe=[\"sqlite\",\"postgres\",\"mysql\",\"mongo\",\"redis\",\"tiered\"],RO=class extends Ont{constructor(e,{emitErrors:r=!0,...o}={}){if(super(),this.opts={namespace:\"keyv\",serialize:Loe.stringify,deserialize:Loe.parse,...typeof e==\"string\"?{uri:e}:e,...o},!this.opts.store){let n={...this.opts};this.opts.store=Unt(n)}if(this.opts.compression){let n=this.opts.compression;this.opts.serialize=n.serialize.bind(n),this.opts.deserialize=n.deserialize.bind(n)}typeof this.opts.store.on==\"function\"&&r&&this.opts.store.on(\"error\",n=>this.emit(\"error\",n)),this.opts.store.namespace=this.opts.namespace;let a=n=>async function*(){for await(let[u,A]of typeof n==\"function\"?n(this.opts.store.namespace):n){let p=await this.opts.deserialize(A);if(!(this.opts.store.namespace&&!u.includes(this.opts.store.namespace))){if(typeof p.expires==\"number\"&&Date.now()>p.expires){this.delete(u);continue}yield[this._getKeyUnprefix(u),p.value]}}};typeof this.opts.store[Symbol.iterator]==\"function\"&&this.opts.store instanceof Map?this.iterator=a(this.opts.store):typeof this.opts.store.iterator==\"function\"&&this.opts.store.opts&&this._checkIterableAdaptar()&&(this.iterator=a(this.opts.store.iterator.bind(this.opts.store)))}_checkIterableAdaptar(){return Moe.includes(this.opts.store.opts.dialect)||Moe.findIndex(e=>this.opts.store.opts.url.includes(e))>=0}_getKeyPrefix(e){return`${this.opts.namespace}:${e}`}_getKeyPrefixArray(e){return e.map(r=>`${this.opts.namespace}:${r}`)}_getKeyUnprefix(e){return e.split(\":\").splice(1).join(\":\")}get(e,r){let{store:o}=this.opts,a=Array.isArray(e),n=a?this._getKeyPrefixArray(e):this._getKeyPrefix(e);if(a&&o.getMany===void 0){let u=[];for(let A of n)u.push(Promise.resolve().then(()=>o.get(A)).then(p=>typeof p==\"string\"?this.opts.deserialize(p):this.opts.compression?this.opts.deserialize(p):p).then(p=>{if(p!=null)return typeof p.expires==\"number\"&&Date.now()>p.expires?this.delete(A).then(()=>{}):r&&r.raw?p:p.value}));return Promise.allSettled(u).then(A=>{let p=[];for(let h of A)p.push(h.value);return p})}return Promise.resolve().then(()=>a?o.getMany(n):o.get(n)).then(u=>typeof u==\"string\"?this.opts.deserialize(u):this.opts.compression?this.opts.deserialize(u):u).then(u=>{if(u!=null)return a?u.map((A,p)=>{if(typeof A==\"string\"&&(A=this.opts.deserialize(A)),A!=null){if(typeof A.expires==\"number\"&&Date.now()>A.expires){this.delete(e[p]).then(()=>{});return}return r&&r.raw?A:A.value}}):typeof u.expires==\"number\"&&Date.now()>u.expires?this.delete(e).then(()=>{}):r&&r.raw?u:u.value})}set(e,r,o){let a=this._getKeyPrefix(e);typeof o>\"u\"&&(o=this.opts.ttl),o===0&&(o=void 0);let{store:n}=this.opts;return Promise.resolve().then(()=>{let u=typeof o==\"number\"?Date.now()+o:null;return typeof r==\"symbol\"&&this.emit(\"error\",\"symbol cannot be serialized\"),r={value:r,expires:u},this.opts.serialize(r)}).then(u=>n.set(a,u,o)).then(()=>!0)}delete(e){let{store:r}=this.opts;if(Array.isArray(e)){let a=this._getKeyPrefixArray(e);if(r.deleteMany===void 0){let n=[];for(let u of a)n.push(r.delete(u));return Promise.allSettled(n).then(u=>u.every(A=>A.value===!0))}return Promise.resolve().then(()=>r.deleteMany(a))}let o=this._getKeyPrefix(e);return Promise.resolve().then(()=>r.delete(o))}clear(){let{store:e}=this.opts;return Promise.resolve().then(()=>e.clear())}has(e){let r=this._getKeyPrefix(e),{store:o}=this.opts;return Promise.resolve().then(async()=>typeof o.has==\"function\"?o.has(r):await o.get(r)!==void 0)}disconnect(){let{store:e}=this.opts;if(typeof e.disconnect==\"function\")return e.disconnect()}};Ooe.exports=RO});var qoe=_((FLt,Hoe)=>{\"use strict\";var _nt=ve(\"events\"),Gb=ve(\"url\"),Hnt=foe(),qnt=Doe(),TO=boe(),_oe=koe(),jnt=jb(),Gnt=Toe(),Ynt=Uoe(),XI=class t{constructor(e,r){if(typeof e!=\"function\")throw new TypeError(\"Parameter `request` must be a function\");return this.cache=new Ynt({uri:typeof r==\"string\"&&r,store:typeof r!=\"string\"&&r,namespace:\"cacheable-request\"}),this.createCacheableRequest(e)}createCacheableRequest(e){return(r,o)=>{let a;if(typeof r==\"string\")a=NO(Gb.parse(r)),r={};else if(r instanceof Gb.URL)a=NO(Gb.parse(r.toString())),r={};else{let[I,...v]=(r.path||\"\").split(\"?\"),x=v.length>0?`?${v.join(\"?\")}`:\"\";a=NO({...r,pathname:I,search:x})}r={headers:{},method:\"GET\",cache:!0,strictTtl:!1,automaticFailover:!1,...r,...Wnt(a)},r.headers=jnt(r.headers);let n=new _nt,u=Hnt(Gb.format(a),{stripWWW:!1,removeTrailingSlash:!1,stripAuthentication:!1}),A=`${r.method}:${u}`,p=!1,h=!1,E=I=>{h=!0;let v=!1,x,C=new Promise(L=>{x=()=>{v||(v=!0,L())}}),R=L=>{if(p&&!I.forceRefresh){L.status=L.statusCode;let z=TO.fromObject(p.cachePolicy).revalidatedPolicy(I,L);if(!z.modified){let te=z.policy.responseHeaders();L=new _oe(p.statusCode,te,p.body,p.url),L.cachePolicy=z.policy,L.fromCache=!0}}L.fromCache||(L.cachePolicy=new TO(I,L,I),L.fromCache=!1);let U;I.cache&&L.cachePolicy.storable()?(U=Gnt(L),(async()=>{try{let z=qnt.buffer(L);if(await Promise.race([C,new Promise(ce=>L.once(\"end\",ce))]),v)return;let te=await z,ae={cachePolicy:L.cachePolicy.toObject(),url:L.url,statusCode:L.fromCache?p.statusCode:L.statusCode,body:te},le=I.strictTtl?L.cachePolicy.timeToLive():void 0;I.maxTtl&&(le=le?Math.min(le,I.maxTtl):I.maxTtl),await this.cache.set(A,ae,le)}catch(z){n.emit(\"error\",new t.CacheError(z))}})()):I.cache&&p&&(async()=>{try{await this.cache.delete(A)}catch(z){n.emit(\"error\",new t.CacheError(z))}})(),n.emit(\"response\",U||L),typeof o==\"function\"&&o(U||L)};try{let L=e(I,R);L.once(\"error\",x),L.once(\"abort\",x),n.emit(\"request\",L)}catch(L){n.emit(\"error\",new t.RequestError(L))}};return(async()=>{let I=async x=>{await Promise.resolve();let C=x.cache?await this.cache.get(A):void 0;if(typeof C>\"u\")return E(x);let R=TO.fromObject(C.cachePolicy);if(R.satisfiesWithoutRevalidation(x)&&!x.forceRefresh){let L=R.responseHeaders(),U=new _oe(C.statusCode,L,C.body,C.url);U.cachePolicy=R,U.fromCache=!0,n.emit(\"response\",U),typeof o==\"function\"&&o(U)}else p=C,x.headers=R.revalidationHeaders(x),E(x)},v=x=>n.emit(\"error\",new t.CacheError(x));this.cache.once(\"error\",v),n.on(\"response\",()=>this.cache.removeListener(\"error\",v));try{await I(r)}catch(x){r.automaticFailover&&!h&&E(r),n.emit(\"error\",new t.CacheError(x))}})(),n}}};function Wnt(t){let e={...t};return e.path=`${t.pathname||\"/\"}${t.search||\"\"}`,delete e.pathname,delete e.search,e}function NO(t){return{protocol:t.protocol,auth:t.auth,hostname:t.hostname||t.host||\"localhost\",port:t.port,pathname:t.pathname,search:t.search}}XI.RequestError=class extends Error{constructor(t){super(t.message),this.name=\"RequestError\",Object.assign(this,t)}};XI.CacheError=class extends Error{constructor(t){super(t.message),this.name=\"CacheError\",Object.assign(this,t)}};Hoe.exports=XI});var Goe=_((NLt,joe)=>{\"use strict\";var Knt=[\"aborted\",\"complete\",\"headers\",\"httpVersion\",\"httpVersionMinor\",\"httpVersionMajor\",\"method\",\"rawHeaders\",\"rawTrailers\",\"setTimeout\",\"socket\",\"statusCode\",\"statusMessage\",\"trailers\",\"url\"];joe.exports=(t,e)=>{if(e._readableState.autoDestroy)throw new Error(\"The second stream must have the `autoDestroy` option set to `false`\");let r=new Set(Object.keys(t).concat(Knt)),o={};for(let a of r)a in e||(o[a]={get(){let n=t[a];return typeof n==\"function\"?n.bind(t):n},set(n){t[a]=n},enumerable:!0,configurable:!1});return Object.defineProperties(e,o),t.once(\"aborted\",()=>{e.destroy(),e.emit(\"aborted\")}),t.once(\"close\",()=>{t.complete&&e.readable?e.once(\"end\",()=>{e.emit(\"close\")}):e.emit(\"close\")}),e}});var Woe=_((LLt,Yoe)=>{\"use strict\";var{Transform:Vnt,PassThrough:znt}=ve(\"stream\"),LO=ve(\"zlib\"),Jnt=Goe();Yoe.exports=t=>{let e=(t.headers[\"content-encoding\"]||\"\").toLowerCase();if(![\"gzip\",\"deflate\",\"br\"].includes(e))return t;let r=e===\"br\";if(r&&typeof LO.createBrotliDecompress!=\"function\")return t.destroy(new Error(\"Brotli is not supported on Node.js < 12\")),t;let o=!0,a=new Vnt({transform(A,p,h){o=!1,h(null,A)},flush(A){A()}}),n=new znt({autoDestroy:!1,destroy(A,p){t.destroy(),p(A)}}),u=r?LO.createBrotliDecompress():LO.createUnzip();return u.once(\"error\",A=>{if(o&&!t.readable){n.end();return}n.destroy(A)}),Jnt(t,n),t.pipe(a).pipe(u).pipe(n),n}});var OO=_((MLt,Koe)=>{\"use strict\";var MO=class{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw new TypeError(\"`maxSize` must be a number greater than 0\");this.maxSize=e.maxSize,this.onEviction=e.onEviction,this.cache=new Map,this.oldCache=new Map,this._size=0}_set(e,r){if(this.cache.set(e,r),this._size++,this._size>=this.maxSize){if(this._size=0,typeof this.onEviction==\"function\")for(let[o,a]of this.oldCache.entries())this.onEviction(o,a);this.oldCache=this.cache,this.cache=new Map}}get(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e)){let r=this.oldCache.get(e);return this.oldCache.delete(e),this._set(e,r),r}}set(e,r){return this.cache.has(e)?this.cache.set(e,r):this._set(e,r),this}has(e){return this.cache.has(e)||this.oldCache.has(e)}peek(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e))return this.oldCache.get(e)}delete(e){let r=this.cache.delete(e);return r&&this._size--,this.oldCache.delete(e)||r}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}*keys(){for(let[e]of this)yield e}*values(){for(let[,e]of this)yield e}*[Symbol.iterator](){for(let e of this.cache)yield e;for(let e of this.oldCache){let[r]=e;this.cache.has(r)||(yield e)}}get size(){let e=0;for(let r of this.oldCache.keys())this.cache.has(r)||e++;return Math.min(this._size+e,this.maxSize)}};Koe.exports=MO});var _O=_((OLt,Xoe)=>{\"use strict\";var Xnt=ve(\"events\"),Znt=ve(\"tls\"),$nt=ve(\"http2\"),eit=OO(),ra=Symbol(\"currentStreamsCount\"),Voe=Symbol(\"request\"),Kl=Symbol(\"cachedOriginSet\"),ty=Symbol(\"gracefullyClosing\"),tit=[\"maxDeflateDynamicTableSize\",\"maxSessionMemory\",\"maxHeaderListPairs\",\"maxOutstandingPings\",\"maxReservedRemoteStreams\",\"maxSendHeaderBlockLength\",\"paddingStrategy\",\"localAddress\",\"path\",\"rejectUnauthorized\",\"minDHSize\",\"ca\",\"cert\",\"clientCertEngine\",\"ciphers\",\"key\",\"pfx\",\"servername\",\"minVersion\",\"maxVersion\",\"secureProtocol\",\"crl\",\"honorCipherOrder\",\"ecdhCurve\",\"dhparam\",\"secureOptions\",\"sessionIdContext\"],rit=(t,e,r)=>{let o=0,a=t.length;for(;o<a;){let n=o+a>>>1;r(t[n],e)?o=n+1:a=n}return o},nit=(t,e)=>t.remoteSettings.maxConcurrentStreams>e.remoteSettings.maxConcurrentStreams,UO=(t,e)=>{for(let r of t)r[Kl].length<e[Kl].length&&r[Kl].every(o=>e[Kl].includes(o))&&r[ra]+e[ra]<=e.remoteSettings.maxConcurrentStreams&&Joe(r)},iit=(t,e)=>{for(let r of t)e[Kl].length<r[Kl].length&&e[Kl].every(o=>r[Kl].includes(o))&&e[ra]+r[ra]<=r.remoteSettings.maxConcurrentStreams&&Joe(e)},zoe=({agent:t,isFree:e})=>{let r={};for(let o in t.sessions){let n=t.sessions[o].filter(u=>{let A=u[Cg.kCurrentStreamsCount]<u.remoteSettings.maxConcurrentStreams;return e?A:!A});n.length!==0&&(r[o]=n)}return r},Joe=t=>{t[ty]=!0,t[ra]===0&&t.close()},Cg=class t extends Xnt{constructor({timeout:e=6e4,maxSessions:r=1/0,maxFreeSessions:o=10,maxCachedTlsSessions:a=100}={}){super(),this.sessions={},this.queue={},this.timeout=e,this.maxSessions=r,this.maxFreeSessions=o,this._freeSessionsCount=0,this._sessionsCount=0,this.settings={enablePush:!1},this.tlsSessionCache=new eit({maxSize:a})}static normalizeOrigin(e,r){return typeof e==\"string\"&&(e=new URL(e)),r&&e.hostname!==r&&(e.hostname=r),e.origin}normalizeOptions(e){let r=\"\";if(e)for(let o of tit)e[o]&&(r+=`:${e[o]}`);return r}_tryToCreateNewSession(e,r){if(!(e in this.queue)||!(r in this.queue[e]))return;let o=this.queue[e][r];this._sessionsCount<this.maxSessions&&!o.completed&&(o.completed=!0,o())}getSession(e,r,o){return new Promise((a,n)=>{Array.isArray(o)?(o=[...o],a()):o=[{resolve:a,reject:n}];let u=this.normalizeOptions(r),A=t.normalizeOrigin(e,r&&r.servername);if(A===void 0){for(let{reject:E}of o)E(new TypeError(\"The `origin` argument needs to be a string or an URL object\"));return}if(u in this.sessions){let E=this.sessions[u],I=-1,v=-1,x;for(let C of E){let R=C.remoteSettings.maxConcurrentStreams;if(R<I)break;if(C[Kl].includes(A)){let L=C[ra];if(L>=R||C[ty]||C.destroyed)continue;x||(I=R),L>v&&(x=C,v=L)}}if(x){if(o.length!==1){for(let{reject:C}of o){let R=new Error(`Expected the length of listeners to be 1, got ${o.length}.\nPlease report this to https://github.com/szmarczak/http2-wrapper/`);C(R)}return}o[0].resolve(x);return}}if(u in this.queue){if(A in this.queue[u]){this.queue[u][A].listeners.push(...o),this._tryToCreateNewSession(u,A);return}}else this.queue[u]={};let p=()=>{u in this.queue&&this.queue[u][A]===h&&(delete this.queue[u][A],Object.keys(this.queue[u]).length===0&&delete this.queue[u])},h=()=>{let E=`${A}:${u}`,I=!1;try{let v=$nt.connect(e,{createConnection:this.createConnection,settings:this.settings,session:this.tlsSessionCache.get(E),...r});v[ra]=0,v[ty]=!1;let x=()=>v[ra]<v.remoteSettings.maxConcurrentStreams,C=!0;v.socket.once(\"session\",L=>{this.tlsSessionCache.set(E,L)}),v.once(\"error\",L=>{for(let{reject:U}of o)U(L);this.tlsSessionCache.delete(E)}),v.setTimeout(this.timeout,()=>{v.destroy()}),v.once(\"close\",()=>{if(I){C&&this._freeSessionsCount--,this._sessionsCount--;let L=this.sessions[u];L.splice(L.indexOf(v),1),L.length===0&&delete this.sessions[u]}else{let L=new Error(\"Session closed without receiving a SETTINGS frame\");L.code=\"HTTP2WRAPPER_NOSETTINGS\";for(let{reject:U}of o)U(L);p()}this._tryToCreateNewSession(u,A)});let R=()=>{if(!(!(u in this.queue)||!x())){for(let L of v[Kl])if(L in this.queue[u]){let{listeners:U}=this.queue[u][L];for(;U.length!==0&&x();)U.shift().resolve(v);let z=this.queue[u];if(z[L].listeners.length===0&&(delete z[L],Object.keys(z).length===0)){delete this.queue[u];break}if(!x())break}}};v.on(\"origin\",()=>{v[Kl]=v.originSet,x()&&(R(),UO(this.sessions[u],v))}),v.once(\"remoteSettings\",()=>{if(v.ref(),v.unref(),this._sessionsCount++,h.destroyed){let L=new Error(\"Agent has been destroyed\");for(let U of o)U.reject(L);v.destroy();return}v[Kl]=v.originSet;{let L=this.sessions;if(u in L){let U=L[u];U.splice(rit(U,v,nit),0,v)}else L[u]=[v]}this._freeSessionsCount+=1,I=!0,this.emit(\"session\",v),R(),p(),v[ra]===0&&this._freeSessionsCount>this.maxFreeSessions&&v.close(),o.length!==0&&(this.getSession(A,r,o),o.length=0),v.on(\"remoteSettings\",()=>{R(),UO(this.sessions[u],v)})}),v[Voe]=v.request,v.request=(L,U)=>{if(v[ty])throw new Error(\"The session is gracefully closing. No new streams are allowed.\");let z=v[Voe](L,U);return v.ref(),++v[ra],v[ra]===v.remoteSettings.maxConcurrentStreams&&this._freeSessionsCount--,z.once(\"close\",()=>{if(C=x(),--v[ra],!v.destroyed&&!v.closed&&(iit(this.sessions[u],v),x()&&!v.closed)){C||(this._freeSessionsCount++,C=!0);let te=v[ra]===0;te&&v.unref(),te&&(this._freeSessionsCount>this.maxFreeSessions||v[ty])?v.close():(UO(this.sessions[u],v),R())}}),z}}catch(v){for(let x of o)x.reject(v);p()}};h.listeners=o,h.completed=!1,h.destroyed=!1,this.queue[u][A]=h,this._tryToCreateNewSession(u,A)})}request(e,r,o,a){return new Promise((n,u)=>{this.getSession(e,r,[{reject:u,resolve:A=>{try{n(A.request(o,a))}catch(p){u(p)}}}])})}createConnection(e,r){return t.connect(e,r)}static connect(e,r){r.ALPNProtocols=[\"h2\"];let o=e.port||443,a=e.hostname||e.host;return typeof r.servername>\"u\"&&(r.servername=a),Znt.connect(o,a,r)}closeFreeSessions(){for(let e of Object.values(this.sessions))for(let r of e)r[ra]===0&&r.close()}destroy(e){for(let r of Object.values(this.sessions))for(let o of r)o.destroy(e);for(let r of Object.values(this.queue))for(let o of Object.values(r))o.destroyed=!0;this.queue={}}get freeSessions(){return zoe({agent:this,isFree:!0})}get busySessions(){return zoe({agent:this,isFree:!1})}};Cg.kCurrentStreamsCount=ra;Cg.kGracefullyClosing=ty;Xoe.exports={Agent:Cg,globalAgent:new Cg}});var qO=_((ULt,Zoe)=>{\"use strict\";var{Readable:sit}=ve(\"stream\"),HO=class extends sit{constructor(e,r){super({highWaterMark:r,autoDestroy:!1}),this.statusCode=null,this.statusMessage=\"\",this.httpVersion=\"2.0\",this.httpVersionMajor=2,this.httpVersionMinor=0,this.headers={},this.trailers={},this.req=null,this.aborted=!1,this.complete=!1,this.upgrade=null,this.rawHeaders=[],this.rawTrailers=[],this.socket=e,this.connection=e,this._dumped=!1}_destroy(e){this.req._request.destroy(e)}setTimeout(e,r){return this.req.setTimeout(e,r),this}_dump(){this._dumped||(this._dumped=!0,this.removeAllListeners(\"data\"),this.resume())}_read(){this.req&&this.req._request.resume()}};Zoe.exports=HO});var jO=_((_Lt,$oe)=>{\"use strict\";$oe.exports=t=>{let e={protocol:t.protocol,hostname:typeof t.hostname==\"string\"&&t.hostname.startsWith(\"[\")?t.hostname.slice(1,-1):t.hostname,host:t.host,hash:t.hash,search:t.search,pathname:t.pathname,href:t.href,path:`${t.pathname||\"\"}${t.search||\"\"}`};return typeof t.port==\"string\"&&t.port.length!==0&&(e.port=Number(t.port)),(t.username||t.password)&&(e.auth=`${t.username||\"\"}:${t.password||\"\"}`),e}});var tae=_((HLt,eae)=>{\"use strict\";eae.exports=(t,e,r)=>{for(let o of r)t.on(o,(...a)=>e.emit(o,...a))}});var nae=_((qLt,rae)=>{\"use strict\";rae.exports=t=>{switch(t){case\":method\":case\":scheme\":case\":authority\":case\":path\":return!0;default:return!1}}});var sae=_((GLt,iae)=>{\"use strict\";var ry=(t,e,r)=>{iae.exports[e]=class extends t{constructor(...a){super(typeof r==\"string\"?r:r(a)),this.name=`${super.name} [${e}]`,this.code=e}}};ry(TypeError,\"ERR_INVALID_ARG_TYPE\",t=>{let e=t[0].includes(\".\")?\"property\":\"argument\",r=t[1],o=Array.isArray(r);return o&&(r=`${r.slice(0,-1).join(\", \")} or ${r.slice(-1)}`),`The \"${t[0]}\" ${e} must be ${o?\"one of\":\"of\"} type ${r}. Received ${typeof t[2]}`});ry(TypeError,\"ERR_INVALID_PROTOCOL\",t=>`Protocol \"${t[0]}\" not supported. Expected \"${t[1]}\"`);ry(Error,\"ERR_HTTP_HEADERS_SENT\",t=>`Cannot ${t[0]} headers after they are sent to the client`);ry(TypeError,\"ERR_INVALID_HTTP_TOKEN\",t=>`${t[0]} must be a valid HTTP token [${t[1]}]`);ry(TypeError,\"ERR_HTTP_INVALID_HEADER_VALUE\",t=>`Invalid value \"${t[0]} for header \"${t[1]}\"`);ry(TypeError,\"ERR_INVALID_CHAR\",t=>`Invalid character in ${t[0]} [${t[1]}]`)});var VO=_((YLt,fae)=>{\"use strict\";var oit=ve(\"http2\"),{Writable:ait}=ve(\"stream\"),{Agent:oae,globalAgent:lit}=_O(),cit=qO(),uit=jO(),Ait=tae(),fit=nae(),{ERR_INVALID_ARG_TYPE:GO,ERR_INVALID_PROTOCOL:pit,ERR_HTTP_HEADERS_SENT:aae,ERR_INVALID_HTTP_TOKEN:hit,ERR_HTTP_INVALID_HEADER_VALUE:git,ERR_INVALID_CHAR:dit}=sae(),{HTTP2_HEADER_STATUS:lae,HTTP2_HEADER_METHOD:cae,HTTP2_HEADER_PATH:uae,HTTP2_METHOD_CONNECT:mit}=oit.constants,Qo=Symbol(\"headers\"),YO=Symbol(\"origin\"),WO=Symbol(\"session\"),Aae=Symbol(\"options\"),Yb=Symbol(\"flushedHeaders\"),ZI=Symbol(\"jobs\"),yit=/^[\\^`\\-\\w!#$%&*+.|~]+$/,Eit=/[^\\t\\u0020-\\u007E\\u0080-\\u00FF]/,KO=class extends ait{constructor(e,r,o){super({autoDestroy:!1});let a=typeof e==\"string\"||e instanceof URL;if(a&&(e=uit(e instanceof URL?e:new URL(e))),typeof r==\"function\"||r===void 0?(o=r,r=a?e:{...e}):r={...e,...r},r.h2session)this[WO]=r.h2session;else if(r.agent===!1)this.agent=new oae({maxFreeSessions:0});else if(typeof r.agent>\"u\"||r.agent===null)typeof r.createConnection==\"function\"?(this.agent=new oae({maxFreeSessions:0}),this.agent.createConnection=r.createConnection):this.agent=lit;else if(typeof r.agent.request==\"function\")this.agent=r.agent;else throw new GO(\"options.agent\",[\"Agent-like Object\",\"undefined\",\"false\"],r.agent);if(r.protocol&&r.protocol!==\"https:\")throw new pit(r.protocol,\"https:\");let n=r.port||r.defaultPort||this.agent&&this.agent.defaultPort||443,u=r.hostname||r.host||\"localhost\";delete r.hostname,delete r.host,delete r.port;let{timeout:A}=r;if(r.timeout=void 0,this[Qo]=Object.create(null),this[ZI]=[],this.socket=null,this.connection=null,this.method=r.method||\"GET\",this.path=r.path,this.res=null,this.aborted=!1,this.reusedSocket=!1,r.headers)for(let[p,h]of Object.entries(r.headers))this.setHeader(p,h);r.auth&&!(\"authorization\"in this[Qo])&&(this[Qo].authorization=\"Basic \"+Buffer.from(r.auth).toString(\"base64\")),r.session=r.tlsSession,r.path=r.socketPath,this[Aae]=r,n===443?(this[YO]=`https://${u}`,\":authority\"in this[Qo]||(this[Qo][\":authority\"]=u)):(this[YO]=`https://${u}:${n}`,\":authority\"in this[Qo]||(this[Qo][\":authority\"]=`${u}:${n}`)),A&&this.setTimeout(A),o&&this.once(\"response\",o),this[Yb]=!1}get method(){return this[Qo][cae]}set method(e){e&&(this[Qo][cae]=e.toUpperCase())}get path(){return this[Qo][uae]}set path(e){e&&(this[Qo][uae]=e)}get _mustNotHaveABody(){return this.method===\"GET\"||this.method===\"HEAD\"||this.method===\"DELETE\"}_write(e,r,o){if(this._mustNotHaveABody){o(new Error(\"The GET, HEAD and DELETE methods must NOT have a body\"));return}this.flushHeaders();let a=()=>this._request.write(e,r,o);this._request?a():this[ZI].push(a)}_final(e){if(this.destroyed)return;this.flushHeaders();let r=()=>{if(this._mustNotHaveABody){e();return}this._request.end(e)};this._request?r():this[ZI].push(r)}abort(){this.res&&this.res.complete||(this.aborted||process.nextTick(()=>this.emit(\"abort\")),this.aborted=!0,this.destroy())}_destroy(e,r){this.res&&this.res._dump(),this._request&&this._request.destroy(),r(e)}async flushHeaders(){if(this[Yb]||this.destroyed)return;this[Yb]=!0;let e=this.method===mit,r=o=>{if(this._request=o,this.destroyed){o.destroy();return}e||Ait(o,this,[\"timeout\",\"continue\",\"close\",\"error\"]);let a=u=>(...A)=>{!this.writable&&!this.destroyed?u(...A):this.once(\"finish\",()=>{u(...A)})};o.once(\"response\",a((u,A,p)=>{let h=new cit(this.socket,o.readableHighWaterMark);this.res=h,h.req=this,h.statusCode=u[lae],h.headers=u,h.rawHeaders=p,h.once(\"end\",()=>{this.aborted?(h.aborted=!0,h.emit(\"aborted\")):(h.complete=!0,h.socket=null,h.connection=null)}),e?(h.upgrade=!0,this.emit(\"connect\",h,o,Buffer.alloc(0))?this.emit(\"close\"):o.destroy()):(o.on(\"data\",E=>{!h._dumped&&!h.push(E)&&o.pause()}),o.once(\"end\",()=>{h.push(null)}),this.emit(\"response\",h)||h._dump())})),o.once(\"headers\",a(u=>this.emit(\"information\",{statusCode:u[lae]}))),o.once(\"trailers\",a((u,A,p)=>{let{res:h}=this;h.trailers=u,h.rawTrailers=p}));let{socket:n}=o.session;this.socket=n,this.connection=n;for(let u of this[ZI])u();this.emit(\"socket\",this.socket)};if(this[WO])try{r(this[WO].request(this[Qo]))}catch(o){this.emit(\"error\",o)}else{this.reusedSocket=!0;try{r(await this.agent.request(this[YO],this[Aae],this[Qo]))}catch(o){this.emit(\"error\",o)}}}getHeader(e){if(typeof e!=\"string\")throw new GO(\"name\",\"string\",e);return this[Qo][e.toLowerCase()]}get headersSent(){return this[Yb]}removeHeader(e){if(typeof e!=\"string\")throw new GO(\"name\",\"string\",e);if(this.headersSent)throw new aae(\"remove\");delete this[Qo][e.toLowerCase()]}setHeader(e,r){if(this.headersSent)throw new aae(\"set\");if(typeof e!=\"string\"||!yit.test(e)&&!fit(e))throw new hit(\"Header name\",e);if(typeof r>\"u\")throw new git(r,e);if(Eit.test(r))throw new dit(\"header content\",e);this[Qo][e.toLowerCase()]=r}setNoDelay(){}setSocketKeepAlive(){}setTimeout(e,r){let o=()=>this._request.setTimeout(e,r);return this._request?o():this[ZI].push(o),this}get maxHeadersCount(){if(!this.destroyed&&this._request)return this._request.session.localSettings.maxHeaderListSize}set maxHeadersCount(e){}};fae.exports=KO});var hae=_((WLt,pae)=>{\"use strict\";var Cit=ve(\"tls\");pae.exports=(t={},e=Cit.connect)=>new Promise((r,o)=>{let a=!1,n,u=async()=>{await p,n.off(\"timeout\",A),n.off(\"error\",o),t.resolveSocket?(r({alpnProtocol:n.alpnProtocol,socket:n,timeout:a}),a&&(await Promise.resolve(),n.emit(\"timeout\"))):(n.destroy(),r({alpnProtocol:n.alpnProtocol,timeout:a}))},A=async()=>{a=!0,u()},p=(async()=>{try{n=await e(t,u),n.on(\"error\",o),n.once(\"timeout\",A)}catch(h){o(h)}})()})});var dae=_((KLt,gae)=>{\"use strict\";var wit=ve(\"net\");gae.exports=t=>{let e=t.host,r=t.headers&&t.headers.host;return r&&(r.startsWith(\"[\")?r.indexOf(\"]\")===-1?e=r:e=r.slice(1,-1):e=r.split(\":\",1)[0]),wit.isIP(e)?\"\":e}});var Eae=_((VLt,JO)=>{\"use strict\";var mae=ve(\"http\"),zO=ve(\"https\"),Iit=hae(),Bit=OO(),vit=VO(),Dit=dae(),Pit=jO(),Wb=new Bit({maxSize:100}),$I=new Map,yae=(t,e,r)=>{e._httpMessage={shouldKeepAlive:!0};let o=()=>{t.emit(\"free\",e,r)};e.on(\"free\",o);let a=()=>{t.removeSocket(e,r)};e.on(\"close\",a);let n=()=>{t.removeSocket(e,r),e.off(\"close\",a),e.off(\"free\",o),e.off(\"agentRemove\",n)};e.on(\"agentRemove\",n),t.emit(\"free\",e,r)},bit=async t=>{let e=`${t.host}:${t.port}:${t.ALPNProtocols.sort()}`;if(!Wb.has(e)){if($I.has(e))return(await $I.get(e)).alpnProtocol;let{path:r,agent:o}=t;t.path=t.socketPath;let a=Iit(t);$I.set(e,a);try{let{socket:n,alpnProtocol:u}=await a;if(Wb.set(e,u),t.path=r,u===\"h2\")n.destroy();else{let{globalAgent:A}=zO,p=zO.Agent.prototype.createConnection;o?o.createConnection===p?yae(o,n,t):n.destroy():A.createConnection===p?yae(A,n,t):n.destroy()}return $I.delete(e),u}catch(n){throw $I.delete(e),n}}return Wb.get(e)};JO.exports=async(t,e,r)=>{if((typeof t==\"string\"||t instanceof URL)&&(t=Pit(new URL(t))),typeof e==\"function\"&&(r=e,e=void 0),e={ALPNProtocols:[\"h2\",\"http/1.1\"],...t,...e,resolveSocket:!0},!Array.isArray(e.ALPNProtocols)||e.ALPNProtocols.length===0)throw new Error(\"The `ALPNProtocols` option must be an Array with at least one entry\");e.protocol=e.protocol||\"https:\";let o=e.protocol===\"https:\";e.host=e.hostname||e.host||\"localhost\",e.session=e.tlsSession,e.servername=e.servername||Dit(e),e.port=e.port||(o?443:80),e._defaultAgent=o?zO.globalAgent:mae.globalAgent;let a=e.agent;if(a){if(a.addRequest)throw new Error(\"The `options.agent` object can contain only `http`, `https` or `http2` properties\");e.agent=a[o?\"https\":\"http\"]}return o&&await bit(e)===\"h2\"?(a&&(e.agent=a.http2),new vit(e,r)):mae.request(e,r)};JO.exports.protocolCache=Wb});var wae=_((zLt,Cae)=>{\"use strict\";var Sit=ve(\"http2\"),xit=_O(),XO=VO(),kit=qO(),Qit=Eae(),Fit=(t,e,r)=>new XO(t,e,r),Rit=(t,e,r)=>{let o=new XO(t,e,r);return o.end(),o};Cae.exports={...Sit,ClientRequest:XO,IncomingMessage:kit,...xit,request:Fit,get:Rit,auto:Qit}});var $O=_(ZO=>{\"use strict\";Object.defineProperty(ZO,\"__esModule\",{value:!0});var Iae=Qf();ZO.default=t=>Iae.default.nodeStream(t)&&Iae.default.function_(t.getBoundary)});var Pae=_(e4=>{\"use strict\";Object.defineProperty(e4,\"__esModule\",{value:!0});var vae=ve(\"fs\"),Dae=ve(\"util\"),Bae=Qf(),Tit=$O(),Nit=Dae.promisify(vae.stat);e4.default=async(t,e)=>{if(e&&\"content-length\"in e)return Number(e[\"content-length\"]);if(!t)return 0;if(Bae.default.string(t))return Buffer.byteLength(t);if(Bae.default.buffer(t))return t.length;if(Tit.default(t))return Dae.promisify(t.getLength.bind(t))();if(t instanceof vae.ReadStream){let{size:r}=await Nit(t.path);return r===0?void 0:r}}});var r4=_(t4=>{\"use strict\";Object.defineProperty(t4,\"__esModule\",{value:!0});function Lit(t,e,r){let o={};for(let a of r)o[a]=(...n)=>{e.emit(a,...n)},t.on(a,o[a]);return()=>{for(let a of r)t.off(a,o[a])}}t4.default=Lit});var bae=_(n4=>{\"use strict\";Object.defineProperty(n4,\"__esModule\",{value:!0});n4.default=()=>{let t=[];return{once(e,r,o){e.once(r,o),t.push({origin:e,event:r,fn:o})},unhandleAll(){for(let e of t){let{origin:r,event:o,fn:a}=e;r.removeListener(o,a)}t.length=0}}}});var xae=_(e1=>{\"use strict\";Object.defineProperty(e1,\"__esModule\",{value:!0});e1.TimeoutError=void 0;var Mit=ve(\"net\"),Oit=bae(),Sae=Symbol(\"reentry\"),Uit=()=>{},Kb=class extends Error{constructor(e,r){super(`Timeout awaiting '${r}' for ${e}ms`),this.event=r,this.name=\"TimeoutError\",this.code=\"ETIMEDOUT\"}};e1.TimeoutError=Kb;e1.default=(t,e,r)=>{if(Sae in t)return Uit;t[Sae]=!0;let o=[],{once:a,unhandleAll:n}=Oit.default(),u=(I,v,x)=>{var C;let R=setTimeout(v,I,I,x);(C=R.unref)===null||C===void 0||C.call(R);let L=()=>{clearTimeout(R)};return o.push(L),L},{host:A,hostname:p}=r,h=(I,v)=>{t.destroy(new Kb(I,v))},E=()=>{for(let I of o)I();n()};if(t.once(\"error\",I=>{if(E(),t.listenerCount(\"error\")===0)throw I}),t.once(\"close\",E),a(t,\"response\",I=>{a(I,\"end\",E)}),typeof e.request<\"u\"&&u(e.request,h,\"request\"),typeof e.socket<\"u\"){let I=()=>{h(e.socket,\"socket\")};t.setTimeout(e.socket,I),o.push(()=>{t.removeListener(\"timeout\",I)})}return a(t,\"socket\",I=>{var v;let{socketPath:x}=t;if(I.connecting){let C=!!(x??Mit.isIP((v=p??A)!==null&&v!==void 0?v:\"\")!==0);if(typeof e.lookup<\"u\"&&!C&&typeof I.address().address>\"u\"){let R=u(e.lookup,h,\"lookup\");a(I,\"lookup\",R)}if(typeof e.connect<\"u\"){let R=()=>u(e.connect,h,\"connect\");C?a(I,\"connect\",R()):a(I,\"lookup\",L=>{L===null&&a(I,\"connect\",R())})}typeof e.secureConnect<\"u\"&&r.protocol===\"https:\"&&a(I,\"connect\",()=>{let R=u(e.secureConnect,h,\"secureConnect\");a(I,\"secureConnect\",R)})}if(typeof e.send<\"u\"){let C=()=>u(e.send,h,\"send\");I.connecting?a(I,\"connect\",()=>{a(t,\"upload-complete\",C())}):a(t,\"upload-complete\",C())}}),typeof e.response<\"u\"&&a(t,\"upload-complete\",()=>{let I=u(e.response,h,\"response\");a(t,\"response\",I)}),E}});var Qae=_(i4=>{\"use strict\";Object.defineProperty(i4,\"__esModule\",{value:!0});var kae=Qf();i4.default=t=>{t=t;let e={protocol:t.protocol,hostname:kae.default.string(t.hostname)&&t.hostname.startsWith(\"[\")?t.hostname.slice(1,-1):t.hostname,host:t.host,hash:t.hash,search:t.search,pathname:t.pathname,href:t.href,path:`${t.pathname||\"\"}${t.search||\"\"}`};return kae.default.string(t.port)&&t.port.length>0&&(e.port=Number(t.port)),(t.username||t.password)&&(e.auth=`${t.username||\"\"}:${t.password||\"\"}`),e}});var Fae=_(s4=>{\"use strict\";Object.defineProperty(s4,\"__esModule\",{value:!0});var _it=ve(\"url\"),Hit=[\"protocol\",\"host\",\"hostname\",\"port\",\"pathname\",\"search\"];s4.default=(t,e)=>{var r,o;if(e.path){if(e.pathname)throw new TypeError(\"Parameters `path` and `pathname` are mutually exclusive.\");if(e.search)throw new TypeError(\"Parameters `path` and `search` are mutually exclusive.\");if(e.searchParams)throw new TypeError(\"Parameters `path` and `searchParams` are mutually exclusive.\")}if(e.search&&e.searchParams)throw new TypeError(\"Parameters `search` and `searchParams` are mutually exclusive.\");if(!t){if(!e.protocol)throw new TypeError(\"No URL protocol specified\");t=`${e.protocol}//${(o=(r=e.hostname)!==null&&r!==void 0?r:e.host)!==null&&o!==void 0?o:\"\"}`}let a=new _it.URL(t);if(e.path){let n=e.path.indexOf(\"?\");n===-1?e.pathname=e.path:(e.pathname=e.path.slice(0,n),e.search=e.path.slice(n+1)),delete e.path}for(let n of Hit)e[n]&&(a[n]=e[n].toString());return a}});var Rae=_(a4=>{\"use strict\";Object.defineProperty(a4,\"__esModule\",{value:!0});var o4=class{constructor(){this.weakMap=new WeakMap,this.map=new Map}set(e,r){typeof e==\"object\"?this.weakMap.set(e,r):this.map.set(e,r)}get(e){return typeof e==\"object\"?this.weakMap.get(e):this.map.get(e)}has(e){return typeof e==\"object\"?this.weakMap.has(e):this.map.has(e)}};a4.default=o4});var c4=_(l4=>{\"use strict\";Object.defineProperty(l4,\"__esModule\",{value:!0});var qit=async t=>{let e=[],r=0;for await(let o of t)e.push(o),r+=Buffer.byteLength(o);return Buffer.isBuffer(e[0])?Buffer.concat(e,r):Buffer.from(e.join(\"\"))};l4.default=qit});var Nae=_(wg=>{\"use strict\";Object.defineProperty(wg,\"__esModule\",{value:!0});wg.dnsLookupIpVersionToFamily=wg.isDnsLookupIpVersion=void 0;var Tae={auto:0,ipv4:4,ipv6:6};wg.isDnsLookupIpVersion=t=>t in Tae;wg.dnsLookupIpVersionToFamily=t=>{if(wg.isDnsLookupIpVersion(t))return Tae[t];throw new Error(\"Invalid DNS lookup IP version\")}});var u4=_(Vb=>{\"use strict\";Object.defineProperty(Vb,\"__esModule\",{value:!0});Vb.isResponseOk=void 0;Vb.isResponseOk=t=>{let{statusCode:e}=t,r=t.request.options.followRedirect?299:399;return e>=200&&e<=r||e===304}});var Mae=_(A4=>{\"use strict\";Object.defineProperty(A4,\"__esModule\",{value:!0});var Lae=new Set;A4.default=t=>{Lae.has(t)||(Lae.add(t),process.emitWarning(`Got: ${t}`,{type:\"DeprecationWarning\"}))}});var Oae=_(f4=>{\"use strict\";Object.defineProperty(f4,\"__esModule\",{value:!0});var Ai=Qf(),jit=(t,e)=>{if(Ai.default.null_(t.encoding))throw new TypeError(\"To get a Buffer, set `options.responseType` to `buffer` instead\");Ai.assert.any([Ai.default.string,Ai.default.undefined],t.encoding),Ai.assert.any([Ai.default.boolean,Ai.default.undefined],t.resolveBodyOnly),Ai.assert.any([Ai.default.boolean,Ai.default.undefined],t.methodRewriting),Ai.assert.any([Ai.default.boolean,Ai.default.undefined],t.isStream),Ai.assert.any([Ai.default.string,Ai.default.undefined],t.responseType),t.responseType===void 0&&(t.responseType=\"text\");let{retry:r}=t;if(e?t.retry={...e.retry}:t.retry={calculateDelay:o=>o.computedValue,limit:0,methods:[],statusCodes:[],errorCodes:[],maxRetryAfter:void 0},Ai.default.object(r)?(t.retry={...t.retry,...r},t.retry.methods=[...new Set(t.retry.methods.map(o=>o.toUpperCase()))],t.retry.statusCodes=[...new Set(t.retry.statusCodes)],t.retry.errorCodes=[...new Set(t.retry.errorCodes)]):Ai.default.number(r)&&(t.retry.limit=r),Ai.default.undefined(t.retry.maxRetryAfter)&&(t.retry.maxRetryAfter=Math.min(...[t.timeout.request,t.timeout.connect].filter(Ai.default.number))),Ai.default.object(t.pagination)){e&&(t.pagination={...e.pagination,...t.pagination});let{pagination:o}=t;if(!Ai.default.function_(o.transform))throw new Error(\"`options.pagination.transform` must be implemented\");if(!Ai.default.function_(o.shouldContinue))throw new Error(\"`options.pagination.shouldContinue` must be implemented\");if(!Ai.default.function_(o.filter))throw new TypeError(\"`options.pagination.filter` must be implemented\");if(!Ai.default.function_(o.paginate))throw new Error(\"`options.pagination.paginate` must be implemented\")}return t.responseType===\"json\"&&t.headers.accept===void 0&&(t.headers.accept=\"application/json\"),t};f4.default=jit});var Uae=_(t1=>{\"use strict\";Object.defineProperty(t1,\"__esModule\",{value:!0});t1.retryAfterStatusCodes=void 0;t1.retryAfterStatusCodes=new Set([413,429,503]);var Git=({attemptCount:t,retryOptions:e,error:r,retryAfter:o})=>{if(t>e.limit)return 0;let a=e.methods.includes(r.options.method),n=e.errorCodes.includes(r.code),u=r.response&&e.statusCodes.includes(r.response.statusCode);if(!a||!n&&!u)return 0;if(r.response){if(o)return e.maxRetryAfter===void 0||o>e.maxRetryAfter?0:o;if(r.response.statusCode===413)return 0}let A=Math.random()*100;return 2**(t-1)*1e3+A};t1.default=Git});var i1=_(Bn=>{\"use strict\";Object.defineProperty(Bn,\"__esModule\",{value:!0});Bn.UnsupportedProtocolError=Bn.ReadError=Bn.TimeoutError=Bn.UploadError=Bn.CacheError=Bn.HTTPError=Bn.MaxRedirectsError=Bn.RequestError=Bn.setNonEnumerableProperties=Bn.knownHookEvents=Bn.withoutBody=Bn.kIsNormalizedAlready=void 0;var _ae=ve(\"util\"),Hae=ve(\"stream\"),Yit=ve(\"fs\"),sh=ve(\"url\"),qae=ve(\"http\"),p4=ve(\"http\"),Wit=ve(\"https\"),Kit=roe(),Vit=coe(),jae=qoe(),zit=Woe(),Jit=wae(),Xit=jb(),ot=Qf(),Zit=Pae(),Gae=$O(),$it=r4(),Yae=xae(),est=Qae(),Wae=Fae(),tst=Rae(),rst=c4(),Kae=Nae(),nst=u4(),oh=Mae(),ist=Oae(),sst=Uae(),h4,$s=Symbol(\"request\"),Xb=Symbol(\"response\"),ny=Symbol(\"responseSize\"),iy=Symbol(\"downloadedSize\"),sy=Symbol(\"bodySize\"),oy=Symbol(\"uploadedSize\"),zb=Symbol(\"serverResponsesPiped\"),Vae=Symbol(\"unproxyEvents\"),zae=Symbol(\"isFromCache\"),g4=Symbol(\"cancelTimeouts\"),Jae=Symbol(\"startedReading\"),ay=Symbol(\"stopReading\"),Jb=Symbol(\"triggerRead\"),ah=Symbol(\"body\"),r1=Symbol(\"jobs\"),Xae=Symbol(\"originalResponse\"),Zae=Symbol(\"retryTimeout\");Bn.kIsNormalizedAlready=Symbol(\"isNormalizedAlready\");var ost=ot.default.string(process.versions.brotli);Bn.withoutBody=new Set([\"GET\",\"HEAD\"]);Bn.knownHookEvents=[\"init\",\"beforeRequest\",\"beforeRedirect\",\"beforeError\",\"beforeRetry\",\"afterResponse\"];function ast(t){for(let e in t){let r=t[e];if(!ot.default.string(r)&&!ot.default.number(r)&&!ot.default.boolean(r)&&!ot.default.null_(r)&&!ot.default.undefined(r))throw new TypeError(`The \\`searchParams\\` value '${String(r)}' must be a string, number, boolean or null`)}}function lst(t){return ot.default.object(t)&&!(\"statusCode\"in t)}var d4=new tst.default,cst=async t=>new Promise((e,r)=>{let o=a=>{r(a)};t.pending||e(),t.once(\"error\",o),t.once(\"ready\",()=>{t.off(\"error\",o),e()})}),ust=new Set([300,301,302,303,304,307,308]),Ast=[\"context\",\"body\",\"json\",\"form\"];Bn.setNonEnumerableProperties=(t,e)=>{let r={};for(let o of t)if(o)for(let a of Ast)a in o&&(r[a]={writable:!0,configurable:!0,enumerable:!1,value:o[a]});Object.defineProperties(e,r)};var Ji=class extends Error{constructor(e,r,o){var a;if(super(e),Error.captureStackTrace(this,this.constructor),this.name=\"RequestError\",this.code=r.code,o instanceof iS?(Object.defineProperty(this,\"request\",{enumerable:!1,value:o}),Object.defineProperty(this,\"response\",{enumerable:!1,value:o[Xb]}),Object.defineProperty(this,\"options\",{enumerable:!1,value:o.options})):Object.defineProperty(this,\"options\",{enumerable:!1,value:o}),this.timings=(a=this.request)===null||a===void 0?void 0:a.timings,ot.default.string(r.stack)&&ot.default.string(this.stack)){let n=this.stack.indexOf(this.message)+this.message.length,u=this.stack.slice(n).split(`\n`).reverse(),A=r.stack.slice(r.stack.indexOf(r.message)+r.message.length).split(`\n`).reverse();for(;A.length!==0&&A[0]===u[0];)u.shift();this.stack=`${this.stack.slice(0,n)}${u.reverse().join(`\n`)}${A.reverse().join(`\n`)}`}}};Bn.RequestError=Ji;var Zb=class extends Ji{constructor(e){super(`Redirected ${e.options.maxRedirects} times. Aborting.`,{},e),this.name=\"MaxRedirectsError\"}};Bn.MaxRedirectsError=Zb;var $b=class extends Ji{constructor(e){super(`Response code ${e.statusCode} (${e.statusMessage})`,{},e.request),this.name=\"HTTPError\"}};Bn.HTTPError=$b;var eS=class extends Ji{constructor(e,r){super(e.message,e,r),this.name=\"CacheError\"}};Bn.CacheError=eS;var tS=class extends Ji{constructor(e,r){super(e.message,e,r),this.name=\"UploadError\"}};Bn.UploadError=tS;var rS=class extends Ji{constructor(e,r,o){super(e.message,e,o),this.name=\"TimeoutError\",this.event=e.event,this.timings=r}};Bn.TimeoutError=rS;var n1=class extends Ji{constructor(e,r){super(e.message,e,r),this.name=\"ReadError\"}};Bn.ReadError=n1;var nS=class extends Ji{constructor(e){super(`Unsupported protocol \"${e.url.protocol}\"`,{},e),this.name=\"UnsupportedProtocolError\"}};Bn.UnsupportedProtocolError=nS;var fst=[\"socket\",\"connect\",\"continue\",\"information\",\"upgrade\",\"timeout\"],iS=class extends Hae.Duplex{constructor(e,r={},o){super({autoDestroy:!1,highWaterMark:0}),this[iy]=0,this[oy]=0,this.requestInitialized=!1,this[zb]=new Set,this.redirects=[],this[ay]=!1,this[Jb]=!1,this[r1]=[],this.retryCount=0,this._progressCallbacks=[];let a=()=>this._unlockWrite(),n=()=>this._lockWrite();this.on(\"pipe\",h=>{h.prependListener(\"data\",a),h.on(\"data\",n),h.prependListener(\"end\",a),h.on(\"end\",n)}),this.on(\"unpipe\",h=>{h.off(\"data\",a),h.off(\"data\",n),h.off(\"end\",a),h.off(\"end\",n)}),this.on(\"pipe\",h=>{h instanceof p4.IncomingMessage&&(this.options.headers={...h.headers,...this.options.headers})});let{json:u,body:A,form:p}=r;if((u||A||p)&&this._lockWrite(),Bn.kIsNormalizedAlready in r)this.options=r;else try{this.options=this.constructor.normalizeArguments(e,r,o)}catch(h){ot.default.nodeStream(r.body)&&r.body.destroy(),this.destroy(h);return}(async()=>{var h;try{this.options.body instanceof Yit.ReadStream&&await cst(this.options.body);let{url:E}=this.options;if(!E)throw new TypeError(\"Missing `url` property\");if(this.requestUrl=E.toString(),decodeURI(this.requestUrl),await this._finalizeBody(),await this._makeRequest(),this.destroyed){(h=this[$s])===null||h===void 0||h.destroy();return}for(let I of this[r1])I();this[r1].length=0,this.requestInitialized=!0}catch(E){if(E instanceof Ji){this._beforeError(E);return}this.destroyed||this.destroy(E)}})()}static normalizeArguments(e,r,o){var a,n,u,A,p;let h=r;if(ot.default.object(e)&&!ot.default.urlInstance(e))r={...o,...e,...r};else{if(e&&r&&r.url!==void 0)throw new TypeError(\"The `url` option is mutually exclusive with the `input` argument\");r={...o,...r},e!==void 0&&(r.url=e),ot.default.urlInstance(r.url)&&(r.url=new sh.URL(r.url.toString()))}if(r.cache===!1&&(r.cache=void 0),r.dnsCache===!1&&(r.dnsCache=void 0),ot.assert.any([ot.default.string,ot.default.undefined],r.method),ot.assert.any([ot.default.object,ot.default.undefined],r.headers),ot.assert.any([ot.default.string,ot.default.urlInstance,ot.default.undefined],r.prefixUrl),ot.assert.any([ot.default.object,ot.default.undefined],r.cookieJar),ot.assert.any([ot.default.object,ot.default.string,ot.default.undefined],r.searchParams),ot.assert.any([ot.default.object,ot.default.string,ot.default.undefined],r.cache),ot.assert.any([ot.default.object,ot.default.number,ot.default.undefined],r.timeout),ot.assert.any([ot.default.object,ot.default.undefined],r.context),ot.assert.any([ot.default.object,ot.default.undefined],r.hooks),ot.assert.any([ot.default.boolean,ot.default.undefined],r.decompress),ot.assert.any([ot.default.boolean,ot.default.undefined],r.ignoreInvalidCookies),ot.assert.any([ot.default.boolean,ot.default.undefined],r.followRedirect),ot.assert.any([ot.default.number,ot.default.undefined],r.maxRedirects),ot.assert.any([ot.default.boolean,ot.default.undefined],r.throwHttpErrors),ot.assert.any([ot.default.boolean,ot.default.undefined],r.http2),ot.assert.any([ot.default.boolean,ot.default.undefined],r.allowGetBody),ot.assert.any([ot.default.string,ot.default.undefined],r.localAddress),ot.assert.any([Kae.isDnsLookupIpVersion,ot.default.undefined],r.dnsLookupIpVersion),ot.assert.any([ot.default.object,ot.default.undefined],r.https),ot.assert.any([ot.default.boolean,ot.default.undefined],r.rejectUnauthorized),r.https&&(ot.assert.any([ot.default.boolean,ot.default.undefined],r.https.rejectUnauthorized),ot.assert.any([ot.default.function_,ot.default.undefined],r.https.checkServerIdentity),ot.assert.any([ot.default.string,ot.default.object,ot.default.array,ot.default.undefined],r.https.certificateAuthority),ot.assert.any([ot.default.string,ot.default.object,ot.default.array,ot.default.undefined],r.https.key),ot.assert.any([ot.default.string,ot.default.object,ot.default.array,ot.default.undefined],r.https.certificate),ot.assert.any([ot.default.string,ot.default.undefined],r.https.passphrase),ot.assert.any([ot.default.string,ot.default.buffer,ot.default.array,ot.default.undefined],r.https.pfx)),ot.assert.any([ot.default.object,ot.default.undefined],r.cacheOptions),ot.default.string(r.method)?r.method=r.method.toUpperCase():r.method=\"GET\",r.headers===o?.headers?r.headers={...r.headers}:r.headers=Xit({...o?.headers,...r.headers}),\"slashes\"in r)throw new TypeError(\"The legacy `url.Url` has been deprecated. Use `URL` instead.\");if(\"auth\"in r)throw new TypeError(\"Parameter `auth` is deprecated. Use `username` / `password` instead.\");if(\"searchParams\"in r&&r.searchParams&&r.searchParams!==o?.searchParams){let x;if(ot.default.string(r.searchParams)||r.searchParams instanceof sh.URLSearchParams)x=new sh.URLSearchParams(r.searchParams);else{ast(r.searchParams),x=new sh.URLSearchParams;for(let C in r.searchParams){let R=r.searchParams[C];R===null?x.append(C,\"\"):R!==void 0&&x.append(C,R)}}(a=o?.searchParams)===null||a===void 0||a.forEach((C,R)=>{x.has(R)||x.append(R,C)}),r.searchParams=x}if(r.username=(n=r.username)!==null&&n!==void 0?n:\"\",r.password=(u=r.password)!==null&&u!==void 0?u:\"\",ot.default.undefined(r.prefixUrl)?r.prefixUrl=(A=o?.prefixUrl)!==null&&A!==void 0?A:\"\":(r.prefixUrl=r.prefixUrl.toString(),r.prefixUrl!==\"\"&&!r.prefixUrl.endsWith(\"/\")&&(r.prefixUrl+=\"/\")),ot.default.string(r.url)){if(r.url.startsWith(\"/\"))throw new Error(\"`input` must not start with a slash when using `prefixUrl`\");r.url=Wae.default(r.prefixUrl+r.url,r)}else(ot.default.undefined(r.url)&&r.prefixUrl!==\"\"||r.protocol)&&(r.url=Wae.default(r.prefixUrl,r));if(r.url){\"port\"in r&&delete r.port;let{prefixUrl:x}=r;Object.defineProperty(r,\"prefixUrl\",{set:R=>{let L=r.url;if(!L.href.startsWith(R))throw new Error(`Cannot change \\`prefixUrl\\` from ${x} to ${R}: ${L.href}`);r.url=new sh.URL(R+L.href.slice(x.length)),x=R},get:()=>x});let{protocol:C}=r.url;if(C===\"unix:\"&&(C=\"http:\",r.url=new sh.URL(`http://unix${r.url.pathname}${r.url.search}`)),r.searchParams&&(r.url.search=r.searchParams.toString()),C!==\"http:\"&&C!==\"https:\")throw new nS(r);r.username===\"\"?r.username=r.url.username:r.url.username=r.username,r.password===\"\"?r.password=r.url.password:r.url.password=r.password}let{cookieJar:E}=r;if(E){let{setCookie:x,getCookieString:C}=E;ot.assert.function_(x),ot.assert.function_(C),x.length===4&&C.length===0&&(x=_ae.promisify(x.bind(r.cookieJar)),C=_ae.promisify(C.bind(r.cookieJar)),r.cookieJar={setCookie:x,getCookieString:C})}let{cache:I}=r;if(I&&(d4.has(I)||d4.set(I,new jae((x,C)=>{let R=x[$s](x,C);return ot.default.promise(R)&&(R.once=(L,U)=>{if(L===\"error\")R.catch(U);else if(L===\"abort\")(async()=>{try{(await R).once(\"abort\",U)}catch{}})();else throw new Error(`Unknown HTTP2 promise event: ${L}`);return R}),R},I))),r.cacheOptions={...r.cacheOptions},r.dnsCache===!0)h4||(h4=new Vit.default),r.dnsCache=h4;else if(!ot.default.undefined(r.dnsCache)&&!r.dnsCache.lookup)throw new TypeError(`Parameter \\`dnsCache\\` must be a CacheableLookup instance or a boolean, got ${ot.default(r.dnsCache)}`);ot.default.number(r.timeout)?r.timeout={request:r.timeout}:o&&r.timeout!==o.timeout?r.timeout={...o.timeout,...r.timeout}:r.timeout={...r.timeout},r.context||(r.context={});let v=r.hooks===o?.hooks;r.hooks={...r.hooks};for(let x of Bn.knownHookEvents)if(x in r.hooks)if(ot.default.array(r.hooks[x]))r.hooks[x]=[...r.hooks[x]];else throw new TypeError(`Parameter \\`${x}\\` must be an Array, got ${ot.default(r.hooks[x])}`);else r.hooks[x]=[];if(o&&!v)for(let x of Bn.knownHookEvents)o.hooks[x].length>0&&(r.hooks[x]=[...o.hooks[x],...r.hooks[x]]);if(\"family\"in r&&oh.default('\"options.family\" was never documented, please use \"options.dnsLookupIpVersion\"'),o?.https&&(r.https={...o.https,...r.https}),\"rejectUnauthorized\"in r&&oh.default('\"options.rejectUnauthorized\" is now deprecated, please use \"options.https.rejectUnauthorized\"'),\"checkServerIdentity\"in r&&oh.default('\"options.checkServerIdentity\" was never documented, please use \"options.https.checkServerIdentity\"'),\"ca\"in r&&oh.default('\"options.ca\" was never documented, please use \"options.https.certificateAuthority\"'),\"key\"in r&&oh.default('\"options.key\" was never documented, please use \"options.https.key\"'),\"cert\"in r&&oh.default('\"options.cert\" was never documented, please use \"options.https.certificate\"'),\"passphrase\"in r&&oh.default('\"options.passphrase\" was never documented, please use \"options.https.passphrase\"'),\"pfx\"in r&&oh.default('\"options.pfx\" was never documented, please use \"options.https.pfx\"'),\"followRedirects\"in r)throw new TypeError(\"The `followRedirects` option does not exist. Use `followRedirect` instead.\");if(r.agent){for(let x in r.agent)if(x!==\"http\"&&x!==\"https\"&&x!==\"http2\")throw new TypeError(`Expected the \\`options.agent\\` properties to be \\`http\\`, \\`https\\` or \\`http2\\`, got \\`${x}\\``)}return r.maxRedirects=(p=r.maxRedirects)!==null&&p!==void 0?p:0,Bn.setNonEnumerableProperties([o,h],r),ist.default(r,o)}_lockWrite(){let e=()=>{throw new TypeError(\"The payload has been already provided\")};this.write=e,this.end=e}_unlockWrite(){this.write=super.write,this.end=super.end}async _finalizeBody(){let{options:e}=this,{headers:r}=e,o=!ot.default.undefined(e.form),a=!ot.default.undefined(e.json),n=!ot.default.undefined(e.body),u=o||a||n,A=Bn.withoutBody.has(e.method)&&!(e.method===\"GET\"&&e.allowGetBody);if(this._cannotHaveBody=A,u){if(A)throw new TypeError(`The \\`${e.method}\\` method cannot be used with a body`);if([n,o,a].filter(p=>p).length>1)throw new TypeError(\"The `body`, `json` and `form` options are mutually exclusive\");if(n&&!(e.body instanceof Hae.Readable)&&!ot.default.string(e.body)&&!ot.default.buffer(e.body)&&!Gae.default(e.body))throw new TypeError(\"The `body` option must be a stream.Readable, string or Buffer\");if(o&&!ot.default.object(e.form))throw new TypeError(\"The `form` option must be an Object\");{let p=!ot.default.string(r[\"content-type\"]);n?(Gae.default(e.body)&&p&&(r[\"content-type\"]=`multipart/form-data; boundary=${e.body.getBoundary()}`),this[ah]=e.body):o?(p&&(r[\"content-type\"]=\"application/x-www-form-urlencoded\"),this[ah]=new sh.URLSearchParams(e.form).toString()):(p&&(r[\"content-type\"]=\"application/json\"),this[ah]=e.stringifyJson(e.json));let h=await Zit.default(this[ah],e.headers);ot.default.undefined(r[\"content-length\"])&&ot.default.undefined(r[\"transfer-encoding\"])&&!A&&!ot.default.undefined(h)&&(r[\"content-length\"]=String(h))}}else A?this._lockWrite():this._unlockWrite();this[sy]=Number(r[\"content-length\"])||void 0}async _onResponseBase(e){let{options:r}=this,{url:o}=r;this[Xae]=e,r.decompress&&(e=zit(e));let a=e.statusCode,n=e;n.statusMessage=n.statusMessage?n.statusMessage:qae.STATUS_CODES[a],n.url=r.url.toString(),n.requestUrl=this.requestUrl,n.redirectUrls=this.redirects,n.request=this,n.isFromCache=e.fromCache||!1,n.ip=this.ip,n.retryCount=this.retryCount,this[zae]=n.isFromCache,this[ny]=Number(e.headers[\"content-length\"])||void 0,this[Xb]=e,e.once(\"end\",()=>{this[ny]=this[iy],this.emit(\"downloadProgress\",this.downloadProgress)}),e.once(\"error\",A=>{e.destroy(),this._beforeError(new n1(A,this))}),e.once(\"aborted\",()=>{this._beforeError(new n1({name:\"Error\",message:\"The server aborted pending request\",code:\"ECONNRESET\"},this))}),this.emit(\"downloadProgress\",this.downloadProgress);let u=e.headers[\"set-cookie\"];if(ot.default.object(r.cookieJar)&&u){let A=u.map(async p=>r.cookieJar.setCookie(p,o.toString()));r.ignoreInvalidCookies&&(A=A.map(async p=>p.catch(()=>{})));try{await Promise.all(A)}catch(p){this._beforeError(p);return}}if(r.followRedirect&&e.headers.location&&ust.has(a)){if(e.resume(),this[$s]&&(this[g4](),delete this[$s],this[Vae]()),(a===303&&r.method!==\"GET\"&&r.method!==\"HEAD\"||!r.methodRewriting)&&(r.method=\"GET\",\"body\"in r&&delete r.body,\"json\"in r&&delete r.json,\"form\"in r&&delete r.form,this[ah]=void 0,delete r.headers[\"content-length\"]),this.redirects.length>=r.maxRedirects){this._beforeError(new Zb(this));return}try{let p=Buffer.from(e.headers.location,\"binary\").toString(),h=new sh.URL(p,o),E=h.toString();decodeURI(E),h.hostname!==o.hostname||h.port!==o.port?(\"host\"in r.headers&&delete r.headers.host,\"cookie\"in r.headers&&delete r.headers.cookie,\"authorization\"in r.headers&&delete r.headers.authorization,(r.username||r.password)&&(r.username=\"\",r.password=\"\")):(h.username=r.username,h.password=r.password),this.redirects.push(E),r.url=h;for(let I of r.hooks.beforeRedirect)await I(r,n);this.emit(\"redirect\",n,r),await this._makeRequest()}catch(p){this._beforeError(p);return}return}if(r.isStream&&r.throwHttpErrors&&!nst.isResponseOk(n)){this._beforeError(new $b(n));return}e.on(\"readable\",()=>{this[Jb]&&this._read()}),this.on(\"resume\",()=>{e.resume()}),this.on(\"pause\",()=>{e.pause()}),e.once(\"end\",()=>{this.push(null)}),this.emit(\"response\",e);for(let A of this[zb])if(!A.headersSent){for(let p in e.headers){let h=r.decompress?p!==\"content-encoding\":!0,E=e.headers[p];h&&A.setHeader(p,E)}A.statusCode=a}}async _onResponse(e){try{await this._onResponseBase(e)}catch(r){this._beforeError(r)}}_onRequest(e){let{options:r}=this,{timeout:o,url:a}=r;Kit.default(e),this[g4]=Yae.default(e,o,a);let n=r.cache?\"cacheableResponse\":\"response\";e.once(n,p=>{this._onResponse(p)}),e.once(\"error\",p=>{var h;e.destroy(),(h=e.res)===null||h===void 0||h.removeAllListeners(\"end\"),p=p instanceof Yae.TimeoutError?new rS(p,this.timings,this):new Ji(p.message,p,this),this._beforeError(p)}),this[Vae]=$it.default(e,this,fst),this[$s]=e,this.emit(\"uploadProgress\",this.uploadProgress);let u=this[ah],A=this.redirects.length===0?this:e;ot.default.nodeStream(u)?(u.pipe(A),u.once(\"error\",p=>{this._beforeError(new tS(p,this))})):(this._unlockWrite(),ot.default.undefined(u)?(this._cannotHaveBody||this._noPipe)&&(A.end(),this._lockWrite()):(this._writeRequest(u,void 0,()=>{}),A.end(),this._lockWrite())),this.emit(\"request\",e)}async _createCacheableRequest(e,r){return new Promise((o,a)=>{Object.assign(r,est.default(e)),delete r.url;let n,u=d4.get(r.cache)(r,async A=>{A._readableState.autoDestroy=!1,n&&(await n).emit(\"cacheableResponse\",A),o(A)});r.url=e,u.once(\"error\",a),u.once(\"request\",async A=>{n=A,o(n)})})}async _makeRequest(){var e,r,o,a,n;let{options:u}=this,{headers:A}=u;for(let U in A)if(ot.default.undefined(A[U]))delete A[U];else if(ot.default.null_(A[U]))throw new TypeError(`Use \\`undefined\\` instead of \\`null\\` to delete the \\`${U}\\` header`);if(u.decompress&&ot.default.undefined(A[\"accept-encoding\"])&&(A[\"accept-encoding\"]=ost?\"gzip, deflate, br\":\"gzip, deflate\"),u.cookieJar){let U=await u.cookieJar.getCookieString(u.url.toString());ot.default.nonEmptyString(U)&&(u.headers.cookie=U)}for(let U of u.hooks.beforeRequest){let z=await U(u);if(!ot.default.undefined(z)){u.request=()=>z;break}}u.body&&this[ah]!==u.body&&(this[ah]=u.body);let{agent:p,request:h,timeout:E,url:I}=u;if(u.dnsCache&&!(\"lookup\"in u)&&(u.lookup=u.dnsCache.lookup),I.hostname===\"unix\"){let U=/(?<socketPath>.+?):(?<path>.+)/.exec(`${I.pathname}${I.search}`);if(U?.groups){let{socketPath:z,path:te}=U.groups;Object.assign(u,{socketPath:z,path:te,host:\"\"})}}let v=I.protocol===\"https:\",x;u.http2?x=Jit.auto:x=v?Wit.request:qae.request;let C=(e=u.request)!==null&&e!==void 0?e:x,R=u.cache?this._createCacheableRequest:C;p&&!u.http2&&(u.agent=p[v?\"https\":\"http\"]),u[$s]=C,delete u.request,delete u.timeout;let L=u;if(L.shared=(r=u.cacheOptions)===null||r===void 0?void 0:r.shared,L.cacheHeuristic=(o=u.cacheOptions)===null||o===void 0?void 0:o.cacheHeuristic,L.immutableMinTimeToLive=(a=u.cacheOptions)===null||a===void 0?void 0:a.immutableMinTimeToLive,L.ignoreCargoCult=(n=u.cacheOptions)===null||n===void 0?void 0:n.ignoreCargoCult,u.dnsLookupIpVersion!==void 0)try{L.family=Kae.dnsLookupIpVersionToFamily(u.dnsLookupIpVersion)}catch{throw new Error(\"Invalid `dnsLookupIpVersion` option value\")}u.https&&(\"rejectUnauthorized\"in u.https&&(L.rejectUnauthorized=u.https.rejectUnauthorized),u.https.checkServerIdentity&&(L.checkServerIdentity=u.https.checkServerIdentity),u.https.certificateAuthority&&(L.ca=u.https.certificateAuthority),u.https.certificate&&(L.cert=u.https.certificate),u.https.key&&(L.key=u.https.key),u.https.passphrase&&(L.passphrase=u.https.passphrase),u.https.pfx&&(L.pfx=u.https.pfx));try{let U=await R(I,L);ot.default.undefined(U)&&(U=x(I,L)),u.request=h,u.timeout=E,u.agent=p,u.https&&(\"rejectUnauthorized\"in u.https&&delete L.rejectUnauthorized,u.https.checkServerIdentity&&delete L.checkServerIdentity,u.https.certificateAuthority&&delete L.ca,u.https.certificate&&delete L.cert,u.https.key&&delete L.key,u.https.passphrase&&delete L.passphrase,u.https.pfx&&delete L.pfx),lst(U)?this._onRequest(U):this.writable?(this.once(\"finish\",()=>{this._onResponse(U)}),this._unlockWrite(),this.end(),this._lockWrite()):this._onResponse(U)}catch(U){throw U instanceof jae.CacheError?new eS(U,this):new Ji(U.message,U,this)}}async _error(e){try{for(let r of this.options.hooks.beforeError)e=await r(e)}catch(r){e=new Ji(r.message,r,this)}this.destroy(e)}_beforeError(e){if(this[ay])return;let{options:r}=this,o=this.retryCount+1;this[ay]=!0,e instanceof Ji||(e=new Ji(e.message,e,this));let a=e,{response:n}=a;(async()=>{if(n&&!n.body){n.setEncoding(this._readableState.encoding);try{n.rawBody=await rst.default(n),n.body=n.rawBody.toString()}catch{}}if(this.listenerCount(\"retry\")!==0){let u;try{let A;n&&\"retry-after\"in n.headers&&(A=Number(n.headers[\"retry-after\"]),Number.isNaN(A)?(A=Date.parse(n.headers[\"retry-after\"])-Date.now(),A<=0&&(A=1)):A*=1e3),u=await r.retry.calculateDelay({attemptCount:o,retryOptions:r.retry,error:a,retryAfter:A,computedValue:sst.default({attemptCount:o,retryOptions:r.retry,error:a,retryAfter:A,computedValue:0})})}catch(A){this._error(new Ji(A.message,A,this));return}if(u){let A=async()=>{try{for(let p of this.options.hooks.beforeRetry)await p(this.options,a,o)}catch(p){this._error(new Ji(p.message,e,this));return}this.destroyed||(this.destroy(),this.emit(\"retry\",o,e))};this[Zae]=setTimeout(A,u);return}}this._error(a)})()}_read(){this[Jb]=!0;let e=this[Xb];if(e&&!this[ay]){e.readableLength&&(this[Jb]=!1);let r;for(;(r=e.read())!==null;){this[iy]+=r.length,this[Jae]=!0;let o=this.downloadProgress;o.percent<1&&this.emit(\"downloadProgress\",o),this.push(r)}}}_write(e,r,o){let a=()=>{this._writeRequest(e,r,o)};this.requestInitialized?a():this[r1].push(a)}_writeRequest(e,r,o){this[$s].destroyed||(this._progressCallbacks.push(()=>{this[oy]+=Buffer.byteLength(e,r);let a=this.uploadProgress;a.percent<1&&this.emit(\"uploadProgress\",a)}),this[$s].write(e,r,a=>{!a&&this._progressCallbacks.length>0&&this._progressCallbacks.shift()(),o(a)}))}_final(e){let r=()=>{for(;this._progressCallbacks.length!==0;)this._progressCallbacks.shift()();if(!($s in this)){e();return}if(this[$s].destroyed){e();return}this[$s].end(o=>{o||(this[sy]=this[oy],this.emit(\"uploadProgress\",this.uploadProgress),this[$s].emit(\"upload-complete\")),e(o)})};this.requestInitialized?r():this[r1].push(r)}_destroy(e,r){var o;this[ay]=!0,clearTimeout(this[Zae]),$s in this&&(this[g4](),!((o=this[Xb])===null||o===void 0)&&o.complete||this[$s].destroy()),e!==null&&!ot.default.undefined(e)&&!(e instanceof Ji)&&(e=new Ji(e.message,e,this)),r(e)}get _isAboutToError(){return this[ay]}get ip(){var e;return(e=this.socket)===null||e===void 0?void 0:e.remoteAddress}get aborted(){var e,r,o;return((r=(e=this[$s])===null||e===void 0?void 0:e.destroyed)!==null&&r!==void 0?r:this.destroyed)&&!(!((o=this[Xae])===null||o===void 0)&&o.complete)}get socket(){var e,r;return(r=(e=this[$s])===null||e===void 0?void 0:e.socket)!==null&&r!==void 0?r:void 0}get downloadProgress(){let e;return this[ny]?e=this[iy]/this[ny]:this[ny]===this[iy]?e=1:e=0,{percent:e,transferred:this[iy],total:this[ny]}}get uploadProgress(){let e;return this[sy]?e=this[oy]/this[sy]:this[sy]===this[oy]?e=1:e=0,{percent:e,transferred:this[oy],total:this[sy]}}get timings(){var e;return(e=this[$s])===null||e===void 0?void 0:e.timings}get isFromCache(){return this[zae]}pipe(e,r){if(this[Jae])throw new Error(\"Failed to pipe. The response has been emitted already.\");return e instanceof p4.ServerResponse&&this[zb].add(e),super.pipe(e,r)}unpipe(e){return e instanceof p4.ServerResponse&&this[zb].delete(e),super.unpipe(e),this}};Bn.default=iS});var s1=_(Yc=>{\"use strict\";var pst=Yc&&Yc.__createBinding||(Object.create?function(t,e,r,o){o===void 0&&(o=r),Object.defineProperty(t,o,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,o){o===void 0&&(o=r),t[o]=e[r]}),hst=Yc&&Yc.__exportStar||function(t,e){for(var r in t)r!==\"default\"&&!Object.prototype.hasOwnProperty.call(e,r)&&pst(e,t,r)};Object.defineProperty(Yc,\"__esModule\",{value:!0});Yc.CancelError=Yc.ParseError=void 0;var $ae=i1(),m4=class extends $ae.RequestError{constructor(e,r){let{options:o}=r.request;super(`${e.message} in \"${o.url.toString()}\"`,e,r.request),this.name=\"ParseError\"}};Yc.ParseError=m4;var y4=class extends $ae.RequestError{constructor(e){super(\"Promise was canceled\",{},e),this.name=\"CancelError\"}get isCanceled(){return!0}};Yc.CancelError=y4;hst(i1(),Yc)});var tle=_(E4=>{\"use strict\";Object.defineProperty(E4,\"__esModule\",{value:!0});var ele=s1(),gst=(t,e,r,o)=>{let{rawBody:a}=t;try{if(e===\"text\")return a.toString(o);if(e===\"json\")return a.length===0?\"\":r(a.toString());if(e===\"buffer\")return a;throw new ele.ParseError({message:`Unknown body type '${e}'`,name:\"Error\"},t)}catch(n){throw new ele.ParseError(n,t)}};E4.default=gst});var C4=_(lh=>{\"use strict\";var dst=lh&&lh.__createBinding||(Object.create?function(t,e,r,o){o===void 0&&(o=r),Object.defineProperty(t,o,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,o){o===void 0&&(o=r),t[o]=e[r]}),mst=lh&&lh.__exportStar||function(t,e){for(var r in t)r!==\"default\"&&!Object.prototype.hasOwnProperty.call(e,r)&&dst(e,t,r)};Object.defineProperty(lh,\"__esModule\",{value:!0});var yst=ve(\"events\"),Est=Qf(),Cst=eoe(),sS=s1(),rle=tle(),nle=i1(),wst=r4(),Ist=c4(),ile=u4(),Bst=[\"request\",\"response\",\"redirect\",\"uploadProgress\",\"downloadProgress\"];function sle(t){let e,r,o=new yst.EventEmitter,a=new Cst((u,A,p)=>{let h=E=>{let I=new nle.default(void 0,t);I.retryCount=E,I._noPipe=!0,p(()=>I.destroy()),p.shouldReject=!1,p(()=>A(new sS.CancelError(I))),e=I,I.once(\"response\",async C=>{var R;if(C.retryCount=E,C.request.aborted)return;let L;try{L=await Ist.default(I),C.rawBody=L}catch{return}if(I._isAboutToError)return;let U=((R=C.headers[\"content-encoding\"])!==null&&R!==void 0?R:\"\").toLowerCase(),z=[\"gzip\",\"deflate\",\"br\"].includes(U),{options:te}=I;if(z&&!te.decompress)C.body=L;else try{C.body=rle.default(C,te.responseType,te.parseJson,te.encoding)}catch(ae){if(C.body=L.toString(),ile.isResponseOk(C)){I._beforeError(ae);return}}try{for(let[ae,le]of te.hooks.afterResponse.entries())C=await le(C,async ce=>{let Ce=nle.default.normalizeArguments(void 0,{...ce,retry:{calculateDelay:()=>0},throwHttpErrors:!1,resolveBodyOnly:!1},te);Ce.hooks.afterResponse=Ce.hooks.afterResponse.slice(0,ae);for(let Be of Ce.hooks.beforeRetry)await Be(Ce);let de=sle(Ce);return p(()=>{de.catch(()=>{}),de.cancel()}),de})}catch(ae){I._beforeError(new sS.RequestError(ae.message,ae,I));return}if(!ile.isResponseOk(C)){I._beforeError(new sS.HTTPError(C));return}r=C,u(I.options.resolveBodyOnly?C.body:C)});let v=C=>{if(a.isCanceled)return;let{options:R}=I;if(C instanceof sS.HTTPError&&!R.throwHttpErrors){let{response:L}=C;u(I.options.resolveBodyOnly?L.body:L);return}A(C)};I.once(\"error\",v);let x=I.options.body;I.once(\"retry\",(C,R)=>{var L,U;if(x===((L=R.request)===null||L===void 0?void 0:L.options.body)&&Est.default.nodeStream((U=R.request)===null||U===void 0?void 0:U.options.body)){v(R);return}h(C)}),wst.default(I,o,Bst)};h(0)});a.on=(u,A)=>(o.on(u,A),a);let n=u=>{let A=(async()=>{await a;let{options:p}=r.request;return rle.default(r,u,p.parseJson,p.encoding)})();return Object.defineProperties(A,Object.getOwnPropertyDescriptors(a)),A};return a.json=()=>{let{headers:u}=e.options;return!e.writableFinished&&u.accept===void 0&&(u.accept=\"application/json\"),n(\"json\")},a.buffer=()=>n(\"buffer\"),a.text=()=>n(\"text\"),a}lh.default=sle;mst(s1(),lh)});var ole=_(w4=>{\"use strict\";Object.defineProperty(w4,\"__esModule\",{value:!0});var vst=s1();function Dst(t,...e){let r=(async()=>{if(t instanceof vst.RequestError)try{for(let a of e)if(a)for(let n of a)t=await n(t)}catch(a){t=a}throw t})(),o=()=>r;return r.json=o,r.text=o,r.buffer=o,r.on=o,r}w4.default=Dst});var cle=_(I4=>{\"use strict\";Object.defineProperty(I4,\"__esModule\",{value:!0});var ale=Qf();function lle(t){for(let e of Object.values(t))(ale.default.plainObject(e)||ale.default.array(e))&&lle(e);return Object.freeze(t)}I4.default=lle});var Ale=_(ule=>{\"use strict\";Object.defineProperty(ule,\"__esModule\",{value:!0})});var B4=_(zl=>{\"use strict\";var Pst=zl&&zl.__createBinding||(Object.create?function(t,e,r,o){o===void 0&&(o=r),Object.defineProperty(t,o,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,o){o===void 0&&(o=r),t[o]=e[r]}),bst=zl&&zl.__exportStar||function(t,e){for(var r in t)r!==\"default\"&&!Object.prototype.hasOwnProperty.call(e,r)&&Pst(e,t,r)};Object.defineProperty(zl,\"__esModule\",{value:!0});zl.defaultHandler=void 0;var fle=Qf(),Vl=C4(),Sst=ole(),aS=i1(),xst=cle(),kst={RequestError:Vl.RequestError,CacheError:Vl.CacheError,ReadError:Vl.ReadError,HTTPError:Vl.HTTPError,MaxRedirectsError:Vl.MaxRedirectsError,TimeoutError:Vl.TimeoutError,ParseError:Vl.ParseError,CancelError:Vl.CancelError,UnsupportedProtocolError:Vl.UnsupportedProtocolError,UploadError:Vl.UploadError},Qst=async t=>new Promise(e=>{setTimeout(e,t)}),{normalizeArguments:oS}=aS.default,ple=(...t)=>{let e;for(let r of t)e=oS(void 0,r,e);return e},Fst=t=>t.isStream?new aS.default(void 0,t):Vl.default(t),Rst=t=>\"defaults\"in t&&\"options\"in t.defaults,Tst=[\"get\",\"post\",\"put\",\"patch\",\"head\",\"delete\"];zl.defaultHandler=(t,e)=>e(t);var hle=(t,e)=>{if(t)for(let r of t)r(e)},gle=t=>{t._rawHandlers=t.handlers,t.handlers=t.handlers.map(o=>(a,n)=>{let u,A=o(a,p=>(u=n(p),u));if(A!==u&&!a.isStream&&u){let p=A,{then:h,catch:E,finally:I}=p;Object.setPrototypeOf(p,Object.getPrototypeOf(u)),Object.defineProperties(p,Object.getOwnPropertyDescriptors(u)),p.then=h,p.catch=E,p.finally=I}return A});let e=(o,a={},n)=>{var u,A;let p=0,h=E=>t.handlers[p++](E,p===t.handlers.length?Fst:h);if(fle.default.plainObject(o)){let E={...o,...a};aS.setNonEnumerableProperties([o,a],E),a=E,o=void 0}try{let E;try{hle(t.options.hooks.init,a),hle((u=a.hooks)===null||u===void 0?void 0:u.init,a)}catch(v){E=v}let I=oS(o,a,n??t.options);if(I[aS.kIsNormalizedAlready]=!0,E)throw new Vl.RequestError(E.message,E,I);return h(I)}catch(E){if(a.isStream)throw E;return Sst.default(E,t.options.hooks.beforeError,(A=a.hooks)===null||A===void 0?void 0:A.beforeError)}};e.extend=(...o)=>{let a=[t.options],n=[...t._rawHandlers],u;for(let A of o)Rst(A)?(a.push(A.defaults.options),n.push(...A.defaults._rawHandlers),u=A.defaults.mutableDefaults):(a.push(A),\"handlers\"in A&&n.push(...A.handlers),u=A.mutableDefaults);return n=n.filter(A=>A!==zl.defaultHandler),n.length===0&&n.push(zl.defaultHandler),gle({options:ple(...a),handlers:n,mutableDefaults:!!u})};let r=async function*(o,a){let n=oS(o,a,t.options);n.resolveBodyOnly=!1;let u=n.pagination;if(!fle.default.object(u))throw new TypeError(\"`options.pagination` must be implemented\");let A=[],{countLimit:p}=u,h=0;for(;h<u.requestLimit;){h!==0&&await Qst(u.backoff);let E=await e(void 0,void 0,n),I=await u.transform(E),v=[];for(let C of I)if(u.filter(C,A,v)&&(!u.shouldContinue(C,A,v)||(yield C,u.stackAllItems&&A.push(C),v.push(C),--p<=0)))return;let x=u.paginate(E,A,v);if(x===!1)return;x===E.request.options?n=E.request.options:x!==void 0&&(n=oS(void 0,x,n)),h++}};e.paginate=r,e.paginate.all=async(o,a)=>{let n=[];for await(let u of r(o,a))n.push(u);return n},e.paginate.each=r,e.stream=(o,a)=>e(o,{...a,isStream:!0});for(let o of Tst)e[o]=(a,n)=>e(a,{...n,method:o}),e.stream[o]=(a,n)=>e(a,{...n,method:o,isStream:!0});return Object.assign(e,kst),Object.defineProperty(e,\"defaults\",{value:t.mutableDefaults?t:xst.default(t),writable:t.mutableDefaults,configurable:t.mutableDefaults,enumerable:!0}),e.mergeOptions=ple,e};zl.default=gle;bst(Ale(),zl)});var yle=_((Ff,lS)=>{\"use strict\";var Nst=Ff&&Ff.__createBinding||(Object.create?function(t,e,r,o){o===void 0&&(o=r),Object.defineProperty(t,o,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,o){o===void 0&&(o=r),t[o]=e[r]}),dle=Ff&&Ff.__exportStar||function(t,e){for(var r in t)r!==\"default\"&&!Object.prototype.hasOwnProperty.call(e,r)&&Nst(e,t,r)};Object.defineProperty(Ff,\"__esModule\",{value:!0});var Lst=ve(\"url\"),mle=B4(),Mst={options:{method:\"GET\",retry:{limit:2,methods:[\"GET\",\"PUT\",\"HEAD\",\"DELETE\",\"OPTIONS\",\"TRACE\"],statusCodes:[408,413,429,500,502,503,504,521,522,524],errorCodes:[\"ETIMEDOUT\",\"ECONNRESET\",\"EADDRINUSE\",\"ECONNREFUSED\",\"EPIPE\",\"ENOTFOUND\",\"ENETUNREACH\",\"EAI_AGAIN\"],maxRetryAfter:void 0,calculateDelay:({computedValue:t})=>t},timeout:{},headers:{\"user-agent\":\"got (https://github.com/sindresorhus/got)\"},hooks:{init:[],beforeRequest:[],beforeRedirect:[],beforeRetry:[],beforeError:[],afterResponse:[]},cache:void 0,dnsCache:void 0,decompress:!0,throwHttpErrors:!0,followRedirect:!0,isStream:!1,responseType:\"text\",resolveBodyOnly:!1,maxRedirects:10,prefixUrl:\"\",methodRewriting:!0,ignoreInvalidCookies:!1,context:{},http2:!1,allowGetBody:!1,https:void 0,pagination:{transform:t=>t.request.options.responseType===\"json\"?t.body:JSON.parse(t.body),paginate:t=>{if(!Reflect.has(t.headers,\"link\"))return!1;let e=t.headers.link.split(\",\"),r;for(let o of e){let a=o.split(\";\");if(a[1].includes(\"next\")){r=a[0].trimStart().trim(),r=r.slice(1,-1);break}}return r?{url:new Lst.URL(r)}:!1},filter:()=>!0,shouldContinue:()=>!0,countLimit:1/0,backoff:0,requestLimit:1e4,stackAllItems:!0},parseJson:t=>JSON.parse(t),stringifyJson:t=>JSON.stringify(t),cacheOptions:{}},handlers:[mle.defaultHandler],mutableDefaults:!1},v4=mle.default(Mst);Ff.default=v4;lS.exports=v4;lS.exports.default=v4;lS.exports.__esModule=!0;dle(B4(),Ff);dle(C4(),Ff)});var sn={};Vt(sn,{Method:()=>Dle,del:()=>qst,get:()=>S4,getNetworkSettings:()=>vle,post:()=>x4,put:()=>Hst,request:()=>o1});function wle(t){let e=new URL(t),r={host:e.hostname,headers:{}};return e.port&&(r.port=Number(e.port)),e.username&&e.password&&(r.proxyAuth=`${e.username}:${e.password}`),{proxy:r}}async function D4(t){return al(Cle,t,()=>oe.readFilePromise(t).then(e=>(Cle.set(t,e),e)))}function _st({statusCode:t,statusMessage:e},r){let o=Ot(r,t,yt.NUMBER),a=`https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/${t}`;return Tm(r,`${o}${e?` (${e})`:\"\"}`,a)}async function cS(t,{configuration:e,customErrorMessage:r}){try{return await t}catch(o){if(o.name!==\"HTTPError\")throw o;let a=r?.(o,e)??o.response.body?.error;a==null&&(o.message.startsWith(\"Response code\")?a=\"The remote server failed to provide the requested resource\":a=o.message),o.code===\"ETIMEDOUT\"&&o.event===\"socket\"&&(a+=`(can be increased via ${Ot(e,\"httpTimeout\",yt.SETTING)})`);let n=new Jt(35,a,u=>{o.response&&u.reportError(35,`  ${Xu(e,{label:\"Response Code\",value:Hc(yt.NO_HINT,_st(o.response,e))})}`),o.request&&(u.reportError(35,`  ${Xu(e,{label:\"Request Method\",value:Hc(yt.NO_HINT,o.request.options.method)})}`),u.reportError(35,`  ${Xu(e,{label:\"Request URL\",value:Hc(yt.URL,o.request.requestUrl)})}`)),o.request.redirects.length>0&&u.reportError(35,`  ${Xu(e,{label:\"Request Redirects\",value:Hc(yt.NO_HINT,mL(e,o.request.redirects,yt.URL))})}`),o.request.retryCount===o.request.options.retry.limit&&u.reportError(35,`  ${Xu(e,{label:\"Request Retry Count\",value:Hc(yt.NO_HINT,`${Ot(e,o.request.retryCount,yt.NUMBER)} (can be increased via ${Ot(e,\"httpRetry\",yt.SETTING)})`)})}`)});throw n.originalError=o,n}}function vle(t,e){let r=[...e.configuration.get(\"networkSettings\")].sort(([u],[A])=>A.length-u.length),o={enableNetwork:void 0,httpsCaFilePath:void 0,httpProxy:void 0,httpsProxy:void 0,httpsKeyFilePath:void 0,httpsCertFilePath:void 0},a=Object.keys(o),n=typeof t==\"string\"?new URL(t):t;for(let[u,A]of r)if(b4.default.isMatch(n.hostname,u))for(let p of a){let h=A.get(p);h!==null&&typeof o[p]>\"u\"&&(o[p]=h)}for(let u of a)typeof o[u]>\"u\"&&(o[u]=e.configuration.get(u));return o}async function o1(t,e,{configuration:r,headers:o,jsonRequest:a,jsonResponse:n,method:u=\"GET\",wrapNetworkRequest:A}){let p={target:t,body:e,configuration:r,headers:o,jsonRequest:a,jsonResponse:n,method:u},h=async()=>await jst(t,e,p),E=typeof A<\"u\"?await A(h,p):h;return await(await r.reduceHook(v=>v.wrapNetworkRequest,E,p))()}async function S4(t,{configuration:e,jsonResponse:r,customErrorMessage:o,wrapNetworkRequest:a,...n}){let u=()=>cS(o1(t,null,{configuration:e,wrapNetworkRequest:a,...n}),{configuration:e,customErrorMessage:o}).then(p=>p.body),A=await(typeof a<\"u\"?u():al(Ele,t,()=>u().then(p=>(Ele.set(t,p),p))));return r?JSON.parse(A.toString()):A}async function Hst(t,e,{customErrorMessage:r,...o}){return(await cS(o1(t,e,{...o,method:\"PUT\"}),{customErrorMessage:r,configuration:o.configuration})).body}async function x4(t,e,{customErrorMessage:r,...o}){return(await cS(o1(t,e,{...o,method:\"POST\"}),{customErrorMessage:r,configuration:o.configuration})).body}async function qst(t,{customErrorMessage:e,...r}){return(await cS(o1(t,null,{...r,method:\"DELETE\"}),{customErrorMessage:e,configuration:r.configuration})).body}async function jst(t,e,{configuration:r,headers:o,jsonRequest:a,jsonResponse:n,method:u=\"GET\"}){let A=typeof t==\"string\"?new URL(t):t,p=vle(A,{configuration:r});if(p.enableNetwork===!1)throw new Jt(80,`Request to '${A.href}' has been blocked because of your configuration settings`);if(A.protocol===\"http:\"&&!b4.default.isMatch(A.hostname,r.get(\"unsafeHttpWhitelist\")))throw new Jt(81,`Unsafe http requests must be explicitly whitelisted in your configuration (${A.hostname})`);let E={agent:{http:p.httpProxy?P4.default.httpOverHttp(wle(p.httpProxy)):Ost,https:p.httpsProxy?P4.default.httpsOverHttp(wle(p.httpsProxy)):Ust},headers:o,method:u};E.responseType=n?\"json\":\"buffer\",e!==null&&(Buffer.isBuffer(e)||!a&&typeof e==\"string\"?E.body=e:E.json=e);let I=r.get(\"httpTimeout\"),v=r.get(\"httpRetry\"),x=r.get(\"enableStrictSsl\"),C=p.httpsCaFilePath,R=p.httpsCertFilePath,L=p.httpsKeyFilePath,{default:U}=await Promise.resolve().then(()=>Ze(yle())),z=C?await D4(C):void 0,te=R?await D4(R):void 0,ae=L?await D4(L):void 0,le=U.extend({timeout:{socket:I},retry:v,https:{rejectUnauthorized:x,certificateAuthority:z,certificate:te,key:ae},...E});return r.getLimit(\"networkConcurrency\")(()=>le(A))}var Ile,Ble,b4,P4,Ele,Cle,Ost,Ust,Dle,uS=Et(()=>{Pt();Ile=ve(\"https\"),Ble=ve(\"http\"),b4=Ze($o()),P4=Ze(zse());Wl();jl();ql();Ele=new Map,Cle=new Map,Ost=new Ble.Agent({keepAlive:!0}),Ust=new Ile.Agent({keepAlive:!0});Dle=(a=>(a.GET=\"GET\",a.PUT=\"PUT\",a.POST=\"POST\",a.DELETE=\"DELETE\",a))(Dle||{})});var Xi={};Vt(Xi,{availableParallelism:()=>Q4,getArchitecture:()=>a1,getArchitectureName:()=>Vst,getArchitectureSet:()=>k4,getCaller:()=>Zst,major:()=>Gst,openUrl:()=>Yst});function Kst(){if(process.platform===\"darwin\"||process.platform===\"win32\")return null;let t;try{t=oe.readFileSync(Wst)}catch{}if(typeof t<\"u\"){if(t&&(t.includes(\"GLIBC\")||t.includes(\"libc\")))return\"glibc\";if(t&&t.includes(\"musl\"))return\"musl\"}let r=(process.report?.getReport()??{}).sharedObjects??[],o=/\\/(?:(ld-linux-|[^/]+-linux-gnu\\/)|(libc.musl-|ld-musl-))/;return Vp(r,a=>{let n=a.match(o);if(!n)return Vp.skip;if(n[1])return\"glibc\";if(n[2])return\"musl\";throw new Error(\"Assertion failed: Expected the libc variant to have been detected\")})??null}function a1(){return ble=ble??{os:process.platform,cpu:process.arch,libc:Kst()}}function Vst(t=a1()){return t.libc?`${t.os}-${t.cpu}-${t.libc}`:`${t.os}-${t.cpu}`}function k4(){let t=a1();return Sle=Sle??{os:[t.os],cpu:[t.cpu],libc:t.libc?[t.libc]:[]}}function Xst(t){let e=zst.exec(t);if(!e)return null;let r=e[2]&&e[2].indexOf(\"native\")===0,o=e[2]&&e[2].indexOf(\"eval\")===0,a=Jst.exec(e[2]);return o&&a!=null&&(e[2]=a[1],e[3]=a[2],e[4]=a[3]),{file:r?null:e[2],methodName:e[1]||\"<unknown>\",arguments:r?[e[2]]:[],line:e[3]?+e[3]:null,column:e[4]?+e[4]:null}}function Zst(){let e=new Error().stack.split(`\n`)[3];return Xst(e)}function Q4(){return typeof AS.default.availableParallelism<\"u\"?AS.default.availableParallelism():Math.max(1,AS.default.cpus().length)}var AS,Gst,Ple,Yst,Wst,ble,Sle,zst,Jst,fS=Et(()=>{Pt();AS=Ze(ve(\"os\"));pS();ql();Gst=Number(process.versions.node.split(\".\")[0]),Ple=new Map([[\"darwin\",\"open\"],[\"linux\",\"xdg-open\"],[\"win32\",\"explorer.exe\"]]).get(process.platform),Yst=typeof Ple<\"u\"?async t=>{try{return await F4(Ple,[t],{cwd:V.cwd()}),!0}catch{return!1}}:void 0,Wst=\"/usr/bin/ldd\";zst=/^\\s*at (.*?) ?\\(((?:file|https?|blob|chrome-extension|native|eval|webpack|<anonymous>|\\/|[a-z]:\\\\|\\\\\\\\).*?)(?::(\\d+))?(?::(\\d+))?\\)?\\s*$/i,Jst=/\\((\\S*)(?::(\\d+))(?::(\\d+))\\)/});function M4(t,e,r,o,a){let n=VI(r);if(o.isArray||o.type===\"ANY\"&&Array.isArray(n))return Array.isArray(n)?n.map((u,A)=>R4(t,`${e}[${A}]`,u,o,a)):String(n).split(/,/).map(u=>R4(t,e,u,o,a));if(Array.isArray(n))throw new Error(`Non-array configuration settings \"${e}\" cannot be an array`);return R4(t,e,r,o,a)}function R4(t,e,r,o,a){let n=VI(r);switch(o.type){case\"ANY\":return Fb(n);case\"SHAPE\":return rot(t,e,r,o,a);case\"MAP\":return not(t,e,r,o,a)}if(n===null&&!o.isNullable&&o.default!==null)throw new Error(`Non-nullable configuration settings \"${e}\" cannot be set to null`);if(o.values?.includes(n))return n;let A=(()=>{if(o.type===\"BOOLEAN\"&&typeof n!=\"string\")return QI(n);if(typeof n!=\"string\")throw new Error(`Expected configuration setting \"${e}\" to be a string, got ${typeof n}`);let p=YP(n,{env:t.env});switch(o.type){case\"ABSOLUTE_PATH\":{let h=a,E=cO(r);return E&&E[0]!==\"<\"&&(h=V.dirname(E)),V.resolve(h,ue.toPortablePath(p))}case\"LOCATOR_LOOSE\":return bf(p,!1);case\"NUMBER\":return parseInt(p);case\"LOCATOR\":return bf(p);case\"BOOLEAN\":return QI(p);default:return p}})();if(o.values&&!o.values.includes(A))throw new Error(`Invalid value, expected one of ${o.values.join(\", \")}`);return A}function rot(t,e,r,o,a){let n=VI(r);if(typeof n!=\"object\"||Array.isArray(n))throw new st(`Object configuration settings \"${e}\" must be an object`);let u=O4(t,o,{ignoreArrays:!0});if(n===null)return u;for(let[A,p]of Object.entries(n)){let h=`${e}.${A}`;if(!o.properties[A])throw new st(`Unrecognized configuration settings found: ${e}.${A} - run \"yarn config -v\" to see the list of settings supported in Yarn`);u.set(A,M4(t,h,p,o.properties[A],a))}return u}function not(t,e,r,o,a){let n=VI(r),u=new Map;if(typeof n!=\"object\"||Array.isArray(n))throw new st(`Map configuration settings \"${e}\" must be an object`);if(n===null)return u;for(let[A,p]of Object.entries(n)){let h=o.normalizeKeys?o.normalizeKeys(A):A,E=`${e}['${h}']`,I=o.valueDefinition;u.set(h,M4(t,E,p,I,a))}return u}function O4(t,e,{ignoreArrays:r=!1}={}){switch(e.type){case\"SHAPE\":{if(e.isArray&&!r)return[];let o=new Map;for(let[a,n]of Object.entries(e.properties))o.set(a,O4(t,n));return o}case\"MAP\":return e.isArray&&!r?[]:new Map;case\"ABSOLUTE_PATH\":return e.default===null?null:t.projectCwd===null?Array.isArray(e.default)?e.default.map(o=>V.normalize(o)):V.isAbsolute(e.default)?V.normalize(e.default):e.isNullable?null:void 0:Array.isArray(e.default)?e.default.map(o=>V.resolve(t.projectCwd,o)):V.resolve(t.projectCwd,e.default);default:return e.default}}function gS(t,e,r){if(e.type===\"SECRET\"&&typeof t==\"string\"&&r.hideSecrets)return tot;if(e.type===\"ABSOLUTE_PATH\"&&typeof t==\"string\"&&r.getNativePaths)return ue.fromPortablePath(t);if(e.isArray&&Array.isArray(t)){let o=[];for(let a of t)o.push(gS(a,e,r));return o}if(e.type===\"MAP\"&&t instanceof Map){if(t.size===0)return;let o=new Map;for(let[a,n]of t.entries()){let u=gS(n,e.valueDefinition,r);typeof u<\"u\"&&o.set(a,u)}return o}if(e.type===\"SHAPE\"&&t instanceof Map){if(t.size===0)return;let o=new Map;for(let[a,n]of t.entries()){let u=e.properties[a],A=gS(n,u,r);typeof A<\"u\"&&o.set(a,A)}return o}return t}function iot(){let t={};for(let[e,r]of Object.entries(process.env))e=e.toLowerCase(),e.startsWith(dS)&&(e=(0,kle.default)(e.slice(dS.length)),t[e]=r);return t}function N4(){let t=`${dS}rc_filename`;for(let[e,r]of Object.entries(process.env))if(e.toLowerCase()===t&&typeof r==\"string\")return r;return L4}async function xle(t){try{return await oe.readFilePromise(t)}catch{return Buffer.of()}}async function sot(t,e){return Buffer.compare(...await Promise.all([xle(t),xle(e)]))===0}async function oot(t,e){let[r,o]=await Promise.all([oe.statPromise(t),oe.statPromise(e)]);return r.dev===o.dev&&r.ino===o.ino}async function lot({configuration:t,selfPath:e}){let r=t.get(\"yarnPath\");return t.get(\"ignorePath\")||r===null||r===e||await aot(r,e)?null:r}var kle,Rf,Qle,Fle,Rle,T4,$st,l1,eot,ly,dS,L4,tot,c1,Tle,mS,hS,aot,Ke,u1=Et(()=>{Pt();Nl();kle=Ze(sV()),Rf=Ze(X0());qt();Qle=Ze(ZV()),Fle=ve(\"module\"),Rle=Ze(eg()),T4=ve(\"stream\");use();Gm();tO();rO();nO();Ose();iO();mg();jse();Tb();jl();th();uS();ql();fS();Sf();So();$st=function(){if(!Rf.GITHUB_ACTIONS||!process.env.GITHUB_EVENT_PATH)return!1;let t=ue.toPortablePath(process.env.GITHUB_EVENT_PATH),e;try{e=oe.readJsonSync(t)}catch{return!1}return!(!(\"repository\"in e)||!e.repository||(e.repository.private??!0))}(),l1=new Set([\"@yarnpkg/plugin-constraints\",\"@yarnpkg/plugin-exec\",\"@yarnpkg/plugin-interactive-tools\",\"@yarnpkg/plugin-stage\",\"@yarnpkg/plugin-typescript\",\"@yarnpkg/plugin-version\",\"@yarnpkg/plugin-workspace-tools\"]),eot=new Set([\"isTestEnv\",\"injectNpmUser\",\"injectNpmPassword\",\"injectNpm2FaToken\",\"zipDataEpilogue\",\"cacheCheckpointOverride\",\"cacheVersionOverride\",\"lockfileVersionOverride\",\"binFolder\",\"version\",\"flags\",\"profile\",\"gpg\",\"ignoreNode\",\"wrapOutput\",\"home\",\"confDir\",\"registry\",\"ignoreCwd\"]),ly=/^(?!v)[a-z0-9._-]+$/i,dS=\"yarn_\",L4=\".yarnrc.yml\",tot=\"********\",c1=(E=>(E.ANY=\"ANY\",E.BOOLEAN=\"BOOLEAN\",E.ABSOLUTE_PATH=\"ABSOLUTE_PATH\",E.LOCATOR=\"LOCATOR\",E.LOCATOR_LOOSE=\"LOCATOR_LOOSE\",E.NUMBER=\"NUMBER\",E.STRING=\"STRING\",E.SECRET=\"SECRET\",E.SHAPE=\"SHAPE\",E.MAP=\"MAP\",E))(c1||{}),Tle=yt,mS=(r=>(r.JUNCTIONS=\"junctions\",r.SYMLINKS=\"symlinks\",r))(mS||{}),hS={lastUpdateCheck:{description:\"Last timestamp we checked whether new Yarn versions were available\",type:\"STRING\",default:null},yarnPath:{description:\"Path to the local executable that must be used over the global one\",type:\"ABSOLUTE_PATH\",default:null},ignorePath:{description:\"If true, the local executable will be ignored when using the global one\",type:\"BOOLEAN\",default:!1},globalFolder:{description:\"Folder where all system-global files are stored\",type:\"ABSOLUTE_PATH\",default:AO()},cacheFolder:{description:\"Folder where the cache files must be written\",type:\"ABSOLUTE_PATH\",default:\"./.yarn/cache\"},compressionLevel:{description:\"Zip files compression level, from 0 to 9 or mixed (a variant of 9, which stores some files uncompressed, when compression doesn't yield good results)\",type:\"NUMBER\",values:[\"mixed\",0,1,2,3,4,5,6,7,8,9],default:0},virtualFolder:{description:\"Folder where the virtual packages (cf doc) will be mapped on the disk (must be named __virtual__)\",type:\"ABSOLUTE_PATH\",default:\"./.yarn/__virtual__\"},installStatePath:{description:\"Path of the file where the install state will be persisted\",type:\"ABSOLUTE_PATH\",default:\"./.yarn/install-state.gz\"},immutablePatterns:{description:\"Array of glob patterns; files matching them won't be allowed to change during immutable installs\",type:\"STRING\",default:[],isArray:!0},rcFilename:{description:\"Name of the files where the configuration can be found\",type:\"STRING\",default:N4()},enableGlobalCache:{description:\"If true, the system-wide cache folder will be used regardless of `cache-folder`\",type:\"BOOLEAN\",default:!0},cacheMigrationMode:{description:\"Defines the conditions under which Yarn upgrades should cause the cache archives to be regenerated.\",type:\"STRING\",values:[\"always\",\"match-spec\",\"required-only\"],default:\"always\"},enableColors:{description:\"If true, the CLI is allowed to use colors in its output\",type:\"BOOLEAN\",default:VP,defaultText:\"<dynamic>\"},enableHyperlinks:{description:\"If true, the CLI is allowed to use hyperlinks in its output\",type:\"BOOLEAN\",default:dL,defaultText:\"<dynamic>\"},enableInlineBuilds:{description:\"If true, the CLI will print the build output on the command line\",type:\"BOOLEAN\",default:Rf.isCI,defaultText:\"<dynamic>\"},enableMessageNames:{description:\"If true, the CLI will prefix most messages with codes suitable for search engines\",type:\"BOOLEAN\",default:!0},enableProgressBars:{description:\"If true, the CLI is allowed to show a progress bar for long-running events\",type:\"BOOLEAN\",default:!Rf.isCI,defaultText:\"<dynamic>\"},enableTimers:{description:\"If true, the CLI is allowed to print the time spent executing commands\",type:\"BOOLEAN\",default:!0},enableTips:{description:\"If true, installs will print a helpful message every day of the week\",type:\"BOOLEAN\",default:!Rf.isCI,defaultText:\"<dynamic>\"},preferInteractive:{description:\"If true, the CLI will automatically use the interactive mode when called from a TTY\",type:\"BOOLEAN\",default:!1},preferTruncatedLines:{description:\"If true, the CLI will truncate lines that would go beyond the size of the terminal\",type:\"BOOLEAN\",default:!1},progressBarStyle:{description:\"Which style of progress bar should be used (only when progress bars are enabled)\",type:\"STRING\",default:void 0,defaultText:\"<dynamic>\"},defaultLanguageName:{description:\"Default language mode that should be used when a package doesn't offer any insight\",type:\"STRING\",default:\"node\"},defaultProtocol:{description:\"Default resolution protocol used when resolving pure semver and tag ranges\",type:\"STRING\",default:\"npm:\"},enableTransparentWorkspaces:{description:\"If false, Yarn won't automatically resolve workspace dependencies unless they use the `workspace:` protocol\",type:\"BOOLEAN\",default:!0},supportedArchitectures:{description:\"Architectures that Yarn will fetch and inject into the resolver\",type:\"SHAPE\",properties:{os:{description:\"Array of supported process.platform strings, or null to target them all\",type:\"STRING\",isArray:!0,isNullable:!0,default:[\"current\"]},cpu:{description:\"Array of supported process.arch strings, or null to target them all\",type:\"STRING\",isArray:!0,isNullable:!0,default:[\"current\"]},libc:{description:\"Array of supported libc libraries, or null to target them all\",type:\"STRING\",isArray:!0,isNullable:!0,default:[\"current\"]}}},enableMirror:{description:\"If true, the downloaded packages will be retrieved and stored in both the local and global folders\",type:\"BOOLEAN\",default:!0},enableNetwork:{description:\"If false, Yarn will refuse to use the network if required to\",type:\"BOOLEAN\",default:!0},enableOfflineMode:{description:\"If true, Yarn will attempt to retrieve files and metadata from the global cache rather than the network\",type:\"BOOLEAN\",default:!1},httpProxy:{description:\"URL of the http proxy that must be used for outgoing http requests\",type:\"STRING\",default:null},httpsProxy:{description:\"URL of the http proxy that must be used for outgoing https requests\",type:\"STRING\",default:null},unsafeHttpWhitelist:{description:\"List of the hostnames for which http queries are allowed (glob patterns are supported)\",type:\"STRING\",default:[],isArray:!0},httpTimeout:{description:\"Timeout of each http request in milliseconds\",type:\"NUMBER\",default:6e4},httpRetry:{description:\"Retry times on http failure\",type:\"NUMBER\",default:3},networkConcurrency:{description:\"Maximal number of concurrent requests\",type:\"NUMBER\",default:50},taskPoolConcurrency:{description:\"Maximal amount of concurrent heavy task processing\",type:\"NUMBER\",default:Q4()},taskPoolMode:{description:\"Execution strategy for heavy tasks\",type:\"STRING\",values:[\"async\",\"workers\"],default:\"workers\"},networkSettings:{description:\"Network settings per hostname (glob patterns are supported)\",type:\"MAP\",valueDefinition:{description:\"\",type:\"SHAPE\",properties:{httpsCaFilePath:{description:\"Path to file containing one or multiple Certificate Authority signing certificates\",type:\"ABSOLUTE_PATH\",default:null},enableNetwork:{description:\"If false, the package manager will refuse to use the network if required to\",type:\"BOOLEAN\",default:null},httpProxy:{description:\"URL of the http proxy that must be used for outgoing http requests\",type:\"STRING\",default:null},httpsProxy:{description:\"URL of the http proxy that must be used for outgoing https requests\",type:\"STRING\",default:null},httpsKeyFilePath:{description:\"Path to file containing private key in PEM format\",type:\"ABSOLUTE_PATH\",default:null},httpsCertFilePath:{description:\"Path to file containing certificate chain in PEM format\",type:\"ABSOLUTE_PATH\",default:null}}}},httpsCaFilePath:{description:\"A path to a file containing one or multiple Certificate Authority signing certificates\",type:\"ABSOLUTE_PATH\",default:null},httpsKeyFilePath:{description:\"Path to file containing private key in PEM format\",type:\"ABSOLUTE_PATH\",default:null},httpsCertFilePath:{description:\"Path to file containing certificate chain in PEM format\",type:\"ABSOLUTE_PATH\",default:null},enableStrictSsl:{description:\"If false, SSL certificate errors will be ignored\",type:\"BOOLEAN\",default:!0},logFilters:{description:\"Overrides for log levels\",type:\"SHAPE\",isArray:!0,concatenateValues:!0,properties:{code:{description:\"Code of the messages covered by this override\",type:\"STRING\",default:void 0},text:{description:\"Code of the texts covered by this override\",type:\"STRING\",default:void 0},pattern:{description:\"Code of the patterns covered by this override\",type:\"STRING\",default:void 0},level:{description:\"Log level override, set to null to remove override\",type:\"STRING\",values:Object.values(JP),isNullable:!0,default:void 0}}},enableTelemetry:{description:\"If true, telemetry will be periodically sent, following the rules in https://yarnpkg.com/advanced/telemetry\",type:\"BOOLEAN\",default:!0},telemetryInterval:{description:\"Minimal amount of time between two telemetry uploads, in days\",type:\"NUMBER\",default:7},telemetryUserId:{description:\"If you desire to tell us which project you are, you can set this field. Completely optional and opt-in.\",type:\"STRING\",default:null},enableHardenedMode:{description:\"If true, automatically enable --check-resolutions --refresh-lockfile on installs\",type:\"BOOLEAN\",default:Rf.isPR&&$st,defaultText:\"<true on public PRs>\"},enableScripts:{description:\"If true, packages are allowed to have install scripts by default\",type:\"BOOLEAN\",default:!0},enableStrictSettings:{description:\"If true, unknown settings will cause Yarn to abort\",type:\"BOOLEAN\",default:!0},enableImmutableCache:{description:\"If true, the cache is reputed immutable and actions that would modify it will throw\",type:\"BOOLEAN\",default:!1},checksumBehavior:{description:\"Enumeration defining what to do when a checksum doesn't match expectations\",type:\"STRING\",default:\"throw\"},injectEnvironmentFiles:{description:\"List of all the environment files that Yarn should inject inside the process when it starts\",type:\"ABSOLUTE_PATH\",default:[\".env.yarn?\"],isArray:!0},packageExtensions:{description:\"Map of package corrections to apply on the dependency tree\",type:\"MAP\",valueDefinition:{description:\"The extension that will be applied to any package whose version matches the specified range\",type:\"SHAPE\",properties:{dependencies:{description:\"The set of dependencies that must be made available to the current package in order for it to work properly\",type:\"MAP\",valueDefinition:{description:\"A range\",type:\"STRING\"}},peerDependencies:{description:\"Inherited dependencies - the consumer of the package will be tasked to provide them\",type:\"MAP\",valueDefinition:{description:\"A semver range\",type:\"STRING\"}},peerDependenciesMeta:{description:\"Extra information related to the dependencies listed in the peerDependencies field\",type:\"MAP\",valueDefinition:{description:\"The peerDependency meta\",type:\"SHAPE\",properties:{optional:{description:\"If true, the selected peer dependency will be marked as optional by the package manager and the consumer omitting it won't be reported as an error\",type:\"BOOLEAN\",default:!1}}}}}}}};aot=process.platform===\"win32\"?sot:oot;Ke=class t{constructor(e){this.isCI=Rf.isCI;this.projectCwd=null;this.plugins=new Map;this.settings=new Map;this.values=new Map;this.sources=new Map;this.invalid=new Map;this.env={};this.limits=new Map;this.packageExtensions=null;this.startingCwd=e}static{this.deleteProperty=Symbol()}static{this.telemetry=null}static create(e,r,o){let a=new t(e);typeof r<\"u\"&&!(r instanceof Map)&&(a.projectCwd=r),a.importSettings(hS);let n=typeof o<\"u\"?o:r instanceof Map?r:new Map;for(let[u,A]of n)a.activatePlugin(u,A);return a}static async find(e,r,{strict:o=!0,usePathCheck:a=null,useRc:n=!0}={}){let u=iot();delete u.rcFilename;let A=new t(e),p=await t.findRcFiles(e),h=await t.findFolderRcFile(Jm());h&&(p.find(Ce=>Ce.path===h.path)||p.unshift(h));let E=qse(p.map(ce=>[ce.path,ce.data])),I=It.dot,v=new Set(Object.keys(hS)),x=({yarnPath:ce,ignorePath:Ce,injectEnvironmentFiles:de})=>({yarnPath:ce,ignorePath:Ce,injectEnvironmentFiles:de}),C=({yarnPath:ce,ignorePath:Ce,injectEnvironmentFiles:de,...Be})=>{let Ee={};for(let[g,me]of Object.entries(Be))v.has(g)&&(Ee[g]=me);return Ee},R=({yarnPath:ce,ignorePath:Ce,...de})=>{let Be={};for(let[Ee,g]of Object.entries(de))v.has(Ee)||(Be[Ee]=g);return Be};if(A.importSettings(x(hS)),A.useWithSource(\"<environment>\",x(u),e,{strict:!1}),E){let[ce,Ce]=E;A.useWithSource(ce,x(Ce),I,{strict:!1})}if(a){if(await lot({configuration:A,selfPath:a})!==null)return A;A.useWithSource(\"<override>\",{ignorePath:!0},e,{strict:!1,overwrite:!0})}let L=await t.findProjectCwd(e);A.startingCwd=e,A.projectCwd=L;let U=Object.assign(Object.create(null),process.env);A.env=U;let z=await Promise.all(A.get(\"injectEnvironmentFiles\").map(async ce=>{let Ce=ce.endsWith(\"?\")?await oe.readFilePromise(ce.slice(0,-1),\"utf8\").catch(()=>\"\"):await oe.readFilePromise(ce,\"utf8\");return(0,Qle.parse)(Ce)}));for(let ce of z)for(let[Ce,de]of Object.entries(ce))A.env[Ce]=YP(de,{env:U});if(A.importSettings(C(hS)),A.useWithSource(\"<environment>\",C(u),e,{strict:o}),E){let[ce,Ce]=E;A.useWithSource(ce,C(Ce),I,{strict:o})}let te=ce=>\"default\"in ce?ce.default:ce,ae=new Map([[\"@@core\",cse]]);if(r!==null)for(let ce of r.plugins.keys())ae.set(ce,te(r.modules.get(ce)));for(let[ce,Ce]of ae)A.activatePlugin(ce,Ce);let le=new Map([]);if(r!==null){let ce=new Map;for(let Be of Fle.builtinModules)ce.set(Be,()=>vf(Be));for(let[Be,Ee]of r.modules)ce.set(Be,()=>Ee);let Ce=new Set,de=async(Be,Ee)=>{let{factory:g,name:me}=vf(Be);if(!g||Ce.has(me))return;let we=new Map(ce),Ae=Z=>{if(we.has(Z))return we.get(Z)();throw new st(`This plugin cannot access the package referenced via ${Z} which is neither a builtin, nor an exposed entry`)},ne=await xm(async()=>te(await g(Ae)),Z=>`${Z} (when initializing ${me}, defined in ${Ee})`);ce.set(me,()=>ne),Ce.add(me),le.set(me,ne)};if(u.plugins)for(let Be of u.plugins.split(\";\")){let Ee=V.resolve(e,ue.toPortablePath(Be));await de(Ee,\"<environment>\")}for(let{path:Be,cwd:Ee,data:g}of p)if(n&&Array.isArray(g.plugins))for(let me of g.plugins){let we=typeof me!=\"string\"?me.path:me,Ae=me?.spec??\"\",ne=me?.checksum??\"\";if(l1.has(Ae))continue;let Z=V.resolve(Ee,ue.toPortablePath(we));if(!await oe.existsPromise(Z)){if(!Ae){let ht=Ot(A,V.basename(Z,\".cjs\"),yt.NAME),H=Ot(A,\".gitignore\",yt.NAME),rt=Ot(A,A.values.get(\"rcFilename\"),yt.NAME),Te=Ot(A,\"https://yarnpkg.com/getting-started/qa#which-files-should-be-gitignored\",yt.URL);throw new st(`Missing source for the ${ht} plugin - please try to remove the plugin from ${rt} then reinstall it manually. This error usually occurs because ${H} is incorrect, check ${Te} to make sure your plugin folder isn't gitignored.`)}if(!Ae.match(/^https?:/)){let ht=Ot(A,V.basename(Z,\".cjs\"),yt.NAME),H=Ot(A,A.values.get(\"rcFilename\"),yt.NAME);throw new st(`Failed to recognize the source for the ${ht} plugin - please try to delete the plugin from ${H} then reinstall it manually.`)}let xe=await S4(Ae,{configuration:A}),Ne=zi(xe);if(ne&&ne!==Ne){let ht=Ot(A,V.basename(Z,\".cjs\"),yt.NAME),H=Ot(A,A.values.get(\"rcFilename\"),yt.NAME),rt=Ot(A,`yarn plugin import ${Ae}`,yt.CODE);throw new st(`Failed to fetch the ${ht} plugin from its remote location: its checksum seems to have changed. If this is expected, please remove the plugin from ${H} then run ${rt} to reimport it.`)}await oe.mkdirPromise(V.dirname(Z),{recursive:!0}),await oe.writeFilePromise(Z,xe)}await de(Z,Be)}}for(let[ce,Ce]of le)A.activatePlugin(ce,Ce);if(A.useWithSource(\"<environment>\",R(u),e,{strict:o}),E){let[ce,Ce]=E;A.useWithSource(ce,R(Ce),I,{strict:o})}return A.get(\"enableGlobalCache\")&&(A.values.set(\"cacheFolder\",`${A.get(\"globalFolder\")}/cache`),A.sources.set(\"cacheFolder\",\"<internal>\")),A}static async findRcFiles(e){let r=N4(),o=[],a=e,n=null;for(;a!==n;){n=a;let u=V.join(n,r);if(oe.existsSync(u)){let A=await oe.readFilePromise(u,\"utf8\"),p;try{p=Ki(A)}catch{let E=\"\";throw A.match(/^\\s+(?!-)[^:]+\\s+\\S+/m)&&(E=\" (in particular, make sure you list the colons after each key name)\"),new st(`Parse error when loading ${u}; please check it's proper Yaml${E}`)}o.unshift({path:u,cwd:n,data:p})}a=V.dirname(n)}return o}static async findFolderRcFile(e){let r=V.join(e,dr.rc),o;try{o=await oe.readFilePromise(r,\"utf8\")}catch(n){if(n.code===\"ENOENT\")return null;throw n}let a=Ki(o);return{path:r,cwd:e,data:a}}static async findProjectCwd(e){let r=null,o=e,a=null;for(;o!==a;){if(a=o,oe.existsSync(V.join(a,dr.lockfile)))return a;oe.existsSync(V.join(a,dr.manifest))&&(r=a),o=V.dirname(a)}return r}static async updateConfiguration(e,r,o={}){let a=N4(),n=V.join(e,a),u=oe.existsSync(n)?Ki(await oe.readFilePromise(n,\"utf8\")):{},A=!1,p;if(typeof r==\"function\"){try{p=r(u)}catch{p=r({})}if(p===u)return!1}else{p=u;for(let h of Object.keys(r)){let E=u[h],I=r[h],v;if(typeof I==\"function\")try{v=I(E)}catch{v=I(void 0)}else v=I;E!==v&&(v===t.deleteProperty?delete p[h]:p[h]=v,A=!0)}if(!A)return!1}return await oe.changeFilePromise(n,Da(p),{automaticNewlines:!0}),!0}static async addPlugin(e,r){r.length!==0&&await t.updateConfiguration(e,o=>{let a=o.plugins??[];if(a.length===0)return{...o,plugins:r};let n=[],u=[...r];for(let A of a){let p=typeof A!=\"string\"?A.path:A,h=u.find(E=>E.path===p);h?(n.push(h),u=u.filter(E=>E!==h)):n.push(A)}return n.push(...u),{...o,plugins:n}})}static async updateHomeConfiguration(e){let r=Jm();return await t.updateConfiguration(r,e)}activatePlugin(e,r){this.plugins.set(e,r),typeof r.configuration<\"u\"&&this.importSettings(r.configuration)}importSettings(e){for(let[r,o]of Object.entries(e))if(o!=null){if(this.settings.has(r))throw new Error(`Cannot redefine settings \"${r}\"`);this.settings.set(r,o),this.values.set(r,O4(this,o))}}useWithSource(e,r,o,a){try{this.use(e,r,o,a)}catch(n){throw n.message+=` (in ${Ot(this,e,yt.PATH)})`,n}}use(e,r,o,{strict:a=!0,overwrite:n=!1}={}){a=a&&this.get(\"enableStrictSettings\");for(let u of[\"enableStrictSettings\",...Object.keys(r)]){let A=r[u],p=cO(A);if(p&&(e=p),typeof A>\"u\"||u===\"plugins\"||e===\"<environment>\"&&eot.has(u))continue;if(u===\"rcFilename\")throw new st(`The rcFilename settings can only be set via ${`${dS}RC_FILENAME`.toUpperCase()}, not via a rc file`);let h=this.settings.get(u);if(!h){let I=Jm(),v=e[0]!==\"<\"?V.dirname(e):null;if(a&&!(v!==null?I===v:!1))throw new st(`Unrecognized or legacy configuration settings found: ${u} - run \"yarn config -v\" to see the list of settings supported in Yarn`);this.invalid.set(u,e);continue}if(this.sources.has(u)&&!(n||h.type===\"MAP\"||h.isArray&&h.concatenateValues))continue;let E;try{E=M4(this,u,A,h,o)}catch(I){throw I.message+=` in ${Ot(this,e,yt.PATH)}`,I}if(u===\"enableStrictSettings\"&&e!==\"<environment>\"){a=E;continue}if(h.type===\"MAP\"){let I=this.values.get(u);this.values.set(u,new Map(n?[...I,...E]:[...E,...I])),this.sources.set(u,`${this.sources.get(u)}, ${e}`)}else if(h.isArray&&h.concatenateValues){let I=this.values.get(u);this.values.set(u,n?[...I,...E]:[...E,...I]),this.sources.set(u,`${this.sources.get(u)}, ${e}`)}else this.values.set(u,E),this.sources.set(u,e)}}get(e){if(!this.values.has(e))throw new Error(`Invalid configuration key \"${e}\"`);return this.values.get(e)}getSpecial(e,{hideSecrets:r=!1,getNativePaths:o=!1}){let a=this.get(e),n=this.settings.get(e);if(typeof n>\"u\")throw new st(`Couldn't find a configuration settings named \"${e}\"`);return gS(a,n,{hideSecrets:r,getNativePaths:o})}getSubprocessStreams(e,{header:r,prefix:o,report:a}){let n,u,A=oe.createWriteStream(e);if(this.get(\"enableInlineBuilds\")){let p=a.createStreamReporter(`${o} ${Ot(this,\"STDOUT\",\"green\")}`),h=a.createStreamReporter(`${o} ${Ot(this,\"STDERR\",\"red\")}`);n=new T4.PassThrough,n.pipe(p),n.pipe(A),u=new T4.PassThrough,u.pipe(h),u.pipe(A)}else n=A,u=A,typeof r<\"u\"&&n.write(`${r}\n`);return{stdout:n,stderr:u}}makeResolver(){let e=[];for(let r of this.plugins.values())for(let o of r.resolvers||[])e.push(new o);return new yg([new Qb,new ei,...e])}makeFetcher(){let e=[];for(let r of this.plugins.values())for(let o of r.fetchers||[])e.push(new o);return new Wm([new Km,new Vm,...e])}getLinkers(){let e=[];for(let r of this.plugins.values())for(let o of r.linkers||[])e.push(new o);return e}getSupportedArchitectures(){let e=a1(),r=this.get(\"supportedArchitectures\"),o=r.get(\"os\");o!==null&&(o=o.map(u=>u===\"current\"?e.os:u));let a=r.get(\"cpu\");a!==null&&(a=a.map(u=>u===\"current\"?e.cpu:u));let n=r.get(\"libc\");return n!==null&&(n=ol(n,u=>u===\"current\"?e.libc??ol.skip:u)),{os:o,cpu:a,libc:n}}isInteractive({interactive:e,stdout:r}){return r.isTTY?e??this.get(\"preferInteractive\"):!1}async getPackageExtensions(){if(this.packageExtensions!==null)return this.packageExtensions;this.packageExtensions=new Map;let e=this.packageExtensions,r=(o,a,{userProvided:n=!1}={})=>{if(!Qa(o.range))throw new Error(\"Only semver ranges are allowed as keys for the packageExtensions setting\");let u=new Ut;u.load(a,{yamlCompatibilityMode:!0});let A=xI(e,o.identHash),p=[];A.push([o.range,p]);let h={status:\"inactive\",userProvided:n,parentDescriptor:o};for(let E of u.dependencies.values())p.push({...h,type:\"Dependency\",descriptor:E});for(let E of u.peerDependencies.values())p.push({...h,type:\"PeerDependency\",descriptor:E});for(let[E,I]of u.peerDependenciesMeta)for(let[v,x]of Object.entries(I))p.push({...h,type:\"PeerDependencyMeta\",selector:E,key:v,value:x})};await this.triggerHook(o=>o.registerPackageExtensions,this,r);for(let[o,a]of this.get(\"packageExtensions\"))r(rh(o,!0),GP(a),{userProvided:!0});return e}normalizeLocator(e){return Qa(e.reference)?Rs(e,`${this.get(\"defaultProtocol\")}${e.reference}`):ly.test(e.reference)?Rs(e,`${this.get(\"defaultProtocol\")}${e.reference}`):e}normalizeDependency(e){return Qa(e.range)?In(e,`${this.get(\"defaultProtocol\")}${e.range}`):ly.test(e.range)?In(e,`${this.get(\"defaultProtocol\")}${e.range}`):e}normalizeDependencyMap(e){return new Map([...e].map(([r,o])=>[r,this.normalizeDependency(o)]))}normalizePackage(e,{packageExtensions:r}){let o=OI(e),a=r.get(e.identHash);if(typeof a<\"u\"){let u=e.version;if(u!==null){for(let[A,p]of a)if(tA(u,A))for(let h of p)switch(h.status===\"inactive\"&&(h.status=\"redundant\"),h.type){case\"Dependency\":typeof o.dependencies.get(h.descriptor.identHash)>\"u\"&&(h.status=\"active\",o.dependencies.set(h.descriptor.identHash,this.normalizeDependency(h.descriptor)));break;case\"PeerDependency\":typeof o.peerDependencies.get(h.descriptor.identHash)>\"u\"&&(h.status=\"active\",o.peerDependencies.set(h.descriptor.identHash,h.descriptor));break;case\"PeerDependencyMeta\":{let E=o.peerDependenciesMeta.get(h.selector);(typeof E>\"u\"||!Object.hasOwn(E,h.key)||E[h.key]!==h.value)&&(h.status=\"active\",al(o.peerDependenciesMeta,h.selector,()=>({}))[h.key]=h.value)}break;default:cL(h)}}}let n=u=>u.scope?`${u.scope}__${u.name}`:`${u.name}`;for(let u of o.peerDependenciesMeta.keys()){let A=ea(u);o.peerDependencies.has(A.identHash)||o.peerDependencies.set(A.identHash,In(A,\"*\"))}for(let u of o.peerDependencies.values()){if(u.scope===\"types\")continue;let A=n(u),p=eA(\"types\",A),h=rn(p);o.peerDependencies.has(p.identHash)||o.peerDependenciesMeta.has(h)||(o.peerDependencies.set(p.identHash,In(p,\"*\")),o.peerDependenciesMeta.set(h,{optional:!0}))}return o.dependencies=new Map(Fs(o.dependencies,([,u])=>xa(u))),o.peerDependencies=new Map(Fs(o.peerDependencies,([,u])=>xa(u))),o}getLimit(e){return al(this.limits,e,()=>(0,Rle.default)(this.get(e)))}async triggerHook(e,...r){for(let o of this.plugins.values()){let a=o.hooks;if(!a)continue;let n=e(a);n&&await n(...r)}}async triggerMultipleHooks(e,r){for(let o of r)await this.triggerHook(e,...o)}async reduceHook(e,r,...o){let a=r;for(let n of this.plugins.values()){let u=n.hooks;if(!u)continue;let A=e(u);A&&(a=await A(a,...o))}return a}async firstHook(e,...r){for(let o of this.plugins.values()){let a=o.hooks;if(!a)continue;let n=e(a);if(!n)continue;let u=await n(...r);if(typeof u<\"u\")return u}return null}}});var Ur={};Vt(Ur,{EndStrategy:()=>q4,ExecError:()=>yS,PipeError:()=>A1,execvp:()=>F4,pipevp:()=>Wc});function Ig(t){return t!==null&&typeof t.fd==\"number\"}function U4(){}function _4(){for(let t of Bg)t.kill()}async function Wc(t,e,{cwd:r,env:o=process.env,strict:a=!1,stdin:n=null,stdout:u,stderr:A,end:p=2}){let h=[\"pipe\",\"pipe\",\"pipe\"];n===null?h[0]=\"ignore\":Ig(n)&&(h[0]=n),Ig(u)&&(h[1]=u),Ig(A)&&(h[2]=A);let E=(0,H4.default)(t,e,{cwd:ue.fromPortablePath(r),env:{...o,PWD:ue.fromPortablePath(r)},stdio:h});Bg.add(E),Bg.size===1&&(process.on(\"SIGINT\",U4),process.on(\"SIGTERM\",_4)),!Ig(n)&&n!==null&&n.pipe(E.stdin),Ig(u)||E.stdout.pipe(u,{end:!1}),Ig(A)||E.stderr.pipe(A,{end:!1});let I=()=>{for(let v of new Set([u,A]))Ig(v)||v.end()};return new Promise((v,x)=>{E.on(\"error\",C=>{Bg.delete(E),Bg.size===0&&(process.off(\"SIGINT\",U4),process.off(\"SIGTERM\",_4)),(p===2||p===1)&&I(),x(C)}),E.on(\"close\",(C,R)=>{Bg.delete(E),Bg.size===0&&(process.off(\"SIGINT\",U4),process.off(\"SIGTERM\",_4)),(p===2||p===1&&C!==0)&&I(),C===0||!a?v({code:j4(C,R)}):x(new A1({fileName:t,code:C,signal:R}))})})}async function F4(t,e,{cwd:r,env:o=process.env,encoding:a=\"utf8\",strict:n=!1}){let u=[\"ignore\",\"pipe\",\"pipe\"],A=[],p=[],h=ue.fromPortablePath(r);typeof o.PWD<\"u\"&&(o={...o,PWD:h});let E=(0,H4.default)(t,e,{cwd:h,env:o,stdio:u});return E.stdout.on(\"data\",I=>{A.push(I)}),E.stderr.on(\"data\",I=>{p.push(I)}),await new Promise((I,v)=>{E.on(\"error\",x=>{let C=Ke.create(r),R=Ot(C,t,yt.PATH);v(new Jt(1,`Process ${R} failed to spawn`,L=>{L.reportError(1,`  ${Xu(C,{label:\"Thrown Error\",value:Hc(yt.NO_HINT,x.message)})}`)}))}),E.on(\"close\",(x,C)=>{let R=a===\"buffer\"?Buffer.concat(A):Buffer.concat(A).toString(a),L=a===\"buffer\"?Buffer.concat(p):Buffer.concat(p).toString(a);x===0||!n?I({code:j4(x,C),stdout:R,stderr:L}):v(new yS({fileName:t,code:x,signal:C,stdout:R,stderr:L}))})})}function j4(t,e){let r=cot.get(e);return typeof r<\"u\"?128+r:t??1}function uot(t,e,{configuration:r,report:o}){o.reportError(1,`  ${Xu(r,t!==null?{label:\"Exit Code\",value:Hc(yt.NUMBER,t)}:{label:\"Exit Signal\",value:Hc(yt.CODE,e)})}`)}var H4,q4,A1,yS,Bg,cot,pS=Et(()=>{Pt();H4=Ze(KR());u1();Wl();jl();q4=(o=>(o[o.Never=0]=\"Never\",o[o.ErrorCode=1]=\"ErrorCode\",o[o.Always=2]=\"Always\",o))(q4||{}),A1=class extends Jt{constructor({fileName:e,code:r,signal:o}){let a=Ke.create(V.cwd()),n=Ot(a,e,yt.PATH);super(1,`Child ${n} reported an error`,u=>{uot(r,o,{configuration:a,report:u})}),this.code=j4(r,o)}},yS=class extends A1{constructor({fileName:e,code:r,signal:o,stdout:a,stderr:n}){super({fileName:e,code:r,signal:o}),this.stdout=a,this.stderr=n}};Bg=new Set;cot=new Map([[\"SIGINT\",2],[\"SIGQUIT\",3],[\"SIGKILL\",9],[\"SIGTERM\",15]])});function Lle(t){Nle=t}function f1(){return typeof G4>\"u\"&&(G4=Nle()),G4}var G4,Nle,Y4=Et(()=>{Nle=()=>{throw new Error(\"Assertion failed: No libzip instance is available, and no factory was configured\")}});var Mle=_((ES,K4)=>{var Aot=Object.assign({},ve(\"fs\")),W4=function(){var t=typeof document<\"u\"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename<\"u\"&&(t=t||__filename),function(e){e=e||{};var r=typeof e<\"u\"?e:{},o,a;r.ready=new Promise(function(We,tt){o=We,a=tt});var n={},u;for(u in r)r.hasOwnProperty(u)&&(n[u]=r[u]);var A=[],p=\"./this.program\",h=function(We,tt){throw tt},E=!1,I=!0,v=\"\";function x(We){return r.locateFile?r.locateFile(We,v):v+We}var C,R,L,U;I&&(E?v=ve(\"path\").dirname(v)+\"/\":v=__dirname+\"/\",C=function(tt,Bt){var or=ii(tt);return or?Bt?or:or.toString():(L||(L=Aot),U||(U=ve(\"path\")),tt=U.normalize(tt),L.readFileSync(tt,Bt?null:\"utf8\"))},R=function(tt){var Bt=C(tt,!0);return Bt.buffer||(Bt=new Uint8Array(Bt)),me(Bt.buffer),Bt},process.argv.length>1&&(p=process.argv[1].replace(/\\\\/g,\"/\")),A=process.argv.slice(2),h=function(We){process.exit(We)},r.inspect=function(){return\"[Emscripten Module object]\"});var z=r.print||console.log.bind(console),te=r.printErr||console.warn.bind(console);for(u in n)n.hasOwnProperty(u)&&(r[u]=n[u]);n=null,r.arguments&&(A=r.arguments),r.thisProgram&&(p=r.thisProgram),r.quit&&(h=r.quit);var ae=0,le=function(We){ae=We},ce;r.wasmBinary&&(ce=r.wasmBinary);var Ce=r.noExitRuntime||!0;typeof WebAssembly!=\"object\"&&Ri(\"no native wasm support detected\");function de(We,tt,Bt){switch(tt=tt||\"i8\",tt.charAt(tt.length-1)===\"*\"&&(tt=\"i32\"),tt){case\"i1\":return Ye[We>>0];case\"i8\":return Ye[We>>0];case\"i16\":return op((We>>1)*2);case\"i32\":return Us((We>>2)*4);case\"i64\":return Us((We>>2)*4);case\"float\":return Au((We>>2)*4);case\"double\":return sp((We>>3)*8);default:Ri(\"invalid type for getValue: \"+tt)}return null}var Be,Ee=!1,g;function me(We,tt){We||Ri(\"Assertion failed: \"+tt)}function we(We){var tt=r[\"_\"+We];return me(tt,\"Cannot call unknown function \"+We+\", make sure it is exported\"),tt}function Ae(We,tt,Bt,or,ee){var ye={string:function(rs){var bi=0;if(rs!=null&&rs!==0){var qo=(rs.length<<2)+1;bi=Un(qo),ht(rs,bi,qo)}return bi},array:function(rs){var bi=Un(rs.length);return Te(rs,bi),bi}};function Le(rs){return tt===\"string\"?xe(rs):tt===\"boolean\"?!!rs:rs}var ft=we(We),pt=[],Nt=0;if(or)for(var rr=0;rr<or.length;rr++){var $r=ye[Bt[rr]];$r?(Nt===0&&(Nt=Es()),pt[rr]=$r(or[rr])):pt[rr]=or[rr]}var ji=ft.apply(null,pt);return ji=Le(ji),Nt!==0&&qs(Nt),ji}function ne(We,tt,Bt,or){Bt=Bt||[];var ee=Bt.every(function(Le){return Le===\"number\"}),ye=tt!==\"string\";return ye&&ee&&!or?we(We):function(){return Ae(We,tt,Bt,arguments,or)}}var Z=new TextDecoder(\"utf8\");function xe(We,tt){if(!We)return\"\";for(var Bt=We+tt,or=We;!(or>=Bt)&&be[or];)++or;return Z.decode(be.subarray(We,or))}function Ne(We,tt,Bt,or){if(!(or>0))return 0;for(var ee=Bt,ye=Bt+or-1,Le=0;Le<We.length;++Le){var ft=We.charCodeAt(Le);if(ft>=55296&&ft<=57343){var pt=We.charCodeAt(++Le);ft=65536+((ft&1023)<<10)|pt&1023}if(ft<=127){if(Bt>=ye)break;tt[Bt++]=ft}else if(ft<=2047){if(Bt+1>=ye)break;tt[Bt++]=192|ft>>6,tt[Bt++]=128|ft&63}else if(ft<=65535){if(Bt+2>=ye)break;tt[Bt++]=224|ft>>12,tt[Bt++]=128|ft>>6&63,tt[Bt++]=128|ft&63}else{if(Bt+3>=ye)break;tt[Bt++]=240|ft>>18,tt[Bt++]=128|ft>>12&63,tt[Bt++]=128|ft>>6&63,tt[Bt++]=128|ft&63}}return tt[Bt]=0,Bt-ee}function ht(We,tt,Bt){return Ne(We,be,tt,Bt)}function H(We){for(var tt=0,Bt=0;Bt<We.length;++Bt){var or=We.charCodeAt(Bt);or>=55296&&or<=57343&&(or=65536+((or&1023)<<10)|We.charCodeAt(++Bt)&1023),or<=127?++tt:or<=2047?tt+=2:or<=65535?tt+=3:tt+=4}return tt}function rt(We){var tt=H(We)+1,Bt=Ni(tt);return Bt&&Ne(We,Ye,Bt,tt),Bt}function Te(We,tt){Ye.set(We,tt)}function Fe(We,tt){return We%tt>0&&(We+=tt-We%tt),We}var ke,Ye,be,et,Ue,S,w,b,y,F;function J(We){ke=We,r.HEAP_DATA_VIEW=F=new DataView(We),r.HEAP8=Ye=new Int8Array(We),r.HEAP16=et=new Int16Array(We),r.HEAP32=S=new Int32Array(We),r.HEAPU8=be=new Uint8Array(We),r.HEAPU16=Ue=new Uint16Array(We),r.HEAPU32=w=new Uint32Array(We),r.HEAPF32=b=new Float32Array(We),r.HEAPF64=y=new Float64Array(We)}var X=r.INITIAL_MEMORY||16777216,$,ie=[],Se=[],Re=[],at=!1;function dt(){if(r.preRun)for(typeof r.preRun==\"function\"&&(r.preRun=[r.preRun]);r.preRun.length;)bt(r.preRun.shift());oo(ie)}function jt(){at=!0,oo(Se)}function tr(){if(r.postRun)for(typeof r.postRun==\"function\"&&(r.postRun=[r.postRun]);r.postRun.length;)kr(r.postRun.shift());oo(Re)}function bt(We){ie.unshift(We)}function ln(We){Se.unshift(We)}function kr(We){Re.unshift(We)}var mr=0,Sr=null,Kr=null;function Kn(We){mr++,r.monitorRunDependencies&&r.monitorRunDependencies(mr)}function Ms(We){if(mr--,r.monitorRunDependencies&&r.monitorRunDependencies(mr),mr==0&&(Sr!==null&&(clearInterval(Sr),Sr=null),Kr)){var tt=Kr;Kr=null,tt()}}r.preloadedImages={},r.preloadedAudios={};function Ri(We){r.onAbort&&r.onAbort(We),We+=\"\",te(We),Ee=!0,g=1,We=\"abort(\"+We+\"). Build with -s ASSERTIONS=1 for more info.\";var tt=new WebAssembly.RuntimeError(We);throw a(tt),tt}var gs=\"data:application/octet-stream;base64,\";function io(We){return We.startsWith(gs)}var Pi=\"data:application/octet-stream;base64,AGFzbQEAAAAB/wEkYAN/f38Bf2ABfwF/YAJ/fwF/YAF/AGAEf39/fwF/YAN/f38AYAV/f39/fwF/YAJ/fwBgBH9/f38AYAABf2AFf39/fn8BfmAEf35/fwF/YAR/f35/AX5gAn9+AX9gA398fwBgA39/fgF/YAF/AX5gBn9/f39/fwF/YAN/fn8Bf2AEf39/fwF+YAV/f35/fwF/YAR/f35/AX9gA39/fgF+YAJ/fgBgAn9/AX5gBX9/f39/AGADf35/AX5gBX5+f35/AX5gA39/fwF+YAZ/fH9/f38Bf2AAAGAHf35/f39+fwF/YAV/fn9/fwF/YAV/f39/fwF+YAJ+fwF/YAJ/fAACJQYBYQFhAAMBYQFiAAEBYQFjAAABYQFkAAEBYQFlAAIBYQFmAAED5wHlAQMAAwEDAwEHDAgDFgcNEgEDDRcFAQ8DEAUQAwIBAhgECxkEAQMBBQsFAwMDARACBAMAAggLBwEAAwADGgQDGwYGABwBBgMTFBEHBwcVCx4ABAgHBAICAgAfAQICA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siAGotAABBCkcNAAsgASADIAQgASgCJBEAACAESQ0CIAMgBGohAyABKAIUIQUgAiAEawwBCyACCyEAIAUgAyAAEAcaIAEgASgCFCAAajYCFAsLCwvNBQEGfyAAKAIwIgNBhgJrIQYgACgCPCECIAMhAQNAIAAoAkQgAiAAKAJoIgRqayECIAEgBmogBE0EQCAAKAJIIgEgASADaiADEAcaAkAgAyAAKAJsIgFNBEAgACABIANrNgJsDAELIABCADcCbAsgACAAKAJoIANrIgE2AmggACAAKAJYIANrNgJYIAEgACgChC5JBEAgACABNgKELgsgAEH8gAEoAgARAwAgAiADaiECCwJAIAAoAgAiASgCBCIERQ0AIAAoAjwhBSAAIAIgBCACIARJGyICBH8gACgCSCAAKAJoaiAFaiEFIAEgBCACazYCBAJAAkACQAJAIAEoAhwiBCgCFEEBaw4CAQACCyAEQaABaiAFIAEoAgAgAkHcgAEoAgARCAAMAgsgASABKAIwIAUgASgCACACQcSAASgCABEEADYCMAwBCyAFIAEoAgAgAhAHGgsgASABKAIAIAJqNgIAIAEgASgCCCACajYCCCAAKAI8BSAFCyACaiICNgI8AkAgACgChC4iASACakEDSQ0AIAAoAmggAWshAQJAIAAoAnRBgQhPBEAgACAAIAAoAkggAWoiAi0AACACLQABIAAoAnwRAAA2AlQMAQsgAUUNACAAIAFBAWsgACgChAERAgAaCyAAKAKELiAAKAI8IgJBAUZrIgRFDQAgACABIAQgACgCgAERBQAgACAAKAKELiAEazYChC4gACgCPCECCyACQYUCSw0AIAAoAgAoAgRFDQAgACgCMCEBDAELCwJAIAAoAkQiAiAAKAJAIgNNDQAgAAJ/IAAoAjwgACgCaGoiASADSwRAIAAoAkggAWpBACACIAFrIgNBggIgA0GCAkkbIgMQGSABIANqDAELIAFBggJqIgEgA00NASAAKAJIIANqQQAgAiADayICIAEgA2siAyACIANJGyIDEBkgACgCQCADags2AkALC50CAQF/AkAgAAJ/IAAoAqAuIgFBwABGBEAgACgCBCAAKAIQaiAAKQOYLjcAACAAQgA3A5guIAAg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LQABIgNrIQggGiADrYghGiACLQAAIgRBEHFFDQEMBAsLIAdB0f4ANgIEIABB7A42AhggGiEdDAMLIARB/wFxIgJBwABxRQRAIAggDSADLwECQQJ0aiAdp0F/IAJ0QX9zcUECdGoiAy0AASICayEIIB0gAq2IIR0gAy0AACIERQ0HDAELCyAEQSBxBEAgB0G//gA2AgQgASECDAgLIAdB0f4ANgIEIABB0A42AhggASECDAcLIB1BfyAGdEF/c62DIBt8IhunIQUgCCAEQQ9xIgNrIQggGiAErUIPg4ghHSABIBdrIgYgAjMBAiAaQX8gA3RBf3Otg3ynIgRPDQIgBCAGayIGIBlNDQEgBygCjEdFDQEgB0HR/gA2AgQgAEG5DDYCGAsgASECIAshBQwFCwJAIA5FBEAgDCARIAZraiEDDAELIAYgDk0EQCAMIA4gBmtqIQMMAQsgDCARIAYgDmsiBmtqIQMgBSAGTQ0AIAUgBmshBQJAAkAgASADTSABIA8gAWusIhogBq0iGyAaIBtUGyIapyIGaiICIANLcQ0AIAMgBmogAUsgASADT3ENACABIAMgBhAHGiACIQEMAQsgASADIAMgAWsiASABQR91IgFqIAFzIgIQByACaiEBIBogAq0iHn0iHFANACACIANqIQIDQAJAIBwgHiAcIB5UGyIbQiBUBEAgGyEaDAELIBsiGkIgfSIgQgWIQgF8QgODIh9QRQRAA0AgASACKQAANwAAIAEgAikAGDcAGCABIAIpABA3ABAgASACKQAINwAIIBpCIH0hGiACQSBqIQIgAUEgaiEBIB9CAX0iH0IAUg0ACwsgIELgAFQNAANAIAEgAikAADcAACABIAIpABg3ABggASACKQAQNwAQIAEgAikACDcACCABIAIpADg3ADggASACKQAwNwAwIAEgAikAKDcAKCABIAIpACA3ACAgASACKQBYNwBYIAEgAikAUDcAUCABIAIpAEg3AEggASACKQBANwBAIAEgAikAYDcAYCABIAIpAGg3AGggASACKQBwNwBwIAEgAikAeDcAeCACQYABaiECIAFBgAFqIQEgGkKAAX0iGkIfVg0ACwsgGkIQWgRAIAEgAikAADcAACABIAIpAAg3A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AOgAAIAJBAWohAiABQQFqIQELIBxCAFINAAsLIAUgBmshAUEAIARrIQUCQCAEQQdLBEAgBCEDDAELIAEgBE0EQCAEIQMMAQsgAiAEayEFA0ACQCACIAUpAAA3AAAgBEEBdCEDIAEgBGshASACIARqIQIgBEEDSw0AIAMhBCABIANLDQELC0EAIANrIQULIAIgBWohBAJAIAUgDyACa6wiGiABrSIbIBogG1QbIhqnIgFIIAVBf0pxDQAgBUEBSCABIARqIAJLcQ0AIAIgBCABEAcgAWohAgwDCyACIAQgAyADQR91IgFqIAFzIgEQByABaiECIBogAa0iHn0iHFANAiABIARqIQEDQAJAIBwgHiAcIB5UGyIbQiBUBEAgGyEaDAELIBsiGkIgfSIgQgWIQgF8QgODIh9QRQRAA0AgAiABKQAANwAAIAIgASkAGDcAGCACIAEpABA3ABAgAiABKQAINwAIIBpCIH0hGiABQSBqIQEgAkEgaiECIB9CAX0iH0IAUg0ACwsgIELgAFQNAANAIAIgASkAADcAACACIAEpABg3ABggAiABKQAQNwAQIAIgASkACDcACCACIAEpADg3ADggAiABKQAwNwAwIAIgASkAKDcAKCACIAEpACA3ACAgAiABKQBYNwBYIAIgASkAUDcAUCACIAEpAEg3AEggAiABKQBANwBAIAIgASkAYDcAYCACIAEpAGg3AGggAiABKQBwNwBwIAIgASkAeDcAeCABQYABaiEBIAJBgAFqIQIgGkKAAX0iGkIfVg0ACwsgGkIQWgRAIAIgASkAADcAACACIAEpAAg3AAggGkIQfSEaIAJBEGohAiABQRBqIQELIBpCCFoEQCACIAEpAAA3AAAgGkIIfSEaIAJBCGohAiABQQhqIQELIBpCBFoEQCACIAEoAAA2AAAgGkIEfSEaIAJBBGohAiABQQRqIQELIBpCAloEQCACIAEvAAA7AAAgGkICfSEaIAJBAmohAiABQQJqIQELIBwgG30hHCAaUEUEQCACIAEtAAA6AAAgAkEBaiECIAFBAWohAQsgHFBFDQALDAILAkAgASADTSABIA8gAWusIhogBa0iGyAaIBtUGyIapyIEaiICIANLcQ0AIAMgBGogAUsgASADT3ENACABIAMgBBAHGgwCCyABIAMgAyABayIBIAFBH3UiAWogAXMiARAHIAFqIQIgGiABrSIefSIcUA0BIAEgA2ohAQNAAkAgHCAeIBwgHlQbIhtCIFQEQCAbIRoMAQsgGyIaQiB9IiBCBYhCAXxCA4MiH1BFBEADQCACIAEpAAA3AAAgAiABKQAYNwAYIAIgASkAEDcAECACIAEpAAg3AAggGkIgfSEaIAFBIGohASACQSBqIQIgH0IBfSIfQgBSDQALCyAgQuAAVA0AA0AgAiABKQAANwAAIAIgASkAGDcAGCACIAEpABA3ABAgAiABKQAINwAIIAIgASkAODcAOCACIAEpADA3ADAgAiABKQAoNwAoIAIgASkAIDcAICACIAEpAFg3AFggAiABKQBQNwBQIAIgASkASDcASCACIAEpAEA3AEAgAiABKQBgNwBgIAIgASkAaDcAaCACIAEpAHA3AHAgAiABKQB4NwB4IAFBgAFqIQEgAkGAAWohAiAaQoABfSIaQh9WDQALCyAaQhBaBEAgAiABKQAANwAAIAIgASkACDcACCAaQhB9IRogAkEQaiECIAFBEGohAQsgGkIIWgRAIAIgASkAADcAACAaQgh9IRogAkEIaiECIAFBCGohAQsgGkIEWgRAIAIgASgAADYAACAaQgR9IRogAkEEaiECIAFBBGohAQsgGkICWgRAIAIgAS8AADsAACAaQgJ9IRogAkECaiECIAFBAmohAQsgHCAbfSEcIBpQRQRAIAIgAS0AADoAACACQQFqIQIgAUEBaiEBCyAcUEUNAAsMAQsCQAJAIBYEQAJAIAQgBUkEQCAHKAKYRyAESw0BCyABIARrIQMCQEEAIARrIgVBf0ogDyABa6wiGiAbIBogG1QbIhqnIgIgBUpxDQAgBUEBSCACIANqIAFLcQ0AIAEgAyACEAcgAmohAgwFCyABIAMgBCAEQR91IgFqIAFzIgEQByABaiECIBogAa0iHn0iHFANBCABIANqIQEDQAJAIBwgHiAcIB5UGyIbQiBUBEAgGyEaDAELIBsiGkIgfSIgQgWIQgF8QgODIh9QRQRAA0AgAiABKQAANwAAIAIgASkAGDc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0AIAEgAi0AADoABCAJQQRrIQYgA0EFayEFIAJBAWohAgJAIAFBBWoiCkEHcUUNACAFRQ0AIAEgAi0AADoABSAJQQVrIQYgA0EGayEFIAJBAWohAgJAIAFBBmoiCkEHcUUNACAFRQ0AIAEgAi0AADoABiAJQQZrIQYgA0EHayEFIAJBAWohAgJAIAFBB2oiCkEHcUUNACAFRQ0AIAEgAi0AADoAByAJQQdrIQYgA0EIayEDIAFBCGohASACQQFqIQIMBgsgCiEBIAUhAwwFCyAKIQEgBSEDDAQLIAohASAFIQMMAwsgCiEBIAUhAwwCCyAKIQEgBSEDDAELIAohASAFIQMLAkACQCAGQRdNBEAgA0UNASADQQFrIQUgA0EHcSIEBEADQCABIAItAAA6AAAgA0EBayEDIAFBAWohASACQQFqIQIgBEEBayIEDQALCyAFQQdJDQEDQCABIAItAAA6AAAgASACLQABOgABIAEgAi0AAjoAAiABIAItAAM6AAMgASACLQAEOgAEIAEgAi0ABToABSABIAItAAY6AAYgASACLQAHOgAHIAFBCGohASACQQhqIQIgA0EIayIDDQALDAELIAMNAQsgASECDAELIAEgBCADED8hAgsgCyEFDAELIAEgAy0AAjoAACABQQFqIQILIAUgFE8NACACIBNJDQELCyAAIAI2AgwgACAFIAhBA3ZrIgE2AgAgACATIAJrQYMCajYCECAAIBQgAWtBDmo2AgQgByAIQQdxIgA2AogBIAcgHUJ/IACthkJ/hYM+AoQBC+cFAQR/IAMgAiACIANLGyEEIAAgAWshAgJAIABBB3FFDQAgBEUNACAAIAItAAA6AAAgA0EBayEGIAJBAWohAiAAQQFqIgdBB3FBACAEQQFrIgUbRQRAIAchACAFIQQgBiEDDAELIAAgAi0AADoAASADQQJrIQYgBEECayEFIAJBAWohAgJAIABBAmoiB0EHcUUNACAFRQ0AIAAgAi0AADoAAiADQQNrIQYgBEEDayEFIAJBAWohAgJAIABBA2oiB0EHcUUNACAFRQ0AIAAgAi0AADoAAyADQQRrIQYgBEEEayEFIAJBAWohAgJAIABBBGoiB0EHcUUNAC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QQA2AjAgACABQTsgAxBCCw8AIAAgASACQQBBABCCAQusAgECfyABRQRAIABBCGoiAARAIABBADYCBCAAQRI2AgALQQAPCwJAIAJBfUsNACACQf//A3FBCEYNACAAQQhqIgAEQCAAQQA2AgQgAEEQNgIAC0EADwsCQEGwwAAQCSIFBEAgBUEANgIIIAVCADcCACAFQYiBAUGogQEgAxs2AqhAIAUgAjYCFCAFIAM6ABAgBUEAOgAPIAVBADsBDCAFIAMgAkF9SyIGcToADiAFQQggAiAGG0H//wNxIAQgBUGIgQFBqIEBIAMbKAIAEQAAIgI2AqxAIAINASAFEDEgBRAGCyAAQQhqIgAEQCAAQQA2AgQgAEEONgIAC0EADwsgACABQTogBRBCIgAEfyAABSAFKAKsQCAFKAKoQCgCBBEDACAFEDEgBRAGQQALC6ABAQF/IAIgACgCBCIDIAIgA0kbIgIEQCAAIAMgAms2AgQCQAJAAkACQCAAKAIcIgMoAhRBAWsOAgEAAgsgA0GgAWogASAAKAIAIAJB3IABKAIAEQgADAILIAAgACgCMCABIAAoAgAgAkHEgAEoAgARBAA2AjAMAQsgASAAKAIAIAIQBxoLIAAgACgCACACajYCACAAIAAoAgggAmo2AggLC7cCAQR/QX4hAgJAIABFDQAgACgCIEUNACAAKAIkIgRFDQAgACgCHCIBRQ0AIAEoAgAgAEcNAAJAAkAgASgCICIDQTlrDjkBAgICAgICAgICAgIBAgICAQICAgICAgICAgICAgICAgICAQICAgICAgICAgICAQICAgICAgICAgEACyADQZoFRg0AIANBKkcNAQsCfwJ/An8gASgCBCICBEAgBCAAKAIoIAIQHiAAKAIcIQELIAEoAlAiAgsEQCAAKAIkIAAoAiggAhAeIAAoAhwhAQsgASgCTCICCwRAIAAoAiQgACgCKCACEB4gACgCHCEBCyABKAJIIgILBEAgACgCJCAAKAIoIAIQHiAAKAIcIQELIAAoAiQgACgCKCABEB4gAEEANgIcQX1BACADQfEARhshAgsgAgvrCQEIfyAAKAIwIgMgACgCDEEFayICIAIgA0sbIQggACgCACIEKAI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AQsgACgCBCAAKAIQaiAMIAOthiALhDcAACAAIAAoAhBBCGo2AhAgAUFAaiEBIAxBwAAgA2utiCEMCyAAIAw3A5guIAAgATYCoC4L8AQBA38gAEHkAWohAgNAIAIgAUECdCIDakEAOwEAIAIgA0EEcmpBADsBACABQQJqIgFBngJHDQALIABBADsBzBUgAEEAOwHYEyAAQZQWakEAOwEAIABBkBZqQQA7AQAgAEGMFmpBADsBACAAQYgWakEAOwEAIABBhBZqQQA7AQAgAEGAFmpBADsBACAAQfwVakEAOwEAIABB+BVqQQA7AQAgAEH0FWpBADsBACAAQfAVakEAOwEAIABB7BVqQQA7AQAgAEHoFWpBADsBACAAQeQVakEAOwEAIABB4BVqQQA7AQAgAEHcFWpBADsBACAAQdgVakEAOwEAIABB1BVqQQA7AQAgAEHQFWpBADsBACAAQcwUakEAOwEAIABByBRqQQA7AQAgAEHEFGpBADsBACAAQcAUakEAOwEAIABBvBRqQQA7AQAgAEG4FGpBADsBACAAQbQUakEAOwEAIABBsBRqQQA7AQAgAEGsFGpBADsBACAAQagUakEAOwEAIABBpBRqQQA7AQAgAEGgFGpBADsBACAAQZwUakEAOwEAIABBmBRqQQA7AQAgAEGUFGpBADsBACAAQZAUakEAOwEAIABBjBRqQQA7AQAgAEGIFGpBADsBACAAQYQUakEAOwEAIABBgBRqQQA7AQAgAEH8E2pBADsBACAAQfgTakEAOwEAIABB9BNqQQA7AQAgAEHwE2pBADsBACAAQewTakEAOwEAIABB6BNqQQA7AQAgAEHkE2pBADsBACAAQeATakEAOwEAIABB3BNqQQA7AQAgAEIANwL8LSAAQeQJakEBOwEAIABBADYC+C0gAEEANgLwLQuKAwIGfwR+QcgAEAkiBEUEQEEADwsgBEIANwMAIARCADcDMCAEQQA2AiggBEIANwMgIARCADcDGCAEQgA3AxAgBEIANwMIIARCADcDOCABUARAIARBCBAJIgA2AgQgAEUEQCAEEAYgAwRAIANBADYCBCADQQ42AgALQQAPCyAAQgA3AwAgBA8LAkAgAaciBUEEdBAJ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AyADKAJoQQFqIgQ2AmgMAQsgAyADKALwLSIBQQFqNgLwLSABIAMoAuwtakEBOgAAIAMgAygC8C0iAUEBajYC8C0gASADKALsLWpBADoAACADIAMoAvAtIgFBAWo2AvAtIAEgAygC7C1qIARBA2s6AAAgAyADKAKALkEBajYCgC4gBEH9zgBqLQAAQQJ0IANqQegJaiIBIAEvAQBBAWo7AQAgA0GAywAtAABBAnRqQdgTaiIBIAEvAQBBAWo7AQAgAyADKAI8IARrNgI8IAMgAygCaCAEaiIENgJoCyADKALwLSADKAL0LUcNAUEAIQggAyADKAJYIgFBAE4EfyADKAJIIAFqBUEACyAEIAFrQQAQDyADIAMoAmg2AlggAygCABAKIAMoAgAoAhANAQwCCwsgA0EANgKELiAKQQRGBEAgAyADKAJYIgFBAE4EfyADKAJIIAFqBUEACyADKAJoIAFrQQEQDyADIAMoAmg2AlggAygCABAKQQNBAiADKAIAKAIQGwwCCyADKALwLQRAQQAhCCADIAMoAlgiAUEATgR/IAMoAkggAWoFQQALIAMoAmggAWtBABAPIAMgAygCaDYCWCADKAIAEAogAygCACgCEEUNAQtBASEICyAICwwBCyADIAogAUEMbEG42ABqKAIAEQIACyIBQX5xQQJGBEAgA0GaBTYCIAsgAUF9cUUEQEEAIQQgBSgCEA0CDAQLIAFBAUcNAAJAAkACQCAKQQFrDgUAAQEBAgELIAMpA5guISICfwJ+IAMoAqAuIgFBA2oiCUE/TQRAQgIgAa2GICKEDAELIAFBwABGBEAgAygCBCADKAIQaiAiNwAAIAMgAygCEEEIajYCEEICISJBCgwCCyADKAIEIAMoAhBqQgIgAa2GICKENwAAIAMgAygCEEEIajYCECABQT1rIQlCAkHAACABa62ICyEiIAlBB2ogCUE5SQ0AGiADKAIEIAMoAhBqICI3AAAgAyADKAIQQQhqNgIQQgAhIiAJQTlrCyEBIAMgIjcDmC4gAyABNgKgLiADEDAMAQsgA0EAQQBBABA5IApBA0cNACADKAJQQQBBgIAIEBkgAygCPA0AIANBADYChC4gA0EANgJYIANB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AIoAiRFBEAgAkEoNgIkC0EGIAEgAUF/RhsiBUEASA0AIAVBCUoNAEF8IQMgBCACKAIoQQFB0C4QKCIBRQ0AIAIgATYCHCABIAI2AgAgAUEPNgI0IAFCgICAgKAFNwIcIAFBADYCFCABQYCAAjYCMCABQf//ATYCOCABIAIoAiAgAigCKEGAgAJBAhAoNgJIIAEgAigCICACKAIoIAEoAjBBAhAoIgM2AkwgA0EAIAEoAjBBAXQQGSACKAIgIAIoAihBgIAEQQIQKCEDIAFBgIACNgLoLSABQQA2AkAgASADNgJQIAEgAigCICACKAIoQYCAAkEEECgiAzYCBCABIAEoAugtIgRBAnQ2AgwCQAJAIAEoAkhFDQAgASgCTEUNACABKAJQRQ0AIAMNAQsgAUGaBTYCICACQejAACgCADYCGCACEIQBGkF8DAILIAFBADYCjAEgASAFNgKIASABQgA3AyggASADIARqNgLsLSABIARBA2xBA2s2AvQtQX4hAwJAIAJFDQAgAigCIEUNACACKAIkRQ0AIAIoAhwiAUUNACABKAIAIAJHDQACQAJAIAEoAiAiBEE5aw45AQICAgICAgICAgICAQICAgECAgICAgICAgICAgICAgICAgECAgICAgICAgICAgECAgICAgICAgIBAAsgBEGaBUYNACAEQSpHDQELIAJBAjYCLCACQQA2AgggAkIANwIUIAFBADYCECABIAEoAgQ2AgggASgCFCIDQX9MBEAgAUEAIANrIgM2AhQLIAFBOUEqIANBAkYbNgIgIAIgA0ECRgR/IAFBoAFqQeSAASgCABEBAAVBAQs2AjAgAUF+NgIkIAFBADYCoC4gAUIANwOYLiABQYgXakGg0wA2AgAgASABQcwVajYCgBcgAUH8FmpBjNMANgIAIAEgAUHYE2o2AvQWIAFB8BZqQfjSADYCACABIAFB5AFqNgLoFiABEIgBQQAhAwsgAw0AIAIoAhwiAiACKAIwQQF0NgJEQQAhAyACKAJQQQBBgIAIEBkgAiACKAKIASIEQQxsIgFBtNgAai8BADYClAEgAiABQbDYAGovAQA2ApABIAIgAUGy2ABqLwEANgJ4IAIgAUG22ABqLwEAN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WRlZABObyBtZWRpdW0gZm91bmQAV3JvbmcgbWVkaXVtIHR5cGUATm8gZXJyb3IgaW5mb3JtYXRpb24AQcCAAQuFARMAAAAUAAAAFQAAABYAAAAXAAAAGAAAABkAAAAaAAAAGwAAABwAAAAdAAAAHgAAAB8AAAAgAAAAIQAAACIAAAAjAAAAgERQADEAAAAyAAAAMwAAADQAAAA1AAAANgAAADcAAAA4AAAAOQAAADIAAAAzAAAANAAAADUAAAA2AAAANwAAADgAQfSCAQsCXEQAQbCDAQsQ/////////////////////w==\";io(Pi)||(Pi=x(Pi));function Os(We){try{if(We==Pi&&ce)return new Uint8Array(ce);var tt=ii(We);if(tt)return tt;if(R)return R(We);throw\"sync fetching of the wasm failed: you can preload it to Module['wasmBinary'] manually, or emcc.py will do that for you when generating HTML (but not JS)\"}catch(Bt){Ri(Bt)}}function so(We,tt){var Bt,or,ee;try{ee=Os(We),or=new WebAssembly.Module(ee),Bt=new WebAssembly.Instance(or,tt)}catch(Le){var ye=Le.toString();throw te(\"failed to compile wasm module: \"+ye),(ye.includes(\"imported Memory\")||ye.includes(\"memory import\"))&&te(\"Memory size incompatibility issues may be due to changing INITIAL_MEMORY at runtime to something too large. Use ALLOW_MEMORY_GROWTH to allow any size memory (and also make sure not to set INITIAL_MEMORY at runtime to something smaller than it was at compile time).\"),Le}return[Bt,or]}function uc(){var We={a:Ha};function tt(ee,ye){var Le=ee.exports;r.asm=Le,Be=r.asm.g,J(Be.buffer),$=r.asm.W,ln(r.asm.h),Ms(\"wasm-instantiate\")}if(Kn(\"wasm-instantiate\"),r.instantiateWasm)try{var Bt=r.instantiateWasm(We,tt);return Bt}catch(ee){return te(\"Module.instantiateWasm callback failed with error: \"+ee),!1}var or=so(Pi,We);return tt(or[0]),r.asm}function Au(We){return F.getFloat32(We,!0)}function sp(We){return F.getFloat64(We,!0)}function op(We){return F.getInt16(We,!0)}function Us(We){return F.getInt32(We,!0)}function Dn(We,tt){F.setInt32(We,tt,!0)}function oo(We){for(;We.length>0;){var tt=We.shift();if(typeof tt==\"function\"){tt(r);continue}var Bt=tt.func;typeof Bt==\"number\"?tt.arg===void 0?$.get(Bt)():$.get(Bt)(tt.arg):Bt(tt.arg===void 0?null:tt.arg)}}function _s(We,tt){var Bt=new Date(Us((We>>2)*4)*1e3);Dn((tt>>2)*4,Bt.getUTCSeconds()),Dn((tt+4>>2)*4,Bt.getUTCMinutes()),Dn((tt+8>>2)*4,Bt.getUTCHours()),Dn((tt+12>>2)*4,Bt.getUTCDate()),Dn((tt+16>>2)*4,Bt.getUTCMonth()),Dn((tt+20>>2)*4,Bt.getUTCFullYear()-1900),Dn((tt+24>>2)*4,Bt.getUTCDay()),Dn((tt+36>>2)*4,0),Dn((tt+32>>2)*4,0);var or=Date.UTC(Bt.getUTCFullYear(),0,1,0,0,0,0),ee=(Bt.getTime()-or)/(1e3*60*60*24)|0;return Dn((tt+28>>2)*4,ee),_s.GMTString||(_s.GMTString=rt(\"GMT\")),Dn((tt+40>>2)*4,_s.GMTString),tt}function ml(We,tt){return _s(We,tt)}function yl(We,tt,Bt){be.copyWithin(We,tt,tt+Bt)}function ao(We){try{return Be.grow(We-ke.byteLength+65535>>>16),J(Be.buffer),1}catch{}}function Vn(We){var tt=be.length;We=We>>>0;var Bt=2147483648;if(We>Bt)return!1;for(var or=1;or<=4;or*=2){var ee=tt*(1+.2/or);ee=Math.min(ee,We+100663296);var ye=Math.min(Bt,Fe(Math.max(We,ee),65536)),Le=ao(ye);if(Le)return!0}return!1}function Mn(We){le(We)}function Ti(We){var tt=Date.now()/1e3|0;return We&&Dn((We>>2)*4,tt),tt}function On(){if(On.called)return;On.called=!0;var We=new Date().getFullYear(),tt=new Date(We,0,1),Bt=new Date(We,6,1),or=tt.getTimezoneOffset(),ee=Bt.getTimezoneOffset(),ye=Math.max(or,ee);Dn((ys()>>2)*4,ye*60),Dn((ms()>>2)*4,+(or!=ee));function Le($r){var ji=$r.toTimeString().match(/\\(([A-Za-z ]+)\\)$/);return ji?ji[1]:\"GMT\"}var ft=Le(tt),pt=Le(Bt),Nt=rt(ft),rr=rt(pt);ee<or?(Dn((Ci()>>2)*4,Nt),Dn((Ci()+4>>2)*4,rr)):(Dn((Ci()>>2)*4,rr),Dn((Ci()+4>>2)*4,Nt))}function _i(We){On();var tt=Date.UTC(Us((We+20>>2)*4)+1900,Us((We+16>>2)*4),Us((We+12>>2)*4),Us((We+8>>2)*4),Us((We+4>>2)*4),Us((We>>2)*4),0),Bt=new Date(tt);Dn((We+24>>2)*4,Bt.getUTCDay());var or=Date.UTC(Bt.getUTCFullYear(),0,1,0,0,0,0),ee=(Bt.getTime()-or)/(1e3*60*60*24)|0;return Dn((We+28>>2)*4,ee),Bt.getTime()/1e3|0}var ir=typeof atob==\"function\"?atob:function(We){var tt=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\",Bt=\"\",or,ee,ye,Le,ft,pt,Nt,rr=0;We=We.replace(/[^A-Za-z0-9\\+\\/\\=]/g,\"\");do Le=tt.indexOf(We.charAt(rr++)),ft=tt.indexOf(We.charAt(rr++)),pt=tt.indexOf(We.charAt(rr++)),Nt=tt.indexOf(We.charAt(rr++)),or=Le<<2|ft>>4,ee=(ft&15)<<4|pt>>2,ye=(pt&3)<<6|Nt,Bt=Bt+String.fromCharCode(or),pt!==64&&(Bt=Bt+String.fromCharCode(ee)),Nt!==64&&(Bt=Bt+String.fromCharCode(ye));while(rr<We.length);return Bt};function Me(We){if(typeof I==\"boolean\"&&I){var tt;try{tt=Buffer.from(We,\"base64\")}catch{tt=new Buffer(We,\"base64\")}return new Uint8Array(tt.buffer,tt.byteOffset,tt.byteLength)}try{for(var Bt=ir(We),or=new Uint8Array(Bt.length),ee=0;ee<Bt.length;++ee)or[ee]=Bt.charCodeAt(ee);return or}catch{throw new Error(\"Converting base64 string to bytes failed.\")}}function ii(We){if(io(We))return Me(We.slice(gs.length))}var Ha={e:ml,c:yl,d:Vn,a:Mn,b:Ti,f:_i},hr=uc(),Ac=r.___wasm_call_ctors=hr.h,fu=r._zip_ext_count_symlinks=hr.i,fc=r._zip_file_get_external_attributes=hr.j,El=r._zipstruct_statS=hr.k,vA=r._zipstruct_stat_size=hr.l,pu=r._zipstruct_stat_mtime=hr.m,Ie=r._zipstruct_stat_crc=hr.n,Tt=r._zipstruct_errorS=hr.o,pc=r._zipstruct_error_code_zip=hr.p,Hi=r._zipstruct_stat_comp_size=hr.q,hu=r._zipstruct_stat_comp_method=hr.r,Yt=r._zip_close=hr.s,Cl=r._zip_delete=hr.t,DA=r._zip_dir_add=hr.u,ap=r._zip_discard=hr.v,hc=r._zip_error_init_with_code=hr.w,PA=r._zip_get_error=hr.x,Qn=r._zip_file_get_error=hr.y,hi=r._zip_error_strerror=hr.z,gc=r._zip_fclose=hr.A,bA=r._zip_file_add=hr.B,aa=r._free=hr.C,Ni=r._malloc=hr.D,_o=r._zip_source_error=hr.E,Xe=r._zip_source_seek=hr.F,lo=r._zip_file_set_external_attributes=hr.G,dc=r._zip_file_set_mtime=hr.H,gu=r._zip_fopen_index=hr.I,qi=r._zip_fread=hr.J,du=r._zip_get_name=hr.K,SA=r._zip_get_num_entries=hr.L,qa=r._zip_source_read=hr.M,mc=r._zip_name_locate=hr.N,ds=r._zip_open_from_source=hr.O,Ht=r._zip_set_file_compression=hr.P,Fn=r._zip_source_buffer=hr.Q,Ei=r._zip_source_buffer_create=hr.R,la=r._zip_source_close=hr.S,co=r._zip_source_free=hr.T,Hs=r._zip_source_keep=hr.U,ca=r._zip_source_open=hr.V,ua=r._zip_source_tell=hr.X,Ho=r._zip_stat_index=hr.Y,Ci=r.__get_tzname=hr.Z,ms=r.__get_daylight=hr._,ys=r.__get_timezone=hr.$,Es=r.stackSave=hr.aa,qs=r.stackRestore=hr.ba,Un=r.stackAlloc=hr.ca;r.cwrap=ne,r.getValue=de;var Pn;Kr=function We(){Pn||Cs(),Pn||(Kr=We)};function Cs(We){if(We=We||A,mr>0||(dt(),mr>0))return;function tt(){Pn||(Pn=!0,r.calledRun=!0,!Ee&&(jt(),o(r),r.onRuntimeInitialized&&r.onRuntimeInitialized(),tr()))}r.setStatus?(r.setStatus(\"Running...\"),setTimeout(function(){setTimeout(function(){r.setStatus(\"\")},1),tt()},1)):tt()}if(r.run=Cs,r.preInit)for(typeof r.preInit==\"function\"&&(r.preInit=[r.preInit]);r.preInit.length>0;)r.preInit.pop()();return Cs(),e}}();typeof ES==\"object\"&&typeof K4==\"object\"?K4.exports=W4:typeof define==\"function\"&&define.amd?define([],function(){return W4}):typeof ES==\"object\"&&(ES.createModule=W4)});var Tf,Ole,Ule,_le=Et(()=>{Tf=[\"number\",\"number\"],Ole=(Z=>(Z[Z.ZIP_ER_OK=0]=\"ZIP_ER_OK\",Z[Z.ZIP_ER_MULTIDISK=1]=\"ZIP_ER_MULTIDISK\",Z[Z.ZIP_ER_RENAME=2]=\"ZIP_ER_RENAME\",Z[Z.ZIP_ER_CLOSE=3]=\"ZIP_ER_CLOSE\",Z[Z.ZIP_ER_SEEK=4]=\"ZIP_ER_SEEK\",Z[Z.ZIP_ER_READ=5]=\"ZIP_ER_READ\",Z[Z.ZIP_ER_WRITE=6]=\"ZIP_ER_WRITE\",Z[Z.ZIP_ER_CRC=7]=\"ZIP_ER_CRC\",Z[Z.ZIP_ER_ZIPCLOSED=8]=\"ZIP_ER_ZIPCLOSED\",Z[Z.ZIP_ER_NOENT=9]=\"ZIP_ER_NOENT\",Z[Z.ZIP_ER_EXISTS=10]=\"ZIP_ER_EXISTS\",Z[Z.ZIP_ER_OPEN=11]=\"ZIP_ER_OPEN\",Z[Z.ZIP_ER_TMPOPEN=12]=\"ZIP_ER_TMPOPEN\",Z[Z.ZIP_ER_ZLIB=13]=\"ZIP_ER_ZLIB\",Z[Z.ZIP_ER_MEMORY=14]=\"ZIP_ER_MEMORY\",Z[Z.ZIP_ER_CHANGED=15]=\"ZIP_ER_CHANGED\",Z[Z.ZIP_ER_COMPNOTSUPP=16]=\"ZIP_ER_COM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S:11,ZIP_OPSYS_VSE:12,ZIP_OPSYS_ACORN_RISC:13,ZIP_OPSYS_VFAT:14,ZIP_OPSYS_ALTERNATE_MVS:15,ZIP_OPSYS_BEOS:16,ZIP_OPSYS_TANDEM:17,ZIP_OPSYS_OS_400:18,ZIP_OPSYS_OS_X:19,ZIP_CM_DEFAULT:-1,ZIP_CM_STORE:0,ZIP_CM_DEFLATE:8,uint08S:t._malloc(1),uint32S:t._malloc(4),malloc:t._malloc,free:t._free,getValue:t.getValue,openFromSource:t.cwrap(\"zip_open_from_source\",\"number\",[\"number\",\"number\",\"number\"]),close:t.cwrap(\"zip_close\",\"number\",[\"number\"]),discard:t.cwrap(\"zip_discard\",null,[\"number\"]),getError:t.cwrap(\"zip_get_error\",\"number\",[\"number\"]),getName:t.cwrap(\"zip_get_name\",\"string\",[\"number\",\"number\",\"number\"]),getNumEntries:t.cwrap(\"zip_get_num_entries\",\"number\",[\"number\",\"number\"]),delete:t.cwrap(\"zip_delete\",\"number\",[\"number\",\"number\"]),statIndex:t.cwrap(\"zip_stat_index\",\"number\",[\"number\",...Tf,\"number\",\"number\"]),fopenIndex:t.cwrap(\"zip_fopen_index\",\"number\",[\"number\",...Tf,\"number\"]),fread:t.cwrap(\"zip_fread\",\"number\",[\"number\",\"number\",\"number\",\"number\"]),fclose:t.cwrap(\"zip_fclose\",\"number\",[\"number\"]),dir:{add:t.cwrap(\"zip_dir_add\",\"number\",[\"number\",\"string\"])},file:{add:t.cwrap(\"zip_file_add\",\"number\",[\"number\",\"string\",\"number\",\"number\"]),getError:t.cwrap(\"zip_file_get_error\",\"number\",[\"number\"]),getExternalAttributes:t.cwrap(\"zip_file_get_external_attributes\",\"number\",[\"number\",...Tf,\"number\",\"number\",\"number\"]),setExternalAttributes:t.cwrap(\"zip_file_set_external_attributes\",\"number\",[\"number\",...Tf,\"number\",\"number\",\"number\"]),setMtime:t.cwrap(\"zip_file_set_mtime\",\"number\",[\"number\",...Tf,\"number\",\"number\"]),setCompression:t.cwrap(\"zip_set_file_compression\",\"number\",[\"number\",...Tf,\"number\",\"number\"])},ext:{countSymlinks:t.cwrap(\"zip_ext_count_symlinks\",\"number\",[\"number\"])},error:{initWithCode:t.cwrap(\"zip_error_init_with_code\",null,[\"number\",\"number\"]),strerror:t.cwrap(\"zip_error_strerror\",\"string\",[\"number\"])},name:{locate:t.cwrap(\"zip_name_locate\",\"number\",[\"number\",\"string\",\"number\"])},source:{fromUnattachedBuffer:t.cwrap(\"zip_source_buffer_create\",\"number\",[\"number\",...Tf,\"number\",\"number\"]),fromBuffer:t.cwrap(\"zip_source_buffer\",\"number\",[\"number\",\"number\",...Tf,\"number\"]),free:t.cwrap(\"zip_source_free\",null,[\"number\"]),keep:t.cwrap(\"zip_source_keep\",null,[\"number\"]),open:t.cwrap(\"zip_source_open\",\"number\",[\"number\"]),close:t.cwrap(\"zip_source_close\",\"number\",[\"number\"]),seek:t.cwrap(\"zip_source_seek\",\"number\",[\"number\",...Tf,\"number\"]),tell:t.cwrap(\"zip_source_tell\",\"number\",[\"number\"]),read:t.cwrap(\"zip_source_read\",\"number\",[\"number\",\"number\",\"number\"]),error:t.cwrap(\"zip_source_error\",\"number\",[\"number\"])},struct:{statS:t.cwrap(\"zipstruct_statS\",\"number\",[]),statSize:t.cwrap(\"zipstruct_stat_size\",\"number\",[\"number\"]),statCompSize:t.cwrap(\"zipstruct_stat_comp_size\",\"number\",[\"number\"]),statCompMethod:t.cwrap(\"zipstruct_stat_comp_method\",\"number\",[\"number\"]),statMtime:t.cwrap(\"zipstruct_stat_mtime\",\"number\",[\"number\"]),statCrc:t.cwrap(\"zipstruct_stat_crc\",\"number\",[\"number\"]),errorS:t.cwrap(\"zipstruct_errorS\",\"number\",[]),errorCodeZip:t.cwrap(\"zipstruct_error_code_zip\",\"number\",[\"number\"])}})});function V4(t,e){let r=t.indexOf(e);if(r<=0)return null;let o=r;for(;r>=0&&(o=r+e.length,t[o]!==V.sep);){if(t[r-1]===V.sep)return null;r=t.indexOf(e,o)}return t.length>o&&t[o]!==V.sep?null:t.slice(0,o)}var rA,Hle=Et(()=>{Pt();Pt();nA();rA=class t extends Op{static async openPromise(e,r){let o=new t(r);try{return await e(o)}finally{o.saveAndClose()}}constructor(e={}){let r=e.fileExtensions,o=e.readOnlyArchives,a=typeof r>\"u\"?A=>V4(A,\".zip\"):A=>{for(let p of r){let h=V4(A,p);if(h)return h}return null},n=(A,p)=>new Zi(p,{baseFs:A,readOnly:o,stats:A.statSync(p)}),u=async(A,p)=>{let h={baseFs:A,readOnly:o,stats:await A.statPromise(p)};return()=>new Zi(p,h)};super({...e,factorySync:n,factoryPromise:u,getMountPoint:a})}}});function fot(t){if(typeof t==\"string\"&&String(+t)===t)return+t;if(typeof t==\"number\"&&Number.isFinite(t))return t<0?Date.now()/1e3:t;if(qle.types.isDate(t))return t.getTime()/1e3;throw new Error(\"Invalid time\")}function CS(){return Buffer.from([80,75,5,6,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0])}var na,z4,qle,J4,jle,wS,Zi,X4=Et(()=>{Pt();Pt();Pt();Pt();Pt();Pt();na=ve(\"fs\"),z4=ve(\"stream\"),qle=ve(\"util\"),J4=Ze(ve(\"zlib\"));Y4();jle=\"mixed\";wS=class extends Error{constructor(e,r){super(e),this.name=\"Libzip Error\",this.code=r}},Zi=class extends _u{constructor(r,o={}){super();this.listings=new Map;this.entries=new Map;this.fileSources=new Map;this.fds=new Map;this.nextFd=0;this.ready=!1;this.readOnly=!1;let a=o;if(this.level=typeof a.level<\"u\"?a.level:jle,r??=CS(),typeof r==\"string\"){let{baseFs:A=new Tn}=a;this.baseFs=A,this.path=r}else this.path=null,this.baseFs=null;if(o.stats)this.stats=o.stats;else if(typeof r==\"string\")try{this.stats=this.baseFs.statSync(r)}catch(A){if(A.code===\"ENOENT\"&&a.create)this.stats=wa.makeDefaultStats();else throw A}else this.stats=wa.makeDefaultStats();this.libzip=f1();let n=this.libzip.malloc(4);try{let A=0;o.readOnly&&(A|=this.libzip.ZIP_RDONLY,this.readOnly=!0),typeof r==\"string\"&&(r=a.create?CS():this.baseFs.readFileSync(r));let p=this.allocateUnattachedSource(r);try{this.zip=this.libzip.openFromSource(p,A,n),this.lzSource=p}catch(h){throw this.libzip.source.free(p),h}if(this.zip===0){let h=this.libzip.struct.errorS();throw this.libzip.error.initWithCode(h,this.libzip.getValue(n,\"i32\")),this.makeLibzipError(h)}}finally{this.libzip.free(n)}this.listings.set(It.root,new Set);let u=this.libzip.getNumEntries(this.zip,0);for(let A=0;A<u;++A){let p=this.libzip.getName(this.zip,A,0);if(V.isAbsolute(p))continue;let h=V.resolve(It.root,p);this.registerEntry(h,A),p.endsWith(\"/\")&&this.registerListing(h)}if(this.symlinkCount=this.libzip.ext.countSymlinks(this.zip),this.symlinkCount===-1)throw this.makeLibzipError(this.libzip.getError(this.zip));this.ready=!0}makeLibzipError(r){let o=this.libzip.struct.errorCodeZip(r),a=this.libzip.error.strerror(r),n=new wS(a,this.libzip.errors[o]);if(o===this.libzip.errors.ZIP_ER_CHANGED)throw new Error(`Assertion failed: Unexpected libzip error: ${n.message}`);return n}getExtractHint(r){for(let o of this.entries.keys()){let a=this.pathUtils.extname(o);if(r.relevantExtensions.has(a))return!0}return!1}getAllFiles(){return Array.from(this.entries.keys())}getRealPath(){if(!this.path)throw new Error(\"ZipFS don't have real paths when loaded from a buffer\");return this.path}prepareClose(){if(!this.ready)throw nr.EBUSY(\"archive closed, close\");N0(this)}getBufferAndClose(){if(this.prepareClose(),this.entries.size===0)return this.discardAndClose(),CS();try{if(this.libzip.source.keep(this.lzSource),this.libzip.close(this.zip)===-1)throw this.makeLibzipError(this.libzip.getError(this.zip));if(this.libzip.source.open(this.lzSource)===-1)throw this.makeLibzipError(this.libzip.source.error(this.lzSource));if(this.libzip.source.seek(this.lzSource,0,0,this.libzip.SEEK_END)===-1)throw this.makeLibzipError(this.libzip.source.error(this.lzSource));let r=this.libzip.source.tell(this.lzSource);if(r===-1)throw this.makeLibzipError(this.libzip.source.error(this.lzSource));if(this.libzip.source.seek(this.lzSource,0,0,this.libzip.SEEK_SET)===-1)throw this.makeLibzipError(this.libzip.source.error(this.lzSource));let o=this.libzip.malloc(r);if(!o)throw new Error(\"Couldn't allocate enough memory\");try{let a=this.libzip.source.read(this.lzSource,o,r);if(a===-1)throw this.makeLibzipError(this.libzip.source.error(this.lzSource));if(a<r)throw new Error(\"Incomplete read\");if(a>r)throw new Error(\"Overread\");let n=Buffer.from(this.libzip.HEAPU8.subarray(o,o+r));return process.env.YARN_IS_TEST_ENV&&process.env.YARN_ZIP_DATA_EPILOGUE&&(n=Buffer.concat([n,Buffer.from(process.env.YARN_ZIP_DATA_EPILOGUE)])),n}finally{this.libzip.free(o)}}finally{this.libzip.source.close(this.lzSource),this.libzip.source.free(this.lzSource),this.ready=!1}}discardAndClose(){this.prepareClose(),this.libzip.discard(this.zip),this.ready=!1}saveAndClose(){if(!this.path||!this.baseFs)throw new Error(\"ZipFS cannot be saved and must be discarded when loaded from a buffer\");if(this.readOnly){this.discardAndClose();return}let r=this.baseFs.existsSync(this.path)||this.stats.mode===wa.DEFAULT_MODE?void 0:this.stats.mode;this.baseFs.writeFileSync(this.path,this.getBufferAndClose(),{mode:r}),this.ready=!1}resolve(r){return V.resolve(It.root,r)}async openPromise(r,o,a){return this.openSync(r,o,a)}openSync(r,o,a){let n=this.nextFd++;return this.fds.set(n,{cursor:0,p:r}),n}hasOpenFileHandles(){return!!this.fds.size}async opendirPromise(r,o){return this.opendirSync(r,o)}opendirSync(r,o={}){let a=this.resolveFilename(`opendir '${r}'`,r);if(!this.entries.has(a)&&!this.listings.has(a))throw nr.ENOENT(`opendir '${r}'`);let n=this.listings.get(a);if(!n)throw nr.ENOTDIR(`opendir '${r}'`);let u=[...n],A=this.openSync(a,\"r\");return uD(this,a,u,{onClose:()=>{this.closeSync(A)}})}async readPromise(r,o,a,n,u){return this.readSync(r,o,a,n,u)}readSync(r,o,a=0,n=o.byteLength,u=-1){let A=this.fds.get(r);if(typeof A>\"u\")throw nr.EBADF(\"read\");let p=u===-1||u===null?A.cursor:u,h=this.readFileSync(A.p);h.copy(o,a,p,p+n);let E=Math.max(0,Math.min(h.length-p,n));return(u===-1||u===null)&&(A.cursor+=E),E}async writePromise(r,o,a,n,u){return typeof o==\"string\"?this.writeSync(r,o,u):this.writeSync(r,o,a,n,u)}writeSync(r,o,a,n,u){throw typeof this.fds.get(r)>\"u\"?nr.EBADF(\"read\"):new Error(\"Unimplemented\")}async closePromise(r){return this.closeSync(r)}closeSync(r){if(typeof this.fds.get(r)>\"u\")throw nr.EBADF(\"read\");this.fds.delete(r)}createReadStream(r,{encoding:o}={}){if(r===null)throw new Error(\"Unimplemented\");let a=this.openSync(r,\"r\"),n=Object.assign(new z4.PassThrough({emitClose:!0,autoDestroy:!0,destroy:(A,p)=>{clearImmediate(u),this.closeSync(a),p(A)}}),{close(){n.destroy()},bytesRead:0,path:r,pending:!1}),u=setImmediate(async()=>{try{let A=await this.readFilePromise(r,o);n.bytesRead=A.length,n.end(A)}catch(A){n.destroy(A)}});return n}createWriteStream(r,{encoding:o}={}){if(this.readOnly)throw nr.EROFS(`open '${r}'`);if(r===null)throw new Error(\"Unimplemented\");let a=[],n=this.openSync(r,\"w\"),u=Object.assign(new z4.PassThrough({autoDestroy:!0,emitClose:!0,destroy:(A,p)=>{try{A?p(A):(this.writeFileSync(r,Buffer.concat(a),o),p(null))}catch(h){p(h)}finally{this.closeSync(n)}}}),{close(){u.destroy()},bytesWritten:0,path:r,pending:!1});return u.on(\"data\",A=>{let p=Buffer.from(A);u.bytesWritten+=p.length,a.push(p)}),u}async realpathPromise(r){return this.realpathSync(r)}realpathSync(r){let o=this.resolveFilename(`lstat '${r}'`,r);if(!this.entries.has(o)&&!this.listings.has(o))throw nr.ENOENT(`lstat '${r}'`);return o}async existsPromise(r){return this.existsSync(r)}existsSync(r){if(!this.ready)throw nr.EBUSY(`archive closed, existsSync '${r}'`);if(this.symlinkCount===0){let a=V.resolve(It.root,r);return this.entries.has(a)||this.listings.has(a)}let o;try{o=this.resolveFilename(`stat '${r}'`,r,void 0,!1)}catch{return!1}return o===void 0?!1:this.entries.has(o)||this.listings.has(o)}async accessPromise(r,o){return this.accessSync(r,o)}accessSync(r,o=na.constants.F_OK){let a=this.resolveFilename(`access '${r}'`,r);if(!this.entries.has(a)&&!this.listings.has(a))throw nr.ENOENT(`access '${r}'`);if(this.readOnly&&o&na.constants.W_OK)throw nr.EROFS(`access '${r}'`)}async statPromise(r,o={bigint:!1}){return o.bigint?this.statSync(r,{bigint:!0}):this.statSync(r)}statSync(r,o={bigint:!1,throwIfNoEntry:!0}){let a=this.resolveFilename(`stat '${r}'`,r,void 0,o.throwIfNoEntry);if(a!==void 0){if(!this.entries.has(a)&&!this.listings.has(a)){if(o.throwIfNoEntry===!1)return;throw nr.ENOENT(`stat '${r}'`)}if(r[r.length-1]===\"/\"&&!this.listings.has(a))throw nr.ENOTDIR(`stat '${r}'`);return this.statImpl(`stat '${r}'`,a,o)}}async fstatPromise(r,o){return this.fstatSync(r,o)}fstatSync(r,o){let a=this.fds.get(r);if(typeof a>\"u\")throw nr.EBADF(\"fstatSync\");let{p:n}=a,u=this.resolveFilename(`stat '${n}'`,n);if(!this.entries.has(u)&&!this.listings.has(u))throw nr.ENOENT(`stat '${n}'`);if(n[n.length-1]===\"/\"&&!this.listings.has(u))throw nr.ENOTDIR(`stat '${n}'`);return this.statImpl(`fstat '${n}'`,u,o)}async lstatPromise(r,o={bigint:!1}){return o.bigint?this.lstatSync(r,{bigint:!0}):this.lstatSync(r)}lstatSync(r,o={bigint:!1,throwIfNoEntry:!0}){let a=this.resolveFilename(`lstat '${r}'`,r,!1,o.throwIfNoEntry);if(a!==void 0){if(!this.entries.has(a)&&!this.listings.has(a)){if(o.throwIfNoEntry===!1)return;throw nr.ENOENT(`lstat '${r}'`)}if(r[r.length-1]===\"/\"&&!this.listings.has(a))throw nr.ENOTDIR(`lstat '${r}'`);return this.statImpl(`lstat '${r}'`,a,o)}}statImpl(r,o,a={}){let n=this.entries.get(o);if(typeof n<\"u\"){let u=this.libzip.struct.statS();if(this.libzip.statIndex(this.zip,n,0,0,u)===-1)throw this.makeLibzipError(this.libzip.getError(this.zip));let p=this.stats.uid,h=this.stats.gid,E=this.libzip.struct.statSize(u)>>>0,I=512,v=Math.ceil(E/I),x=(this.libzip.struct.statMtime(u)>>>0)*1e3,C=x,R=x,L=x,U=new Date(C),z=new Date(R),te=new Date(L),ae=new Date(x),le=this.listings.has(o)?na.constants.S_IFDIR:this.isSymbolicLink(n)?na.constants.S_IFLNK:na.constants.S_IFREG,ce=le===na.constants.S_IFDIR?493:420,Ce=le|this.getUnixMode(n,ce)&511,de=this.libzip.struct.statCrc(u),Be=Object.assign(new wa.StatEntry,{uid:p,gid:h,size:E,blksize:I,blocks:v,atime:U,birthtime:z,ctime:te,mtime:ae,atimeMs:C,birthtimeMs:R,ctimeMs:L,mtimeMs:x,mode:Ce,crc:de});return a.bigint===!0?wa.convertToBigIntStats(Be):Be}if(this.listings.has(o)){let u=this.stats.uid,A=this.stats.gid,p=0,h=512,E=0,I=this.stats.mtimeMs,v=this.stats.mtimeMs,x=this.stats.mtimeMs,C=this.stats.mtimeMs,R=new Date(I),L=new Date(v),U=new Date(x),z=new Date(C),te=na.constants.S_IFDIR|493,le=Object.assign(new wa.StatEntry,{uid:u,gid:A,size:p,blksize:h,blocks:E,atime:R,birthtime:L,ctime:U,mtime:z,atimeMs:I,birthtimeMs:v,ctimeMs:x,mtimeMs:C,mode:te,crc:0});return a.bigint===!0?wa.convertToBigIntStats(le):le}throw new Error(\"Unreachable\")}getUnixMode(r,o){if(this.libzip.file.getExternalAttributes(this.zip,r,0,0,this.libzip.uint08S,this.libzip.uint32S)===-1)throw this.makeLibzipError(this.libzip.getError(this.zip));return this.libzip.getValue(this.libzip.uint08S,\"i8\")>>>0!==this.libzip.ZIP_OPSYS_UNIX?o:this.libzip.getValue(this.libzip.uint32S,\"i32\")>>>16}registerListing(r){let o=this.listings.get(r);if(o)return o;this.registerListing(V.dirname(r)).add(V.basename(r));let n=new Set;return this.listings.set(r,n),n}registerEntry(r,o){this.registerListing(V.dirname(r)).add(V.basename(r)),this.entries.set(r,o)}unregisterListing(r){this.listings.delete(r),this.listings.get(V.dirname(r))?.delete(V.basename(r))}unregisterEntry(r){this.unregisterListing(r);let o=this.entries.get(r);this.entries.delete(r),!(typeof o>\"u\")&&(this.fileSources.delete(o),this.isSymbolicLink(o)&&this.symlinkCount--)}deleteEntry(r,o){if(this.unregisterEntry(r),this.libzip.delete(this.zip,o)===-1)throw this.makeLibzipError(this.libzip.getError(this.zip))}resolveFilename(r,o,a=!0,n=!0){if(!this.ready)throw nr.EBUSY(`archive closed, ${r}`);let u=V.resolve(It.root,o);if(u===\"/\")return It.root;let A=this.entries.get(u);if(a&&A!==void 0)if(this.symlinkCount!==0&&this.isSymbolicLink(A)){let p=this.getFileSource(A).toString();return this.resolveFilename(r,V.resolve(V.dirname(u),p),!0,n)}else return u;for(;;){let p=this.resolveFilename(r,V.dirname(u),!0,n);if(p===void 0)return p;let h=this.listings.has(p),E=this.entries.has(p);if(!h&&!E){if(n===!1)return;throw nr.ENOENT(r)}if(!h)throw nr.ENOTDIR(r);if(u=V.resolve(p,V.basename(u)),!a||this.symlinkCount===0)break;let I=this.libzip.name.locate(this.zip,u.slice(1),0);if(I===-1)break;if(this.isSymbolicLink(I)){let v=this.getFileSource(I).toString();u=V.resolve(V.dirname(u),v)}else break}return u}allocateBuffer(r){Buffer.isBuffer(r)||(r=Buffer.from(r));let o=this.libzip.malloc(r.byteLength);if(!o)throw new Error(\"Couldn't allocate enough memory\");return new Uint8Array(this.libzip.HEAPU8.buffer,o,r.byteLength).set(r),{buffer:o,byteLength:r.byteLength}}allocateUnattachedSource(r){let o=this.libzip.struct.errorS(),{buffer:a,byteLength:n}=this.allocateBuffer(r),u=this.libzip.source.fromUnattachedBuffer(a,n,0,1,o);if(u===0)throw this.libzip.free(o),this.makeLibzipError(o);return u}allocateSource(r){let{buffer:o,byteLength:a}=this.allocateBuffer(r),n=this.libzip.source.fromBuffer(this.zip,o,a,0,1);if(n===0)throw this.libzip.free(o),this.makeLibzipError(this.libzip.getError(this.zip));return n}setFileSource(r,o){let a=Buffer.isBuffer(o)?o:Buffer.from(o),n=V.relative(It.root,r),u=this.allocateSource(o);try{let A=this.libzip.file.add(this.zip,n,u,this.libzip.ZIP_FL_OVERWRITE);if(A===-1)throw this.makeLibzipError(this.libzip.getError(this.zip));if(this.level!==\"mixed\"){let p=this.level===0?this.libzip.ZIP_CM_STORE:this.libzip.ZIP_CM_DEFLATE;if(this.libzip.file.setCompression(this.zip,A,0,p,this.level)===-1)throw this.makeLibzipError(this.libzip.getError(this.zip))}return this.fileSources.set(A,a),A}catch(A){throw this.libzip.source.free(u),A}}isSymbolicLink(r){if(this.symlinkCount===0)return!1;if(this.libzip.file.getExternalAttributes(this.zip,r,0,0,this.libzip.uint08S,this.libzip.uint32S)===-1)throw this.makeLibzipError(this.libzip.getError(this.zip));return this.libzip.getValue(this.libzip.uint08S,\"i8\")>>>0!==this.libzip.ZIP_OPSYS_UNIX?!1:(this.libzip.getValue(this.libzip.uint32S,\"i32\")>>>16&na.constants.S_IFMT)===na.constants.S_IFLNK}getFileSource(r,o={asyncDecompress:!1}){let a=this.fileSources.get(r);if(typeof a<\"u\")return a;let n=this.libzip.struct.statS();if(this.libzip.statIndex(this.zip,r,0,0,n)===-1)throw this.makeLibzipError(this.libzip.getError(this.zip));let A=this.libzip.struct.statCompSize(n),p=this.libzip.struct.statCompMethod(n),h=this.libzip.malloc(A);try{let E=this.libzip.fopenIndex(this.zip,r,0,this.libzip.ZIP_FL_COMPRESSED);if(E===0)throw this.makeLibzipError(this.libzip.getError(this.zip));try{let I=this.libzip.fread(E,h,A,0);if(I===-1)throw this.makeLibzipError(this.libzip.file.getError(E));if(I<A)throw new Error(\"Incomplete read\");if(I>A)throw new Error(\"Overread\");let v=this.libzip.HEAPU8.subarray(h,h+A),x=Buffer.from(v);if(p===0)return this.fileSources.set(r,x),x;if(o.asyncDecompress)return new Promise((C,R)=>{J4.default.inflateRaw(x,(L,U)=>{L?R(L):(this.fileSources.set(r,U),C(U))})});{let C=J4.default.inflateRawSync(x);return this.fileSources.set(r,C),C}}finally{this.libzip.fclose(E)}}finally{this.libzip.free(h)}}async fchmodPromise(r,o){return this.chmodPromise(this.fdToPath(r,\"fchmod\"),o)}fchmodSync(r,o){return this.chmodSync(this.fdToPath(r,\"fchmodSync\"),o)}async chmodPromise(r,o){return this.chmodSync(r,o)}chmodSync(r,o){if(this.readOnly)throw nr.EROFS(`chmod '${r}'`);o&=493;let a=this.resolveFilename(`chmod '${r}'`,r,!1),n=this.entries.get(a);if(typeof n>\"u\")throw new Error(`Assertion failed: The entry should have been registered (${a})`);let A=this.getUnixMode(n,na.constants.S_IFREG|0)&-512|o;if(this.libzip.file.setExternalAttributes(this.zip,n,0,0,this.libzip.ZIP_OPSYS_UNIX,A<<16)===-1)throw this.makeLibzipError(this.libzip.getError(this.zip))}async fchownPromise(r,o,a){return this.chownPromise(this.fdToPath(r,\"fchown\"),o,a)}fchownSync(r,o,a){return this.chownSync(this.fdToPath(r,\"fchownSync\"),o,a)}async chownPromise(r,o,a){return this.chownSync(r,o,a)}chownSync(r,o,a){throw new Error(\"Unimplemented\")}async renamePromise(r,o){return this.renameSync(r,o)}renameSync(r,o){throw new Error(\"Unimplemented\")}async copyFilePromise(r,o,a){let{indexSource:n,indexDest:u,resolvedDestP:A}=this.prepareCopyFile(r,o,a),p=await this.getFileSource(n,{asyncDecompress:!0}),h=this.setFileSource(A,p);h!==u&&this.registerEntry(A,h)}copyFileSync(r,o,a=0){let{indexSource:n,indexDest:u,resolvedDestP:A}=this.prepareCopyFile(r,o,a),p=this.getFileSource(n),h=this.setFileSource(A,p);h!==u&&this.registerEntry(A,h)}prepareCopyFile(r,o,a=0){if(this.readOnly)throw nr.EROFS(`copyfile '${r} -> '${o}'`);if(a&na.constants.COPYFILE_FICLONE_FORCE)throw nr.ENOSYS(\"unsupported clone operation\",`copyfile '${r}' -> ${o}'`);let n=this.resolveFilename(`copyfile '${r} -> ${o}'`,r),u=this.entries.get(n);if(typeof u>\"u\")throw nr.EINVAL(`copyfile '${r}' -> '${o}'`);let A=this.resolveFilename(`copyfile '${r}' -> ${o}'`,o),p=this.entries.get(A);if(a&(na.constants.COPYFILE_EXCL|na.constants.COPYFILE_FICLONE_FORCE)&&typeof p<\"u\")throw nr.EEXIST(`copyfile '${r}' -> '${o}'`);return{indexSource:u,resolvedDestP:A,indexDest:p}}async appendFilePromise(r,o,a){if(this.readOnly)throw nr.EROFS(`open '${r}'`);return typeof a>\"u\"?a={flag:\"a\"}:typeof a==\"string\"?a={flag:\"a\",encoding:a}:typeof a.flag>\"u\"&&(a={flag:\"a\",...a}),this.writeFilePromise(r,o,a)}appendFileSync(r,o,a={}){if(this.readOnly)throw nr.EROFS(`open '${r}'`);return typeof a>\"u\"?a={flag:\"a\"}:typeof a==\"string\"?a={flag:\"a\",encoding:a}:typeof a.flag>\"u\"&&(a={flag:\"a\",...a}),this.writeFileSync(r,o,a)}fdToPath(r,o){let a=this.fds.get(r)?.p;if(typeof a>\"u\")throw nr.EBADF(o);return a}async writeFilePromise(r,o,a){let{encoding:n,mode:u,index:A,resolvedP:p}=this.prepareWriteFile(r,a);A!==void 0&&typeof a==\"object\"&&a.flag&&a.flag.includes(\"a\")&&(o=Buffer.concat([await this.getFileSource(A,{asyncDecompress:!0}),Buffer.from(o)])),n!==null&&(o=o.toString(n));let h=this.setFileSource(p,o);h!==A&&this.registerEntry(p,h),u!==null&&await this.chmodPromise(p,u)}writeFileSync(r,o,a){let{encoding:n,mode:u,index:A,resolvedP:p}=this.prepareWriteFile(r,a);A!==void 0&&typeof a==\"object\"&&a.flag&&a.flag.includes(\"a\")&&(o=Buffer.concat([this.getFileSource(A),Buffer.from(o)])),n!==null&&(o=o.toString(n));let h=this.setFileSource(p,o);h!==A&&this.registerEntry(p,h),u!==null&&this.chmodSync(p,u)}prepareWriteFile(r,o){if(typeof r==\"number\"&&(r=this.fdToPath(r,\"read\")),this.readOnly)throw nr.EROFS(`open '${r}'`);let a=this.resolveFilename(`open '${r}'`,r);if(this.listings.has(a))throw nr.EISDIR(`open '${r}'`);let n=null,u=null;typeof o==\"string\"?n=o:typeof o==\"object\"&&({encoding:n=null,mode:u=null}=o);let A=this.entries.get(a);return{encoding:n,mode:u,resolvedP:a,index:A}}async unlinkPromise(r){return this.unlinkSync(r)}unlinkSync(r){if(this.readOnly)throw nr.EROFS(`unlink '${r}'`);let o=this.resolveFilename(`unlink '${r}'`,r);if(this.listings.has(o))throw nr.EISDIR(`unlink '${r}'`);let a=this.entries.get(o);if(typeof a>\"u\")throw nr.EINVAL(`unlink '${r}'`);this.deleteEntry(o,a)}async utimesPromise(r,o,a){return this.utimesSync(r,o,a)}utimesSync(r,o,a){if(this.readOnly)throw nr.EROFS(`utimes '${r}'`);let n=this.resolveFilename(`utimes '${r}'`,r);this.utimesImpl(n,a)}async lutimesPromise(r,o,a){return this.lutimesSync(r,o,a)}lutimesSync(r,o,a){if(this.readOnly)throw nr.EROFS(`lutimes '${r}'`);let n=this.resolveFilename(`utimes '${r}'`,r,!1);this.utimesImpl(n,a)}utimesImpl(r,o){this.listings.has(r)&&(this.entries.has(r)||this.hydrateDirectory(r));let a=this.entries.get(r);if(a===void 0)throw new Error(\"Unreachable\");if(this.libzip.file.setMtime(this.zip,a,0,fot(o),0)===-1)throw this.makeLibzipError(this.libzip.getError(this.zip))}async mkdirPromise(r,o){return this.mkdirSync(r,o)}mkdirSync(r,{mode:o=493,recursive:a=!1}={}){if(a)return this.mkdirpSync(r,{chmod:o});if(this.readOnly)throw nr.EROFS(`mkdir '${r}'`);let n=this.resolveFilename(`mkdir '${r}'`,r);if(this.entries.has(n)||this.listings.has(n))throw nr.EEXIST(`mkdir '${r}'`);this.hydrateDirectory(n),this.chmodSync(n,o)}async rmdirPromise(r,o){return this.rmdirSync(r,o)}rmdirSync(r,{recursive:o=!1}={}){if(this.readOnly)throw nr.EROFS(`rmdir '${r}'`);if(o){this.removeSync(r);return}let a=this.resolveFilename(`rmdir '${r}'`,r),n=this.listings.get(a);if(!n)throw nr.ENOTDIR(`rmdir '${r}'`);if(n.size>0)throw nr.ENOTEMPTY(`rmdir '${r}'`);let u=this.entries.get(a);if(typeof u>\"u\")throw nr.EINVAL(`rmdir '${r}'`);this.deleteEntry(r,u)}async rmPromise(r,o){return this.rmSync(r,o)}rmSync(r,{recursive:o=!1}={}){if(this.readOnly)throw nr.EROFS(`rm '${r}'`);if(o){this.removeSync(r);return}let a=this.resolveFilename(`rm '${r}'`,r),n=this.listings.get(a);if(!n)throw nr.ENOTDIR(`rm '${r}'`);if(n.size>0)throw nr.ENOTEMPTY(`rm '${r}'`);let u=this.entries.get(a);if(typeof u>\"u\")throw nr.EINVAL(`rm '${r}'`);this.deleteEntry(r,u)}hydrateDirectory(r){let o=this.libzip.dir.add(this.zip,V.relative(It.root,r));if(o===-1)throw this.makeLibzipError(this.libzip.getError(this.zip));return this.registerListing(r),this.registerEntry(r,o),o}async linkPromise(r,o){return this.linkSync(r,o)}linkSync(r,o){throw nr.EOPNOTSUPP(`link '${r}' -> '${o}'`)}async symlinkPromise(r,o){return this.symlinkSync(r,o)}symlinkSync(r,o){if(this.readOnly)throw nr.EROFS(`symlink '${r}' -> '${o}'`);let a=this.resolveFilename(`symlink '${r}' -> '${o}'`,o);if(this.listings.has(a))throw nr.EISDIR(`symlink '${r}' -> '${o}'`);if(this.entries.has(a))throw nr.EEXIST(`symlink '${r}' -> '${o}'`);let n=this.setFileSource(a,r);if(this.registerEntry(a,n),this.libzip.file.setExternalAttributes(this.zip,n,0,0,this.libzip.ZIP_OPSYS_UNIX,(na.constants.S_IFLNK|511)<<16)===-1)throw this.makeLibzipError(this.libzip.getError(this.zip));this.symlinkCount+=1}async readFilePromise(r,o){typeof o==\"object\"&&(o=o?o.encoding:void 0);let a=await this.readFileBuffer(r,{asyncDecompress:!0});return o?a.toString(o):a}readFileSync(r,o){typeof o==\"object\"&&(o=o?o.encoding:void 0);let a=this.readFileBuffer(r);return o?a.toString(o):a}readFileBuffer(r,o={asyncDecompress:!1}){typeof r==\"number\"&&(r=this.fdToPath(r,\"read\"));let a=this.resolveFilename(`open '${r}'`,r);if(!this.entries.has(a)&&!this.listings.has(a))throw nr.ENOENT(`open '${r}'`);if(r[r.length-1]===\"/\"&&!this.listings.has(a))throw nr.ENOTDIR(`open '${r}'`);if(this.listings.has(a))throw nr.EISDIR(\"read\");let n=this.entries.get(a);if(n===void 0)throw new Error(\"Unreachable\");return this.getFileSource(n,o)}async readdirPromise(r,o){return this.readdirSync(r,o)}readdirSync(r,o){let a=this.resolveFilename(`scandir '${r}'`,r);if(!this.entries.has(a)&&!this.listings.has(a))throw nr.ENOENT(`scandir '${r}'`);let n=this.listings.get(a);if(!n)throw nr.ENOTDIR(`scandir '${r}'`);if(o?.recursive)if(o?.withFileTypes){let u=Array.from(n,A=>Object.assign(this.statImpl(\"lstat\",V.join(r,A)),{name:A,path:It.dot}));for(let A of u){if(!A.isDirectory())continue;let p=V.join(A.path,A.name),h=this.listings.get(V.join(a,p));for(let E of h)u.push(Object.assign(this.statImpl(\"lstat\",V.join(r,p,E)),{name:E,path:p}))}return u}else{let u=[...n];for(let A of u){let p=this.listings.get(V.join(a,A));if(!(typeof p>\"u\"))for(let h of p)u.push(V.join(A,h))}return u}else return o?.withFileTypes?Array.from(n,u=>Object.assign(this.statImpl(\"lstat\",V.join(r,u)),{name:u,path:void 0})):[...n]}async readlinkPromise(r){let o=this.prepareReadlink(r);return(await this.getFileSource(o,{asyncDecompress:!0})).toString()}readlinkSync(r){let o=this.prepareReadlink(r);return this.getFileSource(o).toString()}prepareReadlink(r){let o=this.resolveFilename(`readlink '${r}'`,r,!1);if(!this.entries.has(o)&&!this.listings.has(o))throw nr.ENOENT(`readlink '${r}'`);if(r[r.length-1]===\"/\"&&!this.listings.has(o))throw nr.ENOTDIR(`open '${r}'`);if(this.listings.has(o))throw nr.EINVAL(`readlink '${r}'`);let a=this.entries.get(o);if(a===void 0)throw new Error(\"Unreachable\");if(!this.isSymbolicLink(a))throw nr.EINVAL(`readlink '${r}'`);return a}async truncatePromise(r,o=0){let a=this.resolveFilename(`open '${r}'`,r),n=this.entries.get(a);if(typeof n>\"u\")throw nr.EINVAL(`open '${r}'`);let u=await this.getFileSource(n,{asyncDecompress:!0}),A=Buffer.alloc(o,0);return u.copy(A),await this.writeFilePromise(r,A)}truncateSync(r,o=0){let a=this.resolveFilename(`open '${r}'`,r),n=this.entries.get(a);if(typeof n>\"u\")throw nr.EINVAL(`open '${r}'`);let u=this.getFileSource(n),A=Buffer.alloc(o,0);return u.copy(A),this.writeFileSync(r,A)}async ftruncatePromise(r,o){return this.truncatePromise(this.fdToPath(r,\"ftruncate\"),o)}ftruncateSync(r,o){return this.truncateSync(this.fdToPath(r,\"ftruncateSync\"),o)}watch(r,o,a){let n;switch(typeof o){case\"function\":case\"string\":case\"undefined\":n=!0;break;default:({persistent:n=!0}=o);break}if(!n)return{on:()=>{},close:()=>{}};let u=setInterval(()=>{},24*60*60*1e3);return{on:()=>{},close:()=>{clearInterval(u)}}}watchFile(r,o,a){let n=V.resolve(It.root,r);return jd(this,n,o,a)}unwatchFile(r,o){let a=V.resolve(It.root,r);return T0(this,a,o)}}});function Yle(t,e,r=Buffer.alloc(0),o){let a=new Zi(r),n=I=>I===e||I.startsWith(`${e}/`)?I.slice(0,e.length):null,u=async(I,v)=>()=>a,A=(I,v)=>a,p={...t},h=new Tn(p),E=new Op({baseFs:h,getMountPoint:n,factoryPromise:u,factorySync:A,magicByte:21,maxAge:1/0,typeCheck:o?.typeCheck});return xw(Gle.default,new Up(E)),a}var Gle,Wle=Et(()=>{Pt();Gle=Ze(ve(\"fs\"));X4()});var Kle=Et(()=>{Hle();X4();Wle()});var p1={};Vt(p1,{DEFAULT_COMPRESSION_LEVEL:()=>jle,LibzipError:()=>wS,ZipFS:()=>Zi,ZipOpenFS:()=>rA,getArchivePart:()=>V4,getLibzipPromise:()=>hot,getLibzipSync:()=>pot,makeEmptyArchive:()=>CS,mountMemoryDrive:()=>Yle});function pot(){return f1()}async function hot(){return f1()}var Vle,nA=Et(()=>{Y4();Vle=Ze(Mle());_le();Kle();Lle(()=>{let t=(0,Vle.default)();return Ule(t)})});var h1,zle=Et(()=>{Pt();qt();g1();h1=class extends it{constructor(){super(...arguments);this.cwd=ge.String(\"--cwd\",process.cwd(),{description:\"The directory to run the command in\"});this.commandName=ge.String();this.args=ge.Proxy()}static{this.usage={description:\"run a command using yarn's portable shell\",details:`\n      This command will run a command using Yarn's portable shell.\n\n      Make sure to escape glob patterns, redirections, and other features that might be expanded by your own shell.\n\n      Note: To escape something from Yarn's shell, you might have to escape it twice, the first time from your own shell.\n\n      Note: Don't use this command in Yarn scripts, as Yarn's shell is automatically used.\n\n      For a list of features, visit: https://github.com/yarnpkg/berry/blob/master/packages/yarnpkg-shell/README.md.\n    `,examples:[[\"Run a simple command\",\"$0 echo Hello\"],[\"Run a command with a glob pattern\",\"$0 echo '*.js'\"],[\"Run a command with a redirection\",\"$0 echo Hello World '>' hello.txt\"],[\"Run a command with an escaped glob pattern (The double escape is needed in Unix shells)\",`$0 echo '\"*.js\"'`],[\"Run a command with a variable (Double quotes are needed in Unix shells, to prevent them from expanding the variable)\",'$0 \"GREETING=Hello echo $GREETING World\"']]}}async execute(){let r=this.args.length>0?`${this.commandName} ${this.args.join(\" \")}`:this.commandName;return await cy(r,[],{cwd:ue.toPortablePath(this.cwd),stdin:this.context.stdin,stdout:this.context.stdout,stderr:this.context.stderr})}}});var ll,Jle=Et(()=>{ll=class extends Error{constructor(e){super(e),this.name=\"ShellError\"}}});var vS={};Vt(vS,{fastGlobOptions:()=>$le,isBraceExpansion:()=>Z4,isGlobPattern:()=>got,match:()=>dot,micromatchOptions:()=>BS});function got(t){if(!IS.default.scan(t,BS).isGlob)return!1;try{IS.default.parse(t,BS)}catch{return!1}return!0}function dot(t,{cwd:e,baseFs:r}){return(0,Xle.default)(t,{...$le,cwd:ue.fromPortablePath(e),fs:mD(Zle.default,new Up(r))})}function Z4(t){return IS.default.scan(t,BS).isBrace}var Xle,Zle,IS,BS,$le,ece=Et(()=>{Pt();Xle=Ze(Cb()),Zle=Ze(ve(\"fs\")),IS=Ze($o()),BS={strictBrackets:!0},$le={onlyDirectories:!1,onlyFiles:!1}});function $4(){}function eU(){for(let t of vg)t.kill()}function ice(t,e,r,o){return a=>{let n=a[0]instanceof iA.Transform?\"pipe\":a[0],u=a[1]instanceof iA.Transform?\"pipe\":a[1],A=a[2]instanceof iA.Transform?\"pipe\":a[2],p=(0,rce.default)(t,e,{...o,stdio:[n,u,A]});return vg.add(p),vg.size===1&&(process.on(\"SIGINT\",$4),process.on(\"SIGTERM\",eU)),a[0]instanceof iA.Transform&&a[0].pipe(p.stdin),a[1]instanceof iA.Transform&&p.stdout.pipe(a[1],{end:!1}),a[2]instanceof iA.Transform&&p.stderr.pipe(a[2],{end:!1}),{stdin:p.stdin,promise:new Promise(h=>{p.on(\"error\",E=>{switch(vg.delete(p),vg.size===0&&(process.off(\"SIGINT\",$4),process.off(\"SIGTERM\",eU)),E.code){case\"ENOENT\":a[2].write(`command not found: ${t}\n`),h(127);break;case\"EACCES\":a[2].write(`permission denied: ${t}\n`),h(128);break;default:a[2].write(`uncaught error: ${E.message}\n`),h(1);break}}),p.on(\"close\",E=>{vg.delete(p),vg.size===0&&(process.off(\"SIGINT\",$4),process.off(\"SIGTERM\",eU)),h(E!==null?E:129)})})}}}function sce(t){return e=>{let r=e[0]===\"pipe\"?new iA.PassThrough:e[0];return{stdin:r,promise:Promise.resolve().then(()=>t({stdin:r,stdout:e[1],stderr:e[2]}))}}}function DS(t,e){return rU.start(t,e)}function tce(t,e=null){let r=new iA.PassThrough,o=new nce.StringDecoder,a=\"\";return r.on(\"data\",n=>{let u=o.write(n),A;do if(A=u.indexOf(`\n`),A!==-1){let p=a+u.substring(0,A);u=u.substring(A+1),a=\"\",t(e!==null?`${e} ${p}`:p)}while(A!==-1);a+=u}),r.on(\"end\",()=>{let n=o.end();n!==\"\"&&t(e!==null?`${e} ${n}`:n)}),r}function oce(t,{prefix:e}){return{stdout:tce(r=>t.stdout.write(`${r}\n`),t.stdout.isTTY?e:null),stderr:tce(r=>t.stderr.write(`${r}\n`),t.stderr.isTTY?e:null)}}var rce,iA,nce,vg,Jl,tU,rU,nU=Et(()=>{rce=Ze(KR()),iA=ve(\"stream\"),nce=ve(\"string_decoder\"),vg=new Set;Jl=class{constructor(e){this.stream=e}close(){}get(){return this.stream}},tU=class{constructor(){this.stream=null}close(){if(this.stream===null)throw new Error(\"Assertion failed: No stream attached\");this.stream.end()}attach(e){this.stream=e}get(){if(this.stream===null)throw new Error(\"Assertion failed: No stream attached\");return this.stream}},rU=class t{constructor(e,r){this.stdin=null;this.stdout=null;this.stderr=null;this.pipe=null;this.ancestor=e,this.implementation=r}static start(e,{stdin:r,stdout:o,stderr:a}){let n=new t(null,e);return n.stdin=r,n.stdout=o,n.stderr=a,n}pipeTo(e,r=1){let o=new t(this,e),a=new tU;return o.pipe=a,o.stdout=this.stdout,o.stderr=this.stderr,(r&1)===1?this.stdout=a:this.ancestor!==null&&(this.stderr=this.ancestor.stdout),(r&2)===2?this.stderr=a:this.ancestor!==null&&(this.stderr=this.ancestor.stderr),o}async exec(){let e=[\"ignore\",\"ignore\",\"ignore\"];if(this.pipe)e[0]=\"pipe\";else{if(this.stdin===null)throw new Error(\"Assertion failed: No input stream registered\");e[0]=this.stdin.get()}let r;if(this.stdout===null)throw new Error(\"Assertion failed: No output stream registered\");r=this.stdout,e[1]=r.get();let o;if(this.stderr===null)throw new Error(\"Assertion failed: No error stream registered\");o=this.stderr,e[2]=o.get();let a=this.implementation(e);return this.pipe&&this.pipe.attach(a.stdin),await a.promise.then(n=>(r.close(),o.close(),n))}async run(){let e=[];for(let o=this;o;o=o.ancestor)e.push(o.exec());return(await Promise.all(e))[0]}}});var E1={};Vt(E1,{EntryCommand:()=>h1,ShellError:()=>ll,execute:()=>cy,globUtils:()=>vS});function ace(t,e,r){let o=new cl.PassThrough({autoDestroy:!0});switch(t){case 0:(e&1)===1&&r.stdin.pipe(o,{end:!1}),(e&2)===2&&r.stdin instanceof cl.Writable&&o.pipe(r.stdin,{end:!1});break;case 1:(e&1)===1&&r.stdout.pipe(o,{end:!1}),(e&2)===2&&o.pipe(r.stdout,{end:!1});break;case 2:(e&1)===1&&r.stderr.pipe(o,{end:!1}),(e&2)===2&&o.pipe(r.stderr,{end:!1});break;default:throw new ll(`Bad file descriptor: \"${t}\"`)}return o}function bS(t,e={}){let r={...t,...e};return r.environment={...t.environment,...e.environment},r.variables={...t.variables,...e.variables},r}async function yot(t,e,r){let o=[],a=new cl.PassThrough;return a.on(\"data\",n=>o.push(n)),await SS(t,e,bS(r,{stdout:a})),Buffer.concat(o).toString().replace(/[\\r\\n]+$/,\"\")}async function lce(t,e,r){let o=t.map(async n=>{let u=await Dg(n.args,e,r);return{name:n.name,value:u.join(\" \")}});return(await Promise.all(o)).reduce((n,u)=>(n[u.name]=u.value,n),{})}function PS(t){return t.match(/[^ \\r\\n\\t]+/g)||[]}async function hce(t,e,r,o,a=o){switch(t.name){case\"$\":o(String(process.pid));break;case\"#\":o(String(e.args.length));break;case\"@\":if(t.quoted)for(let n of e.args)a(n);else for(let n of e.args){let u=PS(n);for(let A=0;A<u.length-1;++A)a(u[A]);o(u[u.length-1])}break;case\"*\":{let n=e.args.join(\" \");if(t.quoted)o(n);else for(let u of PS(n))a(u)}break;case\"PPID\":o(String(process.ppid));break;case\"RANDOM\":o(String(Math.floor(Math.random()*32768)));break;default:{let n=parseInt(t.name,10),u,A=Number.isFinite(n);if(A?n>=0&&n<e.args.length&&(u=e.args[n]):Object.hasOwn(r.variables,t.name)?u=r.variables[t.name]:Object.hasOwn(r.environment,t.name)&&(u=r.environment[t.name]),typeof u<\"u\"&&t.alternativeValue?u=(await Dg(t.alternativeValue,e,r)).join(\" \"):typeof u>\"u\"&&(t.defaultValue?u=(await Dg(t.defaultValue,e,r)).join(\" \"):t.alternativeValue&&(u=\"\")),typeof u>\"u\")throw A?new ll(`Unbound argument #${n}`):new ll(`Unbound variable \"${t.name}\"`);if(t.quoted)o(u);else{let p=PS(u);for(let E=0;E<p.length-1;++E)a(p[E]);let h=p[p.length-1];typeof h<\"u\"&&o(h)}}break}}async function d1(t,e,r){if(t.type===\"number\"){if(Number.isInteger(t.value))return t.value;throw new Error(`Invalid number: \"${t.value}\", only integers are allowed`)}else if(t.type===\"variable\"){let o=[];await hce({...t,quoted:!0},e,r,n=>o.push(n));let a=Number(o.join(\" \"));return Number.isNaN(a)?d1({type:\"variable\",name:o.join(\" \")},e,r):d1({type:\"number\",value:a},e,r)}else return Eot[t.type](await d1(t.left,e,r),await d1(t.right,e,r))}async function Dg(t,e,r){let o=new Map,a=[],n=[],u=E=>{n.push(E)},A=()=>{n.length>0&&a.push(n.join(\"\")),n=[]},p=E=>{u(E),A()},h=(E,I,v)=>{let x=JSON.stringify({type:E,fd:I}),C=o.get(x);typeof C>\"u\"&&o.set(x,C=[]),C.push(v)};for(let E of t){let I=!1;switch(E.type){case\"redirection\":{let v=await Dg(E.args,e,r);for(let x of v)h(E.subtype,E.fd,x)}break;case\"argument\":for(let v of E.segments)switch(v.type){case\"text\":u(v.text);break;case\"glob\":u(v.pattern),I=!0;break;case\"shell\":{let x=await yot(v.shell,e,r);if(v.quoted)u(x);else{let C=PS(x);for(let R=0;R<C.length-1;++R)p(C[R]);u(C[C.length-1])}}break;case\"variable\":await hce(v,e,r,u,p);break;case\"arithmetic\":u(String(await d1(v.arithmetic,e,r)));break}break}if(A(),I){let v=a.pop();if(typeof v>\"u\")throw new Error(\"Assertion failed: Expected a glob pattern to have been set\");let x=await e.glob.match(v,{cwd:r.cwd,baseFs:e.baseFs});if(x.length===0){let C=Z4(v)?\". Note: Brace expansion of arbitrary strings isn't currently supported. For more details, please read this issue: https://github.com/yarnpkg/berry/issues/22\":\"\";throw new ll(`No matches found: \"${v}\"${C}`)}for(let C of x.sort())p(C)}}if(o.size>0){let E=[];for(let[I,v]of o.entries())E.splice(E.length,0,I,String(v.length),...v);a.splice(0,0,\"__ysh_set_redirects\",...E,\"--\")}return a}function m1(t,e,r){e.builtins.has(t[0])||(t=[\"command\",...t]);let o=ue.fromPortablePath(r.cwd),a=r.environment;typeof a.PWD<\"u\"&&(a={...a,PWD:o});let[n,...u]=t;if(n===\"command\")return ice(u[0],u.slice(1),e,{cwd:o,env:a});let A=e.builtins.get(n);if(typeof A>\"u\")throw new Error(`Assertion failed: A builtin should exist for \"${n}\"`);return sce(async({stdin:p,stdout:h,stderr:E})=>{let{stdin:I,stdout:v,stderr:x}=r;r.stdin=p,r.stdout=h,r.stderr=E;try{return await A(u,e,r)}finally{r.stdin=I,r.stdout=v,r.stderr=x}})}function Cot(t,e,r){return o=>{let a=new cl.PassThrough,n=SS(t,e,bS(r,{stdin:a}));return{stdin:a,promise:n}}}function wot(t,e,r){return o=>{let a=new cl.PassThrough,n=SS(t,e,r);return{stdin:a,promise:n}}}function cce(t,e,r,o){if(e.length===0)return t;{let a;do a=String(Math.random());while(Object.hasOwn(o.procedures,a));return o.procedures={...o.procedures},o.procedures[a]=t,m1([...e,\"__ysh_run_procedure\",a],r,o)}}async function uce(t,e,r){let o=t,a=null,n=null;for(;o;){let u=o.then?{...r}:r,A;switch(o.type){case\"command\":{let p=await Dg(o.args,e,r),h=await lce(o.envs,e,r);A=o.envs.length?m1(p,e,bS(u,{environment:h})):m1(p,e,u)}break;case\"subshell\":{let p=await Dg(o.args,e,r),h=Cot(o.subshell,e,u);A=cce(h,p,e,u)}break;case\"group\":{let p=await Dg(o.args,e,r),h=wot(o.group,e,u);A=cce(h,p,e,u)}break;case\"envs\":{let p=await lce(o.envs,e,r);u.environment={...u.environment,...p},A=m1([\"true\"],e,u)}break}if(typeof A>\"u\")throw new Error(\"Assertion failed: An action should have been generated\");if(a===null)n=DS(A,{stdin:new Jl(u.stdin),stdout:new Jl(u.stdout),stderr:new Jl(u.stderr)});else{if(n===null)throw new Error(\"Assertion failed: The execution pipeline should have been setup\");switch(a){case\"|\":n=n.pipeTo(A,1);break;case\"|&\":n=n.pipeTo(A,3);break}}o.then?(a=o.then.type,o=o.then.chain):o=null}if(n===null)throw new Error(\"Assertion failed: The execution pipeline should have been setup\");return await n.run()}async function Iot(t,e,r,{background:o=!1}={}){function a(n){let u=[\"#2E86AB\",\"#A23B72\",\"#F18F01\",\"#C73E1D\",\"#CCE2A3\"],A=u[n%u.length];return Ace.default.hex(A)}if(o){let n=r.nextBackgroundJobIndex++,u=a(n),A=`[${n}]`,p=u(A),{stdout:h,stderr:E}=oce(r,{prefix:p});return r.backgroundJobs.push(uce(t,e,bS(r,{stdout:h,stderr:E})).catch(I=>E.write(`${I.message}\n`)).finally(()=>{r.stdout.isTTY&&r.stdout.write(`Job ${p}, '${u(Jd(t))}' has ended\n`)})),0}return await uce(t,e,r)}async function Bot(t,e,r,{background:o=!1}={}){let a,n=A=>{a=A,r.variables[\"?\"]=String(A)},u=async A=>{try{return await Iot(A.chain,e,r,{background:o&&typeof A.then>\"u\"})}catch(p){if(!(p instanceof ll))throw p;return r.stderr.write(`${p.message}\n`),1}};for(n(await u(t));t.then;){if(r.exitCode!==null)return r.exitCode;switch(t.then.type){case\"&&\":a===0&&n(await u(t.then.line));break;case\"||\":a!==0&&n(await u(t.then.line));break;default:throw new Error(`Assertion failed: Unsupported command type: \"${t.then.type}\"`)}t=t.then.line}return a}async function SS(t,e,r){let o=r.backgroundJobs;r.backgroundJobs=[];let a=0;for(let{command:n,type:u}of t){if(a=await Bot(n,e,r,{background:u===\"&\"}),r.exitCode!==null)return r.exitCode;r.variables[\"?\"]=String(a)}return await Promise.all(r.backgroundJobs),r.backgroundJobs=o,a}function gce(t){switch(t.type){case\"variable\":return t.name===\"@\"||t.name===\"#\"||t.name===\"*\"||Number.isFinite(parseInt(t.name,10))||\"defaultValue\"in t&&!!t.defaultValue&&t.defaultValue.some(e=>y1(e))||\"alternativeValue\"in t&&!!t.alternativeValue&&t.alternativeValue.some(e=>y1(e));case\"arithmetic\":return iU(t.arithmetic);case\"shell\":return sU(t.shell);default:return!1}}function y1(t){switch(t.type){case\"redirection\":return t.args.some(e=>y1(e));case\"argument\":return t.segments.some(e=>gce(e));default:throw new Error(`Assertion failed: Unsupported argument type: \"${t.type}\"`)}}function iU(t){switch(t.type){case\"variable\":return gce(t);case\"number\":return!1;default:return iU(t.left)||iU(t.right)}}function sU(t){return t.some(({command:e})=>{for(;e;){let r=e.chain;for(;r;){let o;switch(r.type){case\"subshell\":o=sU(r.subshell);break;case\"command\":o=r.envs.some(a=>a.args.some(n=>y1(n)))||r.args.some(a=>y1(a));break}if(o)return!0;if(!r.then)break;r=r.then.chain}if(!e.then)break;e=e.then.line}return!1})}async function cy(t,e=[],{baseFs:r=new Tn,builtins:o={},cwd:a=ue.toPortablePath(process.cwd()),env:n=process.env,stdin:u=process.stdin,stdout:A=process.stdout,stderr:p=process.stderr,variables:h={},glob:E=vS}={}){let I={};for(let[C,R]of Object.entries(n))typeof R<\"u\"&&(I[C]=R);let v=new Map(mot);for(let[C,R]of Object.entries(o))v.set(C,R);u===null&&(u=new cl.PassThrough,u.end());let x=CD(t,E);if(!sU(x)&&x.length>0&&e.length>0){let{command:C}=x[x.length-1];for(;C.then;)C=C.then.line;let R=C.chain;for(;R.then;)R=R.then.chain;R.type===\"command\"&&(R.args=R.args.concat(e.map(L=>({type:\"argument\",segments:[{type:\"text\",text:L}]}))))}return await SS(x,{args:e,baseFs:r,builtins:v,initialStdin:u,initialStdout:A,initialStderr:p,glob:E},{cwd:a,environment:I,exitCode:null,procedures:{},stdin:u,stdout:A,stderr:p,variables:Object.assign({},h,{\"?\":0}),nextBackgroundJobIndex:1,backgroundJobs:[]})}var Ace,fce,cl,pce,mot,Eot,g1=Et(()=>{Pt();Nl();Ace=Ze(pN()),fce=ve(\"os\"),cl=ve(\"stream\"),pce=ve(\"timers/promises\");zle();Jle();ece();nU();nU();mot=new Map([[\"cd\",async([t=(0,fce.homedir)(),...e],r,o)=>{let a=V.resolve(o.cwd,ue.toPortablePath(t));if(!(await r.baseFs.statPromise(a).catch(u=>{throw u.code===\"ENOENT\"?new ll(`cd: no such file or directory: ${t}`):u})).isDirectory())throw new ll(`cd: not a directory: ${t}`);return o.cwd=a,0}],[\"pwd\",async(t,e,r)=>(r.stdout.write(`${ue.fromPortablePath(r.cwd)}\n`),0)],[\":\",async(t,e,r)=>0],[\"true\",async(t,e,r)=>0],[\"false\",async(t,e,r)=>1],[\"exit\",async([t,...e],r,o)=>o.exitCode=parseInt(t??o.variables[\"?\"],10)],[\"echo\",async(t,e,r)=>(r.stdout.write(`${t.join(\" \")}\n`),0)],[\"sleep\",async([t],e,r)=>{if(typeof t>\"u\")throw new ll(\"sleep: missing operand\");let o=Number(t);if(Number.isNaN(o))throw new ll(`sleep: invalid time interval '${t}'`);return await(0,pce.setTimeout)(1e3*o,0)}],[\"__ysh_run_procedure\",async(t,e,r)=>{let o=r.procedures[t[0]];return await DS(o,{stdin:new Jl(r.stdin),stdout:new Jl(r.stdout),stderr:new Jl(r.stderr)}).run()}],[\"__ysh_set_redirects\",async(t,e,r)=>{let o=r.stdin,a=r.stdout,n=r.stderr,u=[],A=[],p=[],h=0;for(;t[h]!==\"--\";){let I=t[h++],{type:v,fd:x}=JSON.parse(I),C=z=>{switch(x){case null:case 0:u.push(z);break;default:throw new Error(`Unsupported file descriptor: \"${x}\"`)}},R=z=>{switch(x){case null:case 1:A.push(z);break;case 2:p.push(z);break;default:throw new Error(`Unsupported file descriptor: \"${x}\"`)}},L=Number(t[h++]),U=h+L;for(let z=h;z<U;++h,++z)switch(v){case\"<\":C(()=>e.baseFs.createReadStream(V.resolve(r.cwd,ue.toPortablePath(t[z]))));break;case\"<<<\":C(()=>{let te=new cl.PassThrough;return process.nextTick(()=>{te.write(`${t[z]}\n`),te.end()}),te});break;case\"<&\":C(()=>ace(Number(t[z]),1,r));break;case\">\":case\">>\":{let te=V.resolve(r.cwd,ue.toPortablePath(t[z]));R(te===\"/dev/null\"?new cl.Writable({autoDestroy:!0,emitClose:!0,write(ae,le,ce){setImmediate(ce)}}):e.baseFs.createWriteStream(te,v===\">>\"?{flags:\"a\"}:void 0))}break;case\">&\":R(ace(Number(t[z]),2,r));break;default:throw new Error(`Assertion failed: Unsupported redirection type: \"${v}\"`)}}if(u.length>0){let I=new cl.PassThrough;o=I;let v=x=>{if(x===u.length)I.end();else{let C=u[x]();C.pipe(I,{end:!1}),C.on(\"end\",()=>{v(x+1)})}};v(0)}if(A.length>0){let I=new cl.PassThrough;a=I;for(let v of A)I.pipe(v)}if(p.length>0){let I=new cl.PassThrough;n=I;for(let v of p)I.pipe(v)}let E=await DS(m1(t.slice(h+1),e,r),{stdin:new Jl(o),stdout:new Jl(a),stderr:new Jl(n)}).run();return await Promise.all(A.map(I=>new Promise((v,x)=>{I.on(\"error\",C=>{x(C)}),I.on(\"close\",()=>{v()}),I.end()}))),await Promise.all(p.map(I=>new Promise((v,x)=>{I.on(\"error\",C=>{x(C)}),I.on(\"close\",()=>{v()}),I.end()}))),E}]]);Eot={addition:(t,e)=>t+e,subtraction:(t,e)=>t-e,multiplication:(t,e)=>t*e,division:(t,e)=>Math.trunc(t/e)}});var xS=_((l4t,dce)=>{function vot(t,e){for(var r=-1,o=t==null?0:t.length,a=Array(o);++r<o;)a[r]=e(t[r],r,t);return a}dce.exports=vot});var Ice=_((c4t,wce)=>{var mce=lg(),Dot=xS(),Pot=Hl(),bot=Ym(),Sot=1/0,yce=mce?mce.prototype:void 0,Ece=yce?yce.toString:void 0;function Cce(t){if(typeof t==\"string\")return t;if(Pot(t))return Dot(t,Cce)+\"\";if(bot(t))return Ece?Ece.call(t):\"\";var e=t+\"\";return e==\"0\"&&1/t==-Sot?\"-0\":e}wce.exports=Cce});var C1=_((u4t,Bce)=>{var xot=Ice();function kot(t){return t==null?\"\":xot(t)}Bce.exports=kot});var oU=_((A4t,vce)=>{function Qot(t,e,r){var o=-1,a=t.length;e<0&&(e=-e>a?0:a+e),r=r>a?a:r,r<0&&(r+=a),a=e>r?0:r-e>>>0,e>>>=0;for(var n=Array(a);++o<a;)n[o]=t[o+e];return n}vce.exports=Qot});var Pce=_((f4t,Dce)=>{var Fot=oU();function Rot(t,e,r){var o=t.length;return r=r===void 0?o:r,!e&&r>=o?t:Fot(t,e,r)}Dce.exports=Rot});var aU=_((p4t,bce)=>{var Tot=\"\\\\ud800-\\\\udfff\",Not=\"\\\\u0300-\\\\u036f\",Lot=\"\\\\ufe20-\\\\ufe2f\",Mot=\"\\\\u20d0-\\\\u20ff\",Oot=Not+Lot+Mot,Uot=\"\\\\ufe0e\\\\ufe0f\",_ot=\"\\\\u200d\",Hot=RegExp(\"[\"+_ot+Tot+Oot+Uot+\"]\");function qot(t){return Hot.test(t)}bce.exports=qot});var xce=_((h4t,Sce)=>{function jot(t){return t.split(\"\")}Sce.exports=jot});var Mce=_((g4t,Lce)=>{var kce=\"\\\\ud800-\\\\udfff\",Got=\"\\\\u0300-\\\\u036f\",Yot=\"\\\\ufe20-\\\\ufe2f\",Wot=\"\\\\u20d0-\\\\u20ff\",Kot=Got+Yot+Wot,Vot=\"\\\\ufe0e\\\\ufe0f\",zot=\"[\"+kce+\"]\",lU=\"[\"+Kot+\"]\",cU=\"\\\\ud83c[\\\\udffb-\\\\udfff]\",Jot=\"(?:\"+lU+\"|\"+cU+\")\",Qce=\"[^\"+kce+\"]\",Fce=\"(?:\\\\ud83c[\\\\udde6-\\\\uddff]){2}\",Rce=\"[\\\\ud800-\\\\udbff][\\\\udc00-\\\\udfff]\",Xot=\"\\\\u200d\",Tce=Jot+\"?\",Nce=\"[\"+Vot+\"]?\",Zot=\"(?:\"+Xot+\"(?:\"+[Qce,Fce,Rce].join(\"|\")+\")\"+Nce+Tce+\")*\",$ot=Nce+Tce+Zot,eat=\"(?:\"+[Qce+lU+\"?\",lU,Fce,Rce,zot].join(\"|\")+\")\",tat=RegExp(cU+\"(?=\"+cU+\")|\"+eat+$ot,\"g\");function rat(t){return t.match(tat)||[]}Lce.exports=rat});var Uce=_((d4t,Oce)=>{var nat=xce(),iat=aU(),sat=Mce();function oat(t){return iat(t)?sat(t):nat(t)}Oce.exports=oat});var Hce=_((m4t,_ce)=>{var aat=Pce(),lat=aU(),cat=Uce(),uat=C1();function Aat(t){return function(e){e=uat(e);var r=lat(e)?cat(e):void 0,o=r?r[0]:e.charAt(0),a=r?aat(r,1).join(\"\"):e.slice(1);return o[t]()+a}}_ce.exports=Aat});var jce=_((y4t,qce)=>{var fat=Hce(),pat=fat(\"toUpperCase\");qce.exports=pat});var uU=_((E4t,Gce)=>{var hat=C1(),gat=jce();function dat(t){return gat(hat(t).toLowerCase())}Gce.exports=dat});var Yce=_((C4t,kS)=>{function mat(){var t=0,e=1,r=2,o=3,a=4,n=5,u=6,A=7,p=8,h=9,E=10,I=11,v=12,x=13,C=14,R=15,L=16,U=17,z=0,te=1,ae=2,le=3,ce=4;function Ce(g,me){return 55296<=g.charCodeAt(me)&&g.charCodeAt(me)<=56319&&56320<=g.charCodeAt(me+1)&&g.charCodeAt(me+1)<=57343}function de(g,me){me===void 0&&(me=0);var we=g.charCodeAt(me);if(55296<=we&&we<=56319&&me<g.length-1){var Ae=we,ne=g.charCodeAt(me+1);return 56320<=ne&&ne<=57343?(Ae-55296)*1024+(ne-56320)+65536:Ae}if(56320<=we&&we<=57343&&me>=1){var Ae=g.charCodeAt(me-1),ne=we;return 55296<=Ae&&Ae<=56319?(Ae-55296)*1024+(ne-56320)+65536:ne}return we}function Be(g,me,we){var Ae=[g].concat(me).concat([we]),ne=Ae[Ae.length-2],Z=we,xe=Ae.lastIndexOf(C);if(xe>1&&Ae.slice(1,xe).every(function(H){return H==o})&&[o,x,U].indexOf(g)==-1)return ae;var Ne=Ae.lastIndexOf(a);if(Ne>0&&Ae.slice(1,Ne).every(function(H){return H==a})&&[v,a].indexOf(ne)==-1)return Ae.filter(function(H){return H==a}).length%2==1?le:ce;if(ne==t&&Z==e)return z;if(ne==r||ne==t||ne==e)return Z==C&&me.every(function(H){return H==o})?ae:te;if(Z==r||Z==t||Z==e)return te;if(ne==u&&(Z==u||Z==A||Z==h||Z==E))return z;if((ne==h||ne==A)&&(Z==A||Z==p))return z;if((ne==E||ne==p)&&Z==p)return z;if(Z==o||Z==R)return z;if(Z==n)return z;if(ne==v)return z;var ht=Ae.indexOf(o)!=-1?Ae.lastIndexOf(o)-1:Ae.length-2;return[x,U].indexOf(Ae[ht])!=-1&&Ae.slice(ht+1,-1).every(function(H){return H==o})&&Z==C||ne==R&&[L,U].indexOf(Z)!=-1?z:me.indexOf(a)!=-1?ae:ne==a&&Z==a?z:te}this.nextBreak=function(g,me){if(me===void 0&&(me=0),me<0)return 0;if(me>=g.length-1)return g.length;for(var we=Ee(de(g,me)),Ae=[],ne=me+1;ne<g.length;ne++)if(!Ce(g,ne-1)){var Z=Ee(de(g,ne));if(Be(we,Ae,Z))return ne;Ae.push(Z)}return g.length},this.splitGraphemes=function(g){for(var me=[],we=0,Ae;(Ae=this.nextBreak(g,we))<g.length;)me.push(g.slice(we,Ae)),we=Ae;return we<g.length&&me.push(g.slice(we)),me},this.iterateGraphemes=function(g){var me=0,we={next:function(){var Ae,ne;return(ne=this.nextBreak(g,me))<g.length?(Ae=g.slice(me,ne),me=ne,{value:Ae,done:!1}):me<g.length?(Ae=g.slice(me),me=g.length,{value:Ae,done:!1}):{value:void 0,done:!0}}.bind(this)};return typeof Symbol<\"u\"&&Symbol.iterator&&(we[Symbol.iterator]=function(){return we}),we},this.countGraphemes=function(g){for(var me=0,we=0,Ae;(Ae=this.nextBreak(g,we))<g.length;)we=Ae,me++;return we<g.length&&me++,me};function Ee(g){return 1536<=g&&g<=1541||g==1757||g==1807||g==2274||g==3406||g==69821||70082<=g&&g<=70083||g==72250||72326<=g&&g<=72329||g==73030?v:g==13?t:g==10?e:0<=g&&g<=9||11<=g&&g<=12||14<=g&&g<=31||127<=g&&g<=159||g==173||g==1564||g==6158||g==8203||8206<=g&&g<=8207||g==8232||g==8233||8234<=g&&g<=8238||8288<=g&&g<=8292||g==8293||8294<=g&&g<=8303||55296<=g&&g<=57343||g==65279||65520<=g&&g<=65528||65529<=g&&g<=65531||113824<=g&&g<=113827||119155<=g&&g<=119162||g==917504||g==917505||917506<=g&&g<=917535||917632<=g&&g<=917759||918e3<=g&&g<=921599?r:768<=g&&g<=879||1155<=g&&g<=1159||1160<=g&&g<=1161||1425<=g&&g<=1469||g==1471||1473<=g&&g<=1474||1476<=g&&g<=1477||g==1479||1552<=g&&g<=1562||1611<=g&&g<=1631||g==1648||1750<=g&&g<=1756||1759<=g&&g<=1764||1767<=g&&g<=1768||1770<=g&&g<=1773||g==1809||1840<=g&&g<=1866||1958<=g&&g<=1968||2027<=g&&g<=2035||2070<=g&&g<=2073||2075<=g&&g<=2083||2085<=g&&g<=2087||2089<=g&&g<=2093||2137<=g&&g<=2139||2260<=g&&g<=2273||2275<=g&&g<=2306||g==2362||g==2364||2369<=g&&g<=2376||g==2381||2385<=g&&g<=2391||2402<=g&&g<=2403||g==2433||g==2492||g==2494||2497<=g&&g<=2500||g==2509||g==2519||2530<=g&&g<=2531||2561<=g&&g<=2562||g==2620||2625<=g&&g<=2626||2631<=g&&g<=2632||2635<=g&&g<=2637||g==2641||2672<=g&&g<=2673||g==2677||2689<=g&&g<=2690||g==2748||2753<=g&&g<=2757||2759<=g&&g<=2760||g==2765||2786<=g&&g<=2787||2810<=g&&g<=2815||g==2817||g==2876||g==2878||g==2879||2881<=g&&g<=2884||g==2893||g==2902||g==2903||2914<=g&&g<=2915||g==2946||g==3006||g==3008||g==3021||g==3031||g==3072||3134<=g&&g<=3136||3142<=g&&g<=3144||3146<=g&&g<=3149||3157<=g&&g<=3158||3170<=g&&g<=3171||g==3201||g==3260||g==3263||g==3266||g==3270||3276<=g&&g<=3277||3285<=g&&g<=3286||3298<=g&&g<=3299||3328<=g&&g<=3329||3387<=g&&g<=3388||g==3390||3393<=g&&g<=3396||g==3405||g==3415||3426<=g&&g<=3427||g==3530||g==3535||3538<=g&&g<=3540||g==3542||g==3551||g==3633||3636<=g&&g<=3642||3655<=g&&g<=3662||g==3761||3764<=g&&g<=3769||3771<=g&&g<=3772||3784<=g&&g<=3789||3864<=g&&g<=3865||g==3893||g==3895||g==3897||3953<=g&&g<=3966||3968<=g&&g<=3972||3974<=g&&g<=3975||3981<=g&&g<=3991||3993<=g&&g<=4028||g==4038||4141<=g&&g<=4144||4146<=g&&g<=4151||4153<=g&&g<=4154||4157<=g&&g<=4158||4184<=g&&g<=4185||4190<=g&&g<=4192||4209<=g&&g<=4212||g==4226||4229<=g&&g<=4230||g==4237||g==4253||4957<=g&&g<=4959||5906<=g&&g<=5908||5938<=g&&g<=5940||5970<=g&&g<=5971||6002<=g&&g<=6003||6068<=g&&g<=6069||6071<=g&&g<=6077||g==6086||6089<=g&&g<=6099||g==6109||6155<=g&&g<=6157||6277<=g&&g<=6278||g==6313||6432<=g&&g<=6434||6439<=g&&g<=6440||g==6450||6457<=g&&g<=6459||6679<=g&&g<=6680||g==6683||g==6742||6744<=g&&g<=6750||g==6752||g==6754||6757<=g&&g<=6764||6771<=g&&g<=6780||g==6783||6832<=g&&g<=6845||g==6846||6912<=g&&g<=6915||g==6964||6966<=g&&g<=6970||g==6972||g==6978||7019<=g&&g<=7027||7040<=g&&g<=7041||7074<=g&&g<=7077||7080<=g&&g<=7081||7083<=g&&g<=7085||g==7142||7144<=g&&g<=7145||g==7149||7151<=g&&g<=7153||7212<=g&&g<=7219||7222<=g&&g<=7223||7376<=g&&g<=7378||7380<=g&&g<=7392||7394<=g&&g<=7400||g==7405||g==7412||7416<=g&&g<=7417||7616<=g&&g<=7673||7675<=g&&g<=7679||g==8204||8400<=g&&g<=8412||8413<=g&&g<=8416||g==8417||8418<=g&&g<=8420||8421<=g&&g<=8432||11503<=g&&g<=11505||g==11647||11744<=g&&g<=11775||12330<=g&&g<=12333||12334<=g&&g<=12335||12441<=g&&g<=12442||g==42607||42608<=g&&g<=42610||42612<=g&&g<=42621||42654<=g&&g<=42655||42736<=g&&g<=42737||g==43010||g==43014||g==43019||43045<=g&&g<=43046||43204<=g&&g<=43205||43232<=g&&g<=43249||43302<=g&&g<=43309||43335<=g&&g<=43345||43392<=g&&g<=43394||g==43443||43446<=g&&g<=43449||g==43452||g==43493||43561<=g&&g<=43566||43569<=g&&g<=43570||43573<=g&&g<=43574||g==43587||g==43596||g==43644||g==43696||43698<=g&&g<=43700||43703<=g&&g<=43704||43710<=g&&g<=43711||g==43713||43756<=g&&g<=43757||g==43766||g==44005||g==44008||g==44013||g==64286||65024<=g&&g<=65039||65056<=g&&g<=65071||65438<=g&&g<=65439||g==66045||g==66272||66422<=g&&g<=66426||68097<=g&&g<=68099||68101<=g&&g<=68102||68108<=g&&g<=68111||68152<=g&&g<=68154||g==68159||68325<=g&&g<=68326||g==69633||69688<=g&&g<=69702||69759<=g&&g<=69761||69811<=g&&g<=69814||69817<=g&&g<=69818||69888<=g&&g<=69890||69927<=g&&g<=69931||69933<=g&&g<=69940||g==70003||70016<=g&&g<=70017||70070<=g&&g<=70078||70090<=g&&g<=70092||70191<=g&&g<=70193||g==70196||70198<=g&&g<=70199||g==70206||g==70367||70371<=g&&g<=70378||70400<=g&&g<=70401||g==70460||g==70462||g==70464||g==70487||70502<=g&&g<=70508||70512<=g&&g<=70516||70712<=g&&g<=70719||70722<=g&&g<=70724||g==70726||g==70832||70835<=g&&g<=70840||g==70842||g==70845||70847<=g&&g<=70848||70850<=g&&g<=70851||g==71087||71090<=g&&g<=71093||71100<=g&&g<=71101||71103<=g&&g<=71104||71132<=g&&g<=71133||71219<=g&&g<=71226||g==71229||71231<=g&&g<=71232||g==71339||g==71341||71344<=g&&g<=71349||g==71351||71453<=g&&g<=71455||71458<=g&&g<=71461||71463<=g&&g<=71467||72193<=g&&g<=72198||72201<=g&&g<=72202||72243<=g&&g<=72248||72251<=g&&g<=72254||g==72263||72273<=g&&g<=72278||72281<=g&&g<=72283||72330<=g&&g<=72342||72344<=g&&g<=72345||72752<=g&&g<=72758||72760<=g&&g<=72765||g==72767||72850<=g&&g<=72871||72874<=g&&g<=72880||72882<=g&&g<=72883||72885<=g&&g<=72886||73009<=g&&g<=73014||g==73018||73020<=g&&g<=73021||73023<=g&&g<=73029||g==73031||92912<=g&&g<=92916||92976<=g&&g<=92982||94095<=g&&g<=94098||113821<=g&&g<=113822||g==119141||119143<=g&&g<=119145||119150<=g&&g<=119154||119163<=g&&g<=119170||119173<=g&&g<=119179||119210<=g&&g<=119213||119362<=g&&g<=119364||121344<=g&&g<=121398||121403<=g&&g<=121452||g==121461||g==121476||121499<=g&&g<=121503||121505<=g&&g<=121519||122880<=g&&g<=122886||122888<=g&&g<=122904||122907<=g&&g<=122913||122915<=g&&g<=122916||122918<=g&&g<=122922||125136<=g&&g<=125142||125252<=g&&g<=125258||917536<=g&&g<=917631||917760<=g&&g<=917999?o:127462<=g&&g<=127487?a:g==2307||g==2363||2366<=g&&g<=2368||2377<=g&&g<=2380||2382<=g&&g<=2383||2434<=g&&g<=2435||2495<=g&&g<=2496||2503<=g&&g<=2504||2507<=g&&g<=2508||g==2563||2622<=g&&g<=2624||g==2691||2750<=g&&g<=2752||g==2761||2763<=g&&g<=2764||2818<=g&&g<=2819||g==2880||2887<=g&&g<=2888||2891<=g&&g<=2892||g==3007||3009<=g&&g<=3010||3014<=g&&g<=3016||3018<=g&&g<=3020||3073<=g&&g<=3075||3137<=g&&g<=3140||3202<=g&&g<=3203||g==3262||3264<=g&&g<=3265||3267<=g&&g<=3268||3271<=g&&g<=3272||3274<=g&&g<=3275||3330<=g&&g<=3331||3391<=g&&g<=3392||3398<=g&&g<=3400||3402<=g&&g<=3404||3458<=g&&g<=3459||3536<=g&&g<=3537||3544<=g&&g<=3550||3570<=g&&g<=3571||g==3635||g==3763||3902<=g&&g<=3903||g==3967||g==4145||4155<=g&&g<=4156||4182<=g&&g<=4183||g==4228||g==6070||6078<=g&&g<=6085||6087<=g&&g<=6088||6435<=g&&g<=6438||6441<=g&&g<=6443||6448<=g&&g<=6449||6451<=g&&g<=6456||6681<=g&&g<=6682||g==6741||g==6743||6765<=g&&g<=6770||g==6916||g==6965||g==6971||6973<=g&&g<=6977||6979<=g&&g<=6980||g==7042||g==7073||7078<=g&&g<=7079||g==7082||g==7143||7146<=g&&g<=7148||g==7150||7154<=g&&g<=7155||7204<=g&&g<=7211||7220<=g&&g<=7221||g==7393||7410<=g&&g<=7411||g==7415||43043<=g&&g<=43044||g==43047||43136<=g&&g<=43137||43188<=g&&g<=43203||43346<=g&&g<=43347||g==43395||43444<=g&&g<=43445||43450<=g&&g<=43451||43453<=g&&g<=43456||43567<=g&&g<=43568||43571<=g&&g<=43572||g==43597||g==43755||43758<=g&&g<=43759||g==43765||44003<=g&&g<=44004||44006<=g&&g<=44007||44009<=g&&g<=44010||g==44012||g==69632||g==69634||g==69762||69808<=g&&g<=69810||69815<=g&&g<=69816||g==69932||g==70018||70067<=g&&g<=70069||70079<=g&&g<=70080||70188<=g&&g<=70190||70194<=g&&g<=70195||g==70197||70368<=g&&g<=70370||70402<=g&&g<=70403||g==70463||70465<=g&&g<=70468||70471<=g&&g<=70472||70475<=g&&g<=70477||70498<=g&&g<=70499||70709<=g&&g<=70711||70720<=g&&g<=70721||g==70725||70833<=g&&g<=70834||g==70841||70843<=g&&g<=70844||g==70846||g==70849||71088<=g&&g<=71089||71096<=g&&g<=71099||g==71102||71216<=g&&g<=71218||71227<=g&&g<=71228||g==71230||g==71340||71342<=g&&g<=71343||g==71350||71456<=g&&g<=71457||g==71462||72199<=g&&g<=72200||g==72249||72279<=g&&g<=72280||g==72343||g==72751||g==72766||g==72873||g==72881||g==72884||94033<=g&&g<=94078||g==119142||g==119149?n:4352<=g&&g<=4447||43360<=g&&g<=43388?u:4448<=g&&g<=4519||55216<=g&&g<=55238?A:4520<=g&&g<=4607||55243<=g&&g<=55291?p:g==44032||g==44060||g==44088||g==44116||g==44144||g==44172||g==44200||g==44228||g==44256||g==44284||g==44312||g==44340||g==44368||g==44396||g==44424||g==44452||g==44480||g==44508||g==44536||g==44564||g==44592||g==44620||g==44648||g==44676||g==44704||g==44732||g==44760||g==44788||g==44816||g==44844||g==44872||g==44900||g==44928||g==44956||g==44984||g==45012||g==45040||g==45068||g==45096||g==45124||g==45152||g==45180||g==45208||g==45236||g==45264||g==45292||g==45320||g==45348||g==45376||g==45404||g==45432||g==45460||g==45488||g==45516||g==45544||g==45572||g==45600||g==45628||g==45656||g==45684||g==45712||g==45740||g==45768||g==45796||g==45824||g==45852||g==45880||g==45908||g==45936||g==45964||g==45992||g==46020||g==46048||g==46076||g==46104||g==46132||g==46160||g==46188||g==46216||g==46244||g==46272||g==46300||g==46328||g==46356||g==46384||g==46412||g==46440||g==46468||g==46496||g==46524||g==46552||g==46580||g==46608||g==46636||g==46664||g==46692||g==46720||g==46748||g==46776||g==46804||g==46832||g==46860||g==46888||g==46916||g==46944||g==46972||g==47e3||g==47028||g==47056||g==47084||g==47112||g==47140||g==47168||g==47196||g==47224||g==47252||g==47280||g==47308||g==47336||g==47364||g==47392||g==47420||g==47448||g==47476||g==47504||g==47532||g==47560||g==47588||g==47616||g==47644||g==47672||g==47700||g==47728||g==47756||g==47784||g==47812||g==47840||g==47868||g==47896||g==47924||g==47952||g==47980||g==48008||g==48036||g==48064||g==48092||g==48120||g==48148||g==48176||g==48204||g==48232||g==48260||g==48288||g==48316||g==48344||g==48372||g==48400||g==48428||g==48456||g==48484||g==48512||g==48540||g==48568||g==48596||g==48624||g==48652||g==48680||g==48708||g==48736||g==48764||g==48792||g==48820||g==48848||g==48876||g==48904||g==48932||g==48960||g==48988||g==49016||g==49044||g==49072||g==49100||g==49128||g==49156||g==49184||g==49212||g==49240||g==49268||g==49296||g==49324||g==49352||g==49380||g==49408||g==49436||g==49464||g==49492||g==49520||g==49548||g==49576||g==49604||g==49632||g==49660||g==49688||g==49716||g==49744||g==49772||g==49800||g==49828||g==49856||g==49884||g==49912||g==49940||g==49968||g==49996||g==50024||g==50052||g==50080||g==50108||g==50136||g==50164||g==50192||g==50220||g==50248||g==50276||g==50304||g==50332||g==50360||g==50388||g==50416||g==50444||g==50472||g==50500||g==50528||g==50556||g==50584||g==50612||g==50640||g==50668||g==50696||g==50724||g==50752||g==50780||g==50808||g==50836||g==50864||g==50892||g==50920||g==50948||g==50976||g==51004||g==51032||g==51060||g==51088||g==51116||g==51144||g==51172||g==51200||g==51228||g==51256||g==51284||g==51312||g==51340||g==51368||g==51396||g==51424||g==51452||g==51480||g==51508||g==51536||g==51564||g==51592||g==51620||g==51648||g==51676||g==51704||g==51732||g==51760||g==51788||g==51816||g==51844||g==51872||g==51900||g==51928||g==51956||g==51984||g==52012||g==52040||g==52068||g==52096||g==52124||g==52152||g==52180||g==52208||g==52236||g==52264||g==52292||g==52320||g==52348||g==52376||g==52404||g==52432||g==52460||g==52488||g==52516||g==52544||g==52572||g==52600||g==52628||g==52656||g==52684||g==52712||g==52740||g==52768||g==52796||g==52824||g==52852||g==52880||g==52908||g==52936||g==52964||g==52992||g==53020||g==53048||g==53076||g==53104||g==53132||g==53160||g==53188||g==53216||g==53244||g==53272||g==53300||g==53328||g==53356||g==53384||g==53412||g==53440||g==53468||g==53496||g==53524||g==53552||g==53580||g==53608||g==53636||g==53664||g==53692||g==53720||g==53748||g==53776||g==53804||g==53832||g==53860||g==53888||g==53916||g==53944||g==53972||g==54e3||g==54028||g==54056||g==54084||g==54112||g==54140||g==54168||g==54196||g==54224||g==54252||g==54280||g==54308||g==54336||g==54364||g==54392||g==54420||g==54448||g==54476||g==54504||g==54532||g==54560||g==54588||g==54616||g==54644||g==54672||g==54700||g==54728||g==54756||g==54784||g==54812||g==54840||g==54868||g==54896||g==54924||g==54952||g==54980||g==55008||g==55036||g==55064||g==55092||g==55120||g==55148||g==55176?h:44033<=g&&g<=44059||44061<=g&&g<=44087||44089<=g&&g<=44115||44117<=g&&g<=44143||44145<=g&&g<=44171||44173<=g&&g<=44199||44201<=g&&g<=44227||44229<=g&&g<=44255||44257<=g&&g<=44283||44285<=g&&g<=44311||44313<=g&&g<=44339||44341<=g&&g<=44367||44369<=g&&g<=44395||44397<=g&&g<=44423||44425<=g&&g<=44451||44453<=g&&g<=44479||44481<=g&&g<=44507||44509<=g&&g<=44535||44537<=g&&g<=44563||44565<=g&&g<=44591||44593<=g&&g<=44619||44621<=g&&g<=44647||44649<=g&&g<=44675||44677<=g&&g<=44703||44705<=g&&g<=44731||44733<=g&&g<=44759||44761<=g&&g<=44787||44789<=g&&g<=44815||44817<=g&&g<=44843||44845<=g&&g<=44871||44873<=g&&g<=44899||44901<=g&&g<=44927||44929<=g&&g<=44955||44957<=g&&g<=44983||44985<=g&&g<=45011||45013<=g&&g<=45039||45041<=g&&g<=45067||45069<=g&&g<=45095||45097<=g&&g<=45123||45125<=g&&g<=45151||45153<=g&&g<=45179||45181<=g&&g<=45207||45209<=g&&g<=45235||45237<=g&&g<=45263||45265<=g&&g<=45291||45293<=g&&g<=45319||45321<=g&&g<=45347||45349<=g&&g<=45375||45377<=g&&g<=45403||45405<=g&&g<=45431||45433<=g&&g<=45459||45461<=g&&g<=45487||45489<=g&&g<=45515||45517<=g&&g<=45543||45545<=g&&g<=45571||45573<=g&&g<=45599||45601<=g&&g<=45627||45629<=g&&g<=45655||45657<=g&&g<=45683||45685<=g&&g<=45711||45713<=g&&g<=45739||45741<=g&&g<=45767||45769<=g&&g<=45795||45797<=g&&g<=45823||45825<=g&&g<=45851||45853<=g&&g<=45879||45881<=g&&g<=45907||45909<=g&&g<=45935||45937<=g&&g<=45963||45965<=g&&g<=45991||45993<=g&&g<=46019||46021<=g&&g<=46047||46049<=g&&g<=46075||46077<=g&&g<=46103||46105<=g&&g<=46131||46133<=g&&g<=46159||46161<=g&&g<=46187||46189<=g&&g<=46215||46217<=g&&g<=46243||46245<=g&&g<=46271||46273<=g&&g<=46299||46301<=g&&g<=46327||46329<=g&&g<=46355||46357<=g&&g<=46383||46385<=g&&g<=46411||46413<=g&&g<=46439||46441<=g&&g<=46467||46469<=g&&g<=46495||46497<=g&&g<=46523||46525<=g&&g<=46551||46553<=g&&g<=46579||46581<=g&&g<=46607||46609<=g&&g<=46635||46637<=g&&g<=46663||46665<=g&&g<=46691||46693<=g&&g<=46719||46721<=g&&g<=46747||46749<=g&&g<=46775||46777<=g&&g<=46803||46805<=g&&g<=46831||46833<=g&&g<=46859||46861<=g&&g<=46887||46889<=g&&g<=46915||46917<=g&&g<=46943||46945<=g&&g<=46971||46973<=g&&g<=46999||47001<=g&&g<=47027||47029<=g&&g<=47055||47057<=g&&g<=47083||47085<=g&&g<=47111||47113<=g&&g<=47139||47141<=g&&g<=47167||47169<=g&&g<=47195||47197<=g&&g<=47223||47225<=g&&g<=47251||47253<=g&&g<=47279||47281<=g&&g<=47307||47309<=g&&g<=47335||47337<=g&&g<=47363||47365<=g&&g<=47391||47393<=g&&g<=47419||47421<=g&&g<=47447||47449<=g&&g<=47475||47477<=g&&g<=47503||47505<=g&&g<=47531||47533<=g&&g<=47559||47561<=g&&g<=47587||47589<=g&&g<=47615||47617<=g&&g<=47643||47645<=g&&g<=47671||47673<=g&&g<=47699||47701<=g&&g<=47727||47729<=g&&g<=47755||47757<=g&&g<=47783||47785<=g&&g<=47811||47813<=g&&g<=47839||47841<=g&&g<=47867||47869<=g&&g<=47895||47897<=g&&g<=47923||47925<=g&&g<=47951||47953<=g&&g<=47979||47981<=g&&g<=48007||48009<=g&&g<=48035||48037<=g&&g<=48063||48065<=g&&g<=48091||48093<=g&&g<=48119||48121<=g&&g<=48147||48149<=g&&g<=48175||48177<=g&&g<=48203||48205<=g&&g<=48231||48233<=g&&g<=48259||48261<=g&&g<=48287||48289<=g&&g<=48315||48317<=g&&g<=48343||48345<=g&&g<=48371||48373<=g&&g<=48399||48401<=g&&g<=48427||48429<=g&&g<=48455||48457<=g&&g<=48483||48485<=g&&g<=48511||48513<=g&&g<=48539||48541<=g&&g<=48567||48569<=g&&g<=48595||48597<=g&&g<=48623||48625<=g&&g<=48651||48653<=g&&g<=48679||48681<=g&&g<=48707||48709<=g&&g<=48735||48737<=g&&g<=48763||48765<=g&&g<=48791||48793<=g&&g<=48819||48821<=g&&g<=48847||48849<=g&&g<=48875||48877<=g&&g<=48903||48905<=g&&g<=48931||48933<=g&&g<=48959||48961<=g&&g<=48987||48989<=g&&g<=49015||49017<=g&&g<=49043||49045<=g&&g<=49071||49073<=g&&g<=49099||49101<=g&&g<=49127||49129<=g&&g<=49155||49157<=g&&g<=49183||49185<=g&&g<=49211||49213<=g&&g<=49239||49241<=g&&g<=49267||49269<=g&&g<=49295||49297<=g&&g<=49323||49325<=g&&g<=49351||49353<=g&&g<=49379||49381<=g&&g<=49407||49409<=g&&g<=49435||49437<=g&&g<=49463||49465<=g&&g<=49491||49493<=g&&g<=49519||49521<=g&&g<=49547||49549<=g&&g<=49575||49577<=g&&g<=49603||49605<=g&&g<=49631||49633<=g&&g<=49659||49661<=g&&g<=49687||49689<=g&&g<=49715||49717<=g&&g<=49743||49745<=g&&g<=49771||49773<=g&&g<=49799||49801<=g&&g<=49827||49829<=g&&g<=49855||49857<=g&&g<=49883||49885<=g&&g<=49911||49913<=g&&g<=49939||49941<=g&&g<=49967||49969<=g&&g<=49995||49997<=g&&g<=50023||50025<=g&&g<=50051||50053<=g&&g<=50079||50081<=g&&g<=50107||50109<=g&&g<=50135||50137<=g&&g<=50163||50165<=g&&g<=50191||50193<=g&&g<=50219||50221<=g&&g<=50247||50249<=g&&g<=50275||50277<=g&&g<=50303||50305<=g&&g<=50331||50333<=g&&g<=50359||50361<=g&&g<=50387||50389<=g&&g<=50415||50417<=g&&g<=50443||50445<=g&&g<=50471||50473<=g&&g<=50499||50501<=g&&g<=50527||50529<=g&&g<=50555||50557<=g&&g<=50583||50585<=g&&g<=50611||50613<=g&&g<=50639||50641<=g&&g<=50667||50669<=g&&g<=50695||50697<=g&&g<=50723||50725<=g&&g<=50751||50753<=g&&g<=50779||50781<=g&&g<=50807||50809<=g&&g<=50835||50837<=g&&g<=50863||50865<=g&&g<=50891||50893<=g&&g<=50919||50921<=g&&g<=50947||50949<=g&&g<=50975||50977<=g&&g<=51003||51005<=g&&g<=51031||51033<=g&&g<=51059||51061<=g&&g<=51087||51089<=g&&g<=51115||51117<=g&&g<=51143||51145<=g&&g<=51171||51173<=g&&g<=51199||51201<=g&&g<=51227||51229<=g&&g<=51255||51257<=g&&g<=51283||51285<=g&&g<=51311||51313<=g&&g<=51339||51341<=g&&g<=51367||51369<=g&&g<=51395||51397<=g&&g<=51423||51425<=g&&g<=51451||51453<=g&&g<=51479||51481<=g&&g<=51507||51509<=g&&g<=51535||51537<=g&&g<=51563||51565<=g&&g<=51591||51593<=g&&g<=51619||51621<=g&&g<=51647||51649<=g&&g<=51675||51677<=g&&g<=51703||51705<=g&&g<=51731||51733<=g&&g<=51759||51761<=g&&g<=51787||51789<=g&&g<=51815||51817<=g&&g<=51843||51845<=g&&g<=51871||51873<=g&&g<=51899||51901<=g&&g<=51927||51929<=g&&g<=51955||51957<=g&&g<=51983||51985<=g&&g<=52011||52013<=g&&g<=52039||52041<=g&&g<=52067||52069<=g&&g<=52095||52097<=g&&g<=52123||52125<=g&&g<=52151||52153<=g&&g<=52179||52181<=g&&g<=52207||52209<=g&&g<=52235||52237<=g&&g<=52263||52265<=g&&g<=52291||52293<=g&&g<=52319||52321<=g&&g<=52347||52349<=g&&g<=52375||52377<=g&&g<=52403||52405<=g&&g<=52431||52433<=g&&g<=52459||52461<=g&&g<=52487||52489<=g&&g<=52515||52517<=g&&g<=52543||52545<=g&&g<=52571||52573<=g&&g<=52599||52601<=g&&g<=52627||52629<=g&&g<=52655||52657<=g&&g<=52683||52685<=g&&g<=52711||52713<=g&&g<=52739||52741<=g&&g<=52767||52769<=g&&g<=52795||52797<=g&&g<=52823||52825<=g&&g<=52851||52853<=g&&g<=52879||52881<=g&&g<=52907||52909<=g&&g<=52935||52937<=g&&g<=52963||52965<=g&&g<=52991||52993<=g&&g<=53019||53021<=g&&g<=53047||53049<=g&&g<=53075||53077<=g&&g<=53103||53105<=g&&g<=53131||53133<=g&&g<=53159||53161<=g&&g<=53187||53189<=g&&g<=53215||53217<=g&&g<=53243||53245<=g&&g<=53271||53273<=g&&g<=53299||53301<=g&&g<=53327||53329<=g&&g<=53355||53357<=g&&g<=53383||53385<=g&&g<=53411||53413<=g&&g<=53439||53441<=g&&g<=53467||53469<=g&&g<=53495||53497<=g&&g<=53523||53525<=g&&g<=53551||53553<=g&&g<=53579||53581<=g&&g<=53607||53609<=g&&g<=53635||53637<=g&&g<=53663||53665<=g&&g<=53691||53693<=g&&g<=53719||53721<=g&&g<=53747||53749<=g&&g<=53775||53777<=g&&g<=53803||53805<=g&&g<=53831||53833<=g&&g<=53859||53861<=g&&g<=53887||53889<=g&&g<=53915||53917<=g&&g<=53943||53945<=g&&g<=53971||53973<=g&&g<=53999||54001<=g&&g<=54027||54029<=g&&g<=54055||54057<=g&&g<=54083||54085<=g&&g<=54111||54113<=g&&g<=54139||54141<=g&&g<=54167||54169<=g&&g<=54195||54197<=g&&g<=54223||54225<=g&&g<=54251||54253<=g&&g<=54279||54281<=g&&g<=54307||54309<=g&&g<=54335||54337<=g&&g<=54363||54365<=g&&g<=54391||54393<=g&&g<=54419||54421<=g&&g<=54447||54449<=g&&g<=54475||54477<=g&&g<=54503||54505<=g&&g<=54531||54533<=g&&g<=54559||54561<=g&&g<=54587||54589<=g&&g<=54615||54617<=g&&g<=54643||54645<=g&&g<=54671||54673<=g&&g<=54699||54701<=g&&g<=54727||54729<=g&&g<=54755||54757<=g&&g<=54783||54785<=g&&g<=54811||54813<=g&&g<=54839||54841<=g&&g<=54867||54869<=g&&g<=54895||54897<=g&&g<=54923||54925<=g&&g<=54951||54953<=g&&g<=54979||54981<=g&&g<=55007||55009<=g&&g<=55035||55037<=g&&g<=55063||55065<=g&&g<=55091||55093<=g&&g<=55119||55121<=g&&g<=55147||55149<=g&&g<=55175||55177<=g&&g<=55203?E:g==9757||g==9977||9994<=g&&g<=9997||g==127877||127938<=g&&g<=127940||g==127943||127946<=g&&g<=127948||128066<=g&&g<=128067||128070<=g&&g<=128080||g==128110||128112<=g&&g<=128120||g==128124||128129<=g&&g<=128131||128133<=g&&g<=128135||g==128170||128372<=g&&g<=128373||g==128378||g==128400||128405<=g&&g<=128406||128581<=g&&g<=128583||128587<=g&&g<=128591||g==128675||128692<=g&&g<=128694||g==128704||g==128716||129304<=g&&g<=129308||129310<=g&&g<=129311||g==129318||129328<=g&&g<=129337||129341<=g&&g<=129342||129489<=g&&g<=129501?x:127995<=g&&g<=127999?C:g==8205?R:g==9792||g==9794||9877<=g&&g<=9878||g==9992||g==10084||g==127752||g==127806||g==127859||g==127891||g==127908||g==127912||g==127979||g==127981||g==128139||128187<=g&&g<=128188||g==128295||g==128300||g==128488||g==128640||g==128658?L:128102<=g&&g<=128105?U:I}return this}typeof kS<\"u\"&&kS.exports&&(kS.exports=mat)});var Kce=_((w4t,Wce)=>{var yat=/^(.*?)(\\x1b\\[[^m]+m|\\x1b\\]8;;.*?(\\x1b\\\\|\\u0007))/,QS;function Eat(){if(QS)return QS;if(typeof Intl.Segmenter<\"u\"){let t=new Intl.Segmenter(\"en\",{granularity:\"grapheme\"});return QS=e=>Array.from(t.segment(e),({segment:r})=>r)}else{let t=Yce(),e=new t;return QS=r=>e.splitGraphemes(r)}}Wce.exports=(t,e=0,r=t.length)=>{if(e<0||r<0)throw new RangeError(\"Negative indices aren't supported by this implementation\");let o=r-e,a=\"\",n=0,u=0;for(;t.length>0;){let A=t.match(yat)||[t,t,void 0],p=Eat()(A[1]),h=Math.min(e-n,p.length);p=p.slice(h);let E=Math.min(o-u,p.length);a+=p.slice(0,E).join(\"\"),n+=h,u+=E,typeof A[2]<\"u\"&&(a+=A[2]),t=t.slice(A[0].length)}return a}});var nn,w1=Et(()=>{nn=process.env.YARN_IS_TEST_ENV?\"0.0.0\":\"4.4.1\"});function $ce(t,{configuration:e,json:r}){if(!e.get(\"enableMessageNames\"))return\"\";let a=Ku(t===null?0:t);return!r&&t===null?Ot(e,a,\"grey\"):a}function AU(t,{configuration:e,json:r}){let o=$ce(t,{configuration:e,json:r});if(!o||t===null||t===0)return o;let a=wr[t],n=`https://yarnpkg.com/advanced/error-codes#${o}---${a}`.toLowerCase();return Tm(e,o,n)}async function uy({configuration:t,stdout:e,forceError:r},o){let a=await Rt.start({configuration:t,stdout:e,includeFooter:!1},async n=>{let u=!1,A=!1;for(let p of o)typeof p.option<\"u\"&&(p.error||r?(A=!0,n.reportError(50,p.message)):(u=!0,n.reportWarning(50,p.message)),p.callback?.());u&&!A&&n.reportSeparator()});return a.hasErrors()?a.exitCode():null}var Xce,RS,Cat,Vce,zce,ch,Zce,Jce,wat,Iat,TS,Bat,Rt,I1=Et(()=>{Xce=Ze(Kce()),RS=Ze(X0());$D();Wl();w1();jl();Cat=\"\\xB7\",Vce=[\"\\u280B\",\"\\u2819\",\"\\u2839\",\"\\u2838\",\"\\u283C\",\"\\u2834\",\"\\u2826\",\"\\u2827\",\"\\u2807\",\"\\u280F\"],zce=80,ch=RS.default.GITHUB_ACTIONS?{start:t=>`::group::${t}\n`,end:t=>`::endgroup::\n`}:RS.default.TRAVIS?{start:t=>`travis_fold:start:${t}\n`,end:t=>`travis_fold:end:${t}\n`}:RS.default.GITLAB?{start:t=>`section_start:${Math.floor(Date.now()/1e3)}:${t.toLowerCase().replace(/\\W+/g,\"_\")}[collapsed=true]\\r\\x1B[0K${t}\n`,end:t=>`section_end:${Math.floor(Date.now()/1e3)}:${t.toLowerCase().replace(/\\W+/g,\"_\")}\\r\\x1B[0K`}:null,Zce=ch!==null,Jce=new Date,wat=[\"iTerm.app\",\"Apple_Terminal\",\"WarpTerminal\",\"vscode\"].includes(process.env.TERM_PROGRAM)||!!process.env.WT_SESSION,Iat=t=>t,TS=Iat({patrick:{date:[17,3],chars:[\"\\u{1F340}\",\"\\u{1F331}\"],size:40},simba:{date:[19,7],chars:[\"\\u{1F981}\",\"\\u{1F334}\"],size:40},jack:{date:[31,10],chars:[\"\\u{1F383}\",\"\\u{1F987}\"],size:40},hogsfather:{date:[31,12],chars:[\"\\u{1F389}\",\"\\u{1F384}\"],size:40},default:{chars:[\"=\",\"-\"],size:80}}),Bat=wat&&Object.keys(TS).find(t=>{let e=TS[t];return!(e.date&&(e.date[0]!==Jce.getDate()||e.date[1]!==Jce.getMonth()+1))})||\"default\";Rt=class extends Zs{constructor({configuration:r,stdout:o,json:a=!1,forceSectionAlignment:n=!1,includeNames:u=!0,includePrefix:A=!0,includeFooter:p=!0,includeLogs:h=!a,includeInfos:E=h,includeWarnings:I=h}){super();this.uncommitted=new Set;this.warningCount=0;this.errorCount=0;this.timerFooter=[];this.startTime=Date.now();this.indent=0;this.level=0;this.progress=new Map;this.progressTime=0;this.progressFrame=0;this.progressTimeout=null;this.progressStyle=null;this.progressMaxScaledSize=null;if(TI(this,{configuration:r}),this.configuration=r,this.forceSectionAlignment=n,this.includeNames=u,this.includePrefix=A,this.includeFooter=p,this.includeInfos=E,this.includeWarnings=I,this.json=a,this.stdout=o,r.get(\"enableProgressBars\")&&!a&&o.isTTY&&o.columns>22){let v=r.get(\"progressBarStyle\")||Bat;if(!Object.hasOwn(TS,v))throw new Error(\"Assertion failed: Invalid progress bar style\");this.progressStyle=TS[v];let x=Math.min(this.getRecommendedLength(),80);this.progressMaxScaledSize=Math.floor(this.progressStyle.size*x/80)}}static async start(r,o){let a=new this(r),n=process.emitWarning;process.emitWarning=(u,A)=>{if(typeof u!=\"string\"){let h=u;u=h.message,A=A??h.name}let p=typeof A<\"u\"?`${A}: ${u}`:u;a.reportWarning(0,p)},r.includeVersion&&a.reportInfo(0,fg(r.configuration,`Yarn ${nn}`,2));try{await o(a)}catch(u){a.reportExceptionOnce(u)}finally{await a.finalize(),process.emitWarning=n}return a}hasErrors(){return this.errorCount>0}exitCode(){return this.hasErrors()?1:0}getRecommendedLength(){let o=this.progressStyle!==null?this.stdout.columns-1:super.getRecommendedLength();return Math.max(40,o-12-this.indent*2)}startSectionSync({reportHeader:r,reportFooter:o,skipIfEmpty:a},n){let u={committed:!1,action:()=>{r?.()}};a?this.uncommitted.add(u):(u.action(),u.committed=!0);let A=Date.now();try{return n()}catch(p){throw this.reportExceptionOnce(p),p}finally{let p=Date.now();this.uncommitted.delete(u),u.committed&&o?.(p-A)}}async startSectionPromise({reportHeader:r,reportFooter:o,skipIfEmpty:a},n){let u={committed:!1,action:()=>{r?.()}};a?this.uncommitted.add(u):(u.action(),u.committed=!0);let A=Date.now();try{return await n()}catch(p){throw this.reportExceptionOnce(p),p}finally{let p=Date.now();this.uncommitted.delete(u),u.committed&&o?.(p-A)}}startTimerImpl(r,o,a){return{cb:typeof o==\"function\"?o:a,reportHeader:()=>{this.level+=1,this.reportInfo(null,`\\u250C ${r}`),this.indent+=1,ch!==null&&!this.json&&this.includeInfos&&this.stdout.write(ch.start(r))},reportFooter:A=>{if(this.indent-=1,ch!==null&&!this.json&&this.includeInfos){this.stdout.write(ch.end(r));for(let p of this.timerFooter)p()}this.configuration.get(\"enableTimers\")&&A>200?this.reportInfo(null,`\\u2514 Completed in ${Ot(this.configuration,A,yt.DURATION)}`):this.reportInfo(null,\"\\u2514 Completed\"),this.level-=1},skipIfEmpty:(typeof o==\"function\"?{}:o).skipIfEmpty}}startTimerSync(r,o,a){let{cb:n,...u}=this.startTimerImpl(r,o,a);return this.startSectionSync(u,n)}async startTimerPromise(r,o,a){let{cb:n,...u}=this.startTimerImpl(r,o,a);return this.startSectionPromise(u,n)}reportSeparator(){this.indent===0?this.writeLine(\"\"):this.reportInfo(null,\"\")}reportInfo(r,o){if(!this.includeInfos)return;this.commit();let a=this.formatNameWithHyperlink(r),n=a?`${a}: `:\"\",u=`${this.formatPrefix(n,\"blueBright\")}${o}`;this.json?this.reportJson({type:\"info\",name:r,displayName:this.formatName(r),indent:this.formatIndent(),data:o}):this.writeLine(u)}reportWarning(r,o){if(this.warningCount+=1,!this.includeWarnings)return;this.commit();let a=this.formatNameWithHyperlink(r),n=a?`${a}: `:\"\";this.json?this.reportJson({type:\"warning\",name:r,displayName:this.formatName(r),indent:this.formatIndent(),data:o}):this.writeLine(`${this.formatPrefix(n,\"yellowBright\")}${o}`)}reportError(r,o){this.errorCount+=1,this.timerFooter.push(()=>this.reportErrorImpl(r,o)),this.reportErrorImpl(r,o)}reportErrorImpl(r,o){this.commit();let a=this.formatNameWithHyperlink(r),n=a?`${a}: `:\"\";this.json?this.reportJson({type:\"error\",name:r,displayName:this.formatName(r),indent:this.formatIndent(),data:o}):this.writeLine(`${this.formatPrefix(n,\"redBright\")}${o}`,{truncate:!1})}reportFold(r,o){if(!ch)return;let a=`${ch.start(r)}${o}${ch.end(r)}`;this.timerFooter.push(()=>this.stdout.write(a))}reportProgress(r){if(this.progressStyle===null)return{...Promise.resolve(),stop:()=>{}};if(r.hasProgress&&r.hasTitle)throw new Error(\"Unimplemented: Progress bars can't have both progress and titles.\");let o=!1,a=Promise.resolve().then(async()=>{let u={progress:r.hasProgress?0:void 0,title:r.hasTitle?\"\":void 0};this.progress.set(r,{definition:u,lastScaledSize:r.hasProgress?-1:void 0,lastTitle:void 0}),this.refreshProgress({delta:-1});for await(let{progress:A,title:p}of r)o||u.progress===A&&u.title===p||(u.progress=A,u.title=p,this.refreshProgress());n()}),n=()=>{o||(o=!0,this.progress.delete(r),this.refreshProgress({delta:1}))};return{...a,stop:n}}reportJson(r){this.json&&this.writeLine(`${JSON.stringify(r)}`)}async finalize(){if(!this.includeFooter)return;let r=\"\";this.errorCount>0?r=\"Failed with errors\":this.warningCount>0?r=\"Done with warnings\":r=\"Done\";let o=Ot(this.configuration,Date.now()-this.startTime,yt.DURATION),a=this.configuration.get(\"enableTimers\")?`${r} in ${o}`:r;this.errorCount>0?this.reportError(0,a):this.warningCount>0?this.reportWarning(0,a):this.reportInfo(0,a)}writeLine(r,{truncate:o}={}){this.clearProgress({clear:!0}),this.stdout.write(`${this.truncate(r,{truncate:o})}\n`),this.writeProgress()}writeLines(r,{truncate:o}={}){this.clearProgress({delta:r.length});for(let a of r)this.stdout.write(`${this.truncate(a,{truncate:o})}\n`);this.writeProgress()}commit(){let r=this.uncommitted;this.uncommitted=new Set;for(let o of r)o.committed=!0,o.action()}clearProgress({delta:r=0,clear:o=!1}){this.progressStyle!==null&&this.progress.size+r>0&&(this.stdout.write(`\\x1B[${this.progress.size+r}A`),(r>0||o)&&this.stdout.write(\"\\x1B[0J\"))}writeProgress(){if(this.progressStyle===null||(this.progressTimeout!==null&&clearTimeout(this.progressTimeout),this.progressTimeout=null,this.progress.size===0))return;let r=Date.now();r-this.progressTime>zce&&(this.progressFrame=(this.progressFrame+1)%Vce.length,this.progressTime=r);let o=Vce[this.progressFrame];for(let a of this.progress.values()){let n=\"\";if(typeof a.lastScaledSize<\"u\"){let h=this.progressStyle.chars[0].repeat(a.lastScaledSize),E=this.progressStyle.chars[1].repeat(this.progressMaxScaledSize-a.lastScaledSize);n=` ${h}${E}`}let u=this.formatName(null),A=u?`${u}: `:\"\",p=a.definition.title?` ${a.definition.title}`:\"\";this.stdout.write(`${Ot(this.configuration,\"\\u27A4\",\"blueBright\")} ${A}${o}${n}${p}\n`)}this.progressTimeout=setTimeout(()=>{this.refreshProgress({force:!0})},zce)}refreshProgress({delta:r=0,force:o=!1}={}){let a=!1,n=!1;if(o||this.progress.size===0)a=!0;else for(let u of this.progress.values()){let A=typeof u.definition.progress<\"u\"?Math.trunc(this.progressMaxScaledSize*u.definition.progress):void 0,p=u.lastScaledSize;u.lastScaledSize=A;let h=u.lastTitle;if(u.lastTitle=u.definition.title,A!==p||(n=h!==u.definition.title)){a=!0;break}}a&&(this.clearProgress({delta:r,clear:n}),this.writeProgress())}truncate(r,{truncate:o}={}){return this.progressStyle===null&&(o=!1),typeof o>\"u\"&&(o=this.configuration.get(\"preferTruncatedLines\")),o&&(r=(0,Xce.default)(r,0,this.stdout.columns-1)),r}formatName(r){return this.includeNames?$ce(r,{configuration:this.configuration,json:this.json}):\"\"}formatPrefix(r,o){return this.includePrefix?`${Ot(this.configuration,\"\\u27A4\",o)} ${r}${this.formatIndent()}`:\"\"}formatNameWithHyperlink(r){return this.includeNames?AU(r,{configuration:this.configuration,json:this.json}):\"\"}formatIndent(){return this.level>0||!this.forceSectionAlignment?\"\\u2502 \".repeat(this.indent):`${Cat} `}}});var An={};Vt(An,{PackageManager:()=>rue,detectPackageManager:()=>nue,executePackageAccessibleBinary:()=>lue,executePackageScript:()=>NS,executePackageShellcode:()=>fU,executeWorkspaceAccessibleBinary:()=>kat,executeWorkspaceLifecycleScript:()=>oue,executeWorkspaceScript:()=>sue,getPackageAccessibleBinaries:()=>LS,getWorkspaceAccessibleBinaries:()=>aue,hasPackageScript:()=>bat,hasWorkspaceScript:()=>pU,isNodeScript:()=>hU,makeScriptEnv:()=>B1,maybeExecuteWorkspaceLifecycleScript:()=>xat,prepareExternalProject:()=>Pat});async function uh(t,e,r,o=[]){if(process.platform===\"win32\"){let a=`@goto #_undefined_# 2>NUL || @title %COMSPEC% & @setlocal & @\"${r}\" ${o.map(n=>`\"${n.replace('\"','\"\"')}\"`).join(\" \")} %*`;await oe.writeFilePromise(V.format({dir:t,name:e,ext:\".cmd\"}),a)}await oe.writeFilePromise(V.join(t,e),`#!/bin/sh\nexec \"${r}\" ${o.map(a=>`'${a.replace(/'/g,`'\"'\"'`)}'`).join(\" \")} \"$@\"\n`,{mode:493})}async function nue(t){let e=await Ut.tryFind(t);if(e?.packageManager){let o=Pb(e.packageManager);if(o?.name){let a=`found ${JSON.stringify({packageManager:e.packageManager})} in manifest`,[n]=o.reference.split(\".\");switch(o.name){case\"yarn\":return{packageManagerField:!0,packageManager:Number(n)===1?\"Yarn Classic\":\"Yarn\",reason:a};case\"npm\":return{packageManagerField:!0,packageManager:\"npm\",reason:a};case\"pnpm\":return{packageManagerField:!0,packageManager:\"pnpm\",reason:a}}}}let r;try{r=await oe.readFilePromise(V.join(t,dr.lockfile),\"utf8\")}catch{}return r!==void 0?r.match(/^__metadata:$/m)?{packageManager:\"Yarn\",reason:'\"__metadata\" key found in yarn.lock'}:{packageManager:\"Yarn Classic\",reason:'\"__metadata\" key not found in yarn.lock, must be a Yarn classic lockfile'}:oe.existsSync(V.join(t,\"package-lock.json\"))?{packageManager:\"npm\",reason:`found npm's \"package-lock.json\" lockfile`}:oe.existsSync(V.join(t,\"pnpm-lock.yaml\"))?{packageManager:\"pnpm\",reason:`found pnpm's \"pnpm-lock.yaml\" lockfile`}:null}async function B1({project:t,locator:e,binFolder:r,ignoreCorepack:o,lifecycleScript:a,baseEnv:n=t?.configuration.env??process.env}){let u={};for(let[E,I]of Object.entries(n))typeof I<\"u\"&&(u[E.toLowerCase()!==\"path\"?E:\"PATH\"]=I);let A=ue.fromPortablePath(r);u.BERRY_BIN_FOLDER=ue.fromPortablePath(A);let p=process.env.COREPACK_ROOT&&!o?ue.join(process.env.COREPACK_ROOT,\"dist/yarn.js\"):process.argv[1];if(await Promise.all([uh(r,\"node\",process.execPath),...nn!==null?[uh(r,\"run\",process.execPath,[p,\"run\"]),uh(r,\"yarn\",process.execPath,[p]),uh(r,\"yarnpkg\",process.execPath,[p]),uh(r,\"node-gyp\",process.execPath,[p,\"run\",\"--top-level\",\"node-gyp\"])]:[]]),t&&(u.INIT_CWD=ue.fromPortablePath(t.configuration.startingCwd),u.PROJECT_CWD=ue.fromPortablePath(t.cwd)),u.PATH=u.PATH?`${A}${ue.delimiter}${u.PATH}`:`${A}`,u.npm_execpath=`${A}${ue.sep}yarn`,u.npm_node_execpath=`${A}${ue.sep}node`,e){if(!t)throw new Error(\"Assertion failed: Missing project\");let E=t.tryWorkspaceByLocator(e),I=E?E.manifest.version??\"\":t.storedPackages.get(e.locatorHash).version??\"\";u.npm_package_name=rn(e),u.npm_package_version=I;let v;if(E)v=E.cwd;else{let x=t.storedPackages.get(e.locatorHash);if(!x)throw new Error(`Package for ${qr(t.configuration,e)} not found in the project`);let C=t.configuration.getLinkers(),R={project:t,report:new Rt({stdout:new Ah.PassThrough,configuration:t.configuration})},L=C.find(U=>U.supportsPackage(x,R));if(!L)throw new Error(`The package ${qr(t.configuration,x)} isn't supported by any of the available linkers`);v=await L.findPackageLocation(x,R)}u.npm_package_json=ue.fromPortablePath(V.join(v,dr.manifest))}let h=nn!==null?`yarn/${nn}`:`yarn/${vf(\"@yarnpkg/core\").version}-core`;return u.npm_config_user_agent=`${h} npm/? node/${process.version} ${process.platform} ${process.arch}`,a&&(u.npm_lifecycle_event=a),t&&await t.configuration.triggerHook(E=>E.setupScriptEnvironment,t,u,async(E,I,v)=>await uh(r,E,I,v)),u}async function Pat(t,e,{configuration:r,report:o,workspace:a=null,locator:n=null}){await Dat(async()=>{await oe.mktempPromise(async u=>{let A=V.join(u,\"pack.log\"),p=null,{stdout:h,stderr:E}=r.getSubprocessStreams(A,{prefix:ue.fromPortablePath(t),report:o}),I=n&&Gc(n)?_I(n):n,v=I?ka(I):\"an external project\";h.write(`Packing ${v} from sources\n`);let x=await nue(t),C;x!==null?(h.write(`Using ${x.packageManager} for bootstrap. Reason: ${x.reason}\n\n`),C=x.packageManager):(h.write(`No package manager configuration detected; defaulting to Yarn\n\n`),C=\"Yarn\");let R=C===\"Yarn\"&&!x?.packageManagerField;await oe.mktempPromise(async L=>{let U=await B1({binFolder:L,ignoreCorepack:R}),te=new Map([[\"Yarn Classic\",async()=>{let le=a!==null?[\"workspace\",a]:[],ce=V.join(t,dr.manifest),Ce=await oe.readFilePromise(ce),de=await Wc(process.execPath,[process.argv[1],\"set\",\"version\",\"classic\",\"--only-if-needed\",\"--yarn-path\"],{cwd:t,env:U,stdin:p,stdout:h,stderr:E,end:1});if(de.code!==0)return de.code;await oe.writeFilePromise(ce,Ce),await oe.appendFilePromise(V.join(t,\".npmignore\"),`/.yarn\n`),h.write(`\n`),delete U.NODE_ENV;let Be=await Wc(\"yarn\",[\"install\"],{cwd:t,env:U,stdin:p,stdout:h,stderr:E,end:1});if(Be.code!==0)return Be.code;h.write(`\n`);let Ee=await Wc(\"yarn\",[...le,\"pack\",\"--filename\",ue.fromPortablePath(e)],{cwd:t,env:U,stdin:p,stdout:h,stderr:E});return Ee.code!==0?Ee.code:0}],[\"Yarn\",async()=>{let le=a!==null?[\"workspace\",a]:[];U.YARN_ENABLE_INLINE_BUILDS=\"1\";let ce=V.join(t,dr.lockfile);await oe.existsPromise(ce)||await oe.writeFilePromise(ce,\"\");let Ce=await Wc(\"yarn\",[...le,\"pack\",\"--install-if-needed\",\"--filename\",ue.fromPortablePath(e)],{cwd:t,env:U,stdin:p,stdout:h,stderr:E});return Ce.code!==0?Ce.code:0}],[\"npm\",async()=>{if(a!==null){let me=new Ah.PassThrough,we=km(me);me.pipe(h,{end:!1});let Ae=await Wc(\"npm\",[\"--version\"],{cwd:t,env:U,stdin:p,stdout:me,stderr:E,end:0});if(me.end(),Ae.code!==0)return h.end(),E.end(),Ae.code;let ne=(await we).toString().trim();if(!tA(ne,\">=7.x\")){let Z=eA(null,\"npm\"),xe=In(Z,ne),Ne=In(Z,\">=7.x\");throw new Error(`Workspaces aren't supported by ${jn(r,xe)}; please upgrade to ${jn(r,Ne)} (npm has been detected as the primary package manager for ${Ot(r,t,yt.PATH)})`)}}let le=a!==null?[\"--workspace\",a]:[];delete U.npm_config_user_agent,delete U.npm_config_production,delete U.NPM_CONFIG_PRODUCTION,delete U.NODE_ENV;let ce=await Wc(\"npm\",[\"install\",\"--legacy-peer-deps\"],{cwd:t,env:U,stdin:p,stdout:h,stderr:E,end:1});if(ce.code!==0)return ce.code;let Ce=new Ah.PassThrough,de=km(Ce);Ce.pipe(h);let Be=await Wc(\"npm\",[\"pack\",\"--silent\",...le],{cwd:t,env:U,stdin:p,stdout:Ce,stderr:E});if(Be.code!==0)return Be.code;let Ee=(await de).toString().trim().replace(/^.*\\n/s,\"\"),g=V.resolve(t,ue.toPortablePath(Ee));return await oe.renamePromise(g,e),0}]]).get(C);if(typeof te>\"u\")throw new Error(\"Assertion failed: Unsupported workflow\");let ae=await te();if(!(ae===0||typeof ae>\"u\"))throw oe.detachTemp(u),new Jt(58,`Packing the package failed (exit code ${ae}, logs can be found here: ${Ot(r,A,yt.PATH)})`)})})})}async function bat(t,e,{project:r}){let o=r.tryWorkspaceByLocator(t);if(o!==null)return pU(o,e);let a=r.storedPackages.get(t.locatorHash);if(!a)throw new Error(`Package for ${qr(r.configuration,t)} not found in the project`);return await rA.openPromise(async n=>{let u=r.configuration,A=r.configuration.getLinkers(),p={project:r,report:new Rt({stdout:new Ah.PassThrough,configuration:u})},h=A.find(x=>x.supportsPackage(a,p));if(!h)throw new Error(`The package ${qr(r.configuration,a)} isn't supported by any of the available linkers`);let E=await h.findPackageLocation(a,p),I=new gn(E,{baseFs:n});return(await Ut.find(It.dot,{baseFs:I})).scripts.has(e)})}async function NS(t,e,r,{cwd:o,project:a,stdin:n,stdout:u,stderr:A}){return await oe.mktempPromise(async p=>{let{manifest:h,env:E,cwd:I}=await iue(t,{project:a,binFolder:p,cwd:o,lifecycleScript:e}),v=h.scripts.get(e);if(typeof v>\"u\")return 1;let x=async()=>await cy(v,r,{cwd:I,env:E,stdin:n,stdout:u,stderr:A});return await(await a.configuration.reduceHook(R=>R.wrapScriptExecution,x,a,t,e,{script:v,args:r,cwd:I,env:E,stdin:n,stdout:u,stderr:A}))()})}async function fU(t,e,r,{cwd:o,project:a,stdin:n,stdout:u,stderr:A}){return await oe.mktempPromise(async p=>{let{env:h,cwd:E}=await iue(t,{project:a,binFolder:p,cwd:o});return await cy(e,r,{cwd:E,env:h,stdin:n,stdout:u,stderr:A})})}async function Sat(t,{binFolder:e,cwd:r,lifecycleScript:o}){let a=await B1({project:t.project,locator:t.anchoredLocator,binFolder:e,lifecycleScript:o});return await gU(e,await aue(t)),typeof r>\"u\"&&(r=V.dirname(await oe.realpathPromise(V.join(t.cwd,\"package.json\")))),{manifest:t.manifest,binFolder:e,env:a,cwd:r}}async function iue(t,{project:e,binFolder:r,cwd:o,lifecycleScript:a}){let n=e.tryWorkspaceByLocator(t);if(n!==null)return Sat(n,{binFolder:r,cwd:o,lifecycleScript:a});let u=e.storedPackages.get(t.locatorHash);if(!u)throw new Error(`Package for ${qr(e.configuration,t)} not found in the project`);return await rA.openPromise(async A=>{let p=e.configuration,h=e.configuration.getLinkers(),E={project:e,report:new Rt({stdout:new Ah.PassThrough,configuration:p})},I=h.find(L=>L.supportsPackage(u,E));if(!I)throw new Error(`The package ${qr(e.configuration,u)} isn't supported by any of the available linkers`);let v=await B1({project:e,locator:t,binFolder:r,lifecycleScript:a});await gU(r,await LS(t,{project:e}));let x=await I.findPackageLocation(u,E),C=new gn(x,{baseFs:A}),R=await Ut.find(It.dot,{baseFs:C});return typeof o>\"u\"&&(o=x),{manifest:R,binFolder:r,env:v,cwd:o}})}async function sue(t,e,r,{cwd:o,stdin:a,stdout:n,stderr:u}){return await NS(t.anchoredLocator,e,r,{cwd:o,project:t.project,stdin:a,stdout:n,stderr:u})}function pU(t,e){return t.manifest.scripts.has(e)}async function oue(t,e,{cwd:r,report:o}){let{configuration:a}=t.project,n=null;await oe.mktempPromise(async u=>{let A=V.join(u,`${e}.log`),p=`# This file contains the result of Yarn calling the \"${e}\" lifecycle script inside a workspace (\"${ue.fromPortablePath(t.cwd)}\")\n`,{stdout:h,stderr:E}=a.getSubprocessStreams(A,{report:o,prefix:qr(a,t.anchoredLocator),header:p});o.reportInfo(36,`Calling the \"${e}\" lifecycle script`);let I=await sue(t,e,[],{cwd:r,stdin:n,stdout:h,stderr:E});if(h.end(),E.end(),I!==0)throw oe.detachTemp(u),new Jt(36,`${(0,eue.default)(e)} script failed (exit code ${Ot(a,I,yt.NUMBER)}, logs can be found here: ${Ot(a,A,yt.PATH)}); run ${Ot(a,`yarn ${e}`,yt.CODE)} to investigate`)})}async function xat(t,e,r){pU(t,e)&&await oue(t,e,r)}function hU(t){let e=V.extname(t);if(e.match(/\\.[cm]?[jt]sx?$/))return!0;if(e===\".exe\"||e===\".bin\")return!1;let r=Buffer.alloc(4),o;try{o=oe.openSync(t,\"r\")}catch{return!0}try{oe.readSync(o,r,0,r.length,0)}finally{oe.closeSync(o)}let a=r.readUint32BE();return!(a===3405691582||a===3489328638||a===2135247942||(a&4294901760)===1297743872)}async function LS(t,{project:e}){let r=e.configuration,o=new Map,a=e.storedPackages.get(t.locatorHash);if(!a)throw new Error(`Package for ${qr(r,t)} not found in the project`);let n=new Ah.Writable,u=r.getLinkers(),A={project:e,report:new Rt({configuration:r,stdout:n})},p=new Set([t.locatorHash]);for(let E of a.dependencies.values()){let I=e.storedResolutions.get(E.descriptorHash);if(!I)throw new Error(`Assertion failed: The resolution (${jn(r,E)}) should have been registered`);p.add(I)}let h=await Promise.all(Array.from(p,async E=>{let I=e.storedPackages.get(E);if(!I)throw new Error(`Assertion failed: The package (${E}) should have been registered`);if(I.bin.size===0)return ol.skip;let v=u.find(C=>C.supportsPackage(I,A));if(!v)return ol.skip;let x=null;try{x=await v.findPackageLocation(I,A)}catch(C){if(C.code===\"LOCATOR_NOT_INSTALLED\")return ol.skip;throw C}return{dependency:I,packageLocation:x}}));for(let E of h){if(E===ol.skip)continue;let{dependency:I,packageLocation:v}=E;for(let[x,C]of I.bin){let R=V.resolve(v,C);o.set(x,[I,ue.fromPortablePath(R),hU(R)])}}return o}async function aue(t){return await LS(t.anchoredLocator,{project:t.project})}async function gU(t,e){await Promise.all(Array.from(e,([r,[,o,a]])=>a?uh(t,r,process.execPath,[o]):uh(t,r,o,[])))}async function lue(t,e,r,{cwd:o,project:a,stdin:n,stdout:u,stderr:A,nodeArgs:p=[],packageAccessibleBinaries:h}){h??=await LS(t,{project:a});let E=h.get(e);if(!E)throw new Error(`Binary not found (${e}) for ${qr(a.configuration,t)}`);return await oe.mktempPromise(async I=>{let[,v]=E,x=await B1({project:a,locator:t,binFolder:I});await gU(x.BERRY_BIN_FOLDER,h);let C=hU(ue.toPortablePath(v))?Wc(process.execPath,[...p,v,...r],{cwd:o,env:x,stdin:n,stdout:u,stderr:A}):Wc(v,r,{cwd:o,env:x,stdin:n,stdout:u,stderr:A}),R;try{R=await C}finally{await oe.removePromise(x.BERRY_BIN_FOLDER)}return R.code})}async function kat(t,e,r,{cwd:o,stdin:a,stdout:n,stderr:u,packageAccessibleBinaries:A}){return await lue(t.anchoredLocator,e,r,{project:t.project,cwd:o,stdin:a,stdout:n,stderr:u,packageAccessibleBinaries:A})}var eue,tue,Ah,rue,vat,Dat,dU=Et(()=>{Pt();Pt();nA();g1();eue=Ze(uU()),tue=Ze(eg()),Ah=ve(\"stream\");Gm();Wl();I1();w1();pS();jl();ql();Sf();So();rue=(a=>(a.Yarn1=\"Yarn Classic\",a.Yarn2=\"Yarn\",a.Npm=\"npm\",a.Pnpm=\"pnpm\",a))(rue||{});vat=2,Dat=(0,tue.default)(vat)});var Ay=_((q4t,uue)=>{\"use strict\";var cue=new Map([[\"C\",\"cwd\"],[\"f\",\"file\"],[\"z\",\"gzip\"],[\"P\",\"preservePaths\"],[\"U\",\"unlink\"],[\"strip-components\",\"strip\"],[\"stripComponents\",\"strip\"],[\"keep-newer\",\"newer\"],[\"keepNewer\",\"newer\"],[\"keep-newer-files\",\"newer\"],[\"keepNewerFiles\",\"newer\"],[\"k\",\"keep\"],[\"keep-existing\",\"keep\"],[\"keepExisting\",\"keep\"],[\"m\",\"noMtime\"],[\"no-mtime\",\"noMtime\"],[\"p\",\"preserveOwner\"],[\"L\",\"follow\"],[\"h\",\"follow\"]]);uue.exports=t=>t?Object.keys(t).map(e=>[cue.has(e)?cue.get(e):e,t[e]]).reduce((e,r)=>(e[r[0]]=r[1],e),Object.create(null)):{}});var py=_((j4t,Eue)=>{\"use strict\";var Aue=typeof process==\"object\"&&process?process:{stdout:null,stderr:null},Qat=ve(\"events\"),fue=ve(\"stream\"),pue=ve(\"string_decoder\").StringDecoder,Nf=Symbol(\"EOF\"),Lf=Symbol(\"maybeEmitEnd\"),fh=Symbol(\"emittedEnd\"),MS=Symbol(\"emittingEnd\"),v1=Symbol(\"emittedError\"),OS=Symbol(\"closed\"),hue=Symbol(\"read\"),US=Symbol(\"flush\"),gue=Symbol(\"flushChunk\"),Fa=Symbol(\"encoding\"),Mf=Symbol(\"decoder\"),_S=Symbol(\"flowing\"),D1=Symbol(\"paused\"),fy=Symbol(\"resume\"),Ts=Symbol(\"bufferLength\"),mU=Symbol(\"bufferPush\"),yU=Symbol(\"bufferShift\"),Fo=Symbol(\"objectMode\"),Ro=Symbol(\"destroyed\"),EU=Symbol(\"emitData\"),due=Symbol(\"emitEnd\"),CU=Symbol(\"emitEnd2\"),Of=Symbol(\"async\"),P1=t=>Promise.resolve().then(t),mue=global._MP_NO_ITERATOR_SYMBOLS_!==\"1\",Fat=mue&&Symbol.asyncIterator||Symbol(\"asyncIterator not implemented\"),Rat=mue&&Symbol.iterator||Symbol(\"iterator not implemented\"),Tat=t=>t===\"end\"||t===\"finish\"||t===\"prefinish\",Nat=t=>t instanceof ArrayBuffer||typeof t==\"object\"&&t.constructor&&t.constructor.name===\"ArrayBuffer\"&&t.byteLength>=0,Lat=t=>!Buffer.isBuffer(t)&&ArrayBuffer.isView(t),HS=class{constructor(e,r,o){this.src=e,this.dest=r,this.opts=o,this.ondrain=()=>e[fy](),r.on(\"drain\",this.ondrain)}unpipe(){this.dest.removeListener(\"drain\",this.ondrain)}proxyErrors(){}end(){this.unpipe(),this.opts.end&&this.dest.end()}},wU=class extends HS{unpipe(){this.src.removeListener(\"error\",this.proxyErrors),super.unpipe()}constructor(e,r,o){super(e,r,o),this.proxyErrors=a=>r.emit(\"error\",a),e.on(\"error\",this.proxyErrors)}};Eue.exports=class yue extends fue{constructor(e){super(),this[_S]=!1,this[D1]=!1,this.pipes=[],this.buffer=[],this[Fo]=e&&e.objectMode||!1,this[Fo]?this[Fa]=null:this[Fa]=e&&e.encoding||null,this[Fa]===\"buffer\"&&(this[Fa]=null),this[Of]=e&&!!e.async||!1,this[Mf]=this[Fa]?new pue(this[Fa]):null,this[Nf]=!1,this[fh]=!1,this[MS]=!1,this[OS]=!1,this[v1]=null,this.writable=!0,this.readable=!0,this[Ts]=0,this[Ro]=!1}get bufferLength(){return this[Ts]}get encoding(){return this[Fa]}set encoding(e){if(this[Fo])throw new Error(\"cannot set encoding in objectMode\");if(this[Fa]&&e!==this[Fa]&&(this[Mf]&&this[Mf].lastNeed||this[Ts]))throw new Error(\"cannot change encoding\");this[Fa]!==e&&(this[Mf]=e?new pue(e):null,this.buffer.length&&(this.buffer=this.buffer.map(r=>this[Mf].write(r)))),this[Fa]=e}setEncoding(e){this.encoding=e}get objectMode(){return this[Fo]}set objectMode(e){this[Fo]=this[Fo]||!!e}get async(){return this[Of]}set async(e){this[Of]=this[Of]||!!e}write(e,r,o){if(this[Nf])throw new Error(\"write after end\");if(this[Ro])return this.emit(\"error\",Object.assign(new Error(\"Cannot call write after a stream was destroyed\"),{code:\"ERR_STREAM_DESTROYED\"})),!0;typeof r==\"function\"&&(o=r,r=\"utf8\"),r||(r=\"utf8\");let a=this[Of]?P1:n=>n();return!this[Fo]&&!Buffer.isBuffer(e)&&(Lat(e)?e=Buffer.from(e.buffer,e.byteOffset,e.byteLength):Nat(e)?e=Buffer.from(e):typeof e!=\"string\"&&(this.objectMode=!0)),this[Fo]?(this.flowing&&this[Ts]!==0&&this[US](!0),this.flowing?this.emit(\"data\",e):this[mU](e),this[Ts]!==0&&this.emit(\"readable\"),o&&a(o),this.flowing):e.length?(typeof e==\"string\"&&!(r===this[Fa]&&!this[Mf].lastNeed)&&(e=Buffer.from(e,r)),Buffer.isBuffer(e)&&this[Fa]&&(e=this[Mf].write(e)),this.flowing&&this[Ts]!==0&&this[US](!0),this.flowing?this.emit(\"data\",e):this[mU](e),this[Ts]!==0&&this.emit(\"readable\"),o&&a(o),this.flowing):(this[Ts]!==0&&this.emit(\"readable\"),o&&a(o),this.flowing)}read(e){if(this[Ro])return null;if(this[Ts]===0||e===0||e>this[Ts])return this[Lf](),null;this[Fo]&&(e=null),this.buffer.length>1&&!this[Fo]&&(this.encoding?this.buffer=[this.buffer.join(\"\")]:this.buffer=[Buffer.concat(this.buffer,this[Ts])]);let r=this[hue](e||null,this.buffer[0]);return this[Lf](),r}[hue](e,r){return e===r.length||e===null?this[yU]():(this.buffer[0]=r.slice(e),r=r.slice(0,e),this[Ts]-=e),this.emit(\"data\",r),!this.buffer.length&&!this[Nf]&&this.emit(\"drain\"),r}end(e,r,o){return typeof e==\"function\"&&(o=e,e=null),typeof r==\"function\"&&(o=r,r=\"utf8\"),e&&this.write(e,r),o&&this.once(\"end\",o),this[Nf]=!0,this.writable=!1,(this.flowing||!this[D1])&&this[Lf](),this}[fy](){this[Ro]||(this[D1]=!1,this[_S]=!0,this.emit(\"resume\"),this.buffer.length?this[US]():this[Nf]?this[Lf]():this.emit(\"drain\"))}resume(){return this[fy]()}pause(){this[_S]=!1,this[D1]=!0}get destroyed(){return this[Ro]}get flowing(){return this[_S]}get paused(){return this[D1]}[mU](e){this[Fo]?this[Ts]+=1:this[Ts]+=e.length,this.buffer.push(e)}[yU](){return this.buffer.length&&(this[Fo]?this[Ts]-=1:this[Ts]-=this.buffer[0].length),this.buffer.shift()}[US](e){do;while(this[gue](this[yU]()));!e&&!this.buffer.length&&!this[Nf]&&this.emit(\"drain\")}[gue](e){return e?(this.emit(\"data\",e),this.flowing):!1}pipe(e,r){if(this[Ro])return;let o=this[fh];return r=r||{},e===Aue.stdout||e===Aue.stderr?r.end=!1:r.end=r.end!==!1,r.proxyErrors=!!r.proxyErrors,o?r.end&&e.end():(this.pipes.push(r.proxyErrors?new wU(this,e,r):new HS(this,e,r)),this[Of]?P1(()=>this[fy]()):this[fy]()),e}unpipe(e){let r=this.pipes.find(o=>o.dest===e);r&&(this.pipes.splice(this.pipes.indexOf(r),1),r.unpipe())}addListener(e,r){return this.on(e,r)}on(e,r){let o=super.on(e,r);return e===\"data\"&&!this.pipes.length&&!this.flowing?this[fy]():e===\"readable\"&&this[Ts]!==0?super.emit(\"readable\"):Tat(e)&&this[fh]?(super.emit(e),this.removeAllListeners(e)):e===\"error\"&&this[v1]&&(this[Of]?P1(()=>r.call(this,this[v1])):r.call(this,this[v1])),o}get emittedEnd(){return this[fh]}[Lf](){!this[MS]&&!this[fh]&&!this[Ro]&&this.buffer.length===0&&this[Nf]&&(this[MS]=!0,this.emit(\"end\"),this.emit(\"prefinish\"),this.emit(\"finish\"),this[OS]&&this.emit(\"close\"),this[MS]=!1)}emit(e,r,...o){if(e!==\"error\"&&e!==\"close\"&&e!==Ro&&this[Ro])return;if(e===\"data\")return r?this[Of]?P1(()=>this[EU](r)):this[EU](r):!1;if(e===\"end\")return this[due]();if(e===\"close\"){if(this[OS]=!0,!this[fh]&&!this[Ro])return;let n=super.emit(\"close\");return this.removeAllListeners(\"close\"),n}else if(e===\"error\"){this[v1]=r;let n=super.emit(\"error\",r);return this[Lf](),n}else if(e===\"resume\"){let n=super.emit(\"resume\");return this[Lf](),n}else if(e===\"finish\"||e===\"prefinish\"){let n=super.emit(e);return this.removeAllListeners(e),n}let a=super.emit(e,r,...o);return this[Lf](),a}[EU](e){for(let o of this.pipes)o.dest.write(e)===!1&&this.pause();let r=super.emit(\"data\",e);return this[Lf](),r}[due](){this[fh]||(this[fh]=!0,this.readable=!1,this[Of]?P1(()=>this[CU]()):this[CU]())}[CU](){if(this[Mf]){let r=this[Mf].end();if(r){for(let o of this.pipes)o.dest.write(r);super.emit(\"data\",r)}}for(let r of this.pipes)r.end();let e=super.emit(\"end\");return this.removeAllListeners(\"end\"),e}collect(){let e=[];this[Fo]||(e.dataLength=0);let r=this.promise();return this.on(\"data\",o=>{e.push(o),this[Fo]||(e.dataLength+=o.length)}),r.then(()=>e)}concat(){return this[Fo]?Promise.reject(new Error(\"cannot concat in objectMode\")):this.collect().then(e=>this[Fo]?Promise.reject(new Error(\"cannot concat in objectMode\")):this[Fa]?e.join(\"\"):Buffer.concat(e,e.dataLength))}promise(){return new Promise((e,r)=>{this.on(Ro,()=>r(new Error(\"stream destroyed\"))),this.on(\"error\",o=>r(o)),this.on(\"end\",()=>e())})}[Fat](){return{next:()=>{let r=this.read();if(r!==null)return Promise.resolve({done:!1,value:r});if(this[Nf])return Promise.resolve({done:!0});let o=null,a=null,n=h=>{this.removeListener(\"data\",u),this.removeListener(\"end\",A),a(h)},u=h=>{this.removeListener(\"error\",n),this.removeListener(\"end\",A),this.pause(),o({value:h,done:!!this[Nf]})},A=()=>{this.removeListener(\"error\",n),this.removeListener(\"data\",u),o({done:!0})},p=()=>n(new Error(\"stream destroyed\"));return new Promise((h,E)=>{a=E,o=h,this.once(Ro,p),this.once(\"error\",n),this.once(\"end\",A),this.once(\"data\",u)})}}}[Rat](){return{next:()=>{let r=this.read();return{value:r,done:r===null}}}}destroy(e){return this[Ro]?(e?this.emit(\"error\",e):this.emit(Ro),this):(this[Ro]=!0,this.buffer.length=0,this[Ts]=0,typeof this.close==\"function\"&&!this[OS]&&this.close(),e?this.emit(\"error\",e):this.emit(Ro),this)}static isStream(e){return!!e&&(e instanceof yue||e instanceof fue||e instanceof Qat&&(typeof e.pipe==\"function\"||typeof e.write==\"function\"&&typeof e.end==\"function\"))}}});var wue=_((G4t,Cue)=>{var Mat=ve(\"zlib\").constants||{ZLIB_VERNUM:4736};Cue.exports=Object.freeze(Object.assign(Object.create(null),{Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_VERSION_ERROR:-6,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,DEFLATE:1,INFLATE:2,GZIP:3,GUNZIP:4,DEFLATERAW:5,INFLATERAW:6,UNZIP:7,BROTLI_DECODE:8,BROTLI_ENCODE:9,Z_MIN_WINDOWBITS:8,Z_MAX_WINDOWBITS:15,Z_DEFAULT_WINDOWBITS:15,Z_MIN_CHUNK:64,Z_MAX_CHUNK:1/0,Z_DEFAULT_CHUNK:16384,Z_MIN_MEMLEVEL:1,Z_MAX_MEMLEVEL:9,Z_DEFAULT_MEMLEVEL:8,Z_MIN_LEVEL:-1,Z_MAX_LEVEL:9,Z_DEFAULT_LEVEL:-1,BROTLI_OPERATION_PROCESS:0,BROTLI_OPERATION_FLUSH:1,BROTLI_OPERATION_FINISH:2,BROTLI_OPERATION_EMIT_METADATA:3,BROTLI_MODE_GENERIC:0,BROTLI_MODE_TEXT:1,BROTLI_MODE_FONT:2,BROTLI_DEFAULT_MODE:0,BROTLI_MIN_QUALITY:0,BROTLI_MAX_QUALITY:11,BROTLI_DEFAULT_QUALITY:11,BROTLI_MIN_WINDOW_BITS:10,BROTLI_MAX_WINDOW_BITS:24,BROTLI_LARGE_MAX_WINDOW_BITS:30,BROTLI_DEFAULT_WINDOW:22,BROTLI_MIN_INPUT_BLOCK_BITS:16,BROTLI_MAX_INPUT_BLOCK_BITS:24,BROTLI_PARAM_MODE:0,BROTLI_PARAM_QUALITY:1,BROTLI_PARAM_LGWIN:2,BROTLI_PARAM_LGBLOCK:3,BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING:4,BROTLI_PARAM_SIZE_HINT:5,BROTLI_PARAM_LARGE_WINDOW:6,BROTLI_PARAM_NPOSTFIX:7,BROTLI_PARAM_NDIRECT:8,BROTLI_DECODER_RESULT_ERROR:0,BROTLI_DECODER_RESULT_SUCCESS:1,BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT:2,BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION:0,BROTLI_DECODER_PARAM_LARGE_WINDOW:1,BROTLI_DECODER_NO_ERROR:0,BROTLI_DECODER_SUCCESS:1,BROTLI_DECODER_NEEDS_MORE_INPUT:2,BROTLI_DECODER_NEEDS_MORE_OUTPUT:3,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE:-1,BROTLI_DECODER_ERROR_FORMAT_RESERVED:-2,BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE:-3,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET:-4,BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME:-5,BROTLI_DECODER_ERROR_FORMAT_CL_SPACE:-6,BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE:-7,BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT:-8,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1:-9,BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2:-10,BROTLI_DECODER_ERROR_FORMAT_TRANSFORM:-11,BROTLI_DECODER_ERROR_FORMAT_DICTIONARY:-12,BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS:-13,BROTLI_DECODER_ERROR_FORMAT_PADDING_1:-14,BROTLI_DECODER_ERROR_FORMAT_PADDING_2:-15,BROTLI_DECODER_ERROR_FORMAT_DISTANCE:-16,BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET:-19,BROTLI_DECODER_ERROR_INVALID_ARGUMENTS:-20,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES:-21,BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS:-22,BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP:-25,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1:-26,BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2:-27,BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES:-30,BROTLI_DECODER_ERROR_UNREACHABLE:-31},Mat))});var MU=_(ul=>{\"use strict\";var PU=ve(\"assert\"),ph=ve(\"buffer\").Buffer,vue=ve(\"zlib\"),Pg=ul.constants=wue(),Oat=py(),Iue=ph.concat,bg=Symbol(\"_superWrite\"),gy=class extends Error{constructor(e){super(\"zlib: \"+e.message),this.code=e.code,this.errno=e.errno,this.code||(this.code=\"ZLIB_ERROR\"),this.message=\"zlib: \"+e.message,Error.captureStackTrace(this,this.constructor)}get name(){return\"ZlibError\"}},Uat=Symbol(\"opts\"),b1=Symbol(\"flushFlag\"),Bue=Symbol(\"finishFlushFlag\"),LU=Symbol(\"fullFlushFlag\"),ti=Symbol(\"handle\"),qS=Symbol(\"onError\"),hy=Symbol(\"sawError\"),IU=Symbol(\"level\"),BU=Symbol(\"strategy\"),vU=Symbol(\"ended\"),Y4t=Symbol(\"_defaultFullFlush\"),jS=class extends Oat{constructor(e,r){if(!e||typeof e!=\"object\")throw new TypeError(\"invalid options for ZlibBase constructor\");super(e),this[hy]=!1,this[vU]=!1,this[Uat]=e,this[b1]=e.flush,this[Bue]=e.finishFlush;try{this[ti]=new vue[r](e)}catch(o){throw new gy(o)}this[qS]=o=>{this[hy]||(this[hy]=!0,this.close(),this.emit(\"error\",o))},this[ti].on(\"error\",o=>this[qS](new gy(o))),this.once(\"end\",()=>this.close)}close(){this[ti]&&(this[ti].close(),this[ti]=null,this.emit(\"close\"))}reset(){if(!this[hy])return PU(this[ti],\"zlib binding closed\"),this[ti].reset()}flush(e){this.ended||(typeof e!=\"number\"&&(e=this[LU]),this.write(Object.assign(ph.alloc(0),{[b1]:e})))}end(e,r,o){return e&&this.write(e,r),this.flush(this[Bue]),this[vU]=!0,super.end(null,null,o)}get ended(){return this[vU]}write(e,r,o){if(typeof r==\"function\"&&(o=r,r=\"utf8\"),typeof e==\"string\"&&(e=ph.from(e,r)),this[hy])return;PU(this[ti],\"zlib binding closed\");let a=this[ti]._handle,n=a.close;a.close=()=>{};let u=this[ti].close;this[ti].close=()=>{},ph.concat=h=>h;let A;try{let h=typeof e[b1]==\"number\"?e[b1]:this[b1];A=this[ti]._processChunk(e,h),ph.concat=Iue}catch(h){ph.concat=Iue,this[qS](new gy(h))}finally{this[ti]&&(this[ti]._handle=a,a.close=n,this[ti].close=u,this[ti].removeAllListeners(\"error\"))}this[ti]&&this[ti].on(\"error\",h=>this[qS](new gy(h)));let p;if(A)if(Array.isArray(A)&&A.length>0){p=this[bg](ph.from(A[0]));for(let h=1;h<A.length;h++)p=this[bg](A[h])}else p=this[bg](ph.from(A));return o&&o(),p}[bg](e){return super.write(e)}},Uf=class extends jS{constructor(e,r){e=e||{},e.flush=e.flush||Pg.Z_NO_FLUSH,e.finishFlush=e.finishFlush||Pg.Z_FINISH,super(e,r),this[LU]=Pg.Z_FULL_FLUSH,this[IU]=e.level,this[BU]=e.strategy}params(e,r){if(!this[hy]){if(!this[ti])throw new Error(\"cannot switch params when binding is closed\");if(!this[ti].params)throw new Error(\"not supported in this implementation\");if(this[IU]!==e||this[BU]!==r){this.flush(Pg.Z_SYNC_FLUSH),PU(this[ti],\"zlib binding closed\");let o=this[ti].flush;this[ti].flush=(a,n)=>{this.flush(a),n()};try{this[ti].params(e,r)}finally{this[ti].flush=o}this[ti]&&(this[IU]=e,this[BU]=r)}}}},bU=class extends Uf{constructor(e){super(e,\"Deflate\")}},SU=class extends Uf{constructor(e){super(e,\"Inflate\")}},DU=Symbol(\"_portable\"),xU=class extends Uf{constructor(e){super(e,\"Gzip\"),this[DU]=e&&!!e.portable}[bg](e){return this[DU]?(this[DU]=!1,e[9]=255,super[bg](e)):super[bg](e)}},kU=class extends Uf{constructor(e){super(e,\"Gunzip\")}},QU=class extends Uf{constructor(e){super(e,\"DeflateRaw\")}},FU=class extends Uf{constructor(e){super(e,\"InflateRaw\")}},RU=class extends Uf{constructor(e){super(e,\"Unzip\")}},GS=class extends jS{constructor(e,r){e=e||{},e.flush=e.flush||Pg.BROTLI_OPERATION_PROCESS,e.finishFlush=e.finishFlush||Pg.BROTLI_OPERATION_FINISH,super(e,r),this[LU]=Pg.BROTLI_OPERATION_FLUSH}},TU=class extends GS{constructor(e){super(e,\"BrotliCompress\")}},NU=class extends GS{constructor(e){super(e,\"BrotliDecompress\")}};ul.Deflate=bU;ul.Inflate=SU;ul.Gzip=xU;ul.Gunzip=kU;ul.DeflateRaw=QU;ul.InflateRaw=FU;ul.Unzip=RU;typeof vue.BrotliCompress==\"function\"?(ul.BrotliCompress=TU,ul.BrotliDecompress=NU):ul.BrotliCompress=ul.BrotliDecompress=class{constructor(){throw new Error(\"Brotli is not supported in this version of Node.js\")}}});var dy=_((V4t,Due)=>{var _at=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform;Due.exports=_at!==\"win32\"?t=>t:t=>t&&t.replace(/\\\\/g,\"/\")});var YS=_((J4t,Pue)=>{\"use strict\";var Hat=py(),OU=dy(),UU=Symbol(\"slurp\");Pue.exports=class extends Hat{constructor(e,r,o){switch(super(),this.pause(),this.extended=r,this.globalExtended=o,this.header=e,this.startBlockSize=512*Math.ceil(e.size/512),this.blockRemain=this.startBlockSize,this.remain=e.size,this.type=e.type,this.meta=!1,this.ignore=!1,this.type){case\"File\":case\"OldFile\":case\"Link\":case\"SymbolicLink\":case\"CharacterDevice\":case\"BlockDevice\":case\"Directory\":case\"FIFO\":case\"ContiguousFile\":case\"GNUDumpDir\":break;case\"NextFileHasLongLinkpath\":case\"NextFileHasLongPath\":case\"OldGnuLongPath\":case\"GlobalExtendedHeader\":case\"ExtendedHeader\":case\"OldExtendedHeader\":this.meta=!0;break;default:this.ignore=!0}this.path=OU(e.path),this.mode=e.mode,this.mode&&(this.mode=this.mode&4095),this.uid=e.uid,this.gid=e.gid,this.uname=e.uname,this.gname=e.gname,this.size=e.size,this.mtime=e.mtime,this.atime=e.atime,this.ctime=e.ctime,this.linkpath=OU(e.linkpath),this.uname=e.uname,this.gname=e.gname,r&&this[UU](r),o&&this[UU](o,!0)}write(e){let r=e.length;if(r>this.blockRemain)throw new Error(\"writing more to entry than is appropriate\");let o=this.remain,a=this.blockRemain;return this.remain=Math.max(0,o-r),this.blockRemain=Math.max(0,a-r),this.ignore?!0:o>=r?super.write(e):super.write(e.slice(0,o))}[UU](e,r){for(let o in e)e[o]!==null&&e[o]!==void 0&&!(r&&o===\"path\")&&(this[o]=o===\"path\"||o===\"linkpath\"?OU(e[o]):e[o])}}});var _U=_(WS=>{\"use strict\";WS.name=new Map([[\"0\",\"File\"],[\"\",\"OldFile\"],[\"1\",\"Link\"],[\"2\",\"SymbolicLink\"],[\"3\",\"CharacterDevice\"],[\"4\",\"BlockDevice\"],[\"5\",\"Directory\"],[\"6\",\"FIFO\"],[\"7\",\"ContiguousFile\"],[\"g\",\"GlobalExtendedHeader\"],[\"x\",\"ExtendedHeader\"],[\"A\",\"SolarisACL\"],[\"D\",\"GNUDumpDir\"],[\"I\",\"Inode\"],[\"K\",\"NextFileHasLongLinkpath\"],[\"L\",\"NextFileHasLongPath\"],[\"M\",\"ContinuationFile\"],[\"N\",\"OldGnuLongPath\"],[\"S\",\"SparseFile\"],[\"V\",\"TapeVolumeHeader\"],[\"X\",\"OldExtendedHeader\"]]);WS.code=new Map(Array.from(WS.name).map(t=>[t[1],t[0]]))});var kue=_((Z4t,xue)=>{\"use strict\";var qat=(t,e)=>{if(Number.isSafeInteger(t))t<0?Gat(t,e):jat(t,e);else throw Error(\"cannot encode number outside of javascript safe integer range\");return e},jat=(t,e)=>{e[0]=128;for(var r=e.length;r>1;r--)e[r-1]=t&255,t=Math.floor(t/256)},Gat=(t,e)=>{e[0]=255;var r=!1;t=t*-1;for(var o=e.length;o>1;o--){var a=t&255;t=Math.floor(t/256),r?e[o-1]=bue(a):a===0?e[o-1]=0:(r=!0,e[o-1]=Sue(a))}},Yat=t=>{let e=t[0],r=e===128?Kat(t.slice(1,t.length)):e===255?Wat(t):null;if(r===null)throw Error(\"invalid base256 encoding\");if(!Number.isSafeInteger(r))throw Error(\"parsed number outside of javascript safe integer range\");return r},Wat=t=>{for(var e=t.length,r=0,o=!1,a=e-1;a>-1;a--){var n=t[a],u;o?u=bue(n):n===0?u=n:(o=!0,u=Sue(n)),u!==0&&(r-=u*Math.pow(256,e-a-1))}return r},Kat=t=>{for(var e=t.length,r=0,o=e-1;o>-1;o--){var a=t[o];a!==0&&(r+=a*Math.pow(256,e-o-1))}return r},bue=t=>(255^t)&255,Sue=t=>(255^t)+1&255;xue.exports={encode:qat,parse:Yat}});var yy=_(($4t,Fue)=>{\"use strict\";var HU=_U(),my=ve(\"path\").posix,Que=kue(),qU=Symbol(\"slurp\"),Al=Symbol(\"type\"),YU=class{constructor(e,r,o,a){this.cksumValid=!1,this.needPax=!1,this.nullBlock=!1,this.block=null,this.path=null,this.mode=null,this.uid=null,this.gid=null,this.size=null,this.mtime=null,this.cksum=null,this[Al]=\"0\",this.linkpath=null,this.uname=null,this.gname=null,this.devmaj=0,this.devmin=0,this.atime=null,this.ctime=null,Buffer.isBuffer(e)?this.decode(e,r||0,o,a):e&&this.set(e)}decode(e,r,o,a){if(r||(r=0),!e||!(e.length>=r+512))throw new Error(\"need 512 bytes for header\");if(this.path=Sg(e,r,100),this.mode=hh(e,r+100,8),this.uid=hh(e,r+108,8),this.gid=hh(e,r+116,8),this.size=hh(e,r+124,12),this.mtime=jU(e,r+136,12),this.cksum=hh(e,r+148,12),this[qU](o),this[qU](a,!0),this[Al]=Sg(e,r+156,1),this[Al]===\"\"&&(this[Al]=\"0\"),this[Al]===\"0\"&&this.path.substr(-1)===\"/\"&&(this[Al]=\"5\"),this[Al]===\"5\"&&(this.size=0),this.linkpath=Sg(e,r+157,100),e.slice(r+257,r+265).toString()===\"ustar\\x0000\")if(this.uname=Sg(e,r+265,32),this.gname=Sg(e,r+297,32),this.devmaj=hh(e,r+329,8),this.devmin=hh(e,r+337,8),e[r+475]!==0){let u=Sg(e,r+345,155);this.path=u+\"/\"+this.path}else{let u=Sg(e,r+345,130);u&&(this.path=u+\"/\"+this.path),this.atime=jU(e,r+476,12),this.ctime=jU(e,r+488,12)}let n=8*32;for(let u=r;u<r+148;u++)n+=e[u];for(let u=r+156;u<r+512;u++)n+=e[u];this.cksumValid=n===this.cksum,this.cksum===null&&n===8*32&&(this.nullBlock=!0)}[qU](e,r){for(let o in e)e[o]!==null&&e[o]!==void 0&&!(r&&o===\"path\")&&(this[o]=e[o])}encode(e,r){if(e||(e=this.block=Buffer.alloc(512),r=0),r||(r=0),!(e.length>=r+512))throw new Error(\"need 512 bytes for header\");let o=this.ctime||this.atime?130:155,a=Vat(this.path||\"\",o),n=a[0],u=a[1];this.needPax=a[2],this.needPax=xg(e,r,100,n)||this.needPax,this.needPax=gh(e,r+100,8,this.mode)||this.needPax,this.needPax=gh(e,r+108,8,this.uid)||this.needPax,this.needPax=gh(e,r+116,8,this.gid)||this.needPax,this.needPax=gh(e,r+124,12,this.size)||this.needPax,this.needPax=GU(e,r+136,12,this.mtime)||this.needPax,e[r+156]=this[Al].charCodeAt(0),this.needPax=xg(e,r+157,100,this.linkpath)||this.needPax,e.write(\"ustar\\x0000\",r+257,8),this.needPax=xg(e,r+265,32,this.uname)||this.needPax,this.needPax=xg(e,r+297,32,this.gname)||this.needPax,this.needPax=gh(e,r+329,8,this.devmaj)||this.needPax,this.needPax=gh(e,r+337,8,this.devmin)||this.needPax,this.needPax=xg(e,r+345,o,u)||this.needPax,e[r+475]!==0?this.needPax=xg(e,r+345,155,u)||this.needPax:(this.needPax=xg(e,r+345,130,u)||this.needPax,this.needPax=GU(e,r+476,12,this.atime)||this.needPax,this.needPax=GU(e,r+488,12,this.ctime)||this.needPax);let A=8*32;for(let p=r;p<r+148;p++)A+=e[p];for(let p=r+156;p<r+512;p++)A+=e[p];return this.cksum=A,gh(e,r+148,8,this.cksum),this.cksumValid=!0,this.needPax}set(e){for(let r in e)e[r]!==null&&e[r]!==void 0&&(this[r]=e[r])}get type(){return HU.name.get(this[Al])||this[Al]}get typeKey(){return this[Al]}set type(e){HU.code.has(e)?this[Al]=HU.code.get(e):this[Al]=e}},Vat=(t,e)=>{let o=t,a=\"\",n,u=my.parse(t).root||\".\";if(Buffer.byteLength(o)<100)n=[o,a,!1];else{a=my.dirname(o),o=my.basename(o);do Buffer.byteLength(o)<=100&&Buffer.byteLength(a)<=e?n=[o,a,!1]:Buffer.byteLength(o)>100&&Buffer.byteLength(a)<=e?n=[o.substr(0,99),a,!0]:(o=my.join(my.basename(a),o),a=my.dirname(a));while(a!==u&&!n);n||(n=[t.substr(0,99),\"\",!0])}return n},Sg=(t,e,r)=>t.slice(e,e+r).toString(\"utf8\").replace(/\\0.*/,\"\"),jU=(t,e,r)=>zat(hh(t,e,r)),zat=t=>t===null?null:new Date(t*1e3),hh=(t,e,r)=>t[e]&128?Que.parse(t.slice(e,e+r)):Xat(t,e,r),Jat=t=>isNaN(t)?null:t,Xat=(t,e,r)=>Jat(parseInt(t.slice(e,e+r).toString(\"utf8\").replace(/\\0.*$/,\"\").trim(),8)),Zat={12:8589934591,8:2097151},gh=(t,e,r,o)=>o===null?!1:o>Zat[r]||o<0?(Que.encode(o,t.slice(e,e+r)),!0):($at(t,e,r,o),!1),$at=(t,e,r,o)=>t.write(elt(o,r),e,r,\"ascii\"),elt=(t,e)=>tlt(Math.floor(t).toString(8),e),tlt=(t,e)=>(t.length===e-1?t:new Array(e-t.length-1).join(\"0\")+t+\" \")+\"\\0\",GU=(t,e,r,o)=>o===null?!1:gh(t,e,r,o.getTime()/1e3),rlt=new Array(156).join(\"\\0\"),xg=(t,e,r,o)=>o===null?!1:(t.write(o+rlt,e,r,\"utf8\"),o.length!==Buffer.byteLength(o)||o.length>r);Fue.exports=YU});var KS=_((eUt,Rue)=>{\"use strict\";var nlt=yy(),ilt=ve(\"path\"),S1=class{constructor(e,r){this.atime=e.atime||null,this.charset=e.charset||null,this.comment=e.comment||null,this.ctime=e.ctime||null,this.gid=e.gid||null,this.gname=e.gname||null,this.linkpath=e.linkpath||null,this.mtime=e.mtime||null,this.path=e.path||null,this.size=e.size||null,this.uid=e.uid||null,this.uname=e.uname||null,this.dev=e.dev||null,this.ino=e.ino||null,this.nlink=e.nlink||null,this.global=r||!1}encode(){let e=this.encodeBody();if(e===\"\")return null;let r=Buffer.byteLength(e),o=512*Math.ceil(1+r/512),a=Buffer.allocUnsafe(o);for(let n=0;n<512;n++)a[n]=0;new nlt({path:(\"PaxHeader/\"+ilt.basename(this.path)).slice(0,99),mode:this.mode||420,uid:this.uid||null,gid:this.gid||null,size:r,mtime:this.mtime||null,type:this.global?\"GlobalExtendedHeader\":\"ExtendedHeader\",linkpath:\"\",uname:this.uname||\"\",gname:this.gname||\"\",devmaj:0,devmin:0,atime:this.atime||null,ctime:this.ctime||null}).encode(a),a.write(e,512,r,\"utf8\");for(let n=r+512;n<a.length;n++)a[n]=0;return a}encodeBody(){return this.encodeField(\"path\")+this.encodeField(\"ctime\")+this.encodeField(\"atime\")+this.encodeField(\"dev\")+this.encodeField(\"ino\")+this.encodeField(\"nlink\")+this.encodeField(\"charset\")+this.encodeField(\"comment\")+this.encodeField(\"gid\")+this.encodeField(\"gname\")+this.encodeField(\"linkpath\")+this.encodeField(\"mtime\")+this.encodeField(\"size\")+this.encodeField(\"uid\")+this.encodeField(\"uname\")}encodeField(e){if(this[e]===null||this[e]===void 0)return\"\";let r=this[e]instanceof Date?this[e].getTime()/1e3:this[e],o=\" \"+(e===\"dev\"||e===\"ino\"||e===\"nlink\"?\"SCHILY.\":\"\")+e+\"=\"+r+`\n`,a=Buffer.byteLength(o),n=Math.floor(Math.log(a)/Math.log(10))+1;return a+n>=Math.pow(10,n)&&(n+=1),n+a+o}};S1.parse=(t,e,r)=>new S1(slt(olt(t),e),r);var slt=(t,e)=>e?Object.keys(t).reduce((r,o)=>(r[o]=t[o],r),e):t,olt=t=>t.replace(/\\n$/,\"\").split(`\n`).reduce(alt,Object.create(null)),alt=(t,e)=>{let r=parseInt(e,10);if(r!==Buffer.byteLength(e)+1)return t;e=e.substr((r+\" \").length);let o=e.split(\"=\"),a=o.shift().replace(/^SCHILY\\.(dev|ino|nlink)/,\"$1\");if(!a)return t;let n=o.join(\"=\");return t[a]=/^([A-Z]+\\.)?([mac]|birth|creation)time$/.test(a)?new Date(n*1e3):/^[0-9]+$/.test(n)?+n:n,t};Rue.exports=S1});var Ey=_((tUt,Tue)=>{Tue.exports=t=>{let e=t.length-1,r=-1;for(;e>-1&&t.charAt(e)===\"/\";)r=e,e--;return r===-1?t:t.slice(0,r)}});var VS=_((rUt,Nue)=>{\"use strict\";Nue.exports=t=>class extends t{warn(e,r,o={}){this.file&&(o.file=this.file),this.cwd&&(o.cwd=this.cwd),o.code=r instanceof Error&&r.code||e,o.tarCode=e,!this.strict&&o.recoverable!==!1?(r instanceof Error&&(o=Object.assign(r,o),r=r.message),this.emit(\"warn\",o.tarCode,r,o)):r instanceof Error?this.emit(\"error\",Object.assign(r,o)):this.emit(\"error\",Object.assign(new Error(`${e}: ${r}`),o))}}});var KU=_((iUt,Lue)=>{\"use strict\";var zS=[\"|\",\"<\",\">\",\"?\",\":\"],WU=zS.map(t=>String.fromCharCode(61440+t.charCodeAt(0))),llt=new Map(zS.map((t,e)=>[t,WU[e]])),clt=new Map(WU.map((t,e)=>[t,zS[e]]));Lue.exports={encode:t=>zS.reduce((e,r)=>e.split(r).join(llt.get(r)),t),decode:t=>WU.reduce((e,r)=>e.split(r).join(clt.get(r)),t)}});var VU=_((sUt,Oue)=>{var{isAbsolute:ult,parse:Mue}=ve(\"path\").win32;Oue.exports=t=>{let e=\"\",r=Mue(t);for(;ult(t)||r.root;){let o=t.charAt(0)===\"/\"&&t.slice(0,4)!==\"//?/\"?\"/\":r.root;t=t.substr(o.length),e+=o,r=Mue(t)}return[e,t]}});var _ue=_((oUt,Uue)=>{\"use strict\";Uue.exports=(t,e,r)=>(t&=4095,r&&(t=(t|384)&-19),e&&(t&256&&(t|=64),t&32&&(t|=8),t&4&&(t|=1)),t)});var i3=_((cUt,eAe)=>{\"use strict\";var Kue=py(),Vue=KS(),zue=yy(),oA=ve(\"fs\"),Hue=ve(\"path\"),sA=dy(),Alt=Ey(),Jue=(t,e)=>e?(t=sA(t).replace(/^\\.(\\/|$)/,\"\"),Alt(e)+\"/\"+t):sA(t),flt=16*1024*1024,que=Symbol(\"process\"),jue=Symbol(\"file\"),Gue=Symbol(\"directory\"),JU=Symbol(\"symlink\"),Yue=Symbol(\"hardlink\"),x1=Symbol(\"header\"),JS=Symbol(\"read\"),XU=Symbol(\"lstat\"),XS=Symbol(\"onlstat\"),ZU=Symbol(\"onread\"),$U=Symbol(\"onreadlink\"),e3=Symbol(\"openfile\"),t3=Symbol(\"onopenfile\"),dh=Symbol(\"close\"),ZS=Symbol(\"mode\"),r3=Symbol(\"awaitDrain\"),zU=Symbol(\"ondrain\"),aA=Symbol(\"prefix\"),Wue=Symbol(\"hadError\"),Xue=VS(),plt=KU(),Zue=VU(),$ue=_ue(),$S=Xue(class extends Kue{constructor(e,r){if(r=r||{},super(r),typeof e!=\"string\")throw new TypeError(\"path is required\");this.path=sA(e),this.portable=!!r.portable,this.myuid=process.getuid&&process.getuid()||0,this.myuser=process.env.USER||\"\",this.maxReadSize=r.maxReadSize||flt,this.linkCache=r.linkCache||new Map,this.statCache=r.statCache||new Map,this.preservePaths=!!r.preservePaths,this.cwd=sA(r.cwd||process.cwd()),this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.mtime=r.mtime||null,this.prefix=r.prefix?sA(r.prefix):null,this.fd=null,this.blockLen=null,this.blockRemain=null,this.buf=null,this.offset=null,this.length=null,this.pos=null,this.remain=null,typeof r.onwarn==\"function\"&&this.on(\"warn\",r.onwarn);let o=!1;if(!this.preservePaths){let[a,n]=Zue(this.path);a&&(this.path=n,o=a)}this.win32=!!r.win32||process.platform===\"win32\",this.win32&&(this.path=plt.decode(this.path.replace(/\\\\/g,\"/\")),e=e.replace(/\\\\/g,\"/\")),this.absolute=sA(r.absolute||Hue.resolve(this.cwd,e)),this.path===\"\"&&(this.path=\"./\"),o&&this.warn(\"TAR_ENTRY_INFO\",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.statCache.has(this.absolute)?this[XS](this.statCache.get(this.absolute)):this[XU]()}emit(e,...r){return e===\"error\"&&(this[Wue]=!0),super.emit(e,...r)}[XU](){oA.lstat(this.absolute,(e,r)=>{if(e)return this.emit(\"error\",e);this[XS](r)})}[XS](e){this.statCache.set(this.absolute,e),this.stat=e,e.isFile()||(e.size=0),this.type=glt(e),this.emit(\"stat\",e),this[que]()}[que](){switch(this.type){case\"File\":return this[jue]();case\"Directory\":return this[Gue]();case\"SymbolicLink\":return this[JU]();default:return this.end()}}[ZS](e){return $ue(e,this.type===\"Directory\",this.portable)}[aA](e){return Jue(e,this.prefix)}[x1](){this.type===\"Directory\"&&this.portable&&(this.noMtime=!0),this.header=new zue({path:this[aA](this.path),linkpath:this.type===\"Link\"?this[aA](this.linkpath):this.linkpath,mode:this[ZS](this.stat.mode),uid:this.portable?null:this.stat.uid,gid:this.portable?null:this.stat.gid,size:this.stat.size,mtime:this.noMtime?null:this.mtime||this.stat.mtime,type:this.type,uname:this.portable?null:this.stat.uid===this.myuid?this.myuser:\"\",atime:this.portable?null:this.stat.atime,ctime:this.portable?null:this.stat.ctime}),this.header.encode()&&!this.noPax&&super.write(new Vue({atime:this.portable?null:this.header.atime,ctime:this.portable?null:this.header.ctime,gid:this.portable?null:this.header.gid,mtime:this.noMtime?null:this.mtime||this.header.mtime,path:this[aA](this.path),linkpath:this.type===\"Link\"?this[aA](this.linkpath):this.linkpath,size:this.header.size,uid:this.portable?null:this.header.uid,uname:this.portable?null:this.header.uname,dev:this.portable?null:this.stat.dev,ino:this.portable?null:this.stat.ino,nlink:this.portable?null:this.stat.nlink}).encode()),super.write(this.header.block)}[Gue](){this.path.substr(-1)!==\"/\"&&(this.path+=\"/\"),this.stat.size=0,this[x1](),this.end()}[JU](){oA.readlink(this.absolute,(e,r)=>{if(e)return this.emit(\"error\",e);this[$U](r)})}[$U](e){this.linkpath=sA(e),this[x1](),this.end()}[Yue](e){this.type=\"Link\",this.linkpath=sA(Hue.relative(this.cwd,e)),this.stat.size=0,this[x1](),this.end()}[jue](){if(this.stat.nlink>1){let e=this.stat.dev+\":\"+this.stat.ino;if(this.linkCache.has(e)){let r=this.linkCache.get(e);if(r.indexOf(this.cwd)===0)return this[Yue](r)}this.linkCache.set(e,this.absolute)}if(this[x1](),this.stat.size===0)return this.end();this[e3]()}[e3](){oA.open(this.absolute,\"r\",(e,r)=>{if(e)return this.emit(\"error\",e);this[t3](r)})}[t3](e){if(this.fd=e,this[Wue])return this[dh]();this.blockLen=512*Math.ceil(this.stat.size/512),this.blockRemain=this.blockLen;let r=Math.min(this.blockLen,this.maxReadSize);this.buf=Buffer.allocUnsafe(r),this.offset=0,this.pos=0,this.remain=this.stat.size,this.length=this.buf.length,this[JS]()}[JS](){let{fd:e,buf:r,offset:o,length:a,pos:n}=this;oA.read(e,r,o,a,n,(u,A)=>{if(u)return this[dh](()=>this.emit(\"error\",u));this[ZU](A)})}[dh](e){oA.close(this.fd,e)}[ZU](e){if(e<=0&&this.remain>0){let a=new Error(\"encountered unexpected EOF\");return a.path=this.absolute,a.syscall=\"read\",a.code=\"EOF\",this[dh](()=>this.emit(\"error\",a))}if(e>this.remain){let a=new Error(\"did not encounter expected EOF\");return a.path=this.absolute,a.syscall=\"read\",a.code=\"EOF\",this[dh](()=>this.emit(\"error\",a))}if(e===this.remain)for(let a=e;a<this.length&&e<this.blockRemain;a++)this.buf[a+this.offset]=0,e++,this.remain++;let r=this.offset===0&&e===this.buf.length?this.buf:this.buf.slice(this.offset,this.offset+e);this.write(r)?this[zU]():this[r3](()=>this[zU]())}[r3](e){this.once(\"drain\",e)}write(e){if(this.blockRemain<e.length){let r=new Error(\"writing more data than expected\");return r.path=this.absolute,this.emit(\"error\",r)}return this.remain-=e.length,this.blockRemain-=e.length,this.pos+=e.length,this.offset+=e.length,super.write(e)}[zU](){if(!this.remain)return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),this[dh](e=>e?this.emit(\"error\",e):this.end());this.offset>=this.length&&(this.buf=Buffer.allocUnsafe(Math.min(this.blockRemain,this.buf.length)),this.offset=0),this.length=this.buf.length-this.offset,this[JS]()}}),n3=class extends $S{[XU](){this[XS](oA.lstatSync(this.absolute))}[JU](){this[$U](oA.readlinkSync(this.absolute))}[e3](){this[t3](oA.openSync(this.absolute,\"r\"))}[JS](){let e=!0;try{let{fd:r,buf:o,offset:a,length:n,pos:u}=this,A=oA.readSync(r,o,a,n,u);this[ZU](A),e=!1}finally{if(e)try{this[dh](()=>{})}catch{}}}[r3](e){e()}[dh](e){oA.closeSync(this.fd),e()}},hlt=Xue(class extends Kue{constructor(e,r){r=r||{},super(r),this.preservePaths=!!r.preservePaths,this.portable=!!r.portable,this.strict=!!r.strict,this.noPax=!!r.noPax,this.noMtime=!!r.noMtime,this.readEntry=e,this.type=e.type,this.type===\"Directory\"&&this.portable&&(this.noMtime=!0),this.prefix=r.prefix||null,this.path=sA(e.path),this.mode=this[ZS](e.mode),this.uid=this.portable?null:e.uid,this.gid=this.portable?null:e.gid,this.uname=this.portable?null:e.uname,this.gname=this.portable?null:e.gname,this.size=e.size,this.mtime=this.noMtime?null:r.mtime||e.mtime,this.atime=this.portable?null:e.atime,this.ctime=this.portable?null:e.ctime,this.linkpath=sA(e.linkpath),typeof r.onwarn==\"function\"&&this.on(\"warn\",r.onwarn);let o=!1;if(!this.preservePaths){let[a,n]=Zue(this.path);a&&(this.path=n,o=a)}this.remain=e.size,this.blockRemain=e.startBlockSize,this.header=new zue({path:this[aA](this.path),linkpath:this.type===\"Link\"?this[aA](this.linkpath):this.linkpath,mode:this.mode,uid:this.portable?null:this.uid,gid:this.portable?null:this.gid,size:this.size,mtime:this.noMtime?null:this.mtime,type:this.type,uname:this.portable?null:this.uname,atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime}),o&&this.warn(\"TAR_ENTRY_INFO\",`stripping ${o} from absolute path`,{entry:this,path:o+this.path}),this.header.encode()&&!this.noPax&&super.write(new Vue({atime:this.portable?null:this.atime,ctime:this.portable?null:this.ctime,gid:this.portable?null:this.gid,mtime:this.noMtime?null:this.mtime,path:this[aA](this.path),linkpath:this.type===\"Link\"?this[aA](this.linkpath):this.linkpath,size:this.size,uid:this.portable?null:this.uid,uname:this.portable?null:this.uname,dev:this.portable?null:this.readEntry.dev,ino:this.portable?null:this.readEntry.ino,nlink:this.portable?null:this.readEntry.nlink}).encode()),super.write(this.header.block),e.pipe(this)}[aA](e){return Jue(e,this.prefix)}[ZS](e){return $ue(e,this.type===\"Directory\",this.portable)}write(e){let r=e.length;if(r>this.blockRemain)throw new Error(\"writing more to entry than is appropriate\");return this.blockRemain-=r,super.write(e)}end(){return this.blockRemain&&super.write(Buffer.alloc(this.blockRemain)),super.end()}});$S.Sync=n3;$S.Tar=hlt;var glt=t=>t.isFile()?\"File\":t.isDirectory()?\"Directory\":t.isSymbolicLink()?\"SymbolicLink\":\"Unsupported\";eAe.exports=$S});var lx=_((AUt,aAe)=>{\"use strict\";var ox=class{constructor(e,r){this.path=e||\"./\",this.absolute=r,this.entry=null,this.stat=null,this.readdir=null,this.pending=!1,this.ignore=!1,this.piped=!1}},dlt=py(),mlt=MU(),ylt=YS(),p3=i3(),Elt=p3.Sync,Clt=p3.Tar,wlt=cP(),tAe=Buffer.alloc(1024),rx=Symbol(\"onStat\"),ex=Symbol(\"ended\"),lA=Symbol(\"queue\"),Cy=Symbol(\"current\"),kg=Symbol(\"process\"),tx=Symbol(\"processing\"),rAe=Symbol(\"processJob\"),cA=Symbol(\"jobs\"),s3=Symbol(\"jobDone\"),nx=Symbol(\"addFSEntry\"),nAe=Symbol(\"addTarEntry\"),c3=Symbol(\"stat\"),u3=Symbol(\"readdir\"),ix=Symbol(\"onreaddir\"),sx=Symbol(\"pipe\"),iAe=Symbol(\"entry\"),o3=Symbol(\"entryOpt\"),A3=Symbol(\"writeEntryClass\"),oAe=Symbol(\"write\"),a3=Symbol(\"ondrain\"),ax=ve(\"fs\"),sAe=ve(\"path\"),Ilt=VS(),l3=dy(),h3=Ilt(class extends dlt{constructor(e){super(e),e=e||Object.create(null),this.opt=e,this.file=e.file||\"\",this.cwd=e.cwd||process.cwd(),this.maxReadSize=e.maxReadSize,this.preservePaths=!!e.preservePaths,this.strict=!!e.strict,this.noPax=!!e.noPax,this.prefix=l3(e.prefix||\"\"),this.linkCache=e.linkCache||new Map,this.statCache=e.statCache||new Map,this.readdirCache=e.readdirCache||new Map,this[A3]=p3,typeof e.onwarn==\"function\"&&this.on(\"warn\",e.onwarn),this.portable=!!e.portable,this.zip=null,e.gzip?(typeof e.gzip!=\"object\"&&(e.gzip={}),this.portable&&(e.gzip.portable=!0),this.zip=new mlt.Gzip(e.gzip),this.zip.on(\"data\",r=>super.write(r)),this.zip.on(\"end\",r=>super.end()),this.zip.on(\"drain\",r=>this[a3]()),this.on(\"resume\",r=>this.zip.resume())):this.on(\"drain\",this[a3]),this.noDirRecurse=!!e.noDirRecurse,this.follow=!!e.follow,this.noMtime=!!e.noMtime,this.mtime=e.mtime||null,this.filter=typeof e.filter==\"function\"?e.filter:r=>!0,this[lA]=new wlt,this[cA]=0,this.jobs=+e.jobs||4,this[tx]=!1,this[ex]=!1}[oAe](e){return super.write(e)}add(e){return this.write(e),this}end(e){return e&&this.write(e),this[ex]=!0,this[kg](),this}write(e){if(this[ex])throw new Error(\"write after end\");return e instanceof ylt?this[nAe](e):this[nx](e),this.flowing}[nAe](e){let r=l3(sAe.resolve(this.cwd,e.path));if(!this.filter(e.path,e))e.resume();else{let o=new ox(e.path,r,!1);o.entry=new Clt(e,this[o3](o)),o.entry.on(\"end\",a=>this[s3](o)),this[cA]+=1,this[lA].push(o)}this[kg]()}[nx](e){let r=l3(sAe.resolve(this.cwd,e));this[lA].push(new ox(e,r)),this[kg]()}[c3](e){e.pending=!0,this[cA]+=1;let r=this.follow?\"stat\":\"lstat\";ax[r](e.absolute,(o,a)=>{e.pending=!1,this[cA]-=1,o?this.emit(\"error\",o):this[rx](e,a)})}[rx](e,r){this.statCache.set(e.absolute,r),e.stat=r,this.filter(e.path,r)||(e.ignore=!0),this[kg]()}[u3](e){e.pending=!0,this[cA]+=1,ax.readdir(e.absolute,(r,o)=>{if(e.pending=!1,this[cA]-=1,r)return this.emit(\"error\",r);this[ix](e,o)})}[ix](e,r){this.readdirCache.set(e.absolute,r),e.readdir=r,this[kg]()}[kg](){if(!this[tx]){this[tx]=!0;for(let e=this[lA].head;e!==null&&this[cA]<this.jobs;e=e.next)if(this[rAe](e.value),e.value.ignore){let r=e.next;this[lA].removeNode(e),e.next=r}this[tx]=!1,this[ex]&&!this[lA].length&&this[cA]===0&&(this.zip?this.zip.end(tAe):(super.write(tAe),super.end()))}}get[Cy](){return this[lA]&&this[lA].head&&this[lA].head.value}[s3](e){this[lA].shift(),this[cA]-=1,this[kg]()}[rAe](e){if(!e.pending){if(e.entry){e===this[Cy]&&!e.piped&&this[sx](e);return}if(e.stat||(this.statCache.has(e.absolute)?this[rx](e,this.statCache.get(e.absolute)):this[c3](e)),!!e.stat&&!e.ignore&&!(!this.noDirRecurse&&e.stat.isDirectory()&&!e.readdir&&(this.readdirCache.has(e.absolute)?this[ix](e,this.readdirCache.get(e.absolute)):this[u3](e),!e.readdir))){if(e.entry=this[iAe](e),!e.entry){e.ignore=!0;return}e===this[Cy]&&!e.piped&&this[sx](e)}}}[o3](e){return{onwarn:(r,o,a)=>this.warn(r,o,a),noPax:this.noPax,cwd:this.cwd,absolute:e.absolute,preservePaths:this.preservePaths,maxReadSize:this.maxReadSize,strict:this.strict,portable:this.portable,linkCache:this.linkCache,statCache:this.statCache,noMtime:this.noMtime,mtime:this.mtime,prefix:this.prefix}}[iAe](e){this[cA]+=1;try{return new this[A3](e.path,this[o3](e)).on(\"end\",()=>this[s3](e)).on(\"error\",r=>this.emit(\"error\",r))}catch(r){this.emit(\"error\",r)}}[a3](){this[Cy]&&this[Cy].entry&&this[Cy].entry.resume()}[sx](e){e.piped=!0,e.readdir&&e.readdir.forEach(a=>{let n=e.path,u=n===\"./\"?\"\":n.replace(/\\/*$/,\"/\");this[nx](u+a)});let r=e.entry,o=this.zip;o?r.on(\"data\",a=>{o.write(a)||r.pause()}):r.on(\"data\",a=>{super.write(a)||r.pause()})}pause(){return this.zip&&this.zip.pause(),super.pause()}}),f3=class extends h3{constructor(e){super(e),this[A3]=Elt}pause(){}resume(){}[c3](e){let r=this.follow?\"statSync\":\"lstatSync\";this[rx](e,ax[r](e.absolute))}[u3](e,r){this[ix](e,ax.readdirSync(e.absolute))}[sx](e){let r=e.entry,o=this.zip;e.readdir&&e.readdir.forEach(a=>{let n=e.path,u=n===\"./\"?\"\":n.replace(/\\/*$/,\"/\");this[nx](u+a)}),o?r.on(\"data\",a=>{o.write(a)}):r.on(\"data\",a=>{super[oAe](a)})}};h3.Sync=f3;aAe.exports=h3});var Sy=_(Q1=>{\"use strict\";var Blt=py(),vlt=ve(\"events\").EventEmitter,Ra=ve(\"fs\"),m3=Ra.writev;if(!m3){let t=process.binding(\"fs\"),e=t.FSReqWrap||t.FSReqCallback;m3=(r,o,a,n)=>{let u=(p,h)=>n(p,h,o),A=new e;A.oncomplete=u,t.writeBuffers(r,o,a,A)}}var Py=Symbol(\"_autoClose\"),Kc=Symbol(\"_close\"),k1=Symbol(\"_ended\"),Gn=Symbol(\"_fd\"),lAe=Symbol(\"_finished\"),yh=Symbol(\"_flags\"),g3=Symbol(\"_flush\"),y3=Symbol(\"_handleChunk\"),E3=Symbol(\"_makeBuf\"),px=Symbol(\"_mode\"),cx=Symbol(\"_needDrain\"),vy=Symbol(\"_onerror\"),by=Symbol(\"_onopen\"),d3=Symbol(\"_onread\"),Iy=Symbol(\"_onwrite\"),Eh=Symbol(\"_open\"),_f=Symbol(\"_path\"),Qg=Symbol(\"_pos\"),uA=Symbol(\"_queue\"),By=Symbol(\"_read\"),cAe=Symbol(\"_readSize\"),mh=Symbol(\"_reading\"),ux=Symbol(\"_remain\"),uAe=Symbol(\"_size\"),Ax=Symbol(\"_write\"),wy=Symbol(\"_writing\"),fx=Symbol(\"_defaultFlag\"),Dy=Symbol(\"_errored\"),hx=class extends Blt{constructor(e,r){if(r=r||{},super(r),this.readable=!0,this.writable=!1,typeof e!=\"string\")throw new TypeError(\"path must be a string\");this[Dy]=!1,this[Gn]=typeof r.fd==\"number\"?r.fd:null,this[_f]=e,this[cAe]=r.readSize||16*1024*1024,this[mh]=!1,this[uAe]=typeof r.size==\"number\"?r.size:1/0,this[ux]=this[uAe],this[Py]=typeof r.autoClose==\"boolean\"?r.autoClose:!0,typeof this[Gn]==\"number\"?this[By]():this[Eh]()}get fd(){return this[Gn]}get path(){return this[_f]}write(){throw new TypeError(\"this is a readable stream\")}end(){throw new TypeError(\"this is a readable stream\")}[Eh](){Ra.open(this[_f],\"r\",(e,r)=>this[by](e,r))}[by](e,r){e?this[vy](e):(this[Gn]=r,this.emit(\"open\",r),this[By]())}[E3](){return Buffer.allocUnsafe(Math.min(this[cAe],this[ux]))}[By](){if(!this[mh]){this[mh]=!0;let e=this[E3]();if(e.length===0)return process.nextTick(()=>this[d3](null,0,e));Ra.read(this[Gn],e,0,e.length,null,(r,o,a)=>this[d3](r,o,a))}}[d3](e,r,o){this[mh]=!1,e?this[vy](e):this[y3](r,o)&&this[By]()}[Kc](){if(this[Py]&&typeof this[Gn]==\"number\"){let e=this[Gn];this[Gn]=null,Ra.close(e,r=>r?this.emit(\"error\",r):this.emit(\"close\"))}}[vy](e){this[mh]=!0,this[Kc](),this.emit(\"error\",e)}[y3](e,r){let o=!1;return this[ux]-=e,e>0&&(o=super.write(e<r.length?r.slice(0,e):r)),(e===0||this[ux]<=0)&&(o=!1,this[Kc](),super.end()),o}emit(e,r){switch(e){case\"prefinish\":case\"finish\":break;case\"drain\":typeof this[Gn]==\"number\"&&this[By]();break;case\"error\":return this[Dy]?void 0:(this[Dy]=!0,super.emit(e,r));default:return super.emit(e,r)}}},C3=class extends hx{[Eh](){let e=!0;try{this[by](null,Ra.openSync(this[_f],\"r\")),e=!1}finally{e&&this[Kc]()}}[By](){let e=!0;try{if(!this[mh]){this[mh]=!0;do{let r=this[E3](),o=r.length===0?0:Ra.readSync(this[Gn],r,0,r.length,null);if(!this[y3](o,r))break}while(!0);this[mh]=!1}e=!1}finally{e&&this[Kc]()}}[Kc](){if(this[Py]&&typeof this[Gn]==\"number\"){let e=this[Gn];this[Gn]=null,Ra.closeSync(e),this.emit(\"close\")}}},gx=class extends vlt{constructor(e,r){r=r||{},super(r),this.readable=!1,this.writable=!0,this[Dy]=!1,this[wy]=!1,this[k1]=!1,this[cx]=!1,this[uA]=[],this[_f]=e,this[Gn]=typeof r.fd==\"number\"?r.fd:null,this[px]=r.mode===void 0?438:r.mode,this[Qg]=typeof r.start==\"number\"?r.start:null,this[Py]=typeof r.autoClose==\"boolean\"?r.autoClose:!0;let o=this[Qg]!==null?\"r+\":\"w\";this[fx]=r.flags===void 0,this[yh]=this[fx]?o:r.flags,this[Gn]===null&&this[Eh]()}emit(e,r){if(e===\"error\"){if(this[Dy])return;this[Dy]=!0}return super.emit(e,r)}get fd(){return this[Gn]}get path(){return this[_f]}[vy](e){this[Kc](),this[wy]=!0,this.emit(\"error\",e)}[Eh](){Ra.open(this[_f],this[yh],this[px],(e,r)=>this[by](e,r))}[by](e,r){this[fx]&&this[yh]===\"r+\"&&e&&e.code===\"ENOENT\"?(this[yh]=\"w\",this[Eh]()):e?this[vy](e):(this[Gn]=r,this.emit(\"open\",r),this[g3]())}end(e,r){return e&&this.write(e,r),this[k1]=!0,!this[wy]&&!this[uA].length&&typeof this[Gn]==\"number\"&&this[Iy](null,0),this}write(e,r){return typeof e==\"string\"&&(e=Buffer.from(e,r)),this[k1]?(this.emit(\"error\",new Error(\"write() after end()\")),!1):this[Gn]===null||this[wy]||this[uA].length?(this[uA].push(e),this[cx]=!0,!1):(this[wy]=!0,this[Ax](e),!0)}[Ax](e){Ra.write(this[Gn],e,0,e.length,this[Qg],(r,o)=>this[Iy](r,o))}[Iy](e,r){e?this[vy](e):(this[Qg]!==null&&(this[Qg]+=r),this[uA].length?this[g3]():(this[wy]=!1,this[k1]&&!this[lAe]?(this[lAe]=!0,this[Kc](),this.emit(\"finish\")):this[cx]&&(this[cx]=!1,this.emit(\"drain\"))))}[g3](){if(this[uA].length===0)this[k1]&&this[Iy](null,0);else if(this[uA].length===1)this[Ax](this[uA].pop());else{let e=this[uA];this[uA]=[],m3(this[Gn],e,this[Qg],(r,o)=>this[Iy](r,o))}}[Kc](){if(this[Py]&&typeof this[Gn]==\"number\"){let e=this[Gn];this[Gn]=null,Ra.close(e,r=>r?this.emit(\"error\",r):this.emit(\"close\"))}}},w3=class extends gx{[Eh](){let e;if(this[fx]&&this[yh]===\"r+\")try{e=Ra.openSync(this[_f],this[yh],this[px])}catch(r){if(r.code===\"ENOENT\")return this[yh]=\"w\",this[Eh]();throw r}else e=Ra.openSync(this[_f],this[yh],this[px]);this[by](null,e)}[Kc](){if(this[Py]&&typeof this[Gn]==\"number\"){let e=this[Gn];this[Gn]=null,Ra.closeSync(e),this.emit(\"close\")}}[Ax](e){let r=!0;try{this[Iy](null,Ra.writeSync(this[Gn],e,0,e.length,this[Qg])),r=!1}finally{if(r)try{this[Kc]()}catch{}}}};Q1.ReadStream=hx;Q1.ReadStreamSync=C3;Q1.WriteStream=gx;Q1.WriteStreamSync=w3});var Ix=_((hUt,mAe)=>{\"use strict\";var Dlt=VS(),Plt=yy(),blt=ve(\"events\"),Slt=cP(),xlt=1024*1024,klt=YS(),AAe=KS(),Qlt=MU(),I3=Buffer.from([31,139]),Xl=Symbol(\"state\"),Fg=Symbol(\"writeEntry\"),Hf=Symbol(\"readEntry\"),B3=Symbol(\"nextEntry\"),fAe=Symbol(\"processEntry\"),Zl=Symbol(\"extendedHeader\"),F1=Symbol(\"globalExtendedHeader\"),Ch=Symbol(\"meta\"),pAe=Symbol(\"emitMeta\"),fi=Symbol(\"buffer\"),qf=Symbol(\"queue\"),Rg=Symbol(\"ended\"),hAe=Symbol(\"emittedEnd\"),Tg=Symbol(\"emit\"),Ta=Symbol(\"unzip\"),dx=Symbol(\"consumeChunk\"),mx=Symbol(\"consumeChunkSub\"),v3=Symbol(\"consumeBody\"),gAe=Symbol(\"consumeMeta\"),dAe=Symbol(\"consumeHeader\"),yx=Symbol(\"consuming\"),D3=Symbol(\"bufferConcat\"),P3=Symbol(\"maybeEnd\"),R1=Symbol(\"writing\"),wh=Symbol(\"aborted\"),Ex=Symbol(\"onDone\"),Ng=Symbol(\"sawValidEntry\"),Cx=Symbol(\"sawNullBlock\"),wx=Symbol(\"sawEOF\"),Flt=t=>!0;mAe.exports=Dlt(class extends blt{constructor(e){e=e||{},super(e),this.file=e.file||\"\",this[Ng]=null,this.on(Ex,r=>{(this[Xl]===\"begin\"||this[Ng]===!1)&&this.warn(\"TAR_BAD_ARCHIVE\",\"Unrecognized archive format\")}),e.ondone?this.on(Ex,e.ondone):this.on(Ex,r=>{this.emit(\"prefinish\"),this.emit(\"finish\"),this.emit(\"end\"),this.emit(\"close\")}),this.strict=!!e.strict,this.maxMetaEntrySize=e.maxMetaEntrySize||xlt,this.filter=typeof e.filter==\"function\"?e.filter:Flt,this.writable=!0,this.readable=!1,this[qf]=new Slt,this[fi]=null,this[Hf]=null,this[Fg]=null,this[Xl]=\"begin\",this[Ch]=\"\",this[Zl]=null,this[F1]=null,this[Rg]=!1,this[Ta]=null,this[wh]=!1,this[Cx]=!1,this[wx]=!1,typeof e.onwarn==\"function\"&&this.on(\"warn\",e.onwarn),typeof e.onentry==\"function\"&&this.on(\"entry\",e.onentry)}[dAe](e,r){this[Ng]===null&&(this[Ng]=!1);let o;try{o=new Plt(e,r,this[Zl],this[F1])}catch(a){return this.warn(\"TAR_ENTRY_INVALID\",a)}if(o.nullBlock)this[Cx]?(this[wx]=!0,this[Xl]===\"begin\"&&(this[Xl]=\"header\"),this[Tg](\"eof\")):(this[Cx]=!0,this[Tg](\"nullBlock\"));else if(this[Cx]=!1,!o.cksumValid)this.warn(\"TAR_ENTRY_INVALID\",\"checksum failure\",{header:o});else if(!o.path)this.warn(\"TAR_ENTRY_INVALID\",\"path is required\",{header:o});else{let a=o.type;if(/^(Symbolic)?Link$/.test(a)&&!o.linkpath)this.warn(\"TAR_ENTRY_INVALID\",\"linkpath required\",{header:o});else if(!/^(Symbolic)?Link$/.test(a)&&o.linkpath)this.warn(\"TAR_ENTRY_INVALID\",\"linkpath forbidden\",{header:o});else{let n=this[Fg]=new klt(o,this[Zl],this[F1]);if(!this[Ng])if(n.remain){let u=()=>{n.invalid||(this[Ng]=!0)};n.on(\"end\",u)}else this[Ng]=!0;n.meta?n.size>this.maxMetaEntrySize?(n.ignore=!0,this[Tg](\"ignoredEntry\",n),this[Xl]=\"ignore\",n.resume()):n.size>0&&(this[Ch]=\"\",n.on(\"data\",u=>this[Ch]+=u),this[Xl]=\"meta\"):(this[Zl]=null,n.ignore=n.ignore||!this.filter(n.path,n),n.ignore?(this[Tg](\"ignoredEntry\",n),this[Xl]=n.remain?\"ignore\":\"header\",n.resume()):(n.remain?this[Xl]=\"body\":(this[Xl]=\"header\",n.end()),this[Hf]?this[qf].push(n):(this[qf].push(n),this[B3]())))}}}[fAe](e){let r=!0;return e?Array.isArray(e)?this.emit.apply(this,e):(this[Hf]=e,this.emit(\"entry\",e),e.emittedEnd||(e.on(\"end\",o=>this[B3]()),r=!1)):(this[Hf]=null,r=!1),r}[B3](){do;while(this[fAe](this[qf].shift()));if(!this[qf].length){let e=this[Hf];!e||e.flowing||e.size===e.remain?this[R1]||this.emit(\"drain\"):e.once(\"drain\",o=>this.emit(\"drain\"))}}[v3](e,r){let o=this[Fg],a=o.blockRemain,n=a>=e.length&&r===0?e:e.slice(r,r+a);return o.write(n),o.blockRemain||(this[Xl]=\"header\",this[Fg]=null,o.end()),n.length}[gAe](e,r){let o=this[Fg],a=this[v3](e,r);return this[Fg]||this[pAe](o),a}[Tg](e,r,o){!this[qf].length&&!this[Hf]?this.emit(e,r,o):this[qf].push([e,r,o])}[pAe](e){switch(this[Tg](\"meta\",this[Ch]),e.type){case\"ExtendedHeader\":case\"OldExtendedHeader\":this[Zl]=AAe.parse(this[Ch],this[Zl],!1);break;case\"GlobalExtendedHeader\":this[F1]=AAe.parse(this[Ch],this[F1],!0);break;case\"NextFileHasLongPath\":case\"OldGnuLongPath\":this[Zl]=this[Zl]||Object.create(null),this[Zl].path=this[Ch].replace(/\\0.*/,\"\");break;case\"NextFileHasLongLinkpath\":this[Zl]=this[Zl]||Object.create(null),this[Zl].linkpath=this[Ch].replace(/\\0.*/,\"\");break;default:throw new Error(\"unknown meta: \"+e.type)}}abort(e){this[wh]=!0,this.emit(\"abort\",e),this.warn(\"TAR_ABORT\",e,{recoverable:!1})}write(e){if(this[wh])return;if(this[Ta]===null&&e){if(this[fi]&&(e=Buffer.concat([this[fi],e]),this[fi]=null),e.length<I3.length)return this[fi]=e,!0;for(let o=0;this[Ta]===null&&o<I3.length;o++)e[o]!==I3[o]&&(this[Ta]=!1);if(this[Ta]===null){let o=this[Rg];this[Rg]=!1,this[Ta]=new Qlt.Unzip,this[Ta].on(\"data\",n=>this[dx](n)),this[Ta].on(\"error\",n=>this.abort(n)),this[Ta].on(\"end\",n=>{this[Rg]=!0,this[dx]()}),this[R1]=!0;let a=this[Ta][o?\"end\":\"write\"](e);return this[R1]=!1,a}}this[R1]=!0,this[Ta]?this[Ta].write(e):this[dx](e),this[R1]=!1;let r=this[qf].length?!1:this[Hf]?this[Hf].flowing:!0;return!r&&!this[qf].length&&this[Hf].once(\"drain\",o=>this.emit(\"drain\")),r}[D3](e){e&&!this[wh]&&(this[fi]=this[fi]?Buffer.concat([this[fi],e]):e)}[P3](){if(this[Rg]&&!this[hAe]&&!this[wh]&&!this[yx]){this[hAe]=!0;let e=this[Fg];if(e&&e.blockRemain){let r=this[fi]?this[fi].length:0;this.warn(\"TAR_BAD_ARCHIVE\",`Truncated input (needed ${e.blockRemain} more bytes, only ${r} available)`,{entry:e}),this[fi]&&e.write(this[fi]),e.end()}this[Tg](Ex)}}[dx](e){if(this[yx])this[D3](e);else if(!e&&!this[fi])this[P3]();else{if(this[yx]=!0,this[fi]){this[D3](e);let r=this[fi];this[fi]=null,this[mx](r)}else this[mx](e);for(;this[fi]&&this[fi].length>=512&&!this[wh]&&!this[wx];){let r=this[fi];this[fi]=null,this[mx](r)}this[yx]=!1}(!this[fi]||this[Rg])&&this[P3]()}[mx](e){let r=0,o=e.length;for(;r+512<=o&&!this[wh]&&!this[wx];)switch(this[Xl]){case\"begin\":case\"header\":this[dAe](e,r),r+=512;break;case\"ignore\":case\"body\":r+=this[v3](e,r);break;case\"meta\":r+=this[gAe](e,r);break;default:throw new Error(\"invalid state: \"+this[Xl])}r<o&&(this[fi]?this[fi]=Buffer.concat([e.slice(r),this[fi]]):this[fi]=e.slice(r))}end(e){this[wh]||(this[Ta]?this[Ta].end(e):(this[Rg]=!0,this.write(e)))}})});var Bx=_((gUt,wAe)=>{\"use strict\";var Rlt=Ay(),EAe=Ix(),xy=ve(\"fs\"),Tlt=Sy(),yAe=ve(\"path\"),b3=Ey();wAe.exports=(t,e,r)=>{typeof t==\"function\"?(r=t,e=null,t={}):Array.isArray(t)&&(e=t,t={}),typeof e==\"function\"&&(r=e,e=null),e?e=Array.from(e):e=[];let o=Rlt(t);if(o.sync&&typeof r==\"function\")throw new TypeError(\"callback not supported for sync tar functions\");if(!o.file&&typeof r==\"function\")throw new TypeError(\"callback only supported with file option\");return e.length&&Llt(o,e),o.noResume||Nlt(o),o.file&&o.sync?Mlt(o):o.file?Olt(o,r):CAe(o)};var Nlt=t=>{let e=t.onentry;t.onentry=e?r=>{e(r),r.resume()}:r=>r.resume()},Llt=(t,e)=>{let r=new Map(e.map(n=>[b3(n),!0])),o=t.filter,a=(n,u)=>{let A=u||yAe.parse(n).root||\".\",p=n===A?!1:r.has(n)?r.get(n):a(yAe.dirname(n),A);return r.set(n,p),p};t.filter=o?(n,u)=>o(n,u)&&a(b3(n)):n=>a(b3(n))},Mlt=t=>{let e=CAe(t),r=t.file,o=!0,a;try{let n=xy.statSync(r),u=t.maxReadSize||16*1024*1024;if(n.size<u)e.end(xy.readFileSync(r));else{let A=0,p=Buffer.allocUnsafe(u);for(a=xy.openSync(r,\"r\");A<n.size;){let h=xy.readSync(a,p,0,u,A);A+=h,e.write(p.slice(0,h))}e.end()}o=!1}finally{if(o&&a)try{xy.closeSync(a)}catch{}}},Olt=(t,e)=>{let r=new EAe(t),o=t.maxReadSize||16*1024*1024,a=t.file,n=new Promise((u,A)=>{r.on(\"error\",A),r.on(\"end\",u),xy.stat(a,(p,h)=>{if(p)A(p);else{let E=new Tlt.ReadStream(a,{readSize:o,size:h.size});E.on(\"error\",A),E.pipe(r)}})});return e?n.then(e,e):n},CAe=t=>new EAe(t)});var bAe=_((dUt,PAe)=>{\"use strict\";var Ult=Ay(),vx=lx(),IAe=Sy(),BAe=Bx(),vAe=ve(\"path\");PAe.exports=(t,e,r)=>{if(typeof e==\"function\"&&(r=e),Array.isArray(t)&&(e=t,t={}),!e||!Array.isArray(e)||!e.length)throw new TypeError(\"no files or directories specified\");e=Array.from(e);let o=Ult(t);if(o.sync&&typeof r==\"function\")throw new TypeError(\"callback not supported for sync tar functions\");if(!o.file&&typeof r==\"function\")throw new TypeError(\"callback only supported with file option\");return o.file&&o.sync?_lt(o,e):o.file?Hlt(o,e,r):o.sync?qlt(o,e):jlt(o,e)};var _lt=(t,e)=>{let r=new vx.Sync(t),o=new IAe.WriteStreamSync(t.file,{mode:t.mode||438});r.pipe(o),DAe(r,e)},Hlt=(t,e,r)=>{let o=new vx(t),a=new IAe.WriteStream(t.file,{mode:t.mode||438});o.pipe(a);let n=new Promise((u,A)=>{a.on(\"error\",A),a.on(\"close\",u),o.on(\"error\",A)});return S3(o,e),r?n.then(r,r):n},DAe=(t,e)=>{e.forEach(r=>{r.charAt(0)===\"@\"?BAe({file:vAe.resolve(t.cwd,r.substr(1)),sync:!0,noResume:!0,onentry:o=>t.add(o)}):t.add(r)}),t.end()},S3=(t,e)=>{for(;e.length;){let r=e.shift();if(r.charAt(0)===\"@\")return BAe({file:vAe.resolve(t.cwd,r.substr(1)),noResume:!0,onentry:o=>t.add(o)}).then(o=>S3(t,e));t.add(r)}t.end()},qlt=(t,e)=>{let r=new vx.Sync(t);return DAe(r,e),r},jlt=(t,e)=>{let r=new vx(t);return S3(r,e),r}});var x3=_((mUt,TAe)=>{\"use strict\";var Glt=Ay(),SAe=lx(),fl=ve(\"fs\"),xAe=Sy(),kAe=Bx(),QAe=ve(\"path\"),FAe=yy();TAe.exports=(t,e,r)=>{let o=Glt(t);if(!o.file)throw new TypeError(\"file is required\");if(o.gzip)throw new TypeError(\"cannot append to compressed archives\");if(!e||!Array.isArray(e)||!e.length)throw new TypeError(\"no files or directories specified\");return e=Array.from(e),o.sync?Ylt(o,e):Klt(o,e,r)};var Ylt=(t,e)=>{let r=new SAe.Sync(t),o=!0,a,n;try{try{a=fl.openSync(t.file,\"r+\")}catch(p){if(p.code===\"ENOENT\")a=fl.openSync(t.file,\"w+\");else throw p}let u=fl.fstatSync(a),A=Buffer.alloc(512);e:for(n=0;n<u.size;n+=512){for(let E=0,I=0;E<512;E+=I){if(I=fl.readSync(a,A,E,A.length-E,n+E),n===0&&A[0]===31&&A[1]===139)throw new Error(\"cannot append to compressed archives\");if(!I)break e}let p=new FAe(A);if(!p.cksumValid)break;let h=512*Math.ceil(p.size/512);if(n+h+512>u.size)break;n+=h,t.mtimeCache&&t.mtimeCache.set(p.path,p.mtime)}o=!1,Wlt(t,r,n,a,e)}finally{if(o)try{fl.closeSync(a)}catch{}}},Wlt=(t,e,r,o,a)=>{let n=new xAe.WriteStreamSync(t.file,{fd:o,start:r});e.pipe(n),Vlt(e,a)},Klt=(t,e,r)=>{e=Array.from(e);let o=new SAe(t),a=(u,A,p)=>{let h=(C,R)=>{C?fl.close(u,L=>p(C)):p(null,R)},E=0;if(A===0)return h(null,0);let I=0,v=Buffer.alloc(512),x=(C,R)=>{if(C)return h(C);if(I+=R,I<512&&R)return fl.read(u,v,I,v.length-I,E+I,x);if(E===0&&v[0]===31&&v[1]===139)return h(new Error(\"cannot append to compressed archives\"));if(I<512)return h(null,E);let L=new FAe(v);if(!L.cksumValid)return h(null,E);let U=512*Math.ceil(L.size/512);if(E+U+512>A||(E+=U+512,E>=A))return h(null,E);t.mtimeCache&&t.mtimeCache.set(L.path,L.mtime),I=0,fl.read(u,v,0,512,E,x)};fl.read(u,v,0,512,E,x)},n=new Promise((u,A)=>{o.on(\"error\",A);let p=\"r+\",h=(E,I)=>{if(E&&E.code===\"ENOENT\"&&p===\"r+\")return p=\"w+\",fl.open(t.file,p,h);if(E)return A(E);fl.fstat(I,(v,x)=>{if(v)return fl.close(I,()=>A(v));a(I,x.size,(C,R)=>{if(C)return A(C);let L=new xAe.WriteStream(t.file,{fd:I,start:R});o.pipe(L),L.on(\"error\",A),L.on(\"close\",u),RAe(o,e)})})};fl.open(t.file,p,h)});return r?n.then(r,r):n},Vlt=(t,e)=>{e.forEach(r=>{r.charAt(0)===\"@\"?kAe({file:QAe.resolve(t.cwd,r.substr(1)),sync:!0,noResume:!0,onentry:o=>t.add(o)}):t.add(r)}),t.end()},RAe=(t,e)=>{for(;e.length;){let r=e.shift();if(r.charAt(0)===\"@\")return kAe({file:QAe.resolve(t.cwd,r.substr(1)),noResume:!0,onentry:o=>t.add(o)}).then(o=>RAe(t,e));t.add(r)}t.end()}});var LAe=_((yUt,NAe)=>{\"use strict\";var zlt=Ay(),Jlt=x3();NAe.exports=(t,e,r)=>{let o=zlt(t);if(!o.file)throw new TypeError(\"file is required\");if(o.gzip)throw new TypeError(\"cannot append to compressed archives\");if(!e||!Array.isArray(e)||!e.length)throw new TypeError(\"no files or directories specified\");return e=Array.from(e),Xlt(o),Jlt(o,e,r)};var Xlt=t=>{let e=t.filter;t.mtimeCache||(t.mtimeCache=new Map),t.filter=e?(r,o)=>e(r,o)&&!(t.mtimeCache.get(r)>o.mtime):(r,o)=>!(t.mtimeCache.get(r)>o.mtime)}});var UAe=_((EUt,OAe)=>{var{promisify:MAe}=ve(\"util\"),Ih=ve(\"fs\"),Zlt=t=>{if(!t)t={mode:511,fs:Ih};else if(typeof t==\"object\")t={mode:511,fs:Ih,...t};else if(typeof t==\"number\")t={mode:t,fs:Ih};else if(typeof t==\"string\")t={mode:parseInt(t,8),fs:Ih};else throw new TypeError(\"invalid options argument\");return t.mkdir=t.mkdir||t.fs.mkdir||Ih.mkdir,t.mkdirAsync=MAe(t.mkdir),t.stat=t.stat||t.fs.stat||Ih.stat,t.statAsync=MAe(t.stat),t.statSync=t.statSync||t.fs.statSync||Ih.statSync,t.mkdirSync=t.mkdirSync||t.fs.mkdirSync||Ih.mkdirSync,t};OAe.exports=Zlt});var HAe=_((CUt,_Ae)=>{var $lt=process.platform,{resolve:ect,parse:tct}=ve(\"path\"),rct=t=>{if(/\\0/.test(t))throw Object.assign(new TypeError(\"path must be a string without null bytes\"),{path:t,code:\"ERR_INVALID_ARG_VALUE\"});if(t=ect(t),$lt===\"win32\"){let e=/[*|\"<>?:]/,{root:r}=tct(t);if(e.test(t.substr(r.length)))throw Object.assign(new Error(\"Illegal characters in path.\"),{path:t,code:\"EINVAL\"})}return t};_Ae.exports=rct});var WAe=_((wUt,YAe)=>{var{dirname:qAe}=ve(\"path\"),jAe=(t,e,r=void 0)=>r===e?Promise.resolve():t.statAsync(e).then(o=>o.isDirectory()?r:void 0,o=>o.code===\"ENOENT\"?jAe(t,qAe(e),e):void 0),GAe=(t,e,r=void 0)=>{if(r!==e)try{return t.statSync(e).isDirectory()?r:void 0}catch(o){return o.code===\"ENOENT\"?GAe(t,qAe(e),e):void 0}};YAe.exports={findMade:jAe,findMadeSync:GAe}});var F3=_((IUt,VAe)=>{var{dirname:KAe}=ve(\"path\"),k3=(t,e,r)=>{e.recursive=!1;let o=KAe(t);return o===t?e.mkdirAsync(t,e).catch(a=>{if(a.code!==\"EISDIR\")throw a}):e.mkdirAsync(t,e).then(()=>r||t,a=>{if(a.code===\"ENOENT\")return k3(o,e).then(n=>k3(t,e,n));if(a.code!==\"EEXIST\"&&a.code!==\"EROFS\")throw a;return e.statAsync(t).then(n=>{if(n.isDirectory())return r;throw a},()=>{throw a})})},Q3=(t,e,r)=>{let o=KAe(t);if(e.recursive=!1,o===t)try{return e.mkdirSync(t,e)}catch(a){if(a.code!==\"EISDIR\")throw a;return}try{return e.mkdirSync(t,e),r||t}catch(a){if(a.code===\"ENOENT\")return Q3(t,e,Q3(o,e,r));if(a.code!==\"EEXIST\"&&a.code!==\"EROFS\")throw a;try{if(!e.statSync(t).isDirectory())throw a}catch{throw a}}};VAe.exports={mkdirpManual:k3,mkdirpManualSync:Q3}});var XAe=_((BUt,JAe)=>{var{dirname:zAe}=ve(\"path\"),{findMade:nct,findMadeSync:ict}=WAe(),{mkdirpManual:sct,mkdirpManualSync:oct}=F3(),act=(t,e)=>(e.recursive=!0,zAe(t)===t?e.mkdirAsync(t,e):nct(e,t).then(o=>e.mkdirAsync(t,e).then(()=>o).catch(a=>{if(a.code===\"ENOENT\")return sct(t,e);throw a}))),lct=(t,e)=>{if(e.recursive=!0,zAe(t)===t)return e.mkdirSync(t,e);let o=ict(e,t);try{return e.mkdirSync(t,e),o}catch(a){if(a.code===\"ENOENT\")return oct(t,e);throw a}};JAe.exports={mkdirpNative:act,mkdirpNativeSync:lct}});var tfe=_((vUt,efe)=>{var ZAe=ve(\"fs\"),cct=process.version,R3=cct.replace(/^v/,\"\").split(\".\"),$Ae=+R3[0]>10||+R3[0]==10&&+R3[1]>=12,uct=$Ae?t=>t.mkdir===ZAe.mkdir:()=>!1,Act=$Ae?t=>t.mkdirSync===ZAe.mkdirSync:()=>!1;efe.exports={useNative:uct,useNativeSync:Act}});var afe=_((DUt,ofe)=>{var ky=UAe(),Qy=HAe(),{mkdirpNative:rfe,mkdirpNativeSync:nfe}=XAe(),{mkdirpManual:ife,mkdirpManualSync:sfe}=F3(),{useNative:fct,useNativeSync:pct}=tfe(),Fy=(t,e)=>(t=Qy(t),e=ky(e),fct(e)?rfe(t,e):ife(t,e)),hct=(t,e)=>(t=Qy(t),e=ky(e),pct(e)?nfe(t,e):sfe(t,e));Fy.sync=hct;Fy.native=(t,e)=>rfe(Qy(t),ky(e));Fy.manual=(t,e)=>ife(Qy(t),ky(e));Fy.nativeSync=(t,e)=>nfe(Qy(t),ky(e));Fy.manualSync=(t,e)=>sfe(Qy(t),ky(e));ofe.exports=Fy});var hfe=_((PUt,pfe)=>{\"use strict\";var $l=ve(\"fs\"),Lg=ve(\"path\"),gct=$l.lchown?\"lchown\":\"chown\",dct=$l.lchownSync?\"lchownSync\":\"chownSync\",cfe=$l.lchown&&!process.version.match(/v1[1-9]+\\./)&&!process.version.match(/v10\\.[6-9]/),lfe=(t,e,r)=>{try{return $l[dct](t,e,r)}catch(o){if(o.code!==\"ENOENT\")throw o}},mct=(t,e,r)=>{try{return $l.chownSync(t,e,r)}catch(o){if(o.code!==\"ENOENT\")throw o}},yct=cfe?(t,e,r,o)=>a=>{!a||a.code!==\"EISDIR\"?o(a):$l.chown(t,e,r,o)}:(t,e,r,o)=>o,T3=cfe?(t,e,r)=>{try{return lfe(t,e,r)}catch(o){if(o.code!==\"EISDIR\")throw o;mct(t,e,r)}}:(t,e,r)=>lfe(t,e,r),Ect=process.version,ufe=(t,e,r)=>$l.readdir(t,e,r),Cct=(t,e)=>$l.readdirSync(t,e);/^v4\\./.test(Ect)&&(ufe=(t,e,r)=>$l.readdir(t,r));var Dx=(t,e,r,o)=>{$l[gct](t,e,r,yct(t,e,r,a=>{o(a&&a.code!==\"ENOENT\"?a:null)}))},Afe=(t,e,r,o,a)=>{if(typeof e==\"string\")return $l.lstat(Lg.resolve(t,e),(n,u)=>{if(n)return a(n.code!==\"ENOENT\"?n:null);u.name=e,Afe(t,u,r,o,a)});if(e.isDirectory())N3(Lg.resolve(t,e.name),r,o,n=>{if(n)return a(n);let u=Lg.resolve(t,e.name);Dx(u,r,o,a)});else{let n=Lg.resolve(t,e.name);Dx(n,r,o,a)}},N3=(t,e,r,o)=>{ufe(t,{withFileTypes:!0},(a,n)=>{if(a){if(a.code===\"ENOENT\")return o();if(a.code!==\"ENOTDIR\"&&a.code!==\"ENOTSUP\")return o(a)}if(a||!n.length)return Dx(t,e,r,o);let u=n.length,A=null,p=h=>{if(!A){if(h)return o(A=h);if(--u===0)return Dx(t,e,r,o)}};n.forEach(h=>Afe(t,h,e,r,p))})},wct=(t,e,r,o)=>{if(typeof e==\"string\")try{let a=$l.lstatSync(Lg.resolve(t,e));a.name=e,e=a}catch(a){if(a.code===\"ENOENT\")return;throw a}e.isDirectory()&&ffe(Lg.resolve(t,e.name),r,o),T3(Lg.resolve(t,e.name),r,o)},ffe=(t,e,r)=>{let o;try{o=Cct(t,{withFileTypes:!0})}catch(a){if(a.code===\"ENOENT\")return;if(a.code===\"ENOTDIR\"||a.code===\"ENOTSUP\")return T3(t,e,r);throw a}return o&&o.length&&o.forEach(a=>wct(t,a,e,r)),T3(t,e,r)};pfe.exports=N3;N3.sync=ffe});var yfe=_((bUt,L3)=>{\"use strict\";var gfe=afe(),ec=ve(\"fs\"),Px=ve(\"path\"),dfe=hfe(),Vc=dy(),bx=class extends Error{constructor(e,r){super(\"Cannot extract through symbolic link\"),this.path=r,this.symlink=e}get name(){return\"SylinkError\"}},Sx=class extends Error{constructor(e,r){super(r+\": Cannot cd into '\"+e+\"'\"),this.path=e,this.code=r}get name(){return\"CwdError\"}},xx=(t,e)=>t.get(Vc(e)),T1=(t,e,r)=>t.set(Vc(e),r),Ict=(t,e)=>{ec.stat(t,(r,o)=>{(r||!o.isDirectory())&&(r=new Sx(t,r&&r.code||\"ENOTDIR\")),e(r)})};L3.exports=(t,e,r)=>{t=Vc(t);let o=e.umask,a=e.mode|448,n=(a&o)!==0,u=e.uid,A=e.gid,p=typeof u==\"number\"&&typeof A==\"number\"&&(u!==e.processUid||A!==e.processGid),h=e.preserve,E=e.unlink,I=e.cache,v=Vc(e.cwd),x=(L,U)=>{L?r(L):(T1(I,t,!0),U&&p?dfe(U,u,A,z=>x(z)):n?ec.chmod(t,a,r):r())};if(I&&xx(I,t)===!0)return x();if(t===v)return Ict(t,x);if(h)return gfe(t,{mode:a}).then(L=>x(null,L),x);let R=Vc(Px.relative(v,t)).split(\"/\");kx(v,R,a,I,E,v,null,x)};var kx=(t,e,r,o,a,n,u,A)=>{if(!e.length)return A(null,u);let p=e.shift(),h=Vc(Px.resolve(t+\"/\"+p));if(xx(o,h))return kx(h,e,r,o,a,n,u,A);ec.mkdir(h,r,mfe(h,e,r,o,a,n,u,A))},mfe=(t,e,r,o,a,n,u,A)=>p=>{p?ec.lstat(t,(h,E)=>{if(h)h.path=h.path&&Vc(h.path),A(h);else if(E.isDirectory())kx(t,e,r,o,a,n,u,A);else if(a)ec.unlink(t,I=>{if(I)return A(I);ec.mkdir(t,r,mfe(t,e,r,o,a,n,u,A))});else{if(E.isSymbolicLink())return A(new bx(t,t+\"/\"+e.join(\"/\")));A(p)}}):(u=u||t,kx(t,e,r,o,a,n,u,A))},Bct=t=>{let e=!1,r=\"ENOTDIR\";try{e=ec.statSync(t).isDirectory()}catch(o){r=o.code}finally{if(!e)throw new Sx(t,r)}};L3.exports.sync=(t,e)=>{t=Vc(t);let r=e.umask,o=e.mode|448,a=(o&r)!==0,n=e.uid,u=e.gid,A=typeof n==\"number\"&&typeof u==\"number\"&&(n!==e.processUid||u!==e.processGid),p=e.preserve,h=e.unlink,E=e.cache,I=Vc(e.cwd),v=L=>{T1(E,t,!0),L&&A&&dfe.sync(L,n,u),a&&ec.chmodSync(t,o)};if(E&&xx(E,t)===!0)return v();if(t===I)return Bct(I),v();if(p)return v(gfe.sync(t,o));let C=Vc(Px.relative(I,t)).split(\"/\"),R=null;for(let L=C.shift(),U=I;L&&(U+=\"/\"+L);L=C.shift())if(U=Vc(Px.resolve(U)),!xx(E,U))try{ec.mkdirSync(U,o),R=R||U,T1(E,U,!0)}catch{let te=ec.lstatSync(U);if(te.isDirectory()){T1(E,U,!0);continue}else if(h){ec.unlinkSync(U),ec.mkdirSync(U,o),R=R||U,T1(E,U,!0);continue}else if(te.isSymbolicLink())return new bx(U,U+\"/\"+C.join(\"/\"))}return v(R)}});var O3=_((SUt,Efe)=>{var M3=Object.create(null),{hasOwnProperty:vct}=Object.prototype;Efe.exports=t=>(vct.call(M3,t)||(M3[t]=t.normalize(\"NFKD\")),M3[t])});var Bfe=_((xUt,Ife)=>{var Cfe=ve(\"assert\"),Dct=O3(),Pct=Ey(),{join:wfe}=ve(\"path\"),bct=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,Sct=bct===\"win32\";Ife.exports=()=>{let t=new Map,e=new Map,r=h=>h.split(\"/\").slice(0,-1).reduce((I,v)=>(I.length&&(v=wfe(I[I.length-1],v)),I.push(v||\"/\"),I),[]),o=new Set,a=h=>{let E=e.get(h);if(!E)throw new Error(\"function does not have any path reservations\");return{paths:E.paths.map(I=>t.get(I)),dirs:[...E.dirs].map(I=>t.get(I))}},n=h=>{let{paths:E,dirs:I}=a(h);return E.every(v=>v[0]===h)&&I.every(v=>v[0]instanceof Set&&v[0].has(h))},u=h=>o.has(h)||!n(h)?!1:(o.add(h),h(()=>A(h)),!0),A=h=>{if(!o.has(h))return!1;let{paths:E,dirs:I}=e.get(h),v=new Set;return E.forEach(x=>{let C=t.get(x);Cfe.equal(C[0],h),C.length===1?t.delete(x):(C.shift(),typeof C[0]==\"function\"?v.add(C[0]):C[0].forEach(R=>v.add(R)))}),I.forEach(x=>{let C=t.get(x);Cfe(C[0]instanceof Set),C[0].size===1&&C.length===1?t.delete(x):C[0].size===1?(C.shift(),v.add(C[0])):C[0].delete(h)}),o.delete(h),v.forEach(x=>u(x)),!0};return{check:n,reserve:(h,E)=>{h=Sct?[\"win32 parallelization disabled\"]:h.map(v=>Dct(Pct(wfe(v))).toLowerCase());let I=new Set(h.map(v=>r(v)).reduce((v,x)=>v.concat(x)));return e.set(E,{dirs:I,paths:h}),h.forEach(v=>{let x=t.get(v);x?x.push(E):t.set(v,[E])}),I.forEach(v=>{let x=t.get(v);x?x[x.length-1]instanceof Set?x[x.length-1].add(E):x.push(new Set([E])):t.set(v,[new Set([E])])}),u(E)}}}});var Pfe=_((kUt,Dfe)=>{var xct=process.platform,kct=xct===\"win32\",Qct=global.__FAKE_TESTING_FS__||ve(\"fs\"),{O_CREAT:Fct,O_TRUNC:Rct,O_WRONLY:Tct,UV_FS_O_FILEMAP:vfe=0}=Qct.constants,Nct=kct&&!!vfe,Lct=512*1024,Mct=vfe|Rct|Fct|Tct;Dfe.exports=Nct?t=>t<Lct?Mct:\"w\":()=>\"w\"});var K3=_((QUt,_fe)=>{\"use strict\";var Oct=ve(\"assert\"),Uct=Ix(),vn=ve(\"fs\"),_ct=Sy(),jf=ve(\"path\"),Mfe=yfe(),bfe=KU(),Hct=Bfe(),qct=VU(),pl=dy(),jct=Ey(),Gct=O3(),Sfe=Symbol(\"onEntry\"),H3=Symbol(\"checkFs\"),xfe=Symbol(\"checkFs2\"),Rx=Symbol(\"pruneCache\"),q3=Symbol(\"isReusable\"),tc=Symbol(\"makeFs\"),j3=Symbol(\"file\"),G3=Symbol(\"directory\"),Tx=Symbol(\"link\"),kfe=Symbol(\"symlink\"),Qfe=Symbol(\"hardlink\"),Ffe=Symbol(\"unsupported\"),Rfe=Symbol(\"checkPath\"),Bh=Symbol(\"mkdir\"),To=Symbol(\"onError\"),Qx=Symbol(\"pending\"),Tfe=Symbol(\"pend\"),Ry=Symbol(\"unpend\"),U3=Symbol(\"ended\"),_3=Symbol(\"maybeClose\"),Y3=Symbol(\"skip\"),N1=Symbol(\"doChown\"),L1=Symbol(\"uid\"),M1=Symbol(\"gid\"),O1=Symbol(\"checkedCwd\"),Ofe=ve(\"crypto\"),Ufe=Pfe(),Yct=process.env.TESTING_TAR_FAKE_PLATFORM||process.platform,U1=Yct===\"win32\",Wct=(t,e)=>{if(!U1)return vn.unlink(t,e);let r=t+\".DELETE.\"+Ofe.randomBytes(16).toString(\"hex\");vn.rename(t,r,o=>{if(o)return e(o);vn.unlink(r,e)})},Kct=t=>{if(!U1)return vn.unlinkSync(t);let e=t+\".DELETE.\"+Ofe.randomBytes(16).toString(\"hex\");vn.renameSync(t,e),vn.unlinkSync(e)},Nfe=(t,e,r)=>t===t>>>0?t:e===e>>>0?e:r,Lfe=t=>Gct(jct(pl(t))).toLowerCase(),Vct=(t,e)=>{e=Lfe(e);for(let r of t.keys()){let o=Lfe(r);(o===e||o.indexOf(e+\"/\")===0)&&t.delete(r)}},zct=t=>{for(let e of t.keys())t.delete(e)},_1=class extends Uct{constructor(e){if(e||(e={}),e.ondone=r=>{this[U3]=!0,this[_3]()},super(e),this[O1]=!1,this.reservations=Hct(),this.transform=typeof e.transform==\"function\"?e.transform:null,this.writable=!0,this.readable=!1,this[Qx]=0,this[U3]=!1,this.dirCache=e.dirCache||new Map,typeof e.uid==\"number\"||typeof e.gid==\"number\"){if(typeof e.uid!=\"number\"||typeof e.gid!=\"number\")throw new TypeError(\"cannot set owner without number uid and gid\");if(e.preserveOwner)throw new TypeError(\"cannot preserve owner in archive and also set owner explicitly\");this.uid=e.uid,this.gid=e.gid,this.setOwner=!0}else this.uid=null,this.gid=null,this.setOwner=!1;e.preserveOwner===void 0&&typeof e.uid!=\"number\"?this.preserveOwner=process.getuid&&process.getuid()===0:this.preserveOwner=!!e.preserveOwner,this.processUid=(this.preserveOwner||this.setOwner)&&process.getuid?process.getuid():null,this.processGid=(this.preserveOwner||this.setOwner)&&process.getgid?process.getgid():null,this.forceChown=e.forceChown===!0,this.win32=!!e.win32||U1,this.newer=!!e.newer,this.keep=!!e.keep,this.noMtime=!!e.noMtime,this.preservePaths=!!e.preservePaths,this.unlink=!!e.unlink,this.cwd=pl(jf.resolve(e.cwd||process.cwd())),this.strip=+e.strip||0,this.processUmask=e.noChmod?0:process.umask(),this.umask=typeof e.umask==\"number\"?e.umask:this.processUmask,this.dmode=e.dmode||511&~this.umask,this.fmode=e.fmode||438&~this.umask,this.on(\"entry\",r=>this[Sfe](r))}warn(e,r,o={}){return(e===\"TAR_BAD_ARCHIVE\"||e===\"TAR_ABORT\")&&(o.recoverable=!1),super.warn(e,r,o)}[_3](){this[U3]&&this[Qx]===0&&(this.emit(\"prefinish\"),this.emit(\"finish\"),this.emit(\"end\"),this.emit(\"close\"))}[Rfe](e){if(this.strip){let r=pl(e.path).split(\"/\");if(r.length<this.strip)return!1;if(e.path=r.slice(this.strip).join(\"/\"),e.type===\"Link\"){let o=pl(e.linkpath).split(\"/\");if(o.length>=this.strip)e.linkpath=o.slice(this.strip).join(\"/\");else return!1}}if(!this.preservePaths){let r=pl(e.path),o=r.split(\"/\");if(o.includes(\"..\")||U1&&/^[a-z]:\\.\\.$/i.test(o[0]))return this.warn(\"TAR_ENTRY_ERROR\",\"path contains '..'\",{entry:e,path:r}),!1;let[a,n]=qct(r);a&&(e.path=n,this.warn(\"TAR_ENTRY_INFO\",`stripping ${a} from absolute path`,{entry:e,path:r}))}if(jf.isAbsolute(e.path)?e.absolute=pl(jf.resolve(e.path)):e.absolute=pl(jf.resolve(this.cwd,e.path)),!this.preservePaths&&e.absolute.indexOf(this.cwd+\"/\")!==0&&e.absolute!==this.cwd)return this.warn(\"TAR_ENTRY_ERROR\",\"path escaped extraction target\",{entry:e,path:pl(e.path),resolvedPath:e.absolute,cwd:this.cwd}),!1;if(e.absolute===this.cwd&&e.type!==\"Directory\"&&e.type!==\"GNUDumpDir\")return!1;if(this.win32){let{root:r}=jf.win32.parse(e.absolute);e.absolute=r+bfe.encode(e.absolute.substr(r.length));let{root:o}=jf.win32.parse(e.path);e.path=o+bfe.encode(e.path.substr(o.length))}return!0}[Sfe](e){if(!this[Rfe](e))return e.resume();switch(Oct.equal(typeof e.absolute,\"string\"),e.type){case\"Directory\":case\"GNUDumpDir\":e.mode&&(e.mode=e.mode|448);case\"File\":case\"OldFile\":case\"ContiguousFile\":case\"Link\":case\"SymbolicLink\":return this[H3](e);case\"CharacterDevice\":case\"BlockDevice\":case\"FIFO\":default:return this[Ffe](e)}}[To](e,r){e.name===\"CwdError\"?this.emit(\"error\",e):(this.warn(\"TAR_ENTRY_ERROR\",e,{entry:r}),this[Ry](),r.resume())}[Bh](e,r,o){Mfe(pl(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:r,noChmod:this.noChmod},o)}[N1](e){return this.forceChown||this.preserveOwner&&(typeof e.uid==\"number\"&&e.uid!==this.processUid||typeof e.gid==\"number\"&&e.gid!==this.processGid)||typeof this.uid==\"number\"&&this.uid!==this.processUid||typeof this.gid==\"number\"&&this.gid!==this.processGid}[L1](e){return Nfe(this.uid,e.uid,this.processUid)}[M1](e){return Nfe(this.gid,e.gid,this.processGid)}[j3](e,r){let o=e.mode&4095||this.fmode,a=new _ct.WriteStream(e.absolute,{flags:Ufe(e.size),mode:o,autoClose:!1});a.on(\"error\",p=>{a.fd&&vn.close(a.fd,()=>{}),a.write=()=>!0,this[To](p,e),r()});let n=1,u=p=>{if(p){a.fd&&vn.close(a.fd,()=>{}),this[To](p,e),r();return}--n===0&&vn.close(a.fd,h=>{h?this[To](h,e):this[Ry](),r()})};a.on(\"finish\",p=>{let h=e.absolute,E=a.fd;if(e.mtime&&!this.noMtime){n++;let I=e.atime||new Date,v=e.mtime;vn.futimes(E,I,v,x=>x?vn.utimes(h,I,v,C=>u(C&&x)):u())}if(this[N1](e)){n++;let I=this[L1](e),v=this[M1](e);vn.fchown(E,I,v,x=>x?vn.chown(h,I,v,C=>u(C&&x)):u())}u()});let A=this.transform&&this.transform(e)||e;A!==e&&(A.on(\"error\",p=>{this[To](p,e),r()}),e.pipe(A)),A.pipe(a)}[G3](e,r){let o=e.mode&4095||this.dmode;this[Bh](e.absolute,o,a=>{if(a){this[To](a,e),r();return}let n=1,u=A=>{--n===0&&(r(),this[Ry](),e.resume())};e.mtime&&!this.noMtime&&(n++,vn.utimes(e.absolute,e.atime||new Date,e.mtime,u)),this[N1](e)&&(n++,vn.chown(e.absolute,this[L1](e),this[M1](e),u)),u()})}[Ffe](e){e.unsupported=!0,this.warn(\"TAR_ENTRY_UNSUPPORTED\",`unsupported entry type: ${e.type}`,{entry:e}),e.resume()}[kfe](e,r){this[Tx](e,e.linkpath,\"symlink\",r)}[Qfe](e,r){let o=pl(jf.resolve(this.cwd,e.linkpath));this[Tx](e,o,\"link\",r)}[Tfe](){this[Qx]++}[Ry](){this[Qx]--,this[_3]()}[Y3](e){this[Ry](),e.resume()}[q3](e,r){return e.type===\"File\"&&!this.unlink&&r.isFile()&&r.nlink<=1&&!U1}[H3](e){this[Tfe]();let r=[e.path];e.linkpath&&r.push(e.linkpath),this.reservations.reserve(r,o=>this[xfe](e,o))}[Rx](e){e.type===\"SymbolicLink\"?zct(this.dirCache):e.type!==\"Directory\"&&Vct(this.dirCache,e.absolute)}[xfe](e,r){this[Rx](e);let o=A=>{this[Rx](e),r(A)},a=()=>{this[Bh](this.cwd,this.dmode,A=>{if(A){this[To](A,e),o();return}this[O1]=!0,n()})},n=()=>{if(e.absolute!==this.cwd){let A=pl(jf.dirname(e.absolute));if(A!==this.cwd)return this[Bh](A,this.dmode,p=>{if(p){this[To](p,e),o();return}u()})}u()},u=()=>{vn.lstat(e.absolute,(A,p)=>{if(p&&(this.keep||this.newer&&p.mtime>e.mtime)){this[Y3](e),o();return}if(A||this[q3](e,p))return this[tc](null,e,o);if(p.isDirectory()){if(e.type===\"Directory\"){let h=!this.noChmod&&e.mode&&(p.mode&4095)!==e.mode,E=I=>this[tc](I,e,o);return h?vn.chmod(e.absolute,e.mode,E):E()}if(e.absolute!==this.cwd)return vn.rmdir(e.absolute,h=>this[tc](h,e,o))}if(e.absolute===this.cwd)return this[tc](null,e,o);Wct(e.absolute,h=>this[tc](h,e,o))})};this[O1]?n():a()}[tc](e,r,o){if(e){this[To](e,r),o();return}switch(r.type){case\"File\":case\"OldFile\":case\"ContiguousFile\":return this[j3](r,o);case\"Link\":return this[Qfe](r,o);case\"SymbolicLink\":return this[kfe](r,o);case\"Directory\":case\"GNUDumpDir\":return this[G3](r,o)}}[Tx](e,r,o,a){vn[o](r,e.absolute,n=>{n?this[To](n,e):(this[Ry](),e.resume()),a()})}},Fx=t=>{try{return[null,t()]}catch(e){return[e,null]}},W3=class extends _1{[tc](e,r){return super[tc](e,r,()=>{})}[H3](e){if(this[Rx](e),!this[O1]){let n=this[Bh](this.cwd,this.dmode);if(n)return this[To](n,e);this[O1]=!0}if(e.absolute!==this.cwd){let n=pl(jf.dirname(e.absolute));if(n!==this.cwd){let u=this[Bh](n,this.dmode);if(u)return this[To](u,e)}}let[r,o]=Fx(()=>vn.lstatSync(e.absolute));if(o&&(this.keep||this.newer&&o.mtime>e.mtime))return this[Y3](e);if(r||this[q3](e,o))return this[tc](null,e);if(o.isDirectory()){if(e.type===\"Directory\"){let u=!this.noChmod&&e.mode&&(o.mode&4095)!==e.mode,[A]=u?Fx(()=>{vn.chmodSync(e.absolute,e.mode)}):[];return this[tc](A,e)}let[n]=Fx(()=>vn.rmdirSync(e.absolute));this[tc](n,e)}let[a]=e.absolute===this.cwd?[]:Fx(()=>Kct(e.absolute));this[tc](a,e)}[j3](e,r){let o=e.mode&4095||this.fmode,a=A=>{let p;try{vn.closeSync(n)}catch(h){p=h}(A||p)&&this[To](A||p,e),r()},n;try{n=vn.openSync(e.absolute,Ufe(e.size),o)}catch(A){return a(A)}let u=this.transform&&this.transform(e)||e;u!==e&&(u.on(\"error\",A=>this[To](A,e)),e.pipe(u)),u.on(\"data\",A=>{try{vn.writeSync(n,A,0,A.length)}catch(p){a(p)}}),u.on(\"end\",A=>{let p=null;if(e.mtime&&!this.noMtime){let h=e.atime||new Date,E=e.mtime;try{vn.futimesSync(n,h,E)}catch(I){try{vn.utimesSync(e.absolute,h,E)}catch{p=I}}}if(this[N1](e)){let h=this[L1](e),E=this[M1](e);try{vn.fchownSync(n,h,E)}catch(I){try{vn.chownSync(e.absolute,h,E)}catch{p=p||I}}}a(p)})}[G3](e,r){let o=e.mode&4095||this.dmode,a=this[Bh](e.absolute,o);if(a){this[To](a,e),r();return}if(e.mtime&&!this.noMtime)try{vn.utimesSync(e.absolute,e.atime||new Date,e.mtime)}catch{}if(this[N1](e))try{vn.chownSync(e.absolute,this[L1](e),this[M1](e))}catch{}r(),e.resume()}[Bh](e,r){try{return Mfe.sync(pl(e),{uid:this.uid,gid:this.gid,processUid:this.processUid,processGid:this.processGid,umask:this.processUmask,preserve:this.preservePaths,unlink:this.unlink,cache:this.dirCache,cwd:this.cwd,mode:r})}catch(o){return o}}[Tx](e,r,o,a){try{vn[o+\"Sync\"](r,e.absolute),a(),e.resume()}catch(n){return this[To](n,e)}}};_1.Sync=W3;_fe.exports=_1});var Yfe=_((FUt,Gfe)=>{\"use strict\";var Jct=Ay(),Nx=K3(),qfe=ve(\"fs\"),jfe=Sy(),Hfe=ve(\"path\"),V3=Ey();Gfe.exports=(t,e,r)=>{typeof t==\"function\"?(r=t,e=null,t={}):Array.isArray(t)&&(e=t,t={}),typeof e==\"function\"&&(r=e,e=null),e?e=Array.from(e):e=[];let o=Jct(t);if(o.sync&&typeof r==\"function\")throw new TypeError(\"callback not supported for sync tar functions\");if(!o.file&&typeof r==\"function\")throw new TypeError(\"callback only supported with file option\");return e.length&&Xct(o,e),o.file&&o.sync?Zct(o):o.file?$ct(o,r):o.sync?eut(o):tut(o)};var Xct=(t,e)=>{let r=new Map(e.map(n=>[V3(n),!0])),o=t.filter,a=(n,u)=>{let A=u||Hfe.parse(n).root||\".\",p=n===A?!1:r.has(n)?r.get(n):a(Hfe.dirname(n),A);return r.set(n,p),p};t.filter=o?(n,u)=>o(n,u)&&a(V3(n)):n=>a(V3(n))},Zct=t=>{let e=new Nx.Sync(t),r=t.file,o=qfe.statSync(r),a=t.maxReadSize||16*1024*1024;new jfe.ReadStreamSync(r,{readSize:a,size:o.size}).pipe(e)},$ct=(t,e)=>{let r=new Nx(t),o=t.maxReadSize||16*1024*1024,a=t.file,n=new Promise((u,A)=>{r.on(\"error\",A),r.on(\"close\",u),qfe.stat(a,(p,h)=>{if(p)A(p);else{let E=new jfe.ReadStream(a,{readSize:o,size:h.size});E.on(\"error\",A),E.pipe(r)}})});return e?n.then(e,e):n},eut=t=>new Nx.Sync(t),tut=t=>new Nx(t)});var Wfe=_(As=>{\"use strict\";As.c=As.create=bAe();As.r=As.replace=x3();As.t=As.list=Bx();As.u=As.update=LAe();As.x=As.extract=Yfe();As.Pack=lx();As.Unpack=K3();As.Parse=Ix();As.ReadEntry=YS();As.WriteEntry=i3();As.Header=yy();As.Pax=KS();As.types=_U()});var z3,Kfe,vh,H1,q1,Vfe=Et(()=>{z3=Ze(eg()),Kfe=ve(\"worker_threads\"),vh=Symbol(\"kTaskInfo\"),H1=class{constructor(e,r){this.fn=e;this.limit=(0,z3.default)(r.poolSize)}run(e){return this.limit(()=>this.fn(e))}},q1=class{constructor(e,r){this.source=e;this.workers=[];this.limit=(0,z3.default)(r.poolSize),this.cleanupInterval=setInterval(()=>{if(this.limit.pendingCount===0&&this.limit.activeCount===0){let o=this.workers.pop();o?o.terminate():clearInterval(this.cleanupInterval)}},5e3).unref()}createWorker(){this.cleanupInterval.refresh();let e=new Kfe.Worker(this.source,{eval:!0,execArgv:[...process.execArgv,\"--unhandled-rejections=strict\"]});return e.on(\"message\",r=>{if(!e[vh])throw new Error(\"Assertion failed: Worker sent a result without having a task assigned\");e[vh].resolve(r),e[vh]=null,e.unref(),this.workers.push(e)}),e.on(\"error\",r=>{e[vh]?.reject(r),e[vh]=null}),e.on(\"exit\",r=>{r!==0&&e[vh]?.reject(new Error(`Worker exited with code ${r}`)),e[vh]=null}),e}run(e){return this.limit(()=>{let r=this.workers.pop()??this.createWorker();return r.ref(),new Promise((o,a)=>{r[vh]={resolve:o,reject:a},r.postMessage(e)})})}}});var Jfe=_((LUt,zfe)=>{var J3;zfe.exports.getContent=()=>(typeof J3>\"u\"&&(J3=ve(\"zlib\").brotliDecompressSync(Buffer.from(\"W21FVsM2RDBrv7qreO687zfJ9iXKGNtRLJtHewoXfnGFRRcYpwXYD+UNa6n8F9ONUh1V1aykMMbcoLYBoJrW61US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AEIKICf8UoDxogB6G0RA4C6okauuRkUraUrnOlwlcAJAG8KkAICwPeSC4aCJEmO1262w5lMMOMnNtybaTOMnTRPtNmJ827bHUlBZIR2TAIJojdugkAm+FSyyoM3GYDXFH/LQkrlQU6BVCiAifA+Tz5/x/nL76yH+VkpHuWl9fmp+KfmP/+p5DtOZIR9pGSRTE7y+Cb7QY81PBvvOk96wNJbD+qTVvm75GU/G9w1Iv76WtieR7frljsz4hnXCtZ82mHzR9yld0FfL3n0jvmugQ6N6jiVHt6BJyAREHJcpif3P4GkftYjs6FxdNr2PR/x1DrowpYyUDsBsQNK5kFPK0FUlfIcFDFTyzJJhCimHzJlt/iU3zw7J3Ty5VeaoM/n/GP2rBjKIkCqor2//VqV8isKvV5J27DMLfOg98x8HttHLGR36loFTgWljtS74O2Nz60dSJpbN4G9VlL3LdlTw+M1tXO79pgOhZtuQ59tcr0F3/vlOzBd5nOWkF57WybHUC9WDwx7a/4adgtNXMSs1oNsazds+898yOAkRl/S7A2TAIMnAnf8Z2Ntps/fOnBy7vIeQuZ7obd6oNTRokPMgLtiPnzIliZNt8mcdti8fKom8Ms+sSi/v4IWL8et24gsVb8nqlWc6YHJyZM6TPnxhtgTmzqsIAlK8QLq6KvveIS4ivSNsbvbOu+ePwmctfunEzDNxjxTeYyQ3b7Xf8m0hmUy2BmyVbld3vqlX/X+rcpvraX/1Fu3mk5AI//N927NSzalX1Ub3nzIV4IiAZAxhiHS1WwdHnwvXosHJH7GQ76qFJXxZbBLGyPDx0fEfkztKNGfljn1EdjTsdGo57zM7c3SBMbu+vvoZtkg84Zd3Z/Nu/NXFYXhPI2X/MXsFw==\",\"base64\")).toString()),J3)});var $i={};Vt($i,{convertToZip:()=>sut,convertToZipWorker:()=>$3,extractArchiveTo:()=>tpe,getDefaultTaskPool:()=>$fe,getTaskPoolForConfiguration:()=>epe,makeArchiveFromDirectory:()=>iut});function rut(t,e){switch(t){case\"async\":return new H1($3,{poolSize:e});case\"workers\":return new q1((0,Z3.getContent)(),{poolSize:e});default:throw new Error(`Assertion failed: Unknown value ${t} for taskPoolMode`)}}function $fe(){return typeof X3>\"u\"&&(X3=rut(\"workers\",Xi.availableParallelism())),X3}function epe(t){return typeof t>\"u\"?$fe():al(nut,t,()=>{let e=t.get(\"taskPoolMode\"),r=t.get(\"taskPoolConcurrency\");switch(e){case\"async\":return new H1($3,{poolSize:r});case\"workers\":return new q1((0,Z3.getContent)(),{poolSize:r});default:throw new Error(`Assertion failed: Unknown value ${e} for taskPoolMode`)}})}async function $3(t){let{tmpFile:e,tgz:r,compressionLevel:o,extractBufferOpts:a}=t,n=new Zi(e,{create:!0,level:o,stats:wa.makeDefaultStats()}),u=Buffer.from(r.buffer,r.byteOffset,r.byteLength);return await tpe(u,n,a),n.saveAndClose(),e}async function iut(t,{baseFs:e=new Tn,prefixPath:r=It.root,compressionLevel:o,inMemory:a=!1}={}){let n;if(a)n=new Zi(null,{level:o});else{let A=await oe.mktempPromise(),p=V.join(A,\"archive.zip\");n=new Zi(p,{create:!0,level:o})}let u=V.resolve(It.root,r);return await n.copyPromise(u,t,{baseFs:e,stableTime:!0,stableSort:!0}),n}async function sut(t,e={}){let r=await oe.mktempPromise(),o=V.join(r,\"archive.zip\"),a=e.compressionLevel??e.configuration?.get(\"compressionLevel\")??\"mixed\",n={prefixPath:e.prefixPath,stripComponents:e.stripComponents};return await(e.taskPool??epe(e.configuration)).run({tmpFile:o,tgz:t,compressionLevel:a,extractBufferOpts:n}),new Zi(o,{level:e.compressionLevel})}async function*out(t){let e=new Zfe.default.Parse,r=new Xfe.PassThrough({objectMode:!0,autoDestroy:!0,emitClose:!0});e.on(\"entry\",o=>{r.write(o)}),e.on(\"error\",o=>{r.destroy(o)}),e.on(\"close\",()=>{r.destroyed||r.end()}),e.end(t);for await(let o of r){let a=o;yield a,a.resume()}}async function tpe(t,e,{stripComponents:r=0,prefixPath:o=It.dot}={}){function a(n){if(n.path[0]===\"/\")return!0;let u=n.path.split(/\\//g);return!!(u.some(A=>A===\"..\")||u.length<=r)}for await(let n of out(t)){if(a(n))continue;let u=V.normalize(ue.toPortablePath(n.path)).replace(/\\/$/,\"\").split(/\\//g);if(u.length<=r)continue;let A=u.slice(r).join(\"/\"),p=V.join(o,A),h=420;switch((n.type===\"Directory\"||(n.mode??0)&73)&&(h|=73),n.type){case\"Directory\":e.mkdirpSync(V.dirname(p),{chmod:493,utimes:[Bi.SAFE_TIME,Bi.SAFE_TIME]}),e.mkdirSync(p,{mode:h}),e.utimesSync(p,Bi.SAFE_TIME,Bi.SAFE_TIME);break;case\"OldFile\":case\"File\":e.mkdirpSync(V.dirname(p),{chmod:493,utimes:[Bi.SAFE_TIME,Bi.SAFE_TIME]}),e.writeFileSync(p,await km(n),{mode:h}),e.utimesSync(p,Bi.SAFE_TIME,Bi.SAFE_TIME);break;case\"SymbolicLink\":e.mkdirpSync(V.dirname(p),{chmod:493,utimes:[Bi.SAFE_TIME,Bi.SAFE_TIME]}),e.symlinkSync(n.linkpath,p),e.lutimesSync(p,Bi.SAFE_TIME,Bi.SAFE_TIME);break}}return e}var Xfe,Zfe,Z3,X3,nut,rpe=Et(()=>{Ge();Pt();nA();Xfe=ve(\"stream\"),Zfe=Ze(Wfe());Vfe();ql();Z3=Ze(Jfe());nut=new WeakMap});var ipe=_((e_,npe)=>{(function(t,e){typeof e_==\"object\"?npe.exports=e():typeof define==\"function\"&&define.amd?define(e):t.treeify=e()})(e_,function(){function t(a,n){var u=n?\"\\u2514\":\"\\u251C\";return a?u+=\"\\u2500 \":u+=\"\\u2500\\u2500\\u2510\",u}function e(a,n){var u=[];for(var A in a)a.hasOwnProperty(A)&&(n&&typeof a[A]==\"function\"||u.push(A));return u}function r(a,n,u,A,p,h,E){var I=\"\",v=0,x,C,R=A.slice(0);if(R.push([n,u])&&A.length>0&&(A.forEach(function(U,z){z>0&&(I+=(U[1]?\" \":\"\\u2502\")+\"  \"),!C&&U[0]===n&&(C=!0)}),I+=t(a,u)+a,p&&(typeof n!=\"object\"||n instanceof Date)&&(I+=\": \"+n),C&&(I+=\" (circular ref.)\"),E(I)),!C&&typeof n==\"object\"){var L=e(n,h);L.forEach(function(U){x=++v===L.length,r(U,n[U],x,R,p,h,E)})}}var o={};return o.asLines=function(a,n,u,A){var p=typeof u!=\"function\"?u:!1;r(\".\",a,!1,[],n,p,A||u)},o.asTree=function(a,n,u){var A=\"\";return r(\".\",a,!1,[],n,u,function(p){A+=p+`\n`}),A},o})});var fs={};Vt(fs,{emitList:()=>aut,emitTree:()=>lpe,treeNodeToJson:()=>ape,treeNodeToTreeify:()=>ope});function ope(t,{configuration:e}){let r={},o=0,a=(n,u)=>{let A=Array.isArray(n)?n.entries():Object.entries(n);for(let[p,h]of A){if(!h)continue;let{label:E,value:I,children:v}=h,x=[];typeof E<\"u\"&&x.push(fg(e,E,2)),typeof I<\"u\"&&x.push(Ot(e,I[0],I[1])),x.length===0&&x.push(fg(e,`${p}`,2));let C=x.join(\": \").trim(),R=`\\0${o++}\\0`,L=u[`${R}${C}`]={};typeof v<\"u\"&&a(v,L)}};if(typeof t.children>\"u\")throw new Error(\"The root node must only contain children\");return a(t.children,r),r}function ape(t){let e=r=>{if(typeof r.children>\"u\"){if(typeof r.value>\"u\")throw new Error(\"Assertion failed: Expected a value to be set if the children are missing\");return pg(r.value[0],r.value[1])}let o=Array.isArray(r.children)?r.children.entries():Object.entries(r.children??{}),a=Array.isArray(r.children)?[]:{};for(let[n,u]of o)u&&(a[lut(n)]=e(u));return typeof r.value>\"u\"?a:{value:pg(r.value[0],r.value[1]),children:a}};return e(t)}function aut(t,{configuration:e,stdout:r,json:o}){let a=t.map(n=>({value:n}));lpe({children:a},{configuration:e,stdout:r,json:o})}function lpe(t,{configuration:e,stdout:r,json:o,separators:a=0}){if(o){let u=Array.isArray(t.children)?t.children.values():Object.values(t.children??{});for(let A of u)A&&r.write(`${JSON.stringify(ape(A))}\n`);return}let n=(0,spe.asTree)(ope(t,{configuration:e}),!1,!1);if(n=n.replace(/\\0[0-9]+\\0/g,\"\"),a>=1&&(n=n.replace(/^([├└]─)/gm,`\\u2502\n$1`).replace(/^│\\n/,\"\")),a>=2)for(let u=0;u<2;++u)n=n.replace(/^([│ ].{2}[├│ ].{2}[^\\n]+\\n)(([│ ]).{2}[├└].{2}[^\\n]*\\n[│ ].{2}[│ ].{2}[├└]─)/gm,`$1$3  \\u2502 \n$2`).replace(/^│\\n/,\"\");if(a>=3)throw new Error(\"Only the first two levels are accepted by treeUtils.emitTree\");r.write(n)}function lut(t){return typeof t==\"string\"?t.replace(/^\\0[0-9]+\\0/,\"\"):t}var spe,cpe=Et(()=>{spe=Ze(ipe());jl()});function j1(t){let e=t.match(cut);if(!e?.groups)throw new Error(\"Assertion failed: Expected the checksum to match the requested pattern\");let r=e.groups.cacheVersion?parseInt(e.groups.cacheVersion):null;return{cacheKey:e.groups.cacheKey??null,cacheVersion:r,cacheSpec:e.groups.cacheSpec??null,hash:e.groups.hash}}var upe,t_,r_,Lx,Gr,cut,n_=Et(()=>{Ge();Pt();Pt();nA();upe=ve(\"crypto\"),t_=Ze(ve(\"fs\"));Wl();th();ql();So();r_=Qm(process.env.YARN_CACHE_CHECKPOINT_OVERRIDE??process.env.YARN_CACHE_VERSION_OVERRIDE??9),Lx=Qm(process.env.YARN_CACHE_VERSION_OVERRIDE??10),Gr=class t{constructor(e,{configuration:r,immutable:o=r.get(\"enableImmutableCache\"),check:a=!1}){this.markedFiles=new Set;this.mutexes=new Map;this.cacheId=`-${(0,upe.randomBytes)(8).toString(\"hex\")}.tmp`;this.configuration=r,this.cwd=e,this.immutable=o,this.check=a;let{cacheSpec:n,cacheKey:u}=t.getCacheKey(r);this.cacheSpec=n,this.cacheKey=u}static async find(e,{immutable:r,check:o}={}){let a=new t(e.get(\"cacheFolder\"),{configuration:e,immutable:r,check:o});return await a.setup(),a}static getCacheKey(e){let r=e.get(\"compressionLevel\"),o=r!==\"mixed\"?`c${r}`:\"\";return{cacheKey:[Lx,o].join(\"\"),cacheSpec:o}}get mirrorCwd(){if(!this.configuration.get(\"enableMirror\"))return null;let e=`${this.configuration.get(\"globalFolder\")}/cache`;return e!==this.cwd?e:null}getVersionFilename(e){return`${Hm(e)}-${this.cacheKey}.zip`}getChecksumFilename(e,r){let a=j1(r).hash.slice(0,10);return`${Hm(e)}-${a}.zip`}isChecksumCompatible(e){if(e===null)return!1;let{cacheVersion:r,cacheSpec:o}=j1(e);if(r===null||r<r_)return!1;let a=this.configuration.get(\"cacheMigrationMode\");return!(r<Lx&&a===\"always\"||o!==this.cacheSpec&&a!==\"required-only\")}getLocatorPath(e,r){return this.mirrorCwd===null?V.resolve(this.cwd,this.getVersionFilename(e)):r===null?V.resolve(this.cwd,this.getVersionFilename(e)):V.resolve(this.cwd,this.getChecksumFilename(e,r))}getLocatorMirrorPath(e){let r=this.mirrorCwd;return r!==null?V.resolve(r,this.getVersionFilename(e)):null}async setup(){if(!this.configuration.get(\"enableGlobalCache\"))if(this.immutable){if(!await oe.existsPromise(this.cwd))throw new Jt(56,\"Cache path does not exist.\")}else{await oe.mkdirPromise(this.cwd,{recursive:!0});let e=V.resolve(this.cwd,\".gitignore\");await oe.changeFilePromise(e,`/.gitignore\n*.flock\n*.tmp\n`)}(this.mirrorCwd||!this.immutable)&&await oe.mkdirPromise(this.mirrorCwd||this.cwd,{recursive:!0})}async fetchPackageFromCache(e,r,{onHit:o,onMiss:a,loader:n,...u}){let A=this.getLocatorMirrorPath(e),p=new Tn,h=()=>{let de=new Zi,Be=V.join(It.root,zM(e));return de.mkdirSync(Be,{recursive:!0}),de.writeJsonSync(V.join(Be,dr.manifest),{name:rn(e),mocked:!0}),de},E=async(de,{isColdHit:Be,controlPath:Ee=null})=>{if(Ee===null&&u.unstablePackages?.has(e.locatorHash))return{isValid:!0,hash:null};let g=r&&!Be?j1(r).cacheKey:this.cacheKey,me=!u.skipIntegrityCheck||!r?`${g}/${await Ib(de)}`:r;if(Ee!==null){let Ae=!u.skipIntegrityCheck||!r?`${this.cacheKey}/${await Ib(Ee)}`:r;if(me!==Ae)throw new Jt(18,\"The remote archive doesn't match the local checksum - has the local cache been corrupted?\")}let we=null;switch(r!==null&&me!==r&&(this.check?we=\"throw\":j1(r).cacheKey!==j1(me).cacheKey?we=\"update\":we=this.configuration.get(\"checksumBehavior\")),we){case null:case\"update\":return{isValid:!0,hash:me};case\"ignore\":return{isValid:!0,hash:r};case\"reset\":return{isValid:!1,hash:r};default:case\"throw\":throw new Jt(18,\"The remote archive doesn't match the expected checksum\")}},I=async de=>{if(!n)throw new Error(`Cache check required but no loader configured for ${qr(this.configuration,e)}`);let Be=await n(),Ee=Be.getRealPath();Be.saveAndClose(),await oe.chmodPromise(Ee,420);let g=await E(de,{controlPath:Ee,isColdHit:!1});if(!g.isValid)throw new Error(\"Assertion failed: Expected a valid checksum\");return g.hash},v=async()=>{if(A===null||!await oe.existsPromise(A)){let de=await n(),Be=de.getRealPath();return de.saveAndClose(),{source:\"loader\",path:Be}}return{source:\"mirror\",path:A}},x=async()=>{if(!n)throw new Error(`Cache entry required but missing for ${qr(this.configuration,e)}`);if(this.immutable)throw new Jt(56,`Cache entry required but missing for ${qr(this.configuration,e)}`);let{path:de,source:Be}=await v(),{hash:Ee}=await E(de,{isColdHit:!0}),g=this.getLocatorPath(e,Ee),me=[];Be!==\"mirror\"&&A!==null&&me.push(async()=>{let Ae=`${A}${this.cacheId}`;await oe.copyFilePromise(de,Ae,t_.default.constants.COPYFILE_FICLONE),await oe.chmodPromise(Ae,420),await oe.renamePromise(Ae,A)}),(!u.mirrorWriteOnly||A===null)&&me.push(async()=>{let Ae=`${g}${this.cacheId}`;await oe.copyFilePromise(de,Ae,t_.default.constants.COPYFILE_FICLONE),await oe.chmodPromise(Ae,420),await oe.renamePromise(Ae,g)});let we=u.mirrorWriteOnly?A??g:g;return await Promise.all(me.map(Ae=>Ae())),[!1,we,Ee]},C=async()=>{let Be=(async()=>{let Ee=u.unstablePackages?.has(e.locatorHash),g=Ee||!r||this.isChecksumCompatible(r)?this.getLocatorPath(e,r):null,me=g!==null?this.markedFiles.has(g)||await p.existsPromise(g):!1,we=!!u.mockedPackages?.has(e.locatorHash)&&(!this.check||!me),Ae=we||me,ne=Ae?o:a;if(ne&&ne(),Ae){let Z=null,xe=g;if(!we)if(this.check)Z=await I(xe);else{let Ne=await E(xe,{isColdHit:!1});if(Ne.isValid)Z=Ne.hash;else return x()}return[we,xe,Z]}else{if(this.immutable&&Ee)throw new Jt(56,`Cache entry required but missing for ${qr(this.configuration,e)}; consider defining ${pe.pretty(this.configuration,\"supportedArchitectures\",pe.Type.CODE)} to cache packages for multiple systems`);return x()}})();this.mutexes.set(e.locatorHash,Be);try{return await Be}finally{this.mutexes.delete(e.locatorHash)}};for(let de;de=this.mutexes.get(e.locatorHash);)await de;let[R,L,U]=await C();R||this.markedFiles.add(L);let z,te=R?()=>h():()=>new Zi(L,{baseFs:p,readOnly:!0}),ae=new Gd(()=>uL(()=>z=te(),de=>`Failed to open the cache entry for ${qr(this.configuration,e)}: ${de}`),V),le=new Hu(L,{baseFs:ae,pathUtils:V}),ce=()=>{z?.discardAndClose()},Ce=u.unstablePackages?.has(e.locatorHash)?null:U;return[le,ce,Ce]}},cut=/^(?:(?<cacheKey>(?<cacheVersion>[0-9]+)(?<cacheSpec>.*))\\/)?(?<hash>.*)$/});var Mx,Ape=Et(()=>{Mx=(r=>(r[r.SCRIPT=0]=\"SCRIPT\",r[r.SHELLCODE=1]=\"SHELLCODE\",r))(Mx||{})});var uut,Ty,i_=Et(()=>{Pt();Nl();Sf();So();uut=[[/^(git(?:\\+(?:https|ssh))?:\\/\\/.*(?:\\.git)?)#(.*)$/,(t,e,r,o)=>`${r}#commit=${o}`],[/^https:\\/\\/((?:[^/]+?)@)?codeload\\.github\\.com\\/([^/]+\\/[^/]+)\\/tar\\.gz\\/([0-9a-f]+)$/,(t,e,r=\"\",o,a)=>`https://${r}github.com/${o}.git#commit=${a}`],[/^https:\\/\\/((?:[^/]+?)@)?github\\.com\\/([^/]+\\/[^/]+?)(?:\\.git)?#([0-9a-f]+)$/,(t,e,r=\"\",o,a)=>`https://${r}github.com/${o}.git#commit=${a}`],[/^https?:\\/\\/[^/]+\\/(?:[^/]+\\/)*(?:@.+(?:\\/|(?:%2f)))?([^/]+)\\/(?:-|download)\\/\\1-[^/]+\\.tgz(?:#|$)/,t=>`npm:${t}`],[/^https:\\/\\/npm\\.pkg\\.github\\.com\\/download\\/(?:@[^/]+)\\/(?:[^/]+)\\/(?:[^/]+)\\/(?:[0-9a-f]+)(?:#|$)/,t=>`npm:${t}`],[/^https:\\/\\/npm\\.fontawesome\\.com\\/(?:@[^/]+)\\/([^/]+)\\/-\\/([^/]+)\\/\\1-\\2.tgz(?:#|$)/,t=>`npm:${t}`],[/^https?:\\/\\/[^/]+\\/.*\\/(@[^/]+)\\/([^/]+)\\/-\\/\\1\\/\\2-(?:[.\\d\\w-]+)\\.tgz(?:#|$)/,(t,e)=>bb({protocol:\"npm:\",source:null,selector:t,params:{__archiveUrl:e}})],[/^[^/]+\\.tgz#[0-9a-f]+$/,t=>`npm:${t}`]],Ty=class{constructor(e){this.resolver=e;this.resolutions=null}async setup(e,{report:r}){let o=V.join(e.cwd,dr.lockfile);if(!oe.existsSync(o))return;let a=await oe.readFilePromise(o,\"utf8\"),n=Ki(a);if(Object.hasOwn(n,\"__metadata\"))return;let u=this.resolutions=new Map;for(let A of Object.keys(n)){let p=jI(A);if(!p){r.reportWarning(14,`Failed to parse the string \"${A}\" into a proper descriptor`);continue}let h=Qa(p.range)?In(p,`npm:${p.range}`):p,{version:E,resolved:I}=n[A];if(!I)continue;let v;for(let[C,R]of uut){let L=I.match(C);if(L){v=R(E,...L);break}}if(!v){r.reportWarning(14,`${jn(e.configuration,h)}: Only some patterns can be imported from legacy lockfiles (not \"${I}\")`);continue}let x=h;try{let C=dg(h.range),R=jI(C.selector,!0);R&&(x=R)}catch{}u.set(h.descriptorHash,Rs(x,v))}}supportsDescriptor(e,r){return this.resolutions?this.resolutions.has(e.descriptorHash):!1}supportsLocator(e,r){return!1}shouldPersistResolution(e,r){throw new Error(\"Assertion failed: This resolver doesn't support resolving locators to packages\")}bindDescriptor(e,r,o){return e}getResolutionDependencies(e,r){return{}}async getCandidates(e,r,o){if(!this.resolutions)throw new Error(\"Assertion failed: The resolution store should have been setup\");let a=this.resolutions.get(e.descriptorHash);if(!a)throw new Error(\"Assertion failed: The resolution should have been registered\");let n=YM(a),u=o.project.configuration.normalizeDependency(n);return await this.resolver.getCandidates(u,r,o)}async getSatisfying(e,r,o,a){let[n]=await this.getCandidates(e,r,a);return{locators:o.filter(u=>u.locatorHash===n.locatorHash),sorted:!1}}async resolve(e,r){throw new Error(\"Assertion failed: This resolver doesn't support resolving locators to packages\")}}});var AA,fpe=Et(()=>{Wl();I1();jl();AA=class extends Zs{constructor({configuration:r,stdout:o,suggestInstall:a=!0}){super();this.errorCount=0;TI(this,{configuration:r}),this.configuration=r,this.stdout=o,this.suggestInstall=a}static async start(r,o){let a=new this(r);try{await o(a)}catch(n){a.reportExceptionOnce(n)}finally{await a.finalize()}return a}hasErrors(){return this.errorCount>0}exitCode(){return this.hasErrors()?1:0}reportCacheHit(r){}reportCacheMiss(r){}startSectionSync(r,o){return o()}async startSectionPromise(r,o){return await o()}startTimerSync(r,o,a){return(typeof o==\"function\"?o:a)()}async startTimerPromise(r,o,a){return await(typeof o==\"function\"?o:a)()}reportSeparator(){}reportInfo(r,o){}reportWarning(r,o){}reportError(r,o){this.errorCount+=1,this.stdout.write(`${Ot(this.configuration,\"\\u27A4\",\"redBright\")} ${this.formatNameWithHyperlink(r)}: ${o}\n`)}reportProgress(r){return{...Promise.resolve().then(async()=>{for await(let{}of r);}),stop:()=>{}}}reportJson(r){}reportFold(r,o){}async finalize(){this.errorCount>0&&(this.stdout.write(`\n`),this.stdout.write(`${Ot(this.configuration,\"\\u27A4\",\"redBright\")} Errors happened when preparing the environment required to run this command.\n`),this.suggestInstall&&this.stdout.write(`${Ot(this.configuration,\"\\u27A4\",\"redBright\")} This might be caused by packages being missing from the lockfile, in which case running \"yarn install\" might help.\n`))}formatNameWithHyperlink(r){return AU(r,{configuration:this.configuration,json:!1})}}});var Ny,s_=Et(()=>{So();Ny=class{constructor(e){this.resolver=e}supportsDescriptor(e,r){return!!(r.project.storedResolutions.get(e.descriptorHash)||r.project.originalPackages.has(vb(e).locatorHash))}supportsLocator(e,r){return!!(r.project.originalPackages.has(e.locatorHash)&&!r.project.lockfileNeedsRefresh)}shouldPersistResolution(e,r){throw new Error(\"The shouldPersistResolution method shouldn't be called on the lockfile resolver, which would always answer yes\")}bindDescriptor(e,r,o){return e}getResolutionDependencies(e,r){return this.resolver.getResolutionDependencies(e,r)}async getCandidates(e,r,o){let a=o.project.storedResolutions.get(e.descriptorHash);if(a){let u=o.project.originalPackages.get(a);if(u)return[u]}let n=o.project.originalPackages.get(vb(e).locatorHash);if(n)return[n];throw new Error(\"Resolution expected from the lockfile data\")}async getSatisfying(e,r,o,a){let[n]=await this.getCandidates(e,r,a);return{locators:o.filter(u=>u.locatorHash===n.locatorHash),sorted:!1}}async resolve(e,r){let o=r.project.originalPackages.get(e.locatorHash);if(!o)throw new Error(\"The lockfile resolver isn't meant to resolve packages - they should already have been stored into a cache\");return o}}});function Gf(){}function Aut(t,e,r,o,a){for(var n=0,u=e.length,A=0,p=0;n<u;n++){var h=e[n];if(h.removed){if(h.value=t.join(o.slice(p,p+h.count)),p+=h.count,n&&e[n-1].added){var I=e[n-1];e[n-1]=e[n],e[n]=I}}else{if(!h.added&&a){var E=r.slice(A,A+h.count);E=E.map(function(x,C){var R=o[p+C];return R.length>x.length?R:x}),h.value=t.join(E)}else h.value=t.join(r.slice(A,A+h.count));A+=h.count,h.added||(p+=h.count)}}var v=e[u-1];return u>1&&typeof v.value==\"string\"&&(v.added||v.removed)&&t.equals(\"\",v.value)&&(e[u-2].value+=v.value,e.pop()),e}function fut(t){return{newPos:t.newPos,components:t.components.slice(0)}}function put(t,e){if(typeof t==\"function\")e.callback=t;else if(t)for(var r in t)t.hasOwnProperty(r)&&(e[r]=t[r]);return e}function gpe(t,e,r){return r=put(r,{ignoreWhitespace:!0}),u_.diff(t,e,r)}function hut(t,e,r){return A_.diff(t,e,r)}function Ox(t){\"@babel/helpers - typeof\";return typeof Symbol==\"function\"&&typeof Symbol.iterator==\"symbol\"?Ox=function(e){return typeof e}:Ox=function(e){return e&&typeof Symbol==\"function\"&&e.constructor===Symbol&&e!==Symbol.prototype?\"symbol\":typeof e},Ox(t)}function o_(t){return mut(t)||yut(t)||Eut(t)||Cut()}function mut(t){if(Array.isArray(t))return a_(t)}function yut(t){if(typeof Symbol<\"u\"&&Symbol.iterator in Object(t))return Array.from(t)}function Eut(t,e){if(t){if(typeof t==\"string\")return a_(t,e);var r=Object.prototype.toString.call(t).slice(8,-1);if(r===\"Object\"&&t.constructor&&(r=t.constructor.name),r===\"Map\"||r===\"Set\")return Array.from(t);if(r===\"Arguments\"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r))return a_(t,e)}}function a_(t,e){(e==null||e>t.length)&&(e=t.length);for(var r=0,o=new Array(e);r<e;r++)o[r]=t[r];return o}function Cut(){throw new TypeError(`Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function l_(t,e,r,o,a){e=e||[],r=r||[],o&&(t=o(a,t));var n;for(n=0;n<e.length;n+=1)if(e[n]===t)return r[n];var u;if(wut.call(t)===\"[object Array]\"){for(e.push(t),u=new Array(t.length),r.push(u),n=0;n<t.length;n+=1)u[n]=l_(t[n],e,r,o,a);return e.pop(),r.pop(),u}if(t&&t.toJSON&&(t=t.toJSON()),Ox(t)===\"object\"&&t!==null){e.push(t),u={},r.push(u);var A=[],p;for(p in t)t.hasOwnProperty(p)&&A.push(p);for(A.sort(),n=0;n<A.length;n+=1)p=A[n],u[p]=l_(t[p],e,r,o,p);e.pop(),r.pop()}else u=t;return u}function dpe(t,e,r,o,a,n,u){u||(u={}),typeof u.context>\"u\"&&(u.context=4);var A=hut(r,o,u);if(!A)return;A.push({value:\"\",lines:[]});function p(U){return U.map(function(z){return\" \"+z})}for(var h=[],E=0,I=0,v=[],x=1,C=1,R=function(z){var te=A[z],ae=te.lines||te.value.replace(/\\n$/,\"\").split(`\n`);if(te.lines=ae,te.added||te.removed){var le;if(!E){var ce=A[z-1];E=x,I=C,ce&&(v=u.context>0?p(ce.lines.slice(-u.context)):[],E-=v.length,I-=v.length)}(le=v).push.apply(le,o_(ae.map(function(Ae){return(te.added?\"+\":\"-\")+Ae}))),te.added?C+=ae.length:x+=ae.length}else{if(E)if(ae.length<=u.context*2&&z<A.length-2){var Ce;(Ce=v).push.apply(Ce,o_(p(ae)))}else{var de,Be=Math.min(ae.length,u.context);(de=v).push.apply(de,o_(p(ae.slice(0,Be))));var Ee={oldStart:E,oldLines:x-E+Be,newStart:I,newLines:C-I+Be,lines:v};if(z>=A.length-2&&ae.length<=u.context){var g=/\\n$/.test(r),me=/\\n$/.test(o),we=ae.length==0&&v.length>Ee.oldLines;!g&&we&&r.length>0&&v.splice(Ee.oldLines,0,\"\\\\ No newline at end of file\"),(!g&&!we||!me)&&v.push(\"\\\\ No newline at end of file\")}h.push(Ee),E=0,I=0,v=[]}x+=ae.length,C+=ae.length}},L=0;L<A.length;L++)R(L);return{oldFileName:t,newFileName:e,oldHeader:a,newHeader:n,hunks:h}}var c3t,ppe,hpe,u_,A_,gut,dut,wut,G1,c_,f_=Et(()=>{Gf.prototype={diff:function(e,r){var o=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},a=o.callback;typeof o==\"function\"&&(a=o,o={}),this.options=o;var n=this;function u(R){return a?(setTimeout(function(){a(void 0,R)},0),!0):R}e=this.castInput(e),r=this.castInput(r),e=this.removeEmpty(this.tokenize(e)),r=this.removeEmpty(this.tokenize(r));var A=r.length,p=e.length,h=1,E=A+p;o.maxEditLength&&(E=Math.min(E,o.maxEditLength));var I=[{newPos:-1,components:[]}],v=this.extractCommon(I[0],r,e,0);if(I[0].newPos+1>=A&&v+1>=p)return u([{value:this.join(r),count:r.length}]);function x(){for(var R=-1*h;R<=h;R+=2){var L=void 0,U=I[R-1],z=I[R+1],te=(z?z.newPos:0)-R;U&&(I[R-1]=void 0);var ae=U&&U.newPos+1<A,le=z&&0<=te&&te<p;if(!ae&&!le){I[R]=void 0;continue}if(!ae||le&&U.newPos<z.newPos?(L=fut(z),n.pushComponent(L.components,void 0,!0)):(L=U,L.newPos++,n.pushComponent(L.components,!0,void 0)),te=n.extractCommon(L,r,e,R),L.newPos+1>=A&&te+1>=p)return u(Aut(n,L.components,r,e,n.useLongestToken));I[R]=L}h++}if(a)(function R(){setTimeout(function(){if(h>E)return a();x()||R()},0)})();else for(;h<=E;){var C=x();if(C)return C}},pushComponent:function(e,r,o){var a=e[e.length-1];a&&a.added===r&&a.removed===o?e[e.length-1]={count:a.count+1,added:r,removed:o}:e.push({count:1,added:r,removed:o})},extractCommon:function(e,r,o,a){for(var n=r.length,u=o.length,A=e.newPos,p=A-a,h=0;A+1<n&&p+1<u&&this.equals(r[A+1],o[p+1]);)A++,p++,h++;return h&&e.components.push({count:h}),e.newPos=A,p},equals:function(e,r){return this.options.comparator?this.options.comparator(e,r):e===r||this.options.ignoreCase&&e.toLowerCase()===r.toLowerCase()},removeEmpty:function(e){for(var r=[],o=0;o<e.length;o++)e[o]&&r.push(e[o]);return r},castInput:function(e){return e},tokenize:function(e){return e.split(\"\")},join:function(e){return e.join(\"\")}};c3t=new Gf;ppe=/^[A-Za-z\\xC0-\\u02C6\\u02C8-\\u02D7\\u02DE-\\u02FF\\u1E00-\\u1EFF]+$/,hpe=/\\S/,u_=new Gf;u_.equals=function(t,e){return this.options.ignoreCase&&(t=t.toLowerCase(),e=e.toLowerCase()),t===e||this.options.ignoreWhitespace&&!hpe.test(t)&&!hpe.test(e)};u_.tokenize=function(t){for(var e=t.split(/([^\\S\\r\\n]+|[()[\\]{}'\"\\r\\n]|\\b)/),r=0;r<e.length-1;r++)!e[r+1]&&e[r+2]&&ppe.test(e[r])&&ppe.test(e[r+2])&&(e[r]+=e[r+2],e.splice(r+1,2),r--);return e};A_=new Gf;A_.tokenize=function(t){var e=[],r=t.split(/(\\n|\\r\\n)/);r[r.length-1]||r.pop();for(var o=0;o<r.length;o++){var a=r[o];o%2&&!this.options.newlineIsToken?e[e.length-1]+=a:(this.options.ignoreWhitespace&&(a=a.trim()),e.push(a))}return e};gut=new Gf;gut.tokenize=function(t){return t.split(/(\\S.+?[.!?])(?=\\s+|$)/)};dut=new Gf;dut.tokenize=function(t){return t.split(/([{}:;,]|\\s+)/)};wut=Object.prototype.toString,G1=new Gf;G1.useLongestToken=!0;G1.tokenize=A_.tokenize;G1.castInput=function(t){var e=this.options,r=e.undefinedReplacement,o=e.stringifyReplacer,a=o===void 0?function(n,u){return typeof u>\"u\"?r:u}:o;return typeof t==\"string\"?t:JSON.stringify(l_(t,null,null,a),a,\"  \")};G1.equals=function(t,e){return Gf.prototype.equals.call(G1,t.replace(/,([\\r\\n])/g,\"$1\"),e.replace(/,([\\r\\n])/g,\"$1\"))};c_=new Gf;c_.tokenize=function(t){return t.slice()};c_.join=c_.removeEmpty=function(t){return t}});var ype=_((A3t,mpe)=>{var Iut=Hl(),But=Ym(),vut=/\\.|\\[(?:[^[\\]]*|([\"'])(?:(?!\\1)[^\\\\]|\\\\.)*?\\1)\\]/,Dut=/^\\w*$/;function Put(t,e){if(Iut(t))return!1;var r=typeof t;return r==\"number\"||r==\"symbol\"||r==\"boolean\"||t==null||But(t)?!0:Dut.test(t)||!vut.test(t)||e!=null&&t in Object(e)}mpe.exports=Put});var wpe=_((f3t,Cpe)=>{var Epe=PP(),but=\"Expected a function\";function p_(t,e){if(typeof t!=\"function\"||e!=null&&typeof e!=\"function\")throw new TypeError(but);var r=function(){var o=arguments,a=e?e.apply(this,o):o[0],n=r.cache;if(n.has(a))return n.get(a);var u=t.apply(this,o);return r.cache=n.set(a,u)||n,u};return r.cache=new(p_.Cache||Epe),r}p_.Cache=Epe;Cpe.exports=p_});var Bpe=_((p3t,Ipe)=>{var Sut=wpe(),xut=500;function kut(t){var e=Sut(t,function(o){return r.size===xut&&r.clear(),o}),r=e.cache;return e}Ipe.exports=kut});var h_=_((h3t,vpe)=>{var Qut=Bpe(),Fut=/[^.[\\]]+|\\[(?:(-?\\d+(?:\\.\\d+)?)|([\"'])((?:(?!\\2)[^\\\\]|\\\\.)*?)\\2)\\]|(?=(?:\\.|\\[\\])(?:\\.|\\[\\]|$))/g,Rut=/\\\\(\\\\)?/g,Tut=Qut(function(t){var e=[];return t.charCodeAt(0)===46&&e.push(\"\"),t.replace(Fut,function(r,o,a,n){e.push(a?n.replace(Rut,\"$1\"):o||r)}),e});vpe.exports=Tut});var Mg=_((g3t,Dpe)=>{var Nut=Hl(),Lut=ype(),Mut=h_(),Out=C1();function Uut(t,e){return Nut(t)?t:Lut(t,e)?[t]:Mut(Out(t))}Dpe.exports=Uut});var Ly=_((d3t,Ppe)=>{var _ut=Ym(),Hut=1/0;function qut(t){if(typeof t==\"string\"||_ut(t))return t;var e=t+\"\";return e==\"0\"&&1/t==-Hut?\"-0\":e}Ppe.exports=qut});var Ux=_((m3t,bpe)=>{var jut=Mg(),Gut=Ly();function Yut(t,e){e=jut(e,t);for(var r=0,o=e.length;t!=null&&r<o;)t=t[Gut(e[r++])];return r&&r==o?t:void 0}bpe.exports=Yut});var g_=_((y3t,xpe)=>{var Wut=qP(),Kut=Mg(),Vut=II(),Spe=sl(),zut=Ly();function Jut(t,e,r,o){if(!Spe(t))return t;e=Kut(e,t);for(var a=-1,n=e.length,u=n-1,A=t;A!=null&&++a<n;){var p=zut(e[a]),h=r;if(p===\"__proto__\"||p===\"constructor\"||p===\"prototype\")return t;if(a!=u){var E=A[p];h=o?o(E,p,A):void 0,h===void 0&&(h=Spe(E)?E:Vut(e[a+1])?[]:{})}Wut(A,p,h),A=A[p]}return t}xpe.exports=Jut});var Qpe=_((E3t,kpe)=>{var Xut=Ux(),Zut=g_(),$ut=Mg();function eAt(t,e,r){for(var o=-1,a=e.length,n={};++o<a;){var u=e[o],A=Xut(t,u);r(A,u)&&Zut(n,$ut(u,t),A)}return n}kpe.exports=eAt});var Rpe=_((C3t,Fpe)=>{function tAt(t,e){return t!=null&&e in Object(t)}Fpe.exports=tAt});var d_=_((w3t,Tpe)=>{var rAt=Mg(),nAt=EI(),iAt=Hl(),sAt=II(),oAt=QP(),aAt=Ly();function lAt(t,e,r){e=rAt(e,t);for(var o=-1,a=e.length,n=!1;++o<a;){var u=aAt(e[o]);if(!(n=t!=null&&r(t,u)))break;t=t[u]}return n||++o!=a?n:(a=t==null?0:t.length,!!a&&oAt(a)&&sAt(u,a)&&(iAt(t)||nAt(t)))}Tpe.exports=lAt});var Lpe=_((I3t,Npe)=>{var cAt=Rpe(),uAt=d_();function AAt(t,e){return t!=null&&uAt(t,e,cAt)}Npe.exports=AAt});var Ope=_((B3t,Mpe)=>{var fAt=Qpe(),pAt=Lpe();function hAt(t,e){return fAt(t,e,function(r,o){return pAt(t,o)})}Mpe.exports=hAt});var qpe=_((v3t,Hpe)=>{var Upe=lg(),gAt=EI(),dAt=Hl(),_pe=Upe?Upe.isConcatSpreadable:void 0;function mAt(t){return dAt(t)||gAt(t)||!!(_pe&&t&&t[_pe])}Hpe.exports=mAt});var Ype=_((D3t,Gpe)=>{var yAt=xP(),EAt=qpe();function jpe(t,e,r,o,a){var n=-1,u=t.length;for(r||(r=EAt),a||(a=[]);++n<u;){var A=t[n];e>0&&r(A)?e>1?jpe(A,e-1,r,o,a):yAt(a,A):o||(a[a.length]=A)}return a}Gpe.exports=jpe});var Kpe=_((P3t,Wpe)=>{var CAt=Ype();function wAt(t){var e=t==null?0:t.length;return e?CAt(t,1):[]}Wpe.exports=wAt});var m_=_((b3t,Vpe)=>{var IAt=Kpe(),BAt=rL(),vAt=nL();function DAt(t){return vAt(BAt(t,void 0,IAt),t+\"\")}Vpe.exports=DAt});var y_=_((S3t,zpe)=>{var PAt=Ope(),bAt=m_(),SAt=bAt(function(t,e){return t==null?{}:PAt(t,e)});zpe.exports=SAt});var _x,Jpe=Et(()=>{Wl();_x=class{constructor(e){this.resolver=e}supportsDescriptor(e,r){return this.resolver.supportsDescriptor(e,r)}supportsLocator(e,r){return this.resolver.supportsLocator(e,r)}shouldPersistResolution(e,r){return this.resolver.shouldPersistResolution(e,r)}bindDescriptor(e,r,o){return this.resolver.bindDescriptor(e,r,o)}getResolutionDependencies(e,r){return this.resolver.getResolutionDependencies(e,r)}async getCandidates(e,r,o){throw new Jt(20,`This package doesn't seem to be present in your lockfile; run \"yarn install\" to update the lockfile`)}async getSatisfying(e,r,o,a){throw new Jt(20,`This package doesn't seem to be present in your lockfile; run \"yarn install\" to update the lockfile`)}async resolve(e,r){throw new Jt(20,`This package doesn't seem to be present in your lockfile; run \"yarn install\" to update the lockfile`)}}});var ki,E_=Et(()=>{Wl();ki=class extends Zs{reportCacheHit(e){}reportCacheMiss(e){}startSectionSync(e,r){return r()}async startSectionPromise(e,r){return await r()}startTimerSync(e,r,o){return(typeof r==\"function\"?r:o)()}async startTimerPromise(e,r,o){return await(typeof r==\"function\"?r:o)()}reportSeparator(){}reportInfo(e,r){}reportWarning(e,r){}reportError(e,r){}reportProgress(e){return{...Promise.resolve().then(async()=>{for await(let{}of e);}),stop:()=>{}}}reportJson(e){}reportFold(e,r){}async finalize(){}}});var Xpe,My,C_=Et(()=>{Pt();Xpe=Ze(Cb());Gm();mg();jl();th();Sf();So();My=class{constructor(e,{project:r}){this.workspacesCwds=new Set;this.project=r,this.cwd=e}async setup(){this.manifest=await Ut.tryFind(this.cwd)??new Ut,this.relativeCwd=V.relative(this.project.cwd,this.cwd)||It.dot;let e=this.manifest.name?this.manifest.name:eA(null,`${this.computeCandidateName()}-${zi(this.relativeCwd).substring(0,6)}`);this.anchoredDescriptor=In(e,`${ei.protocol}${this.relativeCwd}`),this.anchoredLocator=Rs(e,`${ei.protocol}${this.relativeCwd}`);let r=this.manifest.workspaceDefinitions.map(({pattern:a})=>a);if(r.length===0)return;let o=await(0,Xpe.default)(r,{cwd:ue.fromPortablePath(this.cwd),onlyDirectories:!0,ignore:[\"**/node_modules\",\"**/.git\",\"**/.yarn\"]});o.sort(),await o.reduce(async(a,n)=>{let u=V.resolve(this.cwd,ue.toPortablePath(n)),A=await oe.existsPromise(V.join(u,\"package.json\"));await a,A&&this.workspacesCwds.add(u)},Promise.resolve())}get anchoredPackage(){let e=this.project.storedPackages.get(this.anchoredLocator.locatorHash);if(!e)throw new Error(`Assertion failed: Expected workspace ${YI(this.project.configuration,this)} (${Ot(this.project.configuration,V.join(this.cwd,dr.manifest),yt.PATH)}) to have been resolved. Run \"yarn install\" to update the lockfile`);return e}accepts(e){let r=e.indexOf(\":\"),o=r!==-1?e.slice(0,r+1):null,a=r!==-1?e.slice(r+1):e;if(o===ei.protocol&&V.normalize(a)===this.relativeCwd||o===ei.protocol&&(a===\"*\"||a===\"^\"||a===\"~\"))return!0;let n=Qa(a);return n?o===ei.protocol?n.test(this.manifest.version??\"0.0.0\"):this.project.configuration.get(\"enableTransparentWorkspaces\")&&this.manifest.version!==null?n.test(this.manifest.version):!1:!1}computeCandidateName(){return this.cwd===this.project.cwd?\"root-workspace\":`${V.basename(this.cwd)}`||\"unnamed-workspace\"}getRecursiveWorkspaceDependencies({dependencies:e=Ut.hardDependencies}={}){let r=new Set,o=a=>{for(let n of e)for(let u of a.manifest[n].values()){let A=this.project.tryWorkspaceByDescriptor(u);A===null||r.has(A)||(r.add(A),o(A))}};return o(this),r}getRecursiveWorkspaceDependents({dependencies:e=Ut.hardDependencies}={}){let r=new Set,o=a=>{for(let n of this.project.workspaces)e.some(A=>[...n.manifest[A].values()].some(p=>{let h=this.project.tryWorkspaceByDescriptor(p);return h!==null&&qI(h.anchoredLocator,a.anchoredLocator)}))&&!r.has(n)&&(r.add(n),o(n))};return o(this),r}getRecursiveWorkspaceChildren(){let e=new Set([this]);for(let r of e)for(let o of r.workspacesCwds){let a=this.project.workspacesByCwd.get(o);a&&e.add(a)}return e.delete(this),Array.from(e)}async persistManifest(){let e={};this.manifest.exportTo(e);let r=V.join(this.cwd,Ut.fileName),o=`${JSON.stringify(e,null,this.manifest.indent)}\n`;await oe.changeFilePromise(r,o,{automaticNewlines:!0}),this.manifest.raw=e}}});function TAt({project:t,allDescriptors:e,allResolutions:r,allPackages:o,accessibleLocators:a=new Set,optionalBuilds:n=new Set,peerRequirements:u=new Map,peerWarnings:A=[],peerRequirementNodes:p=new Map,volatileDescriptors:h=new Set}){let E=new Map,I=[],v=new Map,x=new Map,C=new Map,R=new Map,L=new Map(t.workspaces.map(le=>{let ce=le.anchoredLocator.locatorHash,Ce=o.get(ce);if(typeof Ce>\"u\")throw new Error(\"Assertion failed: The workspace should have an associated package\");return[ce,OI(Ce)]})),U=()=>{let le=oe.mktempSync(),ce=V.join(le,\"stacktrace.log\"),Ce=String(I.length+1).length,de=I.map((Be,Ee)=>`${`${Ee+1}.`.padStart(Ce,\" \")} ${ka(Be)}\n`).join(\"\");throw oe.writeFileSync(ce,de),oe.detachTemp(le),new Jt(45,`Encountered a stack overflow when resolving peer dependencies; cf ${ue.fromPortablePath(ce)}`)},z=le=>{let ce=r.get(le.descriptorHash);if(typeof ce>\"u\")throw new Error(\"Assertion failed: The resolution should have been registered\");let Ce=o.get(ce);if(!Ce)throw new Error(\"Assertion failed: The package could not be found\");return Ce},te=(le,ce,Ce,{top:de,optional:Be})=>{I.length>1e3&&U(),I.push(ce);let Ee=ae(le,ce,Ce,{top:de,optional:Be});return I.pop(),Ee},ae=(le,ce,Ce,{top:de,optional:Be})=>{if(Be||n.delete(ce.locatorHash),a.has(ce.locatorHash))return;a.add(ce.locatorHash);let Ee=o.get(ce.locatorHash);if(!Ee)throw new Error(`Assertion failed: The package (${qr(t.configuration,ce)}) should have been registered`);let g=[],me=new Map,we=[],Ae=[],ne=[],Z=[];for(let Ne of Array.from(Ee.dependencies.values())){if(Ee.peerDependencies.has(Ne.identHash)&&Ee.locatorHash!==de)continue;if(Pf(Ne))throw new Error(\"Assertion failed: Virtual packages shouldn't be encountered when virtualizing a branch\");h.delete(Ne.descriptorHash);let ht=Be;if(!ht){let be=Ee.dependenciesMeta.get(rn(Ne));if(typeof be<\"u\"){let et=be.get(null);typeof et<\"u\"&&et.optional&&(ht=!0)}}let H=r.get(Ne.descriptorHash);if(!H)throw new Error(`Assertion failed: The resolution (${jn(t.configuration,Ne)}) should have been registered`);let rt=L.get(H)||o.get(H);if(!rt)throw new Error(`Assertion failed: The package (${H}, resolved from ${jn(t.configuration,Ne)}) should have been registered`);if(rt.peerDependencies.size===0){te(Ne,rt,new Map,{top:de,optional:ht});continue}let Te,Fe,ke=new Set,Ye=new Map;we.push(()=>{Te=KM(Ne,ce.locatorHash),Fe=VM(rt,ce.locatorHash),Ee.dependencies.delete(Ne.identHash),Ee.dependencies.set(Te.identHash,Te),r.set(Te.descriptorHash,Fe.locatorHash),e.set(Te.descriptorHash,Te),o.set(Fe.locatorHash,Fe),g.push([rt,Te,Fe])}),Ae.push(()=>{R.set(Fe.locatorHash,Ye);for(let be of Fe.peerDependencies.values()){let Ue=al(me,be.identHash,()=>{let S=Ce.get(be.identHash)??null,w=Ee.dependencies.get(be.identHash);return!w&&HI(ce,be)&&(le.identHash===ce.identHash?w=le:(w=In(ce,le.range),e.set(w.descriptorHash,w),r.set(w.descriptorHash,ce.locatorHash),h.delete(w.descriptorHash),S=null)),w||(w=In(be,\"missing:\")),{subject:ce,ident:be,provided:w,root:!S,requests:new Map,hash:`p${zi(ce.locatorHash,be.identHash).slice(0,5)}`}}).provided;if(Ue.range===\"missing:\"&&Fe.dependencies.has(be.identHash)){Fe.peerDependencies.delete(be.identHash);continue}Ye.set(be.identHash,{requester:Fe,descriptor:be,meta:Fe.peerDependenciesMeta.get(rn(be)),children:new Map}),Fe.dependencies.set(be.identHash,Ue),Pf(Ue)&&Sm(C,Ue.descriptorHash).add(Fe.locatorHash),v.set(Ue.identHash,Ue),Ue.range===\"missing:\"&&ke.add(Ue.identHash)}Fe.dependencies=new Map(Fs(Fe.dependencies,([be,et])=>rn(et)))}),ne.push(()=>{if(!o.has(Fe.locatorHash))return;let be=E.get(rt.locatorHash);typeof be==\"number\"&&be>=2&&U();let et=E.get(rt.locatorHash),Ue=typeof et<\"u\"?et+1:1;E.set(rt.locatorHash,Ue),te(Te,Fe,Ye,{top:de,optional:ht}),E.set(rt.locatorHash,Ue-1)}),Z.push(()=>{let be=Ee.dependencies.get(Ne.identHash);if(typeof be>\"u\")throw new Error(\"Assertion failed: Expected the peer dependency to have been turned into a dependency\");let et=r.get(be.descriptorHash);if(typeof et>\"u\")throw new Error(\"Assertion failed: Expected the descriptor to be registered\");let Ue=R.get(et);if(typeof Ue>\"u\")throw new Error(\"Assertion failed: Expected the peer requests to be registered\");for(let S of me.values()){let w=Ue.get(S.ident.identHash);w&&(S.requests.set(be.descriptorHash,w),p.set(S.hash,S),S.root||Ce.get(S.ident.identHash)?.children.set(be.descriptorHash,w))}if(o.has(Fe.locatorHash))for(let S of ke)Fe.dependencies.delete(S)})}for(let Ne of[...we,...Ae])Ne();let xe;do{xe=!0;for(let[Ne,ht,H]of g){let rt=kI(x,Ne.locatorHash),Te=zi(...[...H.dependencies.values()].map(be=>{let et=be.range!==\"missing:\"?r.get(be.descriptorHash):\"missing:\";if(typeof et>\"u\")throw new Error(`Assertion failed: Expected the resolution for ${jn(t.configuration,be)} to have been registered`);return et===de?`${et} (top)`:et}),ht.identHash),Fe=rt.get(Te);if(typeof Fe>\"u\"){rt.set(Te,ht);continue}if(Fe===ht)continue;o.delete(H.locatorHash),e.delete(ht.descriptorHash),r.delete(ht.descriptorHash),a.delete(H.locatorHash);let ke=C.get(ht.descriptorHash)||[],Ye=[Ee.locatorHash,...ke];C.delete(ht.descriptorHash);for(let be of Ye){let et=o.get(be);typeof et>\"u\"||(et.dependencies.get(ht.identHash).descriptorHash!==Fe.descriptorHash&&(xe=!1),et.dependencies.set(ht.identHash,Fe))}for(let be of me.values())be.provided.descriptorHash===ht.descriptorHash&&(be.provided=Fe)}}while(!xe);for(let Ne of[...ne,...Z])Ne()};for(let le of t.workspaces){let ce=le.anchoredLocator;h.delete(le.anchoredDescriptor.descriptorHash),te(le.anchoredDescriptor,ce,new Map,{top:ce.locatorHash,optional:!1})}for(let le of p.values()){if(!le.root)continue;let ce=o.get(le.subject.locatorHash);if(typeof ce>\"u\")continue;for(let de of le.requests.values()){let Be=`p${zi(le.subject.locatorHash,rn(le.ident),de.requester.locatorHash).slice(0,5)}`;u.set(Be,{subject:le.subject.locatorHash,requested:le.ident,rootRequester:de.requester.locatorHash,allRequesters:Array.from(WI(de),Ee=>Ee.requester.locatorHash)})}let Ce=[...WI(le)];if(le.provided.range!==\"missing:\"){let de=z(le.provided),Be=de.version??\"0.0.0\",Ee=me=>{if(me.startsWith(ei.protocol)){if(!t.tryWorkspaceByLocator(de))return null;me=me.slice(ei.protocol.length),(me===\"^\"||me===\"~\")&&(me=\"*\")}return me},g=!0;for(let me of Ce){let we=Ee(me.descriptor.range);if(we===null){g=!1;continue}if(!tA(Be,we)){g=!1;let Ae=`p${zi(le.subject.locatorHash,rn(le.ident),me.requester.locatorHash).slice(0,5)}`;A.push({type:1,subject:ce,requested:le.ident,requester:me.requester,version:Be,hash:Ae,requirementCount:Ce.length})}}if(!g){let me=Ce.map(we=>Ee(we.descriptor.range));A.push({type:3,node:le,range:me.includes(null)?null:XM(me),hash:le.hash})}}else{let de=!0;for(let Be of Ce)if(!Be.meta?.optional){de=!1;let Ee=`p${zi(le.subject.locatorHash,rn(le.ident),Be.requester.locatorHash).slice(0,5)}`;A.push({type:0,subject:ce,requested:le.ident,requester:Be.requester,hash:Ee})}de||A.push({type:2,node:le,hash:le.hash})}}}function*NAt(t){let e=new Map;if(\"children\"in t)e.set(t,t);else for(let r of t.requests.values())e.set(r,r);for(let[r,o]of e){yield{request:r,root:o};for(let a of r.children.values())e.has(a)||e.set(a,o)}}function LAt(t,e){let r=[],o=[],a=!1;for(let n of t.peerWarnings)if(!(n.type===1||n.type===0)){if(!t.tryWorkspaceByLocator(n.node.subject)){a=!0;continue}if(n.type===3){let u=t.storedResolutions.get(n.node.provided.descriptorHash);if(typeof u>\"u\")throw new Error(\"Assertion failed: Expected the descriptor to be registered\");let A=t.storedPackages.get(u);if(typeof A>\"u\")throw new Error(\"Assertion failed: Expected the package to be registered\");let p=Vp(NAt(n.node),({request:I,root:v})=>tA(A.version??\"0.0.0\",I.descriptor.range)?Vp.skip:I===v?Oi(t.configuration,I.requester):`${Oi(t.configuration,I.requester)} (via ${Oi(t.configuration,v.requester)})`),h=[...WI(n.node)].length>1?\"and other dependencies request\":\"requests\",E=n.range?qm(t.configuration,n.range):Ot(t.configuration,\"but they have non-overlapping ranges!\",\"redBright\");r.push(`${Oi(t.configuration,n.node.ident)} is listed by your project with version ${GI(t.configuration,A.version??\"0.0.0\")} (${Ot(t.configuration,n.hash,yt.CODE)}), which doesn't satisfy what ${p} ${h} (${E}).`)}if(n.type===2){let u=n.node.requests.size>1?\" and other dependencies\":\"\";o.push(`${qr(t.configuration,n.node.subject)} doesn't provide ${Oi(t.configuration,n.node.ident)} (${Ot(t.configuration,n.hash,yt.CODE)}), requested by ${Oi(t.configuration,n.node.requests.values().next().value.requester)}${u}.`)}}e.startSectionSync({reportFooter:()=>{e.reportWarning(86,`Some peer dependencies are incorrectly met by your project; run ${Ot(t.configuration,\"yarn explain peer-requirements <hash>\",yt.CODE)} for details, where ${Ot(t.configuration,\"<hash>\",yt.CODE)} is the six-letter p-prefixed code.`)},skipIfEmpty:!0},()=>{for(let n of Fs(r,u=>Rm.default(u)))e.reportWarning(60,n);for(let n of Fs(o,u=>Rm.default(u)))e.reportWarning(2,n)}),a&&e.reportWarning(86,`Some peer dependencies are incorrectly met by dependencies; run ${Ot(t.configuration,\"yarn explain peer-requirements\",yt.CODE)} for details.`)}var Hx,qx,jx,ehe,B_,I_,v_,Gx,xAt,kAt,Zpe,QAt,FAt,RAt,hl,w_,Yx,$pe,kt,the=Et(()=>{Pt();Pt();Nl();qt();Hx=ve(\"crypto\");f_();qx=Ze(y_()),jx=Ze(eg()),ehe=Ze(Jn()),B_=ve(\"util\"),I_=Ze(ve(\"v8\")),v_=Ze(ve(\"zlib\"));n_();u1();i_();s_();Gm();rO();Wl();Jpe();I1();E_();mg();C_();Tb();jl();th();ql();fS();dU();Sf();So();Gx=Qm(process.env.YARN_LOCKFILE_VERSION_OVERRIDE??8),xAt=3,kAt=/ *, */g,Zpe=/\\/$/,QAt=32,FAt=(0,B_.promisify)(v_.default.gzip),RAt=(0,B_.promisify)(v_.default.gunzip),hl=(r=>(r.UpdateLockfile=\"update-lockfile\",r.SkipBuild=\"skip-build\",r))(hl||{}),w_={restoreLinkersCustomData:[\"linkersCustomData\"],restoreResolutions:[\"accessibleLocators\",\"conditionalLocators\",\"disabledLocators\",\"optionalBuilds\",\"storedDescriptors\",\"storedResolutions\",\"storedPackages\",\"lockFileChecksum\"],restoreBuildState:[\"skippedBuilds\",\"storedBuildState\"]},Yx=(a=>(a[a.NotProvided=0]=\"NotProvided\",a[a.NotCompatible=1]=\"NotCompatible\",a[a.NodeNotProvided=2]=\"NodeNotProvided\",a[a.NodeNotCompatible=3]=\"NodeNotCompatible\",a))(Yx||{}),$pe=t=>zi(`${xAt}`,t),kt=class t{constructor(e,{configuration:r}){this.resolutionAliases=new Map;this.workspaces=[];this.workspacesByCwd=new Map;this.workspacesByIdent=new Map;this.storedResolutions=new Map;this.storedDescriptors=new Map;this.storedPackages=new Map;this.storedChecksums=new Map;this.storedBuildState=new Map;this.accessibleLocators=new Set;this.conditionalLocators=new Set;this.disabledLocators=new Set;this.originalPackages=new Map;this.optionalBuilds=new Set;this.skippedBuilds=new Set;this.lockfileLastVersion=null;this.lockfileNeedsRefresh=!1;this.peerRequirements=new Map;this.peerWarnings=[];this.peerRequirementNodes=new Map;this.linkersCustomData=new Map;this.lockFileChecksum=null;this.installStateChecksum=null;this.configuration=r,this.cwd=e}static async find(e,r){if(!e.projectCwd)throw new st(`No project found in ${r}`);let o=e.projectCwd,a=r,n=null;for(;n!==e.projectCwd;){if(n=a,oe.existsSync(V.join(n,dr.manifest))){o=n;break}a=V.dirname(n)}let u=new t(e.projectCwd,{configuration:e});Ke.telemetry?.reportProject(u.cwd),await u.setupResolutions(),await u.setupWorkspaces(),Ke.telemetry?.reportWorkspaceCount(u.workspaces.length),Ke.telemetry?.reportDependencyCount(u.workspaces.reduce((C,R)=>C+R.manifest.dependencies.size+R.manifest.devDependencies.size,0));let A=u.tryWorkspaceByCwd(o);if(A)return{project:u,workspace:A,locator:A.anchoredLocator};let p=await u.findLocatorForLocation(`${o}/`,{strict:!0});if(p)return{project:u,locator:p,workspace:null};let h=Ot(e,u.cwd,yt.PATH),E=Ot(e,V.relative(u.cwd,o),yt.PATH),I=`- If ${h} isn't intended to be a project, remove any yarn.lock and/or package.json file there.`,v=`- If ${h} is intended to be a project, it might be that you forgot to list ${E} in its workspace configuration.`,x=`- Finally, if ${h} is fine and you intend ${E} to be treated as a completely separate project (not even a workspace), create an empty yarn.lock file in it.`;throw new st(`The nearest package directory (${Ot(e,o,yt.PATH)}) doesn't seem to be part of the project declared in ${Ot(e,u.cwd,yt.PATH)}.\n\n${[I,v,x].join(`\n`)}`)}async setupResolutions(){this.storedResolutions=new Map,this.storedDescriptors=new Map,this.storedPackages=new Map,this.lockFileChecksum=null;let e=V.join(this.cwd,dr.lockfile),r=this.configuration.get(\"defaultLanguageName\");if(oe.existsSync(e)){let o=await oe.readFilePromise(e,\"utf8\");this.lockFileChecksum=$pe(o);let a=Ki(o);if(a.__metadata){let n=a.__metadata.version,u=a.__metadata.cacheKey;this.lockfileLastVersion=n,this.lockfileNeedsRefresh=n<Gx;for(let A of Object.keys(a)){if(A===\"__metadata\")continue;let p=a[A];if(typeof p.resolution>\"u\")throw new Error(`Assertion failed: Expected the lockfile entry to have a resolution field (${A})`);let h=bf(p.resolution,!0),E=new Ut;E.load(p,{yamlCompatibilityMode:!0});let I=E.version,v=E.languageName||r,x=p.linkType.toUpperCase(),C=p.conditions??null,R=E.dependencies,L=E.peerDependencies,U=E.dependenciesMeta,z=E.peerDependenciesMeta,te=E.bin;if(p.checksum!=null){let le=typeof u<\"u\"&&!p.checksum.includes(\"/\")?`${u}/${p.checksum}`:p.checksum;this.storedChecksums.set(h.locatorHash,le)}let ae={...h,version:I,languageName:v,linkType:x,conditions:C,dependencies:R,peerDependencies:L,dependenciesMeta:U,peerDependenciesMeta:z,bin:te};this.originalPackages.set(ae.locatorHash,ae);for(let le of A.split(kAt)){let ce=rh(le);n<=6&&(ce=this.configuration.normalizeDependency(ce),ce=In(ce,ce.range.replace(/^patch:[^@]+@(?!npm(:|%3A))/,\"$1npm%3A\"))),this.storedDescriptors.set(ce.descriptorHash,ce),this.storedResolutions.set(ce.descriptorHash,h.locatorHash)}}}else o.includes(\"yarn lockfile v1\")&&(this.lockfileLastVersion=-1)}}async setupWorkspaces(){this.workspaces=[],this.workspacesByCwd=new Map,this.workspacesByIdent=new Map;let e=new Set,r=(0,jx.default)(4),o=async(a,n)=>{if(e.has(n))return a;e.add(n);let u=new My(n,{project:this});await r(()=>u.setup());let A=a.then(()=>{this.addWorkspace(u)});return Array.from(u.workspacesCwds).reduce(o,A)};await o(Promise.resolve(),this.cwd)}addWorkspace(e){let r=this.workspacesByIdent.get(e.anchoredLocator.identHash);if(typeof r<\"u\")throw new Error(`Duplicate workspace name ${Oi(this.configuration,e.anchoredLocator)}: ${ue.fromPortablePath(e.cwd)} conflicts with ${ue.fromPortablePath(r.cwd)}`);this.workspaces.push(e),this.workspacesByCwd.set(e.cwd,e),this.workspacesByIdent.set(e.anchoredLocator.identHash,e)}get topLevelWorkspace(){return this.getWorkspaceByCwd(this.cwd)}tryWorkspaceByCwd(e){V.isAbsolute(e)||(e=V.resolve(this.cwd,e)),e=V.normalize(e).replace(/\\/+$/,\"\");let r=this.workspacesByCwd.get(e);return r||null}getWorkspaceByCwd(e){let r=this.tryWorkspaceByCwd(e);if(!r)throw new Error(`Workspace not found (${e})`);return r}tryWorkspaceByFilePath(e){let r=null;for(let o of this.workspaces)V.relative(o.cwd,e).startsWith(\"../\")||r&&r.cwd.length>=o.cwd.length||(r=o);return r||null}getWorkspaceByFilePath(e){let r=this.tryWorkspaceByFilePath(e);if(!r)throw new Error(`Workspace not found (${e})`);return r}tryWorkspaceByIdent(e){let r=this.workspacesByIdent.get(e.identHash);return typeof r>\"u\"?null:r}getWorkspaceByIdent(e){let r=this.tryWorkspaceByIdent(e);if(!r)throw new Error(`Workspace not found (${Oi(this.configuration,e)})`);return r}tryWorkspaceByDescriptor(e){if(e.range.startsWith(ei.protocol)){let o=e.range.slice(ei.protocol.length);if(o!==\"^\"&&o!==\"~\"&&o!==\"*\"&&!Qa(o))return this.tryWorkspaceByCwd(o)}let r=this.tryWorkspaceByIdent(e);return r===null||(Pf(e)&&(e=UI(e)),!r.accepts(e.range))?null:r}getWorkspaceByDescriptor(e){let r=this.tryWorkspaceByDescriptor(e);if(r===null)throw new Error(`Workspace not found (${jn(this.configuration,e)})`);return r}tryWorkspaceByLocator(e){let r=this.tryWorkspaceByIdent(e);return r===null||(Gc(e)&&(e=_I(e)),r.anchoredLocator.locatorHash!==e.locatorHash)?null:r}getWorkspaceByLocator(e){let r=this.tryWorkspaceByLocator(e);if(!r)throw new Error(`Workspace not found (${qr(this.configuration,e)})`);return r}deleteDescriptor(e){this.storedResolutions.delete(e),this.storedDescriptors.delete(e)}deleteLocator(e){this.originalPackages.delete(e),this.storedPackages.delete(e),this.accessibleLocators.delete(e)}forgetResolution(e){if(\"descriptorHash\"in e){let r=this.storedResolutions.get(e.descriptorHash);this.deleteDescriptor(e.descriptorHash);let o=new Set(this.storedResolutions.values());typeof r<\"u\"&&!o.has(r)&&this.deleteLocator(r)}if(\"locatorHash\"in e){this.deleteLocator(e.locatorHash);for(let[r,o]of this.storedResolutions)o===e.locatorHash&&this.deleteDescriptor(r)}}forgetTransientResolutions(){let e=this.configuration.makeResolver(),r=new Map;for(let[o,a]of this.storedResolutions.entries()){let n=r.get(a);n||r.set(a,n=new Set),n.add(o)}for(let o of this.originalPackages.values()){let a;try{a=e.shouldPersistResolution(o,{project:this,resolver:e})}catch{a=!1}if(!a){this.deleteLocator(o.locatorHash);let n=r.get(o.locatorHash);if(n){r.delete(o.locatorHash);for(let u of n)this.deleteDescriptor(u)}}}}forgetVirtualResolutions(){for(let e of this.storedPackages.values())for(let[r,o]of e.dependencies)Pf(o)&&e.dependencies.set(r,UI(o))}getDependencyMeta(e,r){let o={},n=this.topLevelWorkspace.manifest.dependenciesMeta.get(rn(e));if(!n)return o;let u=n.get(null);if(u&&Object.assign(o,u),r===null||!ehe.default.valid(r))return o;for(let[A,p]of n)A!==null&&A===r&&Object.assign(o,p);return o}async findLocatorForLocation(e,{strict:r=!1}={}){let o=new ki,a=this.configuration.getLinkers(),n={project:this,report:o};for(let u of a){let A=await u.findPackageLocator(e,n);if(A){if(r&&(await u.findPackageLocation(A,n)).replace(Zpe,\"\")!==e.replace(Zpe,\"\"))continue;return A}}return null}async loadUserConfig(){let e=V.join(this.cwd,\".pnp.cjs\");await oe.existsPromise(e)&&vf(e).setup();let r=V.join(this.cwd,\"yarn.config.cjs\");return await oe.existsPromise(r)?vf(r):null}async preparePackage(e,{resolver:r,resolveOptions:o}){let a=await this.configuration.getPackageExtensions(),n=this.configuration.normalizePackage(e,{packageExtensions:a});for(let[u,A]of n.dependencies){let p=await this.configuration.reduceHook(E=>E.reduceDependency,A,this,n,A,{resolver:r,resolveOptions:o});if(!HI(A,p))throw new Error(\"Assertion failed: The descriptor ident cannot be changed through aliases\");let h=r.bindDescriptor(p,n,o);n.dependencies.set(u,h)}return n}async resolveEverything(e){if(!this.workspacesByCwd||!this.workspacesByIdent)throw new Error(\"Workspaces must have been setup before calling this function\");this.forgetVirtualResolutions();let r=new Map(this.originalPackages),o=[];e.lockfileOnly||this.forgetTransientResolutions();let a=e.resolver||this.configuration.makeResolver(),n=new Ty(a);await n.setup(this,{report:e.report});let u=e.lockfileOnly?[new _x(a)]:[n,a],A=new yg([new Ny(a),...u]),p=new yg([...u]),h=this.configuration.makeFetcher(),E=e.lockfileOnly?{project:this,report:e.report,resolver:A}:{project:this,report:e.report,resolver:A,fetchOptions:{project:this,cache:e.cache,checksums:this.storedChecksums,report:e.report,fetcher:h,cacheOptions:{mirrorWriteOnly:!0}}},I=new Map,v=new Map,x=new Map,C=new Map,R=new Map,L=new Map,U=this.topLevelWorkspace.anchoredLocator,z=new Set,te=[],ae=k4(),le=this.configuration.getSupportedArchitectures();await e.report.startProgressPromise(Zs.progressViaTitle(),async ne=>{let Z=async rt=>{let Te=await xm(async()=>await A.resolve(rt,E),be=>`${qr(this.configuration,rt)}: ${be}`);if(!qI(rt,Te))throw new Error(`Assertion failed: The locator cannot be changed by the resolver (went from ${qr(this.configuration,rt)} to ${qr(this.configuration,Te)})`);C.set(Te.locatorHash,Te),!r.delete(Te.locatorHash)&&!this.tryWorkspaceByLocator(Te)&&o.push(Te);let ke=await this.preparePackage(Te,{resolver:A,resolveOptions:E}),Ye=_c([...ke.dependencies.values()].map(be=>H(be)));return te.push(Ye),Ye.catch(()=>{}),v.set(ke.locatorHash,ke),ke},xe=async rt=>{let Te=R.get(rt.locatorHash);if(typeof Te<\"u\")return Te;let Fe=Promise.resolve().then(()=>Z(rt));return R.set(rt.locatorHash,Fe),Fe},Ne=async(rt,Te)=>{let Fe=await H(Te);return I.set(rt.descriptorHash,rt),x.set(rt.descriptorHash,Fe.locatorHash),Fe},ht=async rt=>{ne.setTitle(jn(this.configuration,rt));let Te=this.resolutionAliases.get(rt.descriptorHash);if(typeof Te<\"u\")return Ne(rt,this.storedDescriptors.get(Te));let Fe=A.getResolutionDependencies(rt,E),ke=Object.fromEntries(await _c(Object.entries(Fe).map(async([et,Ue])=>{let S=A.bindDescriptor(Ue,U,E),w=await H(S);return z.add(w.locatorHash),[et,w]}))),be=(await xm(async()=>await A.getCandidates(rt,ke,E),et=>`${jn(this.configuration,rt)}: ${et}`))[0];if(typeof be>\"u\")throw new Jt(82,`${jn(this.configuration,rt)}: No candidates found`);if(e.checkResolutions){let{locators:et}=await p.getSatisfying(rt,ke,[be],{...E,resolver:p});if(!et.find(Ue=>Ue.locatorHash===be.locatorHash))throw new Jt(78,`Invalid resolution ${NI(this.configuration,rt,be)}`)}return I.set(rt.descriptorHash,rt),x.set(rt.descriptorHash,be.locatorHash),xe(be)},H=rt=>{let Te=L.get(rt.descriptorHash);if(typeof Te<\"u\")return Te;I.set(rt.descriptorHash,rt);let Fe=Promise.resolve().then(()=>ht(rt));return L.set(rt.descriptorHash,Fe),Fe};for(let rt of this.workspaces){let Te=rt.anchoredDescriptor;te.push(H(Te))}for(;te.length>0;){let rt=[...te];te.length=0,await _c(rt)}});let ce=ol(r.values(),ne=>this.tryWorkspaceByLocator(ne)?ol.skip:ne);if(o.length>0||ce.length>0){let ne=new Set(this.workspaces.flatMap(rt=>{let Te=v.get(rt.anchoredLocator.locatorHash);if(!Te)throw new Error(\"Assertion failed: The workspace should have been resolved\");return Array.from(Te.dependencies.values(),Fe=>{let ke=x.get(Fe.descriptorHash);if(!ke)throw new Error(\"Assertion failed: The resolution should have been registered\");return ke})})),Z=rt=>ne.has(rt.locatorHash)?\"0\":\"1\",xe=rt=>ka(rt),Ne=Fs(o,[Z,xe]),ht=Fs(ce,[Z,xe]),H=e.report.getRecommendedLength();Ne.length>0&&e.report.reportInfo(85,`${Ot(this.configuration,\"+\",yt.ADDED)} ${zP(this.configuration,Ne,H)}`),ht.length>0&&e.report.reportInfo(85,`${Ot(this.configuration,\"-\",yt.REMOVED)} ${zP(this.configuration,ht,H)}`)}let Ce=new Set(this.resolutionAliases.values()),de=new Set(v.keys()),Be=new Set,Ee=new Map,g=[],me=new Map;TAt({project:this,accessibleLocators:Be,volatileDescriptors:Ce,optionalBuilds:de,peerRequirements:Ee,peerWarnings:g,peerRequirementNodes:me,allDescriptors:I,allResolutions:x,allPackages:v});for(let ne of z)de.delete(ne);for(let ne of Ce)I.delete(ne),x.delete(ne);let we=new Set,Ae=new Set;for(let ne of v.values())ne.conditions!=null&&de.has(ne.locatorHash)&&(xb(ne,le)||(xb(ne,ae)&&e.report.reportWarningOnce(77,`${qr(this.configuration,ne)}: Your current architecture (${process.platform}-${process.arch}) is supported by this package, but is missing from the ${Ot(this.configuration,\"supportedArchitectures\",yt.SETTING)} setting`),Ae.add(ne.locatorHash)),we.add(ne.locatorHash));this.storedResolutions=x,this.storedDescriptors=I,this.storedPackages=v,this.accessibleLocators=Be,this.conditionalLocators=we,this.disabledLocators=Ae,this.originalPackages=C,this.optionalBuilds=de,this.peerRequirements=Ee,this.peerWarnings=g,this.peerRequirementNodes=me}async fetchEverything({cache:e,report:r,fetcher:o,mode:a,persistProject:n=!0}){let u={mockedPackages:this.disabledLocators,unstablePackages:this.conditionalLocators},A=o||this.configuration.makeFetcher(),p={checksums:this.storedChecksums,project:this,cache:e,fetcher:A,report:r,cacheOptions:u},h=Array.from(new Set(Fs(this.storedResolutions.values(),[C=>{let R=this.storedPackages.get(C);if(!R)throw new Error(\"Assertion failed: The locator should have been registered\");return ka(R)}])));a===\"update-lockfile\"&&(h=h.filter(C=>!this.storedChecksums.has(C)));let E=!1,I=Zs.progressViaCounter(h.length);await r.reportProgress(I);let v=(0,jx.default)(QAt);if(await _c(h.map(C=>v(async()=>{let R=this.storedPackages.get(C);if(!R)throw new Error(\"Assertion failed: The locator should have been registered\");if(Gc(R))return;let L;try{L=await A.fetch(R,p)}catch(U){U.message=`${qr(this.configuration,R)}: ${U.message}`,r.reportExceptionOnce(U),E=U;return}L.checksum!=null?this.storedChecksums.set(R.locatorHash,L.checksum):this.storedChecksums.delete(R.locatorHash),L.releaseFs&&L.releaseFs()}).finally(()=>{I.tick()}))),E)throw E;let x=n&&a!==\"update-lockfile\"?await this.cacheCleanup({cache:e,report:r}):null;if(r.cacheMisses.size>0||x){let R=(await Promise.all([...r.cacheMisses].map(async ce=>{let Ce=this.storedPackages.get(ce),de=this.storedChecksums.get(ce)??null,Be=e.getLocatorPath(Ce,de);return(await oe.statPromise(Be)).size}))).reduce((ce,Ce)=>ce+Ce,0)-(x?.size??0),L=r.cacheMisses.size,U=x?.count??0,z=`${jP(L,{zero:\"No new packages\",one:\"A package was\",more:`${Ot(this.configuration,L,yt.NUMBER)} packages were`})} added to the project`,te=`${jP(U,{zero:\"none were\",one:\"one was\",more:`${Ot(this.configuration,U,yt.NUMBER)} were`})} removed`,ae=R!==0?` (${Ot(this.configuration,R,yt.SIZE_DIFF)})`:\"\",le=U>0?L>0?`${z}, and ${te}${ae}.`:`${z}, but ${te}${ae}.`:`${z}${ae}.`;r.reportInfo(13,le)}}async linkEverything({cache:e,report:r,fetcher:o,mode:a}){let n={mockedPackages:this.disabledLocators,unstablePackages:this.conditionalLocators,skipIntegrityCheck:!0},u=o||this.configuration.makeFetcher(),A={checksums:this.storedChecksums,project:this,cache:e,fetcher:u,report:r,cacheOptions:n},p=this.configuration.getLinkers(),h={project:this,report:r},E=new Map(p.map(we=>{let Ae=we.makeInstaller(h),ne=we.getCustomDataKey(),Z=this.linkersCustomData.get(ne);return typeof Z<\"u\"&&Ae.attachCustomData(Z),[we,Ae]})),I=new Map,v=new Map,x=new Map,C=new Map(await _c([...this.accessibleLocators].map(async we=>{let Ae=this.storedPackages.get(we);if(!Ae)throw new Error(\"Assertion failed: The locator should have been registered\");return[we,await u.fetch(Ae,A)]}))),R=[],L=new Set,U=[];for(let we of this.accessibleLocators){let Ae=this.storedPackages.get(we);if(typeof Ae>\"u\")throw new Error(\"Assertion failed: The locator should have been registered\");let ne=C.get(Ae.locatorHash);if(typeof ne>\"u\")throw new Error(\"Assertion failed: The fetch result should have been registered\");let Z=[],xe=ht=>{Z.push(ht)},Ne=this.tryWorkspaceByLocator(Ae);if(Ne!==null){let ht=[],{scripts:H}=Ne.manifest;for(let Te of[\"preinstall\",\"install\",\"postinstall\"])H.has(Te)&&ht.push({type:0,script:Te});try{for(let[Te,Fe]of E)if(Te.supportsPackage(Ae,h)&&(await Fe.installPackage(Ae,ne,{holdFetchResult:xe})).buildRequest!==null)throw new Error(\"Assertion failed: Linkers can't return build directives for workspaces; this responsibility befalls to the Yarn core\")}finally{Z.length===0?ne.releaseFs?.():R.push(_c(Z).catch(()=>{}).then(()=>{ne.releaseFs?.()}))}let rt=V.join(ne.packageFs.getRealPath(),ne.prefixPath);v.set(Ae.locatorHash,rt),!Gc(Ae)&&ht.length>0&&x.set(Ae.locatorHash,{buildDirectives:ht,buildLocations:[rt]})}else{let ht=p.find(Te=>Te.supportsPackage(Ae,h));if(!ht)throw new Jt(12,`${qr(this.configuration,Ae)} isn't supported by any available linker`);let H=E.get(ht);if(!H)throw new Error(\"Assertion failed: The installer should have been registered\");let rt;try{rt=await H.installPackage(Ae,ne,{holdFetchResult:xe})}finally{Z.length===0?ne.releaseFs?.():R.push(_c(Z).then(()=>{}).then(()=>{ne.releaseFs?.()}))}I.set(Ae.locatorHash,ht),v.set(Ae.locatorHash,rt.packageLocation),rt.buildRequest&&rt.packageLocation&&(rt.buildRequest.skipped?(L.add(Ae.locatorHash),this.skippedBuilds.has(Ae.locatorHash)||U.push([Ae,rt.buildRequest.explain])):x.set(Ae.locatorHash,{buildDirectives:rt.buildRequest.directives,buildLocations:[rt.packageLocation]}))}}let z=new Map;for(let we of this.accessibleLocators){let Ae=this.storedPackages.get(we);if(!Ae)throw new Error(\"Assertion failed: The locator should have been registered\");let ne=this.tryWorkspaceByLocator(Ae)!==null,Z=async(xe,Ne)=>{let ht=v.get(Ae.locatorHash);if(typeof ht>\"u\")throw new Error(`Assertion failed: The package (${qr(this.configuration,Ae)}) should have been registered`);let H=[];for(let rt of Ae.dependencies.values()){let Te=this.storedResolutions.get(rt.descriptorHash);if(typeof Te>\"u\")throw new Error(`Assertion failed: The resolution (${jn(this.configuration,rt)}, from ${qr(this.configuration,Ae)})should have been registered`);let Fe=this.storedPackages.get(Te);if(typeof Fe>\"u\")throw new Error(`Assertion failed: The package (${Te}, resolved from ${jn(this.configuration,rt)}) should have been registered`);let ke=this.tryWorkspaceByLocator(Fe)===null?I.get(Te):null;if(typeof ke>\"u\")throw new Error(`Assertion failed: The package (${Te}, resolved from ${jn(this.configuration,rt)}) should have been registered`);ke===xe||ke===null?v.get(Fe.locatorHash)!==null&&H.push([rt,Fe]):!ne&&ht!==null&&xI(z,Te).push(ht)}ht!==null&&await Ne.attachInternalDependencies(Ae,H)};if(ne)for(let[xe,Ne]of E)xe.supportsPackage(Ae,h)&&await Z(xe,Ne);else{let xe=I.get(Ae.locatorHash);if(!xe)throw new Error(\"Assertion failed: The linker should have been found\");let Ne=E.get(xe);if(!Ne)throw new Error(\"Assertion failed: The installer should have been registered\");await Z(xe,Ne)}}for(let[we,Ae]of z){let ne=this.storedPackages.get(we);if(!ne)throw new Error(\"Assertion failed: The package should have been registered\");let Z=I.get(ne.locatorHash);if(!Z)throw new Error(\"Assertion failed: The linker should have been found\");let xe=E.get(Z);if(!xe)throw new Error(\"Assertion failed: The installer should have been registered\");await xe.attachExternalDependents(ne,Ae)}let te=new Map;for(let[we,Ae]of E){let ne=await Ae.finalizeInstall();for(let Z of ne?.records??[])Z.buildRequest.skipped?(L.add(Z.locator.locatorHash),this.skippedBuilds.has(Z.locator.locatorHash)||U.push([Z.locator,Z.buildRequest.explain])):x.set(Z.locator.locatorHash,{buildDirectives:Z.buildRequest.directives,buildLocations:Z.buildLocations});typeof ne?.customData<\"u\"&&te.set(we.getCustomDataKey(),ne.customData)}if(this.linkersCustomData=te,await _c(R),a===\"skip-build\")return;for(let[,we]of Fs(U,([Ae])=>ka(Ae)))we(r);let ae=new Set(x.keys()),le=(0,Hx.createHash)(\"sha512\");le.update(process.versions.node),await this.configuration.triggerHook(we=>we.globalHashGeneration,this,we=>{le.update(\"\\0\"),le.update(we)});let ce=le.digest(\"hex\"),Ce=new Map,de=we=>{let Ae=Ce.get(we.locatorHash);if(typeof Ae<\"u\")return Ae;let ne=this.storedPackages.get(we.locatorHash);if(typeof ne>\"u\")throw new Error(\"Assertion failed: The package should have been registered\");let Z=(0,Hx.createHash)(\"sha512\");Z.update(we.locatorHash),Ce.set(we.locatorHash,\"<recursive>\");for(let xe of ne.dependencies.values()){let Ne=this.storedResolutions.get(xe.descriptorHash);if(typeof Ne>\"u\")throw new Error(`Assertion failed: The resolution (${jn(this.configuration,xe)}) should have been registered`);let ht=this.storedPackages.get(Ne);if(typeof ht>\"u\")throw new Error(\"Assertion failed: The package should have been registered\");Z.update(de(ht))}return Ae=Z.digest(\"hex\"),Ce.set(we.locatorHash,Ae),Ae},Be=(we,Ae)=>{let ne=(0,Hx.createHash)(\"sha512\");ne.update(ce),ne.update(de(we));for(let Z of Ae)ne.update(Z);return ne.digest(\"hex\")},Ee=new Map,g=!1,me=we=>{let Ae=new Set([we.locatorHash]);for(let ne of Ae){let Z=this.storedPackages.get(ne);if(!Z)throw new Error(\"Assertion failed: The package should have been registered\");for(let xe of Z.dependencies.values()){let Ne=this.storedResolutions.get(xe.descriptorHash);if(!Ne)throw new Error(`Assertion failed: The resolution (${jn(this.configuration,xe)}) should have been registered`);if(Ne!==we.locatorHash&&ae.has(Ne))return!1;let ht=this.storedPackages.get(Ne);if(!ht)throw new Error(\"Assertion failed: The package should have been registered\");let H=this.tryWorkspaceByLocator(ht);if(H){if(H.anchoredLocator.locatorHash!==we.locatorHash&&ae.has(H.anchoredLocator.locatorHash))return!1;Ae.add(H.anchoredLocator.locatorHash)}Ae.add(Ne)}}return!0};for(;ae.size>0;){let we=ae.size,Ae=[];for(let ne of ae){let Z=this.storedPackages.get(ne);if(!Z)throw new Error(\"Assertion failed: The package should have been registered\");if(!me(Z))continue;let xe=x.get(Z.locatorHash);if(!xe)throw new Error(\"Assertion failed: The build directive should have been registered\");let Ne=Be(Z,xe.buildLocations);if(this.storedBuildState.get(Z.locatorHash)===Ne){Ee.set(Z.locatorHash,Ne),ae.delete(ne);continue}g||(await this.persistInstallStateFile(),g=!0),this.storedBuildState.has(Z.locatorHash)?r.reportInfo(8,`${qr(this.configuration,Z)} must be rebuilt because its dependency tree changed`):r.reportInfo(7,`${qr(this.configuration,Z)} must be built because it never has been before or the last one failed`);let ht=xe.buildLocations.map(async H=>{if(!V.isAbsolute(H))throw new Error(`Assertion failed: Expected the build location to be absolute (not ${H})`);for(let rt of xe.buildDirectives){let Te=`# This file contains the result of Yarn building a package (${ka(Z)})\n`;switch(rt.type){case 0:Te+=`# Script name: ${rt.script}\n`;break;case 1:Te+=`# Script code: ${rt.script}\n`;break}let Fe=null;if(!await oe.mktempPromise(async Ye=>{let be=V.join(Ye,\"build.log\"),{stdout:et,stderr:Ue}=this.configuration.getSubprocessStreams(be,{header:Te,prefix:qr(this.configuration,Z),report:r}),S;try{switch(rt.type){case 0:S=await NS(Z,rt.script,[],{cwd:H,project:this,stdin:Fe,stdout:et,stderr:Ue});break;case 1:S=await fU(Z,rt.script,[],{cwd:H,project:this,stdin:Fe,stdout:et,stderr:Ue});break}}catch(y){Ue.write(y.stack),S=1}if(et.end(),Ue.end(),S===0)return!0;oe.detachTemp(Ye);let w=`${qr(this.configuration,Z)} couldn't be built successfully (exit code ${Ot(this.configuration,S,yt.NUMBER)}, logs can be found here: ${Ot(this.configuration,be,yt.PATH)})`,b=this.optionalBuilds.has(Z.locatorHash);return b?r.reportInfo(9,w):r.reportError(9,w),Zce&&r.reportFold(ue.fromPortablePath(be),oe.readFileSync(be,\"utf8\")),b}))return!1}return!0});Ae.push(...ht,Promise.allSettled(ht).then(H=>{ae.delete(ne),H.every(rt=>rt.status===\"fulfilled\"&&rt.value===!0)&&Ee.set(Z.locatorHash,Ne)}))}if(await _c(Ae),we===ae.size){let ne=Array.from(ae).map(Z=>{let xe=this.storedPackages.get(Z);if(!xe)throw new Error(\"Assertion failed: The package should have been registered\");return qr(this.configuration,xe)}).join(\", \");r.reportError(3,`Some packages have circular dependencies that make their build order unsatisfiable - as a result they won't be built (affected packages are: ${ne})`);break}}this.storedBuildState=Ee,this.skippedBuilds=L}async installWithNewReport(e,r){return(await Rt.start({configuration:this.configuration,json:e.json,stdout:e.stdout,forceSectionAlignment:!0,includeLogs:!e.json&&!e.quiet,includeVersion:!0},async a=>{await this.install({...r,report:a})})).exitCode()}async install(e){let r=this.configuration.get(\"nodeLinker\");Ke.telemetry?.reportInstall(r);let o=!1;if(await e.report.startTimerPromise(\"Project validation\",{skipIfEmpty:!0},async()=>{this.configuration.get(\"enableOfflineMode\")&&e.report.reportWarning(90,\"Offline work is enabled; Yarn won't fetch packages from the remote registry if it can avoid it\"),await this.configuration.triggerHook(E=>E.validateProject,this,{reportWarning:(E,I)=>{e.report.reportWarning(E,I)},reportError:(E,I)=>{e.report.reportError(E,I),o=!0}})}),o)return;let a=await this.configuration.getPackageExtensions();for(let E of a.values())for(let[,I]of E)for(let v of I)v.status=\"inactive\";let n=V.join(this.cwd,dr.lockfile),u=null;if(e.immutable)try{u=await oe.readFilePromise(n,\"utf8\")}catch(E){throw E.code===\"ENOENT\"?new Jt(28,\"The lockfile would have been created by this install, which is explicitly forbidden.\"):E}await e.report.startTimerPromise(\"Resolution step\",async()=>{await this.resolveEverything(e)}),await e.report.startTimerPromise(\"Post-resolution validation\",{skipIfEmpty:!0},async()=>{LAt(this,e.report);for(let[,E]of a)for(let[,I]of E)for(let v of I)if(v.userProvided){let x=Ot(this.configuration,v,yt.PACKAGE_EXTENSION);switch(v.status){case\"inactive\":e.report.reportWarning(68,`${x}: No matching package in the dependency tree; you may not need this rule anymore.`);break;case\"redundant\":e.report.reportWarning(69,`${x}: This rule seems redundant when applied on the original package; the extension may have been applied upstream.`);break}}if(u!==null){let E=L0(u,this.generateLockfile());if(E!==u){let I=dpe(n,n,u,E,void 0,void 0,{maxEditLength:100});if(I){e.report.reportSeparator();for(let v of I.hunks){e.report.reportInfo(null,`@@ -${v.oldStart},${v.oldLines} +${v.newStart},${v.newLines} @@`);for(let x of v.lines)x.startsWith(\"+\")?e.report.reportError(28,Ot(this.configuration,x,yt.ADDED)):x.startsWith(\"-\")?e.report.reportError(28,Ot(this.configuration,x,yt.REMOVED)):e.report.reportInfo(null,Ot(this.configuration,x,\"grey\"))}e.report.reportSeparator()}throw new Jt(28,\"The lockfile would have been modified by this install, which is explicitly forbidden.\")}}});for(let E of a.values())for(let[,I]of E)for(let v of I)v.userProvided&&v.status===\"active\"&&Ke.telemetry?.reportPackageExtension(pg(v,yt.PACKAGE_EXTENSION));await e.report.startTimerPromise(\"Fetch step\",async()=>{await this.fetchEverything(e)});let A=e.immutable?[...new Set(this.configuration.get(\"immutablePatterns\"))].sort():[],p=await Promise.all(A.map(async E=>Bb(E,{cwd:this.cwd})));(typeof e.persistProject>\"u\"||e.persistProject)&&await this.persist(),await e.report.startTimerPromise(\"Link step\",async()=>{if(e.mode===\"update-lockfile\"){e.report.reportWarning(73,`Skipped due to ${Ot(this.configuration,\"mode=update-lockfile\",yt.CODE)}`);return}await this.linkEverything(e);let E=await Promise.all(A.map(async I=>Bb(I,{cwd:this.cwd})));for(let I=0;I<A.length;++I)p[I]!==E[I]&&e.report.reportError(64,`The checksum for ${A[I]} has been modified by this install, which is explicitly forbidden.`)}),await this.persistInstallStateFile();let h=!1;await e.report.startTimerPromise(\"Post-install validation\",{skipIfEmpty:!0},async()=>{await this.configuration.triggerHook(E=>E.validateProjectAfterInstall,this,{reportWarning:(E,I)=>{e.report.reportWarning(E,I)},reportError:(E,I)=>{e.report.reportError(E,I),h=!0}})}),!h&&await this.configuration.triggerHook(E=>E.afterAllInstalled,this,e)}generateLockfile(){let e=new Map;for(let[n,u]of this.storedResolutions.entries()){let A=e.get(u);A||e.set(u,A=new Set),A.add(n)}let r={},{cacheKey:o}=Gr.getCacheKey(this.configuration);r.__metadata={version:Gx,cacheKey:o};for(let[n,u]of e.entries()){let A=this.originalPackages.get(n);if(!A)continue;let p=[];for(let I of u){let v=this.storedDescriptors.get(I);if(!v)throw new Error(\"Assertion failed: The descriptor should have been registered\");p.push(v)}let h=p.map(I=>xa(I)).sort().join(\", \"),E=new Ut;E.version=A.linkType===\"HARD\"?A.version:\"0.0.0-use.local\",E.languageName=A.languageName,E.dependencies=new Map(A.dependencies),E.peerDependencies=new Map(A.peerDependencies),E.dependenciesMeta=new Map(A.dependenciesMeta),E.peerDependenciesMeta=new Map(A.peerDependenciesMeta),E.bin=new Map(A.bin),r[h]={...E.exportTo({},{compatibilityMode:!1}),linkType:A.linkType.toLowerCase(),resolution:ka(A),checksum:this.storedChecksums.get(A.locatorHash),conditions:A.conditions||void 0}}return`${[`# This file is generated by running \"yarn install\" inside your project.\n`,`# Manual changes might be lost - proceed with caution!\n`].join(\"\")}\n`+Da(r)}async persistLockfile(){let e=V.join(this.cwd,dr.lockfile),r=\"\";try{r=await oe.readFilePromise(e,\"utf8\")}catch{}let o=this.generateLockfile(),a=L0(r,o);a!==r&&(await oe.writeFilePromise(e,a),this.lockFileChecksum=$pe(a),this.lockfileNeedsRefresh=!1)}async persistInstallStateFile(){let e=[];for(let u of Object.values(w_))e.push(...u);let r=(0,qx.default)(this,e),o=I_.default.serialize(r),a=zi(o);if(this.installStateChecksum===a)return;let n=this.configuration.get(\"installStatePath\");await oe.mkdirPromise(V.dirname(n),{recursive:!0}),await oe.writeFilePromise(n,await FAt(o)),this.installStateChecksum=a}async restoreInstallState({restoreLinkersCustomData:e=!0,restoreResolutions:r=!0,restoreBuildState:o=!0}={}){let a=this.configuration.get(\"installStatePath\"),n;try{let u=await RAt(await oe.readFilePromise(a));n=I_.default.deserialize(u),this.installStateChecksum=zi(u)}catch{r&&await this.applyLightResolution();return}e&&typeof n.linkersCustomData<\"u\"&&(this.linkersCustomData=n.linkersCustomData),o&&Object.assign(this,(0,qx.default)(n,w_.restoreBuildState)),r&&(n.lockFileChecksum===this.lockFileChecksum?Object.assign(this,(0,qx.default)(n,w_.restoreResolutions)):await this.applyLightResolution())}async applyLightResolution(){await this.resolveEverything({lockfileOnly:!0,report:new ki}),await this.persistInstallStateFile()}async persist(){let e=(0,jx.default)(4);await Promise.all([this.persistLockfile(),...this.workspaces.map(r=>e(()=>r.persistManifest()))])}async cacheCleanup({cache:e,report:r}){if(this.configuration.get(\"enableGlobalCache\"))return null;let o=new Set([\".gitignore\"]);if(!fO(e.cwd,this.cwd)||!await oe.existsPromise(e.cwd))return null;let a=[];for(let u of await oe.readdirPromise(e.cwd)){if(o.has(u))continue;let A=V.resolve(e.cwd,u);e.markedFiles.has(A)||(e.immutable?r.reportError(56,`${Ot(this.configuration,V.basename(A),\"magenta\")} appears to be unused and would be marked for deletion, but the cache is immutable`):a.push(oe.lstatPromise(A).then(async p=>(await oe.removePromise(A),p.size))))}if(a.length===0)return null;let n=await Promise.all(a);return{count:a.length,size:n.reduce((u,A)=>u+A,0)}}}});function MAt(t){let o=Math.floor(t.timeNow/864e5),a=t.updateInterval*864e5,n=t.state.lastUpdate??t.timeNow+a+Math.floor(a*t.randomInitialInterval),u=n+a,A=t.state.lastTips??o*864e5,p=A+864e5+8*36e5-t.timeZone,h=u<=t.timeNow,E=p<=t.timeNow,I=null;return(h||E||!t.state.lastUpdate||!t.state.lastTips)&&(I={},I.lastUpdate=h?t.timeNow:n,I.lastTips=A,I.blocks=h?{}:t.state.blocks,I.displayedTips=t.state.displayedTips),{nextState:I,triggerUpdate:h,triggerTips:E,nextTips:E?o*864e5:A}}var Oy,rhe=Et(()=>{Pt();w1();th();uS();ql();Sf();Oy=class{constructor(e,r){this.values=new Map;this.hits=new Map;this.enumerators=new Map;this.nextTips=0;this.displayedTips=[];this.shouldCommitTips=!1;this.configuration=e;let o=this.getRegistryPath();this.isNew=!oe.existsSync(o),this.shouldShowTips=!1,this.sendReport(r),this.startBuffer()}commitTips(){this.shouldShowTips&&(this.shouldCommitTips=!0)}selectTip(e){let r=new Set(this.displayedTips),o=A=>A&&nn?tA(nn,A):!1,a=e.map((A,p)=>p).filter(A=>e[A]&&o(e[A]?.selector));if(a.length===0)return null;let n=a.filter(A=>!r.has(A));if(n.length===0){let A=Math.floor(a.length*.2);this.displayedTips=A>0?this.displayedTips.slice(-A):[],n=a.filter(p=>!r.has(p))}let u=n[Math.floor(Math.random()*n.length)];return this.displayedTips.push(u),this.commitTips(),e[u]}reportVersion(e){this.reportValue(\"version\",e.replace(/-git\\..*/,\"-git\"))}reportCommandName(e){this.reportValue(\"commandName\",e||\"<none>\")}reportPluginName(e){this.reportValue(\"pluginName\",e)}reportProject(e){this.reportEnumerator(\"projectCount\",e)}reportInstall(e){this.reportHit(\"installCount\",e)}reportPackageExtension(e){this.reportValue(\"packageExtension\",e)}reportWorkspaceCount(e){this.reportValue(\"workspaceCount\",String(e))}reportDependencyCount(e){this.reportValue(\"dependencyCount\",String(e))}reportValue(e,r){Sm(this.values,e).add(r)}reportEnumerator(e,r){Sm(this.enumerators,e).add(zi(r))}reportHit(e,r=\"*\"){let o=kI(this.hits,e),a=al(o,r,()=>0);o.set(r,a+1)}getRegistryPath(){let e=this.configuration.get(\"globalFolder\");return V.join(e,\"telemetry.json\")}sendReport(e){let r=this.getRegistryPath(),o;try{o=oe.readJsonSync(r)}catch{o={}}let{nextState:a,triggerUpdate:n,triggerTips:u,nextTips:A}=MAt({state:o,timeNow:Date.now(),timeZone:new Date().getTimezoneOffset()*60*1e3,randomInitialInterval:Math.random(),updateInterval:this.configuration.get(\"telemetryInterval\")});if(this.nextTips=A,this.displayedTips=o.displayedTips??[],a!==null)try{oe.mkdirSync(V.dirname(r),{recursive:!0}),oe.writeJsonSync(r,a)}catch{return!1}if(u&&this.configuration.get(\"enableTips\")&&(this.shouldShowTips=!0),n){let p=o.blocks??{};if(Object.keys(p).length===0){let h=`https://browser-http-intake.logs.datadoghq.eu/v1/input/${e}?ddsource=yarn`,E=I=>x4(h,I,{configuration:this.configuration}).catch(()=>{});for(let[I,v]of Object.entries(o.blocks??{})){if(Object.keys(v).length===0)continue;let x=v;x.userId=I,x.reportType=\"primary\";for(let L of Object.keys(x.enumerators??{}))x.enumerators[L]=x.enumerators[L].length;E(x);let C=new Map,R=20;for(let[L,U]of Object.entries(x.values))U.length>0&&C.set(L,U.slice(0,R));for(;C.size>0;){let L={};L.userId=I,L.reportType=\"secondary\",L.metrics={};for(let[U,z]of C)L.metrics[U]=z.shift(),z.length===0&&C.delete(U);E(L)}}}}return!0}applyChanges(){let e=this.getRegistryPath(),r;try{r=oe.readJsonSync(e)}catch{r={}}let o=this.configuration.get(\"telemetryUserId\")??\"*\",a=r.blocks=r.blocks??{},n=a[o]=a[o]??{};for(let u of this.hits.keys()){let A=n.hits=n.hits??{},p=A[u]=A[u]??{};for(let[h,E]of this.hits.get(u))p[h]=(p[h]??0)+E}for(let u of[\"values\",\"enumerators\"])for(let A of this[u].keys()){let p=n[u]=n[u]??{};p[A]=[...new Set([...p[A]??[],...this[u].get(A)??[]])]}this.shouldCommitTips&&(r.lastTips=this.nextTips,r.displayedTips=this.displayedTips),oe.mkdirSync(V.dirname(e),{recursive:!0}),oe.writeJsonSync(e,r)}startBuffer(){process.on(\"exit\",()=>{try{this.applyChanges()}catch{}})}}});var Y1={};Vt(Y1,{BuildDirectiveType:()=>Mx,CACHE_CHECKPOINT:()=>r_,CACHE_VERSION:()=>Lx,Cache:()=>Gr,Configuration:()=>Ke,DEFAULT_RC_FILENAME:()=>L4,FormatType:()=>Tle,InstallMode:()=>hl,LEGACY_PLUGINS:()=>l1,LOCKFILE_VERSION:()=>Gx,LegacyMigrationResolver:()=>Ty,LightReport:()=>AA,LinkType:()=>Fm,LockfileResolver:()=>Ny,Manifest:()=>Ut,MessageName:()=>wr,MultiFetcher:()=>Wm,PackageExtensionStatus:()=>pL,PackageExtensionType:()=>fL,PeerWarningType:()=>Yx,Project:()=>kt,Report:()=>Zs,ReportError:()=>Jt,SettingsType:()=>c1,StreamReport:()=>Rt,TAG_REGEXP:()=>ly,TelemetryManager:()=>Oy,ThrowReport:()=>ki,VirtualFetcher:()=>Km,WindowsLinkType:()=>mS,Workspace:()=>My,WorkspaceFetcher:()=>Vm,WorkspaceResolver:()=>ei,YarnVersion:()=>nn,execUtils:()=>Ur,folderUtils:()=>Rb,formatUtils:()=>pe,hashUtils:()=>wn,httpUtils:()=>sn,miscUtils:()=>He,nodeUtils:()=>Xi,parseMessageName:()=>ZD,reportOptionDeprecations:()=>uy,scriptUtils:()=>An,semverUtils:()=>Lr,stringifyMessageName:()=>Ku,structUtils:()=>G,tgzUtils:()=>$i,treeUtils:()=>fs});var Ge=Et(()=>{pS();Tb();jl();th();uS();ql();fS();dU();Sf();So();rpe();cpe();n_();u1();u1();Ape();i_();fpe();s_();Gm();$D();tO();the();Wl();I1();rhe();E_();nO();iO();mg();C_();w1();Cne()});var lhe=_(($_t,K1)=>{\"use strict\";var UAt=process.env.TERM_PROGRAM===\"Hyper\",_At=process.platform===\"win32\",she=process.platform===\"linux\",D_={ballotDisabled:\"\\u2612\",ballotOff:\"\\u2610\",ballotOn:\"\\u2611\",bullet:\"\\u2022\",bulletWhite:\"\\u25E6\",fullBlock:\"\\u2588\",heart:\"\\u2764\",identicalTo:\"\\u2261\",line:\"\\u2500\",mark:\"\\u203B\",middot:\"\\xB7\",minus:\"\\uFF0D\",multiplication:\"\\xD7\",obelus:\"\\xF7\",pencilDownRight:\"\\u270E\",pencilRight:\"\\u270F\",pencilUpRight:\"\\u2710\",percent:\"%\",pilcrow2:\"\\u2761\",pilcrow:\"\\xB6\",plusMinus:\"\\xB1\",section:\"\\xA7\",starsOff:\"\\u2606\",starsOn:\"\\u2605\",upDownArrow:\"\\u2195\"},ohe=Object.assign({},D_,{check:\"\\u221A\",cross:\"\\xD7\",ellipsisLarge:\"...\",ellipsis:\"...\",info:\"i\",question:\"?\",questionSmall:\"?\",pointer:\">\",pointerSmall:\"\\xBB\",radioOff:\"( )\",radioOn:\"(*)\",warning:\"\\u203C\"}),ahe=Object.assign({},D_,{ballotCross:\"\\u2718\",check:\"\\u2714\",cross:\"\\u2716\",ellipsisLarge:\"\\u22EF\",ellipsis:\"\\u2026\",info:\"\\u2139\",question:\"?\",questionFull:\"\\uFF1F\",questionSmall:\"\\uFE56\",pointer:she?\"\\u25B8\":\"\\u276F\",pointerSmall:she?\"\\u2023\":\"\\u203A\",radioOff:\"\\u25EF\",radioOn:\"\\u25C9\",warning:\"\\u26A0\"});K1.exports=_At&&!UAt?ohe:ahe;Reflect.defineProperty(K1.exports,\"common\",{enumerable:!1,value:D_});Reflect.defineProperty(K1.exports,\"windows\",{enumerable:!1,value:ohe});Reflect.defineProperty(K1.exports,\"other\",{enumerable:!1,value:ahe})});var zc=_((e8t,P_)=>{\"use strict\";var HAt=t=>t!==null&&typeof t==\"object\"&&!Array.isArray(t),qAt=/[\\u001b\\u009b][[\\]#;?()]*(?:(?:(?:[^\\W_]*;?[^\\W_]*)\\u0007)|(?:(?:[0-9]{1,4}(;[0-9]{0,4})*)?[~0-9=<>cf-nqrtyA-PRZ]))/g,che=()=>{let t={enabled:!0,visible:!0,styles:{},keys:{}};\"FORCE_COLOR\"in process.env&&(t.enabled=process.env.FORCE_COLOR!==\"0\");let e=n=>{let u=n.open=`\\x1B[${n.codes[0]}m`,A=n.close=`\\x1B[${n.codes[1]}m`,p=n.regex=new RegExp(`\\\\u001b\\\\[${n.codes[1]}m`,\"g\");return n.wrap=(h,E)=>{h.includes(A)&&(h=h.replace(p,A+u));let I=u+h+A;return E?I.replace(/\\r*\\n/g,`${A}$&${u}`):I},n},r=(n,u,A)=>typeof n==\"function\"?n(u):n.wrap(u,A),o=(n,u)=>{if(n===\"\"||n==null)return\"\";if(t.enabled===!1)return n;if(t.visible===!1)return\"\";let A=\"\"+n,p=A.includes(`\n`),h=u.length;for(h>0&&u.includes(\"unstyle\")&&(u=[...new Set([\"unstyle\",...u])].reverse());h-- >0;)A=r(t.styles[u[h]],A,p);return A},a=(n,u,A)=>{t.styles[n]=e({name:n,codes:u}),(t.keys[A]||(t.keys[A]=[])).push(n),Reflect.defineProperty(t,n,{configurable:!0,enumerable:!0,set(h){t.alias(n,h)},get(){let h=E=>o(E,h.stack);return Reflect.setPrototypeOf(h,t),h.stack=this.stack?this.stack.concat(n):[n],h}})};return a(\"reset\",[0,0],\"modifier\"),a(\"bold\",[1,22],\"modifier\"),a(\"dim\",[2,22],\"modifier\"),a(\"italic\",[3,23],\"modifier\"),a(\"underline\",[4,24],\"modifier\"),a(\"inverse\",[7,27],\"modifier\"),a(\"hidden\",[8,28],\"modifier\"),a(\"strikethrough\",[9,29],\"modifier\"),a(\"black\",[30,39],\"color\"),a(\"red\",[31,39],\"color\"),a(\"green\",[32,39],\"color\"),a(\"yellow\",[33,39],\"color\"),a(\"blue\",[34,39],\"color\"),a(\"magenta\",[35,39],\"color\"),a(\"cyan\",[36,39],\"color\"),a(\"white\",[37,39],\"color\"),a(\"gray\",[90,39],\"color\"),a(\"grey\",[90,39],\"color\"),a(\"bgBlack\",[40,49],\"bg\"),a(\"bgRed\",[41,49],\"bg\"),a(\"bgGreen\",[42,49],\"bg\"),a(\"bgYellow\",[43,49],\"bg\"),a(\"bgBlue\",[44,49],\"bg\"),a(\"bgMagenta\",[45,49],\"bg\"),a(\"bgCyan\",[46,49],\"bg\"),a(\"bgWhite\",[47,49],\"bg\"),a(\"blackBright\",[90,39],\"bright\"),a(\"redBright\",[91,39],\"bright\"),a(\"greenBright\",[92,39],\"bright\"),a(\"yellowBright\",[93,39],\"bright\"),a(\"blueBright\",[94,39],\"bright\"),a(\"magentaBright\",[95,39],\"bright\"),a(\"cyanBright\",[96,39],\"bright\"),a(\"whiteBright\",[97,39],\"bright\"),a(\"bgBlackBright\",[100,49],\"bgBright\"),a(\"bgRedBright\",[101,49],\"bgBright\"),a(\"bgGreenBright\",[102,49],\"bgBright\"),a(\"bgYellowBright\",[103,49],\"bgBright\"),a(\"bgBlueBright\",[104,49],\"bgBright\"),a(\"bgMagentaBright\",[105,49],\"bgBright\"),a(\"bgCyanBright\",[106,49],\"bgBright\"),a(\"bgWhiteBright\",[107,49],\"bgBright\"),t.ansiRegex=qAt,t.hasColor=t.hasAnsi=n=>(t.ansiRegex.lastIndex=0,typeof n==\"string\"&&n!==\"\"&&t.ansiRegex.test(n)),t.alias=(n,u)=>{let A=typeof u==\"string\"?t[u]:u;if(typeof A!=\"function\")throw new TypeError(\"Expected alias to be the name of an existing color (string) or a function\");A.stack||(Reflect.defineProperty(A,\"name\",{value:n}),t.styles[n]=A,A.stack=[n]),Reflect.defineProperty(t,n,{configurable:!0,enumerable:!0,set(p){t.alias(n,p)},get(){let p=h=>o(h,p.stack);return Reflect.setPrototypeOf(p,t),p.stack=this.stack?this.stack.concat(A.stack):A.stack,p}})},t.theme=n=>{if(!HAt(n))throw new TypeError(\"Expected theme to be an object\");for(let u of Object.keys(n))t.alias(u,n[u]);return t},t.alias(\"unstyle\",n=>typeof n==\"string\"&&n!==\"\"?(t.ansiRegex.lastIndex=0,n.replace(t.ansiRegex,\"\")):\"\"),t.alias(\"noop\",n=>n),t.none=t.clear=t.noop,t.stripColor=t.unstyle,t.symbols=lhe(),t.define=a,t};P_.exports=che();P_.exports.create=che});var No=_(on=>{\"use strict\";var jAt=Object.prototype.toString,rc=zc(),uhe=!1,b_=[],Ahe={yellow:\"blue\",cyan:\"red\",green:\"magenta\",black:\"white\",blue:\"yellow\",red:\"cyan\",magenta:\"green\",white:\"black\"};on.longest=(t,e)=>t.reduce((r,o)=>Math.max(r,e?o[e].length:o.length),0);on.hasColor=t=>!!t&&rc.hasColor(t);var Kx=on.isObject=t=>t!==null&&typeof t==\"object\"&&!Array.isArray(t);on.nativeType=t=>jAt.call(t).slice(8,-1).toLowerCase().replace(/\\s/g,\"\");on.isAsyncFn=t=>on.nativeType(t)===\"asyncfunction\";on.isPrimitive=t=>t!=null&&typeof t!=\"object\"&&typeof t!=\"function\";on.resolve=(t,e,...r)=>typeof e==\"function\"?e.call(t,...r):e;on.scrollDown=(t=[])=>[...t.slice(1),t[0]];on.scrollUp=(t=[])=>[t.pop(),...t];on.reorder=(t=[])=>{let e=t.slice();return e.sort((r,o)=>r.index>o.index?1:r.index<o.index?-1:0),e};on.swap=(t,e,r)=>{let o=t.length,a=r===o?0:r<0?o-1:r,n=t[e];t[e]=t[a],t[a]=n};on.width=(t,e=80)=>{let r=t&&t.columns?t.columns:e;return t&&typeof t.getWindowSize==\"function\"&&(r=t.getWindowSize()[0]),process.platform===\"win32\"?r-1:r};on.height=(t,e=20)=>{let r=t&&t.rows?t.rows:e;return t&&typeof t.getWindowSize==\"function\"&&(r=t.getWindowSize()[1]),r};on.wordWrap=(t,e={})=>{if(!t)return t;typeof e==\"number\"&&(e={width:e});let{indent:r=\"\",newline:o=`\n`+r,width:a=80}=e,n=(o+r).match(/[^\\S\\n]/g)||[];a-=n.length;let u=`.{1,${a}}([\\\\s\\\\u200B]+|$)|[^\\\\s\\\\u200B]+?([\\\\s\\\\u200B]+|$)`,A=t.trim(),p=new RegExp(u,\"g\"),h=A.match(p)||[];return h=h.map(E=>E.replace(/\\n$/,\"\")),e.padEnd&&(h=h.map(E=>E.padEnd(a,\" \"))),e.padStart&&(h=h.map(E=>E.padStart(a,\" \"))),r+h.join(o)};on.unmute=t=>{let e=t.stack.find(o=>rc.keys.color.includes(o));return e?rc[e]:t.stack.find(o=>o.slice(2)===\"bg\")?rc[e.slice(2)]:o=>o};on.pascal=t=>t?t[0].toUpperCase()+t.slice(1):\"\";on.inverse=t=>{if(!t||!t.stack)return t;let e=t.stack.find(o=>rc.keys.color.includes(o));if(e){let o=rc[\"bg\"+on.pascal(e)];return o?o.black:t}let r=t.stack.find(o=>o.slice(0,2)===\"bg\");return r?rc[r.slice(2).toLowerCase()]||t:rc.none};on.complement=t=>{if(!t||!t.stack)return t;let e=t.stack.find(o=>rc.keys.color.includes(o)),r=t.stack.find(o=>o.slice(0,2)===\"bg\");if(e&&!r)return rc[Ahe[e]||e];if(r){let o=r.slice(2).toLowerCase(),a=Ahe[o];return a&&rc[\"bg\"+on.pascal(a)]||t}return rc.none};on.meridiem=t=>{let e=t.getHours(),r=t.getMinutes(),o=e>=12?\"pm\":\"am\";e=e%12;let a=e===0?12:e,n=r<10?\"0\"+r:r;return a+\":\"+n+\" \"+o};on.set=(t={},e=\"\",r)=>e.split(\".\").reduce((o,a,n,u)=>{let A=u.length-1>n?o[a]||{}:r;return!on.isObject(A)&&n<u.length-1&&(A={}),o[a]=A},t);on.get=(t={},e=\"\",r)=>{let o=t[e]==null?e.split(\".\").reduce((a,n)=>a&&a[n],t):t[e];return o??r};on.mixin=(t,e)=>{if(!Kx(t))return e;if(!Kx(e))return t;for(let r of Object.keys(e)){let o=Object.getOwnPropertyDescriptor(e,r);if(o.hasOwnProperty(\"value\"))if(t.hasOwnProperty(r)&&Kx(o.value)){let a=Object.getOwnPropertyDescriptor(t,r);Kx(a.value)?t[r]=on.merge({},t[r],e[r]):Reflect.defineProperty(t,r,o)}else Reflect.defineProperty(t,r,o);else Reflect.defineProperty(t,r,o)}return t};on.merge=(...t)=>{let e={};for(let r of t)on.mixin(e,r);return e};on.mixinEmitter=(t,e)=>{let r=e.constructor.prototype;for(let o of Object.keys(r)){let a=r[o];typeof a==\"function\"?on.define(t,o,a.bind(e)):on.define(t,o,a)}};on.onExit=t=>{let e=(r,o)=>{uhe||(uhe=!0,b_.forEach(a=>a()),r===!0&&process.exit(128+o))};b_.length===0&&(process.once(\"SIGTERM\",e.bind(null,!0,15)),process.once(\"SIGINT\",e.bind(null,!0,2)),process.once(\"exit\",e)),b_.push(t)};on.define=(t,e,r)=>{Reflect.defineProperty(t,e,{value:r})};on.defineExport=(t,e,r)=>{let o;Reflect.defineProperty(t,e,{enumerable:!0,configurable:!0,set(a){o=a},get(){return o?o():r()}})}});var fhe=_(qy=>{\"use strict\";qy.ctrl={a:\"first\",b:\"backward\",c:\"cancel\",d:\"deleteForward\",e:\"last\",f:\"forward\",g:\"reset\",i:\"tab\",k:\"cutForward\",l:\"reset\",n:\"newItem\",m:\"cancel\",j:\"submit\",p:\"search\",r:\"remove\",s:\"save\",u:\"undo\",w:\"cutLeft\",x:\"toggleCursor\",v:\"paste\"};qy.shift={up:\"shiftUp\",down:\"shiftDown\",left:\"shiftLeft\",right:\"shiftRight\",tab:\"prev\"};qy.fn={up:\"pageUp\",down:\"pageDown\",left:\"pageLeft\",right:\"pageRight\",delete:\"deleteForward\"};qy.option={b:\"backward\",f:\"forward\",d:\"cutRight\",left:\"cutLeft\",up:\"altUp\",down:\"altDown\"};qy.keys={pageup:\"pageUp\",pagedown:\"pageDown\",home:\"home\",end:\"end\",cancel:\"cancel\",delete:\"deleteForward\",backspace:\"delete\",down:\"down\",enter:\"submit\",escape:\"cancel\",left:\"left\",space:\"space\",number:\"number\",return:\"submit\",right:\"right\",tab:\"next\",up:\"up\"}});var ghe=_((n8t,hhe)=>{\"use strict\";var phe=ve(\"readline\"),GAt=fhe(),YAt=/^(?:\\x1b)([a-zA-Z0-9])$/,WAt=/^(?:\\x1b+)(O|N|\\[|\\[\\[)(?:(\\d+)(?:;(\\d+))?([~^$])|(?:1;)?(\\d+)?([a-zA-Z]))/,KAt={OP:\"f1\",OQ:\"f2\",OR:\"f3\",OS:\"f4\",\"[11~\":\"f1\",\"[12~\":\"f2\",\"[13~\":\"f3\",\"[14~\":\"f4\",\"[[A\":\"f1\",\"[[B\":\"f2\",\"[[C\":\"f3\",\"[[D\":\"f4\",\"[[E\":\"f5\",\"[15~\":\"f5\",\"[17~\":\"f6\",\"[18~\":\"f7\",\"[19~\":\"f8\",\"[20~\":\"f9\",\"[21~\":\"f10\",\"[23~\":\"f11\",\"[24~\":\"f12\",\"[A\":\"up\",\"[B\":\"down\",\"[C\":\"right\",\"[D\":\"left\",\"[E\":\"clear\",\"[F\":\"end\",\"[H\":\"home\",OA:\"up\",OB:\"down\",OC:\"right\",OD:\"left\",OE:\"clear\",OF:\"end\",OH:\"home\",\"[1~\":\"home\",\"[2~\":\"insert\",\"[3~\":\"delete\",\"[4~\":\"end\",\"[5~\":\"pageup\",\"[6~\":\"pagedown\",\"[[5~\":\"pageup\",\"[[6~\":\"pagedown\",\"[7~\":\"home\",\"[8~\":\"end\",\"[a\":\"up\",\"[b\":\"down\",\"[c\":\"right\",\"[d\":\"left\",\"[e\":\"clear\",\"[2$\":\"insert\",\"[3$\":\"delete\",\"[5$\":\"pageup\",\"[6$\":\"pagedown\",\"[7$\":\"home\",\"[8$\":\"end\",Oa:\"up\",Ob:\"down\",Oc:\"right\",Od:\"left\",Oe:\"clear\",\"[2^\":\"insert\",\"[3^\":\"delete\",\"[5^\":\"pageup\",\"[6^\":\"pagedown\",\"[7^\":\"home\",\"[8^\":\"end\",\"[Z\":\"tab\"};function VAt(t){return[\"[a\",\"[b\",\"[c\",\"[d\",\"[e\",\"[2$\",\"[3$\",\"[5$\",\"[6$\",\"[7$\",\"[8$\",\"[Z\"].includes(t)}function zAt(t){return[\"Oa\",\"Ob\",\"Oc\",\"Od\",\"Oe\",\"[2^\",\"[3^\",\"[5^\",\"[6^\",\"[7^\",\"[8^\"].includes(t)}var Vx=(t=\"\",e={})=>{let r,o={name:e.name,ctrl:!1,meta:!1,shift:!1,option:!1,sequence:t,raw:t,...e};if(Buffer.isBuffer(t)?t[0]>127&&t[1]===void 0?(t[0]-=128,t=\"\\x1B\"+String(t)):t=String(t):t!==void 0&&typeof t!=\"string\"?t=String(t):t||(t=o.sequence||\"\"),o.sequence=o.sequence||t||o.name,t===\"\\r\")o.raw=void 0,o.name=\"return\";else if(t===`\n`)o.name=\"enter\";else if(t===\"\t\")o.name=\"tab\";else if(t===\"\\b\"||t===\"\\x7F\"||t===\"\\x1B\\x7F\"||t===\"\\x1B\\b\")o.name=\"backspace\",o.meta=t.charAt(0)===\"\\x1B\";else if(t===\"\\x1B\"||t===\"\\x1B\\x1B\")o.name=\"escape\",o.meta=t.length===2;else if(t===\" \"||t===\"\\x1B \")o.name=\"space\",o.meta=t.length===2;else if(t<=\"\u001a\")o.name=String.fromCharCode(t.charCodeAt(0)+97-1),o.ctrl=!0;else if(t.length===1&&t>=\"0\"&&t<=\"9\")o.name=\"number\";else if(t.length===1&&t>=\"a\"&&t<=\"z\")o.name=t;else if(t.length===1&&t>=\"A\"&&t<=\"Z\")o.name=t.toLowerCase(),o.shift=!0;else if(r=YAt.exec(t))o.meta=!0,o.shift=/^[A-Z]$/.test(r[1]);else if(r=WAt.exec(t)){let a=[...t];a[0]===\"\\x1B\"&&a[1]===\"\\x1B\"&&(o.option=!0);let n=[r[1],r[2],r[4],r[6]].filter(Boolean).join(\"\"),u=(r[3]||r[5]||1)-1;o.ctrl=!!(u&4),o.meta=!!(u&10),o.shift=!!(u&1),o.code=n,o.name=KAt[n],o.shift=VAt(n)||o.shift,o.ctrl=zAt(n)||o.ctrl}return o};Vx.listen=(t={},e)=>{let{stdin:r}=t;if(!r||r!==process.stdin&&!r.isTTY)throw new Error(\"Invalid stream passed\");let o=phe.createInterface({terminal:!0,input:r});phe.emitKeypressEvents(r,o);let a=(A,p)=>e(A,Vx(A,p),o),n=r.isRaw;return r.isTTY&&r.setRawMode(!0),r.on(\"keypress\",a),o.resume(),()=>{r.isTTY&&r.setRawMode(n),r.removeListener(\"keypress\",a),o.pause(),o.close()}};Vx.action=(t,e,r)=>{let o={...GAt,...r};return e.ctrl?(e.action=o.ctrl[e.name],e):e.option&&o.option?(e.action=o.option[e.name],e):e.shift?(e.action=o.shift[e.name],e):(e.action=o.keys[e.name],e)};hhe.exports=Vx});var mhe=_((i8t,dhe)=>{\"use strict\";dhe.exports=t=>{t.timers=t.timers||{};let e=t.options.timers;if(e)for(let r of Object.keys(e)){let o=e[r];typeof o==\"number\"&&(o={interval:o}),JAt(t,r,o)}};function JAt(t,e,r={}){let o=t.timers[e]={name:e,start:Date.now(),ms:0,tick:0},a=r.interval||120;o.frames=r.frames||[],o.loading=!0;let n=setInterval(()=>{o.ms=Date.now()-o.start,o.tick++,t.render()},a);return o.stop=()=>{o.loading=!1,clearInterval(n)},Reflect.defineProperty(o,\"interval\",{value:n}),t.once(\"close\",()=>o.stop()),o.stop}});var Ehe=_((s8t,yhe)=>{\"use strict\";var{define:XAt,width:ZAt}=No(),S_=class{constructor(e){let r=e.options;XAt(this,\"_prompt\",e),this.type=e.type,this.name=e.name,this.message=\"\",this.header=\"\",this.footer=\"\",this.error=\"\",this.hint=\"\",this.input=\"\",this.cursor=0,this.index=0,this.lines=0,this.tick=0,this.prompt=\"\",this.buffer=\"\",this.width=ZAt(r.stdout||process.stdout),Object.assign(this,r),this.name=this.name||this.message,this.message=this.message||this.name,this.symbols=e.symbols,this.styles=e.styles,this.required=new Set,this.cancelled=!1,this.submitted=!1}clone(){let e={...this};return e.status=this.status,e.buffer=Buffer.from(e.buffer),delete e.clone,e}set color(e){this._color=e}get color(){let e=this.prompt.styles;if(this.cancelled)return e.cancelled;if(this.submitted)return e.submitted;let r=this._color||e[this.status];return typeof r==\"function\"?r:e.pending}set loading(e){this._loading=e}get loading(){return typeof this._loading==\"boolean\"?this._loading:this.loadingChoices?\"choices\":!1}get status(){return this.cancelled?\"cancelled\":this.submitted?\"submitted\":\"pending\"}};yhe.exports=S_});var whe=_((o8t,Che)=>{\"use strict\";var x_=No(),eo=zc(),k_={default:eo.noop,noop:eo.noop,set inverse(t){this._inverse=t},get inverse(){return this._inverse||x_.inverse(this.primary)},set complement(t){this._complement=t},get complement(){return this._complement||x_.complement(this.primary)},primary:eo.cyan,success:eo.green,danger:eo.magenta,strong:eo.bold,warning:eo.yellow,muted:eo.dim,disabled:eo.gray,dark:eo.dim.gray,underline:eo.underline,set info(t){this._info=t},get info(){return this._info||this.primary},set em(t){this._em=t},get em(){return this._em||this.primary.underline},set heading(t){this._heading=t},get heading(){return this._heading||this.muted.underline},set pending(t){this._pending=t},get pending(){return this._pending||this.primary},set submitted(t){this._submitted=t},get submitted(){return this._submitted||this.success},set cancelled(t){this._cancelled=t},get cancelled(){return this._cancelled||this.danger},set typing(t){this._typing=t},get typing(){return this._typing||this.dim},set placeholder(t){this._placeholder=t},get placeholder(){return this._placeholder||this.primary.dim},set highlight(t){this._highlight=t},get highlight(){return this._highlight||this.inverse}};k_.merge=(t={})=>{t.styles&&typeof t.styles.enabled==\"boolean\"&&(eo.enabled=t.styles.enabled),t.styles&&typeof t.styles.visible==\"boolean\"&&(eo.visible=t.styles.visible);let e=x_.merge({},k_,t.styles);delete e.merge;for(let r of Object.keys(eo))e.hasOwnProperty(r)||Reflect.defineProperty(e,r,{get:()=>eo[r]});for(let r of Object.keys(eo.styles))e.hasOwnProperty(r)||Reflect.defineProperty(e,r,{get:()=>eo[r]});return e};Che.exports=k_});var Bhe=_((a8t,Ihe)=>{\"use strict\";var Q_=process.platform===\"win32\",Yf=zc(),$At=No(),F_={...Yf.symbols,upDownDoubleArrow:\"\\u21D5\",upDownDoubleArrow2:\"\\u2B0D\",upDownArrow:\"\\u2195\",asterisk:\"*\",asterism:\"\\u2042\",bulletWhite:\"\\u25E6\",electricArrow:\"\\u2301\",ellipsisLarge:\"\\u22EF\",ellipsisSmall:\"\\u2026\",fullBlock:\"\\u2588\",identicalTo:\"\\u2261\",indicator:Yf.symbols.check,leftAngle:\"\\u2039\",mark:\"\\u203B\",minus:\"\\u2212\",multiplication:\"\\xD7\",obelus:\"\\xF7\",percent:\"%\",pilcrow:\"\\xB6\",pilcrow2:\"\\u2761\",pencilUpRight:\"\\u2710\",pencilDownRight:\"\\u270E\",pencilRight:\"\\u270F\",plus:\"+\",plusMinus:\"\\xB1\",pointRight:\"\\u261E\",rightAngle:\"\\u203A\",section:\"\\xA7\",hexagon:{off:\"\\u2B21\",on:\"\\u2B22\",disabled:\"\\u2B22\"},ballot:{on:\"\\u2611\",off:\"\\u2610\",disabled:\"\\u2612\"},stars:{on:\"\\u2605\",off:\"\\u2606\",disabled:\"\\u2606\"},folder:{on:\"\\u25BC\",off:\"\\u25B6\",disabled:\"\\u25B6\"},prefix:{pending:Yf.symbols.question,submitted:Yf.symbols.check,cancelled:Yf.symbols.cross},separator:{pending:Yf.symbols.pointerSmall,submitted:Yf.symbols.middot,cancelled:Yf.symbols.middot},radio:{off:Q_?\"( )\":\"\\u25EF\",on:Q_?\"(*)\":\"\\u25C9\",disabled:Q_?\"(|)\":\"\\u24BE\"},numbers:[\"\\u24EA\",\"\\u2460\",\"\\u2461\",\"\\u2462\",\"\\u2463\",\"\\u2464\",\"\\u2465\",\"\\u2466\",\"\\u2467\",\"\\u2468\",\"\\u2469\",\"\\u246A\",\"\\u246B\",\"\\u246C\",\"\\u246D\",\"\\u246E\",\"\\u246F\",\"\\u2470\",\"\\u2471\",\"\\u2472\",\"\\u2473\",\"\\u3251\",\"\\u3252\",\"\\u3253\",\"\\u3254\",\"\\u3255\",\"\\u3256\",\"\\u3257\",\"\\u3258\",\"\\u3259\",\"\\u325A\",\"\\u325B\",\"\\u325C\",\"\\u325D\",\"\\u325E\",\"\\u325F\",\"\\u32B1\",\"\\u32B2\",\"\\u32B3\",\"\\u32B4\",\"\\u32B5\",\"\\u32B6\",\"\\u32B7\",\"\\u32B8\",\"\\u32B9\",\"\\u32BA\",\"\\u32BB\",\"\\u32BC\",\"\\u32BD\",\"\\u32BE\",\"\\u32BF\"]};F_.merge=t=>{let e=$At.merge({},Yf.symbols,F_,t.symbols);return delete e.merge,e};Ihe.exports=F_});var Dhe=_((l8t,vhe)=>{\"use strict\";var eft=whe(),tft=Bhe(),rft=No();vhe.exports=t=>{t.options=rft.merge({},t.options.theme,t.options),t.symbols=tft.merge(t.options),t.styles=eft.merge(t.options)}});var khe=_((She,xhe)=>{\"use strict\";var Phe=process.env.TERM_PROGRAM===\"Apple_Terminal\",nft=zc(),R_=No(),Jc=xhe.exports=She,vi=\"\\x1B[\",bhe=\"\\x07\",T_=!1,Dh=Jc.code={bell:bhe,beep:bhe,beginning:`${vi}G`,down:`${vi}J`,esc:vi,getPosition:`${vi}6n`,hide:`${vi}?25l`,line:`${vi}2K`,lineEnd:`${vi}K`,lineStart:`${vi}1K`,restorePosition:vi+(Phe?\"8\":\"u\"),savePosition:vi+(Phe?\"7\":\"s\"),screen:`${vi}2J`,show:`${vi}?25h`,up:`${vi}1J`},Og=Jc.cursor={get hidden(){return T_},hide(){return T_=!0,Dh.hide},show(){return T_=!1,Dh.show},forward:(t=1)=>`${vi}${t}C`,backward:(t=1)=>`${vi}${t}D`,nextLine:(t=1)=>`${vi}E`.repeat(t),prevLine:(t=1)=>`${vi}F`.repeat(t),up:(t=1)=>t?`${vi}${t}A`:\"\",down:(t=1)=>t?`${vi}${t}B`:\"\",right:(t=1)=>t?`${vi}${t}C`:\"\",left:(t=1)=>t?`${vi}${t}D`:\"\",to(t,e){return e?`${vi}${e+1};${t+1}H`:`${vi}${t+1}G`},move(t=0,e=0){let r=\"\";return r+=t<0?Og.left(-t):t>0?Og.right(t):\"\",r+=e<0?Og.up(-e):e>0?Og.down(e):\"\",r},restore(t={}){let{after:e,cursor:r,initial:o,input:a,prompt:n,size:u,value:A}=t;if(o=R_.isPrimitive(o)?String(o):\"\",a=R_.isPrimitive(a)?String(a):\"\",A=R_.isPrimitive(A)?String(A):\"\",u){let p=Jc.cursor.up(u)+Jc.cursor.to(n.length),h=a.length-r;return h>0&&(p+=Jc.cursor.left(h)),p}if(A||e){let p=!a&&o?-o.length:-a.length+r;return e&&(p-=e.length),a===\"\"&&o&&!n.includes(o)&&(p+=o.length),Jc.cursor.move(p)}}},N_=Jc.erase={screen:Dh.screen,up:Dh.up,down:Dh.down,line:Dh.line,lineEnd:Dh.lineEnd,lineStart:Dh.lineStart,lines(t){let e=\"\";for(let r=0;r<t;r++)e+=Jc.erase.line+(r<t-1?Jc.cursor.up(1):\"\");return t&&(e+=Jc.code.beginning),e}};Jc.clear=(t=\"\",e=process.stdout.columns)=>{if(!e)return N_.line+Og.to(0);let r=n=>[...nft.unstyle(n)].length,o=t.split(/\\r?\\n/),a=0;for(let n of o)a+=1+Math.floor(Math.max(r(n)-1,0)/e);return(N_.line+Og.prevLine()).repeat(a-1)+N_.line+Og.to(0)}});var jy=_((c8t,Fhe)=>{\"use strict\";var ift=ve(\"events\"),Qhe=zc(),L_=ghe(),sft=mhe(),oft=Ehe(),aft=Dhe(),Na=No(),Ug=khe(),M_=class t extends ift{constructor(e={}){super(),this.name=e.name,this.type=e.type,this.options=e,aft(this),sft(this),this.state=new oft(this),this.initial=[e.initial,e.default].find(r=>r!=null),this.stdout=e.stdout||process.stdout,this.stdin=e.stdin||process.stdin,this.scale=e.scale||1,this.term=this.options.term||process.env.TERM_PROGRAM,this.margin=cft(this.options.margin),this.setMaxListeners(0),lft(this)}async keypress(e,r={}){this.keypressed=!0;let o=L_.action(e,L_(e,r),this.options.actions);this.state.keypress=o,this.emit(\"keypress\",e,o),this.emit(\"state\",this.state.clone());let a=this.options[o.action]||this[o.action]||this.dispatch;if(typeof a==\"function\")return await a.call(this,e,o);this.alert()}alert(){delete this.state.alert,this.options.show===!1?this.emit(\"alert\"):this.stdout.write(Ug.code.beep)}cursorHide(){this.stdout.write(Ug.cursor.hide()),Na.onExit(()=>this.cursorShow())}cursorShow(){this.stdout.write(Ug.cursor.show())}write(e){e&&(this.stdout&&this.state.show!==!1&&this.stdout.write(e),this.state.buffer+=e)}clear(e=0){let r=this.state.buffer;this.state.buffer=\"\",!(!r&&!e||this.options.show===!1)&&this.stdout.write(Ug.cursor.down(e)+Ug.clear(r,this.width))}restore(){if(this.state.closed||this.options.show===!1)return;let{prompt:e,after:r,rest:o}=this.sections(),{cursor:a,initial:n=\"\",input:u=\"\",value:A=\"\"}=this,p=this.state.size=o.length,h={after:r,cursor:a,initial:n,input:u,prompt:e,size:p,value:A},E=Ug.cursor.restore(h);E&&this.stdout.write(E)}sections(){let{buffer:e,input:r,prompt:o}=this.state;o=Qhe.unstyle(o);let a=Qhe.unstyle(e),n=a.indexOf(o),u=a.slice(0,n),p=a.slice(n).split(`\n`),h=p[0],E=p[p.length-1],v=(o+(r?\" \"+r:\"\")).length,x=v<h.length?h.slice(v+1):\"\";return{header:u,prompt:h,after:x,rest:p.slice(1),last:E}}async submit(){this.state.submitted=!0,this.state.validating=!0,this.options.onSubmit&&await this.options.onSubmit.call(this,this.name,this.value,this);let e=this.state.error||await this.validate(this.value,this.state);if(e!==!0){let r=`\n`+this.symbols.pointer+\" \";typeof e==\"string\"?r+=e.trim():r+=\"Invalid input\",this.state.error=`\n`+this.styles.danger(r),this.state.submitted=!1,await this.render(),await this.alert(),this.state.validating=!1,this.state.error=void 0;return}this.state.validating=!1,await this.render(),await this.close(),this.value=await this.result(this.value),this.emit(\"submit\",this.value)}async cancel(e){this.state.cancelled=this.state.submitted=!0,await this.render(),await this.close(),typeof this.options.onCancel==\"function\"&&await this.options.onCancel.call(this,this.name,this.value,this),this.emit(\"cancel\",await this.error(e))}async close(){this.state.closed=!0;try{let e=this.sections(),r=Math.ceil(e.prompt.length/this.width);e.rest&&this.write(Ug.cursor.down(e.rest.length)),this.write(`\n`.repeat(r))}catch{}this.emit(\"close\")}start(){!this.stop&&this.options.show!==!1&&(this.stop=L_.listen(this,this.keypress.bind(this)),this.once(\"close\",this.stop))}async skip(){return this.skipped=this.options.skip===!0,typeof this.options.skip==\"function\"&&(this.skipped=await this.options.skip.call(this,this.name,this.value)),this.skipped}async initialize(){let{format:e,options:r,result:o}=this;if(this.format=()=>e.call(this,this.value),this.result=()=>o.call(this,this.value),typeof r.initial==\"function\"&&(this.initial=await r.initial.call(this,this)),typeof r.onRun==\"function\"&&await r.onRun.call(this,this),typeof r.onSubmit==\"function\"){let a=r.onSubmit.bind(this),n=this.submit.bind(this);delete this.options.onSubmit,this.submit=async()=>(await a(this.name,this.value,this),n())}await this.start(),await this.render()}render(){throw new Error(\"expected prompt to have a custom render method\")}run(){return new Promise(async(e,r)=>{if(this.once(\"submit\",e),this.once(\"cancel\",r),await this.skip())return this.render=()=>{},this.submit();await this.initialize(),this.emit(\"run\")})}async element(e,r,o){let{options:a,state:n,symbols:u,timers:A}=this,p=A&&A[e];n.timer=p;let h=a[e]||n[e]||u[e],E=r&&r[e]!=null?r[e]:await h;if(E===\"\")return E;let I=await this.resolve(E,n,r,o);return!I&&r&&r[e]?this.resolve(h,n,r,o):I}async prefix(){let e=await this.element(\"prefix\")||this.symbols,r=this.timers&&this.timers.prefix,o=this.state;return o.timer=r,Na.isObject(e)&&(e=e[o.status]||e.pending),Na.hasColor(e)?e:(this.styles[o.status]||this.styles.pending)(e)}async message(){let e=await this.element(\"message\");return Na.hasColor(e)?e:this.styles.strong(e)}async separator(){let e=await this.element(\"separator\")||this.symbols,r=this.timers&&this.timers.separator,o=this.state;o.timer=r;let a=e[o.status]||e.pending||o.separator,n=await this.resolve(a,o);return Na.isObject(n)&&(n=n[o.status]||n.pending),Na.hasColor(n)?n:this.styles.muted(n)}async pointer(e,r){let o=await this.element(\"pointer\",e,r);if(typeof o==\"string\"&&Na.hasColor(o))return o;if(o){let a=this.styles,n=this.index===r,u=n?a.primary:h=>h,A=await this.resolve(o[n?\"on\":\"off\"]||o,this.state),p=Na.hasColor(A)?A:u(A);return n?p:\" \".repeat(A.length)}}async indicator(e,r){let o=await this.element(\"indicator\",e,r);if(typeof o==\"string\"&&Na.hasColor(o))return o;if(o){let a=this.styles,n=e.enabled===!0,u=n?a.success:a.dark,A=o[n?\"on\":\"off\"]||o;return Na.hasColor(A)?A:u(A)}return\"\"}body(){return null}footer(){if(this.state.status===\"pending\")return this.element(\"footer\")}header(){if(this.state.status===\"pending\")return this.element(\"header\")}async hint(){if(this.state.status===\"pending\"&&!this.isValue(this.state.input)){let e=await this.element(\"hint\");return Na.hasColor(e)?e:this.styles.muted(e)}}error(e){return this.state.submitted?\"\":e||this.state.error}format(e){return e}result(e){return e}validate(e){return this.options.required===!0?this.isValue(e):!0}isValue(e){return e!=null&&e!==\"\"}resolve(e,...r){return Na.resolve(this,e,...r)}get base(){return t.prototype}get style(){return this.styles[this.state.status]}get height(){return this.options.rows||Na.height(this.stdout,25)}get width(){return this.options.columns||Na.width(this.stdout,80)}get size(){return{width:this.width,height:this.height}}set cursor(e){this.state.cursor=e}get cursor(){return this.state.cursor}set input(e){this.state.input=e}get input(){return this.state.input}set value(e){this.state.value=e}get value(){let{input:e,value:r}=this.state,o=[r,e].find(this.isValue.bind(this));return this.isValue(o)?o:this.initial}static get prompt(){return e=>new this(e).run()}};function lft(t){let e=a=>t[a]===void 0||typeof t[a]==\"function\",r=[\"actions\",\"choices\",\"initial\",\"margin\",\"roles\",\"styles\",\"symbols\",\"theme\",\"timers\",\"value\"],o=[\"body\",\"footer\",\"error\",\"header\",\"hint\",\"indicator\",\"message\",\"prefix\",\"separator\",\"skip\"];for(let a of Object.keys(t.options)){if(r.includes(a)||/^on[A-Z]/.test(a))continue;let n=t.options[a];typeof n==\"function\"&&e(a)?o.includes(a)||(t[a]=n.bind(t)):typeof t[a]!=\"function\"&&(t[a]=n)}}function cft(t){typeof t==\"number\"&&(t=[t,t,t,t]);let e=[].concat(t||[]),r=a=>a%2===0?`\n`:\" \",o=[];for(let a=0;a<4;a++){let n=r(a);e[a]?o.push(n.repeat(e[a])):o.push(\"\")}return o}Fhe.exports=M_});var Nhe=_((u8t,The)=>{\"use strict\";var uft=No(),Rhe={default(t,e){return e},checkbox(t,e){throw new Error(\"checkbox role is not implemented yet\")},editable(t,e){throw new Error(\"editable role is not implemented yet\")},expandable(t,e){throw new Error(\"expandable role is not implemented yet\")},heading(t,e){return e.disabled=\"\",e.indicator=[e.indicator,\" \"].find(r=>r!=null),e.message=e.message||\"\",e},input(t,e){throw new Error(\"input role is not implemented yet\")},option(t,e){return Rhe.default(t,e)},radio(t,e){throw new Error(\"radio role is not implemented yet\")},separator(t,e){return e.disabled=\"\",e.indicator=[e.indicator,\" \"].find(r=>r!=null),e.message=e.message||t.symbols.line.repeat(5),e},spacer(t,e){return e}};The.exports=(t,e={})=>{let r=uft.merge({},Rhe,e.roles);return r[t]||r.default}});var V1=_((A8t,Ohe)=>{\"use strict\";var Aft=zc(),fft=jy(),pft=Nhe(),zx=No(),{reorder:O_,scrollUp:hft,scrollDown:gft,isObject:Lhe,swap:dft}=zx,U_=class extends fft{constructor(e){super(e),this.cursorHide(),this.maxSelected=e.maxSelected||1/0,this.multiple=e.multiple||!1,this.initial=e.initial||0,this.delay=e.delay||0,this.longest=0,this.num=\"\"}async initialize(){typeof this.options.initial==\"function\"&&(this.initial=await this.options.initial.call(this)),await this.reset(!0),await super.initialize()}async reset(){let{choices:e,initial:r,autofocus:o,suggest:a}=this.options;if(this.state._choices=[],this.state.choices=[],this.choices=await Promise.all(await this.toChoices(e)),this.choices.forEach(n=>n.enabled=!1),typeof a!=\"function\"&&this.selectable.length===0)throw new Error(\"At least one choice must be selectable\");Lhe(r)&&(r=Object.keys(r)),Array.isArray(r)?(o!=null&&(this.index=this.findIndex(o)),r.forEach(n=>this.enable(this.find(n))),await this.render()):(o!=null&&(r=o),typeof r==\"string\"&&(r=this.findIndex(r)),typeof r==\"number\"&&r>-1&&(this.index=Math.max(0,Math.min(r,this.choices.length)),this.enable(this.find(this.index)))),this.isDisabled(this.focused)&&await this.down()}async toChoices(e,r){this.state.loadingChoices=!0;let o=[],a=0,n=async(u,A)=>{typeof u==\"function\"&&(u=await u.call(this)),u instanceof Promise&&(u=await u);for(let p=0;p<u.length;p++){let h=u[p]=await this.toChoice(u[p],a++,A);o.push(h),h.choices&&await n(h.choices,h)}return o};return n(e,r).then(u=>(this.state.loadingChoices=!1,u))}async toChoice(e,r,o){if(typeof e==\"function\"&&(e=await e.call(this,this)),e instanceof Promise&&(e=await e),typeof e==\"string\"&&(e={name:e}),e.normalized)return e;e.normalized=!0;let a=e.value;if(e=pft(e.role,this.options)(this,e),typeof e.disabled==\"string\"&&!e.hint&&(e.hint=e.disabled,e.disabled=!0),e.disabled===!0&&e.hint==null&&(e.hint=\"(disabled)\"),e.index!=null)return e;e.name=e.name||e.key||e.title||e.value||e.message,e.message=e.message||e.name||\"\",e.value=[e.value,e.name].find(this.isValue.bind(this)),e.input=\"\",e.index=r,e.cursor=0,zx.define(e,\"parent\",o),e.level=o?o.level+1:1,e.indent==null&&(e.indent=o?o.indent+\"  \":e.indent||\"\"),e.path=o?o.path+\".\"+e.name:e.name,e.enabled=!!(this.multiple&&!this.isDisabled(e)&&(e.enabled||this.isSelected(e))),this.isDisabled(e)||(this.longest=Math.max(this.longest,Aft.unstyle(e.message).length));let u={...e};return e.reset=(A=u.input,p=u.value)=>{for(let h of Object.keys(u))e[h]=u[h];e.input=A,e.value=p},a==null&&typeof e.initial==\"function\"&&(e.input=await e.initial.call(this,this.state,e,r)),e}async onChoice(e,r){this.emit(\"choice\",e,r,this),typeof e.onChoice==\"function\"&&await e.onChoice.call(this,this.state,e,r)}async addChoice(e,r,o){let a=await this.toChoice(e,r,o);return this.choices.push(a),this.index=this.choices.length-1,this.limit=this.choices.length,a}async newItem(e,r,o){let a={name:\"New choice name?\",editable:!0,newChoice:!0,...e},n=await this.addChoice(a,r,o);return n.updateChoice=()=>{delete n.newChoice,n.name=n.message=n.input,n.input=\"\",n.cursor=0},this.render()}indent(e){return e.indent==null?e.level>1?\"  \".repeat(e.level-1):\"\":e.indent}dispatch(e,r){if(this.multiple&&this[r.name])return this[r.name]();this.alert()}focus(e,r){return typeof r!=\"boolean\"&&(r=e.enabled),r&&!e.enabled&&this.selected.length>=this.maxSelected?this.alert():(this.index=e.index,e.enabled=r&&!this.isDisabled(e),e)}space(){return this.multiple?(this.toggle(this.focused),this.render()):this.alert()}a(){if(this.maxSelected<this.choices.length)return this.alert();let e=this.selectable.every(r=>r.enabled);return this.choices.forEach(r=>r.enabled=!e),this.render()}i(){return this.choices.length-this.selected.length>this.maxSelected?this.alert():(this.choices.forEach(e=>e.enabled=!e.enabled),this.render())}g(e=this.focused){return this.choices.some(r=>!!r.parent)?(this.toggle(e.parent&&!e.choices?e.parent:e),this.render()):this.a()}toggle(e,r){if(!e.enabled&&this.selected.length>=this.maxSelected)return this.alert();typeof r!=\"boolean\"&&(r=!e.enabled),e.enabled=r,e.choices&&e.choices.forEach(a=>this.toggle(a,r));let o=e.parent;for(;o;){let a=o.choices.filter(n=>this.isDisabled(n));o.enabled=a.every(n=>n.enabled===!0),o=o.parent}return Mhe(this,this.choices),this.emit(\"toggle\",e,this),e}enable(e){return this.selected.length>=this.maxSelected?this.alert():(e.enabled=!this.isDisabled(e),e.choices&&e.choices.forEach(this.enable.bind(this)),e)}disable(e){return e.enabled=!1,e.choices&&e.choices.forEach(this.disable.bind(this)),e}number(e){this.num+=e;let r=o=>{let a=Number(o);if(a>this.choices.length-1)return this.alert();let n=this.focused,u=this.choices.find(A=>a===A.index);if(!u.enabled&&this.selected.length>=this.maxSelected)return this.alert();if(this.visible.indexOf(u)===-1){let A=O_(this.choices),p=A.indexOf(u);if(n.index>p){let h=A.slice(p,p+this.limit),E=A.filter(I=>!h.includes(I));this.choices=h.concat(E)}else{let h=p-this.limit+1;this.choices=A.slice(h).concat(A.slice(0,h))}}return this.index=this.choices.indexOf(u),this.toggle(this.focused),this.render()};return clearTimeout(this.numberTimeout),new Promise(o=>{let a=this.choices.length,n=this.num,u=(A=!1,p)=>{clearTimeout(this.numberTimeout),A&&(p=r(n)),this.num=\"\",o(p)};if(n===\"0\"||n.length===1&&+(n+\"0\")>a)return u(!0);if(Number(n)>a)return u(!1,this.alert());this.numberTimeout=setTimeout(()=>u(!0),this.delay)})}home(){return this.choices=O_(this.choices),this.index=0,this.render()}end(){let e=this.choices.length-this.limit,r=O_(this.choices);return this.choices=r.slice(e).concat(r.slice(0,e)),this.index=this.limit-1,this.render()}first(){return this.index=0,this.render()}last(){return this.index=this.visible.length-1,this.render()}prev(){return this.visible.length<=1?this.alert():this.up()}next(){return this.visible.length<=1?this.alert():this.down()}right(){return this.cursor>=this.input.length?this.alert():(this.cursor++,this.render())}left(){return this.cursor<=0?this.alert():(this.cursor--,this.render())}up(){let e=this.choices.length,r=this.visible.length,o=this.index;return this.options.scroll===!1&&o===0?this.alert():e>r&&o===0?this.scrollUp():(this.index=(o-1%e+e)%e,this.isDisabled()?this.up():this.render())}down(){let e=this.choices.length,r=this.visible.length,o=this.index;return this.options.scroll===!1&&o===r-1?this.alert():e>r&&o===r-1?this.scrollDown():(this.index=(o+1)%e,this.isDisabled()?this.down():this.render())}scrollUp(e=0){return this.choices=hft(this.choices),this.index=e,this.isDisabled()?this.up():this.render()}scrollDown(e=this.visible.length-1){return this.choices=gft(this.choices),this.index=e,this.isDisabled()?this.down():this.render()}async shiftUp(){if(this.options.sort===!0){this.sorting=!0,this.swap(this.index-1),await this.up(),this.sorting=!1;return}return this.scrollUp(this.index)}async shiftDown(){if(this.options.sort===!0){this.sorting=!0,this.swap(this.index+1),await this.down(),this.sorting=!1;return}return this.scrollDown(this.index)}pageUp(){return this.visible.length<=1?this.alert():(this.limit=Math.max(this.limit-1,0),this.index=Math.min(this.limit-1,this.index),this._limit=this.limit,this.isDisabled()?this.up():this.render())}pageDown(){return this.visible.length>=this.choices.length?this.alert():(this.index=Math.max(0,this.index),this.limit=Math.min(this.limit+1,this.choices.length),this._limit=this.limit,this.isDisabled()?this.down():this.render())}swap(e){dft(this.choices,this.index,e)}isDisabled(e=this.focused){return e&&[\"disabled\",\"collapsed\",\"hidden\",\"completing\",\"readonly\"].some(o=>e[o]===!0)?!0:e&&e.role===\"heading\"}isEnabled(e=this.focused){if(Array.isArray(e))return e.every(r=>this.isEnabled(r));if(e.choices){let r=e.choices.filter(o=>!this.isDisabled(o));return e.enabled&&r.every(o=>this.isEnabled(o))}return e.enabled&&!this.isDisabled(e)}isChoice(e,r){return e.name===r||e.index===Number(r)}isSelected(e){return Array.isArray(this.initial)?this.initial.some(r=>this.isChoice(e,r)):this.isChoice(e,this.initial)}map(e=[],r=\"value\"){return[].concat(e||[]).reduce((o,a)=>(o[a]=this.find(a,r),o),{})}filter(e,r){let a=typeof e==\"function\"?e:(A,p)=>[A.name,p].includes(e),u=(this.options.multiple?this.state._choices:this.choices).filter(a);return r?u.map(A=>A[r]):u}find(e,r){if(Lhe(e))return r?e[r]:e;let a=typeof e==\"function\"?e:(u,A)=>[u.name,A].includes(e),n=this.choices.find(a);if(n)return r?n[r]:n}findIndex(e){return this.choices.indexOf(this.find(e))}async submit(){let e=this.focused;if(!e)return this.alert();if(e.newChoice)return e.input?(e.updateChoice(),this.render()):this.alert();if(this.choices.some(u=>u.newChoice))return this.alert();let{reorder:r,sort:o}=this.options,a=this.multiple===!0,n=this.selected;return n===void 0?this.alert():(Array.isArray(n)&&r!==!1&&o!==!0&&(n=zx.reorder(n)),this.value=a?n.map(u=>u.name):n.name,super.submit())}set choices(e=[]){this.state._choices=this.state._choices||[],this.state.choices=e;for(let r of e)this.state._choices.some(o=>o.name===r.name)||this.state._choices.push(r);if(!this._initial&&this.options.initial){this._initial=!0;let r=this.initial;if(typeof r==\"string\"||typeof r==\"number\"){let o=this.find(r);o&&(this.initial=o.index,this.focus(o,!0))}}}get choices(){return Mhe(this,this.state.choices||[])}set visible(e){this.state.visible=e}get visible(){return(this.state.visible||this.choices).slice(0,this.limit)}set limit(e){this.state.limit=e}get limit(){let{state:e,options:r,choices:o}=this,a=e.limit||this._limit||r.limit||o.length;return Math.min(a,this.height)}set value(e){super.value=e}get value(){return typeof super.value!=\"string\"&&super.value===this.initial?this.input:super.value}set index(e){this.state.index=e}get index(){return Math.max(0,this.state?this.state.index:0)}get enabled(){return this.filter(this.isEnabled.bind(this))}get focused(){let e=this.choices[this.index];return e&&this.state.submitted&&this.multiple!==!0&&(e.enabled=!0),e}get selectable(){return this.choices.filter(e=>!this.isDisabled(e))}get selected(){return this.multiple?this.enabled:this.focused}};function Mhe(t,e){if(e instanceof Promise)return e;if(typeof e==\"function\"){if(zx.isAsyncFn(e))return e;e=e.call(t,t)}for(let r of e){if(Array.isArray(r.choices)){let o=r.choices.filter(a=>!t.isDisabled(a));r.enabled=o.every(a=>a.enabled===!0)}t.isDisabled(r)===!0&&delete r.enabled}return e}Ohe.exports=U_});var Ph=_((f8t,Uhe)=>{\"use strict\";var mft=V1(),__=No(),H_=class extends mft{constructor(e){super(e),this.emptyError=this.options.emptyError||\"No items were selected\"}async dispatch(e,r){if(this.multiple)return this[r.name]?await this[r.name](e,r):await super.dispatch(e,r);this.alert()}separator(){if(this.options.separator)return super.separator();let e=this.styles.muted(this.symbols.ellipsis);return this.state.submitted?super.separator():e}pointer(e,r){return!this.multiple||this.options.pointer?super.pointer(e,r):\"\"}indicator(e,r){return this.multiple?super.indicator(e,r):\"\"}choiceMessage(e,r){let o=this.resolve(e.message,this.state,e,r);return e.role===\"heading\"&&!__.hasColor(o)&&(o=this.styles.strong(o)),this.resolve(o,this.state,e,r)}choiceSeparator(){return\":\"}async renderChoice(e,r){await this.onChoice(e,r);let o=this.index===r,a=await this.pointer(e,r),n=await this.indicator(e,r)+(e.pad||\"\"),u=await this.resolve(e.hint,this.state,e,r);u&&!__.hasColor(u)&&(u=this.styles.muted(u));let A=this.indent(e),p=await this.choiceMessage(e,r),h=()=>[this.margin[3],A+a+n,p,this.margin[1],u].filter(Boolean).join(\" \");return e.role===\"heading\"?h():e.disabled?(__.hasColor(p)||(p=this.styles.disabled(p)),h()):(o&&(p=this.styles.em(p)),h())}async renderChoices(){if(this.state.loading===\"choices\")return this.styles.warning(\"Loading choices\");if(this.state.submitted)return\"\";let e=this.visible.map(async(n,u)=>await this.renderChoice(n,u)),r=await Promise.all(e);r.length||r.push(this.styles.danger(\"No matching choices\"));let o=this.margin[0]+r.join(`\n`),a;return this.options.choicesHeader&&(a=await this.resolve(this.options.choicesHeader,this.state)),[a,o].filter(Boolean).join(`\n`)}format(){return!this.state.submitted||this.state.cancelled?\"\":Array.isArray(this.selected)?this.selected.map(e=>this.styles.primary(e.name)).join(\", \"):this.styles.primary(this.selected.name)}async render(){let{submitted:e,size:r}=this.state,o=\"\",a=await this.header(),n=await this.prefix(),u=await this.separator(),A=await this.message();this.options.promptLine!==!1&&(o=[n,A,u,\"\"].join(\" \"),this.state.prompt=o);let p=await this.format(),h=await this.error()||await this.hint(),E=await this.renderChoices(),I=await this.footer();p&&(o+=p),h&&!o.includes(h)&&(o+=\" \"+h),e&&!p&&!E.trim()&&this.multiple&&this.emptyError!=null&&(o+=this.styles.danger(this.emptyError)),this.clear(r),this.write([a,o,E,I].filter(Boolean).join(`\n`)),this.write(this.margin[2]),this.restore()}};Uhe.exports=H_});var Hhe=_((p8t,_he)=>{\"use strict\";var yft=Ph(),Eft=(t,e)=>{let r=t.toLowerCase();return o=>{let n=o.toLowerCase().indexOf(r),u=e(o.slice(n,n+r.length));return n>=0?o.slice(0,n)+u+o.slice(n+r.length):o}},q_=class extends yft{constructor(e){super(e),this.cursorShow()}moveCursor(e){this.state.cursor+=e}dispatch(e){return this.append(e)}space(e){return this.options.multiple?super.space(e):this.append(e)}append(e){let{cursor:r,input:o}=this.state;return this.input=o.slice(0,r)+e+o.slice(r),this.moveCursor(1),this.complete()}delete(){let{cursor:e,input:r}=this.state;return r?(this.input=r.slice(0,e-1)+r.slice(e),this.moveCursor(-1),this.complete()):this.alert()}deleteForward(){let{cursor:e,input:r}=this.state;return r[e]===void 0?this.alert():(this.input=`${r}`.slice(0,e)+`${r}`.slice(e+1),this.complete())}number(e){return this.append(e)}async complete(){this.completing=!0,this.choices=await this.suggest(this.input,this.state._choices),this.state.limit=void 0,this.index=Math.min(Math.max(this.visible.length-1,0),this.index),await this.render(),this.completing=!1}suggest(e=this.input,r=this.state._choices){if(typeof this.options.suggest==\"function\")return this.options.suggest.call(this,e,r);let o=e.toLowerCase();return r.filter(a=>a.message.toLowerCase().includes(o))}pointer(){return\"\"}format(){if(!this.focused)return this.input;if(this.options.multiple&&this.state.submitted)return this.selected.map(e=>this.styles.primary(e.message)).join(\", \");if(this.state.submitted){let e=this.value=this.input=this.focused.value;return this.styles.primary(e)}return this.input}async render(){if(this.state.status!==\"pending\")return super.render();let e=this.options.highlight?this.options.highlight.bind(this):this.styles.placeholder,r=Eft(this.input,e),o=this.choices;this.choices=o.map(a=>({...a,message:r(a.message)})),await super.render(),this.choices=o}submit(){return this.options.multiple&&(this.value=this.selected.map(e=>e.name)),super.submit()}};_he.exports=q_});var G_=_((h8t,qhe)=>{\"use strict\";var j_=No();qhe.exports=(t,e={})=>{t.cursorHide();let{input:r=\"\",initial:o=\"\",pos:a,showCursor:n=!0,color:u}=e,A=u||t.styles.placeholder,p=j_.inverse(t.styles.primary),h=R=>p(t.styles.black(R)),E=r,I=\" \",v=h(I);if(t.blink&&t.blink.off===!0&&(h=R=>R,v=\"\"),n&&a===0&&o===\"\"&&r===\"\")return h(I);if(n&&a===0&&(r===o||r===\"\"))return h(o[0])+A(o.slice(1));o=j_.isPrimitive(o)?`${o}`:\"\",r=j_.isPrimitive(r)?`${r}`:\"\";let x=o&&o.startsWith(r)&&o!==r,C=x?h(o[r.length]):v;if(a!==r.length&&n===!0&&(E=r.slice(0,a)+h(r[a])+r.slice(a+1),C=\"\"),n===!1&&(C=\"\"),x){let R=t.styles.unstyle(E+C);return E+C+A(o.slice(R.length))}return E+C}});var Jx=_((g8t,jhe)=>{\"use strict\";var Cft=zc(),wft=Ph(),Ift=G_(),Y_=class extends wft{constructor(e){super({...e,multiple:!0}),this.type=\"form\",this.initial=this.options.initial,this.align=[this.options.align,\"right\"].find(r=>r!=null),this.emptyError=\"\",this.values={}}async reset(e){return await super.reset(),e===!0&&(this._index=this.index),this.index=this._index,this.values={},this.choices.forEach(r=>r.reset&&r.reset()),this.render()}dispatch(e){return!!e&&this.append(e)}append(e){let r=this.focused;if(!r)return this.alert();let{cursor:o,input:a}=r;return r.value=r.input=a.slice(0,o)+e+a.slice(o),r.cursor++,this.render()}delete(){let e=this.focused;if(!e||e.cursor<=0)return this.alert();let{cursor:r,input:o}=e;return e.value=e.input=o.slice(0,r-1)+o.slice(r),e.cursor--,this.render()}deleteForward(){let e=this.focused;if(!e)return this.alert();let{cursor:r,input:o}=e;if(o[r]===void 0)return this.alert();let a=`${o}`.slice(0,r)+`${o}`.slice(r+1);return e.value=e.input=a,this.render()}right(){let e=this.focused;return e?e.cursor>=e.input.length?this.alert():(e.cursor++,this.render()):this.alert()}left(){let e=this.focused;return e?e.cursor<=0?this.alert():(e.cursor--,this.render()):this.alert()}space(e,r){return this.dispatch(e,r)}number(e,r){return this.dispatch(e,r)}next(){let e=this.focused;if(!e)return this.alert();let{initial:r,input:o}=e;return r&&r.startsWith(o)&&o!==r?(e.value=e.input=r,e.cursor=e.value.length,this.render()):super.next()}prev(){let e=this.focused;return e?e.cursor===0?super.prev():(e.value=e.input=\"\",e.cursor=0,this.render()):this.alert()}separator(){return\"\"}format(e){return this.state.submitted?\"\":super.format(e)}pointer(){return\"\"}indicator(e){return e.input?\"\\u29BF\":\"\\u2299\"}async choiceSeparator(e,r){let o=await this.resolve(e.separator,this.state,e,r)||\":\";return o?\" \"+this.styles.disabled(o):\"\"}async renderChoice(e,r){await this.onChoice(e,r);let{state:o,styles:a}=this,{cursor:n,initial:u=\"\",name:A,hint:p,input:h=\"\"}=e,{muted:E,submitted:I,primary:v,danger:x}=a,C=p,R=this.index===r,L=e.validate||(()=>!0),U=await this.choiceSeparator(e,r),z=e.message;this.align===\"right\"&&(z=z.padStart(this.longest+1,\" \")),this.align===\"left\"&&(z=z.padEnd(this.longest+1,\" \"));let te=this.values[A]=h||u,ae=h?\"success\":\"dark\";await L.call(e,te,this.state)!==!0&&(ae=\"danger\");let le=a[ae],ce=le(await this.indicator(e,r))+(e.pad||\"\"),Ce=this.indent(e),de=()=>[Ce,ce,z+U,h,C].filter(Boolean).join(\" \");if(o.submitted)return z=Cft.unstyle(z),h=I(h),C=\"\",de();if(e.format)h=await e.format.call(this,h,e,r);else{let Be=this.styles.muted;h=Ift(this,{input:h,initial:u,pos:n,showCursor:R,color:Be})}return this.isValue(h)||(h=this.styles.muted(this.symbols.ellipsis)),e.result&&(this.values[A]=await e.result.call(this,te,e,r)),R&&(z=v(z)),e.error?h+=(h?\" \":\"\")+x(e.error.trim()):e.hint&&(h+=(h?\" \":\"\")+E(e.hint.trim())),de()}async submit(){return this.value=this.values,super.base.submit.call(this)}};jhe.exports=Y_});var W_=_((d8t,Yhe)=>{\"use strict\";var Bft=Jx(),vft=()=>{throw new Error(\"expected prompt to have a custom authenticate method\")},Ghe=(t=vft)=>{class e extends Bft{constructor(o){super(o)}async submit(){this.value=await t.call(this,this.values,this.state),super.base.submit.call(this)}static create(o){return Ghe(o)}}return e};Yhe.exports=Ghe()});var Vhe=_((m8t,Khe)=>{\"use strict\";var Dft=W_();function Pft(t,e){return t.username===this.options.username&&t.password===this.options.password}var Whe=(t=Pft)=>{let e=[{name:\"username\",message:\"username\"},{name:\"password\",message:\"password\",format(o){return this.options.showPassword?o:(this.state.submitted?this.styles.primary:this.styles.muted)(this.symbols.asterisk.repeat(o.length))}}];class r extends Dft.create(t){constructor(a){super({...a,choices:e})}static create(a){return Whe(a)}}return r};Khe.exports=Whe()});var Xx=_((y8t,zhe)=>{\"use strict\";var bft=jy(),{isPrimitive:Sft,hasColor:xft}=No(),K_=class extends bft{constructor(e){super(e),this.cursorHide()}async initialize(){let e=await this.resolve(this.initial,this.state);this.input=await this.cast(e),await super.initialize()}dispatch(e){return this.isValue(e)?(this.input=e,this.submit()):this.alert()}format(e){let{styles:r,state:o}=this;return o.submitted?r.success(e):r.primary(e)}cast(e){return this.isTrue(e)}isTrue(e){return/^[ty1]/i.test(e)}isFalse(e){return/^[fn0]/i.test(e)}isValue(e){return Sft(e)&&(this.isTrue(e)||this.isFalse(e))}async hint(){if(this.state.status===\"pending\"){let e=await this.element(\"hint\");return xft(e)?e:this.styles.muted(e)}}async render(){let{input:e,size:r}=this.state,o=await this.prefix(),a=await this.separator(),n=await this.message(),u=this.styles.muted(this.default),A=[o,n,u,a].filter(Boolean).join(\" \");this.state.prompt=A;let p=await this.header(),h=this.value=this.cast(e),E=await this.format(h),I=await this.error()||await this.hint(),v=await this.footer();I&&!A.includes(I)&&(E+=\" \"+I),A+=\" \"+E,this.clear(r),this.write([p,A,v].filter(Boolean).join(`\n`)),this.restore()}set value(e){super.value=e}get value(){return this.cast(super.value)}};zhe.exports=K_});var Xhe=_((E8t,Jhe)=>{\"use strict\";var kft=Xx(),V_=class extends kft{constructor(e){super(e),this.default=this.options.default||(this.initial?\"(Y/n)\":\"(y/N)\")}};Jhe.exports=V_});var $he=_((C8t,Zhe)=>{\"use strict\";var Qft=Ph(),Fft=Jx(),Gy=Fft.prototype,z_=class extends Qft{constructor(e){super({...e,multiple:!0}),this.align=[this.options.align,\"left\"].find(r=>r!=null),this.emptyError=\"\",this.values={}}dispatch(e,r){let o=this.focused,a=o.parent||{};return!o.editable&&!a.editable&&(e===\"a\"||e===\"i\")?super[e]():Gy.dispatch.call(this,e,r)}append(e,r){return Gy.append.call(this,e,r)}delete(e,r){return Gy.delete.call(this,e,r)}space(e){return this.focused.editable?this.append(e):super.space()}number(e){return this.focused.editable?this.append(e):super.number(e)}next(){return this.focused.editable?Gy.next.call(this):super.next()}prev(){return this.focused.editable?Gy.prev.call(this):super.prev()}async indicator(e,r){let o=e.indicator||\"\",a=e.editable?o:super.indicator(e,r);return await this.resolve(a,this.state,e,r)||\"\"}indent(e){return e.role===\"heading\"?\"\":e.editable?\" \":\"  \"}async renderChoice(e,r){return e.indent=\"\",e.editable?Gy.renderChoice.call(this,e,r):super.renderChoice(e,r)}error(){return\"\"}footer(){return this.state.error}async validate(){let e=!0;for(let r of this.choices){if(typeof r.validate!=\"function\"||r.role===\"heading\")continue;let o=r.parent?this.value[r.parent.name]:this.value;if(r.editable?o=r.value===r.name?r.initial||\"\":r.value:this.isDisabled(r)||(o=r.enabled===!0),e=await r.validate(o,this.state),e!==!0)break}return e!==!0&&(this.state.error=typeof e==\"string\"?e:\"Invalid Input\"),e}submit(){if(this.focused.newChoice===!0)return super.submit();if(this.choices.some(e=>e.newChoice))return this.alert();this.value={};for(let e of this.choices){let r=e.parent?this.value[e.parent.name]:this.value;if(e.role===\"heading\"){this.value[e.name]={};continue}e.editable?r[e.name]=e.value===e.name?e.initial||\"\":e.value:this.isDisabled(e)||(r[e.name]=e.enabled===!0)}return this.base.submit.call(this)}};Zhe.exports=z_});var _g=_((w8t,e0e)=>{\"use strict\";var Rft=jy(),Tft=G_(),{isPrimitive:Nft}=No(),J_=class extends Rft{constructor(e){super(e),this.initial=Nft(this.initial)?String(this.initial):\"\",this.initial&&this.cursorHide(),this.state.prevCursor=0,this.state.clipboard=[]}async keypress(e,r={}){let o=this.state.prevKeypress;return this.state.prevKeypress=r,this.options.multiline===!0&&r.name===\"return\"&&(!o||o.name!==\"return\")?this.append(`\n`,r):super.keypress(e,r)}moveCursor(e){this.cursor+=e}reset(){return this.input=this.value=\"\",this.cursor=0,this.render()}dispatch(e,r){if(!e||r.ctrl||r.code)return this.alert();this.append(e)}append(e){let{cursor:r,input:o}=this.state;this.input=`${o}`.slice(0,r)+e+`${o}`.slice(r),this.moveCursor(String(e).length),this.render()}insert(e){this.append(e)}delete(){let{cursor:e,input:r}=this.state;if(e<=0)return this.alert();this.input=`${r}`.slice(0,e-1)+`${r}`.slice(e),this.moveCursor(-1),this.render()}deleteForward(){let{cursor:e,input:r}=this.state;if(r[e]===void 0)return this.alert();this.input=`${r}`.slice(0,e)+`${r}`.slice(e+1),this.render()}cutForward(){let e=this.cursor;if(this.input.length<=e)return this.alert();this.state.clipboard.push(this.input.slice(e)),this.input=this.input.slice(0,e),this.render()}cutLeft(){let e=this.cursor;if(e===0)return this.alert();let r=this.input.slice(0,e),o=this.input.slice(e),a=r.split(\" \");this.state.clipboard.push(a.pop()),this.input=a.join(\" \"),this.cursor=this.input.length,this.input+=o,this.render()}paste(){if(!this.state.clipboard.length)return this.alert();this.insert(this.state.clipboard.pop()),this.render()}toggleCursor(){this.state.prevCursor?(this.cursor=this.state.prevCursor,this.state.prevCursor=0):(this.state.prevCursor=this.cursor,this.cursor=0),this.render()}first(){this.cursor=0,this.render()}last(){this.cursor=this.input.length-1,this.render()}next(){let e=this.initial!=null?String(this.initial):\"\";if(!e||!e.startsWith(this.input))return this.alert();this.input=this.initial,this.cursor=this.initial.length,this.render()}prev(){if(!this.input)return this.alert();this.reset()}backward(){return this.left()}forward(){return this.right()}right(){return this.cursor>=this.input.length?this.alert():(this.moveCursor(1),this.render())}left(){return this.cursor<=0?this.alert():(this.moveCursor(-1),this.render())}isValue(e){return!!e}async format(e=this.value){let r=await this.resolve(this.initial,this.state);return this.state.submitted?this.styles.submitted(e||r):Tft(this,{input:e,initial:r,pos:this.cursor})}async render(){let e=this.state.size,r=await this.prefix(),o=await this.separator(),a=await this.message(),n=[r,a,o].filter(Boolean).join(\" \");this.state.prompt=n;let u=await this.header(),A=await this.format(),p=await this.error()||await this.hint(),h=await this.footer();p&&!A.includes(p)&&(A+=\" \"+p),n+=\" \"+A,this.clear(e),this.write([u,n,h].filter(Boolean).join(`\n`)),this.restore()}};e0e.exports=J_});var r0e=_((I8t,t0e)=>{\"use strict\";var Lft=t=>t.filter((e,r)=>t.lastIndexOf(e)===r),Zx=t=>Lft(t).filter(Boolean);t0e.exports=(t,e={},r=\"\")=>{let{past:o=[],present:a=\"\"}=e,n,u;switch(t){case\"prev\":case\"undo\":return n=o.slice(0,o.length-1),u=o[o.length-1]||\"\",{past:Zx([r,...n]),present:u};case\"next\":case\"redo\":return n=o.slice(1),u=o[0]||\"\",{past:Zx([...n,r]),present:u};case\"save\":return{past:Zx([...o,r]),present:\"\"};case\"remove\":return u=Zx(o.filter(A=>A!==r)),a=\"\",u.length&&(a=u.pop()),{past:u,present:a};default:throw new Error(`Invalid action: \"${t}\"`)}}});var Z_=_((B8t,i0e)=>{\"use strict\";var Mft=_g(),n0e=r0e(),X_=class extends Mft{constructor(e){super(e);let r=this.options.history;if(r&&r.store){let o=r.values||this.initial;this.autosave=!!r.autosave,this.store=r.store,this.data=this.store.get(\"values\")||{past:[],present:o},this.initial=this.data.present||this.data.past[this.data.past.length-1]}}completion(e){return this.store?(this.data=n0e(e,this.data,this.input),this.data.present?(this.input=this.data.present,this.cursor=this.input.length,this.render()):this.alert()):this.alert()}altUp(){return this.completion(\"prev\")}altDown(){return this.completion(\"next\")}prev(){return this.save(),super.prev()}save(){this.store&&(this.data=n0e(\"save\",this.data,this.input),this.store.set(\"values\",this.data))}submit(){return this.store&&this.autosave===!0&&this.save(),super.submit()}};i0e.exports=X_});var o0e=_((v8t,s0e)=>{\"use strict\";var Oft=_g(),$_=class extends Oft{format(){return\"\"}};s0e.exports=$_});var l0e=_((D8t,a0e)=>{\"use strict\";var Uft=_g(),e8=class extends Uft{constructor(e={}){super(e),this.sep=this.options.separator||/, */,this.initial=e.initial||\"\"}split(e=this.value){return e?String(e).split(this.sep):[]}format(){let e=this.state.submitted?this.styles.primary:r=>r;return this.list.map(e).join(\", \")}async submit(e){let r=this.state.error||await this.validate(this.list,this.state);return r!==!0?(this.state.error=r,super.submit()):(this.value=this.list,super.submit())}get list(){return this.split()}};a0e.exports=e8});var u0e=_((P8t,c0e)=>{\"use strict\";var _ft=Ph(),t8=class extends _ft{constructor(e){super({...e,multiple:!0})}};c0e.exports=t8});var n8=_((b8t,A0e)=>{\"use strict\";var Hft=_g(),r8=class extends Hft{constructor(e={}){super({style:\"number\",...e}),this.min=this.isValue(e.min)?this.toNumber(e.min):-1/0,this.max=this.isValue(e.max)?this.toNumber(e.max):1/0,this.delay=e.delay!=null?e.delay:1e3,this.float=e.float!==!1,this.round=e.round===!0||e.float===!1,this.major=e.major||10,this.minor=e.minor||1,this.initial=e.initial!=null?e.initial:\"\",this.input=String(this.initial),this.cursor=this.input.length,this.cursorShow()}append(e){return!/[-+.]/.test(e)||e===\".\"&&this.input.includes(\".\")?this.alert(\"invalid number\"):super.append(e)}number(e){return super.append(e)}next(){return this.input&&this.input!==this.initial?this.alert():this.isValue(this.initial)?(this.input=this.initial,this.cursor=String(this.initial).length,this.render()):this.alert()}up(e){let r=e||this.minor,o=this.toNumber(this.input);return o>this.max+r?this.alert():(this.input=`${o+r}`,this.render())}down(e){let r=e||this.minor,o=this.toNumber(this.input);return o<this.min-r?this.alert():(this.input=`${o-r}`,this.render())}shiftDown(){return this.down(this.major)}shiftUp(){return this.up(this.major)}format(e=this.input){return typeof this.options.format==\"function\"?this.options.format.call(this,e):this.styles.info(e)}toNumber(e=\"\"){return this.float?+e:Math.round(+e)}isValue(e){return/^[-+]?[0-9]+((\\.)|(\\.[0-9]+))?$/.test(e)}submit(){let e=[this.input,this.initial].find(r=>this.isValue(r));return this.value=this.toNumber(e||0),super.submit()}};A0e.exports=r8});var p0e=_((S8t,f0e)=>{f0e.exports=n8()});var g0e=_((x8t,h0e)=>{\"use strict\";var qft=_g(),i8=class extends qft{constructor(e){super(e),this.cursorShow()}format(e=this.input){return this.keypressed?(this.state.submitted?this.styles.primary:this.styles.muted)(this.symbols.asterisk.repeat(e.length)):\"\"}};h0e.exports=i8});var y0e=_((k8t,m0e)=>{\"use strict\";var jft=zc(),Gft=V1(),d0e=No(),s8=class extends Gft{constructor(e={}){super(e),this.widths=[].concat(e.messageWidth||50),this.align=[].concat(e.align||\"left\"),this.linebreak=e.linebreak||!1,this.edgeLength=e.edgeLength||3,this.newline=e.newline||`\n   `;let r=e.startNumber||1;typeof this.scale==\"number\"&&(this.scaleKey=!1,this.scale=Array(this.scale).fill(0).map((o,a)=>({name:a+r})))}async reset(){return this.tableized=!1,await super.reset(),this.render()}tableize(){if(this.tableized===!0)return;this.tableized=!0;let e=0;for(let r of this.choices){e=Math.max(e,r.message.length),r.scaleIndex=r.initial||2,r.scale=[];for(let o=0;o<this.scale.length;o++)r.scale.push({index:o})}this.widths[0]=Math.min(this.widths[0],e+3)}async dispatch(e,r){if(this.multiple)return this[r.name]?await this[r.name](e,r):await super.dispatch(e,r);this.alert()}heading(e,r,o){return this.styles.strong(e)}separator(){return this.styles.muted(this.symbols.ellipsis)}right(){let e=this.focused;return e.scaleIndex>=this.scale.length-1?this.alert():(e.scaleIndex++,this.render())}left(){let e=this.focused;return e.scaleIndex<=0?this.alert():(e.scaleIndex--,this.render())}indent(){return\"\"}format(){return this.state.submitted?this.choices.map(r=>this.styles.info(r.index)).join(\", \"):\"\"}pointer(){return\"\"}renderScaleKey(){return this.scaleKey===!1||this.state.submitted?\"\":[\"\",...this.scale.map(o=>`   ${o.name} - ${o.message}`)].map(o=>this.styles.muted(o)).join(`\n`)}renderScaleHeading(e){let r=this.scale.map(p=>p.name);typeof this.options.renderScaleHeading==\"function\"&&(r=this.options.renderScaleHeading.call(this,e));let o=this.scaleLength-r.join(\"\").length,a=Math.round(o/(r.length-1)),u=r.map(p=>this.styles.strong(p)).join(\" \".repeat(a)),A=\" \".repeat(this.widths[0]);return this.margin[3]+A+this.margin[1]+u}scaleIndicator(e,r,o){if(typeof this.options.scaleIndicator==\"function\")return this.options.scaleIndicator.call(this,e,r,o);let a=e.scaleIndex===r.index;return r.disabled?this.styles.hint(this.symbols.radio.disabled):a?this.styles.success(this.symbols.radio.on):this.symbols.radio.off}renderScale(e,r){let o=e.scale.map(n=>this.scaleIndicator(e,n,r)),a=this.term===\"Hyper\"?\"\":\" \";return o.join(a+this.symbols.line.repeat(this.edgeLength))}async renderChoice(e,r){await this.onChoice(e,r);let o=this.index===r,a=await this.pointer(e,r),n=await e.hint;n&&!d0e.hasColor(n)&&(n=this.styles.muted(n));let u=C=>this.margin[3]+C.replace(/\\s+$/,\"\").padEnd(this.widths[0],\" \"),A=this.newline,p=this.indent(e),h=await this.resolve(e.message,this.state,e,r),E=await this.renderScale(e,r),I=this.margin[1]+this.margin[3];this.scaleLength=jft.unstyle(E).length,this.widths[0]=Math.min(this.widths[0],this.width-this.scaleLength-I.length);let x=d0e.wordWrap(h,{width:this.widths[0],newline:A}).split(`\n`).map(C=>u(C)+this.margin[1]);return o&&(E=this.styles.info(E),x=x.map(C=>this.styles.info(C))),x[0]+=E,this.linebreak&&x.push(\"\"),[p+a,x.join(`\n`)].filter(Boolean)}async renderChoices(){if(this.state.submitted)return\"\";this.tableize();let e=this.visible.map(async(a,n)=>await this.renderChoice(a,n)),r=await Promise.all(e),o=await this.renderScaleHeading();return this.margin[0]+[o,...r.map(a=>a.join(\" \"))].join(`\n`)}async render(){let{submitted:e,size:r}=this.state,o=await this.prefix(),a=await this.separator(),n=await this.message(),u=\"\";this.options.promptLine!==!1&&(u=[o,n,a,\"\"].join(\" \"),this.state.prompt=u);let A=await this.header(),p=await this.format(),h=await this.renderScaleKey(),E=await this.error()||await this.hint(),I=await this.renderChoices(),v=await this.footer(),x=this.emptyError;p&&(u+=p),E&&!u.includes(E)&&(u+=\" \"+E),e&&!p&&!I.trim()&&this.multiple&&x!=null&&(u+=this.styles.danger(x)),this.clear(r),this.write([A,u,h,I,v].filter(Boolean).join(`\n`)),this.state.submitted||this.write(this.margin[2]),this.restore()}submit(){this.value={};for(let e of this.choices)this.value[e.name]=e.scaleIndex;return this.base.submit.call(this)}};m0e.exports=s8});var w0e=_((Q8t,C0e)=>{\"use strict\";var E0e=zc(),Yft=(t=\"\")=>typeof t==\"string\"?t.replace(/^['\"]|['\"]$/g,\"\"):\"\",a8=class{constructor(e){this.name=e.key,this.field=e.field||{},this.value=Yft(e.initial||this.field.initial||\"\"),this.message=e.message||this.name,this.cursor=0,this.input=\"\",this.lines=[]}},Wft=async(t={},e={},r=o=>o)=>{let o=new Set,a=t.fields||[],n=t.template,u=[],A=[],p=[],h=1;typeof n==\"function\"&&(n=await n());let E=-1,I=()=>n[++E],v=()=>n[E+1],x=C=>{C.line=h,u.push(C)};for(x({type:\"bos\",value:\"\"});E<n.length-1;){let C=I();if(/^[^\\S\\n ]$/.test(C)){x({type:\"text\",value:C});continue}if(C===`\n`){x({type:\"newline\",value:C}),h++;continue}if(C===\"\\\\\"){C+=I(),x({type:\"text\",value:C});continue}if((C===\"$\"||C===\"#\"||C===\"{\")&&v()===\"{\"){let L=I();C+=L;let U={type:\"template\",open:C,inner:\"\",close:\"\",value:C},z;for(;z=I();){if(z===\"}\"){v()===\"}\"&&(z+=I()),U.value+=z,U.close=z;break}z===\":\"?(U.initial=\"\",U.key=U.inner):U.initial!==void 0&&(U.initial+=z),U.value+=z,U.inner+=z}U.template=U.open+(U.initial||U.inner)+U.close,U.key=U.key||U.inner,e.hasOwnProperty(U.key)&&(U.initial=e[U.key]),U=r(U),x(U),p.push(U.key),o.add(U.key);let te=A.find(ae=>ae.name===U.key);U.field=a.find(ae=>ae.name===U.key),te||(te=new a8(U),A.push(te)),te.lines.push(U.line-1);continue}let R=u[u.length-1];R.type===\"text\"&&R.line===h?R.value+=C:x({type:\"text\",value:C})}return x({type:\"eos\",value:\"\"}),{input:n,tabstops:u,unique:o,keys:p,items:A}};C0e.exports=async t=>{let e=t.options,r=new Set(e.required===!0?[]:e.required||[]),o={...e.values,...e.initial},{tabstops:a,items:n,keys:u}=await Wft(e,o),A=o8(\"result\",t,e),p=o8(\"format\",t,e),h=o8(\"validate\",t,e,!0),E=t.isValue.bind(t);return async(I={},v=!1)=>{let x=0;I.required=r,I.items=n,I.keys=u,I.output=\"\";let C=async(z,te,ae,le)=>{let ce=await h(z,te,ae,le);return ce===!1?\"Invalid field \"+ae.name:ce};for(let z of a){let te=z.value,ae=z.key;if(z.type!==\"template\"){te&&(I.output+=te);continue}if(z.type===\"template\"){let le=n.find(Ee=>Ee.name===ae);e.required===!0&&I.required.add(le.name);let ce=[le.input,I.values[le.value],le.value,te].find(E),de=(le.field||{}).message||z.inner;if(v){let Ee=await C(I.values[ae],I,le,x);if(Ee&&typeof Ee==\"string\"||Ee===!1){I.invalid.set(ae,Ee);continue}I.invalid.delete(ae);let g=await A(I.values[ae],I,le,x);I.output+=E0e.unstyle(g);continue}le.placeholder=!1;let Be=te;te=await p(te,I,le,x),ce!==te?(I.values[ae]=ce,te=t.styles.typing(ce),I.missing.delete(de)):(I.values[ae]=void 0,ce=`<${de}>`,te=t.styles.primary(ce),le.placeholder=!0,I.required.has(ae)&&I.missing.add(de)),I.missing.has(de)&&I.validating&&(te=t.styles.warning(ce)),I.invalid.has(ae)&&I.validating&&(te=t.styles.danger(ce)),x===I.index&&(Be!==te?te=t.styles.underline(te):te=t.styles.heading(E0e.unstyle(te))),x++}te&&(I.output+=te)}let R=I.output.split(`\n`).map(z=>\" \"+z),L=n.length,U=0;for(let z of n)I.invalid.has(z.name)&&z.lines.forEach(te=>{R[te][0]===\" \"&&(R[te]=I.styles.danger(I.symbols.bullet)+R[te].slice(1))}),t.isValue(I.values[z.name])&&U++;return I.completed=(U/L*100).toFixed(0),I.output=R.join(`\n`),I.output}};function o8(t,e,r,o){return(a,n,u,A)=>typeof u.field[t]==\"function\"?u.field[t].call(e,a,n,u,A):[o,a].find(p=>e.isValue(p))}});var B0e=_((F8t,I0e)=>{\"use strict\";var Kft=zc(),Vft=w0e(),zft=jy(),l8=class extends zft{constructor(e){super(e),this.cursorHide(),this.reset(!0)}async initialize(){this.interpolate=await Vft(this),await super.initialize()}async reset(e){this.state.keys=[],this.state.invalid=new Map,this.state.missing=new Set,this.state.completed=0,this.state.values={},e!==!0&&(await this.initialize(),await this.render())}moveCursor(e){let r=this.getItem();this.cursor+=e,r.cursor+=e}dispatch(e,r){if(!r.code&&!r.ctrl&&e!=null&&this.getItem()){this.append(e,r);return}this.alert()}append(e,r){let o=this.getItem(),a=o.input.slice(0,this.cursor),n=o.input.slice(this.cursor);this.input=o.input=`${a}${e}${n}`,this.moveCursor(1),this.render()}delete(){let e=this.getItem();if(this.cursor<=0||!e.input)return this.alert();let r=e.input.slice(this.cursor),o=e.input.slice(0,this.cursor-1);this.input=e.input=`${o}${r}`,this.moveCursor(-1),this.render()}increment(e){return e>=this.state.keys.length-1?0:e+1}decrement(e){return e<=0?this.state.keys.length-1:e-1}first(){this.state.index=0,this.render()}last(){this.state.index=this.state.keys.length-1,this.render()}right(){if(this.cursor>=this.input.length)return this.alert();this.moveCursor(1),this.render()}left(){if(this.cursor<=0)return this.alert();this.moveCursor(-1),this.render()}prev(){this.state.index=this.decrement(this.state.index),this.getItem(),this.render()}next(){this.state.index=this.increment(this.state.index),this.getItem(),this.render()}up(){this.prev()}down(){this.next()}format(e){let r=this.state.completed<100?this.styles.warning:this.styles.success;return this.state.submitted===!0&&this.state.completed!==100&&(r=this.styles.danger),r(`${this.state.completed}% completed`)}async render(){let{index:e,keys:r=[],submitted:o,size:a}=this.state,n=[this.options.newline,`\n`].find(z=>z!=null),u=await this.prefix(),A=await this.separator(),p=await this.message(),h=[u,p,A].filter(Boolean).join(\" \");this.state.prompt=h;let E=await this.header(),I=await this.error()||\"\",v=await this.hint()||\"\",x=o?\"\":await this.interpolate(this.state),C=this.state.key=r[e]||\"\",R=await this.format(C),L=await this.footer();R&&(h+=\" \"+R),v&&!R&&this.state.completed===0&&(h+=\" \"+v),this.clear(a);let U=[E,h,x,L,I.trim()];this.write(U.filter(Boolean).join(n)),this.restore()}getItem(e){let{items:r,keys:o,index:a}=this.state,n=r.find(u=>u.name===o[a]);return n&&n.input!=null&&(this.input=n.input,this.cursor=n.cursor),n}async submit(){typeof this.interpolate!=\"function\"&&await this.initialize(),await this.interpolate(this.state,!0);let{invalid:e,missing:r,output:o,values:a}=this.state;if(e.size){let A=\"\";for(let[p,h]of e)A+=`Invalid ${p}: ${h}\n`;return this.state.error=A,super.submit()}if(r.size)return this.state.error=\"Required: \"+[...r.keys()].join(\", \"),super.submit();let u=Kft.unstyle(o).split(`\n`).map(A=>A.slice(1)).join(`\n`);return this.value={values:a,result:u},super.submit()}};I0e.exports=l8});var D0e=_((R8t,v0e)=>{\"use strict\";var Jft=\"(Use <shift>+<up/down> to sort)\",Xft=Ph(),c8=class extends Xft{constructor(e){super({...e,reorder:!1,sort:!0,multiple:!0}),this.state.hint=[this.options.hint,Jft].find(this.isValue.bind(this))}indicator(){return\"\"}async renderChoice(e,r){let o=await super.renderChoice(e,r),a=this.symbols.identicalTo+\" \",n=this.index===r&&this.sorting?this.styles.muted(a):\"  \";return this.options.drag===!1&&(n=\"\"),this.options.numbered===!0?n+`${r+1} - `+o:n+o}get selected(){return this.choices}submit(){return this.value=this.choices.map(e=>e.value),super.submit()}};v0e.exports=c8});var b0e=_((T8t,P0e)=>{\"use strict\";var Zft=V1(),u8=class extends Zft{constructor(e={}){if(super(e),this.emptyError=e.emptyError||\"No items were selected\",this.term=process.env.TERM_PROGRAM,!this.options.header){let r=[\"\",\"4 - Strongly Agree\",\"3 - Agree\",\"2 - Neutral\",\"1 - Disagree\",\"0 - Strongly Disagree\",\"\"];r=r.map(o=>this.styles.muted(o)),this.state.header=r.join(`\n   `)}}async toChoices(...e){if(this.createdScales)return!1;this.createdScales=!0;let r=await super.toChoices(...e);for(let o of r)o.scale=$ft(5,this.options),o.scaleIdx=2;return r}dispatch(){this.alert()}space(){let e=this.focused,r=e.scale[e.scaleIdx],o=r.selected;return e.scale.forEach(a=>a.selected=!1),r.selected=!o,this.render()}indicator(){return\"\"}pointer(){return\"\"}separator(){return this.styles.muted(this.symbols.ellipsis)}right(){let e=this.focused;return e.scaleIdx>=e.scale.length-1?this.alert():(e.scaleIdx++,this.render())}left(){let e=this.focused;return e.scaleIdx<=0?this.alert():(e.scaleIdx--,this.render())}indent(){return\"   \"}async renderChoice(e,r){await this.onChoice(e,r);let o=this.index===r,a=this.term===\"Hyper\",n=a?9:8,u=a?\"\":\" \",A=this.symbols.line.repeat(n),p=\" \".repeat(n+(a?0:1)),h=te=>(te?this.styles.success(\"\\u25C9\"):\"\\u25EF\")+u,E=r+1+\".\",I=o?this.styles.heading:this.styles.noop,v=await this.resolve(e.message,this.state,e,r),x=this.indent(e),C=x+e.scale.map((te,ae)=>h(ae===e.scaleIdx)).join(A),R=te=>te===e.scaleIdx?I(te):te,L=x+e.scale.map((te,ae)=>R(ae)).join(p),U=()=>[E,v].filter(Boolean).join(\" \"),z=()=>[U(),C,L,\" \"].filter(Boolean).join(`\n`);return o&&(C=this.styles.cyan(C),L=this.styles.cyan(L)),z()}async renderChoices(){if(this.state.submitted)return\"\";let e=this.visible.map(async(o,a)=>await this.renderChoice(o,a)),r=await Promise.all(e);return r.length||r.push(this.styles.danger(\"No matching choices\")),r.join(`\n`)}format(){return this.state.submitted?this.choices.map(r=>this.styles.info(r.scaleIdx)).join(\", \"):\"\"}async render(){let{submitted:e,size:r}=this.state,o=await this.prefix(),a=await this.separator(),n=await this.message(),u=[o,n,a].filter(Boolean).join(\" \");this.state.prompt=u;let A=await this.header(),p=await this.format(),h=await this.error()||await this.hint(),E=await this.renderChoices(),I=await this.footer();(p||!h)&&(u+=\" \"+p),h&&!u.includes(h)&&(u+=\" \"+h),e&&!p&&!E&&this.multiple&&this.type!==\"form\"&&(u+=this.styles.danger(this.emptyError)),this.clear(r),this.write([u,A,E,I].filter(Boolean).join(`\n`)),this.restore()}submit(){this.value={};for(let e of this.choices)this.value[e.name]=e.scaleIdx;return this.base.submit.call(this)}};function $ft(t,e={}){if(Array.isArray(e.scale))return e.scale.map(o=>({...o}));let r=[];for(let o=1;o<t+1;o++)r.push({i:o,selected:!1});return r}P0e.exports=u8});var x0e=_((N8t,S0e)=>{S0e.exports=Z_()});var Q0e=_((L8t,k0e)=>{\"use strict\";var ept=Xx(),A8=class extends ept{async initialize(){await super.initialize(),this.value=this.initial=!!this.options.initial,this.disabled=this.options.disabled||\"no\",this.enabled=this.options.enabled||\"yes\",await this.render()}reset(){this.value=this.initial,this.render()}delete(){this.alert()}toggle(){this.value=!this.value,this.render()}enable(){if(this.value===!0)return this.alert();this.value=!0,this.render()}disable(){if(this.value===!1)return this.alert();this.value=!1,this.render()}up(){this.toggle()}down(){this.toggle()}right(){this.toggle()}left(){this.toggle()}next(){this.toggle()}prev(){this.toggle()}dispatch(e=\"\",r){switch(e.toLowerCase()){case\" \":return this.toggle();case\"1\":case\"y\":case\"t\":return this.enable();case\"0\":case\"n\":case\"f\":return this.disable();default:return this.alert()}}format(){let e=o=>this.styles.primary.underline(o);return[this.value?this.disabled:e(this.disabled),this.value?e(this.enabled):this.enabled].join(this.styles.muted(\" / \"))}async render(){let{size:e}=this.state,r=await this.header(),o=await this.prefix(),a=await this.separator(),n=await this.message(),u=await this.format(),A=await this.error()||await this.hint(),p=await this.footer(),h=[o,n,a,u].join(\" \");this.state.prompt=h,A&&!h.includes(A)&&(h+=\" \"+A),this.clear(e),this.write([r,h,p].filter(Boolean).join(`\n`)),this.write(this.margin[2]),this.restore()}};k0e.exports=A8});var R0e=_((M8t,F0e)=>{\"use strict\";var tpt=Ph(),f8=class extends tpt{constructor(e){if(super(e),typeof this.options.correctChoice!=\"number\"||this.options.correctChoice<0)throw new Error(\"Please specify the index of the correct answer from the list of choices\")}async toChoices(e,r){let o=await super.toChoices(e,r);if(o.length<2)throw new Error(\"Please give at least two choices to the user\");if(this.options.correctChoice>o.length)throw new Error(\"Please specify the index of the correct answer from the list of choices\");return o}check(e){return e.index===this.options.correctChoice}async result(e){return{selectedAnswer:e,correctAnswer:this.options.choices[this.options.correctChoice].value,correct:await this.check(this.state)}}};F0e.exports=f8});var N0e=_(p8=>{\"use strict\";var T0e=No(),ps=(t,e)=>{T0e.defineExport(p8,t,e),T0e.defineExport(p8,t.toLowerCase(),e)};ps(\"AutoComplete\",()=>Hhe());ps(\"BasicAuth\",()=>Vhe());ps(\"Confirm\",()=>Xhe());ps(\"Editable\",()=>$he());ps(\"Form\",()=>Jx());ps(\"Input\",()=>Z_());ps(\"Invisible\",()=>o0e());ps(\"List\",()=>l0e());ps(\"MultiSelect\",()=>u0e());ps(\"Numeral\",()=>p0e());ps(\"Password\",()=>g0e());ps(\"Scale\",()=>y0e());ps(\"Select\",()=>Ph());ps(\"Snippet\",()=>B0e());ps(\"Sort\",()=>D0e());ps(\"Survey\",()=>b0e());ps(\"Text\",()=>x0e());ps(\"Toggle\",()=>Q0e());ps(\"Quiz\",()=>R0e())});var M0e=_((U8t,L0e)=>{L0e.exports={ArrayPrompt:V1(),AuthPrompt:W_(),BooleanPrompt:Xx(),NumberPrompt:n8(),StringPrompt:_g()}});var J1=_((_8t,U0e)=>{\"use strict\";var O0e=ve(\"assert\"),g8=ve(\"events\"),bh=No(),Xc=class extends g8{constructor(e,r){super(),this.options=bh.merge({},e),this.answers={...r}}register(e,r){if(bh.isObject(e)){for(let a of Object.keys(e))this.register(a,e[a]);return this}O0e.equal(typeof r,\"function\",\"expected a function\");let o=e.toLowerCase();return r.prototype instanceof this.Prompt?this.prompts[o]=r:this.prompts[o]=r(this.Prompt,this),this}async prompt(e=[]){for(let r of[].concat(e))try{typeof r==\"function\"&&(r=await r.call(this)),await this.ask(bh.merge({},this.options,r))}catch(o){return Promise.reject(o)}return this.answers}async ask(e){typeof e==\"function\"&&(e=await e.call(this));let r=bh.merge({},this.options,e),{type:o,name:a}=e,{set:n,get:u}=bh;if(typeof o==\"function\"&&(o=await o.call(this,e,this.answers)),!o)return this.answers[a];O0e(this.prompts[o],`Prompt \"${o}\" is not registered`);let A=new this.prompts[o](r),p=u(this.answers,a);A.state.answers=this.answers,A.enquirer=this,a&&A.on(\"submit\",E=>{this.emit(\"answer\",a,E,A),n(this.answers,a,E)});let h=A.emit.bind(A);return A.emit=(...E)=>(this.emit.call(this,...E),h(...E)),this.emit(\"prompt\",A,this),r.autofill&&p!=null?(A.value=A.input=p,r.autofill===\"show\"&&await A.submit()):p=A.value=await A.run(),p}use(e){return e.call(this,this),this}set Prompt(e){this._Prompt=e}get Prompt(){return this._Prompt||this.constructor.Prompt}get prompts(){return this.constructor.prompts}static set Prompt(e){this._Prompt=e}static get Prompt(){return this._Prompt||jy()}static get prompts(){return N0e()}static get types(){return M0e()}static get prompt(){let e=(r,...o)=>{let a=new this(...o),n=a.emit.bind(a);return a.emit=(...u)=>(e.emit(...u),n(...u)),a.prompt(r)};return bh.mixinEmitter(e,new g8),e}};bh.mixinEmitter(Xc,new g8);var h8=Xc.prompts;for(let t of Object.keys(h8)){let e=t.toLowerCase(),r=o=>new h8[t](o).run();Xc.prompt[e]=r,Xc[e]=r,Xc[t]||Reflect.defineProperty(Xc,t,{get:()=>h8[t]})}var z1=t=>{bh.defineExport(Xc,t,()=>Xc.types[t])};z1(\"ArrayPrompt\");z1(\"AuthPrompt\");z1(\"BooleanPrompt\");z1(\"NumberPrompt\");z1(\"StringPrompt\");U0e.exports=Xc});var e2=_((IHt,W0e)=>{var apt=Ux();function lpt(t,e,r){var o=t==null?void 0:apt(t,e);return o===void 0?r:o}W0e.exports=lpt});var z0e=_((SHt,V0e)=>{function cpt(t,e){for(var r=-1,o=t==null?0:t.length;++r<o&&e(t[r],r,t)!==!1;);return t}V0e.exports=cpt});var X0e=_((xHt,J0e)=>{var upt=Ag(),Apt=LP();function fpt(t,e){return t&&upt(e,Apt(e),t)}J0e.exports=fpt});var $0e=_((kHt,Z0e)=>{var ppt=Ag(),hpt=bm();function gpt(t,e){return t&&ppt(e,hpt(e),t)}Z0e.exports=gpt});var tge=_((QHt,ege)=>{var dpt=Ag(),mpt=kP();function ypt(t,e){return dpt(t,mpt(t),e)}ege.exports=ypt});var w8=_((FHt,rge)=>{var Ept=xP(),Cpt=HP(),wpt=kP(),Ipt=MN(),Bpt=Object.getOwnPropertySymbols,vpt=Bpt?function(t){for(var e=[];t;)Ept(e,wpt(t)),t=Cpt(t);return e}:Ipt;rge.exports=vpt});var ige=_((RHt,nge)=>{var Dpt=Ag(),Ppt=w8();function bpt(t,e){return Dpt(t,Ppt(t),e)}nge.exports=bpt});var I8=_((THt,sge)=>{var Spt=LN(),xpt=w8(),kpt=bm();function Qpt(t){return Spt(t,kpt,xpt)}sge.exports=Qpt});var age=_((NHt,oge)=>{var Fpt=Object.prototype,Rpt=Fpt.hasOwnProperty;function Tpt(t){var e=t.length,r=new t.constructor(e);return e&&typeof t[0]==\"string\"&&Rpt.call(t,\"index\")&&(r.index=t.index,r.input=t.input),r}oge.exports=Tpt});var cge=_((LHt,lge)=>{var Npt=UP();function Lpt(t,e){var r=e?Npt(t.buffer):t.buffer;return new t.constructor(r,t.byteOffset,t.byteLength)}lge.exports=Lpt});var Age=_((MHt,uge)=>{var Mpt=/\\w*$/;function Opt(t){var e=new t.constructor(t.source,Mpt.exec(t));return e.lastIndex=t.lastIndex,e}uge.exports=Opt});var dge=_((OHt,gge)=>{var fge=lg(),pge=fge?fge.prototype:void 0,hge=pge?pge.valueOf:void 0;function Upt(t){return hge?Object(hge.call(t)):{}}gge.exports=Upt});var yge=_((UHt,mge)=>{var _pt=UP(),Hpt=cge(),qpt=Age(),jpt=dge(),Gpt=XN(),Ypt=\"[object Boolean]\",Wpt=\"[object Date]\",Kpt=\"[object Map]\",Vpt=\"[object Number]\",zpt=\"[object RegExp]\",Jpt=\"[object Set]\",Xpt=\"[object String]\",Zpt=\"[object Symbol]\",$pt=\"[object ArrayBuffer]\",eht=\"[object DataView]\",tht=\"[object Float32Array]\",rht=\"[object Float64Array]\",nht=\"[object Int8Array]\",iht=\"[object Int16Array]\",sht=\"[object Int32Array]\",oht=\"[object Uint8Array]\",aht=\"[object Uint8ClampedArray]\",lht=\"[object Uint16Array]\",cht=\"[object Uint32Array]\";function uht(t,e,r){var o=t.constructor;switch(e){case $pt:return _pt(t);case Ypt:case Wpt:return new o(+t);case eht:return Hpt(t,r);case tht:case rht:case nht:case iht:case sht:case oht:case aht:case lht:case cht:return Gpt(t,r);case Kpt:return new o;case Vpt:case Xpt:return new o(t);case zpt:return qpt(t);case Jpt:return new o;case Zpt:return jpt(t)}}mge.exports=uht});var Cge=_((_Ht,Ege)=>{var Aht=PI(),fht=Ju(),pht=\"[object Map]\";function hht(t){return fht(t)&&Aht(t)==pht}Ege.exports=hht});var vge=_((HHt,Bge)=>{var ght=Cge(),dht=FP(),wge=RP(),Ige=wge&&wge.isMap,mht=Ige?dht(Ige):ght;Bge.exports=mht});var Pge=_((qHt,Dge)=>{var yht=PI(),Eht=Ju(),Cht=\"[object Set]\";function wht(t){return Eht(t)&&yht(t)==Cht}Dge.exports=wht});var kge=_((jHt,xge)=>{var Iht=Pge(),Bht=FP(),bge=RP(),Sge=bge&&bge.isSet,vht=Sge?Bht(Sge):Iht;xge.exports=vht});var B8=_((GHt,Tge)=>{var Dht=bP(),Pht=z0e(),bht=qP(),Sht=X0e(),xht=$0e(),kht=JN(),Qht=_P(),Fht=tge(),Rht=ige(),Tht=HN(),Nht=I8(),Lht=PI(),Mht=age(),Oht=yge(),Uht=ZN(),_ht=Hl(),Hht=wI(),qht=vge(),jht=sl(),Ght=kge(),Yht=LP(),Wht=bm(),Kht=1,Vht=2,zht=4,Qge=\"[object Arguments]\",Jht=\"[object Array]\",Xht=\"[object Boolean]\",Zht=\"[object Date]\",$ht=\"[object Error]\",Fge=\"[object Function]\",e0t=\"[object GeneratorFunction]\",t0t=\"[object Map]\",r0t=\"[object Number]\",Rge=\"[object Object]\",n0t=\"[object RegExp]\",i0t=\"[object Set]\",s0t=\"[object String]\",o0t=\"[object Symbol]\",a0t=\"[object WeakMap]\",l0t=\"[object ArrayBuffer]\",c0t=\"[object DataView]\",u0t=\"[object Float32Array]\",A0t=\"[object Float64Array]\",f0t=\"[object Int8Array]\",p0t=\"[object Int16Array]\",h0t=\"[object Int32Array]\",g0t=\"[object Uint8Array]\",d0t=\"[object Uint8ClampedArray]\",m0t=\"[object Uint16Array]\",y0t=\"[object Uint32Array]\",ri={};ri[Qge]=ri[Jht]=ri[l0t]=ri[c0t]=ri[Xht]=ri[Zht]=ri[u0t]=ri[A0t]=ri[f0t]=ri[p0t]=ri[h0t]=ri[t0t]=ri[r0t]=ri[Rge]=ri[n0t]=ri[i0t]=ri[s0t]=ri[o0t]=ri[g0t]=ri[d0t]=ri[m0t]=ri[y0t]=!0;ri[$ht]=ri[Fge]=ri[a0t]=!1;function ek(t,e,r,o,a,n){var u,A=e&Kht,p=e&Vht,h=e&zht;if(r&&(u=a?r(t,o,a,n):r(t)),u!==void 0)return u;if(!jht(t))return t;var E=_ht(t);if(E){if(u=Mht(t),!A)return Qht(t,u)}else{var I=Lht(t),v=I==Fge||I==e0t;if(Hht(t))return kht(t,A);if(I==Rge||I==Qge||v&&!a){if(u=p||v?{}:Uht(t),!A)return p?Rht(t,xht(u,t)):Fht(t,Sht(u,t))}else{if(!ri[I])return a?t:{};u=Oht(t,I,A)}}n||(n=new Dht);var x=n.get(t);if(x)return x;n.set(t,u),Ght(t)?t.forEach(function(L){u.add(ek(L,e,r,L,t,n))}):qht(t)&&t.forEach(function(L,U){u.set(U,ek(L,e,r,U,t,n))});var C=h?p?Nht:Tht:p?Wht:Yht,R=E?void 0:C(t);return Pht(R||t,function(L,U){R&&(U=L,L=t[U]),bht(u,U,ek(L,e,r,U,t,n))}),u}Tge.exports=ek});var v8=_((YHt,Nge)=>{var E0t=B8(),C0t=1,w0t=4;function I0t(t){return E0t(t,C0t|w0t)}Nge.exports=I0t});var D8=_((WHt,Lge)=>{var B0t=g_();function v0t(t,e,r){return t==null?t:B0t(t,e,r)}Lge.exports=v0t});var Hge=_((ZHt,_ge)=>{var D0t=Object.prototype,P0t=D0t.hasOwnProperty;function b0t(t,e){return t!=null&&P0t.call(t,e)}_ge.exports=b0t});var jge=_(($Ht,qge)=>{var S0t=Hge(),x0t=d_();function k0t(t,e){return t!=null&&x0t(t,e,S0t)}qge.exports=k0t});var Yge=_((e6t,Gge)=>{function Q0t(t){var e=t==null?0:t.length;return e?t[e-1]:void 0}Gge.exports=Q0t});var Kge=_((t6t,Wge)=>{var F0t=Ux(),R0t=oU();function T0t(t,e){return e.length<2?t:F0t(t,R0t(e,0,-1))}Wge.exports=T0t});var b8=_((r6t,Vge)=>{var N0t=Mg(),L0t=Yge(),M0t=Kge(),O0t=Ly();function U0t(t,e){return e=N0t(e,t),t=M0t(t,e),t==null||delete t[O0t(L0t(e))]}Vge.exports=U0t});var S8=_((n6t,zge)=>{var _0t=b8();function H0t(t,e){return t==null?!0:_0t(t,e)}zge.exports=H0t});var ede=_((F6t,G0t)=>{G0t.exports={name:\"@yarnpkg/cli\",version:\"4.4.1\",license:\"BSD-2-Clause\",main:\"./sources/index.ts\",exports:{\".\":\"./sources/index.ts\",\"./polyfills\":\"./sources/polyfills.ts\",\"./package.json\":\"./package.json\"},dependencies:{\"@yarnpkg/core\":\"workspace:^\",\"@yarnpkg/fslib\":\"workspace:^\",\"@yarnpkg/libzip\":\"workspace:^\",\"@yarnpkg/parsers\":\"workspace:^\",\"@yarnpkg/plugin-compat\":\"workspace:^\",\"@yarnpkg/plugin-constraints\":\"workspace:^\",\"@yarnpkg/plugin-dlx\":\"workspace:^\",\"@yarnpkg/plugin-essentials\":\"workspace:^\",\"@yarnpkg/plugin-exec\":\"workspace:^\",\"@yarnpkg/plugin-file\":\"workspace:^\",\"@yarnpkg/plugin-git\":\"workspace:^\",\"@yarnpkg/plugin-github\":\"workspace:^\",\"@yarnpkg/plugin-http\":\"workspace:^\",\"@yarnpkg/plugin-init\":\"workspace:^\",\"@yarnpkg/plugin-interactive-tools\":\"workspace:^\",\"@yarnpkg/plugin-link\":\"workspace:^\",\"@yarnpkg/plugin-nm\":\"workspace:^\",\"@yarnpkg/plugin-npm\":\"workspace:^\",\"@yarnpkg/plugin-npm-cli\":\"workspace:^\",\"@yarnpkg/plugin-pack\":\"workspace:^\",\"@yarnpkg/plugin-patch\":\"workspace:^\",\"@yarnpkg/plugin-pnp\":\"workspace:^\",\"@yarnpkg/plugin-pnpm\":\"workspace:^\",\"@yarnpkg/plugin-stage\":\"workspace:^\",\"@yarnpkg/plugin-typescript\":\"workspace:^\",\"@yarnpkg/plugin-version\":\"workspace:^\",\"@yarnpkg/plugin-workspace-tools\":\"workspace:^\",\"@yarnpkg/shell\":\"workspace:^\",\"ci-info\":\"^4.0.0\",clipanion:\"^4.0.0-rc.2\",semver:\"^7.1.2\",tslib:\"^2.4.0\",typanion:\"^3.14.0\"},devDependencies:{\"@types/semver\":\"^7.1.0\",\"@yarnpkg/builder\":\"workspace:^\",\"@yarnpkg/monorepo\":\"workspace:^\",\"@yarnpkg/pnpify\":\"workspace:^\"},peerDependencies:{\"@yarnpkg/core\":\"workspace:^\"},scripts:{postpack:\"rm -rf lib\",prepack:'run build:compile \"$(pwd)\"',\"build:cli+hook\":\"run build:pnp:hook && builder build bundle\",\"build:cli\":\"builder build bundle\",\"run:cli\":\"builder run\",\"update-local\":\"run build:cli --no-git-hash && rsync -a --delete bundles/ bin/\"},publishConfig:{main:\"./lib/index.js\",bin:null,exports:{\".\":\"./lib/index.js\",\"./package.json\":\"./package.json\"}},files:[\"/lib/**/*\",\"!/lib/pluginConfiguration.*\",\"!/lib/cli.*\"],\"@yarnpkg/builder\":{bundles:{standard:[\"@yarnpkg/plugin-essentials\",\"@yarnpkg/plugin-compat\",\"@yarnpkg/plugin-constraints\",\"@yarnpkg/plugin-dlx\",\"@yarnpkg/plugin-exec\",\"@yarnpkg/plugin-file\",\"@yarnpkg/plugin-git\",\"@yarnpkg/plugin-github\",\"@yarnpkg/plugin-http\",\"@yarnpkg/plugin-init\",\"@yarnpkg/plugin-interactive-tools\",\"@yarnpkg/plugin-link\",\"@yarnpkg/plugin-nm\",\"@yarnpkg/plugin-npm\",\"@yarnpkg/plugin-npm-cli\",\"@yarnpkg/plugin-pack\",\"@yarnpkg/plugin-patch\",\"@yarnpkg/plugin-pnp\",\"@yarnpkg/plugin-pnpm\",\"@yarnpkg/plugin-stage\",\"@yarnpkg/plugin-typescript\",\"@yarnpkg/plugin-version\",\"@yarnpkg/plugin-workspace-tools\"]}},repository:{type:\"git\",url:\"ssh://git@github.com/yarnpkg/berry.git\",directory:\"packages/yarnpkg-cli\"},engines:{node:\">=18.12.0\"}}});var M8=_((cGt,fde)=>{\"use strict\";fde.exports=function(e,r){r===!0&&(r=0);var o=\"\";if(typeof e==\"string\")try{o=new URL(e).protocol}catch{}else e&&e.constructor===URL&&(o=e.protocol);var a=o.split(/\\:|\\+/).filter(Boolean);return typeof r==\"number\"?a[r]:a}});var hde=_((uGt,pde)=>{\"use strict\";var ugt=M8();function Agt(t){var e={protocols:[],protocol:null,port:null,resource:\"\",host:\"\",user:\"\",password:\"\",pathname:\"\",hash:\"\",search:\"\",href:t,query:{},parse_failed:!1};try{var r=new URL(t);e.protocols=ugt(r),e.protocol=e.protocols[0],e.port=r.port,e.resource=r.hostname,e.host=r.host,e.user=r.username||\"\",e.password=r.password||\"\",e.pathname=r.pathname,e.hash=r.hash.slice(1),e.search=r.search.slice(1),e.href=r.href,e.query=Object.fromEntries(r.searchParams)}catch{e.protocols=[\"file\"],e.protocol=e.protocols[0],e.port=\"\",e.resource=\"\",e.user=\"\",e.pathname=\"\",e.hash=\"\",e.search=\"\",e.href=t,e.query={},e.parse_failed=!0}return e}pde.exports=Agt});var mde=_((AGt,dde)=>{\"use strict\";var fgt=hde();function pgt(t){return t&&typeof t==\"object\"&&\"default\"in t?t:{default:t}}var hgt=pgt(fgt),ggt=\"text/plain\",dgt=\"us-ascii\",gde=(t,e)=>e.some(r=>r instanceof RegExp?r.test(t):r===t),mgt=(t,{stripHash:e})=>{let r=/^data:(?<type>[^,]*?),(?<data>[^#]*?)(?:#(?<hash>.*))?$/.exec(t);if(!r)throw new Error(`Invalid URL: ${t}`);let{type:o,data:a,hash:n}=r.groups,u=o.split(\";\");n=e?\"\":n;let A=!1;u[u.length-1]===\"base64\"&&(u.pop(),A=!0);let p=(u.shift()||\"\").toLowerCase(),E=[...u.map(I=>{let[v,x=\"\"]=I.split(\"=\").map(C=>C.trim());return v===\"charset\"&&(x=x.toLowerCase(),x===dgt)?\"\":`${v}${x?`=${x}`:\"\"}`}).filter(Boolean)];return A&&E.push(\"base64\"),(E.length>0||p&&p!==ggt)&&E.unshift(p),`data:${E.join(\";\")},${A?a.trim():a}${n?`#${n}`:\"\"}`};function ygt(t,e){if(e={defaultProtocol:\"http:\",normalizeProtocol:!0,forceHttp:!1,forceHttps:!1,stripAuthentication:!0,stripHash:!1,stripTextFragment:!0,stripWWW:!0,removeQueryParameters:[/^utm_\\w+/i],removeTrailingSlash:!0,removeSingleSlash:!0,removeDirectoryIndex:!1,sortQueryParameters:!0,...e},t=t.trim(),/^data:/i.test(t))return mgt(t,e);if(/^view-source:/i.test(t))throw new Error(\"`view-source:` is not supported as it is a non-standard protocol\");let r=t.startsWith(\"//\");!r&&/^\\.*\\//.test(t)||(t=t.replace(/^(?!(?:\\w+:)?\\/\\/)|^\\/\\//,e.defaultProtocol));let a=new URL(t);if(e.forceHttp&&e.forceHttps)throw new Error(\"The `forceHttp` and `forceHttps` options cannot be used together\");if(e.forceHttp&&a.protocol===\"https:\"&&(a.protocol=\"http:\"),e.forceHttps&&a.protocol===\"http:\"&&(a.protocol=\"https:\"),e.stripAuthentication&&(a.username=\"\",a.password=\"\"),e.stripHash?a.hash=\"\":e.stripTextFragment&&(a.hash=a.hash.replace(/#?:~:text.*?$/i,\"\")),a.pathname){let u=/\\b[a-z][a-z\\d+\\-.]{1,50}:\\/\\//g,A=0,p=\"\";for(;;){let E=u.exec(a.pathname);if(!E)break;let I=E[0],v=E.index,x=a.pathname.slice(A,v);p+=x.replace(/\\/{2,}/g,\"/\"),p+=I,A=v+I.length}let h=a.pathname.slice(A,a.pathname.length);p+=h.replace(/\\/{2,}/g,\"/\"),a.pathname=p}if(a.pathname)try{a.pathname=decodeURI(a.pathname)}catch{}if(e.removeDirectoryIndex===!0&&(e.removeDirectoryIndex=[/^index\\.[a-z]+$/]),Array.isArray(e.removeDirectoryIndex)&&e.removeDirectoryIndex.length>0){let u=a.pathname.split(\"/\"),A=u[u.length-1];gde(A,e.removeDirectoryIndex)&&(u=u.slice(0,-1),a.pathname=u.slice(1).join(\"/\")+\"/\")}if(a.hostname&&(a.hostname=a.hostname.replace(/\\.$/,\"\"),e.stripWWW&&/^www\\.(?!www\\.)[a-z\\-\\d]{1,63}\\.[a-z.\\-\\d]{2,63}$/.test(a.hostname)&&(a.hostname=a.hostname.replace(/^www\\./,\"\"))),Array.isArray(e.removeQueryParameters))for(let u of[...a.searchParams.keys()])gde(u,e.removeQueryParameters)&&a.searchParams.delete(u);if(e.removeQueryParameters===!0&&(a.search=\"\"),e.sortQueryParameters){a.searchParams.sort();try{a.search=decodeURIComponent(a.search)}catch{}}e.removeTrailingSlash&&(a.pathname=a.pathname.replace(/\\/$/,\"\"));let n=t;return t=a.toString(),!e.removeSingleSlash&&a.pathname===\"/\"&&!n.endsWith(\"/\")&&a.hash===\"\"&&(t=t.replace(/\\/$/,\"\")),(e.removeTrailingSlash||a.pathname===\"/\")&&a.hash===\"\"&&e.removeSingleSlash&&(t=t.replace(/\\/$/,\"\")),r&&!e.normalizeProtocol&&(t=t.replace(/^http:\\/\\//,\"//\")),e.stripProtocol&&(t=t.replace(/^(?:https?:)?\\/\\//,\"\")),t}var O8=(t,e=!1)=>{let r=/^(?:([a-z_][a-z0-9_-]{0,31})@|https?:\\/\\/)([\\w\\.\\-@]+)[\\/:]([\\~,\\.\\w,\\-,\\_,\\/]+?(?:\\.git|\\/)?)$/,o=n=>{let u=new Error(n);throw u.subject_url=t,u};(typeof t!=\"string\"||!t.trim())&&o(\"Invalid url.\"),t.length>O8.MAX_INPUT_LENGTH&&o(\"Input exceeds maximum length. If needed, change the value of parseUrl.MAX_INPUT_LENGTH.\"),e&&(typeof e!=\"object\"&&(e={stripHash:!1}),t=ygt(t,e));let a=hgt.default(t);if(a.parse_failed){let n=a.href.match(r);n?(a.protocols=[\"ssh\"],a.protocol=\"ssh\",a.resource=n[2],a.host=n[2],a.user=n[1],a.pathname=`/${n[3]}`,a.parse_failed=!1):o(\"URL parsing failed.\")}return a};O8.MAX_INPUT_LENGTH=2048;dde.exports=O8});var Cde=_((fGt,Ede)=>{\"use strict\";var Egt=M8();function yde(t){if(Array.isArray(t))return t.indexOf(\"ssh\")!==-1||t.indexOf(\"rsync\")!==-1;if(typeof t!=\"string\")return!1;var e=Egt(t);if(t=t.substring(t.indexOf(\"://\")+3),yde(e))return!0;var r=new RegExp(\".([a-zA-Z\\\\d]+):(\\\\d+)/\");return!t.match(r)&&t.indexOf(\"@\")<t.indexOf(\":\")}Ede.exports=yde});var Bde=_((pGt,Ide)=>{\"use strict\";var Cgt=mde(),wde=Cde();function wgt(t){var e=Cgt(t);return e.token=\"\",e.password===\"x-oauth-basic\"?e.token=e.user:e.user===\"x-token-auth\"&&(e.token=e.password),wde(e.protocols)||e.protocols.length===0&&wde(t)?e.protocol=\"ssh\":e.protocols.length?e.protocol=e.protocols[0]:(e.protocol=\"file\",e.protocols=[\"file\"]),e.href=e.href.replace(/\\/$/,\"\"),e}Ide.exports=wgt});var Dde=_((hGt,vde)=>{\"use strict\";var Igt=Bde();function U8(t){if(typeof t!=\"string\")throw new Error(\"The url must be a string.\");var e=/^([a-z\\d-]{1,39})\\/([-\\.\\w]{1,100})$/i;e.test(t)&&(t=\"https://github.com/\"+t);var r=Igt(t),o=r.resource.split(\".\"),a=null;switch(r.toString=function(L){return U8.stringify(this,L)},r.source=o.length>2?o.slice(1-o.length).join(\".\"):r.source=r.resource,r.git_suffix=/\\.git$/.test(r.pathname),r.name=decodeURIComponent((r.pathname||r.href).replace(/(^\\/)|(\\/$)/g,\"\").replace(/\\.git$/,\"\")),r.owner=decodeURIComponent(r.user),r.source){case\"git.cloudforge.com\":r.owner=r.user,r.organization=o[0],r.source=\"cloudforge.com\";break;case\"visualstudio.com\":if(r.resource===\"vs-ssh.visualstudio.com\"){a=r.name.split(\"/\"),a.length===4&&(r.organization=a[1],r.owner=a[2],r.name=a[3],r.full_name=a[2]+\"/\"+a[3]);break}else{a=r.name.split(\"/\"),a.length===2?(r.owner=a[1],r.name=a[1],r.full_name=\"_git/\"+r.name):a.length===3?(r.name=a[2],a[0]===\"DefaultCollection\"?(r.owner=a[2],r.organization=a[0],r.full_name=r.organization+\"/_git/\"+r.name):(r.owner=a[0],r.full_name=r.owner+\"/_git/\"+r.name)):a.length===4&&(r.organization=a[0],r.owner=a[1],r.name=a[3],r.full_name=r.organization+\"/\"+r.owner+\"/_git/\"+r.name);break}case\"dev.azure.com\":case\"azure.com\":if(r.resource===\"ssh.dev.azure.com\"){a=r.name.split(\"/\"),a.length===4&&(r.organization=a[1],r.owner=a[2],r.name=a[3]);break}else{a=r.name.split(\"/\"),a.length===5?(r.organization=a[0],r.owner=a[1],r.name=a[4],r.full_name=\"_git/\"+r.name):a.length===3?(r.name=a[2],a[0]===\"DefaultCollection\"?(r.owner=a[2],r.organization=a[0],r.full_name=r.organization+\"/_git/\"+r.name):(r.owner=a[0],r.full_name=r.owner+\"/_git/\"+r.name)):a.length===4&&(r.organization=a[0],r.owner=a[1],r.name=a[3],r.full_name=r.organization+\"/\"+r.owner+\"/_git/\"+r.name),r.query&&r.query.path&&(r.filepath=r.query.path.replace(/^\\/+/g,\"\")),r.query&&r.query.version&&(r.ref=r.query.version.replace(/^GB/,\"\"));break}default:a=r.name.split(\"/\");var n=a.length-1;if(a.length>=2){var u=a.indexOf(\"-\",2),A=a.indexOf(\"blob\",2),p=a.indexOf(\"tree\",2),h=a.indexOf(\"commit\",2),E=a.indexOf(\"src\",2),I=a.indexOf(\"raw\",2),v=a.indexOf(\"edit\",2);n=u>0?u-1:A>0?A-1:p>0?p-1:h>0?h-1:E>0?E-1:I>0?I-1:v>0?v-1:n,r.owner=a.slice(0,n).join(\"/\"),r.name=a[n],h&&(r.commit=a[n+2])}r.ref=\"\",r.filepathtype=\"\",r.filepath=\"\";var x=a.length>n&&a[n+1]===\"-\"?n+1:n;a.length>x+2&&[\"raw\",\"src\",\"blob\",\"tree\",\"edit\"].indexOf(a[x+1])>=0&&(r.filepathtype=a[x+1],r.ref=a[x+2],a.length>x+3&&(r.filepath=a.slice(x+3).join(\"/\"))),r.organization=r.owner;break}r.full_name||(r.full_name=r.owner,r.name&&(r.full_name&&(r.full_name+=\"/\"),r.full_name+=r.name)),r.owner.startsWith(\"scm/\")&&(r.source=\"bitbucket-server\",r.owner=r.owner.replace(\"scm/\",\"\"),r.organization=r.owner,r.full_name=r.owner+\"/\"+r.name);var C=/(projects|users)\\/(.*?)\\/repos\\/(.*?)((\\/.*$)|$)/,R=C.exec(r.pathname);return R!=null&&(r.source=\"bitbucket-server\",R[1]===\"users\"?r.owner=\"~\"+R[2]:r.owner=R[2],r.organization=r.owner,r.name=R[3],a=R[4].split(\"/\"),a.length>1&&([\"raw\",\"browse\"].indexOf(a[1])>=0?(r.filepathtype=a[1],a.length>2&&(r.filepath=a.slice(2).join(\"/\"))):a[1]===\"commits\"&&a.length>2&&(r.commit=a[2])),r.full_name=r.owner+\"/\"+r.name,r.query.at?r.ref=r.query.at:r.ref=\"\"),r}U8.stringify=function(t,e){e=e||(t.protocols&&t.protocols.length?t.protocols.join(\"+\"):t.protocol);var r=t.port?\":\"+t.port:\"\",o=t.user||\"git\",a=t.git_suffix?\".git\":\"\";switch(e){case\"ssh\":return r?\"ssh://\"+o+\"@\"+t.resource+r+\"/\"+t.full_name+a:o+\"@\"+t.resource+\":\"+t.full_name+a;case\"git+ssh\":case\"ssh+git\":case\"ftp\":case\"ftps\":return e+\"://\"+o+\"@\"+t.resource+r+\"/\"+t.full_name+a;case\"http\":case\"https\":var n=t.token?Bgt(t):t.user&&(t.protocols.includes(\"http\")||t.protocols.includes(\"https\"))?t.user+\"@\":\"\";return e+\"://\"+n+t.resource+r+\"/\"+vgt(t)+a;default:return t.href}};function Bgt(t){switch(t.source){case\"bitbucket.org\":return\"x-token-auth:\"+t.token+\"@\";default:return t.token+\"@\"}}function vgt(t){switch(t.source){case\"bitbucket-server\":return\"scm/\"+t.full_name;default:return\"\"+t.full_name}}vde.exports=U8});var Hde=_((K9t,_de)=>{var Ngt=xS(),Lgt=_P(),Mgt=Hl(),Ogt=Ym(),Ugt=h_(),_gt=Ly(),Hgt=C1();function qgt(t){return Mgt(t)?Ngt(t,_gt):Ogt(t)?[t]:Lgt(Ugt(Hgt(t)))}_de.exports=qgt});function Wgt(t,e){return e===1&&Ygt.has(t[0])}function a2(t){let e=Array.isArray(t)?t:(0,Gde.default)(t);return e.map((o,a)=>jgt.test(o)?`[${o}]`:Ggt.test(o)&&!Wgt(e,a)?`.${o}`:`[${JSON.stringify(o)}]`).join(\"\").replace(/^\\./,\"\")}function Kgt(t,e){let r=[];if(e.methodName!==null&&r.push(pe.pretty(t,e.methodName,pe.Type.CODE)),e.file!==null){let o=[];o.push(pe.pretty(t,e.file,pe.Type.PATH)),e.line!==null&&(o.push(pe.pretty(t,e.line,pe.Type.NUMBER)),e.column!==null&&o.push(pe.pretty(t,e.column,pe.Type.NUMBER))),r.push(`(${o.join(pe.pretty(t,\":\",\"grey\"))})`)}return r.join(\" \")}function ik(t,{manifestUpdates:e,reportedErrors:r},{fix:o}={}){let a=new Map,n=new Map,u=[...r.keys()].map(A=>[A,new Map]);for(let[A,p]of[...u,...e]){let h=r.get(A)?.map(x=>({text:x,fixable:!1}))??[],E=!1,I=t.getWorkspaceByCwd(A),v=I.manifest.exportTo({});for(let[x,C]of p){if(C.size>1){let R=[...C].map(([L,U])=>{let z=pe.pretty(t.configuration,L,pe.Type.INSPECT),te=U.size>0?Kgt(t.configuration,U.values().next().value):null;return te!==null?`\n${z} at ${te}`:`\n${z}`}).join(\"\");h.push({text:`Conflict detected in constraint targeting ${pe.pretty(t.configuration,x,pe.Type.CODE)}; conflicting values are:${R}`,fixable:!1})}else{let[[R]]=C,L=(0,qde.default)(v,x);if(JSON.stringify(L)===JSON.stringify(R))continue;if(!o){let U=typeof L>\"u\"?`Missing field ${pe.pretty(t.configuration,x,pe.Type.CODE)}; expected ${pe.pretty(t.configuration,R,pe.Type.INSPECT)}`:typeof R>\"u\"?`Extraneous field ${pe.pretty(t.configuration,x,pe.Type.CODE)} currently set to ${pe.pretty(t.configuration,L,pe.Type.INSPECT)}`:`Invalid field ${pe.pretty(t.configuration,x,pe.Type.CODE)}; expected ${pe.pretty(t.configuration,R,pe.Type.INSPECT)}, found ${pe.pretty(t.configuration,L,pe.Type.INSPECT)}`;h.push({text:U,fixable:!0});continue}typeof R>\"u\"?(0,Yde.default)(v,x):(0,jde.default)(v,x,R),E=!0}E&&a.set(I,v)}h.length>0&&n.set(I,h)}return{changedWorkspaces:a,remainingErrors:n}}function Wde(t,{configuration:e}){let r={children:[]};for(let[o,a]of t){let n=[];for(let A of a){let p=A.text.split(/\\n/);A.fixable&&(p[0]=`${pe.pretty(e,\"\\u2699\",\"gray\")} ${p[0]}`),n.push({value:pe.tuple(pe.Type.NO_HINT,p[0]),children:p.slice(1).map(h=>({value:pe.tuple(pe.Type.NO_HINT,h)}))})}let u={value:pe.tuple(pe.Type.LOCATOR,o.anchoredLocator),children:He.sortMap(n,A=>A.value[1])};r.children.push(u)}return r.children=He.sortMap(r.children,o=>o.value[1]),r}var qde,jde,Gde,Yde,QE,jgt,Ggt,Ygt,l2=Et(()=>{Ge();qde=Ze(e2()),jde=Ze(D8()),Gde=Ze(Hde()),Yde=Ze(S8()),QE=class{constructor(e){this.indexedFields=e;this.items=[];this.indexes={};this.clear()}clear(){this.items=[];for(let e of this.indexedFields)this.indexes[e]=new Map}insert(e){this.items.push(e);for(let r of this.indexedFields){let o=Object.hasOwn(e,r)?e[r]:void 0;if(typeof o>\"u\")continue;He.getArrayWithDefault(this.indexes[r],o).push(e)}return e}find(e){if(typeof e>\"u\")return this.items;let r=Object.entries(e);if(r.length===0)return this.items;let o=[],a;for(let[u,A]of r){let p=u,h=Object.hasOwn(this.indexes,p)?this.indexes[p]:void 0;if(typeof h>\"u\"){o.push([p,A]);continue}let E=new Set(h.get(A)??[]);if(E.size===0)return[];if(typeof a>\"u\")a=E;else for(let I of a)E.has(I)||a.delete(I);if(a.size===0)break}let n=[...a??[]];return o.length>0&&(n=n.filter(u=>{for(let[A,p]of o)if(!(typeof p<\"u\"?Object.hasOwn(u,A)&&u[A]===p:Object.hasOwn(u,A)===!1))return!1;return!0})),n}},jgt=/^[0-9]+$/,Ggt=/^[a-zA-Z0-9_]+$/,Ygt=new Set([\"scripts\",...Ut.allDependencies])});var Kde=_((s7t,$8)=>{var Vgt;(function(t){var e=function(){return{\"append/2\":[new t.type.Rule(new t.type.Term(\"append\",[new t.type.Var(\"X\"),new t.type.Var(\"L\")]),new t.type.Term(\"foldl\",[new t.type.Term(\"append\",[]),new t.type.Var(\"X\"),new t.type.Term(\"[]\",[]),new t.type.Var(\"L\")]))],\"append/3\":[new t.type.Rule(new t.type.Term(\"append\",[new t.type.Term(\"[]\",[]),new t.type.Var(\"X\"),new t.type.Var(\"X\")]),null),new t.type.Rule(new t.type.Term(\"append\",[new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Var(\"T\")]),new t.type.Var(\"X\"),new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Var(\"S\")])]),new t.type.Term(\"append\",[new t.type.Var(\"T\"),new t.type.Var(\"X\"),new t.type.Var(\"S\")]))],\"member/2\":[new t.type.Rule(new t.type.Term(\"member\",[new t.type.Var(\"X\"),new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Var(\"_\")])]),null),new t.type.Rule(new t.type.Term(\"member\",[new t.type.Var(\"X\"),new t.type.Term(\".\",[new t.type.Var(\"_\"),new t.type.Var(\"Xs\")])]),new t.type.Term(\"member\",[new t.type.Var(\"X\"),new t.type.Var(\"Xs\")]))],\"permutation/2\":[new t.type.Rule(new t.type.Term(\"permutation\",[new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[])]),null),new t.type.Rule(new t.type.Term(\"permutation\",[new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Var(\"T\")]),new t.type.Var(\"S\")]),new t.type.Term(\",\",[new t.type.Term(\"permutation\",[new t.type.Var(\"T\"),new t.type.Var(\"P\")]),new t.type.Term(\",\",[new t.type.Term(\"append\",[new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"P\")]),new t.type.Term(\"append\",[new t.type.Var(\"X\"),new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Var(\"Y\")]),new t.type.Var(\"S\")])])]))],\"maplist/2\":[new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"_\"),new t.type.Term(\"[]\",[])]),null),new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Var(\"Xs\")])]),new t.type.Term(\",\",[new t.type.Term(\"call\",[new t.type.Var(\"P\"),new t.type.Var(\"X\")]),new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Var(\"Xs\")])]))],\"maplist/3\":[new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"_\"),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[])]),null),new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Term(\".\",[new t.type.Var(\"A\"),new t.type.Var(\"As\")]),new t.type.Term(\".\",[new t.type.Var(\"B\"),new t.type.Var(\"Bs\")])]),new t.type.Term(\",\",[new t.type.Term(\"call\",[new t.type.Var(\"P\"),new t.type.Var(\"A\"),new t.type.Var(\"B\")]),new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Var(\"As\"),new t.type.Var(\"Bs\")])]))],\"maplist/4\":[new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"_\"),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[])]),null),new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Term(\".\",[new t.type.Var(\"A\"),new t.type.Var(\"As\")]),new t.type.Term(\".\",[new t.type.Var(\"B\"),new t.type.Var(\"Bs\")]),new t.type.Term(\".\",[new t.type.Var(\"C\"),new t.type.Var(\"Cs\")])]),new t.type.Term(\",\",[new t.type.Term(\"call\",[new t.type.Var(\"P\"),new t.type.Var(\"A\"),new t.type.Var(\"B\"),new t.type.Var(\"C\")]),new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Var(\"As\"),new t.type.Var(\"Bs\"),new t.type.Var(\"Cs\")])]))],\"maplist/5\":[new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"_\"),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[])]),null),new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Term(\".\",[new t.type.Var(\"A\"),new t.type.Var(\"As\")]),new t.type.Term(\".\",[new t.type.Var(\"B\"),new t.type.Var(\"Bs\")]),new t.type.Term(\".\",[new t.type.Var(\"C\"),new t.type.Var(\"Cs\")]),new t.type.Term(\".\",[new t.type.Var(\"D\"),new t.type.Var(\"Ds\")])]),new t.type.Term(\",\",[new t.type.Term(\"call\",[new t.type.Var(\"P\"),new t.type.Var(\"A\"),new t.type.Var(\"B\"),new t.type.Var(\"C\"),new t.type.Var(\"D\")]),new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Var(\"As\"),new t.type.Var(\"Bs\"),new t.type.Var(\"Cs\"),new t.type.Var(\"Ds\")])]))],\"maplist/6\":[new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"_\"),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[])]),null),new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Term(\".\",[new t.type.Var(\"A\"),new t.type.Var(\"As\")]),new t.type.Term(\".\",[new t.type.Var(\"B\"),new t.type.Var(\"Bs\")]),new t.type.Term(\".\",[new t.type.Var(\"C\"),new t.type.Var(\"Cs\")]),new t.type.Term(\".\",[new t.type.Var(\"D\"),new t.type.Var(\"Ds\")]),new t.type.Term(\".\",[new t.type.Var(\"E\"),new t.type.Var(\"Es\")])]),new t.type.Term(\",\",[new t.type.Term(\"call\",[new t.type.Var(\"P\"),new t.type.Var(\"A\"),new t.type.Var(\"B\"),new t.type.Var(\"C\"),new t.type.Var(\"D\"),new t.type.Var(\"E\")]),new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Var(\"As\"),new t.type.Var(\"Bs\"),new t.type.Var(\"Cs\"),new t.type.Var(\"Ds\"),new t.type.Var(\"Es\")])]))],\"maplist/7\":[new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"_\"),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[])]),null),new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Term(\".\",[new t.type.Var(\"A\"),new t.type.Var(\"As\")]),new t.type.Term(\".\",[new t.type.Var(\"B\"),new t.type.Var(\"Bs\")]),new t.type.Term(\".\",[new t.type.Var(\"C\"),new t.type.Var(\"Cs\")]),new t.type.Term(\".\",[new t.type.Var(\"D\"),new t.type.Var(\"Ds\")]),new t.type.Term(\".\",[new t.type.Var(\"E\"),new t.type.Var(\"Es\")]),new t.type.Term(\".\",[new t.type.Var(\"F\"),new t.type.Var(\"Fs\")])]),new t.type.Term(\",\",[new t.type.Term(\"call\",[new t.type.Var(\"P\"),new t.type.Var(\"A\"),new t.type.Var(\"B\"),new t.type.Var(\"C\"),new t.type.Var(\"D\"),new t.type.Var(\"E\"),new t.type.Var(\"F\")]),new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Var(\"As\"),new t.type.Var(\"Bs\"),new t.type.Var(\"Cs\"),new t.type.Var(\"Ds\"),new t.type.Var(\"Es\"),new t.type.Var(\"Fs\")])]))],\"maplist/8\":[new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"_\"),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[])]),null),new t.type.Rule(new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Term(\".\",[new t.type.Var(\"A\"),new t.type.Var(\"As\")]),new t.type.Term(\".\",[new t.type.Var(\"B\"),new t.type.Var(\"Bs\")]),new t.type.Term(\".\",[new t.type.Var(\"C\"),new t.type.Var(\"Cs\")]),new t.type.Term(\".\",[new t.type.Var(\"D\"),new t.type.Var(\"Ds\")]),new t.type.Term(\".\",[new t.type.Var(\"E\"),new t.type.Var(\"Es\")]),new t.type.Term(\".\",[new t.type.Var(\"F\"),new t.type.Var(\"Fs\")]),new t.type.Term(\".\",[new t.type.Var(\"G\"),new t.type.Var(\"Gs\")])]),new t.type.Term(\",\",[new t.type.Term(\"call\",[new t.type.Var(\"P\"),new t.type.Var(\"A\"),new t.type.Var(\"B\"),new t.type.Var(\"C\"),new t.type.Var(\"D\"),new t.type.Var(\"E\"),new t.type.Var(\"F\"),new t.type.Var(\"G\")]),new t.type.Term(\"maplist\",[new t.type.Var(\"P\"),new t.type.Var(\"As\"),new t.type.Var(\"Bs\"),new t.type.Var(\"Cs\"),new t.type.Var(\"Ds\"),new t.type.Var(\"Es\"),new t.type.Var(\"Fs\"),new t.type.Var(\"Gs\")])]))],\"include/3\":[new t.type.Rule(new t.type.Term(\"include\",[new t.type.Var(\"_\"),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[])]),null),new t.type.Rule(new t.type.Term(\"include\",[new t.type.Var(\"P\"),new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Var(\"T\")]),new t.type.Var(\"L\")]),new t.type.Term(\",\",[new t.type.Term(\"=..\",[new t.type.Var(\"P\"),new t.type.Var(\"A\")]),new t.type.Term(\",\",[new t.type.Term(\"append\",[new t.type.Var(\"A\"),new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Term(\"[]\",[])]),new t.type.Var(\"B\")]),new t.type.Term(\",\",[new t.type.Term(\"=..\",[new t.type.Var(\"F\"),new t.type.Var(\"B\")]),new t.type.Term(\",\",[new t.type.Term(\";\",[new t.type.Term(\",\",[new t.type.Term(\"call\",[new t.type.Var(\"F\")]),new t.type.Term(\",\",[new t.type.Term(\"=\",[new t.type.Var(\"L\"),new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Var(\"S\")])]),new t.type.Term(\"!\",[])])]),new t.type.Term(\"=\",[new t.type.Var(\"L\"),new t.type.Var(\"S\")])]),new t.type.Term(\"include\",[new t.type.Var(\"P\"),new t.type.Var(\"T\"),new t.type.Var(\"S\")])])])])]))],\"exclude/3\":[new t.type.Rule(new t.type.Term(\"exclude\",[new t.type.Var(\"_\"),new t.type.Term(\"[]\",[]),new t.type.Term(\"[]\",[])]),null),new t.type.Rule(new t.type.Term(\"exclude\",[new t.type.Var(\"P\"),new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Var(\"T\")]),new t.type.Var(\"S\")]),new t.type.Term(\",\",[new t.type.Term(\"exclude\",[new t.type.Var(\"P\"),new t.type.Var(\"T\"),new t.type.Var(\"E\")]),new t.type.Term(\",\",[new t.type.Term(\"=..\",[new t.type.Var(\"P\"),new t.type.Var(\"L\")]),new t.type.Term(\",\",[new t.type.Term(\"append\",[new t.type.Var(\"L\"),new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Term(\"[]\",[])]),new t.type.Var(\"Q\")]),new t.type.Term(\",\",[new t.type.Term(\"=..\",[new t.type.Var(\"R\"),new t.type.Var(\"Q\")]),new t.type.Term(\";\",[new t.type.Term(\",\",[new t.type.Term(\"call\",[new t.type.Var(\"R\")]),new t.type.Term(\",\",[new t.type.Term(\"!\",[]),new t.type.Term(\"=\",[new t.type.Var(\"S\"),new t.type.Var(\"E\")])])]),new t.type.Term(\"=\",[new t.type.Var(\"S\"),new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Var(\"E\")])])])])])])]))],\"foldl/4\":[new t.type.Rule(new t.type.Term(\"foldl\",[new t.type.Var(\"_\"),new t.type.Term(\"[]\",[]),new t.type.Var(\"I\"),new t.type.Var(\"I\")]),null),new t.type.Rule(new t.type.Term(\"foldl\",[new t.type.Var(\"P\"),new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Var(\"T\")]),new t.type.Var(\"I\"),new t.type.Var(\"R\")]),new t.type.Term(\",\",[new t.type.Term(\"=..\",[new t.type.Var(\"P\"),new t.type.Var(\"L\")]),new t.type.Term(\",\",[new t.type.Term(\"append\",[new t.type.Var(\"L\"),new t.type.Term(\".\",[new t.type.Var(\"I\"),new t.type.Term(\".\",[new t.type.Var(\"H\"),new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Term(\"[]\",[])])])]),new t.type.Var(\"L2\")]),new t.type.Term(\",\",[new t.type.Term(\"=..\",[new t.type.Var(\"P2\"),new t.type.Var(\"L2\")]),new t.type.Term(\",\",[new t.type.Term(\"call\",[new t.type.Var(\"P2\")]),new t.type.Term(\"foldl\",[new t.type.Var(\"P\"),new t.type.Var(\"T\"),new t.type.Var(\"X\"),new t.type.Var(\"R\")])])])])]))],\"select/3\":[new t.type.Rule(new t.type.Term(\"select\",[new t.type.Var(\"E\"),new t.type.Term(\".\",[new t.type.Var(\"E\"),new t.type.Var(\"Xs\")]),new t.type.Var(\"Xs\")]),null),new t.type.Rule(new t.type.Term(\"select\",[new t.type.Var(\"E\"),new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Var(\"Xs\")]),new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Var(\"Ys\")])]),new t.type.Term(\"select\",[new t.type.Var(\"E\"),new t.type.Var(\"Xs\"),new t.type.Var(\"Ys\")]))],\"sum_list/2\":[new t.type.Rule(new t.type.Term(\"sum_list\",[new t.type.Term(\"[]\",[]),new t.type.Num(0,!1)]),null),new t.type.Rule(new t.type.Term(\"sum_list\",[new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Var(\"Xs\")]),new t.type.Var(\"S\")]),new t.type.Term(\",\",[new t.type.Term(\"sum_list\",[new t.type.Var(\"Xs\"),new t.type.Var(\"Y\")]),new t.type.Term(\"is\",[new t.type.Var(\"S\"),new t.type.Term(\"+\",[new t.type.Var(\"X\"),new t.type.Var(\"Y\")])])]))],\"max_list/2\":[new t.type.Rule(new t.type.Term(\"max_list\",[new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Term(\"[]\",[])]),new t.type.Var(\"X\")]),null),new t.type.Rule(new t.type.Term(\"max_list\",[new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Var(\"Xs\")]),new t.type.Var(\"S\")]),new t.type.Term(\",\",[new t.type.Term(\"max_list\",[new t.type.Var(\"Xs\"),new t.type.Var(\"Y\")]),new t.type.Term(\";\",[new t.type.Term(\",\",[new t.type.Term(\">=\",[new t.type.Var(\"X\"),new t.type.Var(\"Y\")]),new t.type.Term(\",\",[new t.type.Term(\"=\",[new t.type.Var(\"S\"),new t.type.Var(\"X\")]),new t.type.Term(\"!\",[])])]),new t.type.Term(\"=\",[new t.type.Var(\"S\"),new t.type.Var(\"Y\")])])]))],\"min_list/2\":[new t.type.Rule(new t.type.Term(\"min_list\",[new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Term(\"[]\",[])]),new t.type.Var(\"X\")]),null),new t.type.Rule(new t.type.Term(\"min_list\",[new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Var(\"Xs\")]),new t.type.Var(\"S\")]),new t.type.Term(\",\",[new t.type.Term(\"min_list\",[new t.type.Var(\"Xs\"),new t.type.Var(\"Y\")]),new t.type.Term(\";\",[new t.type.Term(\",\",[new t.type.Term(\"=<\",[new t.type.Var(\"X\"),new t.type.Var(\"Y\")]),new t.type.Term(\",\",[new t.type.Term(\"=\",[new t.type.Var(\"S\"),new t.type.Var(\"X\")]),new t.type.Term(\"!\",[])])]),new t.type.Term(\"=\",[new t.type.Var(\"S\"),new t.type.Var(\"Y\")])])]))],\"prod_list/2\":[new t.type.Rule(new t.type.Term(\"prod_list\",[new t.type.Term(\"[]\",[]),new t.type.Num(1,!1)]),null),new t.type.Rule(new t.type.Term(\"prod_list\",[new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Var(\"Xs\")]),new t.type.Var(\"S\")]),new t.type.Term(\",\",[new t.type.Term(\"prod_list\",[new t.type.Var(\"Xs\"),new t.type.Var(\"Y\")]),new t.type.Term(\"is\",[new t.type.Var(\"S\"),new t.type.Term(\"*\",[new t.type.Var(\"X\"),new t.type.Var(\"Y\")])])]))],\"last/2\":[new t.type.Rule(new t.type.Term(\"last\",[new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Term(\"[]\",[])]),new t.type.Var(\"X\")]),null),new t.type.Rule(new t.type.Term(\"last\",[new t.type.Term(\".\",[new t.type.Var(\"_\"),new t.type.Var(\"Xs\")]),new t.type.Var(\"X\")]),new t.type.Term(\"last\",[new t.type.Var(\"Xs\"),new t.type.Var(\"X\")]))],\"prefix/2\":[new t.type.Rule(new t.type.Term(\"prefix\",[new t.type.Var(\"Part\"),new t.type.Var(\"Whole\")]),new t.type.Term(\"append\",[new t.type.Var(\"Part\"),new t.type.Var(\"_\"),new t.type.Var(\"Whole\")]))],\"nth0/3\":[new t.type.Rule(new t.type.Term(\"nth0\",[new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\")]),new t.type.Term(\";\",[new t.type.Term(\"->\",[new t.type.Term(\"var\",[new t.type.Var(\"X\")]),new t.type.Term(\"nth\",[new t.type.Num(0,!1),new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\"),new t.type.Var(\"_\")])]),new t.type.Term(\",\",[new t.type.Term(\">=\",[new t.type.Var(\"X\"),new t.type.Num(0,!1)]),new t.type.Term(\",\",[new t.type.Term(\"nth\",[new t.type.Num(0,!1),new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\"),new t.type.Var(\"_\")]),new t.type.Term(\"!\",[])])])]))],\"nth1/3\":[new t.type.Rule(new t.type.Term(\"nth1\",[new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\")]),new t.type.Term(\";\",[new t.type.Term(\"->\",[new t.type.Term(\"var\",[new t.type.Var(\"X\")]),new t.type.Term(\"nth\",[new t.type.Num(1,!1),new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\"),new t.type.Var(\"_\")])]),new t.type.Term(\",\",[new t.type.Term(\">\",[new t.type.Var(\"X\"),new t.type.Num(0,!1)]),new t.type.Term(\",\",[new t.type.Term(\"nth\",[new t.type.Num(1,!1),new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\"),new t.type.Var(\"_\")]),new t.type.Term(\"!\",[])])])]))],\"nth0/4\":[new t.type.Rule(new t.type.Term(\"nth0\",[new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\"),new t.type.Var(\"W\")]),new t.type.Term(\";\",[new t.type.Term(\"->\",[new t.type.Term(\"var\",[new t.type.Var(\"X\")]),new t.type.Term(\"nth\",[new t.type.Num(0,!1),new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\"),new t.type.Var(\"W\")])]),new t.type.Term(\",\",[new t.type.Term(\">=\",[new t.type.Var(\"X\"),new t.type.Num(0,!1)]),new t.type.Term(\",\",[new t.type.Term(\"nth\",[new t.type.Num(0,!1),new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\"),new t.type.Var(\"W\")]),new t.type.Term(\"!\",[])])])]))],\"nth1/4\":[new t.type.Rule(new t.type.Term(\"nth1\",[new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\"),new t.type.Var(\"W\")]),new t.type.Term(\";\",[new t.type.Term(\"->\",[new t.type.Term(\"var\",[new t.type.Var(\"X\")]),new t.type.Term(\"nth\",[new t.type.Num(1,!1),new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\"),new t.type.Var(\"W\")])]),new t.type.Term(\",\",[new t.type.Term(\">\",[new t.type.Var(\"X\"),new t.type.Num(0,!1)]),new t.type.Term(\",\",[new t.type.Term(\"nth\",[new t.type.Num(1,!1),new t.type.Var(\"X\"),new t.type.Var(\"Y\"),new t.type.Var(\"Z\"),new t.type.Var(\"W\")]),new t.type.Term(\"!\",[])])])]))],\"nth/5\":[new t.type.Rule(new t.type.Term(\"nth\",[new t.type.Var(\"N\"),new t.type.Var(\"N\"),new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Var(\"Xs\")]),new t.type.Var(\"X\"),new t.type.Var(\"Xs\")]),null),new t.type.Rule(new t.type.Term(\"nth\",[new t.type.Var(\"N\"),new t.type.Var(\"O\"),new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Var(\"Xs\")]),new t.type.Var(\"Y\"),new t.type.Term(\".\",[new t.type.Var(\"X\"),new t.type.Var(\"Ys\")])]),new t.type.Term(\",\",[new t.type.Term(\"is\",[new t.type.Var(\"M\"),new t.type.Term(\"+\",[new t.type.Var(\"N\"),new t.type.Num(1,!1)])]),new t.type.Term(\"nth\",[new t.type.Var(\"M\"),new t.type.Var(\"O\"),new t.type.Var(\"Xs\"),new t.type.Var(\"Y\"),new t.type.Var(\"Ys\")])]))],\"length/2\":function(o,a,n){var u=n.args[0],A=n.args[1];if(!t.type.is_variable(A)&&!t.type.is_integer(A))o.throw_error(t.error.type(\"integer\",A,n.indicator));else if(t.type.is_integer(A)&&A.value<0)o.throw_error(t.error.domain(\"not_less_than_zero\",A,n.indicator));else{var p=new t.type.Term(\"length\",[u,new t.type.Num(0,!1),A]);t.type.is_integer(A)&&(p=new t.type.Term(\",\",[p,new t.type.Term(\"!\",[])])),o.prepend([new t.type.State(a.goal.replace(p),a.substitution,a)])}},\"length/3\":[new t.type.Rule(new t.type.Term(\"length\",[new t.type.Term(\"[]\",[]),new t.type.Var(\"N\"),new t.type.Var(\"N\")]),null),new t.type.Rule(new t.type.Term(\"length\",[new t.type.Term(\".\",[new t.type.Var(\"_\"),new t.type.Var(\"X\")]),new t.type.Var(\"A\"),new t.type.Var(\"N\")]),new t.type.Term(\",\",[new t.type.Term(\"succ\",[new t.type.Var(\"A\"),new t.type.Var(\"B\")]),new t.type.Term(\"length\",[new t.type.Var(\"X\"),new t.type.Var(\"B\"),new t.type.Var(\"N\")])]))],\"replicate/3\":function(o,a,n){var u=n.args[0],A=n.args[1],p=n.args[2];if(t.type.is_variable(A))o.throw_error(t.error.instantiation(n.indicator));else if(!t.type.is_integer(A))o.throw_error(t.error.type(\"integer\",A,n.indicator));else if(A.value<0)o.throw_error(t.error.domain(\"not_less_than_zero\",A,n.indicator));else if(!t.type.is_variable(p)&&!t.type.is_list(p))o.throw_error(t.error.type(\"list\",p,n.indicator));else{for(var h=new t.type.Term(\"[]\"),E=0;E<A.value;E++)h=new t.type.Term(\".\",[u,h]);o.prepend([new t.type.State(a.goal.replace(new t.type.Term(\"=\",[h,p])),a.substitution,a)])}},\"sort/2\":function(o,a,n){var u=n.args[0],A=n.args[1];if(t.type.is_variable(u))o.throw_error(t.error.instantiation(n.indicator));else if(!t.type.is_variable(A)&&!t.type.is_fully_list(A))o.throw_error(t.error.type(\"list\",A,n.indicator));else{for(var p=[],h=u;h.indicator===\"./2\";)p.push(h.args[0]),h=h.args[1];if(t.type.is_variable(h))o.throw_error(t.error.instantiation(n.indicator));else if(!t.type.is_empty_list(h))o.throw_error(t.error.type(\"list\",u,n.indicator));else{for(var E=p.sort(t.compare),I=E.length-1;I>0;I--)E[I].equals(E[I-1])&&E.splice(I,1);for(var v=new t.type.Term(\"[]\"),I=E.length-1;I>=0;I--)v=new t.type.Term(\".\",[E[I],v]);o.prepend([new t.type.State(a.goal.replace(new t.type.Term(\"=\",[v,A])),a.substitution,a)])}}},\"msort/2\":function(o,a,n){var u=n.args[0],A=n.args[1];if(t.type.is_variable(u))o.throw_error(t.error.instantiation(n.indicator));else if(!t.type.is_variable(A)&&!t.type.is_fully_list(A))o.throw_error(t.error.type(\"list\",A,n.indicator));else{for(var p=[],h=u;h.indicator===\"./2\";)p.push(h.args[0]),h=h.args[1];if(t.type.is_variable(h))o.throw_error(t.error.instantiation(n.indicator));else if(!t.type.is_empty_list(h))o.throw_error(t.error.type(\"list\",u,n.indicator));else{for(var E=p.sort(t.compare),I=new t.type.Term(\"[]\"),v=E.length-1;v>=0;v--)I=new t.type.Term(\".\",[E[v],I]);o.prepend([new t.type.State(a.goal.replace(new t.type.Term(\"=\",[I,A])),a.substitution,a)])}}},\"keysort/2\":function(o,a,n){var u=n.args[0],A=n.args[1];if(t.type.is_variable(u))o.throw_error(t.error.instantiation(n.indicator));else if(!t.type.is_variable(A)&&!t.type.is_fully_list(A))o.throw_error(t.error.type(\"list\",A,n.indicator));else{for(var p=[],h,E=u;E.indicator===\"./2\";){if(h=E.args[0],t.type.is_variable(h)){o.throw_error(t.error.instantiation(n.indicator));return}else if(!t.type.is_term(h)||h.indicator!==\"-/2\"){o.throw_error(t.error.type(\"pair\",h,n.indicator));return}h.args[0].pair=h.args[1],p.push(h.args[0]),E=E.args[1]}if(t.type.is_variable(E))o.throw_error(t.error.instantiation(n.indicator));else if(!t.type.is_empty_list(E))o.throw_error(t.error.type(\"list\",u,n.indicator));else{for(var I=p.sort(t.compare),v=new t.type.Term(\"[]\"),x=I.length-1;x>=0;x--)v=new t.type.Term(\".\",[new t.type.Term(\"-\",[I[x],I[x].pair]),v]),delete I[x].pair;o.prepend([new t.type.State(a.goal.replace(new t.type.Term(\"=\",[v,A])),a.substitution,a)])}}},\"take/3\":function(o,a,n){var u=n.args[0],A=n.args[1],p=n.args[2];if(t.type.is_variable(A)||t.type.is_variable(u))o.throw_error(t.error.instantiation(n.indicator));else if(!t.type.is_list(A))o.throw_error(t.error.type(\"list\",A,n.indicator));else if(!t.type.is_integer(u))o.throw_error(t.error.type(\"integer\",u,n.indicator));else if(!t.type.is_variable(p)&&!t.type.is_list(p))o.throw_error(t.error.type(\"list\",p,n.indicator));else{for(var h=u.value,E=[],I=A;h>0&&I.indicator===\"./2\";)E.push(I.args[0]),I=I.args[1],h--;if(h===0){for(var v=new t.type.Term(\"[]\"),h=E.length-1;h>=0;h--)v=new t.type.Term(\".\",[E[h],v]);o.prepend([new t.type.State(a.goal.replace(new t.type.Term(\"=\",[v,p])),a.substitution,a)])}}},\"drop/3\":function(o,a,n){var u=n.args[0],A=n.args[1],p=n.args[2];if(t.type.is_variable(A)||t.type.is_variable(u))o.throw_error(t.error.instantiation(n.indicator));else if(!t.type.is_list(A))o.throw_error(t.error.type(\"list\",A,n.indicator));else if(!t.type.is_integer(u))o.throw_error(t.error.type(\"integer\",u,n.indicator));else if(!t.type.is_variable(p)&&!t.type.is_list(p))o.throw_error(t.error.type(\"list\",p,n.indicator));else{for(var h=u.value,E=[],I=A;h>0&&I.indicator===\"./2\";)E.push(I.args[0]),I=I.args[1],h--;h===0&&o.prepend([new t.type.State(a.goal.replace(new t.type.Term(\"=\",[I,p])),a.substitution,a)])}},\"reverse/2\":function(o,a,n){var u=n.args[0],A=n.args[1],p=t.type.is_instantiated_list(u),h=t.type.is_instantiated_list(A);if(t.type.is_variable(u)&&t.type.is_variable(A))o.throw_error(t.error.instantiation(n.indicator));else if(!t.type.is_variable(u)&&!t.type.is_fully_list(u))o.throw_error(t.error.type(\"list\",u,n.indicator));else if(!t.type.is_variable(A)&&!t.type.is_fully_list(A))o.throw_error(t.error.type(\"list\",A,n.indicator));else if(!p&&!h)o.throw_error(t.error.instantiation(n.indicator));else{for(var E=p?u:A,I=new t.type.Term(\"[]\",[]);E.indicator===\"./2\";)I=new t.type.Term(\".\",[E.args[0],I]),E=E.args[1];o.prepend([new t.type.State(a.goal.replace(new t.type.Term(\"=\",[I,p?A:u])),a.substitution,a)])}},\"list_to_set/2\":function(o,a,n){var u=n.args[0],A=n.args[1];if(t.type.is_variable(u))o.throw_error(t.error.instantiation(n.indicator));else{for(var p=u,h=[];p.indicator===\"./2\";)h.push(p.args[0]),p=p.args[1];if(t.type.is_variable(p))o.throw_error(t.error.instantiation(n.indicator));else if(!t.type.is_term(p)||p.indicator!==\"[]/0\")o.throw_error(t.error.type(\"list\",u,n.indicator));else{for(var E=[],I=new t.type.Term(\"[]\",[]),v,x=0;x<h.length;x++){v=!1;for(var C=0;C<E.length&&!v;C++)v=t.compare(h[x],E[C])===0;v||E.push(h[x])}for(x=E.length-1;x>=0;x--)I=new t.type.Term(\".\",[E[x],I]);o.prepend([new t.type.State(a.goal.replace(new t.type.Term(\"=\",[A,I])),a.substitution,a)])}}}}},r=[\"append/2\",\"append/3\",\"member/2\",\"permutation/2\",\"maplist/2\",\"maplist/3\",\"maplist/4\",\"maplist/5\",\"maplist/6\",\"maplist/7\",\"maplist/8\",\"include/3\",\"exclude/3\",\"foldl/4\",\"sum_list/2\",\"max_list/2\",\"min_list/2\",\"prod_list/2\",\"last/2\",\"prefix/2\",\"nth0/3\",\"nth1/3\",\"nth0/4\",\"nth1/4\",\"length/2\",\"replicate/3\",\"select/3\",\"sort/2\",\"msort/2\",\"keysort/2\",\"take/3\",\"drop/3\",\"reverse/2\",\"list_to_set/2\"];typeof $8<\"u\"?$8.exports=function(o){t=o,new t.type.Module(\"lists\",e(),r)}:new t.type.Module(\"lists\",e(),r)})(Vgt)});var lme=_(Wr=>{\"use strict\";var jg=process.platform===\"win32\",eH=\"aes-256-cbc\",zgt=\"sha256\",Jde=\"The current environment doesn't support interactive reading from TTY.\",Yn=ve(\"fs\"),Vde=process.binding(\"tty_wrap\").TTY,rH=ve(\"child_process\"),kh=ve(\"path\"),nH={prompt:\"> \",hideEchoBack:!1,mask:\"*\",limit:[],limitMessage:\"Input another, please.$<( [)limit(])>\",defaultInput:\"\",trueValue:[],falseValue:[],caseSensitive:!1,keepWhitespace:!1,encoding:\"utf8\",bufferSize:1024,print:void 0,history:!0,cd:!1,phContent:void 0,preCheck:void 0},Wf=\"none\",$c,RE,zde=!1,xh,ok,tH,Jgt=0,lH=\"\",qg=[],ak,Xde=!1,iH=!1,c2=!1;function Zde(t){function e(r){return r.replace(/[^\\w\\u0080-\\uFFFF]/g,function(o){return\"#\"+o.charCodeAt(0)+\";\"})}return ok.concat(function(r){var o=[];return Object.keys(r).forEach(function(a){r[a]===\"boolean\"?t[a]&&o.push(\"--\"+a):r[a]===\"string\"&&t[a]&&o.push(\"--\"+a,e(t[a]))}),o}({display:\"string\",displayOnly:\"boolean\",keyIn:\"boolean\",hideEchoBack:\"boolean\",mask:\"string\",limit:\"string\",caseSensitive:\"boolean\"}))}function Xgt(t,e){function r(U){var z,te=\"\",ae;for(tH=tH||ve(\"os\").tmpdir();;){z=kh.join(tH,U+te);try{ae=Yn.openSync(z,\"wx\")}catch(le){if(le.code===\"EEXIST\"){te++;continue}else throw le}Yn.closeSync(ae);break}return z}var o,a,n,u={},A,p,h=r(\"readline-sync.stdout\"),E=r(\"readline-sync.stderr\"),I=r(\"readline-sync.exit\"),v=r(\"readline-sync.done\"),x=ve(\"crypto\"),C,R,L;C=x.createHash(zgt),C.update(\"\"+process.pid+Jgt+++Math.random()),L=C.digest(\"hex\"),R=x.createDecipher(eH,L),o=Zde(t),jg?(a=process.env.ComSpec||\"cmd.exe\",process.env.Q='\"',n=[\"/V:ON\",\"/S\",\"/C\",\"(%Q%\"+a+\"%Q% /V:ON /S /C %Q%%Q%\"+xh+\"%Q%\"+o.map(function(U){return\" %Q%\"+U+\"%Q%\"}).join(\"\")+\" & (echo !ERRORLEVEL!)>%Q%\"+I+\"%Q%%Q%) 2>%Q%\"+E+\"%Q% |%Q%\"+process.execPath+\"%Q% %Q%\"+__dirname+\"\\\\encrypt.js%Q% %Q%\"+eH+\"%Q% %Q%\"+L+\"%Q% >%Q%\"+h+\"%Q% & (echo 1)>%Q%\"+v+\"%Q%\"]):(a=\"/bin/sh\",n=[\"-c\",'(\"'+xh+'\"'+o.map(function(U){return\" '\"+U.replace(/'/g,\"'\\\\''\")+\"'\"}).join(\"\")+'; echo $?>\"'+I+'\") 2>\"'+E+'\" |\"'+process.execPath+'\" \"'+__dirname+'/encrypt.js\" \"'+eH+'\" \"'+L+'\" >\"'+h+'\"; echo 1 >\"'+v+'\"']),c2&&c2(\"_execFileSync\",o);try{rH.spawn(a,n,e)}catch(U){u.error=new Error(U.message),u.error.method=\"_execFileSync - spawn\",u.error.program=a,u.error.args=n}for(;Yn.readFileSync(v,{encoding:t.encoding}).trim()!==\"1\";);return(A=Yn.readFileSync(I,{encoding:t.encoding}).trim())===\"0\"?u.input=R.update(Yn.readFileSync(h,{encoding:\"binary\"}),\"hex\",t.encoding)+R.final(t.encoding):(p=Yn.readFileSync(E,{encoding:t.encoding}).trim(),u.error=new Error(Jde+(p?`\n`+p:\"\")),u.error.method=\"_execFileSync\",u.error.program=a,u.error.args=n,u.error.extMessage=p,u.error.exitCode=+A),Yn.unlinkSync(h),Yn.unlinkSync(E),Yn.unlinkSync(I),Yn.unlinkSync(v),u}function Zgt(t){var e,r={},o,a={env:process.env,encoding:t.encoding};if(xh||(jg?process.env.PSModulePath?(xh=\"powershell.exe\",ok=[\"-ExecutionPolicy\",\"Bypass\",\"-File\",__dirname+\"\\\\read.ps1\"]):(xh=\"cscript.exe\",ok=[\"//nologo\",__dirname+\"\\\\read.cs.js\"]):(xh=\"/bin/sh\",ok=[__dirname+\"/read.sh\"])),jg&&!process.env.PSModulePath&&(a.stdio=[process.stdin]),rH.execFileSync){e=Zde(t),c2&&c2(\"execFileSync\",e);try{r.input=rH.execFileSync(xh,e,a)}catch(n){o=n.stderr?(n.stderr+\"\").trim():\"\",r.error=new Error(Jde+(o?`\n`+o:\"\")),r.error.method=\"execFileSync\",r.error.program=xh,r.error.args=e,r.error.extMessage=o,r.error.exitCode=n.status,r.error.code=n.code,r.error.signal=n.signal}}else r=Xgt(t,a);return r.error||(r.input=r.input.replace(/^\\s*'|'\\s*$/g,\"\"),t.display=\"\"),r}function sH(t){var e=\"\",r=t.display,o=!t.display&&t.keyIn&&t.hideEchoBack&&!t.mask;function a(){var n=Zgt(t);if(n.error)throw n.error;return n.input}return iH&&iH(t),function(){var n,u,A;function p(){return n||(n=process.binding(\"fs\"),u=process.binding(\"constants\")),n}if(typeof Wf==\"string\")if(Wf=null,jg){if(A=function(h){var E=h.replace(/^\\D+/,\"\").split(\".\"),I=0;return(E[0]=+E[0])&&(I+=E[0]*1e4),(E[1]=+E[1])&&(I+=E[1]*100),(E[2]=+E[2])&&(I+=E[2]),I}(process.version),!(A>=20302&&A<40204||A>=5e4&&A<50100||A>=50600&&A<60200)&&process.stdin.isTTY)process.stdin.pause(),Wf=process.stdin.fd,RE=process.stdin._handle;else try{Wf=p().open(\"CONIN$\",u.O_RDWR,parseInt(\"0666\",8)),RE=new Vde(Wf,!0)}catch{}if(process.stdout.isTTY)$c=process.stdout.fd;else{try{$c=Yn.openSync(\"\\\\\\\\.\\\\CON\",\"w\")}catch{}if(typeof $c!=\"number\")try{$c=p().open(\"CONOUT$\",u.O_RDWR,parseInt(\"0666\",8))}catch{}}}else{if(process.stdin.isTTY){process.stdin.pause();try{Wf=Yn.openSync(\"/dev/tty\",\"r\"),RE=process.stdin._handle}catch{}}else try{Wf=Yn.openSync(\"/dev/tty\",\"r\"),RE=new Vde(Wf,!1)}catch{}if(process.stdout.isTTY)$c=process.stdout.fd;else try{$c=Yn.openSync(\"/dev/tty\",\"w\")}catch{}}}(),function(){var n,u,A=!t.hideEchoBack&&!t.keyIn,p,h,E,I,v;ak=\"\";function x(C){return C===zde?!0:RE.setRawMode(C)!==0?!1:(zde=C,!0)}if(Xde||!RE||typeof $c!=\"number\"&&(t.display||!A)){e=a();return}if(t.display&&(Yn.writeSync($c,t.display),t.display=\"\"),!t.displayOnly){if(!x(!A)){e=a();return}for(h=t.keyIn?1:t.bufferSize,p=Buffer.allocUnsafe&&Buffer.alloc?Buffer.alloc(h):new Buffer(h),t.keyIn&&t.limit&&(u=new RegExp(\"[^\"+t.limit+\"]\",\"g\"+(t.caseSensitive?\"\":\"i\")));;){E=0;try{E=Yn.readSync(Wf,p,0,h)}catch(C){if(C.code!==\"EOF\"){x(!1),e+=a();return}}if(E>0?(I=p.toString(t.encoding,0,E),ak+=I):(I=`\n`,ak+=\"\\0\"),I&&typeof(v=(I.match(/^(.*?)[\\r\\n]/)||[])[1])==\"string\"&&(I=v,n=!0),I&&(I=I.replace(/[\\x00-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]/g,\"\")),I&&u&&(I=I.replace(u,\"\")),I&&(A||(t.hideEchoBack?t.mask&&Yn.writeSync($c,new Array(I.length+1).join(t.mask)):Yn.writeSync($c,I)),e+=I),!t.keyIn&&n||t.keyIn&&e.length>=h)break}!A&&!o&&Yn.writeSync($c,`\n`),x(!1)}}(),t.print&&!o&&t.print(r+(t.displayOnly?\"\":(t.hideEchoBack?new Array(e.length+1).join(t.mask):e)+`\n`),t.encoding),t.displayOnly?\"\":lH=t.keepWhitespace||t.keyIn?e:e.trim()}function $gt(t,e){var r=[];function o(a){a!=null&&(Array.isArray(a)?a.forEach(o):(!e||e(a))&&r.push(a))}return o(t),r}function cH(t){return t.replace(/[\\x00-\\x7f]/g,function(e){return\"\\\\x\"+(\"00\"+e.charCodeAt().toString(16)).substr(-2)})}function Ns(){var t=Array.prototype.slice.call(arguments),e,r;return t.length&&typeof t[0]==\"boolean\"&&(r=t.shift(),r&&(e=Object.keys(nH),t.unshift(nH))),t.reduce(function(o,a){return a==null||(a.hasOwnProperty(\"noEchoBack\")&&!a.hasOwnProperty(\"hideEchoBack\")&&(a.hideEchoBack=a.noEchoBack,delete a.noEchoBack),a.hasOwnProperty(\"noTrim\")&&!a.hasOwnProperty(\"keepWhitespace\")&&(a.keepWhitespace=a.noTrim,delete a.noTrim),r||(e=Object.keys(a)),e.forEach(function(n){var u;if(a.hasOwnProperty(n))switch(u=a[n],n){case\"mask\":case\"limitMessage\":case\"defaultInput\":case\"encoding\":u=u!=null?u+\"\":\"\",u&&n!==\"limitMessage\"&&(u=u.replace(/[\\r\\n]/g,\"\")),o[n]=u;break;case\"bufferSize\":!isNaN(u=parseInt(u,10))&&typeof u==\"number\"&&(o[n]=u);break;case\"displayOnly\":case\"keyIn\":case\"hideEchoBack\":case\"caseSensitive\":case\"keepWhitespace\":case\"history\":case\"cd\":o[n]=!!u;break;case\"limit\":case\"trueValue\":case\"falseValue\":o[n]=$gt(u,function(A){var p=typeof A;return p===\"string\"||p===\"number\"||p===\"function\"||A instanceof RegExp}).map(function(A){return typeof A==\"string\"?A.replace(/[\\r\\n]/g,\"\"):A});break;case\"print\":case\"phContent\":case\"preCheck\":o[n]=typeof u==\"function\"?u:void 0;break;case\"prompt\":case\"display\":o[n]=u??\"\";break}})),o},{})}function oH(t,e,r){return e.some(function(o){var a=typeof o;return a===\"string\"?r?t===o:t.toLowerCase()===o.toLowerCase():a===\"number\"?parseFloat(t)===o:a===\"function\"?o(t):o instanceof RegExp?o.test(t):!1})}function uH(t,e){var r=kh.normalize(jg?(process.env.HOMEDRIVE||\"\")+(process.env.HOMEPATH||\"\"):process.env.HOME||\"\").replace(/[\\/\\\\]+$/,\"\");return t=kh.normalize(t),e?t.replace(/^~(?=\\/|\\\\|$)/,r):t.replace(new RegExp(\"^\"+cH(r)+\"(?=\\\\/|\\\\\\\\|$)\",jg?\"i\":\"\"),\"~\")}function TE(t,e){var r=\"(?:\\\\(([\\\\s\\\\S]*?)\\\\))?(\\\\w+|.-.)(?:\\\\(([\\\\s\\\\S]*?)\\\\))?\",o=new RegExp(\"(\\\\$)?(\\\\$<\"+r+\">)\",\"g\"),a=new RegExp(\"(\\\\$)?(\\\\$\\\\{\"+r+\"\\\\})\",\"g\");function n(u,A,p,h,E,I){var v;return A||typeof(v=e(E))!=\"string\"?p:v?(h||\"\")+v+(I||\"\"):\"\"}return t.replace(o,n).replace(a,n)}function $de(t,e,r){var o,a=[],n=-1,u=0,A=\"\",p;function h(E,I){return I.length>3?(E.push(I[0]+\"...\"+I[I.length-1]),p=!0):I.length&&(E=E.concat(I)),E}return o=t.reduce(function(E,I){return E.concat((I+\"\").split(\"\"))},[]).reduce(function(E,I){var v,x;return e||(I=I.toLowerCase()),v=/^\\d$/.test(I)?1:/^[A-Z]$/.test(I)?2:/^[a-z]$/.test(I)?3:0,r&&v===0?A+=I:(x=I.charCodeAt(0),v&&v===n&&x===u+1?a.push(I):(E=h(E,a),a=[I],n=v),u=x),E},[]),o=h(o,a),A&&(o.push(A),p=!0),{values:o,suppressed:p}}function eme(t,e){return t.join(t.length>2?\", \":e?\" / \":\"/\")}function tme(t,e){var r,o,a={},n;if(e.phContent&&(r=e.phContent(t,e)),typeof r!=\"string\")switch(t){case\"hideEchoBack\":case\"mask\":case\"defaultInput\":case\"caseSensitive\":case\"keepWhitespace\":case\"encoding\":case\"bufferSize\":case\"history\":case\"cd\":r=e.hasOwnProperty(t)?typeof e[t]==\"boolean\"?e[t]?\"on\":\"off\":e[t]+\"\":\"\";break;case\"limit\":case\"trueValue\":case\"falseValue\":o=e[e.hasOwnProperty(t+\"Src\")?t+\"Src\":t],e.keyIn?(a=$de(o,e.caseSensitive),o=a.values):o=o.filter(function(u){var A=typeof u;return A===\"string\"||A===\"number\"}),r=eme(o,a.suppressed);break;case\"limitCount\":case\"limitCountNotZero\":r=e[e.hasOwnProperty(\"limitSrc\")?\"limitSrc\":\"limit\"].length,r=r||t!==\"limitCountNotZero\"?r+\"\":\"\";break;case\"lastInput\":r=lH;break;case\"cwd\":case\"CWD\":case\"cwdHome\":r=process.cwd(),t===\"CWD\"?r=kh.basename(r):t===\"cwdHome\"&&(r=uH(r));break;case\"date\":case\"time\":case\"localeDate\":case\"localeTime\":r=new Date()[\"to\"+t.replace(/^./,function(u){return u.toUpperCase()})+\"String\"]();break;default:typeof(n=(t.match(/^history_m(\\d+)$/)||[])[1])==\"string\"&&(r=qg[qg.length-n]||\"\")}return r}function rme(t){var e=/^(.)-(.)$/.exec(t),r=\"\",o,a,n,u;if(!e)return null;for(o=e[1].charCodeAt(0),a=e[2].charCodeAt(0),u=o<a?1:-1,n=o;n!==a+u;n+=u)r+=String.fromCharCode(n);return r}function aH(t){var e=new RegExp(/(\\s*)(?:(\"|')(.*?)(?:\\2|$)|(\\S+))/g),r,o=\"\",a=[],n;for(t=t.trim();r=e.exec(t);)n=r[3]||r[4]||\"\",r[1]&&(a.push(o),o=\"\"),o+=n;return o&&a.push(o),a}function nme(t,e){return e.trueValue.length&&oH(t,e.trueValue,e.caseSensitive)?!0:e.falseValue.length&&oH(t,e.falseValue,e.caseSensitive)?!1:t}function ime(t){var e,r,o,a,n,u,A;function p(E){return tme(E,t)}function h(E){t.display+=(/[^\\r\\n]$/.test(t.display)?`\n`:\"\")+E}for(t.limitSrc=t.limit,t.displaySrc=t.display,t.limit=\"\",t.display=TE(t.display+\"\",p);;){if(e=sH(t),r=!1,o=\"\",t.defaultInput&&!e&&(e=t.defaultInput),t.history&&((a=/^\\s*\\!(?:\\!|-1)(:p)?\\s*$/.exec(e))?(n=qg[0]||\"\",a[1]?r=!0:e=n,h(n+`\n`),r||(t.displayOnly=!0,sH(t),t.displayOnly=!1)):e&&e!==qg[qg.length-1]&&(qg=[e])),!r&&t.cd&&e)switch(u=aH(e),u[0].toLowerCase()){case\"cd\":if(u[1])try{process.chdir(uH(u[1],!0))}catch(E){h(E+\"\")}r=!0;break;case\"pwd\":h(process.cwd()),r=!0;break}if(!r&&t.preCheck&&(A=t.preCheck(e,t),e=A.res,A.forceNext&&(r=!0)),!r){if(!t.limitSrc.length||oH(e,t.limitSrc,t.caseSensitive))break;t.limitMessage&&(o=TE(t.limitMessage,p))}h((o?o+`\n`:\"\")+TE(t.displaySrc+\"\",p))}return nme(e,t)}Wr._DBG_set_useExt=function(t){Xde=t};Wr._DBG_set_checkOptions=function(t){iH=t};Wr._DBG_set_checkMethod=function(t){c2=t};Wr._DBG_clearHistory=function(){lH=\"\",qg=[]};Wr.setDefaultOptions=function(t){return nH=Ns(!0,t),Ns(!0)};Wr.question=function(t,e){return ime(Ns(Ns(!0,e),{display:t}))};Wr.prompt=function(t){var e=Ns(!0,t);return e.display=e.prompt,ime(e)};Wr.keyIn=function(t,e){var r=Ns(Ns(!0,e),{display:t,keyIn:!0,keepWhitespace:!0});return r.limitSrc=r.limit.filter(function(o){var a=typeof o;return a===\"string\"||a===\"number\"}).map(function(o){return TE(o+\"\",rme)}),r.limit=cH(r.limitSrc.join(\"\")),[\"trueValue\",\"falseValue\"].forEach(function(o){r[o]=r[o].reduce(function(a,n){var u=typeof n;return u===\"string\"||u===\"number\"?a=a.concat((n+\"\").split(\"\")):a.push(n),a},[])}),r.display=TE(r.display+\"\",function(o){return tme(o,r)}),nme(sH(r),r)};Wr.questionEMail=function(t,e){return t==null&&(t=\"Input e-mail address: \"),Wr.question(t,Ns({hideEchoBack:!1,limit:/^[a-zA-Z0-9.!#$%&'*+\\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,limitMessage:\"Input valid e-mail address, please.\",trueValue:null,falseValue:null},e,{keepWhitespace:!1,cd:!1}))};Wr.questionNewPassword=function(t,e){var r,o,a,n=Ns({hideEchoBack:!0,mask:\"*\",limitMessage:`It can include: $<charlist>\nAnd the length must be: $<length>`,trueValue:null,falseValue:null,caseSensitive:!0},e,{history:!1,cd:!1,phContent:function(x){return x===\"charlist\"?r.text:x===\"length\"?o+\"...\"+a:null}}),u,A,p,h,E,I,v;for(e=e||{},u=TE(e.charlist?e.charlist+\"\":\"$<!-~>\",rme),(isNaN(o=parseInt(e.min,10))||typeof o!=\"number\")&&(o=12),(isNaN(a=parseInt(e.max,10))||typeof a!=\"number\")&&(a=24),h=new RegExp(\"^[\"+cH(u)+\"]{\"+o+\",\"+a+\"}$\"),r=$de([u],n.caseSensitive,!0),r.text=eme(r.values,r.suppressed),A=e.confirmMessage!=null?e.confirmMessage:\"Reinput a same one to confirm it: \",p=e.unmatchMessage!=null?e.unmatchMessage:\"It differs from first one. Hit only the Enter key if you want to retry from first one.\",t==null&&(t=\"Input new password: \"),E=n.limitMessage;!v;)n.limit=h,n.limitMessage=E,I=Wr.question(t,n),n.limit=[I,\"\"],n.limitMessage=p,v=Wr.question(A,n);return I};function sme(t,e,r){var o;function a(n){return o=r(n),!isNaN(o)&&typeof o==\"number\"}return Wr.question(t,Ns({limitMessage:\"Input valid number, please.\"},e,{limit:a,cd:!1})),o}Wr.questionInt=function(t,e){return sme(t,e,function(r){return parseInt(r,10)})};Wr.questionFloat=function(t,e){return sme(t,e,parseFloat)};Wr.questionPath=function(t,e){var r,o=\"\",a=Ns({hideEchoBack:!1,limitMessage:`$<error(\n)>Input valid path, please.$<( Min:)min>$<( Max:)max>`,history:!0,cd:!0},e,{keepWhitespace:!1,limit:function(n){var u,A,p;n=uH(n,!0),o=\"\";function h(E){E.split(/\\/|\\\\/).reduce(function(I,v){var x=kh.resolve(I+=v+kh.sep);if(!Yn.existsSync(x))Yn.mkdirSync(x);else if(!Yn.statSync(x).isDirectory())throw new Error(\"Non directory already exists: \"+x);return I},\"\")}try{if(u=Yn.existsSync(n),r=u?Yn.realpathSync(n):kh.resolve(n),!e.hasOwnProperty(\"exists\")&&!u||typeof e.exists==\"boolean\"&&e.exists!==u)return o=(u?\"Already exists\":\"No such file or directory\")+\": \"+r,!1;if(!u&&e.create&&(e.isDirectory?h(r):(h(kh.dirname(r)),Yn.closeSync(Yn.openSync(r,\"w\"))),r=Yn.realpathSync(r)),u&&(e.min||e.max||e.isFile||e.isDirectory)){if(A=Yn.statSync(r),e.isFile&&!A.isFile())return o=\"Not file: \"+r,!1;if(e.isDirectory&&!A.isDirectory())return o=\"Not directory: \"+r,!1;if(e.min&&A.size<+e.min||e.max&&A.size>+e.max)return o=\"Size \"+A.size+\" is out of range: \"+r,!1}if(typeof e.validate==\"function\"&&(p=e.validate(r))!==!0)return typeof p==\"string\"&&(o=p),!1}catch(E){return o=E+\"\",!1}return!0},phContent:function(n){return n===\"error\"?o:n!==\"min\"&&n!==\"max\"?null:e.hasOwnProperty(n)?e[n]+\"\":\"\"}});return e=e||{},t==null&&(t='Input path (you can \"cd\" and \"pwd\"): '),Wr.question(t,a),r};function ome(t,e){var r={},o={};return typeof t==\"object\"?(Object.keys(t).forEach(function(a){typeof t[a]==\"function\"&&(o[e.caseSensitive?a:a.toLowerCase()]=t[a])}),r.preCheck=function(a){var n;return r.args=aH(a),n=r.args[0]||\"\",e.caseSensitive||(n=n.toLowerCase()),r.hRes=n!==\"_\"&&o.hasOwnProperty(n)?o[n].apply(a,r.args.slice(1)):o.hasOwnProperty(\"_\")?o._.apply(a,r.args):null,{res:a,forceNext:!1}},o.hasOwnProperty(\"_\")||(r.limit=function(){var a=r.args[0]||\"\";return e.caseSensitive||(a=a.toLowerCase()),o.hasOwnProperty(a)})):r.preCheck=function(a){return r.args=aH(a),r.hRes=typeof t==\"function\"?t.apply(a,r.args):!0,{res:a,forceNext:!1}},r}Wr.promptCL=function(t,e){var r=Ns({hideEchoBack:!1,limitMessage:\"Requested command is not available.\",caseSensitive:!1,history:!0},e),o=ome(t,r);return r.limit=o.limit,r.preCheck=o.preCheck,Wr.prompt(r),o.args};Wr.promptLoop=function(t,e){for(var r=Ns({hideEchoBack:!1,trueValue:null,falseValue:null,caseSensitive:!1,history:!0},e);!t(Wr.prompt(r)););};Wr.promptCLLoop=function(t,e){var r=Ns({hideEchoBack:!1,limitMessage:\"Requested command is not available.\",caseSensitive:!1,history:!0},e),o=ome(t,r);for(r.limit=o.limit,r.preCheck=o.preCheck;Wr.prompt(r),!o.hRes;);};Wr.promptSimShell=function(t){return Wr.prompt(Ns({hideEchoBack:!1,history:!0},t,{prompt:function(){return jg?\"$<cwd>>\":(process.env.USER||\"\")+(process.env.HOSTNAME?\"@\"+process.env.HOSTNAME.replace(/\\..*$/,\"\"):\"\")+\":$<cwdHome>$ \"}()}))};function ame(t,e,r){var o;return t==null&&(t=\"Are you sure? \"),(!e||e.guide!==!1)&&(t+=\"\")&&(t=t.replace(/\\s*:?\\s*$/,\"\")+\" [y/n]: \"),o=Wr.keyIn(t,Ns(e,{hideEchoBack:!1,limit:r,trueValue:\"y\",falseValue:\"n\",caseSensitive:!1})),typeof o==\"boolean\"?o:\"\"}Wr.keyInYN=function(t,e){return ame(t,e)};Wr.keyInYNStrict=function(t,e){return ame(t,e,\"yn\")};Wr.keyInPause=function(t,e){t==null&&(t=\"Continue...\"),(!e||e.guide!==!1)&&(t+=\"\")&&(t=t.replace(/\\s+$/,\"\")+\" (Hit any key)\"),Wr.keyIn(t,Ns({limit:null},e,{hideEchoBack:!0,mask:\"\"}))};Wr.keyInSelect=function(t,e,r){var o=Ns({hideEchoBack:!1},r,{trueValue:null,falseValue:null,caseSensitive:!1,phContent:function(p){return p===\"itemsCount\"?t.length+\"\":p===\"firstItem\"?(t[0]+\"\").trim():p===\"lastItem\"?(t[t.length-1]+\"\").trim():null}}),a=\"\",n={},u=49,A=`\n`;if(!Array.isArray(t)||!t.length||t.length>35)throw\"`items` must be Array (max length: 35).\";return t.forEach(function(p,h){var E=String.fromCharCode(u);a+=E,n[E]=h,A+=\"[\"+E+\"] \"+(p+\"\").trim()+`\n`,u=u===57?97:u+1}),(!r||r.cancel!==!1)&&(a+=\"0\",n[0]=-1,A+=\"[0] \"+(r&&r.cancel!=null&&typeof r.cancel!=\"boolean\"?(r.cancel+\"\").trim():\"CANCEL\")+`\n`),o.limit=a,A+=`\n`,e==null&&(e=\"Choose one from list: \"),(e+=\"\")&&((!r||r.guide!==!1)&&(e=e.replace(/\\s*:?\\s*$/,\"\")+\" [$<limit>]: \"),A+=e),n[Wr.keyIn(A,o).toLowerCase()]};Wr.getRawInput=function(){return ak};function u2(t,e){var r;return e.length&&(r={},r[t]=e[0]),Wr.setDefaultOptions(r)[t]}Wr.setPrint=function(){return u2(\"print\",arguments)};Wr.setPrompt=function(){return u2(\"prompt\",arguments)};Wr.setEncoding=function(){return u2(\"encoding\",arguments)};Wr.setMask=function(){return u2(\"mask\",arguments)};Wr.setBufferSize=function(){return u2(\"bufferSize\",arguments)}});var AH=_((a7t,gl)=>{(function(){var t={major:0,minor:2,patch:66,status:\"beta\"};tau_file_system={files:{},open:function(w,b,y){var F=tau_file_system.files[w];if(!F){if(y===\"read\")return null;F={path:w,text:\"\",type:b,get:function(J,X){return X===this.text.length||X>this.text.length?\"end_of_file\":this.text.substring(X,X+J)},put:function(J,X){return X===\"end_of_file\"?(this.text+=J,!0):X===\"past_end_of_file\"?null:(this.text=this.text.substring(0,X)+J+this.text.substring(X+J.length),!0)},get_byte:function(J){if(J===\"end_of_stream\")return-1;var X=Math.floor(J/2);if(this.text.length<=X)return-1;var $=n(this.text[Math.floor(J/2)],0);return J%2===0?$&255:$/256>>>0},put_byte:function(J,X){var $=X===\"end_of_stream\"?this.text.length:Math.floor(X/2);if(this.text.length<$)return null;var ie=this.text.length===$?-1:n(this.text[Math.floor(X/2)],0);return X%2===0?(ie=ie/256>>>0,ie=(ie&255)<<8|J&255):(ie=ie&255,ie=(J&255)<<8|ie&255),this.text.length===$?this.text+=u(ie):this.text=this.text.substring(0,$)+u(ie)+this.text.substring($+1),!0},flush:function(){return!0},close:function(){var J=tau_file_system.files[this.path];return J?!0:null}},tau_file_system.files[w]=F}return y===\"write\"&&(F.text=\"\"),F}},tau_user_input={buffer:\"\",get:function(w,b){for(var y;tau_user_input.buffer.length<w;)y=window.prompt(),y&&(tau_user_input.buffer+=y);return y=tau_user_input.buffer.substr(0,w),tau_user_input.buffer=tau_user_input.buffer.substr(w),y}},tau_user_output={put:function(w,b){return console.log(w),!0},flush:function(){return!0}},nodejs_file_system={open:function(w,b,y){var F=ve(\"fs\"),J=F.openSync(w,y[0]);return y===\"read\"&&!F.existsSync(w)?null:{get:function(X,$){var ie=new Buffer(X);return F.readSync(J,ie,0,X,$),ie.toString()},put:function(X,$){var ie=Buffer.from(X);if($===\"end_of_file\")F.writeSync(J,ie);else{if($===\"past_end_of_file\")return null;F.writeSync(J,ie,0,ie.length,$)}return!0},get_byte:function(X){return null},put_byte:function(X,$){return null},flush:function(){return!0},close:function(){return F.closeSync(J),!0}}}},nodejs_user_input={buffer:\"\",get:function(w,b){for(var y,F=lme();nodejs_user_input.buffer.length<w;)nodejs_user_input.buffer+=F.question();return y=nodejs_user_input.buffer.substr(0,w),nodejs_user_input.buffer=nodejs_user_input.buffer.substr(w),y}},nodejs_user_output={put:function(w,b){return process.stdout.write(w),!0},flush:function(){return!0}};var e;Array.prototype.indexOf?e=function(w,b){return w.indexOf(b)}:e=function(w,b){for(var y=w.length,F=0;F<y;F++)if(b===w[F])return F;return-1};var r=function(w,b){if(w.length!==0){for(var y=w[0],F=w.length,J=1;J<F;J++)y=b(y,w[J]);return y}},o;Array.prototype.map?o=function(w,b){return w.map(b)}:o=function(w,b){for(var y=[],F=w.length,J=0;J<F;J++)y.push(b(w[J]));return y};var a;Array.prototype.filter?a=function(w,b){return w.filter(b)}:a=function(w,b){for(var y=[],F=w.length,J=0;J<F;J++)b(w[J])&&y.push(w[J]);return y};var n;String.prototype.codePointAt?n=function(w,b){return w.codePointAt(b)}:n=function(w,b){return w.charCodeAt(b)};var u;String.fromCodePoint?u=function(){return String.fromCodePoint.apply(null,arguments)}:u=function(){return String.fromCharCode.apply(null,arguments)};var A=0,p=1,h=/(\\\\a)|(\\\\b)|(\\\\f)|(\\\\n)|(\\\\r)|(\\\\t)|(\\\\v)|\\\\x([0-9a-fA-F]+)\\\\|\\\\([0-7]+)\\\\|(\\\\\\\\)|(\\\\')|('')|(\\\\\")|(\\\\`)|(\\\\.)|(.)/g,E={\"\\\\a\":7,\"\\\\b\":8,\"\\\\f\":12,\"\\\\n\":10,\"\\\\r\":13,\"\\\\t\":9,\"\\\\v\":11};function I(w){var b=[],y=!1;return w.replace(h,function(F,J,X,$,ie,Se,Re,at,dt,jt,tr,bt,ln,kr,mr,Sr,Kr){switch(!0){case dt!==void 0:return b.push(parseInt(dt,16)),\"\";case jt!==void 0:return b.push(parseInt(jt,8)),\"\";case tr!==void 0:case bt!==void 0:case ln!==void 0:case kr!==void 0:case mr!==void 0:return b.push(n(F.substr(1),0)),\"\";case Kr!==void 0:return b.push(n(Kr,0)),\"\";case Sr!==void 0:y=!0;default:return b.push(E[F]),\"\"}}),y?null:b}function v(w,b){var y=\"\";if(w.length<2)return w;try{w=w.replace(/\\\\([0-7]+)\\\\/g,function($,ie){return u(parseInt(ie,8))}),w=w.replace(/\\\\x([0-9a-fA-F]+)\\\\/g,function($,ie){return u(parseInt(ie,16))})}catch{return null}for(var F=0;F<w.length;F++){var J=w.charAt(F),X=w.charAt(F+1);if(J===b&&X===b)F++,y+=b;else if(J===\"\\\\\")if([\"a\",\"b\",\"f\",\"n\",\"r\",\"t\",\"v\",\"'\",'\"',\"\\\\\",\"a\",\"\\b\",\"\\f\",`\n`,\"\\r\",\"\t\",\"\\v\"].indexOf(X)!==-1)switch(F+=1,X){case\"a\":y+=\"a\";break;case\"b\":y+=\"\\b\";break;case\"f\":y+=\"\\f\";break;case\"n\":y+=`\n`;break;case\"r\":y+=\"\\r\";break;case\"t\":y+=\"\t\";break;case\"v\":y+=\"\\v\";break;case\"'\":y+=\"'\";break;case'\"':y+='\"';break;case\"\\\\\":y+=\"\\\\\";break}else return null;else y+=J}return y}function x(w){for(var b=\"\",y=0;y<w.length;y++)switch(w.charAt(y)){case\"'\":b+=\"\\\\'\";break;case\"\\\\\":b+=\"\\\\\\\\\";break;case\"\\b\":b+=\"\\\\b\";break;case\"\\f\":b+=\"\\\\f\";break;case`\n`:b+=\"\\\\n\";break;case\"\\r\":b+=\"\\\\r\";break;case\"\t\":b+=\"\\\\t\";break;case\"\\v\":b+=\"\\\\v\";break;default:b+=w.charAt(y);break}return b}function C(w){var b=w.substr(2);switch(w.substr(0,2).toLowerCase()){case\"0x\":return parseInt(b,16);case\"0b\":return parseInt(b,2);case\"0o\":return parseInt(b,8);case\"0'\":return I(b)[0];default:return parseFloat(w)}}var R={whitespace:/^\\s*(?:(?:%.*)|(?:\\/\\*(?:\\n|\\r|.)*?\\*\\/)|(?:\\s+))\\s*/,variable:/^(?:[A-Z_][a-zA-Z0-9_]*)/,atom:/^(\\!|,|;|[a-z][0-9a-zA-Z_]*|[#\\$\\&\\*\\+\\-\\.\\/\\:\\<\\=\\>\\?\\@\\^\\~\\\\]+|'(?:[^']*?(?:\\\\(?:x?\\d+)?\\\\)*(?:'')*(?:\\\\')*)*')/,number:/^(?:0o[0-7]+|0x[0-9a-fA-F]+|0b[01]+|0'(?:''|\\\\[abfnrtv\\\\'\"`]|\\\\x?\\d+\\\\|[^\\\\])|\\d+(?:\\.\\d+(?:[eE][+-]?\\d+)?)?)/,string:/^(?:\"([^\"]|\"\"|\\\\\")*\"|`([^`]|``|\\\\`)*`)/,l_brace:/^(?:\\[)/,r_brace:/^(?:\\])/,l_bracket:/^(?:\\{)/,r_bracket:/^(?:\\})/,bar:/^(?:\\|)/,l_paren:/^(?:\\()/,r_paren:/^(?:\\))/};function L(w,b){return w.get_flag(\"char_conversion\").id===\"on\"?b.replace(/./g,function(y){return w.get_char_conversion(y)}):b}function U(w){this.thread=w,this.text=\"\",this.tokens=[]}U.prototype.set_last_tokens=function(w){return this.tokens=w},U.prototype.new_text=function(w){this.text=w,this.tokens=[]},U.prototype.get_tokens=function(w){var b,y=0,F=0,J=0,X=[],$=!1;if(w){var ie=this.tokens[w-1];y=ie.len,b=L(this.thread,this.text.substr(ie.len)),F=ie.line,J=ie.start}else b=this.text;if(/^\\s*$/.test(b))return null;for(;b!==\"\";){var Se=[],Re=!1;if(/^\\n/.exec(b)!==null){F++,J=0,y++,b=b.replace(/\\n/,\"\"),$=!0;continue}for(var at in R)if(R.hasOwnProperty(at)){var dt=R[at].exec(b);dt&&Se.push({value:dt[0],name:at,matches:dt})}if(!Se.length)return this.set_last_tokens([{value:b,matches:[],name:\"lexical\",line:F,start:J}]);var ie=r(Se,function(kr,mr){return kr.value.length>=mr.value.length?kr:mr});switch(ie.start=J,ie.line=F,b=b.replace(ie.value,\"\"),J+=ie.value.length,y+=ie.value.length,ie.name){case\"atom\":ie.raw=ie.value,ie.value.charAt(0)===\"'\"&&(ie.value=v(ie.value.substr(1,ie.value.length-2),\"'\"),ie.value===null&&(ie.name=\"lexical\",ie.value=\"unknown escape sequence\"));break;case\"number\":ie.float=ie.value.substring(0,2)!==\"0x\"&&ie.value.match(/[.eE]/)!==null&&ie.value!==\"0'.\",ie.value=C(ie.value),ie.blank=Re;break;case\"string\":var jt=ie.value.charAt(0);ie.value=v(ie.value.substr(1,ie.value.length-2),jt),ie.value===null&&(ie.name=\"lexical\",ie.value=\"unknown escape sequence\");break;case\"whitespace\":var tr=X[X.length-1];tr&&(tr.space=!0),Re=!0;continue;case\"r_bracket\":X.length>0&&X[X.length-1].name===\"l_bracket\"&&(ie=X.pop(),ie.name=\"atom\",ie.value=\"{}\",ie.raw=\"{}\",ie.space=!1);break;case\"r_brace\":X.length>0&&X[X.length-1].name===\"l_brace\"&&(ie=X.pop(),ie.name=\"atom\",ie.value=\"[]\",ie.raw=\"[]\",ie.space=!1);break}ie.len=y,X.push(ie),Re=!1}var bt=this.set_last_tokens(X);return bt.length===0?null:bt};function z(w,b,y,F,J){if(!b[y])return{type:A,value:S.error.syntax(b[y-1],\"expression expected\",!0)};var X;if(F===\"0\"){var $=b[y];switch($.name){case\"number\":return{type:p,len:y+1,value:new S.type.Num($.value,$.float)};case\"variable\":return{type:p,len:y+1,value:new S.type.Var($.value)};case\"string\":var ie;switch(w.get_flag(\"double_quotes\").id){case\"atom\":ie=new H($.value,[]);break;case\"codes\":ie=new H(\"[]\",[]);for(var Se=$.value.length-1;Se>=0;Se--)ie=new H(\".\",[new S.type.Num(n($.value,Se),!1),ie]);break;case\"chars\":ie=new H(\"[]\",[]);for(var Se=$.value.length-1;Se>=0;Se--)ie=new H(\".\",[new S.type.Term($.value.charAt(Se),[]),ie]);break}return{type:p,len:y+1,value:ie};case\"l_paren\":var bt=z(w,b,y+1,w.__get_max_priority(),!0);return bt.type!==p?bt:b[bt.len]&&b[bt.len].name===\"r_paren\"?(bt.len++,bt):{type:A,derived:!0,value:S.error.syntax(b[bt.len]?b[bt.len]:b[bt.len-1],\") or operator expected\",!b[bt.len])};case\"l_bracket\":var bt=z(w,b,y+1,w.__get_max_priority(),!0);return bt.type!==p?bt:b[bt.len]&&b[bt.len].name===\"r_bracket\"?(bt.len++,bt.value=new H(\"{}\",[bt.value]),bt):{type:A,derived:!0,value:S.error.syntax(b[bt.len]?b[bt.len]:b[bt.len-1],\"} or operator expected\",!b[bt.len])}}var Re=te(w,b,y,J);return Re.type===p||Re.derived||(Re=ae(w,b,y),Re.type===p||Re.derived)?Re:{type:A,derived:!1,value:S.error.syntax(b[y],\"unexpected token\")}}var at=w.__get_max_priority(),dt=w.__get_next_priority(F),jt=y;if(b[y].name===\"atom\"&&b[y+1]&&(b[y].space||b[y+1].name!==\"l_paren\")){var $=b[y++],tr=w.__lookup_operator_classes(F,$.value);if(tr&&tr.indexOf(\"fy\")>-1){var bt=z(w,b,y,F,J);if(bt.type!==A)return $.value===\"-\"&&!$.space&&S.type.is_number(bt.value)?{value:new S.type.Num(-bt.value.value,bt.value.is_float),len:bt.len,type:p}:{value:new S.type.Term($.value,[bt.value]),len:bt.len,type:p};X=bt}else if(tr&&tr.indexOf(\"fx\")>-1){var bt=z(w,b,y,dt,J);if(bt.type!==A)return{value:new S.type.Term($.value,[bt.value]),len:bt.len,type:p};X=bt}}y=jt;var bt=z(w,b,y,dt,J);if(bt.type===p){y=bt.len;var $=b[y];if(b[y]&&(b[y].name===\"atom\"&&w.__lookup_operator_classes(F,$.value)||b[y].name===\"bar\"&&w.__lookup_operator_classes(F,\"|\"))){var ln=dt,kr=F,tr=w.__lookup_operator_classes(F,$.value);if(tr.indexOf(\"xf\")>-1)return{value:new S.type.Term($.value,[bt.value]),len:++bt.len,type:p};if(tr.indexOf(\"xfx\")>-1){var mr=z(w,b,y+1,ln,J);return mr.type===p?{value:new S.type.Term($.value,[bt.value,mr.value]),len:mr.len,type:p}:(mr.derived=!0,mr)}else if(tr.indexOf(\"xfy\")>-1){var mr=z(w,b,y+1,kr,J);return mr.type===p?{value:new S.type.Term($.value,[bt.value,mr.value]),len:mr.len,type:p}:(mr.derived=!0,mr)}else if(bt.type!==A)for(;;){y=bt.len;var $=b[y];if($&&$.name===\"atom\"&&w.__lookup_operator_classes(F,$.value)){var tr=w.__lookup_operator_classes(F,$.value);if(tr.indexOf(\"yf\")>-1)bt={value:new S.type.Term($.value,[bt.value]),len:++y,type:p};else if(tr.indexOf(\"yfx\")>-1){var mr=z(w,b,++y,ln,J);if(mr.type===A)return mr.derived=!0,mr;y=mr.len,bt={value:new S.type.Term($.value,[bt.value,mr.value]),len:y,type:p}}else break}else break}}else X={type:A,value:S.error.syntax(b[bt.len-1],\"operator expected\")};return bt}return bt}function te(w,b,y,F){if(!b[y]||b[y].name===\"atom\"&&b[y].raw===\".\"&&!F&&(b[y].space||!b[y+1]||b[y+1].name!==\"l_paren\"))return{type:A,derived:!1,value:S.error.syntax(b[y-1],\"unfounded token\")};var J=b[y],X=[];if(b[y].name===\"atom\"&&b[y].raw!==\",\"){if(y++,b[y-1].space)return{type:p,len:y,value:new S.type.Term(J.value,X)};if(b[y]&&b[y].name===\"l_paren\"){if(b[y+1]&&b[y+1].name===\"r_paren\")return{type:A,derived:!0,value:S.error.syntax(b[y+1],\"argument expected\")};var $=z(w,b,++y,\"999\",!0);if($.type===A)return $.derived?$:{type:A,derived:!0,value:S.error.syntax(b[y]?b[y]:b[y-1],\"argument expected\",!b[y])};for(X.push($.value),y=$.len;b[y]&&b[y].name===\"atom\"&&b[y].value===\",\";){if($=z(w,b,y+1,\"999\",!0),$.type===A)return $.derived?$:{type:A,derived:!0,value:S.error.syntax(b[y+1]?b[y+1]:b[y],\"argument expected\",!b[y+1])};X.push($.value),y=$.len}if(b[y]&&b[y].name===\"r_paren\")y++;else return{type:A,derived:!0,value:S.error.syntax(b[y]?b[y]:b[y-1],\", or ) expected\",!b[y])}}return{type:p,len:y,value:new S.type.Term(J.value,X)}}return{type:A,derived:!1,value:S.error.syntax(b[y],\"term expected\")}}function ae(w,b,y){if(!b[y])return{type:A,derived:!1,value:S.error.syntax(b[y-1],\"[ expected\")};if(b[y]&&b[y].name===\"l_brace\"){var F=z(w,b,++y,\"999\",!0),J=[F.value],X=void 0;if(F.type===A)return b[y]&&b[y].name===\"r_brace\"?{type:p,len:y+1,value:new S.type.Term(\"[]\",[])}:{type:A,derived:!0,value:S.error.syntax(b[y],\"] expected\")};for(y=F.len;b[y]&&b[y].name===\"atom\"&&b[y].value===\",\";){if(F=z(w,b,y+1,\"999\",!0),F.type===A)return F.derived?F:{type:A,derived:!0,value:S.error.syntax(b[y+1]?b[y+1]:b[y],\"argument expected\",!b[y+1])};J.push(F.value),y=F.len}var $=!1;if(b[y]&&b[y].name===\"bar\"){if($=!0,F=z(w,b,y+1,\"999\",!0),F.type===A)return F.derived?F:{type:A,derived:!0,value:S.error.syntax(b[y+1]?b[y+1]:b[y],\"argument expected\",!b[y+1])};X=F.value,y=F.len}return b[y]&&b[y].name===\"r_brace\"?{type:p,len:y+1,value:g(J,X)}:{type:A,derived:!0,value:S.error.syntax(b[y]?b[y]:b[y-1],$?\"] expected\":\", or | or ] expected\",!b[y])}}return{type:A,derived:!1,value:S.error.syntax(b[y],\"list expected\")}}function le(w,b,y){var F=b[y].line,J=z(w,b,y,w.__get_max_priority(),!1),X=null,$;if(J.type!==A)if(y=J.len,b[y]&&b[y].name===\"atom\"&&b[y].raw===\".\")if(y++,S.type.is_term(J.value)){if(J.value.indicator===\":-/2\"?(X=new S.type.Rule(J.value.args[0],Ee(J.value.args[1])),$={value:X,len:y,type:p}):J.value.indicator===\"-->/2\"?(X=de(new S.type.Rule(J.value.args[0],J.value.args[1]),w),X.body=Ee(X.body),$={value:X,len:y,type:S.type.is_rule(X)?p:A}):(X=new S.type.Rule(J.value,null),$={value:X,len:y,type:p}),X){var ie=X.singleton_variables();ie.length>0&&w.throw_warning(S.warning.singleton(ie,X.head.indicator,F))}return $}else return{type:A,value:S.error.syntax(b[y],\"callable expected\")};else return{type:A,value:S.error.syntax(b[y]?b[y]:b[y-1],\". or operator expected\")};return J}function ce(w,b,y){y=y||{},y.from=y.from?y.from:\"$tau-js\",y.reconsult=y.reconsult!==void 0?y.reconsult:!0;var F=new U(w),J={},X;F.new_text(b);var $=0,ie=F.get_tokens($);do{if(ie===null||!ie[$])break;var Se=le(w,ie,$);if(Se.type===A)return new H(\"throw\",[Se.value]);if(Se.value.body===null&&Se.value.head.indicator===\"?-/1\"){var Re=new et(w.session);Re.add_goal(Se.value.head.args[0]),Re.answer(function(dt){S.type.is_error(dt)?w.throw_warning(dt.args[0]):(dt===!1||dt===null)&&w.throw_warning(S.warning.failed_goal(Se.value.head.args[0],Se.len))}),$=Se.len;var at=!0}else if(Se.value.body===null&&Se.value.head.indicator===\":-/1\"){var at=w.run_directive(Se.value.head.args[0]);$=Se.len,Se.value.head.args[0].indicator===\"char_conversion/2\"&&(ie=F.get_tokens($),$=0)}else{X=Se.value.head.indicator,y.reconsult!==!1&&J[X]!==!0&&!w.is_multifile_predicate(X)&&(w.session.rules[X]=a(w.session.rules[X]||[],function(jt){return jt.dynamic}),J[X]=!0);var at=w.add_rule(Se.value,y);$=Se.len}if(!at)return at}while(!0);return!0}function Ce(w,b){var y=new U(w);y.new_text(b);var F=0;do{var J=y.get_tokens(F);if(J===null)break;var X=z(w,J,0,w.__get_max_priority(),!1);if(X.type!==A){var $=X.len,ie=$;if(J[$]&&J[$].name===\"atom\"&&J[$].raw===\".\")w.add_goal(Ee(X.value));else{var Se=J[$];return new H(\"throw\",[S.error.syntax(Se||J[$-1],\". or operator expected\",!Se)])}F=X.len+1}else return new H(\"throw\",[X.value])}while(!0);return!0}function de(w,b){w=w.rename(b);var y=b.next_free_variable(),F=Be(w.body,y,b);return F.error?F.value:(w.body=F.value,w.head.args=w.head.args.concat([y,F.variable]),w.head=new H(w.head.id,w.head.args),w)}function Be(w,b,y){var F;if(S.type.is_term(w)&&w.indicator===\"!/0\")return{value:w,variable:b,error:!1};if(S.type.is_term(w)&&w.indicator===\",/2\"){var J=Be(w.args[0],b,y);if(J.error)return J;var X=Be(w.args[1],J.variable,y);return X.error?X:{value:new H(\",\",[J.value,X.value]),variable:X.variable,error:!1}}else{if(S.type.is_term(w)&&w.indicator===\"{}/1\")return{value:w.args[0],variable:b,error:!1};if(S.type.is_empty_list(w))return{value:new H(\"true\",[]),variable:b,error:!1};if(S.type.is_list(w)){F=y.next_free_variable();for(var $=w,ie;$.indicator===\"./2\";)ie=$,$=$.args[1];return S.type.is_variable($)?{value:S.error.instantiation(\"DCG\"),variable:b,error:!0}:S.type.is_empty_list($)?(ie.args[1]=F,{value:new H(\"=\",[b,w]),variable:F,error:!1}):{value:S.error.type(\"list\",w,\"DCG\"),variable:b,error:!0}}else return S.type.is_callable(w)?(F=y.next_free_variable(),w.args=w.args.concat([b,F]),w=new H(w.id,w.args),{value:w,variable:F,error:!1}):{value:S.error.type(\"callable\",w,\"DCG\"),variable:b,error:!0}}}function Ee(w){return S.type.is_variable(w)?new H(\"call\",[w]):S.type.is_term(w)&&[\",/2\",\";/2\",\"->/2\"].indexOf(w.indicator)!==-1?new H(w.id,[Ee(w.args[0]),Ee(w.args[1])]):w}function g(w,b){for(var y=b||new S.type.Term(\"[]\",[]),F=w.length-1;F>=0;F--)y=new S.type.Term(\".\",[w[F],y]);return y}function me(w,b){for(var y=w.length-1;y>=0;y--)w[y]===b&&w.splice(y,1)}function we(w){for(var b={},y=[],F=0;F<w.length;F++)w[F]in b||(y.push(w[F]),b[w[F]]=!0);return y}function Ae(w,b,y,F){if(w.session.rules[y]!==null){for(var J=0;J<w.session.rules[y].length;J++)if(w.session.rules[y][J]===F){w.session.rules[y].splice(J,1),w.success(b);break}}}function ne(w){return function(b,y,F){var J=F.args[0],X=F.args.slice(1,w);if(S.type.is_variable(J))b.throw_error(S.error.instantiation(b.level));else if(!S.type.is_callable(J))b.throw_error(S.error.type(\"callable\",J,b.level));else{var $=new H(J.id,J.args.concat(X));b.prepend([new ke(y.goal.replace($),y.substitution,y)])}}}function Z(w){for(var b=w.length-1;b>=0;b--)if(w.charAt(b)===\"/\")return new H(\"/\",[new H(w.substring(0,b)),new Ne(parseInt(w.substring(b+1)),!1)])}function xe(w){this.id=w}function Ne(w,b){this.is_float=b!==void 0?b:parseInt(w)!==w,this.value=this.is_float?w:parseInt(w)}var ht=0;function H(w,b,y){this.ref=y||++ht,this.id=w,this.args=b||[],this.indicator=w+\"/\"+this.args.length}var rt=0;function Te(w,b,y,F,J,X){this.id=rt++,this.stream=w,this.mode=b,this.alias=y,this.type=F!==void 0?F:\"text\",this.reposition=J!==void 0?J:!0,this.eof_action=X!==void 0?X:\"eof_code\",this.position=this.mode===\"append\"?\"end_of_stream\":0,this.output=this.mode===\"write\"||this.mode===\"append\",this.input=this.mode===\"read\"}function Fe(w){w=w||{},this.links=w}function ke(w,b,y){b=b||new Fe,y=y||null,this.goal=w,this.substitution=b,this.parent=y}function Ye(w,b,y){this.head=w,this.body=b,this.dynamic=y||!1}function be(w){w=w===void 0||w<=0?1e3:w,this.rules={},this.src_predicates={},this.rename=0,this.modules=[],this.thread=new et(this),this.total_threads=1,this.renamed_variables={},this.public_predicates={},this.multifile_predicates={},this.limit=w,this.streams={user_input:new Te(typeof gl<\"u\"&&gl.exports?nodejs_user_input:tau_user_input,\"read\",\"user_input\",\"text\",!1,\"reset\"),user_output:new Te(typeof gl<\"u\"&&gl.exports?nodejs_user_output:tau_user_output,\"write\",\"user_output\",\"text\",!1,\"eof_code\")},this.file_system=typeof gl<\"u\"&&gl.exports?nodejs_file_system:tau_file_system,this.standard_input=this.streams.user_input,this.standard_output=this.streams.user_output,this.current_input=this.streams.user_input,this.current_output=this.streams.user_output,this.format_success=function(b){return b.substitution},this.format_error=function(b){return b.goal},this.flag={bounded:S.flag.bounded.value,max_integer:S.flag.max_integer.value,min_integer:S.flag.min_integer.value,integer_rounding_function:S.flag.integer_rounding_function.value,char_conversion:S.flag.char_conversion.value,debug:S.flag.debug.value,max_arity:S.flag.max_arity.value,unknown:S.flag.unknown.value,double_quotes:S.flag.double_quotes.value,occurs_check:S.flag.occurs_check.value,dialect:S.flag.dialect.value,version_data:S.flag.version_data.value,nodejs:S.flag.nodejs.value},this.__loaded_modules=[],this.__char_conversion={},this.__operators={1200:{\":-\":[\"fx\",\"xfx\"],\"-->\":[\"xfx\"],\"?-\":[\"fx\"]},1100:{\";\":[\"xfy\"]},1050:{\"->\":[\"xfy\"]},1e3:{\",\":[\"xfy\"]},900:{\"\\\\+\":[\"fy\"]},700:{\"=\":[\"xfx\"],\"\\\\=\":[\"xfx\"],\"==\":[\"xfx\"],\"\\\\==\":[\"xfx\"],\"@<\":[\"xfx\"],\"@=<\":[\"xfx\"],\"@>\":[\"xfx\"],\"@>=\":[\"xfx\"],\"=..\":[\"xfx\"],is:[\"xfx\"],\"=:=\":[\"xfx\"],\"=\\\\=\":[\"xfx\"],\"<\":[\"xfx\"],\"=<\":[\"xfx\"],\">\":[\"xfx\"],\">=\":[\"xfx\"]},600:{\":\":[\"xfy\"]},500:{\"+\":[\"yfx\"],\"-\":[\"yfx\"],\"/\\\\\":[\"yfx\"],\"\\\\/\":[\"yfx\"]},400:{\"*\":[\"yfx\"],\"/\":[\"yfx\"],\"//\":[\"yfx\"],rem:[\"yfx\"],mod:[\"yfx\"],\"<<\":[\"yfx\"],\">>\":[\"yfx\"]},200:{\"**\":[\"xfx\"],\"^\":[\"xfy\"],\"-\":[\"fy\"],\"+\":[\"fy\"],\"\\\\\":[\"fy\"]}}}function et(w){this.epoch=Date.now(),this.session=w,this.session.total_threads++,this.total_steps=0,this.cpu_time=0,this.cpu_time_last=0,this.points=[],this.debugger=!1,this.debugger_states=[],this.level=\"top_level/0\",this.__calls=[],this.current_limit=this.session.limit,this.warnings=[]}function Ue(w,b,y){this.id=w,this.rules=b,this.exports=y,S.module[w]=this}Ue.prototype.exports_predicate=function(w){return this.exports.indexOf(w)!==-1},xe.prototype.unify=function(w,b){if(b&&e(w.variables(),this.id)!==-1&&!S.type.is_variable(w))return null;var y={};return y[this.id]=w,new Fe(y)},Ne.prototype.unify=function(w,b){return S.type.is_number(w)&&this.value===w.value&&this.is_float===w.is_float?new Fe:null},H.prototype.unify=function(w,b){if(S.type.is_term(w)&&this.indicator===w.indicator){for(var y=new Fe,F=0;F<this.args.length;F++){var J=S.unify(this.args[F].apply(y),w.args[F].apply(y),b);if(J===null)return null;for(var X in J.links)y.links[X]=J.links[X];y=y.apply(J)}return y}return null},Te.prototype.unify=function(w,b){return S.type.is_stream(w)&&this.id===w.id?new Fe:null},xe.prototype.toString=function(w){return this.id},Ne.prototype.toString=function(w){return this.is_float&&e(this.value.toString(),\".\")===-1?this.value+\".0\":this.value.toString()},H.prototype.toString=function(w,b,y){if(w=w||{},w.quoted=w.quoted===void 0?!0:w.quoted,w.ignore_ops=w.ignore_ops===void 0?!1:w.ignore_ops,w.numbervars=w.numbervars===void 0?!1:w.numbervars,b=b===void 0?1200:b,y=y===void 0?\"\":y,w.numbervars&&this.indicator===\"$VAR/1\"&&S.type.is_integer(this.args[0])&&this.args[0].value>=0){var F=this.args[0].value,J=Math.floor(F/26),X=F%26;return\"ABCDEFGHIJKLMNOPQRSTUVWXYZ\"[X]+(J!==0?J:\"\")}switch(this.indicator){case\"[]/0\":case\"{}/0\":case\"!/0\":return this.id;case\"{}/1\":return\"{\"+this.args[0].toString(w)+\"}\";case\"./2\":for(var $=\"[\"+this.args[0].toString(w),ie=this.args[1];ie.indicator===\"./2\";)$+=\", \"+ie.args[0].toString(w),ie=ie.args[1];return ie.indicator!==\"[]/0\"&&($+=\"|\"+ie.toString(w)),$+=\"]\",$;case\",/2\":return\"(\"+this.args[0].toString(w)+\", \"+this.args[1].toString(w)+\")\";default:var Se=this.id,Re=w.session?w.session.lookup_operator(this.id,this.args.length):null;if(w.session===void 0||w.ignore_ops||Re===null)return w.quoted&&!/^(!|,|;|[a-z][0-9a-zA-Z_]*)$/.test(Se)&&Se!==\"{}\"&&Se!==\"[]\"&&(Se=\"'\"+x(Se)+\"'\"),Se+(this.args.length?\"(\"+o(this.args,function(tr){return tr.toString(w)}).join(\", \")+\")\":\"\");var at=Re.priority>b.priority||Re.priority===b.priority&&(Re.class===\"xfy\"&&this.indicator!==b.indicator||Re.class===\"yfx\"&&this.indicator!==b.indicator||this.indicator===b.indicator&&Re.class===\"yfx\"&&y===\"right\"||this.indicator===b.indicator&&Re.class===\"xfy\"&&y===\"left\");Re.indicator=this.indicator;var dt=at?\"(\":\"\",jt=at?\")\":\"\";return this.args.length===0?\"(\"+this.id+\")\":[\"fy\",\"fx\"].indexOf(Re.class)!==-1?dt+Se+\" \"+this.args[0].toString(w,Re)+jt:[\"yf\",\"xf\"].indexOf(Re.class)!==-1?dt+this.args[0].toString(w,Re)+\" \"+Se+jt:dt+this.args[0].toString(w,Re,\"left\")+\" \"+this.id+\" \"+this.args[1].toString(w,Re,\"right\")+jt}},Te.prototype.toString=function(w){return\"<stream>(\"+this.id+\")\"},Fe.prototype.toString=function(w){var b=\"{\";for(var y in this.links)this.links.hasOwnProperty(y)&&(b!==\"{\"&&(b+=\", \"),b+=y+\"/\"+this.links[y].toString(w));return b+=\"}\",b},ke.prototype.toString=function(w){return this.goal===null?\"<\"+this.substitution.toString(w)+\">\":\"<\"+this.goal.toString(w)+\", \"+this.substitution.toString(w)+\">\"},Ye.prototype.toString=function(w){return this.body?this.head.toString(w)+\" :- \"+this.body.toString(w)+\".\":this.head.toString(w)+\".\"},be.prototype.toString=function(w){for(var b=\"\",y=0;y<this.modules.length;y++)b+=\":- use_module(library(\"+this.modules[y]+`)).\n`;b+=`\n`;for(key in this.rules)for(y=0;y<this.rules[key].length;y++)b+=this.rules[key][y].toString(w),b+=`\n`;return b},xe.prototype.clone=function(){return new xe(this.id)},Ne.prototype.clone=function(){return new Ne(this.value,this.is_float)},H.prototype.clone=function(){return new H(this.id,o(this.args,function(w){return w.clone()}))},Te.prototype.clone=function(){return new Stram(this.stream,this.mode,this.alias,this.type,this.reposition,this.eof_action)},Fe.prototype.clone=function(){var w={};for(var b in this.links)this.links.hasOwnProperty(b)&&(w[b]=this.links[b].clone());return new Fe(w)},ke.prototype.clone=function(){return new ke(this.goal.clone(),this.substitution.clone(),this.parent)},Ye.prototype.clone=function(){return new Ye(this.head.clone(),this.body!==null?this.body.clone():null)},xe.prototype.equals=function(w){return S.type.is_variable(w)&&this.id===w.id},Ne.prototype.equals=function(w){return S.type.is_number(w)&&this.value===w.value&&this.is_float===w.is_float},H.prototype.equals=function(w){if(!S.type.is_term(w)||this.indicator!==w.indicator)return!1;for(var b=0;b<this.args.length;b++)if(!this.args[b].equals(w.args[b]))return!1;return!0},Te.prototype.equals=function(w){return S.type.is_stream(w)&&this.id===w.id},Fe.prototype.equals=function(w){var b;if(!S.type.is_substitution(w))return!1;for(b in this.links)if(this.links.hasOwnProperty(b)&&(!w.links[b]||!this.links[b].equals(w.links[b])))return!1;for(b in w.links)if(w.links.hasOwnProperty(b)&&!this.links[b])return!1;return!0},ke.prototype.equals=function(w){return S.type.is_state(w)&&this.goal.equals(w.goal)&&this.substitution.equals(w.substitution)&&this.parent===w.parent},Ye.prototype.equals=function(w){return S.type.is_rule(w)&&this.head.equals(w.head)&&(this.body===null&&w.body===null||this.body!==null&&this.body.equals(w.body))},xe.prototype.rename=function(w){return w.get_free_variable(this)},Ne.prototype.rename=function(w){return this},H.prototype.rename=function(w){return new H(this.id,o(this.args,function(b){return b.rename(w)}))},Te.prototype.rename=function(w){return this},Ye.prototype.rename=function(w){return new Ye(this.head.rename(w),this.body!==null?this.body.rename(w):null)},xe.prototype.variables=function(){return[this.id]},Ne.prototype.variables=function(){return[]},H.prototype.variables=function(){return[].concat.apply([],o(this.args,function(w){return w.variables()}))},Te.prototype.variables=function(){return[]},Ye.prototype.variables=function(){return this.body===null?this.head.variables():this.head.variables().concat(this.body.variables())},xe.prototype.apply=function(w){return w.lookup(this.id)?w.lookup(this.id):this},Ne.prototype.apply=function(w){return this},H.prototype.apply=function(w){if(this.indicator===\"./2\"){for(var b=[],y=this;y.indicator===\"./2\";)b.push(y.args[0].apply(w)),y=y.args[1];for(var F=y.apply(w),J=b.length-1;J>=0;J--)F=new H(\".\",[b[J],F]);return F}return new H(this.id,o(this.args,function(X){return X.apply(w)}),this.ref)},Te.prototype.apply=function(w){return this},Ye.prototype.apply=function(w){return new Ye(this.head.apply(w),this.body!==null?this.body.apply(w):null)},Fe.prototype.apply=function(w){var b,y={};for(b in this.links)this.links.hasOwnProperty(b)&&(y[b]=this.links[b].apply(w));return new Fe(y)},H.prototype.select=function(){for(var w=this;w.indicator===\",/2\";)w=w.args[0];return w},H.prototype.replace=function(w){return this.indicator===\",/2\"?this.args[0].indicator===\",/2\"?new H(\",\",[this.args[0].replace(w),this.args[1]]):w===null?this.args[1]:new H(\",\",[w,this.args[1]]):w},H.prototype.search=function(w){if(S.type.is_term(w)&&w.ref!==void 0&&this.ref===w.ref)return!0;for(var b=0;b<this.args.length;b++)if(S.type.is_term(this.args[b])&&this.args[b].search(w))return!0;return!1},be.prototype.get_current_input=function(){return this.current_input},et.prototype.get_current_input=function(){return this.session.get_current_input()},be.prototype.get_current_output=function(){return this.current_output},et.prototype.get_current_output=function(){return this.session.get_current_output()},be.prototype.set_current_input=function(w){this.current_input=w},et.prototype.set_current_input=function(w){return this.session.set_current_input(w)},be.prototype.set_current_output=function(w){this.current_input=w},et.prototype.set_current_output=function(w){return this.session.set_current_output(w)},be.prototype.get_stream_by_alias=function(w){return this.streams[w]},et.prototype.get_stream_by_alias=function(w){return this.session.get_stream_by_alias(w)},be.prototype.file_system_open=function(w,b,y){return this.file_system.open(w,b,y)},et.prototype.file_system_open=function(w,b,y){return this.session.file_system_open(w,b,y)},be.prototype.get_char_conversion=function(w){return this.__char_conversion[w]||w},et.prototype.get_char_conversion=function(w){return this.session.get_char_conversion(w)},be.prototype.parse=function(w){return this.thread.parse(w)},et.prototype.parse=function(w){var b=new U(this);b.new_text(w);var y=b.get_tokens();if(y===null)return!1;var F=z(this,y,0,this.__get_max_priority(),!1);return F.len!==y.length?!1:{value:F.value,expr:F,tokens:y}},be.prototype.get_flag=function(w){return this.flag[w]},et.prototype.get_flag=function(w){return this.session.get_flag(w)},be.prototype.add_rule=function(w,b){return b=b||{},b.from=b.from?b.from:\"$tau-js\",this.src_predicates[w.head.indicator]=b.from,this.rules[w.head.indicator]||(this.rules[w.head.indicator]=[]),this.rules[w.head.indicator].push(w),this.public_predicates.hasOwnProperty(w.head.indicator)||(this.public_predicates[w.head.indicator]=!1),!0},et.prototype.add_rule=function(w,b){return this.session.add_rule(w,b)},be.prototype.run_directive=function(w){this.thread.run_directive(w)},et.prototype.run_directive=function(w){return S.type.is_directive(w)?(S.directive[w.indicator](this,w),!0):!1},be.prototype.__get_max_priority=function(){return\"1200\"},et.prototype.__get_max_priority=function(){return this.session.__get_max_priority()},be.prototype.__get_next_priority=function(w){var b=0;w=parseInt(w);for(var y in this.__operators)if(this.__operators.hasOwnProperty(y)){var F=parseInt(y);F>b&&F<w&&(b=F)}return b.toString()},et.prototype.__get_next_priority=function(w){return this.session.__get_next_priority(w)},be.prototype.__lookup_operator_classes=function(w,b){return this.__operators.hasOwnProperty(w)&&this.__operators[w][b]instanceof Array&&this.__operators[w][b]||!1},et.prototype.__lookup_operator_classes=function(w,b){return this.session.__lookup_operator_classes(w,b)},be.prototype.lookup_operator=function(w,b){for(var y in this.__operators)if(this.__operators[y][w]){for(var F=0;F<this.__operators[y][w].length;F++)if(b===0||this.__operators[y][w][F].length===b+1)return{priority:y,class:this.__operators[y][w][F]}}return null},et.prototype.lookup_operator=function(w,b){return this.session.lookup_operator(w,b)},be.prototype.throw_warning=function(w){this.thread.throw_warning(w)},et.prototype.throw_warning=function(w){this.warnings.push(w)},be.prototype.get_warnings=function(){return this.thread.get_warnings()},et.prototype.get_warnings=function(){return this.warnings},be.prototype.add_goal=function(w,b){this.thread.add_goal(w,b)},et.prototype.add_goal=function(w,b,y){y=y||null,b===!0&&(this.points=[]);for(var F=w.variables(),J={},X=0;X<F.length;X++)J[F[X]]=new xe(F[X]);this.points.push(new ke(w,new Fe(J),y))},be.prototype.consult=function(w,b){return this.thread.consult(w,b)},et.prototype.consult=function(w,b){var y=\"\";if(typeof w==\"string\"){y=w;var F=y.length;if(y.substring(F-3,F)===\".pl\"&&document.getElementById(y)){var J=document.getElementById(y),X=J.getAttribute(\"type\");X!==null&&X.replace(/ /g,\"\").toLowerCase()===\"text/prolog\"&&(y=J.text)}}else if(w.nodeName)switch(w.nodeName.toLowerCase()){case\"input\":case\"textarea\":y=w.value;break;default:y=w.innerHTML;break}else return!1;return this.warnings=[],ce(this,y,b)},be.prototype.query=function(w){return this.thread.query(w)},et.prototype.query=function(w){return this.points=[],this.debugger_points=[],Ce(this,w)},be.prototype.head_point=function(){return this.thread.head_point()},et.prototype.head_point=function(){return this.points[this.points.length-1]},be.prototype.get_free_variable=function(w){return this.thread.get_free_variable(w)},et.prototype.get_free_variable=function(w){var b=[];if(w.id===\"_\"||this.session.renamed_variables[w.id]===void 0){for(this.session.rename++,this.points.length>0&&(b=this.head_point().substitution.domain());e(b,S.format_variable(this.session.rename))!==-1;)this.session.rename++;if(w.id===\"_\")return new xe(S.format_variable(this.session.rename));this.session.renamed_variables[w.id]=S.format_variable(this.session.rename)}return new xe(this.session.renamed_variables[w.id])},be.prototype.next_free_variable=function(){return this.thread.next_free_variable()},et.prototype.next_free_variable=function(){this.session.rename++;var w=[];for(this.points.length>0&&(w=this.head_point().substitution.domain());e(w,S.format_variable(this.session.rename))!==-1;)this.session.rename++;return new xe(S.format_variable(this.session.rename))},be.prototype.is_public_predicate=function(w){return!this.public_predicates.hasOwnProperty(w)||this.public_predicates[w]===!0},et.prototype.is_public_predicate=function(w){return this.session.is_public_predicate(w)},be.prototype.is_multifile_predicate=function(w){return this.multifile_predicates.hasOwnProperty(w)&&this.multifile_predicates[w]===!0},et.prototype.is_multifile_predicate=function(w){return this.session.is_multifile_predicate(w)},be.prototype.prepend=function(w){return this.thread.prepend(w)},et.prototype.prepend=function(w){for(var b=w.length-1;b>=0;b--)this.points.push(w[b])},be.prototype.success=function(w,b){return this.thread.success(w,b)},et.prototype.success=function(w,y){var y=typeof y>\"u\"?w:y;this.prepend([new ke(w.goal.replace(null),w.substitution,y)])},be.prototype.throw_error=function(w){return this.thread.throw_error(w)},et.prototype.throw_error=function(w){this.prepend([new ke(new H(\"throw\",[w]),new Fe,null,null)])},be.prototype.step_rule=function(w,b){return this.thread.step_rule(w,b)},et.prototype.step_rule=function(w,b){var y=b.indicator;if(w===\"user\"&&(w=null),w===null&&this.session.rules.hasOwnProperty(y))return this.session.rules[y];for(var F=w===null?this.session.modules:e(this.session.modules,w)===-1?[]:[w],J=0;J<F.length;J++){var X=S.module[F[J]];if(X.rules.hasOwnProperty(y)&&(X.rules.hasOwnProperty(this.level)||X.exports_predicate(y)))return S.module[F[J]].rules[y]}return null},be.prototype.step=function(){return this.thread.step()},et.prototype.step=function(){if(this.points.length!==0){var w=!1,b=this.points.pop();if(this.debugger&&this.debugger_states.push(b),S.type.is_term(b.goal)){var y=b.goal.select(),F=null,J=[];if(y!==null){this.total_steps++;for(var X=b;X.parent!==null&&X.parent.goal.search(y);)X=X.parent;if(this.level=X.parent===null?\"top_level/0\":X.parent.goal.select().indicator,S.type.is_term(y)&&y.indicator===\":/2\"&&(F=y.args[0].id,y=y.args[1]),F===null&&S.type.is_builtin(y))this.__call_indicator=y.indicator,w=S.predicate[y.indicator](this,b,y);else{var $=this.step_rule(F,y);if($===null)this.session.rules.hasOwnProperty(y.indicator)||(this.get_flag(\"unknown\").id===\"error\"?this.throw_error(S.error.existence(\"procedure\",y.indicator,this.level)):this.get_flag(\"unknown\").id===\"warning\"&&this.throw_warning(\"unknown procedure \"+y.indicator+\" (from \"+this.level+\")\"));else if($ instanceof Function)w=$(this,b,y);else{for(var ie in $)if($.hasOwnProperty(ie)){var Se=$[ie];this.session.renamed_variables={},Se=Se.rename(this);var Re=this.get_flag(\"occurs_check\").indicator===\"true/0\",at=new ke,dt=S.unify(y,Se.head,Re);dt!==null&&(at.goal=b.goal.replace(Se.body),at.goal!==null&&(at.goal=at.goal.apply(dt)),at.substitution=b.substitution.apply(dt),at.parent=b,J.push(at))}this.prepend(J)}}}}else S.type.is_variable(b.goal)?this.throw_error(S.error.instantiation(this.level)):this.throw_error(S.error.type(\"callable\",b.goal,this.level));return w}},be.prototype.answer=function(w){return this.thread.answer(w)},et.prototype.answer=function(w){w=w||function(b){},this.__calls.push(w),!(this.__calls.length>1)&&this.again()},be.prototype.answers=function(w,b,y){return this.thread.answers(w,b,y)},et.prototype.answers=function(w,b,y){var F=b||1e3,J=this;if(b<=0){y&&y();return}this.answer(function(X){w(X),X!==!1?setTimeout(function(){J.answers(w,b-1,y)},1):y&&y()})},be.prototype.again=function(w){return this.thread.again(w)},et.prototype.again=function(w){for(var b,y=Date.now();this.__calls.length>0;){for(this.warnings=[],w!==!1&&(this.current_limit=this.session.limit);this.current_limit>0&&this.points.length>0&&this.head_point().goal!==null&&!S.type.is_error(this.head_point().goal);)if(this.current_limit--,this.step()===!0)return;var F=Date.now();this.cpu_time_last=F-y,this.cpu_time+=this.cpu_time_last;var J=this.__calls.shift();this.current_limit<=0?J(null):this.points.length===0?J(!1):S.type.is_error(this.head_point().goal)?(b=this.session.format_error(this.points.pop()),this.points=[],J(b)):(this.debugger&&this.debugger_states.push(this.head_point()),b=this.session.format_success(this.points.pop()),J(b))}},be.prototype.unfold=function(w){if(w.body===null)return!1;var b=w.head,y=w.body,F=y.select(),J=new et(this),X=[];J.add_goal(F),J.step();for(var $=J.points.length-1;$>=0;$--){var ie=J.points[$],Se=b.apply(ie.substitution),Re=y.replace(ie.goal);Re!==null&&(Re=Re.apply(ie.substitution)),X.push(new Ye(Se,Re))}var at=this.rules[b.indicator],dt=e(at,w);return X.length>0&&dt!==-1?(at.splice.apply(at,[dt,1].concat(X)),!0):!1},et.prototype.unfold=function(w){return this.session.unfold(w)},xe.prototype.interpret=function(w){return S.error.instantiation(w.level)},Ne.prototype.interpret=function(w){return this},H.prototype.interpret=function(w){return S.type.is_unitary_list(this)?this.args[0].interpret(w):S.operate(w,this)},xe.prototype.compare=function(w){return this.id<w.id?-1:this.id>w.id?1:0},Ne.prototype.compare=function(w){if(this.value===w.value&&this.is_float===w.is_float)return 0;if(this.value<w.value||this.value===w.value&&this.is_float&&!w.is_float)return-1;if(this.value>w.value)return 1},H.prototype.compare=function(w){if(this.args.length<w.args.length||this.args.length===w.args.length&&this.id<w.id)return-1;if(this.args.length>w.args.length||this.args.length===w.args.length&&this.id>w.id)return 1;for(var b=0;b<this.args.length;b++){var y=S.compare(this.args[b],w.args[b]);if(y!==0)return y}return 0},Fe.prototype.lookup=function(w){return this.links[w]?this.links[w]:null},Fe.prototype.filter=function(w){var b={};for(var y in this.links)if(this.links.hasOwnProperty(y)){var F=this.links[y];w(y,F)&&(b[y]=F)}return new Fe(b)},Fe.prototype.exclude=function(w){var b={};for(var y in this.links)this.links.hasOwnProperty(y)&&e(w,y)===-1&&(b[y]=this.links[y]);return new Fe(b)},Fe.prototype.add=function(w,b){this.links[w]=b},Fe.prototype.domain=function(w){var b=w===!0?function(J){return J}:function(J){return new xe(J)},y=[];for(var F in this.links)y.push(b(F));return y},xe.prototype.compile=function(){return'new pl.type.Var(\"'+this.id.toString()+'\")'},Ne.prototype.compile=function(){return\"new pl.type.Num(\"+this.value.toString()+\", \"+this.is_float.toString()+\")\"},H.prototype.compile=function(){return'new pl.type.Term(\"'+this.id.replace(/\"/g,'\\\\\"')+'\", ['+o(this.args,function(w){return w.compile()})+\"])\"},Ye.prototype.compile=function(){return\"new pl.type.Rule(\"+this.head.compile()+\", \"+(this.body===null?\"null\":this.body.compile())+\")\"},be.prototype.compile=function(){var w,b=[],y;for(var F in this.rules)if(this.rules.hasOwnProperty(F)){var J=this.rules[F];y=[],w='\"'+F+'\": [';for(var X=0;X<J.length;X++)y.push(J[X].compile());w+=y.join(),w+=\"]\",b.push(w)}return\"{\"+b.join()+\"};\"},xe.prototype.toJavaScript=function(){},Ne.prototype.toJavaScript=function(){return this.value},H.prototype.toJavaScript=function(){if(this.args.length===0&&this.indicator!==\"[]/0\")return this.id;if(S.type.is_list(this)){for(var w=[],b=this,y;b.indicator===\"./2\";){if(y=b.args[0].toJavaScript(),y===void 0)return;w.push(y),b=b.args[1]}if(b.indicator===\"[]/0\")return w}},Ye.prototype.singleton_variables=function(){var w=this.head.variables(),b={},y=[];this.body!==null&&(w=w.concat(this.body.variables()));for(var F=0;F<w.length;F++)b[w[F]]===void 0&&(b[w[F]]=0),b[w[F]]++;for(var J in b)J!==\"_\"&&b[J]===1&&y.push(J);return y};var S={__env:typeof gl<\"u\"&&gl.exports?global:window,module:{},version:t,parser:{tokenizer:U,expression:z},utils:{str_indicator:Z,codePointAt:n,fromCodePoint:u},statistics:{getCountTerms:function(){return ht}},fromJavaScript:{test:{boolean:function(w){return w===!0||w===!1},number:function(w){return typeof w==\"number\"},string:function(w){return typeof w==\"string\"},list:function(w){return w instanceof Array},variable:function(w){return w===void 0},any:function(w){return!0}},conversion:{boolean:function(w){return new H(w?\"true\":\"false\",[])},number:function(w){return new Ne(w,w%1!==0)},string:function(w){return new H(w,[])},list:function(w){for(var b=[],y,F=0;F<w.length;F++){if(y=S.fromJavaScript.apply(w[F]),y===void 0)return;b.push(y)}return g(b)},variable:function(w){return new xe(\"_\")},any:function(w){}},apply:function(w){for(var b in S.fromJavaScript.test)if(b!==\"any\"&&S.fromJavaScript.test[b](w))return S.fromJavaScript.conversion[b](w);return S.fromJavaScript.conversion.any(w)}},type:{Var:xe,Num:Ne,Term:H,Rule:Ye,State:ke,Stream:Te,Module:Ue,Thread:et,Session:be,Substitution:Fe,order:[xe,Ne,H,Te],compare:function(w,b){var y=e(S.type.order,w.constructor),F=e(S.type.order,b.constructor);if(y<F)return-1;if(y>F)return 1;if(w.constructor===Ne){if(w.is_float&&b.is_float)return 0;if(w.is_float)return-1;if(b.is_float)return 1}return 0},is_substitution:function(w){return w instanceof Fe},is_state:function(w){return w instanceof ke},is_rule:function(w){return w instanceof Ye},is_variable:function(w){return w instanceof xe},is_stream:function(w){return w instanceof Te},is_anonymous_var:function(w){return w instanceof xe&&w.id===\"_\"},is_callable:function(w){return w instanceof H},is_number:function(w){return w instanceof Ne},is_integer:function(w){return w instanceof Ne&&!w.is_float},is_float:function(w){return w instanceof Ne&&w.is_float},is_term:function(w){return w instanceof H},is_atom:function(w){return w instanceof H&&w.args.length===0},is_ground:function(w){if(w instanceof xe)return!1;if(w instanceof H){for(var b=0;b<w.args.length;b++)if(!S.type.is_ground(w.args[b]))return!1}return!0},is_atomic:function(w){return w instanceof H&&w.args.length===0||w instanceof Ne},is_compound:function(w){return w instanceof H&&w.args.length>0},is_list:function(w){return w instanceof H&&(w.indicator===\"[]/0\"||w.indicator===\"./2\")},is_empty_list:function(w){return w instanceof H&&w.indicator===\"[]/0\"},is_non_empty_list:function(w){return w instanceof H&&w.indicator===\"./2\"},is_fully_list:function(w){for(;w instanceof H&&w.indicator===\"./2\";)w=w.args[1];return w instanceof xe||w instanceof H&&w.indicator===\"[]/0\"},is_instantiated_list:function(w){for(;w instanceof H&&w.indicator===\"./2\";)w=w.args[1];return w instanceof H&&w.indicator===\"[]/0\"},is_unitary_list:function(w){return w instanceof H&&w.indicator===\"./2\"&&w.args[1]instanceof H&&w.args[1].indicator===\"[]/0\"},is_character:function(w){return w instanceof H&&(w.id.length===1||w.id.length>0&&w.id.length<=2&&n(w.id,0)>=65536)},is_character_code:function(w){return w instanceof Ne&&!w.is_float&&w.value>=0&&w.value<=1114111},is_byte:function(w){return w instanceof Ne&&!w.is_float&&w.value>=0&&w.value<=255},is_operator:function(w){return w instanceof H&&S.arithmetic.evaluation[w.indicator]},is_directive:function(w){return w instanceof H&&S.directive[w.indicator]!==void 0},is_builtin:function(w){return w instanceof H&&S.predicate[w.indicator]!==void 0},is_error:function(w){return w instanceof H&&w.indicator===\"throw/1\"},is_predicate_indicator:function(w){return w instanceof H&&w.indicator===\"//2\"&&w.args[0]instanceof H&&w.args[0].args.length===0&&w.args[1]instanceof Ne&&w.args[1].is_float===!1},is_flag:function(w){return w instanceof H&&w.args.length===0&&S.flag[w.id]!==void 0},is_value_flag:function(w,b){if(!S.type.is_flag(w))return!1;for(var y in S.flag[w.id].allowed)if(S.flag[w.id].allowed.hasOwnProperty(y)&&S.flag[w.id].allowed[y].equals(b))return!0;return!1},is_io_mode:function(w){return S.type.is_atom(w)&&[\"read\",\"write\",\"append\"].indexOf(w.id)!==-1},is_stream_option:function(w){return S.type.is_term(w)&&(w.indicator===\"alias/1\"&&S.type.is_atom(w.args[0])||w.indicator===\"reposition/1\"&&S.type.is_atom(w.args[0])&&(w.args[0].id===\"true\"||w.args[0].id===\"false\")||w.indicator===\"type/1\"&&S.type.is_atom(w.args[0])&&(w.args[0].id===\"text\"||w.args[0].id===\"binary\")||w.indicator===\"eof_action/1\"&&S.type.is_atom(w.args[0])&&(w.args[0].id===\"error\"||w.args[0].id===\"eof_code\"||w.args[0].id===\"reset\"))},is_stream_position:function(w){return S.type.is_integer(w)&&w.value>=0||S.type.is_atom(w)&&(w.id===\"end_of_stream\"||w.id===\"past_end_of_stream\")},is_stream_property:function(w){return S.type.is_term(w)&&(w.indicator===\"input/0\"||w.indicator===\"output/0\"||w.indicator===\"alias/1\"&&(S.type.is_variable(w.args[0])||S.type.is_atom(w.args[0]))||w.indicator===\"file_name/1\"&&(S.type.is_variable(w.args[0])||S.type.is_atom(w.args[0]))||w.indicator===\"position/1\"&&(S.type.is_variable(w.args[0])||S.type.is_stream_position(w.args[0]))||w.indicator===\"reposition/1\"&&(S.type.is_variable(w.args[0])||S.type.is_atom(w.args[0])&&(w.args[0].id===\"true\"||w.args[0].id===\"false\"))||w.indicator===\"type/1\"&&(S.type.is_variable(w.args[0])||S.type.is_atom(w.args[0])&&(w.args[0].id===\"text\"||w.args[0].id===\"binary\"))||w.indicator===\"mode/1\"&&(S.type.is_variable(w.args[0])||S.type.is_atom(w.args[0])&&(w.args[0].id===\"read\"||w.args[0].id===\"write\"||w.args[0].id===\"append\"))||w.indicator===\"eof_action/1\"&&(S.type.is_variable(w.args[0])||S.type.is_atom(w.args[0])&&(w.args[0].id===\"error\"||w.args[0].id===\"eof_code\"||w.args[0].id===\"reset\"))||w.indicator===\"end_of_stream/1\"&&(S.type.is_variable(w.args[0])||S.type.is_atom(w.args[0])&&(w.args[0].id===\"at\"||w.args[0].id===\"past\"||w.args[0].id===\"not\")))},is_streamable:function(w){return w.__proto__.stream!==void 0},is_read_option:function(w){return S.type.is_term(w)&&[\"variables/1\",\"variable_names/1\",\"singletons/1\"].indexOf(w.indicator)!==-1},is_write_option:function(w){return S.type.is_term(w)&&(w.indicator===\"quoted/1\"&&S.type.is_atom(w.args[0])&&(w.args[0].id===\"true\"||w.args[0].id===\"false\")||w.indicator===\"ignore_ops/1\"&&S.type.is_atom(w.args[0])&&(w.args[0].id===\"true\"||w.args[0].id===\"false\")||w.indicator===\"numbervars/1\"&&S.type.is_atom(w.args[0])&&(w.args[0].id===\"true\"||w.args[0].id===\"false\"))},is_close_option:function(w){return S.type.is_term(w)&&w.indicator===\"force/1\"&&S.type.is_atom(w.args[0])&&(w.args[0].id===\"true\"||w.args[0].id===\"false\")},is_modifiable_flag:function(w){return S.type.is_flag(w)&&S.flag[w.id].changeable},is_module:function(w){return w instanceof H&&w.indicator===\"library/1\"&&w.args[0]instanceof H&&w.args[0].args.length===0&&S.module[w.args[0].id]!==void 0}},arithmetic:{evaluation:{\"e/0\":{type_args:null,type_result:!0,fn:function(w){return Math.E}},\"pi/0\":{type_args:null,type_result:!0,fn:function(w){return Math.PI}},\"tau/0\":{type_args:null,type_result:!0,fn:function(w){return 2*Math.PI}},\"epsilon/0\":{type_args:null,type_result:!0,fn:function(w){return Number.EPSILON}},\"+/1\":{type_args:null,type_result:null,fn:function(w,b){return w}},\"-/1\":{type_args:null,type_result:null,fn:function(w,b){return-w}},\"\\\\/1\":{type_args:!1,type_result:!1,fn:function(w,b){return~w}},\"abs/1\":{type_args:null,type_result:null,fn:function(w,b){return Math.abs(w)}},\"sign/1\":{type_args:null,type_result:null,fn:function(w,b){return Math.sign(w)}},\"float_integer_part/1\":{type_args:!0,type_result:!1,fn:function(w,b){return parseInt(w)}},\"float_fractional_part/1\":{type_args:!0,type_result:!0,fn:function(w,b){return w-parseInt(w)}},\"float/1\":{type_args:null,type_result:!0,fn:function(w,b){return parseFloat(w)}},\"floor/1\":{type_args:!0,type_result:!1,fn:function(w,b){return Math.floor(w)}},\"truncate/1\":{type_args:!0,type_result:!1,fn:function(w,b){return parseInt(w)}},\"round/1\":{type_args:!0,type_result:!1,fn:function(w,b){return Math.round(w)}},\"ceiling/1\":{type_args:!0,type_result:!1,fn:function(w,b){return Math.ceil(w)}},\"sin/1\":{type_args:null,type_result:!0,fn:function(w,b){return Math.sin(w)}},\"cos/1\":{type_args:null,type_result:!0,fn:function(w,b){return Math.cos(w)}},\"tan/1\":{type_args:null,type_result:!0,fn:function(w,b){return Math.tan(w)}},\"asin/1\":{type_args:null,type_result:!0,fn:function(w,b){return Math.asin(w)}},\"acos/1\":{type_args:null,type_result:!0,fn:function(w,b){return Math.acos(w)}},\"atan/1\":{type_args:null,type_result:!0,fn:function(w,b){return Math.atan(w)}},\"atan2/2\":{type_args:null,type_result:!0,fn:function(w,b,y){return Math.atan2(w,b)}},\"exp/1\":{type_args:null,type_result:!0,fn:function(w,b){return Math.exp(w)}},\"sqrt/1\":{type_args:null,type_result:!0,fn:function(w,b){return Math.sqrt(w)}},\"log/1\":{type_args:null,type_result:!0,fn:function(w,b){return w>0?Math.log(w):S.error.evaluation(\"undefined\",b.__call_indicator)}},\"+/2\":{type_args:null,type_result:null,fn:function(w,b,y){return w+b}},\"-/2\":{type_args:null,type_result:null,fn:function(w,b,y){return w-b}},\"*/2\":{type_args:null,type_result:null,fn:function(w,b,y){return w*b}},\"//2\":{type_args:null,type_result:!0,fn:function(w,b,y){return b?w/b:S.error.evaluation(\"zero_division\",y.__call_indicator)}},\"///2\":{type_args:!1,type_result:!1,fn:function(w,b,y){return b?parseInt(w/b):S.error.evaluation(\"zero_division\",y.__call_indicator)}},\"**/2\":{type_args:null,type_result:!0,fn:function(w,b,y){return Math.pow(w,b)}},\"^/2\":{type_args:null,type_result:null,fn:function(w,b,y){return Math.pow(w,b)}},\"<</2\":{type_args:!1,type_result:!1,fn:function(w,b,y){return w<<b}},\">>/2\":{type_args:!1,type_result:!1,fn:function(w,b,y){return w>>b}},\"/\\\\/2\":{type_args:!1,type_result:!1,fn:function(w,b,y){return w&b}},\"\\\\//2\":{type_args:!1,type_result:!1,fn:function(w,b,y){return w|b}},\"xor/2\":{type_args:!1,type_result:!1,fn:function(w,b,y){return w^b}},\"rem/2\":{type_args:!1,type_result:!1,fn:function(w,b,y){return b?w%b:S.error.evaluation(\"zero_division\",y.__call_indicator)}},\"mod/2\":{type_args:!1,type_result:!1,fn:function(w,b,y){return b?w-parseInt(w/b)*b:S.error.evaluation(\"zero_division\",y.__call_indicator)}},\"max/2\":{type_args:null,type_result:null,fn:function(w,b,y){return Math.max(w,b)}},\"min/2\":{type_args:null,type_result:null,fn:function(w,b,y){return Math.min(w,b)}}}},directive:{\"dynamic/1\":function(w,b){var y=b.args[0];if(S.type.is_variable(y))w.throw_error(S.error.instantiation(b.indicator));else if(!S.type.is_compound(y)||y.indicator!==\"//2\")w.throw_error(S.error.type(\"predicate_indicator\",y,b.indicator));else if(S.type.is_variable(y.args[0])||S.type.is_variable(y.args[1]))w.throw_error(S.error.instantiation(b.indicator));else if(!S.type.is_atom(y.args[0]))w.throw_error(S.error.type(\"atom\",y.args[0],b.indicator));else if(!S.type.is_integer(y.args[1]))w.throw_error(S.error.type(\"integer\",y.args[1],b.indicator));else{var F=b.args[0].args[0].id+\"/\"+b.args[0].args[1].value;w.session.public_predicates[F]=!0,w.session.rules[F]||(w.session.rules[F]=[])}},\"multifile/1\":function(w,b){var y=b.args[0];S.type.is_variable(y)?w.throw_error(S.error.instantiation(b.indicator)):!S.type.is_compound(y)||y.indicator!==\"//2\"?w.throw_error(S.error.type(\"predicate_indicator\",y,b.indicator)):S.type.is_variable(y.args[0])||S.type.is_variable(y.args[1])?w.throw_error(S.error.instantiation(b.indicator)):S.type.is_atom(y.args[0])?S.type.is_integer(y.args[1])?w.session.multifile_predicates[b.args[0].args[0].id+\"/\"+b.args[0].args[1].value]=!0:w.throw_error(S.error.type(\"integer\",y.args[1],b.indicator)):w.throw_error(S.error.type(\"atom\",y.args[0],b.indicator))},\"set_prolog_flag/2\":function(w,b){var y=b.args[0],F=b.args[1];S.type.is_variable(y)||S.type.is_variable(F)?w.throw_error(S.error.instantiation(b.indicator)):S.type.is_atom(y)?S.type.is_flag(y)?S.type.is_value_flag(y,F)?S.type.is_modifiable_flag(y)?w.session.flag[y.id]=F:w.throw_error(S.error.permission(\"modify\",\"flag\",y)):w.throw_error(S.error.domain(\"flag_value\",new H(\"+\",[y,F]),b.indicator)):w.throw_error(S.error.domain(\"prolog_flag\",y,b.indicator)):w.throw_error(S.error.type(\"atom\",y,b.indicator))},\"use_module/1\":function(w,b){var y=b.args[0];if(S.type.is_variable(y))w.throw_error(S.error.instantiation(b.indicator));else if(!S.type.is_term(y))w.throw_error(S.error.type(\"term\",y,b.indicator));else if(S.type.is_module(y)){var F=y.args[0].id;e(w.session.modules,F)===-1&&w.session.modules.push(F)}},\"char_conversion/2\":function(w,b){var y=b.args[0],F=b.args[1];S.type.is_variable(y)||S.type.is_variable(F)?w.throw_error(S.error.instantiation(b.indicator)):S.type.is_character(y)?S.type.is_character(F)?y.id===F.id?delete w.session.__char_conversion[y.id]:w.session.__char_conversion[y.id]=F.id:w.throw_error(S.error.type(\"character\",F,b.indicator)):w.throw_error(S.error.type(\"character\",y,b.indicator))},\"op/3\":function(w,b){var y=b.args[0],F=b.args[1],J=b.args[2];if(S.type.is_variable(y)||S.type.is_variable(F)||S.type.is_variable(J))w.throw_error(S.error.instantiation(b.indicator));else if(!S.type.is_integer(y))w.throw_error(S.error.type(\"integer\",y,b.indicator));else if(!S.type.is_atom(F))w.throw_error(S.error.type(\"atom\",F,b.indicator));else if(!S.type.is_atom(J))w.throw_error(S.error.type(\"atom\",J,b.indicator));else if(y.value<0||y.value>1200)w.throw_error(S.error.domain(\"operator_priority\",y,b.indicator));else if(J.id===\",\")w.throw_error(S.error.permission(\"modify\",\"operator\",J,b.indicator));else if(J.id===\"|\"&&(y.value<1001||F.id.length!==3))w.throw_error(S.error.permission(\"modify\",\"operator\",J,b.indicator));else if([\"fy\",\"fx\",\"yf\",\"xf\",\"xfx\",\"yfx\",\"xfy\"].indexOf(F.id)===-1)w.throw_error(S.error.domain(\"operator_specifier\",F,b.indicator));else{var X={prefix:null,infix:null,postfix:null};for(var $ in w.session.__operators)if(w.session.__operators.hasOwnProperty($)){var ie=w.session.__operators[$][J.id];ie&&(e(ie,\"fx\")!==-1&&(X.prefix={priority:$,type:\"fx\"}),e(ie,\"fy\")!==-1&&(X.prefix={priority:$,type:\"fy\"}),e(ie,\"xf\")!==-1&&(X.postfix={priority:$,type:\"xf\"}),e(ie,\"yf\")!==-1&&(X.postfix={priority:$,type:\"yf\"}),e(ie,\"xfx\")!==-1&&(X.infix={priority:$,type:\"xfx\"}),e(ie,\"xfy\")!==-1&&(X.infix={priority:$,type:\"xfy\"}),e(ie,\"yfx\")!==-1&&(X.infix={priority:$,type:\"yfx\"}))}var Se;switch(F.id){case\"fy\":case\"fx\":Se=\"prefix\";break;case\"yf\":case\"xf\":Se=\"postfix\";break;default:Se=\"infix\";break}if(((X.prefix&&Se===\"prefix\"||X.postfix&&Se===\"postfix\"||X.infix&&Se===\"infix\")&&X[Se].type!==F.id||X.infix&&Se===\"postfix\"||X.postfix&&Se===\"infix\")&&y.value!==0)w.throw_error(S.error.permission(\"create\",\"operator\",J,b.indicator));else return X[Se]&&(me(w.session.__operators[X[Se].priority][J.id],F.id),w.session.__operators[X[Se].priority][J.id].length===0&&delete w.session.__operators[X[Se].priority][J.id]),y.value>0&&(w.session.__operators[y.value]||(w.session.__operators[y.value.toString()]={}),w.session.__operators[y.value][J.id]||(w.session.__operators[y.value][J.id]=[]),w.session.__operators[y.value][J.id].push(F.id)),!0}}},predicate:{\"op/3\":function(w,b,y){S.directive[\"op/3\"](w,y)&&w.success(b)},\"current_op/3\":function(w,b,y){var F=y.args[0],J=y.args[1],X=y.args[2],$=[];for(var ie in w.session.__operators)for(var Se in w.session.__operators[ie])for(var Re=0;Re<w.session.__operators[ie][Se].length;Re++)$.push(new ke(b.goal.replace(new H(\",\",[new H(\"=\",[new Ne(ie,!1),F]),new H(\",\",[new H(\"=\",[new H(w.session.__operators[ie][Se][Re],[]),J]),new H(\"=\",[new H(Se,[]),X])])])),b.substitution,b));w.prepend($)},\";/2\":function(w,b,y){if(S.type.is_term(y.args[0])&&y.args[0].indicator===\"->/2\"){var F=w.points,J=w.session.format_success,X=w.session.format_error;w.session.format_success=function(Re){return Re.substitution},w.session.format_error=function(Re){return Re.goal},w.points=[new ke(y.args[0].args[0],b.substitution,b)];var $=function(Re){w.points=F,w.session.format_success=J,w.session.format_error=X,Re===!1?w.prepend([new ke(b.goal.replace(y.args[1]),b.substitution,b)]):S.type.is_error(Re)?w.throw_error(Re.args[0]):Re===null?(w.prepend([b]),w.__calls.shift()(null)):w.prepend([new ke(b.goal.replace(y.args[0].args[1]).apply(Re),b.substitution.apply(Re),b)])};w.__calls.unshift($)}else{var ie=new ke(b.goal.replace(y.args[0]),b.substitution,b),Se=new ke(b.goal.replace(y.args[1]),b.substitution,b);w.prepend([ie,Se])}},\"!/0\":function(w,b,y){var F,J,X=[];for(F=b,J=null;F.parent!==null&&F.parent.goal.search(y);)if(J=F,F=F.parent,F.goal!==null){var $=F.goal.select();if($&&$.id===\"call\"&&$.search(y)){F=J;break}}for(var ie=w.points.length-1;ie>=0;ie--){for(var Se=w.points[ie],Re=Se.parent;Re!==null&&Re!==F.parent;)Re=Re.parent;Re===null&&Re!==F.parent&&X.push(Se)}w.points=X.reverse(),w.success(b)},\"\\\\+/1\":function(w,b,y){var F=y.args[0];S.type.is_variable(F)?w.throw_error(S.error.instantiation(w.level)):S.type.is_callable(F)?w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\",\",[new H(\"call\",[F]),new H(\"!\",[])]),new H(\"fail\",[])])),b.substitution,b),new ke(b.goal.replace(null),b.substitution,b)]):w.throw_error(S.error.type(\"callable\",F,w.level))},\"->/2\":function(w,b,y){var F=b.goal.replace(new H(\",\",[y.args[0],new H(\",\",[new H(\"!\"),y.args[1]])]));w.prepend([new ke(F,b.substitution,b)])},\"fail/0\":function(w,b,y){},\"false/0\":function(w,b,y){},\"true/0\":function(w,b,y){w.success(b)},\"call/1\":ne(1),\"call/2\":ne(2),\"call/3\":ne(3),\"call/4\":ne(4),\"call/5\":ne(5),\"call/6\":ne(6),\"call/7\":ne(7),\"call/8\":ne(8),\"once/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"call\",[F]),new H(\"!\",[])])),b.substitution,b)])},\"forall/2\":function(w,b,y){var F=y.args[0],J=y.args[1];w.prepend([new ke(b.goal.replace(new H(\"\\\\+\",[new H(\",\",[new H(\"call\",[F]),new H(\"\\\\+\",[new H(\"call\",[J])])])])),b.substitution,b)])},\"repeat/0\":function(w,b,y){w.prepend([new ke(b.goal.replace(null),b.substitution,b),b])},\"throw/1\":function(w,b,y){S.type.is_variable(y.args[0])?w.throw_error(S.error.instantiation(w.level)):w.throw_error(y.args[0])},\"catch/3\":function(w,b,y){var F=w.points;w.points=[],w.prepend([new ke(y.args[0],b.substitution,b)]);var J=w.session.format_success,X=w.session.format_error;w.session.format_success=function(ie){return ie.substitution},w.session.format_error=function(ie){return ie.goal};var $=function(ie){var Se=w.points;if(w.points=F,w.session.format_success=J,w.session.format_error=X,S.type.is_error(ie)){for(var Re=[],at=w.points.length-1;at>=0;at--){for(var tr=w.points[at],dt=tr.parent;dt!==null&&dt!==b.parent;)dt=dt.parent;dt===null&&dt!==b.parent&&Re.push(tr)}w.points=Re;var jt=w.get_flag(\"occurs_check\").indicator===\"true/0\",tr=new ke,bt=S.unify(ie.args[0],y.args[1],jt);bt!==null?(tr.substitution=b.substitution.apply(bt),tr.goal=b.goal.replace(y.args[2]).apply(bt),tr.parent=b,w.prepend([tr])):w.throw_error(ie.args[0])}else if(ie!==!1){for(var ln=ie===null?[]:[new ke(b.goal.apply(ie).replace(null),b.substitution.apply(ie),b)],kr=[],at=Se.length-1;at>=0;at--){kr.push(Se[at]);var mr=Se[at].goal!==null?Se[at].goal.select():null;if(S.type.is_term(mr)&&mr.indicator===\"!/0\")break}var Sr=o(kr,function(Kr){return Kr.goal===null&&(Kr.goal=new H(\"true\",[])),Kr=new ke(b.goal.replace(new H(\"catch\",[Kr.goal,y.args[1],y.args[2]])),b.substitution.apply(Kr.substitution),Kr.parent),Kr.exclude=y.args[0].variables(),Kr}).reverse();w.prepend(Sr),w.prepend(ln),ie===null&&(this.current_limit=0,w.__calls.shift()(null))}};w.__calls.unshift($)},\"=/2\":function(w,b,y){var F=w.get_flag(\"occurs_check\").indicator===\"true/0\",J=new ke,X=S.unify(y.args[0],y.args[1],F);X!==null&&(J.goal=b.goal.apply(X).replace(null),J.substitution=b.substitution.apply(X),J.parent=b,w.prepend([J]))},\"unify_with_occurs_check/2\":function(w,b,y){var F=new ke,J=S.unify(y.args[0],y.args[1],!0);J!==null&&(F.goal=b.goal.apply(J).replace(null),F.substitution=b.substitution.apply(J),F.parent=b,w.prepend([F]))},\"\\\\=/2\":function(w,b,y){var F=w.get_flag(\"occurs_check\").indicator===\"true/0\",J=S.unify(y.args[0],y.args[1],F);J===null&&w.success(b)},\"subsumes_term/2\":function(w,b,y){var F=w.get_flag(\"occurs_check\").indicator===\"true/0\",J=S.unify(y.args[1],y.args[0],F);J!==null&&y.args[1].apply(J).equals(y.args[1])&&w.success(b)},\"findall/3\":function(w,b,y){var F=y.args[0],J=y.args[1],X=y.args[2];if(S.type.is_variable(J))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_callable(J))w.throw_error(S.error.type(\"callable\",J,y.indicator));else if(!S.type.is_variable(X)&&!S.type.is_list(X))w.throw_error(S.error.type(\"list\",X,y.indicator));else{var $=w.next_free_variable(),ie=new H(\",\",[J,new H(\"=\",[$,F])]),Se=w.points,Re=w.session.limit,at=w.session.format_success;w.session.format_success=function(tr){return tr.substitution},w.add_goal(ie,!0,b);var dt=[],jt=function(tr){if(tr!==!1&&tr!==null&&!S.type.is_error(tr))w.__calls.unshift(jt),dt.push(tr.links[$.id]),w.session.limit=w.current_limit;else if(w.points=Se,w.session.limit=Re,w.session.format_success=at,S.type.is_error(tr))w.throw_error(tr.args[0]);else if(w.current_limit>0){for(var bt=new H(\"[]\"),ln=dt.length-1;ln>=0;ln--)bt=new H(\".\",[dt[ln],bt]);w.prepend([new ke(b.goal.replace(new H(\"=\",[X,bt])),b.substitution,b)])}};w.__calls.unshift(jt)}},\"bagof/3\":function(w,b,y){var F,J=y.args[0],X=y.args[1],$=y.args[2];if(S.type.is_variable(X))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_callable(X))w.throw_error(S.error.type(\"callable\",X,y.indicator));else if(!S.type.is_variable($)&&!S.type.is_list($))w.throw_error(S.error.type(\"list\",$,y.indicator));else{var ie=w.next_free_variable(),Se;X.indicator===\"^/2\"?(Se=X.args[0].variables(),X=X.args[1]):Se=[],Se=Se.concat(J.variables());for(var Re=X.variables().filter(function(Sr){return e(Se,Sr)===-1}),at=new H(\"[]\"),dt=Re.length-1;dt>=0;dt--)at=new H(\".\",[new xe(Re[dt]),at]);var jt=new H(\",\",[X,new H(\"=\",[ie,new H(\",\",[at,J])])]),tr=w.points,bt=w.session.limit,ln=w.session.format_success;w.session.format_success=function(Sr){return Sr.substitution},w.add_goal(jt,!0,b);var kr=[],mr=function(Sr){if(Sr!==!1&&Sr!==null&&!S.type.is_error(Sr)){w.__calls.unshift(mr);var Kr=!1,Kn=Sr.links[ie.id].args[0],Ms=Sr.links[ie.id].args[1];for(var Ri in kr)if(kr.hasOwnProperty(Ri)){var gs=kr[Ri];if(gs.variables.equals(Kn)){gs.answers.push(Ms),Kr=!0;break}}Kr||kr.push({variables:Kn,answers:[Ms]}),w.session.limit=w.current_limit}else if(w.points=tr,w.session.limit=bt,w.session.format_success=ln,S.type.is_error(Sr))w.throw_error(Sr.args[0]);else if(w.current_limit>0){for(var io=[],Pi=0;Pi<kr.length;Pi++){Sr=kr[Pi].answers;for(var Os=new H(\"[]\"),so=Sr.length-1;so>=0;so--)Os=new H(\".\",[Sr[so],Os]);io.push(new ke(b.goal.replace(new H(\",\",[new H(\"=\",[at,kr[Pi].variables]),new H(\"=\",[$,Os])])),b.substitution,b))}w.prepend(io)}};w.__calls.unshift(mr)}},\"setof/3\":function(w,b,y){var F,J=y.args[0],X=y.args[1],$=y.args[2];if(S.type.is_variable(X))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_callable(X))w.throw_error(S.error.type(\"callable\",X,y.indicator));else if(!S.type.is_variable($)&&!S.type.is_list($))w.throw_error(S.error.type(\"list\",$,y.indicator));else{var ie=w.next_free_variable(),Se;X.indicator===\"^/2\"?(Se=X.args[0].variables(),X=X.args[1]):Se=[],Se=Se.concat(J.variables());for(var Re=X.variables().filter(function(Sr){return e(Se,Sr)===-1}),at=new H(\"[]\"),dt=Re.length-1;dt>=0;dt--)at=new H(\".\",[new xe(Re[dt]),at]);var jt=new H(\",\",[X,new H(\"=\",[ie,new H(\",\",[at,J])])]),tr=w.points,bt=w.session.limit,ln=w.session.format_success;w.session.format_success=function(Sr){return Sr.substitution},w.add_goal(jt,!0,b);var kr=[],mr=function(Sr){if(Sr!==!1&&Sr!==null&&!S.type.is_error(Sr)){w.__calls.unshift(mr);var Kr=!1,Kn=Sr.links[ie.id].args[0],Ms=Sr.links[ie.id].args[1];for(var Ri in kr)if(kr.hasOwnProperty(Ri)){var gs=kr[Ri];if(gs.variables.equals(Kn)){gs.answers.push(Ms),Kr=!0;break}}Kr||kr.push({variables:Kn,answers:[Ms]}),w.session.limit=w.current_limit}else if(w.points=tr,w.session.limit=bt,w.session.format_success=ln,S.type.is_error(Sr))w.throw_error(Sr.args[0]);else if(w.current_limit>0){for(var io=[],Pi=0;Pi<kr.length;Pi++){Sr=kr[Pi].answers.sort(S.compare);for(var Os=new H(\"[]\"),so=Sr.length-1;so>=0;so--)Os=new H(\".\",[Sr[so],Os]);io.push(new ke(b.goal.replace(new H(\",\",[new H(\"=\",[at,kr[Pi].variables]),new H(\"=\",[$,Os])])),b.substitution,b))}w.prepend(io)}};w.__calls.unshift(mr)}},\"functor/3\":function(w,b,y){var F,J=y.args[0],X=y.args[1],$=y.args[2];if(S.type.is_variable(J)&&(S.type.is_variable(X)||S.type.is_variable($)))w.throw_error(S.error.instantiation(\"functor/3\"));else if(!S.type.is_variable($)&&!S.type.is_integer($))w.throw_error(S.error.type(\"integer\",y.args[2],\"functor/3\"));else if(!S.type.is_variable(X)&&!S.type.is_atomic(X))w.throw_error(S.error.type(\"atomic\",y.args[1],\"functor/3\"));else if(S.type.is_integer(X)&&S.type.is_integer($)&&$.value!==0)w.throw_error(S.error.type(\"atom\",y.args[1],\"functor/3\"));else if(S.type.is_variable(J)){if(y.args[2].value>=0){for(var ie=[],Se=0;Se<$.value;Se++)ie.push(w.next_free_variable());var Re=S.type.is_integer(X)?X:new H(X.id,ie);w.prepend([new ke(b.goal.replace(new H(\"=\",[J,Re])),b.substitution,b)])}}else{var at=S.type.is_integer(J)?J:new H(J.id,[]),dt=S.type.is_integer(J)?new Ne(0,!1):new Ne(J.args.length,!1),jt=new H(\",\",[new H(\"=\",[at,X]),new H(\"=\",[dt,$])]);w.prepend([new ke(b.goal.replace(jt),b.substitution,b)])}},\"arg/3\":function(w,b,y){if(S.type.is_variable(y.args[0])||S.type.is_variable(y.args[1]))w.throw_error(S.error.instantiation(y.indicator));else if(y.args[0].value<0)w.throw_error(S.error.domain(\"not_less_than_zero\",y.args[0],y.indicator));else if(!S.type.is_compound(y.args[1]))w.throw_error(S.error.type(\"compound\",y.args[1],y.indicator));else{var F=y.args[0].value;if(F>0&&F<=y.args[1].args.length){var J=new H(\"=\",[y.args[1].args[F-1],y.args[2]]);w.prepend([new ke(b.goal.replace(J),b.substitution,b)])}}},\"=../2\":function(w,b,y){var F;if(S.type.is_variable(y.args[0])&&(S.type.is_variable(y.args[1])||S.type.is_non_empty_list(y.args[1])&&S.type.is_variable(y.args[1].args[0])))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_fully_list(y.args[1]))w.throw_error(S.error.type(\"list\",y.args[1],y.indicator));else if(S.type.is_variable(y.args[0])){if(!S.type.is_variable(y.args[1])){var X=[];for(F=y.args[1].args[1];F.indicator===\"./2\";)X.push(F.args[0]),F=F.args[1];S.type.is_variable(y.args[0])&&S.type.is_variable(F)?w.throw_error(S.error.instantiation(y.indicator)):X.length===0&&S.type.is_compound(y.args[1].args[0])?w.throw_error(S.error.type(\"atomic\",y.args[1].args[0],y.indicator)):X.length>0&&(S.type.is_compound(y.args[1].args[0])||S.type.is_number(y.args[1].args[0]))?w.throw_error(S.error.type(\"atom\",y.args[1].args[0],y.indicator)):X.length===0?w.prepend([new ke(b.goal.replace(new H(\"=\",[y.args[1].args[0],y.args[0]],b)),b.substitution,b)]):w.prepend([new ke(b.goal.replace(new H(\"=\",[new H(y.args[1].args[0].id,X),y.args[0]])),b.substitution,b)])}}else{if(S.type.is_atomic(y.args[0]))F=new H(\".\",[y.args[0],new H(\"[]\")]);else{F=new H(\"[]\");for(var J=y.args[0].args.length-1;J>=0;J--)F=new H(\".\",[y.args[0].args[J],F]);F=new H(\".\",[new H(y.args[0].id),F])}w.prepend([new ke(b.goal.replace(new H(\"=\",[F,y.args[1]])),b.substitution,b)])}},\"copy_term/2\":function(w,b,y){var F=y.args[0].rename(w);w.prepend([new ke(b.goal.replace(new H(\"=\",[F,y.args[1]])),b.substitution,b.parent)])},\"term_variables/2\":function(w,b,y){var F=y.args[0],J=y.args[1];if(!S.type.is_fully_list(J))w.throw_error(S.error.type(\"list\",J,y.indicator));else{var X=g(o(we(F.variables()),function($){return new xe($)}));w.prepend([new ke(b.goal.replace(new H(\"=\",[J,X])),b.substitution,b)])}},\"clause/2\":function(w,b,y){if(S.type.is_variable(y.args[0]))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_callable(y.args[0]))w.throw_error(S.error.type(\"callable\",y.args[0],y.indicator));else if(!S.type.is_variable(y.args[1])&&!S.type.is_callable(y.args[1]))w.throw_error(S.error.type(\"callable\",y.args[1],y.indicator));else if(w.session.rules[y.args[0].indicator]!==void 0)if(w.is_public_predicate(y.args[0].indicator)){var F=[];for(var J in w.session.rules[y.args[0].indicator])if(w.session.rules[y.args[0].indicator].hasOwnProperty(J)){var X=w.session.rules[y.args[0].indicator][J];w.session.renamed_variables={},X=X.rename(w),X.body===null&&(X.body=new H(\"true\"));var $=new H(\",\",[new H(\"=\",[X.head,y.args[0]]),new H(\"=\",[X.body,y.args[1]])]);F.push(new ke(b.goal.replace($),b.substitution,b))}w.prepend(F)}else w.throw_error(S.error.permission(\"access\",\"private_procedure\",y.args[0].indicator,y.indicator))},\"current_predicate/1\":function(w,b,y){var F=y.args[0];if(!S.type.is_variable(F)&&(!S.type.is_compound(F)||F.indicator!==\"//2\"))w.throw_error(S.error.type(\"predicate_indicator\",F,y.indicator));else if(!S.type.is_variable(F)&&!S.type.is_variable(F.args[0])&&!S.type.is_atom(F.args[0]))w.throw_error(S.error.type(\"atom\",F.args[0],y.indicator));else if(!S.type.is_variable(F)&&!S.type.is_variable(F.args[1])&&!S.type.is_integer(F.args[1]))w.throw_error(S.error.type(\"integer\",F.args[1],y.indicator));else{var J=[];for(var X in w.session.rules)if(w.session.rules.hasOwnProperty(X)){var $=X.lastIndexOf(\"/\"),ie=X.substr(0,$),Se=parseInt(X.substr($+1,X.length-($+1))),Re=new H(\"/\",[new H(ie),new Ne(Se,!1)]),at=new H(\"=\",[Re,F]);J.push(new ke(b.goal.replace(at),b.substitution,b))}w.prepend(J)}},\"asserta/1\":function(w,b,y){if(S.type.is_variable(y.args[0]))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_callable(y.args[0]))w.throw_error(S.error.type(\"callable\",y.args[0],y.indicator));else{var F,J;y.args[0].indicator===\":-/2\"?(F=y.args[0].args[0],J=Ee(y.args[0].args[1])):(F=y.args[0],J=null),S.type.is_callable(F)?J!==null&&!S.type.is_callable(J)?w.throw_error(S.error.type(\"callable\",J,y.indicator)):w.is_public_predicate(F.indicator)?(w.session.rules[F.indicator]===void 0&&(w.session.rules[F.indicator]=[]),w.session.public_predicates[F.indicator]=!0,w.session.rules[F.indicator]=[new Ye(F,J,!0)].concat(w.session.rules[F.indicator]),w.success(b)):w.throw_error(S.error.permission(\"modify\",\"static_procedure\",F.indicator,y.indicator)):w.throw_error(S.error.type(\"callable\",F,y.indicator))}},\"assertz/1\":function(w,b,y){if(S.type.is_variable(y.args[0]))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_callable(y.args[0]))w.throw_error(S.error.type(\"callable\",y.args[0],y.indicator));else{var F,J;y.args[0].indicator===\":-/2\"?(F=y.args[0].args[0],J=Ee(y.args[0].args[1])):(F=y.args[0],J=null),S.type.is_callable(F)?J!==null&&!S.type.is_callable(J)?w.throw_error(S.error.type(\"callable\",J,y.indicator)):w.is_public_predicate(F.indicator)?(w.session.rules[F.indicator]===void 0&&(w.session.rules[F.indicator]=[]),w.session.public_predicates[F.indicator]=!0,w.session.rules[F.indicator].push(new Ye(F,J,!0)),w.success(b)):w.throw_error(S.error.permission(\"modify\",\"static_procedure\",F.indicator,y.indicator)):w.throw_error(S.error.type(\"callable\",F,y.indicator))}},\"retract/1\":function(w,b,y){if(S.type.is_variable(y.args[0]))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_callable(y.args[0]))w.throw_error(S.error.type(\"callable\",y.args[0],y.indicator));else{var F,J;if(y.args[0].indicator===\":-/2\"?(F=y.args[0].args[0],J=y.args[0].args[1]):(F=y.args[0],J=new H(\"true\")),typeof b.retract>\"u\")if(w.is_public_predicate(F.indicator)){if(w.session.rules[F.indicator]!==void 0){for(var X=[],$=0;$<w.session.rules[F.indicator].length;$++){w.session.renamed_variables={};var ie=w.session.rules[F.indicator][$],Se=ie.rename(w);Se.body===null&&(Se.body=new H(\"true\",[]));var Re=w.get_flag(\"occurs_check\").indicator===\"true/0\",at=S.unify(new H(\",\",[F,J]),new H(\",\",[Se.head,Se.body]),Re);if(at!==null){var dt=new ke(b.goal.replace(new H(\",\",[new H(\"retract\",[new H(\":-\",[F,J])]),new H(\",\",[new H(\"=\",[F,Se.head]),new H(\"=\",[J,Se.body])])])),b.substitution,b);dt.retract=ie,X.push(dt)}}w.prepend(X)}}else w.throw_error(S.error.permission(\"modify\",\"static_procedure\",F.indicator,y.indicator));else Ae(w,b,F.indicator,b.retract)}},\"retractall/1\":function(w,b,y){var F=y.args[0];S.type.is_variable(F)?w.throw_error(S.error.instantiation(y.indicator)):S.type.is_callable(F)?w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"retract\",[new S.type.Term(\":-\",[F,new xe(\"_\")])]),new H(\"fail\",[])])),b.substitution,b),new ke(b.goal.replace(null),b.substitution,b)]):w.throw_error(S.error.type(\"callable\",F,y.indicator))},\"abolish/1\":function(w,b,y){if(S.type.is_variable(y.args[0])||S.type.is_term(y.args[0])&&y.args[0].indicator===\"//2\"&&(S.type.is_variable(y.args[0].args[0])||S.type.is_variable(y.args[0].args[1])))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_term(y.args[0])||y.args[0].indicator!==\"//2\")w.throw_error(S.error.type(\"predicate_indicator\",y.args[0],y.indicator));else if(!S.type.is_atom(y.args[0].args[0]))w.throw_error(S.error.type(\"atom\",y.args[0].args[0],y.indicator));else if(!S.type.is_integer(y.args[0].args[1]))w.throw_error(S.error.type(\"integer\",y.args[0].args[1],y.indicator));else if(y.args[0].args[1].value<0)w.throw_error(S.error.domain(\"not_less_than_zero\",y.args[0].args[1],y.indicator));else if(S.type.is_number(w.get_flag(\"max_arity\"))&&y.args[0].args[1].value>w.get_flag(\"max_arity\").value)w.throw_error(S.error.representation(\"max_arity\",y.indicator));else{var F=y.args[0].args[0].id+\"/\"+y.args[0].args[1].value;w.is_public_predicate(F)?(delete w.session.rules[F],w.success(b)):w.throw_error(S.error.permission(\"modify\",\"static_procedure\",F,y.indicator))}},\"atom_length/2\":function(w,b,y){if(S.type.is_variable(y.args[0]))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_atom(y.args[0]))w.throw_error(S.error.type(\"atom\",y.args[0],y.indicator));else if(!S.type.is_variable(y.args[1])&&!S.type.is_integer(y.args[1]))w.throw_error(S.error.type(\"integer\",y.args[1],y.indicator));else if(S.type.is_integer(y.args[1])&&y.args[1].value<0)w.throw_error(S.error.domain(\"not_less_than_zero\",y.args[1],y.indicator));else{var F=new Ne(y.args[0].id.length,!1);w.prepend([new ke(b.goal.replace(new H(\"=\",[F,y.args[1]])),b.substitution,b)])}},\"atom_concat/3\":function(w,b,y){var F,J,X=y.args[0],$=y.args[1],ie=y.args[2];if(S.type.is_variable(ie)&&(S.type.is_variable(X)||S.type.is_variable($)))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(X)&&!S.type.is_atom(X))w.throw_error(S.error.type(\"atom\",X,y.indicator));else if(!S.type.is_variable($)&&!S.type.is_atom($))w.throw_error(S.error.type(\"atom\",$,y.indicator));else if(!S.type.is_variable(ie)&&!S.type.is_atom(ie))w.throw_error(S.error.type(\"atom\",ie,y.indicator));else{var Se=S.type.is_variable(X),Re=S.type.is_variable($);if(!Se&&!Re)J=new H(\"=\",[ie,new H(X.id+$.id)]),w.prepend([new ke(b.goal.replace(J),b.substitution,b)]);else if(Se&&!Re)F=ie.id.substr(0,ie.id.length-$.id.length),F+$.id===ie.id&&(J=new H(\"=\",[X,new H(F)]),w.prepend([new ke(b.goal.replace(J),b.substitution,b)]));else if(Re&&!Se)F=ie.id.substr(X.id.length),X.id+F===ie.id&&(J=new H(\"=\",[$,new H(F)]),w.prepend([new ke(b.goal.replace(J),b.substitution,b)]));else{for(var at=[],dt=0;dt<=ie.id.length;dt++){var jt=new H(ie.id.substr(0,dt)),tr=new H(ie.id.substr(dt));J=new H(\",\",[new H(\"=\",[jt,X]),new H(\"=\",[tr,$])]),at.push(new ke(b.goal.replace(J),b.substitution,b))}w.prepend(at)}}},\"sub_atom/5\":function(w,b,y){var F,J=y.args[0],X=y.args[1],$=y.args[2],ie=y.args[3],Se=y.args[4];if(S.type.is_variable(J))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(X)&&!S.type.is_integer(X))w.throw_error(S.error.type(\"integer\",X,y.indicator));else if(!S.type.is_variable($)&&!S.type.is_integer($))w.throw_error(S.error.type(\"integer\",$,y.indicator));else if(!S.type.is_variable(ie)&&!S.type.is_integer(ie))w.throw_error(S.error.type(\"integer\",ie,y.indicator));else if(S.type.is_integer(X)&&X.value<0)w.throw_error(S.error.domain(\"not_less_than_zero\",X,y.indicator));else if(S.type.is_integer($)&&$.value<0)w.throw_error(S.error.domain(\"not_less_than_zero\",$,y.indicator));else if(S.type.is_integer(ie)&&ie.value<0)w.throw_error(S.error.domain(\"not_less_than_zero\",ie,y.indicator));else{var Re=[],at=[],dt=[];if(S.type.is_variable(X))for(F=0;F<=J.id.length;F++)Re.push(F);else Re.push(X.value);if(S.type.is_variable($))for(F=0;F<=J.id.length;F++)at.push(F);else at.push($.value);if(S.type.is_variable(ie))for(F=0;F<=J.id.length;F++)dt.push(F);else dt.push(ie.value);var jt=[];for(var tr in Re)if(Re.hasOwnProperty(tr)){F=Re[tr];for(var bt in at)if(at.hasOwnProperty(bt)){var ln=at[bt],kr=J.id.length-F-ln;if(e(dt,kr)!==-1&&F+ln+kr===J.id.length){var mr=J.id.substr(F,ln);if(J.id===J.id.substr(0,F)+mr+J.id.substr(F+ln,kr)){var Sr=new H(\"=\",[new H(mr),Se]),Kr=new H(\"=\",[X,new Ne(F)]),Kn=new H(\"=\",[$,new Ne(ln)]),Ms=new H(\"=\",[ie,new Ne(kr)]),Ri=new H(\",\",[new H(\",\",[new H(\",\",[Kr,Kn]),Ms]),Sr]);jt.push(new ke(b.goal.replace(Ri),b.substitution,b))}}}}w.prepend(jt)}},\"atom_chars/2\":function(w,b,y){var F=y.args[0],J=y.args[1];if(S.type.is_variable(F)&&S.type.is_variable(J))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(F)&&!S.type.is_atom(F))w.throw_error(S.error.type(\"atom\",F,y.indicator));else if(S.type.is_variable(F)){for(var ie=J,Se=S.type.is_variable(F),Re=\"\";ie.indicator===\"./2\";){if(S.type.is_character(ie.args[0]))Re+=ie.args[0].id;else if(S.type.is_variable(ie.args[0])&&Se){w.throw_error(S.error.instantiation(y.indicator));return}else if(!S.type.is_variable(ie.args[0])){w.throw_error(S.error.type(\"character\",ie.args[0],y.indicator));return}ie=ie.args[1]}S.type.is_variable(ie)&&Se?w.throw_error(S.error.instantiation(y.indicator)):!S.type.is_empty_list(ie)&&!S.type.is_variable(ie)?w.throw_error(S.error.type(\"list\",J,y.indicator)):w.prepend([new ke(b.goal.replace(new H(\"=\",[new H(Re),F])),b.substitution,b)])}else{for(var X=new H(\"[]\"),$=F.id.length-1;$>=0;$--)X=new H(\".\",[new H(F.id.charAt($)),X]);w.prepend([new ke(b.goal.replace(new H(\"=\",[J,X])),b.substitution,b)])}},\"atom_codes/2\":function(w,b,y){var F=y.args[0],J=y.args[1];if(S.type.is_variable(F)&&S.type.is_variable(J))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(F)&&!S.type.is_atom(F))w.throw_error(S.error.type(\"atom\",F,y.indicator));else if(S.type.is_variable(F)){for(var ie=J,Se=S.type.is_variable(F),Re=\"\";ie.indicator===\"./2\";){if(S.type.is_character_code(ie.args[0]))Re+=u(ie.args[0].value);else if(S.type.is_variable(ie.args[0])&&Se){w.throw_error(S.error.instantiation(y.indicator));return}else if(!S.type.is_variable(ie.args[0])){w.throw_error(S.error.representation(\"character_code\",y.indicator));return}ie=ie.args[1]}S.type.is_variable(ie)&&Se?w.throw_error(S.error.instantiation(y.indicator)):!S.type.is_empty_list(ie)&&!S.type.is_variable(ie)?w.throw_error(S.error.type(\"list\",J,y.indicator)):w.prepend([new ke(b.goal.replace(new H(\"=\",[new H(Re),F])),b.substitution,b)])}else{for(var X=new H(\"[]\"),$=F.id.length-1;$>=0;$--)X=new H(\".\",[new Ne(n(F.id,$),!1),X]);w.prepend([new ke(b.goal.replace(new H(\"=\",[J,X])),b.substitution,b)])}},\"char_code/2\":function(w,b,y){var F=y.args[0],J=y.args[1];if(S.type.is_variable(F)&&S.type.is_variable(J))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(F)&&!S.type.is_character(F))w.throw_error(S.error.type(\"character\",F,y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_integer(J))w.throw_error(S.error.type(\"integer\",J,y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_character_code(J))w.throw_error(S.error.representation(\"character_code\",y.indicator));else if(S.type.is_variable(J)){var X=new Ne(n(F.id,0),!1);w.prepend([new ke(b.goal.replace(new H(\"=\",[X,J])),b.substitution,b)])}else{var $=new H(u(J.value));w.prepend([new ke(b.goal.replace(new H(\"=\",[$,F])),b.substitution,b)])}},\"number_chars/2\":function(w,b,y){var F,J=y.args[0],X=y.args[1];if(S.type.is_variable(J)&&S.type.is_variable(X))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_number(J))w.throw_error(S.error.type(\"number\",J,y.indicator));else if(!S.type.is_variable(X)&&!S.type.is_list(X))w.throw_error(S.error.type(\"list\",X,y.indicator));else{var $=S.type.is_variable(J);if(!S.type.is_variable(X)){var ie=X,Se=!0;for(F=\"\";ie.indicator===\"./2\";){if(S.type.is_character(ie.args[0]))F+=ie.args[0].id;else if(S.type.is_variable(ie.args[0]))Se=!1;else if(!S.type.is_variable(ie.args[0])){w.throw_error(S.error.type(\"character\",ie.args[0],y.indicator));return}ie=ie.args[1]}if(Se=Se&&S.type.is_empty_list(ie),!S.type.is_empty_list(ie)&&!S.type.is_variable(ie)){w.throw_error(S.error.type(\"list\",X,y.indicator));return}if(!Se&&$){w.throw_error(S.error.instantiation(y.indicator));return}else if(Se)if(S.type.is_variable(ie)&&$){w.throw_error(S.error.instantiation(y.indicator));return}else{var Re=w.parse(F),at=Re.value;!S.type.is_number(at)||Re.tokens[Re.tokens.length-1].space?w.throw_error(S.error.syntax_by_predicate(\"parseable_number\",y.indicator)):w.prepend([new ke(b.goal.replace(new H(\"=\",[J,at])),b.substitution,b)]);return}}if(!$){F=J.toString();for(var dt=new H(\"[]\"),jt=F.length-1;jt>=0;jt--)dt=new H(\".\",[new H(F.charAt(jt)),dt]);w.prepend([new ke(b.goal.replace(new H(\"=\",[X,dt])),b.substitution,b)])}}},\"number_codes/2\":function(w,b,y){var F,J=y.args[0],X=y.args[1];if(S.type.is_variable(J)&&S.type.is_variable(X))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_number(J))w.throw_error(S.error.type(\"number\",J,y.indicator));else if(!S.type.is_variable(X)&&!S.type.is_list(X))w.throw_error(S.error.type(\"list\",X,y.indicator));else{var $=S.type.is_variable(J);if(!S.type.is_variable(X)){var ie=X,Se=!0;for(F=\"\";ie.indicator===\"./2\";){if(S.type.is_character_code(ie.args[0]))F+=u(ie.args[0].value);else if(S.type.is_variable(ie.args[0]))Se=!1;else if(!S.type.is_variable(ie.args[0])){w.throw_error(S.error.type(\"character_code\",ie.args[0],y.indicator));return}ie=ie.args[1]}if(Se=Se&&S.type.is_empty_list(ie),!S.type.is_empty_list(ie)&&!S.type.is_variable(ie)){w.throw_error(S.error.type(\"list\",X,y.indicator));return}if(!Se&&$){w.throw_error(S.error.instantiation(y.indicator));return}else if(Se)if(S.type.is_variable(ie)&&$){w.throw_error(S.error.instantiation(y.indicator));return}else{var Re=w.parse(F),at=Re.value;!S.type.is_number(at)||Re.tokens[Re.tokens.length-1].space?w.throw_error(S.error.syntax_by_predicate(\"parseable_number\",y.indicator)):w.prepend([new ke(b.goal.replace(new H(\"=\",[J,at])),b.substitution,b)]);return}}if(!$){F=J.toString();for(var dt=new H(\"[]\"),jt=F.length-1;jt>=0;jt--)dt=new H(\".\",[new Ne(n(F,jt),!1),dt]);w.prepend([new ke(b.goal.replace(new H(\"=\",[X,dt])),b.substitution,b)])}}},\"upcase_atom/2\":function(w,b,y){var F=y.args[0],J=y.args[1];S.type.is_variable(F)?w.throw_error(S.error.instantiation(y.indicator)):S.type.is_atom(F)?!S.type.is_variable(J)&&!S.type.is_atom(J)?w.throw_error(S.error.type(\"atom\",J,y.indicator)):w.prepend([new ke(b.goal.replace(new H(\"=\",[J,new H(F.id.toUpperCase(),[])])),b.substitution,b)]):w.throw_error(S.error.type(\"atom\",F,y.indicator))},\"downcase_atom/2\":function(w,b,y){var F=y.args[0],J=y.args[1];S.type.is_variable(F)?w.throw_error(S.error.instantiation(y.indicator)):S.type.is_atom(F)?!S.type.is_variable(J)&&!S.type.is_atom(J)?w.throw_error(S.error.type(\"atom\",J,y.indicator)):w.prepend([new ke(b.goal.replace(new H(\"=\",[J,new H(F.id.toLowerCase(),[])])),b.substitution,b)]):w.throw_error(S.error.type(\"atom\",F,y.indicator))},\"atomic_list_concat/2\":function(w,b,y){var F=y.args[0],J=y.args[1];w.prepend([new ke(b.goal.replace(new H(\"atomic_list_concat\",[F,new H(\"\",[]),J])),b.substitution,b)])},\"atomic_list_concat/3\":function(w,b,y){var F=y.args[0],J=y.args[1],X=y.args[2];if(S.type.is_variable(J)||S.type.is_variable(F)&&S.type.is_variable(X))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(F)&&!S.type.is_list(F))w.throw_error(S.error.type(\"list\",F,y.indicator));else if(!S.type.is_variable(X)&&!S.type.is_atom(X))w.throw_error(S.error.type(\"atom\",X,y.indicator));else if(S.type.is_variable(X)){for(var ie=\"\",Se=F;S.type.is_term(Se)&&Se.indicator===\"./2\";){if(!S.type.is_atom(Se.args[0])&&!S.type.is_number(Se.args[0])){w.throw_error(S.error.type(\"atomic\",Se.args[0],y.indicator));return}ie!==\"\"&&(ie+=J.id),S.type.is_atom(Se.args[0])?ie+=Se.args[0].id:ie+=\"\"+Se.args[0].value,Se=Se.args[1]}ie=new H(ie,[]),S.type.is_variable(Se)?w.throw_error(S.error.instantiation(y.indicator)):!S.type.is_term(Se)||Se.indicator!==\"[]/0\"?w.throw_error(S.error.type(\"list\",F,y.indicator)):w.prepend([new ke(b.goal.replace(new H(\"=\",[ie,X])),b.substitution,b)])}else{var $=g(o(X.id.split(J.id),function(Re){return new H(Re,[])}));w.prepend([new ke(b.goal.replace(new H(\"=\",[$,F])),b.substitution,b)])}},\"@=</2\":function(w,b,y){S.compare(y.args[0],y.args[1])<=0&&w.success(b)},\"==/2\":function(w,b,y){S.compare(y.args[0],y.args[1])===0&&w.success(b)},\"\\\\==/2\":function(w,b,y){S.compare(y.args[0],y.args[1])!==0&&w.success(b)},\"@</2\":function(w,b,y){S.compare(y.args[0],y.args[1])<0&&w.success(b)},\"@>/2\":function(w,b,y){S.compare(y.args[0],y.args[1])>0&&w.success(b)},\"@>=/2\":function(w,b,y){S.compare(y.args[0],y.args[1])>=0&&w.success(b)},\"compare/3\":function(w,b,y){var F=y.args[0],J=y.args[1],X=y.args[2];if(!S.type.is_variable(F)&&!S.type.is_atom(F))w.throw_error(S.error.type(\"atom\",F,y.indicator));else if(S.type.is_atom(F)&&[\"<\",\">\",\"=\"].indexOf(F.id)===-1)w.throw_error(S.type.domain(\"order\",F,y.indicator));else{var $=S.compare(J,X);$=$===0?\"=\":$===-1?\"<\":\">\",w.prepend([new ke(b.goal.replace(new H(\"=\",[F,new H($,[])])),b.substitution,b)])}},\"is/2\":function(w,b,y){var F=y.args[1].interpret(w);S.type.is_number(F)?w.prepend([new ke(b.goal.replace(new H(\"=\",[y.args[0],F],w.level)),b.substitution,b)]):w.throw_error(F)},\"between/3\":function(w,b,y){var F=y.args[0],J=y.args[1],X=y.args[2];if(S.type.is_variable(F)||S.type.is_variable(J))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_integer(F))w.throw_error(S.error.type(\"integer\",F,y.indicator));else if(!S.type.is_integer(J))w.throw_error(S.error.type(\"integer\",J,y.indicator));else if(!S.type.is_variable(X)&&!S.type.is_integer(X))w.throw_error(S.error.type(\"integer\",X,y.indicator));else if(S.type.is_variable(X)){var $=[new ke(b.goal.replace(new H(\"=\",[X,F])),b.substitution,b)];F.value<J.value&&$.push(new ke(b.goal.replace(new H(\"between\",[new Ne(F.value+1,!1),J,X])),b.substitution,b)),w.prepend($)}else F.value<=X.value&&J.value>=X.value&&w.success(b)},\"succ/2\":function(w,b,y){var F=y.args[0],J=y.args[1];S.type.is_variable(F)&&S.type.is_variable(J)?w.throw_error(S.error.instantiation(y.indicator)):!S.type.is_variable(F)&&!S.type.is_integer(F)?w.throw_error(S.error.type(\"integer\",F,y.indicator)):!S.type.is_variable(J)&&!S.type.is_integer(J)?w.throw_error(S.error.type(\"integer\",J,y.indicator)):!S.type.is_variable(F)&&F.value<0?w.throw_error(S.error.domain(\"not_less_than_zero\",F,y.indicator)):!S.type.is_variable(J)&&J.value<0?w.throw_error(S.error.domain(\"not_less_than_zero\",J,y.indicator)):(S.type.is_variable(J)||J.value>0)&&(S.type.is_variable(F)?w.prepend([new ke(b.goal.replace(new H(\"=\",[F,new Ne(J.value-1,!1)])),b.substitution,b)]):w.prepend([new ke(b.goal.replace(new H(\"=\",[J,new Ne(F.value+1,!1)])),b.substitution,b)]))},\"=:=/2\":function(w,b,y){var F=S.arithmetic_compare(w,y.args[0],y.args[1]);S.type.is_term(F)?w.throw_error(F):F===0&&w.success(b)},\"=\\\\=/2\":function(w,b,y){var F=S.arithmetic_compare(w,y.args[0],y.args[1]);S.type.is_term(F)?w.throw_error(F):F!==0&&w.success(b)},\"</2\":function(w,b,y){var F=S.arithmetic_compare(w,y.args[0],y.args[1]);S.type.is_term(F)?w.throw_error(F):F<0&&w.success(b)},\"=</2\":function(w,b,y){var F=S.arithmetic_compare(w,y.args[0],y.args[1]);S.type.is_term(F)?w.throw_error(F):F<=0&&w.success(b)},\">/2\":function(w,b,y){var F=S.arithmetic_compare(w,y.args[0],y.args[1]);S.type.is_term(F)?w.throw_error(F):F>0&&w.success(b)},\">=/2\":function(w,b,y){var F=S.arithmetic_compare(w,y.args[0],y.args[1]);S.type.is_term(F)?w.throw_error(F):F>=0&&w.success(b)},\"var/1\":function(w,b,y){S.type.is_variable(y.args[0])&&w.success(b)},\"atom/1\":function(w,b,y){S.type.is_atom(y.args[0])&&w.success(b)},\"atomic/1\":function(w,b,y){S.type.is_atomic(y.args[0])&&w.success(b)},\"compound/1\":function(w,b,y){S.type.is_compound(y.args[0])&&w.success(b)},\"integer/1\":function(w,b,y){S.type.is_integer(y.args[0])&&w.success(b)},\"float/1\":function(w,b,y){S.type.is_float(y.args[0])&&w.success(b)},\"number/1\":function(w,b,y){S.type.is_number(y.args[0])&&w.success(b)},\"nonvar/1\":function(w,b,y){S.type.is_variable(y.args[0])||w.success(b)},\"ground/1\":function(w,b,y){y.variables().length===0&&w.success(b)},\"acyclic_term/1\":function(w,b,y){for(var F=b.substitution.apply(b.substitution),J=y.args[0].variables(),X=0;X<J.length;X++)if(b.substitution.links[J[X]]!==void 0&&!b.substitution.links[J[X]].equals(F.links[J[X]]))return;w.success(b)},\"callable/1\":function(w,b,y){S.type.is_callable(y.args[0])&&w.success(b)},\"is_list/1\":function(w,b,y){for(var F=y.args[0];S.type.is_term(F)&&F.indicator===\"./2\";)F=F.args[1];S.type.is_term(F)&&F.indicator===\"[]/0\"&&w.success(b)},\"current_input/1\":function(w,b,y){var F=y.args[0];!S.type.is_variable(F)&&!S.type.is_stream(F)&&!S.type.is_atom(F)?w.throw_error(S.error.domain(\"stream\",F,y.indicator)):(S.type.is_atom(F)&&w.get_stream_by_alias(F.id)&&(F=w.get_stream_by_alias(F.id)),w.prepend([new ke(b.goal.replace(new H(\"=\",[F,w.get_current_input()])),b.substitution,b)]))},\"current_output/1\":function(w,b,y){var F=y.args[0];!S.type.is_variable(F)&&!S.type.is_stream(F)&&!S.type.is_atom(F)?w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator)):(S.type.is_atom(F)&&w.get_stream_by_alias(F.id)&&(F=w.get_stream_by_alias(F.id)),w.prepend([new ke(b.goal.replace(new H(\"=\",[F,w.get_current_output()])),b.substitution,b)]))},\"set_input/1\":function(w,b,y){var F=y.args[0],J=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);S.type.is_variable(F)?w.throw_error(S.error.instantiation(y.indicator)):!S.type.is_variable(F)&&!S.type.is_stream(F)&&!S.type.is_atom(F)?w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator)):S.type.is_stream(J)?J.output===!0?w.throw_error(S.error.permission(\"input\",\"stream\",F,y.indicator)):(w.set_current_input(J),w.success(b)):w.throw_error(S.error.existence(\"stream\",F,y.indicator))},\"set_output/1\":function(w,b,y){var F=y.args[0],J=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);S.type.is_variable(F)?w.throw_error(S.error.instantiation(y.indicator)):!S.type.is_variable(F)&&!S.type.is_stream(F)&&!S.type.is_atom(F)?w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator)):S.type.is_stream(J)?J.input===!0?w.throw_error(S.error.permission(\"output\",\"stream\",F,y.indicator)):(w.set_current_output(J),w.success(b)):w.throw_error(S.error.existence(\"stream\",F,y.indicator))},\"open/3\":function(w,b,y){var F=y.args[0],J=y.args[1],X=y.args[2];w.prepend([new ke(b.goal.replace(new H(\"open\",[F,J,X,new H(\"[]\",[])])),b.substitution,b)])},\"open/4\":function(w,b,y){var F=y.args[0],J=y.args[1],X=y.args[2],$=y.args[3];if(S.type.is_variable(F)||S.type.is_variable(J))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_atom(J))w.throw_error(S.error.type(\"atom\",J,y.indicator));else if(!S.type.is_list($))w.throw_error(S.error.type(\"list\",$,y.indicator));else if(!S.type.is_variable(X))w.throw_error(S.error.type(\"variable\",X,y.indicator));else if(!S.type.is_atom(F)&&!S.type.is_streamable(F))w.throw_error(S.error.domain(\"source_sink\",F,y.indicator));else if(!S.type.is_io_mode(J))w.throw_error(S.error.domain(\"io_mode\",J,y.indicator));else{for(var ie={},Se=$,Re;S.type.is_term(Se)&&Se.indicator===\"./2\";){if(Re=Se.args[0],S.type.is_variable(Re)){w.throw_error(S.error.instantiation(y.indicator));return}else if(!S.type.is_stream_option(Re)){w.throw_error(S.error.domain(\"stream_option\",Re,y.indicator));return}ie[Re.id]=Re.args[0].id,Se=Se.args[1]}if(Se.indicator!==\"[]/0\"){S.type.is_variable(Se)?w.throw_error(S.error.instantiation(y.indicator)):w.throw_error(S.error.type(\"list\",$,y.indicator));return}else{var at=ie.alias;if(at&&w.get_stream_by_alias(at)){w.throw_error(S.error.permission(\"open\",\"source_sink\",new H(\"alias\",[new H(at,[])]),y.indicator));return}ie.type||(ie.type=\"text\");var dt;if(S.type.is_atom(F)?dt=w.file_system_open(F.id,ie.type,J.id):dt=F.stream(ie.type,J.id),dt===!1){w.throw_error(S.error.permission(\"open\",\"source_sink\",F,y.indicator));return}else if(dt===null){w.throw_error(S.error.existence(\"source_sink\",F,y.indicator));return}var jt=new Te(dt,J.id,ie.alias,ie.type,ie.reposition===\"true\",ie.eof_action);at?w.session.streams[at]=jt:w.session.streams[jt.id]=jt,w.prepend([new ke(b.goal.replace(new H(\"=\",[X,jt])),b.substitution,b)])}}},\"close/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\"close\",[F,new H(\"[]\",[])])),b.substitution,b)])},\"close/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);if(S.type.is_variable(F)||S.type.is_variable(J))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_list(J))w.throw_error(S.error.type(\"list\",J,y.indicator));else if(!S.type.is_stream(F)&&!S.type.is_atom(F))w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator));else if(!S.type.is_stream(X)||X.stream===null)w.throw_error(S.error.existence(\"stream\",F,y.indicator));else{for(var $={},ie=J,Se;S.type.is_term(ie)&&ie.indicator===\"./2\";){if(Se=ie.args[0],S.type.is_variable(Se)){w.throw_error(S.error.instantiation(y.indicator));return}else if(!S.type.is_close_option(Se)){w.throw_error(S.error.domain(\"close_option\",Se,y.indicator));return}$[Se.id]=Se.args[0].id===\"true\",ie=ie.args[1]}if(ie.indicator!==\"[]/0\"){S.type.is_variable(ie)?w.throw_error(S.error.instantiation(y.indicator)):w.throw_error(S.error.type(\"list\",J,y.indicator));return}else{if(X===w.session.standard_input||X===w.session.standard_output){w.success(b);return}else X===w.session.current_input?w.session.current_input=w.session.standard_input:X===w.session.current_output&&(w.session.current_output=w.session.current_output);X.alias!==null?delete w.session.streams[X.alias]:delete w.session.streams[X.id],X.output&&X.stream.flush();var Re=X.stream.close();X.stream=null,($.force===!0||Re===!0)&&w.success(b)}}},\"flush_output/0\":function(w,b,y){w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_output\",[new xe(\"S\")]),new H(\"flush_output\",[new xe(\"S\")])])),b.substitution,b)])},\"flush_output/1\":function(w,b,y){var F=y.args[0],J=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);S.type.is_variable(F)?w.throw_error(S.error.instantiation(y.indicator)):!S.type.is_stream(F)&&!S.type.is_atom(F)?w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator)):!S.type.is_stream(J)||J.stream===null?w.throw_error(S.error.existence(\"stream\",F,y.indicator)):F.input===!0?w.throw_error(S.error.permission(\"output\",\"stream\",output,y.indicator)):(J.stream.flush(),w.success(b))},\"stream_property/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);if(!S.type.is_variable(F)&&!S.type.is_stream(F)&&!S.type.is_atom(F))w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator));else if(!S.type.is_variable(F)&&(!S.type.is_stream(X)||X.stream===null))w.throw_error(S.error.existence(\"stream\",F,y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_stream_property(J))w.throw_error(S.error.domain(\"stream_property\",J,y.indicator));else{var $=[],ie=[];if(!S.type.is_variable(F))$.push(X);else for(var Se in w.session.streams)$.push(w.session.streams[Se]);for(var Re=0;Re<$.length;Re++){var at=[];$[Re].filename&&at.push(new H(\"file_name\",[new H($[Re].file_name,[])])),at.push(new H(\"mode\",[new H($[Re].mode,[])])),at.push(new H($[Re].input?\"input\":\"output\",[])),$[Re].alias&&at.push(new H(\"alias\",[new H($[Re].alias,[])])),at.push(new H(\"position\",[typeof $[Re].position==\"number\"?new Ne($[Re].position,!1):new H($[Re].position,[])])),at.push(new H(\"end_of_stream\",[new H($[Re].position===\"end_of_stream\"?\"at\":$[Re].position===\"past_end_of_stream\"?\"past\":\"not\",[])])),at.push(new H(\"eof_action\",[new H($[Re].eof_action,[])])),at.push(new H(\"reposition\",[new H($[Re].reposition?\"true\":\"false\",[])])),at.push(new H(\"type\",[new H($[Re].type,[])]));for(var dt=0;dt<at.length;dt++)ie.push(new ke(b.goal.replace(new H(\",\",[new H(\"=\",[S.type.is_variable(F)?F:X,$[Re]]),new H(\"=\",[J,at[dt]])])),b.substitution,b))}w.prepend(ie)}},\"at_end_of_stream/0\":function(w,b,y){w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_input\",[new xe(\"S\")]),new H(\",\",[new H(\"stream_property\",[new xe(\"S\"),new H(\"end_of_stream\",[new xe(\"E\")])]),new H(\",\",[new H(\"!\",[]),new H(\";\",[new H(\"=\",[new xe(\"E\"),new H(\"at\",[])]),new H(\"=\",[new xe(\"E\"),new H(\"past\",[])])])])])])),b.substitution,b)])},\"at_end_of_stream/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"stream_property\",[F,new H(\"end_of_stream\",[new xe(\"E\")])]),new H(\",\",[new H(\"!\",[]),new H(\";\",[new H(\"=\",[new xe(\"E\"),new H(\"at\",[])]),new H(\"=\",[new xe(\"E\"),new H(\"past\",[])])])])])),b.substitution,b)])},\"set_stream_position/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);S.type.is_variable(F)||S.type.is_variable(J)?w.throw_error(S.error.instantiation(y.indicator)):!S.type.is_stream(F)&&!S.type.is_atom(F)?w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator)):!S.type.is_stream(X)||X.stream===null?w.throw_error(S.error.existence(\"stream\",F,y.indicator)):S.type.is_stream_position(J)?X.reposition===!1?w.throw_error(S.error.permission(\"reposition\",\"stream\",F,y.indicator)):(S.type.is_integer(J)?X.position=J.value:X.position=J.id,w.success(b)):w.throw_error(S.error.domain(\"stream_position\",J,y.indicator))},\"get_char/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_input\",[new xe(\"S\")]),new H(\"get_char\",[new xe(\"S\"),F])])),b.substitution,b)])},\"get_char/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);if(S.type.is_variable(F))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_character(J))w.throw_error(S.error.type(\"in_character\",J,y.indicator));else if(!S.type.is_stream(F)&&!S.type.is_atom(F))w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator));else if(!S.type.is_stream(X)||X.stream===null)w.throw_error(S.error.existence(\"stream\",F,y.indicator));else if(X.output)w.throw_error(S.error.permission(\"input\",\"stream\",F,y.indicator));else if(X.type===\"binary\")w.throw_error(S.error.permission(\"input\",\"binary_stream\",F,y.indicator));else if(X.position===\"past_end_of_stream\"&&X.eof_action===\"error\")w.throw_error(S.error.permission(\"input\",\"past_end_of_stream\",F,y.indicator));else{var $;if(X.position===\"end_of_stream\")$=\"end_of_file\",X.position=\"past_end_of_stream\";else{if($=X.stream.get(1,X.position),$===null){w.throw_error(S.error.representation(\"character\",y.indicator));return}X.position++}w.prepend([new ke(b.goal.replace(new H(\"=\",[new H($,[]),J])),b.substitution,b)])}},\"get_code/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_input\",[new xe(\"S\")]),new H(\"get_code\",[new xe(\"S\"),F])])),b.substitution,b)])},\"get_code/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);if(S.type.is_variable(F))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_integer(J))w.throw_error(S.error.type(\"integer\",char,y.indicator));else if(!S.type.is_variable(F)&&!S.type.is_stream(F)&&!S.type.is_atom(F))w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator));else if(!S.type.is_stream(X)||X.stream===null)w.throw_error(S.error.existence(\"stream\",F,y.indicator));else if(X.output)w.throw_error(S.error.permission(\"input\",\"stream\",F,y.indicator));else if(X.type===\"binary\")w.throw_error(S.error.permission(\"input\",\"binary_stream\",F,y.indicator));else if(X.position===\"past_end_of_stream\"&&X.eof_action===\"error\")w.throw_error(S.error.permission(\"input\",\"past_end_of_stream\",F,y.indicator));else{var $;if(X.position===\"end_of_stream\")$=-1,X.position=\"past_end_of_stream\";else{if($=X.stream.get(1,X.position),$===null){w.throw_error(S.error.representation(\"character\",y.indicator));return}$=n($,0),X.position++}w.prepend([new ke(b.goal.replace(new H(\"=\",[new Ne($,!1),J])),b.substitution,b)])}},\"peek_char/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_input\",[new xe(\"S\")]),new H(\"peek_char\",[new xe(\"S\"),F])])),b.substitution,b)])},\"peek_char/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);if(S.type.is_variable(F))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_character(J))w.throw_error(S.error.type(\"in_character\",J,y.indicator));else if(!S.type.is_stream(F)&&!S.type.is_atom(F))w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator));else if(!S.type.is_stream(X)||X.stream===null)w.throw_error(S.error.existence(\"stream\",F,y.indicator));else if(X.output)w.throw_error(S.error.permission(\"input\",\"stream\",F,y.indicator));else if(X.type===\"binary\")w.throw_error(S.error.permission(\"input\",\"binary_stream\",F,y.indicator));else if(X.position===\"past_end_of_stream\"&&X.eof_action===\"error\")w.throw_error(S.error.permission(\"input\",\"past_end_of_stream\",F,y.indicator));else{var $;if(X.position===\"end_of_stream\")$=\"end_of_file\",X.position=\"past_end_of_stream\";else if($=X.stream.get(1,X.position),$===null){w.throw_error(S.error.representation(\"character\",y.indicator));return}w.prepend([new ke(b.goal.replace(new H(\"=\",[new H($,[]),J])),b.substitution,b)])}},\"peek_code/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_input\",[new xe(\"S\")]),new H(\"peek_code\",[new xe(\"S\"),F])])),b.substitution,b)])},\"peek_code/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);if(S.type.is_variable(F))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_integer(J))w.throw_error(S.error.type(\"integer\",char,y.indicator));else if(!S.type.is_variable(F)&&!S.type.is_stream(F)&&!S.type.is_atom(F))w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator));else if(!S.type.is_stream(X)||X.stream===null)w.throw_error(S.error.existence(\"stream\",F,y.indicator));else if(X.output)w.throw_error(S.error.permission(\"input\",\"stream\",F,y.indicator));else if(X.type===\"binary\")w.throw_error(S.error.permission(\"input\",\"binary_stream\",F,y.indicator));else if(X.position===\"past_end_of_stream\"&&X.eof_action===\"error\")w.throw_error(S.error.permission(\"input\",\"past_end_of_stream\",F,y.indicator));else{var $;if(X.position===\"end_of_stream\")$=-1,X.position=\"past_end_of_stream\";else{if($=X.stream.get(1,X.position),$===null){w.throw_error(S.error.representation(\"character\",y.indicator));return}$=n($,0)}w.prepend([new ke(b.goal.replace(new H(\"=\",[new Ne($,!1),J])),b.substitution,b)])}},\"put_char/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_output\",[new xe(\"S\")]),new H(\"put_char\",[new xe(\"S\"),F])])),b.substitution,b)])},\"put_char/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);S.type.is_variable(F)||S.type.is_variable(J)?w.throw_error(S.error.instantiation(y.indicator)):S.type.is_character(J)?!S.type.is_variable(F)&&!S.type.is_stream(F)&&!S.type.is_atom(F)?w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator)):!S.type.is_stream(X)||X.stream===null?w.throw_error(S.error.existence(\"stream\",F,y.indicator)):X.input?w.throw_error(S.error.permission(\"output\",\"stream\",F,y.indicator)):X.type===\"binary\"?w.throw_error(S.error.permission(\"output\",\"binary_stream\",F,y.indicator)):X.stream.put(J.id,X.position)&&(typeof X.position==\"number\"&&X.position++,w.success(b)):w.throw_error(S.error.type(\"character\",J,y.indicator))},\"put_code/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_output\",[new xe(\"S\")]),new H(\"put_code\",[new xe(\"S\"),F])])),b.substitution,b)])},\"put_code/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);S.type.is_variable(F)||S.type.is_variable(J)?w.throw_error(S.error.instantiation(y.indicator)):S.type.is_integer(J)?S.type.is_character_code(J)?!S.type.is_variable(F)&&!S.type.is_stream(F)&&!S.type.is_atom(F)?w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator)):!S.type.is_stream(X)||X.stream===null?w.throw_error(S.error.existence(\"stream\",F,y.indicator)):X.input?w.throw_error(S.error.permission(\"output\",\"stream\",F,y.indicator)):X.type===\"binary\"?w.throw_error(S.error.permission(\"output\",\"binary_stream\",F,y.indicator)):X.stream.put_char(u(J.value),X.position)&&(typeof X.position==\"number\"&&X.position++,w.success(b)):w.throw_error(S.error.representation(\"character_code\",y.indicator)):w.throw_error(S.error.type(\"integer\",J,y.indicator))},\"nl/0\":function(w,b,y){w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_output\",[new xe(\"S\")]),new H(\"put_char\",[new xe(\"S\"),new H(`\n`,[])])])),b.substitution,b)])},\"nl/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\"put_char\",[F,new H(`\n`,[])])),b.substitution,b)])},\"get_byte/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_input\",[new xe(\"S\")]),new H(\"get_byte\",[new xe(\"S\"),F])])),b.substitution,b)])},\"get_byte/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);if(S.type.is_variable(F))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_byte(J))w.throw_error(S.error.type(\"in_byte\",char,y.indicator));else if(!S.type.is_stream(F)&&!S.type.is_atom(F))w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator));else if(!S.type.is_stream(X)||X.stream===null)w.throw_error(S.error.existence(\"stream\",F,y.indicator));else if(X.output)w.throw_error(S.error.permission(\"input\",\"stream\",F,y.indicator));else if(X.type===\"text\")w.throw_error(S.error.permission(\"input\",\"text_stream\",F,y.indicator));else if(X.position===\"past_end_of_stream\"&&X.eof_action===\"error\")w.throw_error(S.error.permission(\"input\",\"past_end_of_stream\",F,y.indicator));else{var $;if(X.position===\"end_of_stream\")$=\"end_of_file\",X.position=\"past_end_of_stream\";else{if($=X.stream.get_byte(X.position),$===null){w.throw_error(S.error.representation(\"byte\",y.indicator));return}X.position++}w.prepend([new ke(b.goal.replace(new H(\"=\",[new Ne($,!1),J])),b.substitution,b)])}},\"peek_byte/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_input\",[new xe(\"S\")]),new H(\"peek_byte\",[new xe(\"S\"),F])])),b.substitution,b)])},\"peek_byte/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);if(S.type.is_variable(F))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_variable(J)&&!S.type.is_byte(J))w.throw_error(S.error.type(\"in_byte\",char,y.indicator));else if(!S.type.is_stream(F)&&!S.type.is_atom(F))w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator));else if(!S.type.is_stream(X)||X.stream===null)w.throw_error(S.error.existence(\"stream\",F,y.indicator));else if(X.output)w.throw_error(S.error.permission(\"input\",\"stream\",F,y.indicator));else if(X.type===\"text\")w.throw_error(S.error.permission(\"input\",\"text_stream\",F,y.indicator));else if(X.position===\"past_end_of_stream\"&&X.eof_action===\"error\")w.throw_error(S.error.permission(\"input\",\"past_end_of_stream\",F,y.indicator));else{var $;if(X.position===\"end_of_stream\")$=\"end_of_file\",X.position=\"past_end_of_stream\";else if($=X.stream.get_byte(X.position),$===null){w.throw_error(S.error.representation(\"byte\",y.indicator));return}w.prepend([new ke(b.goal.replace(new H(\"=\",[new Ne($,!1),J])),b.substitution,b)])}},\"put_byte/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_output\",[new xe(\"S\")]),new H(\"put_byte\",[new xe(\"S\"),F])])),b.substitution,b)])},\"put_byte/2\":function(w,b,y){var F=y.args[0],J=y.args[1],X=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);S.type.is_variable(F)||S.type.is_variable(J)?w.throw_error(S.error.instantiation(y.indicator)):S.type.is_byte(J)?!S.type.is_variable(F)&&!S.type.is_stream(F)&&!S.type.is_atom(F)?w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator)):!S.type.is_stream(X)||X.stream===null?w.throw_error(S.error.existence(\"stream\",F,y.indicator)):X.input?w.throw_error(S.error.permission(\"output\",\"stream\",F,y.indicator)):X.type===\"text\"?w.throw_error(S.error.permission(\"output\",\"text_stream\",F,y.indicator)):X.stream.put_byte(J.value,X.position)&&(typeof X.position==\"number\"&&X.position++,w.success(b)):w.throw_error(S.error.type(\"byte\",J,y.indicator))},\"read/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_input\",[new xe(\"S\")]),new H(\"read_term\",[new xe(\"S\"),F,new H(\"[]\",[])])])),b.substitution,b)])},\"read/2\":function(w,b,y){var F=y.args[0],J=y.args[1];w.prepend([new ke(b.goal.replace(new H(\"read_term\",[F,J,new H(\"[]\",[])])),b.substitution,b)])},\"read_term/2\":function(w,b,y){var F=y.args[0],J=y.args[1];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_input\",[new xe(\"S\")]),new H(\"read_term\",[new xe(\"S\"),F,J])])),b.substitution,b)])},\"read_term/3\":function(w,b,y){var F=y.args[0],J=y.args[1],X=y.args[2],$=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);if(S.type.is_variable(F)||S.type.is_variable(X))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_list(X))w.throw_error(S.error.type(\"list\",X,y.indicator));else if(!S.type.is_stream(F)&&!S.type.is_atom(F))w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator));else if(!S.type.is_stream($)||$.stream===null)w.throw_error(S.error.existence(\"stream\",F,y.indicator));else if($.output)w.throw_error(S.error.permission(\"input\",\"stream\",F,y.indicator));else if($.type===\"binary\")w.throw_error(S.error.permission(\"input\",\"binary_stream\",F,y.indicator));else if($.position===\"past_end_of_stream\"&&$.eof_action===\"error\")w.throw_error(S.error.permission(\"input\",\"past_end_of_stream\",F,y.indicator));else{for(var ie={},Se=X,Re;S.type.is_term(Se)&&Se.indicator===\"./2\";){if(Re=Se.args[0],S.type.is_variable(Re)){w.throw_error(S.error.instantiation(y.indicator));return}else if(!S.type.is_read_option(Re)){w.throw_error(S.error.domain(\"read_option\",Re,y.indicator));return}ie[Re.id]=Re.args[0],Se=Se.args[1]}if(Se.indicator!==\"[]/0\"){S.type.is_variable(Se)?w.throw_error(S.error.instantiation(y.indicator)):w.throw_error(S.error.type(\"list\",X,y.indicator));return}else{for(var at,dt,jt,tr=\"\",bt=[],ln=null;ln===null||ln.name!==\"atom\"||ln.value!==\".\"||jt.type===A&&S.flatten_error(new H(\"throw\",[jt.value])).found===\"token_not_found\";){if(at=$.stream.get(1,$.position),at===null){w.throw_error(S.error.representation(\"character\",y.indicator));return}if(at===\"end_of_file\"||at===\"past_end_of_file\"){jt?w.throw_error(S.error.syntax(bt[jt.len-1],\". or expression expected\",!1)):w.throw_error(S.error.syntax(null,\"token not found\",!0));return}$.position++,tr+=at,dt=new U(w),dt.new_text(tr),bt=dt.get_tokens(),ln=bt!==null&&bt.length>0?bt[bt.length-1]:null,bt!==null&&(jt=z(w,bt,0,w.__get_max_priority(),!1))}if(jt.type===p&&jt.len===bt.length-1&&ln.value===\".\"){jt=jt.value.rename(w);var kr=new H(\"=\",[J,jt]);if(ie.variables){var mr=g(o(we(jt.variables()),function(Sr){return new xe(Sr)}));kr=new H(\",\",[kr,new H(\"=\",[ie.variables,mr])])}if(ie.variable_names){var mr=g(o(we(jt.variables()),function(Kr){var Kn;for(Kn in w.session.renamed_variables)if(w.session.renamed_variables.hasOwnProperty(Kn)&&w.session.renamed_variables[Kn]===Kr)break;return new H(\"=\",[new H(Kn,[]),new xe(Kr)])}));kr=new H(\",\",[kr,new H(\"=\",[ie.variable_names,mr])])}if(ie.singletons){var mr=g(o(new Ye(jt,null).singleton_variables(),function(Kr){var Kn;for(Kn in w.session.renamed_variables)if(w.session.renamed_variables.hasOwnProperty(Kn)&&w.session.renamed_variables[Kn]===Kr)break;return new H(\"=\",[new H(Kn,[]),new xe(Kr)])}));kr=new H(\",\",[kr,new H(\"=\",[ie.singletons,mr])])}w.prepend([new ke(b.goal.replace(kr),b.substitution,b)])}else jt.type===p?w.throw_error(S.error.syntax(bt[jt.len],\"unexpected token\",!1)):w.throw_error(jt.value)}}},\"write/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_output\",[new xe(\"S\")]),new H(\"write\",[new xe(\"S\"),F])])),b.substitution,b)])},\"write/2\":function(w,b,y){var F=y.args[0],J=y.args[1];w.prepend([new ke(b.goal.replace(new H(\"write_term\",[F,J,new H(\".\",[new H(\"quoted\",[new H(\"false\",[])]),new H(\".\",[new H(\"ignore_ops\",[new H(\"false\")]),new H(\".\",[new H(\"numbervars\",[new H(\"true\")]),new H(\"[]\",[])])])])])),b.substitution,b)])},\"writeq/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_output\",[new xe(\"S\")]),new H(\"writeq\",[new xe(\"S\"),F])])),b.substitution,b)])},\"writeq/2\":function(w,b,y){var F=y.args[0],J=y.args[1];w.prepend([new ke(b.goal.replace(new H(\"write_term\",[F,J,new H(\".\",[new H(\"quoted\",[new H(\"true\",[])]),new H(\".\",[new H(\"ignore_ops\",[new H(\"false\")]),new H(\".\",[new H(\"numbervars\",[new H(\"true\")]),new H(\"[]\",[])])])])])),b.substitution,b)])},\"write_canonical/1\":function(w,b,y){var F=y.args[0];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_output\",[new xe(\"S\")]),new H(\"write_canonical\",[new xe(\"S\"),F])])),b.substitution,b)])},\"write_canonical/2\":function(w,b,y){var F=y.args[0],J=y.args[1];w.prepend([new ke(b.goal.replace(new H(\"write_term\",[F,J,new H(\".\",[new H(\"quoted\",[new H(\"true\",[])]),new H(\".\",[new H(\"ignore_ops\",[new H(\"true\")]),new H(\".\",[new H(\"numbervars\",[new H(\"false\")]),new H(\"[]\",[])])])])])),b.substitution,b)])},\"write_term/2\":function(w,b,y){var F=y.args[0],J=y.args[1];w.prepend([new ke(b.goal.replace(new H(\",\",[new H(\"current_output\",[new xe(\"S\")]),new H(\"write_term\",[new xe(\"S\"),F,J])])),b.substitution,b)])},\"write_term/3\":function(w,b,y){var F=y.args[0],J=y.args[1],X=y.args[2],$=S.type.is_stream(F)?F:w.get_stream_by_alias(F.id);if(S.type.is_variable(F)||S.type.is_variable(X))w.throw_error(S.error.instantiation(y.indicator));else if(!S.type.is_list(X))w.throw_error(S.error.type(\"list\",X,y.indicator));else if(!S.type.is_stream(F)&&!S.type.is_atom(F))w.throw_error(S.error.domain(\"stream_or_alias\",F,y.indicator));else if(!S.type.is_stream($)||$.stream===null)w.throw_error(S.error.existence(\"stream\",F,y.indicator));else if($.input)w.throw_error(S.error.permission(\"output\",\"stream\",F,y.indicator));else if($.type===\"binary\")w.throw_error(S.error.permission(\"output\",\"binary_stream\",F,y.indicator));else if($.position===\"past_end_of_stream\"&&$.eof_action===\"error\")w.throw_error(S.error.permission(\"output\",\"past_end_of_stream\",F,y.indicator));else{for(var ie={},Se=X,Re;S.type.is_term(Se)&&Se.indicator===\"./2\";){if(Re=Se.args[0],S.type.is_variable(Re)){w.throw_error(S.error.instantiation(y.indicator));return}else if(!S.type.is_write_option(Re)){w.throw_error(S.error.domain(\"write_option\",Re,y.indicator));return}ie[Re.id]=Re.args[0].id===\"true\",Se=Se.args[1]}if(Se.indicator!==\"[]/0\"){S.type.is_variable(Se)?w.throw_error(S.error.instantiation(y.indicator)):w.throw_error(S.error.type(\"list\",X,y.indicator));return}else{ie.session=w.session;var at=J.toString(ie);$.stream.put(at,$.position),typeof $.position==\"number\"&&($.position+=at.length),w.success(b)}}},\"halt/0\":function(w,b,y){w.points=[]},\"halt/1\":function(w,b,y){var F=y.args[0];S.type.is_variable(F)?w.throw_error(S.error.instantiation(y.indicator)):S.type.is_integer(F)?w.points=[]:w.throw_error(S.error.type(\"integer\",F,y.indicator))},\"current_prolog_flag/2\":function(w,b,y){var F=y.args[0],J=y.args[1];if(!S.type.is_variable(F)&&!S.type.is_atom(F))w.throw_error(S.error.type(\"atom\",F,y.indicator));else if(!S.type.is_variable(F)&&!S.type.is_flag(F))w.throw_error(S.error.domain(\"prolog_flag\",F,y.indicator));else{var X=[];for(var $ in S.flag)if(S.flag.hasOwnProperty($)){var ie=new H(\",\",[new H(\"=\",[new H($),F]),new H(\"=\",[w.get_flag($),J])]);X.push(new ke(b.goal.replace(ie),b.substitution,b))}w.prepend(X)}},\"set_prolog_flag/2\":function(w,b,y){var F=y.args[0],J=y.args[1];S.type.is_variable(F)||S.type.is_variable(J)?w.throw_error(S.error.instantiation(y.indicator)):S.type.is_atom(F)?S.type.is_flag(F)?S.type.is_value_flag(F,J)?S.type.is_modifiable_flag(F)?(w.session.flag[F.id]=J,w.success(b)):w.throw_error(S.error.permission(\"modify\",\"flag\",F)):w.throw_error(S.error.domain(\"flag_value\",new H(\"+\",[F,J]),y.indicator)):w.throw_error(S.error.domain(\"prolog_flag\",F,y.indicator)):w.throw_error(S.error.type(\"atom\",F,y.indicator))}},flag:{bounded:{allowed:[new H(\"true\"),new H(\"false\")],value:new H(\"true\"),changeable:!1},max_integer:{allowed:[new Ne(Number.MAX_SAFE_INTEGER)],value:new Ne(Number.MAX_SAFE_INTEGER),changeable:!1},min_integer:{allowed:[new Ne(Number.MIN_SAFE_INTEGER)],value:new Ne(Number.MIN_SAFE_INTEGER),changeable:!1},integer_rounding_function:{allowed:[new H(\"down\"),new H(\"toward_zero\")],value:new H(\"toward_zero\"),changeable:!1},char_conversion:{allowed:[new H(\"on\"),new H(\"off\")],value:new H(\"on\"),changeable:!0},debug:{allowed:[new H(\"on\"),new H(\"off\")],value:new H(\"off\"),changeable:!0},max_arity:{allowed:[new H(\"unbounded\")],value:new H(\"unbounded\"),changeable:!1},unknown:{allowed:[new H(\"error\"),new H(\"fail\"),new H(\"warning\")],value:new H(\"error\"),changeable:!0},double_quotes:{allowed:[new H(\"chars\"),new H(\"codes\"),new H(\"atom\")],value:new H(\"codes\"),changeable:!0},occurs_check:{allowed:[new H(\"false\"),new H(\"true\")],value:new H(\"false\"),changeable:!0},dialect:{allowed:[new H(\"tau\")],value:new H(\"tau\"),changeable:!1},version_data:{allowed:[new H(\"tau\",[new Ne(t.major,!1),new Ne(t.minor,!1),new Ne(t.patch,!1),new H(t.status)])],value:new H(\"tau\",[new Ne(t.major,!1),new Ne(t.minor,!1),new Ne(t.patch,!1),new H(t.status)]),changeable:!1},nodejs:{allowed:[new H(\"yes\"),new H(\"no\")],value:new H(typeof gl<\"u\"&&gl.exports?\"yes\":\"no\"),changeable:!1}},unify:function(w,b,y){y=y===void 0?!1:y;for(var F=[{left:w,right:b}],J={};F.length!==0;){var X=F.pop();if(w=X.left,b=X.right,S.type.is_term(w)&&S.type.is_term(b)){if(w.indicator!==b.indicator)return null;for(var $=0;$<w.args.length;$++)F.push({left:w.args[$],right:b.args[$]})}else if(S.type.is_number(w)&&S.type.is_number(b)){if(w.value!==b.value||w.is_float!==b.is_float)return null}else if(S.type.is_variable(w)){if(S.type.is_variable(b)&&w.id===b.id)continue;if(y===!0&&b.variables().indexOf(w.id)!==-1)return null;if(w.id!==\"_\"){var ie=new Fe;ie.add(w.id,b);for(var $=0;$<F.length;$++)F[$].left=F[$].left.apply(ie),F[$].right=F[$].right.apply(ie);for(var $ in J)J[$]=J[$].apply(ie);J[w.id]=b}}else if(S.type.is_variable(b))F.push({left:b,right:w});else if(w.unify!==void 0){if(!w.unify(b))return null}else return null}return new Fe(J)},compare:function(w,b){var y=S.type.compare(w,b);return y!==0?y:w.compare(b)},arithmetic_compare:function(w,b,y){var F=b.interpret(w);if(S.type.is_number(F)){var J=y.interpret(w);return S.type.is_number(J)?F.value<J.value?-1:F.value>J.value?1:0:J}else return F},operate:function(w,b){if(S.type.is_operator(b)){for(var y=S.type.is_operator(b),F=[],J,X=!1,$=0;$<b.args.length;$++){if(J=b.args[$].interpret(w),S.type.is_number(J)){if(y.type_args!==null&&J.is_float!==y.type_args)return S.error.type(y.type_args?\"float\":\"integer\",J,w.__call_indicator);F.push(J.value)}else return J;X=X||J.is_float}return F.push(w),J=S.arithmetic.evaluation[b.indicator].fn.apply(this,F),X=y.type_result===null?X:y.type_result,S.type.is_term(J)?J:J===Number.POSITIVE_INFINITY||J===Number.NEGATIVE_INFINITY?S.error.evaluation(\"overflow\",w.__call_indicator):X===!1&&w.get_flag(\"bounded\").id===\"true\"&&(J>w.get_flag(\"max_integer\").value||J<w.get_flag(\"min_integer\").value)?S.error.evaluation(\"int_overflow\",w.__call_indicator):new Ne(J,X)}else return S.error.type(\"evaluable\",b.indicator,w.__call_indicator)},error:{existence:function(w,b,y){return typeof b==\"string\"&&(b=Z(b)),new H(\"error\",[new H(\"existence_error\",[new H(w),b]),Z(y)])},type:function(w,b,y){return new H(\"error\",[new H(\"type_error\",[new H(w),b]),Z(y)])},instantiation:function(w){return new H(\"error\",[new H(\"instantiation_error\"),Z(w)])},domain:function(w,b,y){return new H(\"error\",[new H(\"domain_error\",[new H(w),b]),Z(y)])},representation:function(w,b){return new H(\"error\",[new H(\"representation_error\",[new H(w)]),Z(b)])},permission:function(w,b,y,F){return new H(\"error\",[new H(\"permission_error\",[new H(w),new H(b),y]),Z(F)])},evaluation:function(w,b){return new H(\"error\",[new H(\"evaluation_error\",[new H(w)]),Z(b)])},syntax:function(w,b,y){w=w||{value:\"\",line:0,column:0,matches:[\"\"],start:0};var F=y&&w.matches.length>0?w.start+w.matches[0].length:w.start,J=y?new H(\"token_not_found\"):new H(\"found\",[new H(w.value.toString())]),X=new H(\".\",[new H(\"line\",[new Ne(w.line+1)]),new H(\".\",[new H(\"column\",[new Ne(F+1)]),new H(\".\",[J,new H(\"[]\",[])])])]);return new H(\"error\",[new H(\"syntax_error\",[new H(b)]),X])},syntax_by_predicate:function(w,b){return new H(\"error\",[new H(\"syntax_error\",[new H(w)]),Z(b)])}},warning:{singleton:function(w,b,y){for(var F=new H(\"[]\"),J=w.length-1;J>=0;J--)F=new H(\".\",[new xe(w[J]),F]);return new H(\"warning\",[new H(\"singleton_variables\",[F,Z(b)]),new H(\".\",[new H(\"line\",[new Ne(y,!1)]),new H(\"[]\")])])},failed_goal:function(w,b){return new H(\"warning\",[new H(\"failed_goal\",[w]),new H(\".\",[new H(\"line\",[new Ne(b,!1)]),new H(\"[]\")])])}},format_variable:function(w){return\"_\"+w},format_answer:function(w,b,F){b instanceof be&&(b=b.thread);var F=F||{};if(F.session=b?b.session:void 0,S.type.is_error(w))return\"uncaught exception: \"+w.args[0].toString();if(w===!1)return\"false.\";if(w===null)return\"limit exceeded ;\";var J=0,X=\"\";if(S.type.is_substitution(w)){var $=w.domain(!0);w=w.filter(function(Re,at){return!S.type.is_variable(at)||$.indexOf(at.id)!==-1&&Re!==at.id})}for(var ie in w.links)w.links.hasOwnProperty(ie)&&(J++,X!==\"\"&&(X+=\", \"),X+=ie.toString(F)+\" = \"+w.links[ie].toString(F));var Se=typeof b>\"u\"||b.points.length>0?\" ;\":\".\";return J===0?\"true\"+Se:X+Se},flatten_error:function(w){if(!S.type.is_error(w))return null;w=w.args[0];var b={};return b.type=w.args[0].id,b.thrown=b.type===\"syntax_error\"?null:w.args[1].id,b.expected=null,b.found=null,b.representation=null,b.existence=null,b.existence_type=null,b.line=null,b.column=null,b.permission_operation=null,b.permission_type=null,b.evaluation_type=null,b.type===\"type_error\"||b.type===\"domain_error\"?(b.expected=w.args[0].args[0].id,b.found=w.args[0].args[1].toString()):b.type===\"syntax_error\"?w.args[1].indicator===\"./2\"?(b.expected=w.args[0].args[0].id,b.found=w.args[1].args[1].args[1].args[0],b.found=b.found.id===\"token_not_found\"?b.found.id:b.found.args[0].id,b.line=w.args[1].args[0].args[0].value,b.column=w.args[1].args[1].args[0].args[0].value):b.thrown=w.args[1].id:b.type===\"permission_error\"?(b.found=w.args[0].args[2].toString(),b.permission_operation=w.args[0].args[0].id,b.permission_type=w.args[0].args[1].id):b.type===\"evaluation_error\"?b.evaluation_type=w.args[0].args[0].id:b.type===\"representation_error\"?b.representation=w.args[0].args[0].id:b.type===\"existence_error\"&&(b.existence=w.args[0].args[1].toString(),b.existence_type=w.args[0].args[0].id),b},create:function(w){return new S.type.Session(w)}};typeof gl<\"u\"?gl.exports=S:window.pl=S})()});function cme(t,e,r){t.prepend(r.map(o=>new La.default.type.State(e.goal.replace(o),e.substitution,e)))}function fH(t){let e=Ame.get(t.session);if(e==null)throw new Error(\"Assertion failed: A project should have been registered for the active session\");return e}function fme(t,e){Ame.set(t,e),t.consult(`:- use_module(library(${rdt.id})).`)}var pH,La,ume,Qh,edt,tdt,Ame,rdt,pme=Et(()=>{Ge();pH=Ze(e2()),La=Ze(AH()),ume=Ze(ve(\"vm\")),{is_atom:Qh,is_variable:edt,is_instantiated_list:tdt}=La.default.type;Ame=new WeakMap;rdt=new La.default.type.Module(\"constraints\",{\"project_workspaces_by_descriptor/3\":(t,e,r)=>{let[o,a,n]=r.args;if(!Qh(o)||!Qh(a)){t.throw_error(La.default.error.instantiation(r.indicator));return}let u=G.parseIdent(o.id),A=G.makeDescriptor(u,a.id),h=fH(t).tryWorkspaceByDescriptor(A);edt(n)&&h!==null&&cme(t,e,[new La.default.type.Term(\"=\",[n,new La.default.type.Term(String(h.relativeCwd))])]),Qh(n)&&h!==null&&h.relativeCwd===n.id&&t.success(e)},\"workspace_field/3\":(t,e,r)=>{let[o,a,n]=r.args;if(!Qh(o)||!Qh(a)){t.throw_error(La.default.error.instantiation(r.indicator));return}let A=fH(t).tryWorkspaceByCwd(o.id);if(A==null)return;let p=(0,pH.default)(A.manifest.raw,a.id);typeof p>\"u\"||cme(t,e,[new La.default.type.Term(\"=\",[n,new La.default.type.Term(typeof p==\"object\"?JSON.stringify(p):p)])])},\"workspace_field_test/3\":(t,e,r)=>{let[o,a,n]=r.args;t.prepend([new La.default.type.State(e.goal.replace(new La.default.type.Term(\"workspace_field_test\",[o,a,n,new La.default.type.Term(\"[]\",[])])),e.substitution,e)])},\"workspace_field_test/4\":(t,e,r)=>{let[o,a,n,u]=r.args;if(!Qh(o)||!Qh(a)||!Qh(n)||!tdt(u)){t.throw_error(La.default.error.instantiation(r.indicator));return}let p=fH(t).tryWorkspaceByCwd(o.id);if(p==null)return;let h=(0,pH.default)(p.manifest.raw,a.id);if(typeof h>\"u\")return;let E={$$:h};for(let[v,x]of u.toJavaScript().entries())E[`$${v}`]=x;ume.default.runInNewContext(n.id,E)&&t.success(e)}},[\"project_workspaces_by_descriptor/3\",\"workspace_field/3\",\"workspace_field_test/3\",\"workspace_field_test/4\"])});var A2={};Vt(A2,{Constraints:()=>gH,DependencyType:()=>mme});function to(t){if(t instanceof NE.default.type.Num)return t.value;if(t instanceof NE.default.type.Term)switch(t.indicator){case\"throw/1\":return to(t.args[0]);case\"error/1\":return to(t.args[0]);case\"error/2\":if(t.args[0]instanceof NE.default.type.Term&&t.args[0].indicator===\"syntax_error/1\")return Object.assign(to(t.args[0]),...to(t.args[1]));{let e=to(t.args[0]);return e.message+=` (in ${to(t.args[1])})`,e}case\"syntax_error/1\":return new Jt(43,`Syntax error: ${to(t.args[0])}`);case\"existence_error/2\":return new Jt(44,`Existence error: ${to(t.args[0])} ${to(t.args[1])} not found`);case\"instantiation_error/0\":return new Jt(75,\"Instantiation error: an argument is variable when an instantiated argument was expected\");case\"line/1\":return{line:to(t.args[0])};case\"column/1\":return{column:to(t.args[0])};case\"found/1\":return{found:to(t.args[0])};case\"./2\":return[to(t.args[0])].concat(to(t.args[1]));case\"//2\":return`${to(t.args[0])}/${to(t.args[1])}`;default:return t.id}throw`couldn't pretty print because of unsupported node ${t}`}function gme(t){let e;try{e=to(t)}catch(r){throw typeof r==\"string\"?new Jt(42,`Unknown error: ${t} (note: ${r})`):r}return typeof e.line<\"u\"&&typeof e.column<\"u\"&&(e.message+=` at line ${e.line}, column ${e.column}`),e}function Gg(t){return t.id===\"null\"?null:`${t.toJavaScript()}`}function ndt(t){if(t.id===\"null\")return null;{let e=t.toJavaScript();if(typeof e!=\"string\")return JSON.stringify(e);try{return JSON.stringify(JSON.parse(e))}catch{return JSON.stringify(e)}}}function Fh(t){return typeof t==\"string\"?`'${t}'`:\"[]\"}var dme,NE,mme,hme,hH,gH,f2=Et(()=>{Ge();Ge();Pt();dme=Ze(Kde()),NE=Ze(AH());l2();pme();(0,dme.default)(NE.default);mme=(o=>(o.Dependencies=\"dependencies\",o.DevDependencies=\"devDependencies\",o.PeerDependencies=\"peerDependencies\",o))(mme||{}),hme=[\"dependencies\",\"devDependencies\",\"peerDependencies\"];hH=class{constructor(e,r){let o=1e3*e.workspaces.length;this.session=NE.default.create(o),fme(this.session,e),this.session.consult(\":- use_module(library(lists)).\"),this.session.consult(r)}fetchNextAnswer(){return new Promise(e=>{this.session.answer(r=>{e(r)})})}async*makeQuery(e){let r=this.session.query(e);if(r!==!0)throw gme(r);for(;;){let o=await this.fetchNextAnswer();if(o===null)throw new Jt(79,\"Resolution limit exceeded\");if(!o)break;if(o.id===\"throw\")throw gme(o);yield o}}};gH=class t{constructor(e){this.source=\"\";this.project=e;let r=e.configuration.get(\"constraintsPath\");oe.existsSync(r)&&(this.source=oe.readFileSync(r,\"utf8\"))}static async find(e){return new t(e)}getProjectDatabase(){let e=\"\";for(let r of hme)e+=`dependency_type(${r}).\n`;for(let r of this.project.workspacesByCwd.values()){let o=r.relativeCwd;e+=`workspace(${Fh(o)}).\n`,e+=`workspace_ident(${Fh(o)}, ${Fh(G.stringifyIdent(r.anchoredLocator))}).\n`,e+=`workspace_version(${Fh(o)}, ${Fh(r.manifest.version)}).\n`;for(let a of hme)for(let n of r.manifest[a].values())e+=`workspace_has_dependency(${Fh(o)}, ${Fh(G.stringifyIdent(n))}, ${Fh(n.range)}, ${a}).\n`}return e+=`workspace(_) :- false.\n`,e+=`workspace_ident(_, _) :- false.\n`,e+=`workspace_version(_, _) :- false.\n`,e+=`workspace_has_dependency(_, _, _, _) :- false.\n`,e}getDeclarations(){let e=\"\";return e+=`gen_enforced_dependency(_, _, _, _) :- false.\n`,e+=`gen_enforced_field(_, _, _) :- false.\n`,e}get fullSource(){return`${this.getProjectDatabase()}\n${this.source}\n${this.getDeclarations()}`}createSession(){return new hH(this.project,this.fullSource)}async processClassic(){let e=this.createSession();return{enforcedDependencies:await this.genEnforcedDependencies(e),enforcedFields:await this.genEnforcedFields(e)}}async process(){let{enforcedDependencies:e,enforcedFields:r}=await this.processClassic(),o=new Map;for(let{workspace:a,dependencyIdent:n,dependencyRange:u,dependencyType:A}of e){let p=a2([A,G.stringifyIdent(n)]),h=He.getMapWithDefault(o,a.cwd);He.getMapWithDefault(h,p).set(u??void 0,new Set)}for(let{workspace:a,fieldPath:n,fieldValue:u}of r){let A=a2(n),p=He.getMapWithDefault(o,a.cwd);He.getMapWithDefault(p,A).set(JSON.parse(u)??void 0,new Set)}return{manifestUpdates:o,reportedErrors:new Map}}async genEnforcedDependencies(e){let r=[];for await(let o of e.makeQuery(\"workspace(WorkspaceCwd), dependency_type(DependencyType), gen_enforced_dependency(WorkspaceCwd, DependencyIdent, DependencyRange, DependencyType).\")){let a=V.resolve(this.project.cwd,Gg(o.links.WorkspaceCwd)),n=Gg(o.links.DependencyIdent),u=Gg(o.links.DependencyRange),A=Gg(o.links.DependencyType);if(a===null||n===null)throw new Error(\"Invalid rule\");let p=this.project.getWorkspaceByCwd(a),h=G.parseIdent(n);r.push({workspace:p,dependencyIdent:h,dependencyRange:u,dependencyType:A})}return He.sortMap(r,[({dependencyRange:o})=>o!==null?\"0\":\"1\",({workspace:o})=>G.stringifyIdent(o.anchoredLocator),({dependencyIdent:o})=>G.stringifyIdent(o)])}async genEnforcedFields(e){let r=[];for await(let o of e.makeQuery(\"workspace(WorkspaceCwd), gen_enforced_field(WorkspaceCwd, FieldPath, FieldValue).\")){let a=V.resolve(this.project.cwd,Gg(o.links.WorkspaceCwd)),n=Gg(o.links.FieldPath),u=ndt(o.links.FieldValue);if(a===null||n===null)throw new Error(\"Invalid rule\");let A=this.project.getWorkspaceByCwd(a);r.push({workspace:A,fieldPath:n,fieldValue:u})}return He.sortMap(r,[({workspace:o})=>G.stringifyIdent(o.anchoredLocator),({fieldPath:o})=>o])}async*query(e){let r=this.createSession();for await(let o of r.makeQuery(e)){let a={};for(let[n,u]of Object.entries(o.links))n!==\"_\"&&(a[n]=Gg(u));yield a}}}});var Pme=_(Ak=>{\"use strict\";Object.defineProperty(Ak,\"__esModule\",{value:!0});function b2(t){let e=[...t.caches],r=e.shift();return r===void 0?Dme():{get(o,a,n={miss:()=>Promise.resolve()}){return r.get(o,a,n).catch(()=>b2({caches:e}).get(o,a,n))},set(o,a){return r.set(o,a).catch(()=>b2({caches:e}).set(o,a))},delete(o){return r.delete(o).catch(()=>b2({caches:e}).delete(o))},clear(){return r.clear().catch(()=>b2({caches:e}).clear())}}}function Dme(){return{get(t,e,r={miss:()=>Promise.resolve()}){return e().then(a=>Promise.all([a,r.miss(a)])).then(([a])=>a)},set(t,e){return Promise.resolve(e)},delete(t){return Promise.resolve()},clear(){return Promise.resolve()}}}Ak.createFallbackableCache=b2;Ak.createNullCache=Dme});var Sme=_((MWt,bme)=>{bme.exports=Pme()});var xme=_(xH=>{\"use strict\";Object.defineProperty(xH,\"__esModule\",{value:!0});function Idt(t={serializable:!0}){let e={};return{get(r,o,a={miss:()=>Promise.resolve()}){let n=JSON.stringify(r);if(n in e)return Promise.resolve(t.serializable?JSON.parse(e[n]):e[n]);let u=o(),A=a&&a.miss||(()=>Promise.resolve());return u.then(p=>A(p)).then(()=>u)},set(r,o){return e[JSON.stringify(r)]=t.serializable?JSON.stringify(o):o,Promise.resolve(o)},delete(r){return delete e[JSON.stringify(r)],Promise.resolve()},clear(){return e={},Promise.resolve()}}}xH.createInMemoryCache=Idt});var Qme=_((UWt,kme)=>{kme.exports=xme()});var Rme=_(eu=>{\"use strict\";Object.defineProperty(eu,\"__esModule\",{value:!0});function Bdt(t,e,r){let o={\"x-algolia-api-key\":r,\"x-algolia-application-id\":e};return{headers(){return t===kH.WithinHeaders?o:{}},queryParameters(){return t===kH.WithinQueryParameters?o:{}}}}function vdt(t){let e=0,r=()=>(e++,new Promise(o=>{setTimeout(()=>{o(t(r))},Math.min(100*e,1e3))}));return t(r)}function Fme(t,e=(r,o)=>Promise.resolve()){return Object.assign(t,{wait(r){return Fme(t.then(o=>Promise.all([e(o,r),o])).then(o=>o[1]))}})}function Ddt(t){let e=t.length-1;for(e;e>0;e--){let r=Math.floor(Math.random()*(e+1)),o=t[e];t[e]=t[r],t[r]=o}return t}function Pdt(t,e){return e&&Object.keys(e).forEach(r=>{t[r]=e[r](t)}),t}function bdt(t,...e){let r=0;return t.replace(/%s/g,()=>encodeURIComponent(e[r++]))}var Sdt=\"4.22.1\",xdt=t=>()=>t.transporter.requester.destroy(),kH={WithinQueryParameters:0,WithinHeaders:1};eu.AuthMode=kH;eu.addMethods=Pdt;eu.createAuth=Bdt;eu.createRetryablePromise=vdt;eu.createWaitablePromise=Fme;eu.destroy=xdt;eu.encode=bdt;eu.shuffle=Ddt;eu.version=Sdt});var S2=_((HWt,Tme)=>{Tme.exports=Rme()});var Nme=_(QH=>{\"use strict\";Object.defineProperty(QH,\"__esModule\",{value:!0});var kdt={Delete:\"DELETE\",Get:\"GET\",Post:\"POST\",Put:\"PUT\"};QH.MethodEnum=kdt});var x2=_((jWt,Lme)=>{Lme.exports=Nme()});var Xme=_(Qi=>{\"use strict\";Object.defineProperty(Qi,\"__esModule\",{value:!0});var Ome=x2();function FH(t,e){let r=t||{},o=r.data||{};return Object.keys(r).forEach(a=>{[\"timeout\",\"headers\",\"queryParameters\",\"data\",\"cacheable\"].indexOf(a)===-1&&(o[a]=r[a])}),{data:Object.entries(o).length>0?o:void 0,timeout:r.timeout||e,headers:r.headers||{},queryParameters:r.queryParameters||{},cacheable:r.cacheable}}var k2={Read:1,Write:2,Any:3},YE={Up:1,Down:2,Timeouted:3},Ume=2*60*1e3;function TH(t,e=YE.Up){return{...t,status:e,lastUpdate:Date.now()}}function _me(t){return t.status===YE.Up||Date.now()-t.lastUpdate>Ume}function Hme(t){return t.status===YE.Timeouted&&Date.now()-t.lastUpdate<=Ume}function NH(t){return typeof t==\"string\"?{protocol:\"https\",url:t,accept:k2.Any}:{protocol:t.protocol||\"https\",url:t.url,accept:t.accept||k2.Any}}function Qdt(t,e){return Promise.all(e.map(r=>t.get(r,()=>Promise.resolve(TH(r))))).then(r=>{let o=r.filter(A=>_me(A)),a=r.filter(A=>Hme(A)),n=[...o,...a],u=n.length>0?n.map(A=>NH(A)):e;return{getTimeout(A,p){return(a.length===0&&A===0?1:a.length+3+A)*p},statelessHosts:u}})}var Fdt=({isTimedOut:t,status:e})=>!t&&~~e===0,Rdt=t=>{let e=t.status;return t.isTimedOut||Fdt(t)||~~(e/100)!==2&&~~(e/100)!==4},Tdt=({status:t})=>~~(t/100)===2,Ndt=(t,e)=>Rdt(t)?e.onRetry(t):Tdt(t)?e.onSuccess(t):e.onFail(t);function Mme(t,e,r,o){let a=[],n=Wme(r,o),u=Kme(t,o),A=r.method,p=r.method!==Ome.MethodEnum.Get?{}:{...r.data,...o.data},h={\"x-algolia-agent\":t.userAgent.value,...t.queryParameters,...p,...o.queryParameters},E=0,I=(v,x)=>{let C=v.pop();if(C===void 0)throw Jme(RH(a));let R={data:n,headers:u,method:A,url:Gme(C,r.path,h),connectTimeout:x(E,t.timeouts.connect),responseTimeout:x(E,o.timeout)},L=z=>{let te={request:R,response:z,host:C,triesLeft:v.length};return a.push(te),te},U={onSuccess:z=>qme(z),onRetry(z){let te=L(z);return z.isTimedOut&&E++,Promise.all([t.logger.info(\"Retryable failure\",LH(te)),t.hostsCache.set(C,TH(C,z.isTimedOut?YE.Timeouted:YE.Down))]).then(()=>I(v,x))},onFail(z){throw L(z),jme(z,RH(a))}};return t.requester.send(R).then(z=>Ndt(z,U))};return Qdt(t.hostsCache,e).then(v=>I([...v.statelessHosts].reverse(),v.getTimeout))}function Ldt(t){let{hostsCache:e,logger:r,requester:o,requestsCache:a,responsesCache:n,timeouts:u,userAgent:A,hosts:p,queryParameters:h,headers:E}=t,I={hostsCache:e,logger:r,requester:o,requestsCache:a,responsesCache:n,timeouts:u,userAgent:A,headers:E,queryParameters:h,hosts:p.map(v=>NH(v)),read(v,x){let C=FH(x,I.timeouts.read),R=()=>Mme(I,I.hosts.filter(z=>(z.accept&k2.Read)!==0),v,C);if((C.cacheable!==void 0?C.cacheable:v.cacheable)!==!0)return R();let U={request:v,mappedRequestOptions:C,transporter:{queryParameters:I.queryParameters,headers:I.headers}};return I.responsesCache.get(U,()=>I.requestsCache.get(U,()=>I.requestsCache.set(U,R()).then(z=>Promise.all([I.requestsCache.delete(U),z]),z=>Promise.all([I.requestsCache.delete(U),Promise.reject(z)])).then(([z,te])=>te)),{miss:z=>I.responsesCache.set(U,z)})},write(v,x){return Mme(I,I.hosts.filter(C=>(C.accept&k2.Write)!==0),v,FH(x,I.timeouts.write))}};return I}function Mdt(t){let e={value:`Algolia for JavaScript (${t})`,add(r){let o=`; ${r.segment}${r.version!==void 0?` (${r.version})`:\"\"}`;return e.value.indexOf(o)===-1&&(e.value=`${e.value}${o}`),e}};return e}function qme(t){try{return JSON.parse(t.content)}catch(e){throw zme(e.message,t)}}function jme({content:t,status:e},r){let o=t;try{o=JSON.parse(t).message}catch{}return Vme(o,e,r)}function Odt(t,...e){let r=0;return t.replace(/%s/g,()=>encodeURIComponent(e[r++]))}function Gme(t,e,r){let o=Yme(r),a=`${t.protocol}://${t.url}/${e.charAt(0)===\"/\"?e.substr(1):e}`;return o.length&&(a+=`?${o}`),a}function Yme(t){let e=r=>Object.prototype.toString.call(r)===\"[object Object]\"||Object.prototype.toString.call(r)===\"[object Array]\";return Object.keys(t).map(r=>Odt(\"%s=%s\",r,e(t[r])?JSON.stringify(t[r]):t[r])).join(\"&\")}function Wme(t,e){if(t.method===Ome.MethodEnum.Get||t.data===void 0&&e.data===void 0)return;let r=Array.isArray(t.data)?t.data:{...t.data,...e.data};return JSON.stringify(r)}function Kme(t,e){let r={...t.headers,...e.headers},o={};return Object.keys(r).forEach(a=>{let n=r[a];o[a.toLowerCase()]=n}),o}function RH(t){return t.map(e=>LH(e))}function LH(t){let e=t.request.headers[\"x-algolia-api-key\"]?{\"x-algolia-api-key\":\"*****\"}:{};return{...t,request:{...t.request,headers:{...t.request.headers,...e}}}}function Vme(t,e,r){return{name:\"ApiError\",message:t,status:e,transporterStackTrace:r}}function zme(t,e){return{name:\"DeserializationError\",message:t,response:e}}function Jme(t){return{name:\"RetryError\",message:\"Unreachable hosts - your application id may be incorrect. If the error persists, contact support@algolia.com.\",transporterStackTrace:t}}Qi.CallEnum=k2;Qi.HostStatusEnum=YE;Qi.createApiError=Vme;Qi.createDeserializationError=zme;Qi.createMappedRequestOptions=FH;Qi.createRetryError=Jme;Qi.createStatefulHost=TH;Qi.createStatelessHost=NH;Qi.createTransporter=Ldt;Qi.createUserAgent=Mdt;Qi.deserializeFailure=jme;Qi.deserializeSuccess=qme;Qi.isStatefulHostTimeouted=Hme;Qi.isStatefulHostUp=_me;Qi.serializeData=Wme;Qi.serializeHeaders=Kme;Qi.serializeQueryParameters=Yme;Qi.serializeUrl=Gme;Qi.stackFrameWithoutCredentials=LH;Qi.stackTraceWithoutCredentials=RH});var Q2=_((YWt,Zme)=>{Zme.exports=Xme()});var $me=_(Rh=>{\"use strict\";Object.defineProperty(Rh,\"__esModule\",{value:!0});var WE=S2(),Udt=Q2(),F2=x2(),_dt=t=>{let e=t.region||\"us\",r=WE.createAuth(WE.AuthMode.WithinHeaders,t.appId,t.apiKey),o=Udt.createTransporter({hosts:[{url:`analytics.${e}.algolia.com`}],...t,headers:{...r.headers(),\"content-type\":\"application/json\",...t.headers},queryParameters:{...r.queryParameters(),...t.queryParameters}}),a=t.appId;return WE.addMethods({appId:a,transporter:o},t.methods)},Hdt=t=>(e,r)=>t.transporter.write({method:F2.MethodEnum.Post,path:\"2/abtests\",data:e},r),qdt=t=>(e,r)=>t.transporter.write({method:F2.MethodEnum.Delete,path:WE.encode(\"2/abtests/%s\",e)},r),jdt=t=>(e,r)=>t.transporter.read({method:F2.MethodEnum.Get,path:WE.encode(\"2/abtests/%s\",e)},r),Gdt=t=>e=>t.transporter.read({method:F2.MethodEnum.Get,path:\"2/abtests\"},e),Ydt=t=>(e,r)=>t.transporter.write({method:F2.MethodEnum.Post,path:WE.encode(\"2/abtests/%s/stop\",e)},r);Rh.addABTest=Hdt;Rh.createAnalyticsClient=_dt;Rh.deleteABTest=qdt;Rh.getABTest=jdt;Rh.getABTests=Gdt;Rh.stopABTest=Ydt});var tye=_((KWt,eye)=>{eye.exports=$me()});var nye=_(R2=>{\"use strict\";Object.defineProperty(R2,\"__esModule\",{value:!0});var MH=S2(),Wdt=Q2(),rye=x2(),Kdt=t=>{let e=t.region||\"us\",r=MH.createAuth(MH.AuthMode.WithinHeaders,t.appId,t.apiKey),o=Wdt.createTransporter({hosts:[{url:`personalization.${e}.algolia.com`}],...t,headers:{...r.headers(),\"content-type\":\"application/json\",...t.headers},queryParameters:{...r.queryParameters(),...t.queryParameters}});return MH.addMethods({appId:t.appId,transporter:o},t.methods)},Vdt=t=>e=>t.transporter.read({method:rye.MethodEnum.Get,path:\"1/strategies/personalization\"},e),zdt=t=>(e,r)=>t.transporter.write({method:rye.MethodEnum.Post,path:\"1/strategies/personalization\",data:e},r);R2.createPersonalizationClient=Kdt;R2.getPersonalizationStrategy=Vdt;R2.setPersonalizationStrategy=zdt});var sye=_((zWt,iye)=>{iye.exports=nye()});var Eye=_(Ft=>{\"use strict\";Object.defineProperty(Ft,\"__esModule\",{value:!0});var Gt=S2(),Ma=Q2(),Ir=x2(),Jdt=ve(\"crypto\");function fk(t){let e=r=>t.request(r).then(o=>{if(t.batch!==void 0&&t.batch(o.hits),!t.shouldStop(o))return o.cursor?e({cursor:o.cursor}):e({page:(r.page||0)+1})});return e({})}var Xdt=t=>{let e=t.appId,r=Gt.createAuth(t.authMode!==void 0?t.authMode:Gt.AuthMode.WithinHeaders,e,t.apiKey),o=Ma.createTransporter({hosts:[{url:`${e}-dsn.algolia.net`,accept:Ma.CallEnum.Read},{url:`${e}.algolia.net`,accept:Ma.CallEnum.Write}].concat(Gt.shuffle([{url:`${e}-1.algolianet.com`},{url:`${e}-2.algolianet.com`},{url:`${e}-3.algolianet.com`}])),...t,headers:{...r.headers(),\"content-type\":\"application/x-www-form-urlencoded\",...t.headers},queryParameters:{...r.queryParameters(),...t.queryParameters}}),a={transporter:o,appId:e,addAlgoliaAgent(n,u){o.userAgent.add({segment:n,version:u})},clearCache(){return Promise.all([o.requestsCache.clear(),o.responsesCache.clear()]).then(()=>{})}};return Gt.addMethods(a,t.methods)};function oye(){return{name:\"MissingObjectIDError\",message:\"All objects must have an unique objectID (like a primary key) to be valid. Algolia is also able to generate objectIDs automatically but *it's not recommended*. To do it, use the `{'autoGenerateObjectIDIfNotExist': true}` option.\"}}function aye(){return{name:\"ObjectNotFoundError\",message:\"Object not found.\"}}function lye(){return{name:\"ValidUntilNotFoundError\",message:\"ValidUntil not found in given secured api key.\"}}var Zdt=t=>(e,r)=>{let{queryParameters:o,...a}=r||{},n={acl:e,...o!==void 0?{queryParameters:o}:{}},u=(A,p)=>Gt.createRetryablePromise(h=>T2(t)(A.key,p).catch(E=>{if(E.status!==404)throw E;return h()}));return Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:\"1/keys\",data:n},a),u)},$dt=t=>(e,r,o)=>{let a=Ma.createMappedRequestOptions(o);return a.queryParameters[\"X-Algolia-User-ID\"]=e,t.transporter.write({method:Ir.MethodEnum.Post,path:\"1/clusters/mapping\",data:{cluster:r}},a)},emt=t=>(e,r,o)=>t.transporter.write({method:Ir.MethodEnum.Post,path:\"1/clusters/mapping/batch\",data:{users:e,cluster:r}},o),tmt=t=>(e,r)=>Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"/1/dictionaries/%s/batch\",e),data:{clearExistingDictionaryEntries:!0,requests:{action:\"addEntry\",body:[]}}},r),(o,a)=>KE(t)(o.taskID,a)),pk=t=>(e,r,o)=>{let a=(n,u)=>N2(t)(e,{methods:{waitTask:es}}).waitTask(n.taskID,u);return Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/operation\",e),data:{operation:\"copy\",destination:r}},o),a)},rmt=t=>(e,r,o)=>pk(t)(e,r,{...o,scope:[gk.Rules]}),nmt=t=>(e,r,o)=>pk(t)(e,r,{...o,scope:[gk.Settings]}),imt=t=>(e,r,o)=>pk(t)(e,r,{...o,scope:[gk.Synonyms]}),smt=t=>(e,r)=>e.method===Ir.MethodEnum.Get?t.transporter.read(e,r):t.transporter.write(e,r),omt=t=>(e,r)=>{let o=(a,n)=>Gt.createRetryablePromise(u=>T2(t)(e,n).then(u).catch(A=>{if(A.status!==404)throw A}));return Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Delete,path:Gt.encode(\"1/keys/%s\",e)},r),o)},amt=t=>(e,r,o)=>{let a=r.map(n=>({action:\"deleteEntry\",body:{objectID:n}}));return Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"/1/dictionaries/%s/batch\",e),data:{clearExistingDictionaryEntries:!1,requests:a}},o),(n,u)=>KE(t)(n.taskID,u))},lmt=()=>(t,e)=>{let r=Ma.serializeQueryParameters(e),o=Jdt.createHmac(\"sha256\",t).update(r).digest(\"hex\");return Buffer.from(o+r).toString(\"base64\")},T2=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Get,path:Gt.encode(\"1/keys/%s\",e)},r),cye=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Get,path:Gt.encode(\"1/task/%s\",e.toString())},r),cmt=t=>e=>t.transporter.read({method:Ir.MethodEnum.Get,path:\"/1/dictionaries/*/settings\"},e),umt=t=>e=>t.transporter.read({method:Ir.MethodEnum.Get,path:\"1/logs\"},e),Amt=()=>t=>{let e=Buffer.from(t,\"base64\").toString(\"ascii\"),r=/validUntil=(\\d+)/,o=e.match(r);if(o===null)throw lye();return parseInt(o[1],10)-Math.round(new Date().getTime()/1e3)},fmt=t=>e=>t.transporter.read({method:Ir.MethodEnum.Get,path:\"1/clusters/mapping/top\"},e),pmt=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Get,path:Gt.encode(\"1/clusters/mapping/%s\",e)},r),hmt=t=>e=>{let{retrieveMappings:r,...o}=e||{};return r===!0&&(o.getClusters=!0),t.transporter.read({method:Ir.MethodEnum.Get,path:\"1/clusters/mapping/pending\"},o)},N2=t=>(e,r={})=>{let o={transporter:t.transporter,appId:t.appId,indexName:e};return Gt.addMethods(o,r.methods)},gmt=t=>e=>t.transporter.read({method:Ir.MethodEnum.Get,path:\"1/keys\"},e),dmt=t=>e=>t.transporter.read({method:Ir.MethodEnum.Get,path:\"1/clusters\"},e),mmt=t=>e=>t.transporter.read({method:Ir.MethodEnum.Get,path:\"1/indexes\"},e),ymt=t=>e=>t.transporter.read({method:Ir.MethodEnum.Get,path:\"1/clusters/mapping\"},e),Emt=t=>(e,r,o)=>{let a=(n,u)=>N2(t)(e,{methods:{waitTask:es}}).waitTask(n.taskID,u);return Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/operation\",e),data:{operation:\"move\",destination:r}},o),a)},Cmt=t=>(e,r)=>{let o=(a,n)=>Promise.all(Object.keys(a.taskID).map(u=>N2(t)(u,{methods:{waitTask:es}}).waitTask(a.taskID[u],n)));return Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:\"1/indexes/*/batch\",data:{requests:e}},r),o)},wmt=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Post,path:\"1/indexes/*/objects\",data:{requests:e}},r),Imt=t=>(e,r)=>{let o=e.map(a=>({...a,params:Ma.serializeQueryParameters(a.params||{})}));return t.transporter.read({method:Ir.MethodEnum.Post,path:\"1/indexes/*/queries\",data:{requests:o},cacheable:!0},r)},Bmt=t=>(e,r)=>Promise.all(e.map(o=>{let{facetName:a,facetQuery:n,...u}=o.params;return N2(t)(o.indexName,{methods:{searchForFacetValues:dye}}).searchForFacetValues(a,n,{...r,...u})})),vmt=t=>(e,r)=>{let o=Ma.createMappedRequestOptions(r);return o.queryParameters[\"X-Algolia-User-ID\"]=e,t.transporter.write({method:Ir.MethodEnum.Delete,path:\"1/clusters/mapping\"},o)},Dmt=t=>(e,r,o)=>{let a=r.map(n=>({action:\"addEntry\",body:n}));return Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"/1/dictionaries/%s/batch\",e),data:{clearExistingDictionaryEntries:!0,requests:a}},o),(n,u)=>KE(t)(n.taskID,u))},Pmt=t=>(e,r)=>{let o=(a,n)=>Gt.createRetryablePromise(u=>T2(t)(e,n).catch(A=>{if(A.status!==404)throw A;return u()}));return Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/keys/%s/restore\",e)},r),o)},bmt=t=>(e,r,o)=>{let a=r.map(n=>({action:\"addEntry\",body:n}));return Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"/1/dictionaries/%s/batch\",e),data:{clearExistingDictionaryEntries:!1,requests:a}},o),(n,u)=>KE(t)(n.taskID,u))},Smt=t=>(e,r,o)=>t.transporter.read({method:Ir.MethodEnum.Post,path:Gt.encode(\"/1/dictionaries/%s/search\",e),data:{query:r},cacheable:!0},o),xmt=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Post,path:\"1/clusters/mapping/search\",data:{query:e}},r),kmt=t=>(e,r)=>Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Put,path:\"/1/dictionaries/*/settings\",data:e},r),(o,a)=>KE(t)(o.taskID,a)),Qmt=t=>(e,r)=>{let o=Object.assign({},r),{queryParameters:a,...n}=r||{},u=a?{queryParameters:a}:{},A=[\"acl\",\"indexes\",\"referers\",\"restrictSources\",\"queryParameters\",\"description\",\"maxQueriesPerIPPerHour\",\"maxHitsPerQuery\"],p=E=>Object.keys(o).filter(I=>A.indexOf(I)!==-1).every(I=>{if(Array.isArray(E[I])&&Array.isArray(o[I])){let v=E[I];return v.length===o[I].length&&v.every((x,C)=>x===o[I][C])}else return E[I]===o[I]}),h=(E,I)=>Gt.createRetryablePromise(v=>T2(t)(e,I).then(x=>p(x)?Promise.resolve():v()));return Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Put,path:Gt.encode(\"1/keys/%s\",e),data:u},n),h)},KE=t=>(e,r)=>Gt.createRetryablePromise(o=>cye(t)(e,r).then(a=>a.status!==\"published\"?o():void 0)),uye=t=>(e,r)=>{let o=(a,n)=>es(t)(a.taskID,n);return Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/batch\",t.indexName),data:{requests:e}},r),o)},Fmt=t=>e=>fk({shouldStop:r=>r.cursor===void 0,...e,request:r=>t.transporter.read({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/browse\",t.indexName),data:r},e)}),Rmt=t=>e=>{let r={hitsPerPage:1e3,...e};return fk({shouldStop:o=>o.hits.length<r.hitsPerPage,...r,request(o){return mye(t)(\"\",{...r,...o}).then(a=>({...a,hits:a.hits.map(n=>(delete n._highlightResult,n))}))}})},Tmt=t=>e=>{let r={hitsPerPage:1e3,...e};return fk({shouldStop:o=>o.hits.length<r.hitsPerPage,...r,request(o){return yye(t)(\"\",{...r,...o}).then(a=>({...a,hits:a.hits.map(n=>(delete n._highlightResult,n))}))}})},hk=t=>(e,r,o)=>{let{batchSize:a,...n}=o||{},u={taskIDs:[],objectIDs:[]},A=(p=0)=>{let h=[],E;for(E=p;E<e.length&&(h.push(e[E]),h.length!==(a||1e3));E++);return h.length===0?Promise.resolve(u):uye(t)(h.map(I=>({action:r,body:I})),n).then(I=>(u.objectIDs=u.objectIDs.concat(I.objectIDs),u.taskIDs.push(I.taskID),E++,A(E)))};return Gt.createWaitablePromise(A(),(p,h)=>Promise.all(p.taskIDs.map(E=>es(t)(E,h))))},Nmt=t=>e=>Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/clear\",t.indexName)},e),(r,o)=>es(t)(r.taskID,o)),Lmt=t=>e=>{let{forwardToReplicas:r,...o}=e||{},a=Ma.createMappedRequestOptions(o);return r&&(a.queryParameters.forwardToReplicas=1),Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/rules/clear\",t.indexName)},a),(n,u)=>es(t)(n.taskID,u))},Mmt=t=>e=>{let{forwardToReplicas:r,...o}=e||{},a=Ma.createMappedRequestOptions(o);return r&&(a.queryParameters.forwardToReplicas=1),Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/synonyms/clear\",t.indexName)},a),(n,u)=>es(t)(n.taskID,u))},Omt=t=>(e,r)=>Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/deleteByQuery\",t.indexName),data:e},r),(o,a)=>es(t)(o.taskID,a)),Umt=t=>e=>Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Delete,path:Gt.encode(\"1/indexes/%s\",t.indexName)},e),(r,o)=>es(t)(r.taskID,o)),_mt=t=>(e,r)=>Gt.createWaitablePromise(Aye(t)([e],r).then(o=>({taskID:o.taskIDs[0]})),(o,a)=>es(t)(o.taskID,a)),Aye=t=>(e,r)=>{let o=e.map(a=>({objectID:a}));return hk(t)(o,Wg.DeleteObject,r)},Hmt=t=>(e,r)=>{let{forwardToReplicas:o,...a}=r||{},n=Ma.createMappedRequestOptions(a);return o&&(n.queryParameters.forwardToReplicas=1),Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Delete,path:Gt.encode(\"1/indexes/%s/rules/%s\",t.indexName,e)},n),(u,A)=>es(t)(u.taskID,A))},qmt=t=>(e,r)=>{let{forwardToReplicas:o,...a}=r||{},n=Ma.createMappedRequestOptions(a);return o&&(n.queryParameters.forwardToReplicas=1),Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Delete,path:Gt.encode(\"1/indexes/%s/synonyms/%s\",t.indexName,e)},n),(u,A)=>es(t)(u.taskID,A))},jmt=t=>e=>fye(t)(e).then(()=>!0).catch(r=>{if(r.status!==404)throw r;return!1}),Gmt=t=>(e,r,o)=>t.transporter.read({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/answers/%s/prediction\",t.indexName),data:{query:e,queryLanguages:r},cacheable:!0},o),Ymt=t=>(e,r)=>{let{query:o,paginate:a,...n}=r||{},u=0,A=()=>gye(t)(o||\"\",{...n,page:u}).then(p=>{for(let[h,E]of Object.entries(p.hits))if(e(E))return{object:E,position:parseInt(h,10),page:u};if(u++,a===!1||u>=p.nbPages)throw aye();return A()});return A()},Wmt=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Get,path:Gt.encode(\"1/indexes/%s/%s\",t.indexName,e)},r),Kmt=()=>(t,e)=>{for(let[r,o]of Object.entries(t.hits))if(o.objectID===e)return parseInt(r,10);return-1},Vmt=t=>(e,r)=>{let{attributesToRetrieve:o,...a}=r||{},n=e.map(u=>({indexName:t.indexName,objectID:u,...o?{attributesToRetrieve:o}:{}}));return t.transporter.read({method:Ir.MethodEnum.Post,path:\"1/indexes/*/objects\",data:{requests:n}},a)},zmt=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Get,path:Gt.encode(\"1/indexes/%s/rules/%s\",t.indexName,e)},r),fye=t=>e=>t.transporter.read({method:Ir.MethodEnum.Get,path:Gt.encode(\"1/indexes/%s/settings\",t.indexName),data:{getVersion:2}},e),Jmt=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Get,path:Gt.encode(\"1/indexes/%s/synonyms/%s\",t.indexName,e)},r),pye=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Get,path:Gt.encode(\"1/indexes/%s/task/%s\",t.indexName,e.toString())},r),Xmt=t=>(e,r)=>Gt.createWaitablePromise(hye(t)([e],r).then(o=>({objectID:o.objectIDs[0],taskID:o.taskIDs[0]})),(o,a)=>es(t)(o.taskID,a)),hye=t=>(e,r)=>{let{createIfNotExists:o,...a}=r||{},n=o?Wg.PartialUpdateObject:Wg.PartialUpdateObjectNoCreate;return hk(t)(e,n,a)},Zmt=t=>(e,r)=>{let{safe:o,autoGenerateObjectIDIfNotExist:a,batchSize:n,...u}=r||{},A=(C,R,L,U)=>Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/operation\",C),data:{operation:L,destination:R}},U),(z,te)=>es(t)(z.taskID,te)),p=Math.random().toString(36).substring(7),h=`${t.indexName}_tmp_${p}`,E=OH({appId:t.appId,transporter:t.transporter,indexName:h}),I=[],v=A(t.indexName,h,\"copy\",{...u,scope:[\"settings\",\"synonyms\",\"rules\"]});I.push(v);let x=(o?v.wait(u):v).then(()=>{let C=E(e,{...u,autoGenerateObjectIDIfNotExist:a,batchSize:n});return I.push(C),o?C.wait(u):C}).then(()=>{let C=A(h,t.indexName,\"move\",u);return I.push(C),o?C.wait(u):C}).then(()=>Promise.all(I)).then(([C,R,L])=>({objectIDs:R.objectIDs,taskIDs:[C.taskID,...R.taskIDs,L.taskID]}));return Gt.createWaitablePromise(x,(C,R)=>Promise.all(I.map(L=>L.wait(R))))},$mt=t=>(e,r)=>UH(t)(e,{...r,clearExistingRules:!0}),eyt=t=>(e,r)=>_H(t)(e,{...r,clearExistingSynonyms:!0}),tyt=t=>(e,r)=>Gt.createWaitablePromise(OH(t)([e],r).then(o=>({objectID:o.objectIDs[0],taskID:o.taskIDs[0]})),(o,a)=>es(t)(o.taskID,a)),OH=t=>(e,r)=>{let{autoGenerateObjectIDIfNotExist:o,...a}=r||{},n=o?Wg.AddObject:Wg.UpdateObject;if(n===Wg.UpdateObject){for(let u of e)if(u.objectID===void 0)return Gt.createWaitablePromise(Promise.reject(oye()))}return hk(t)(e,n,a)},ryt=t=>(e,r)=>UH(t)([e],r),UH=t=>(e,r)=>{let{forwardToReplicas:o,clearExistingRules:a,...n}=r||{},u=Ma.createMappedRequestOptions(n);return o&&(u.queryParameters.forwardToReplicas=1),a&&(u.queryParameters.clearExistingRules=1),Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/rules/batch\",t.indexName),data:e},u),(A,p)=>es(t)(A.taskID,p))},nyt=t=>(e,r)=>_H(t)([e],r),_H=t=>(e,r)=>{let{forwardToReplicas:o,clearExistingSynonyms:a,replaceExistingSynonyms:n,...u}=r||{},A=Ma.createMappedRequestOptions(u);return o&&(A.queryParameters.forwardToReplicas=1),(n||a)&&(A.queryParameters.replaceExistingSynonyms=1),Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/synonyms/batch\",t.indexName),data:e},A),(p,h)=>es(t)(p.taskID,h))},gye=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/query\",t.indexName),data:{query:e},cacheable:!0},r),dye=t=>(e,r,o)=>t.transporter.read({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/facets/%s/query\",t.indexName,e),data:{facetQuery:r},cacheable:!0},o),mye=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/rules/search\",t.indexName),data:{query:e}},r),yye=t=>(e,r)=>t.transporter.read({method:Ir.MethodEnum.Post,path:Gt.encode(\"1/indexes/%s/synonyms/search\",t.indexName),data:{query:e}},r),iyt=t=>(e,r)=>{let{forwardToReplicas:o,...a}=r||{},n=Ma.createMappedRequestOptions(a);return o&&(n.queryParameters.forwardToReplicas=1),Gt.createWaitablePromise(t.transporter.write({method:Ir.MethodEnum.Put,path:Gt.encode(\"1/indexes/%s/settings\",t.indexName),data:e},n),(u,A)=>es(t)(u.taskID,A))},es=t=>(e,r)=>Gt.createRetryablePromise(o=>pye(t)(e,r).then(a=>a.status!==\"published\"?o():void 0)),syt={AddObject:\"addObject\",Analytics:\"analytics\",Browser:\"browse\",DeleteIndex:\"deleteIndex\",DeleteObject:\"deleteObject\",EditSettings:\"editSettings\",Inference:\"inference\",ListIndexes:\"listIndexes\",Logs:\"logs\",Personalization:\"personalization\",Recommendation:\"recommendation\",Search:\"search\",SeeUnretrievableAttributes:\"seeUnretrievableAttributes\",Settings:\"settings\",Usage:\"usage\"},Wg={AddObject:\"addObject\",UpdateObject:\"updateObject\",PartialUpdateObject:\"partialUpdateObject\",PartialUpdateObjectNoCreate:\"partialUpdateObjectNoCreate\",DeleteObject:\"deleteObject\",DeleteIndex:\"delete\",ClearIndex:\"clear\"},gk={Settings:\"settings\",Synonyms:\"synonyms\",Rules:\"rules\"},oyt={None:\"none\",StopIfEnoughMatches:\"stopIfEnoughMatches\"},ayt={Synonym:\"synonym\",OneWaySynonym:\"oneWaySynonym\",AltCorrection1:\"altCorrection1\",AltCorrection2:\"altCorrection2\",Placeholder:\"placeholder\"};Ft.ApiKeyACLEnum=syt;Ft.BatchActionEnum=Wg;Ft.ScopeEnum=gk;Ft.StrategyEnum=oyt;Ft.SynonymEnum=ayt;Ft.addApiKey=Zdt;Ft.assignUserID=$dt;Ft.assignUserIDs=emt;Ft.batch=uye;Ft.browseObjects=Fmt;Ft.browseRules=Rmt;Ft.browseSynonyms=Tmt;Ft.chunkedBatch=hk;Ft.clearDictionaryEntries=tmt;Ft.clearObjects=Nmt;Ft.clearRules=Lmt;Ft.clearSynonyms=Mmt;Ft.copyIndex=pk;Ft.copyRules=rmt;Ft.copySettings=nmt;Ft.copySynonyms=imt;Ft.createBrowsablePromise=fk;Ft.createMissingObjectIDError=oye;Ft.createObjectNotFoundError=aye;Ft.createSearchClient=Xdt;Ft.createValidUntilNotFoundError=lye;Ft.customRequest=smt;Ft.deleteApiKey=omt;Ft.deleteBy=Omt;Ft.deleteDictionaryEntries=amt;Ft.deleteIndex=Umt;Ft.deleteObject=_mt;Ft.deleteObjects=Aye;Ft.deleteRule=Hmt;Ft.deleteSynonym=qmt;Ft.exists=jmt;Ft.findAnswers=Gmt;Ft.findObject=Ymt;Ft.generateSecuredApiKey=lmt;Ft.getApiKey=T2;Ft.getAppTask=cye;Ft.getDictionarySettings=cmt;Ft.getLogs=umt;Ft.getObject=Wmt;Ft.getObjectPosition=Kmt;Ft.getObjects=Vmt;Ft.getRule=zmt;Ft.getSecuredApiKeyRemainingValidity=Amt;Ft.getSettings=fye;Ft.getSynonym=Jmt;Ft.getTask=pye;Ft.getTopUserIDs=fmt;Ft.getUserID=pmt;Ft.hasPendingMappings=hmt;Ft.initIndex=N2;Ft.listApiKeys=gmt;Ft.listClusters=dmt;Ft.listIndices=mmt;Ft.listUserIDs=ymt;Ft.moveIndex=Emt;Ft.multipleBatch=Cmt;Ft.multipleGetObjects=wmt;Ft.multipleQueries=Imt;Ft.multipleSearchForFacetValues=Bmt;Ft.partialUpdateObject=Xmt;Ft.partialUpdateObjects=hye;Ft.removeUserID=vmt;Ft.replaceAllObjects=Zmt;Ft.replaceAllRules=$mt;Ft.replaceAllSynonyms=eyt;Ft.replaceDictionaryEntries=Dmt;Ft.restoreApiKey=Pmt;Ft.saveDictionaryEntries=bmt;Ft.saveObject=tyt;Ft.saveObjects=OH;Ft.saveRule=ryt;Ft.saveRules=UH;Ft.saveSynonym=nyt;Ft.saveSynonyms=_H;Ft.search=gye;Ft.searchDictionaryEntries=Smt;Ft.searchForFacetValues=dye;Ft.searchRules=mye;Ft.searchSynonyms=yye;Ft.searchUserIDs=xmt;Ft.setDictionarySettings=kmt;Ft.setSettings=iyt;Ft.updateApiKey=Qmt;Ft.waitAppTask=KE;Ft.waitTask=es});var wye=_((XWt,Cye)=>{Cye.exports=Eye()});var Iye=_(dk=>{\"use strict\";Object.defineProperty(dk,\"__esModule\",{value:!0});function lyt(){return{debug(t,e){return Promise.resolve()},info(t,e){return Promise.resolve()},error(t,e){return Promise.resolve()}}}var cyt={Debug:1,Info:2,Error:3};dk.LogLevelEnum=cyt;dk.createNullLogger=lyt});var vye=_(($Wt,Bye)=>{Bye.exports=Iye()});var Sye=_(HH=>{\"use strict\";Object.defineProperty(HH,\"__esModule\",{value:!0});var Dye=ve(\"http\"),Pye=ve(\"https\"),uyt=ve(\"url\"),bye={keepAlive:!0},Ayt=new Dye.Agent(bye),fyt=new Pye.Agent(bye);function pyt({agent:t,httpAgent:e,httpsAgent:r,requesterOptions:o={}}={}){let a=e||t||Ayt,n=r||t||fyt;return{send(u){return new Promise(A=>{let p=uyt.parse(u.url),h=p.query===null?p.pathname:`${p.pathname}?${p.query}`,E={...o,agent:p.protocol===\"https:\"?n:a,hostname:p.hostname,path:h,method:u.method,headers:{...o&&o.headers?o.headers:{},...u.headers},...p.port!==void 0?{port:p.port||\"\"}:{}},I=(p.protocol===\"https:\"?Pye:Dye).request(E,R=>{let L=[];R.on(\"data\",U=>{L=L.concat(U)}),R.on(\"end\",()=>{clearTimeout(x),clearTimeout(C),A({status:R.statusCode||0,content:Buffer.concat(L).toString(),isTimedOut:!1})})}),v=(R,L)=>setTimeout(()=>{I.abort(),A({status:0,content:L,isTimedOut:!0})},R*1e3),x=v(u.connectTimeout,\"Connection timeout\"),C;I.on(\"error\",R=>{clearTimeout(x),clearTimeout(C),A({status:0,content:R.message,isTimedOut:!1})}),I.once(\"response\",()=>{clearTimeout(x),C=v(u.responseTimeout,\"Socket timeout\")}),u.data!==void 0&&I.write(u.data),I.end()})},destroy(){return a.destroy(),n.destroy(),Promise.resolve()}}}HH.createNodeHttpRequester=pyt});var kye=_((tKt,xye)=>{xye.exports=Sye()});var Tye=_((rKt,Rye)=>{\"use strict\";var Qye=Sme(),hyt=Qme(),VE=tye(),jH=S2(),qH=sye(),_t=wye(),gyt=vye(),dyt=kye(),myt=Q2();function Fye(t,e,r){let o={appId:t,apiKey:e,timeouts:{connect:2,read:5,write:30},requester:dyt.createNodeHttpRequester(),logger:gyt.createNullLogger(),responsesCache:Qye.createNullCache(),requestsCache:Qye.createNullCache(),hostsCache:hyt.createInMemoryCache(),userAgent:myt.createUserAgent(jH.version).add({segment:\"Node.js\",version:process.versions.node})},a={...o,...r},n=()=>u=>qH.createPersonalizationClient({...o,...u,methods:{getPersonalizationStrategy:qH.getPersonalizationStrategy,setPersonalizationStrategy:qH.setPersonalizationStrategy}});return _t.createSearchClient({...a,methods:{search:_t.multipleQueries,searchForFacetValues:_t.multipleSearchForFacetValues,multipleBatch:_t.multipleBatch,multipleGetObjects:_t.multipleGetObjects,multipleQueries:_t.multipleQueries,copyIndex:_t.copyIndex,copySettings:_t.copySettings,copyRules:_t.copyRules,copySynonyms:_t.copySynonyms,moveIndex:_t.moveIndex,listIndices:_t.listIndices,getLogs:_t.getLogs,listClusters:_t.listClusters,multipleSearchForFacetValues:_t.multipleSearchForFacetValues,getApiKey:_t.getApiKey,addApiKey:_t.addApiKey,listApiKeys:_t.listApiKeys,updateApiKey:_t.updateApiKey,deleteApiKey:_t.deleteApiKey,restoreApiKey:_t.restoreApiKey,assignUserID:_t.assignUserID,assignUserIDs:_t.assignUserIDs,getUserID:_t.getUserID,searchUserIDs:_t.searchUserIDs,listUserIDs:_t.listUserIDs,getTopUserIDs:_t.getTopUserIDs,removeUserID:_t.removeUserID,hasPendingMappings:_t.hasPendingMappings,generateSecuredApiKey:_t.generateSecuredApiKey,getSecuredApiKeyRemainingValidity:_t.getSecuredApiKeyRemainingValidity,destroy:jH.destroy,clearDictionaryEntries:_t.clearDictionaryEntries,deleteDictionaryEntries:_t.deleteDictionaryEntries,getDictionarySettings:_t.getDictionarySettings,getAppTask:_t.getAppTask,replaceDictionaryEntries:_t.replaceDictionaryEntries,saveDictionaryEntries:_t.saveDictionaryEntries,searchDictionaryEntries:_t.searchDictionaryEntries,setDictionarySettings:_t.setDictionarySettings,waitAppTask:_t.waitAppTask,customRequest:_t.customRequest,initIndex:u=>A=>_t.initIndex(u)(A,{methods:{batch:_t.batch,delete:_t.deleteIndex,findAnswers:_t.findAnswers,getObject:_t.getObject,getObjects:_t.getObjects,saveObject:_t.saveObject,saveObjects:_t.saveObjects,search:_t.search,searchForFacetValues:_t.searchForFacetValues,waitTask:_t.waitTask,setSettings:_t.setSettings,getSettings:_t.getSettings,partialUpdateObject:_t.partialUpdateObject,partialUpdateObjects:_t.partialUpdateObjects,deleteObject:_t.deleteObject,deleteObjects:_t.deleteObjects,deleteBy:_t.deleteBy,clearObjects:_t.clearObjects,browseObjects:_t.browseObjects,getObjectPosition:_t.getObjectPosition,findObject:_t.findObject,exists:_t.exists,saveSynonym:_t.saveSynonym,saveSynonyms:_t.saveSynonyms,getSynonym:_t.getSynonym,searchSynonyms:_t.searchSynonyms,browseSynonyms:_t.browseSynonyms,deleteSynonym:_t.deleteSynonym,clearSynonyms:_t.clearSynonyms,replaceAllObjects:_t.replaceAllObjects,replaceAllSynonyms:_t.replaceAllSynonyms,searchRules:_t.searchRules,getRule:_t.getRule,deleteRule:_t.deleteRule,saveRule:_t.saveRule,saveRules:_t.saveRules,replaceAllRules:_t.replaceAllRules,browseRules:_t.browseRules,clearRules:_t.clearRules}}),initAnalytics:()=>u=>VE.createAnalyticsClient({...o,...u,methods:{addABTest:VE.addABTest,getABTest:VE.getABTest,getABTests:VE.getABTests,stopABTest:VE.stopABTest,deleteABTest:VE.deleteABTest}}),initPersonalization:n,initRecommendation:()=>u=>(a.logger.info(\"The `initRecommendation` method is deprecated. Use `initPersonalization` instead.\"),n()(u))}})}Fye.version=jH.version;Rye.exports=Fye});var YH=_((nKt,GH)=>{var Nye=Tye();GH.exports=Nye;GH.exports.default=Nye});var VH=_((sKt,Oye)=>{\"use strict\";var Mye=Object.getOwnPropertySymbols,Eyt=Object.prototype.hasOwnProperty,Cyt=Object.prototype.propertyIsEnumerable;function wyt(t){if(t==null)throw new TypeError(\"Object.assign cannot be called with null or undefined\");return Object(t)}function Iyt(){try{if(!Object.assign)return!1;var t=new String(\"abc\");if(t[5]=\"de\",Object.getOwnPropertyNames(t)[0]===\"5\")return!1;for(var e={},r=0;r<10;r++)e[\"_\"+String.fromCharCode(r)]=r;var o=Object.getOwnPropertyNames(e).map(function(n){return e[n]});if(o.join(\"\")!==\"0123456789\")return!1;var a={};return\"abcdefghijklmnopqrst\".split(\"\").forEach(function(n){a[n]=n}),Object.keys(Object.assign({},a)).join(\"\")===\"abcdefghijklmnopqrst\"}catch{return!1}}Oye.exports=Iyt()?Object.assign:function(t,e){for(var r,o=wyt(t),a,n=1;n<arguments.length;n++){r=Object(arguments[n]);for(var u in r)Eyt.call(r,u)&&(o[u]=r[u]);if(Mye){a=Mye(r);for(var A=0;A<a.length;A++)Cyt.call(r,a[A])&&(o[a[A]]=r[a[A]])}}return o}});var Jye=_(Nn=>{\"use strict\";var $H=VH(),tu=typeof Symbol==\"function\"&&Symbol.for,L2=tu?Symbol.for(\"react.element\"):60103,Byt=tu?Symbol.for(\"react.portal\"):60106,vyt=tu?Symbol.for(\"react.fragment\"):60107,Dyt=tu?Symbol.for(\"react.strict_mode\"):60108,Pyt=tu?Symbol.for(\"react.profiler\"):60114,byt=tu?Symbol.for(\"react.provider\"):60109,Syt=tu?Symbol.for(\"react.context\"):60110,xyt=tu?Symbol.for(\"react.forward_ref\"):60112,kyt=tu?Symbol.for(\"react.suspense\"):60113,Qyt=tu?Symbol.for(\"react.memo\"):60115,Fyt=tu?Symbol.for(\"react.lazy\"):60116,Uye=typeof Symbol==\"function\"&&Symbol.iterator;function M2(t){for(var e=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+t,r=1;r<arguments.length;r++)e+=\"&args[]=\"+encodeURIComponent(arguments[r]);return\"Minified React error #\"+t+\"; visit \"+e+\" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.\"}var _ye={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Hye={};function zE(t,e,r){this.props=t,this.context=e,this.refs=Hye,this.updater=r||_ye}zE.prototype.isReactComponent={};zE.prototype.setState=function(t,e){if(typeof t!=\"object\"&&typeof t!=\"function\"&&t!=null)throw Error(M2(85));this.updater.enqueueSetState(this,t,e,\"setState\")};zE.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,\"forceUpdate\")};function qye(){}qye.prototype=zE.prototype;function e6(t,e,r){this.props=t,this.context=e,this.refs=Hye,this.updater=r||_ye}var t6=e6.prototype=new qye;t6.constructor=e6;$H(t6,zE.prototype);t6.isPureReactComponent=!0;var r6={current:null},jye=Object.prototype.hasOwnProperty,Gye={key:!0,ref:!0,__self:!0,__source:!0};function Yye(t,e,r){var o,a={},n=null,u=null;if(e!=null)for(o in e.ref!==void 0&&(u=e.ref),e.key!==void 0&&(n=\"\"+e.key),e)jye.call(e,o)&&!Gye.hasOwnProperty(o)&&(a[o]=e[o]);var A=arguments.length-2;if(A===1)a.children=r;else if(1<A){for(var p=Array(A),h=0;h<A;h++)p[h]=arguments[h+2];a.children=p}if(t&&t.defaultProps)for(o in A=t.defaultProps,A)a[o]===void 0&&(a[o]=A[o]);return{$$typeof:L2,type:t,key:n,ref:u,props:a,_owner:r6.current}}function Ryt(t,e){return{$$typeof:L2,type:t.type,key:e,ref:t.ref,props:t.props,_owner:t._owner}}function n6(t){return typeof t==\"object\"&&t!==null&&t.$$typeof===L2}function Tyt(t){var e={\"=\":\"=0\",\":\":\"=2\"};return\"$\"+(\"\"+t).replace(/[=:]/g,function(r){return e[r]})}var Wye=/\\/+/g,mk=[];function Kye(t,e,r,o){if(mk.length){var a=mk.pop();return a.result=t,a.keyPrefix=e,a.func=r,a.context=o,a.count=0,a}return{result:t,keyPrefix:e,func:r,context:o,count:0}}function Vye(t){t.result=null,t.keyPrefix=null,t.func=null,t.context=null,t.count=0,10>mk.length&&mk.push(t)}function JH(t,e,r,o){var a=typeof t;(a===\"undefined\"||a===\"boolean\")&&(t=null);var n=!1;if(t===null)n=!0;else switch(a){case\"string\":case\"number\":n=!0;break;case\"object\":switch(t.$$typeof){case L2:case Byt:n=!0}}if(n)return r(o,t,e===\"\"?\".\"+zH(t,0):e),1;if(n=0,e=e===\"\"?\".\":e+\":\",Array.isArray(t))for(var u=0;u<t.length;u++){a=t[u];var A=e+zH(a,u);n+=JH(a,A,r,o)}else if(t===null||typeof t!=\"object\"?A=null:(A=Uye&&t[Uye]||t[\"@@iterator\"],A=typeof A==\"function\"?A:null),typeof A==\"function\")for(t=A.call(t),u=0;!(a=t.next()).done;)a=a.value,A=e+zH(a,u++),n+=JH(a,A,r,o);else if(a===\"object\")throw r=\"\"+t,Error(M2(31,r===\"[object Object]\"?\"object with keys {\"+Object.keys(t).join(\", \")+\"}\":r,\"\"));return n}function XH(t,e,r){return t==null?0:JH(t,\"\",e,r)}function zH(t,e){return typeof t==\"object\"&&t!==null&&t.key!=null?Tyt(t.key):e.toString(36)}function Nyt(t,e){t.func.call(t.context,e,t.count++)}function Lyt(t,e,r){var o=t.result,a=t.keyPrefix;t=t.func.call(t.context,e,t.count++),Array.isArray(t)?ZH(t,o,r,function(n){return n}):t!=null&&(n6(t)&&(t=Ryt(t,a+(!t.key||e&&e.key===t.key?\"\":(\"\"+t.key).replace(Wye,\"$&/\")+\"/\")+r)),o.push(t))}function ZH(t,e,r,o,a){var n=\"\";r!=null&&(n=(\"\"+r).replace(Wye,\"$&/\")+\"/\"),e=Kye(e,n,o,a),XH(t,Lyt,e),Vye(e)}var zye={current:null};function Kf(){var t=zye.current;if(t===null)throw Error(M2(321));return t}var Myt={ReactCurrentDispatcher:zye,ReactCurrentBatchConfig:{suspense:null},ReactCurrentOwner:r6,IsSomeRendererActing:{current:!1},assign:$H};Nn.Children={map:function(t,e,r){if(t==null)return t;var o=[];return ZH(t,o,null,e,r),o},forEach:function(t,e,r){if(t==null)return t;e=Kye(null,null,e,r),XH(t,Nyt,e),Vye(e)},count:function(t){return XH(t,function(){return null},null)},toArray:function(t){var e=[];return ZH(t,e,null,function(r){return r}),e},only:function(t){if(!n6(t))throw Error(M2(143));return t}};Nn.Component=zE;Nn.Fragment=vyt;Nn.Profiler=Pyt;Nn.PureComponent=e6;Nn.StrictMode=Dyt;Nn.Suspense=kyt;Nn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=Myt;Nn.cloneElement=function(t,e,r){if(t==null)throw Error(M2(267,t));var o=$H({},t.props),a=t.key,n=t.ref,u=t._owner;if(e!=null){if(e.ref!==void 0&&(n=e.ref,u=r6.current),e.key!==void 0&&(a=\"\"+e.key),t.type&&t.type.defaultProps)var A=t.type.defaultProps;for(p in e)jye.call(e,p)&&!Gye.hasOwnProperty(p)&&(o[p]=e[p]===void 0&&A!==void 0?A[p]:e[p])}var p=arguments.length-2;if(p===1)o.children=r;else if(1<p){A=Array(p);for(var h=0;h<p;h++)A[h]=arguments[h+2];o.children=A}return{$$typeof:L2,type:t.type,key:a,ref:n,props:o,_owner:u}};Nn.createContext=function(t,e){return e===void 0&&(e=null),t={$$typeof:Syt,_calculateChangedBits:e,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null},t.Provider={$$typeof:byt,_context:t},t.Consumer=t};Nn.createElement=Yye;Nn.createFactory=function(t){var e=Yye.bind(null,t);return e.type=t,e};Nn.createRef=function(){return{current:null}};Nn.forwardRef=function(t){return{$$typeof:xyt,render:t}};Nn.isValidElement=n6;Nn.lazy=function(t){return{$$typeof:Fyt,_ctor:t,_status:-1,_result:null}};Nn.memo=function(t,e){return{$$typeof:Qyt,type:t,compare:e===void 0?null:e}};Nn.useCallback=function(t,e){return Kf().useCallback(t,e)};Nn.useContext=function(t,e){return Kf().useContext(t,e)};Nn.useDebugValue=function(){};Nn.useEffect=function(t,e){return Kf().useEffect(t,e)};Nn.useImperativeHandle=function(t,e,r){return Kf().useImperativeHandle(t,e,r)};Nn.useLayoutEffect=function(t,e){return Kf().useLayoutEffect(t,e)};Nn.useMemo=function(t,e){return Kf().useMemo(t,e)};Nn.useReducer=function(t,e,r){return Kf().useReducer(t,e,r)};Nn.useRef=function(t){return Kf().useRef(t)};Nn.useState=function(t){return Kf().useState(t)};Nn.version=\"16.13.1\"});var an=_((aKt,Xye)=>{\"use strict\";Xye.exports=Jye()});var s6=_((lKt,i6)=>{\"use strict\";var fn=i6.exports;i6.exports.default=fn;var Ln=\"\\x1B[\",O2=\"\\x1B]\",JE=\"\\x07\",yk=\";\",Zye=process.env.TERM_PROGRAM===\"Apple_Terminal\";fn.cursorTo=(t,e)=>{if(typeof t!=\"number\")throw new TypeError(\"The `x` argument is required\");return typeof e!=\"number\"?Ln+(t+1)+\"G\":Ln+(e+1)+\";\"+(t+1)+\"H\"};fn.cursorMove=(t,e)=>{if(typeof t!=\"number\")throw new TypeError(\"The `x` argument is required\");let r=\"\";return t<0?r+=Ln+-t+\"D\":t>0&&(r+=Ln+t+\"C\"),e<0?r+=Ln+-e+\"A\":e>0&&(r+=Ln+e+\"B\"),r};fn.cursorUp=(t=1)=>Ln+t+\"A\";fn.cursorDown=(t=1)=>Ln+t+\"B\";fn.cursorForward=(t=1)=>Ln+t+\"C\";fn.cursorBackward=(t=1)=>Ln+t+\"D\";fn.cursorLeft=Ln+\"G\";fn.cursorSavePosition=Zye?\"\\x1B7\":Ln+\"s\";fn.cursorRestorePosition=Zye?\"\\x1B8\":Ln+\"u\";fn.cursorGetPosition=Ln+\"6n\";fn.cursorNextLine=Ln+\"E\";fn.cursorPrevLine=Ln+\"F\";fn.cursorHide=Ln+\"?25l\";fn.cursorShow=Ln+\"?25h\";fn.eraseLines=t=>{let e=\"\";for(let r=0;r<t;r++)e+=fn.eraseLine+(r<t-1?fn.cursorUp():\"\");return t&&(e+=fn.cursorLeft),e};fn.eraseEndLine=Ln+\"K\";fn.eraseStartLine=Ln+\"1K\";fn.eraseLine=Ln+\"2K\";fn.eraseDown=Ln+\"J\";fn.eraseUp=Ln+\"1J\";fn.eraseScreen=Ln+\"2J\";fn.scrollUp=Ln+\"S\";fn.scrollDown=Ln+\"T\";fn.clearScreen=\"\\x1Bc\";fn.clearTerminal=process.platform===\"win32\"?`${fn.eraseScreen}${Ln}0f`:`${fn.eraseScreen}${Ln}3J${Ln}H`;fn.beep=JE;fn.link=(t,e)=>[O2,\"8\",yk,yk,e,JE,t,O2,\"8\",yk,yk,JE].join(\"\");fn.image=(t,e={})=>{let r=`${O2}1337;File=inline=1`;return e.width&&(r+=`;width=${e.width}`),e.height&&(r+=`;height=${e.height}`),e.preserveAspectRatio===!1&&(r+=\";preserveAspectRatio=0\"),r+\":\"+t.toString(\"base64\")+JE};fn.iTerm={setCwd:(t=process.cwd())=>`${O2}50;CurrentDir=${t}${JE}`,annotation:(t,e={})=>{let r=`${O2}1337;`,o=typeof e.x<\"u\",a=typeof e.y<\"u\";if((o||a)&&!(o&&a&&typeof e.length<\"u\"))throw new Error(\"`x`, `y` and `length` must be defined when `x` or `y` is defined\");return t=t.replace(/\\|/g,\"\"),r+=e.isHidden?\"AddHiddenAnnotation=\":\"AddAnnotation=\",e.length>0?r+=(o?[t,e.length,e.x,e.y]:[e.length,t]).join(\"|\"):r+=t,r+JE}}});var eEe=_((cKt,o6)=>{\"use strict\";var $ye=(t,e)=>{for(let r of Reflect.ownKeys(e))Object.defineProperty(t,r,Object.getOwnPropertyDescriptor(e,r));return t};o6.exports=$ye;o6.exports.default=$ye});var rEe=_((uKt,Ck)=>{\"use strict\";var Oyt=eEe(),Ek=new WeakMap,tEe=(t,e={})=>{if(typeof t!=\"function\")throw new TypeError(\"Expected a function\");let r,o=0,a=t.displayName||t.name||\"<anonymous>\",n=function(...u){if(Ek.set(n,++o),o===1)r=t.apply(this,u),t=null;else if(e.throw===!0)throw new Error(`Function \\`${a}\\` can only be called once`);return r};return Oyt(n,t),Ek.set(n,o),n};Ck.exports=tEe;Ck.exports.default=tEe;Ck.exports.callCount=t=>{if(!Ek.has(t))throw new Error(`The given function \\`${t.name}\\` is not wrapped by the \\`onetime\\` package`);return Ek.get(t)}});var nEe=_((AKt,wk)=>{wk.exports=[\"SIGABRT\",\"SIGALRM\",\"SIGHUP\",\"SIGINT\",\"SIGTERM\"];process.platform!==\"win32\"&&wk.exports.push(\"SIGVTALRM\",\"SIGXCPU\",\"SIGXFSZ\",\"SIGUSR2\",\"SIGTRAP\",\"SIGSYS\",\"SIGQUIT\",\"SIGIOT\");process.platform===\"linux\"&&wk.exports.push(\"SIGIO\",\"SIGPOLL\",\"SIGPWR\",\"SIGSTKFLT\",\"SIGUNUSED\")});var c6=_((fKt,$E)=>{var yi=global.process,Kg=function(t){return t&&typeof t==\"object\"&&typeof t.removeListener==\"function\"&&typeof t.emit==\"function\"&&typeof t.reallyExit==\"function\"&&typeof t.listeners==\"function\"&&typeof t.kill==\"function\"&&typeof t.pid==\"number\"&&typeof t.on==\"function\"};Kg(yi)?(iEe=ve(\"assert\"),XE=nEe(),sEe=/^win/i.test(yi.platform),U2=ve(\"events\"),typeof U2!=\"function\"&&(U2=U2.EventEmitter),yi.__signal_exit_emitter__?Ls=yi.__signal_exit_emitter__:(Ls=yi.__signal_exit_emitter__=new U2,Ls.count=0,Ls.emitted={}),Ls.infinite||(Ls.setMaxListeners(1/0),Ls.infinite=!0),$E.exports=function(t,e){if(!Kg(global.process))return function(){};iEe.equal(typeof t,\"function\",\"a callback must be provided for exit handler\"),ZE===!1&&a6();var r=\"exit\";e&&e.alwaysLast&&(r=\"afterexit\");var o=function(){Ls.removeListener(r,t),Ls.listeners(\"exit\").length===0&&Ls.listeners(\"afterexit\").length===0&&Ik()};return Ls.on(r,t),o},Ik=function(){!ZE||!Kg(global.process)||(ZE=!1,XE.forEach(function(e){try{yi.removeListener(e,Bk[e])}catch{}}),yi.emit=vk,yi.reallyExit=l6,Ls.count-=1)},$E.exports.unload=Ik,Vg=function(e,r,o){Ls.emitted[e]||(Ls.emitted[e]=!0,Ls.emit(e,r,o))},Bk={},XE.forEach(function(t){Bk[t]=function(){if(Kg(global.process)){var r=yi.listeners(t);r.length===Ls.count&&(Ik(),Vg(\"exit\",null,t),Vg(\"afterexit\",null,t),sEe&&t===\"SIGHUP\"&&(t=\"SIGINT\"),yi.kill(yi.pid,t))}}}),$E.exports.signals=function(){return XE},ZE=!1,a6=function(){ZE||!Kg(global.process)||(ZE=!0,Ls.count+=1,XE=XE.filter(function(e){try{return yi.on(e,Bk[e]),!0}catch{return!1}}),yi.emit=aEe,yi.reallyExit=oEe)},$E.exports.load=a6,l6=yi.reallyExit,oEe=function(e){Kg(global.process)&&(yi.exitCode=e||0,Vg(\"exit\",yi.exitCode,null),Vg(\"afterexit\",yi.exitCode,null),l6.call(yi,yi.exitCode))},vk=yi.emit,aEe=function(e,r){if(e===\"exit\"&&Kg(global.process)){r!==void 0&&(yi.exitCode=r);var o=vk.apply(this,arguments);return Vg(\"exit\",yi.exitCode,null),Vg(\"afterexit\",yi.exitCode,null),o}else return vk.apply(this,arguments)}):$E.exports=function(){return function(){}};var iEe,XE,sEe,U2,Ls,Ik,Vg,Bk,ZE,a6,l6,oEe,vk,aEe});var cEe=_((pKt,lEe)=>{\"use strict\";var Uyt=rEe(),_yt=c6();lEe.exports=Uyt(()=>{_yt(()=>{process.stderr.write(\"\\x1B[?25h\")},{alwaysLast:!0})})});var u6=_(eC=>{\"use strict\";var Hyt=cEe(),Dk=!1;eC.show=(t=process.stderr)=>{t.isTTY&&(Dk=!1,t.write(\"\\x1B[?25h\"))};eC.hide=(t=process.stderr)=>{t.isTTY&&(Hyt(),Dk=!0,t.write(\"\\x1B[?25l\"))};eC.toggle=(t,e)=>{t!==void 0&&(Dk=t),Dk?eC.show(e):eC.hide(e)}});var pEe=_(_2=>{\"use strict\";var fEe=_2&&_2.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(_2,\"__esModule\",{value:!0});var uEe=fEe(s6()),AEe=fEe(u6()),qyt=(t,{showCursor:e=!1}={})=>{let r=0,o=\"\",a=!1,n=u=>{!e&&!a&&(AEe.default.hide(),a=!0);let A=u+`\n`;A!==o&&(o=A,t.write(uEe.default.eraseLines(r)+A),r=A.split(`\n`).length)};return n.clear=()=>{t.write(uEe.default.eraseLines(r)),o=\"\",r=0},n.done=()=>{o=\"\",r=0,e||(AEe.default.show(),a=!1)},n};_2.default={create:qyt}});var hEe=_((dKt,jyt)=>{jyt.exports=[{name:\"AppVeyor\",constant:\"APPVEYOR\",env:\"APPVEYOR\",pr:\"APPVEYOR_PULL_REQUEST_NUMBER\"},{name:\"Azure Pipelines\",constant:\"AZURE_PIPELINES\",env:\"SYSTEM_TEAMFOUNDATIONCOLLECTIONURI\",pr:\"SYSTEM_PULLREQUEST_PULLREQUESTID\"},{name:\"Bamboo\",constant:\"BAMBOO\",env:\"bamboo_planKey\"},{name:\"Bitbucket Pipelines\",constant:\"BITBUCKET\",env:\"BITBUCKET_COMMIT\",pr:\"BITBUCKET_PR_ID\"},{name:\"Bitrise\",constant:\"BITRISE\",env:\"BITRISE_IO\",pr:\"BITRISE_PULL_REQUEST\"},{name:\"Buddy\",constant:\"BUDDY\",env:\"BUDDY_WORKSPACE_ID\",pr:\"BUDDY_EXECUTION_PULL_REQUEST_ID\"},{name:\"Buildkite\",constant:\"BUILDKITE\",env:\"BUILDKITE\",pr:{env:\"BUILDKITE_PULL_REQUEST\",ne:\"false\"}},{name:\"CircleCI\",constant:\"CIRCLE\",env:\"CIRCLECI\",pr:\"CIRCLE_PULL_REQUEST\"},{name:\"Cirrus CI\",constant:\"CIRRUS\",env:\"CIRRUS_CI\",pr:\"CIRRUS_PR\"},{name:\"AWS CodeBuild\",constant:\"CODEBUILD\",env:\"CODEBUILD_BUILD_ARN\"},{name:\"Codeship\",constant:\"CODESHIP\",env:{CI_NAME:\"codeship\"}},{name:\"Drone\",constant:\"DRONE\",env:\"DRONE\",pr:{DRONE_BUILD_EVENT:\"pull_request\"}},{name:\"dsari\",constant:\"DSARI\",env:\"DSARI\"},{name:\"GitLab CI\",constant:\"GITLAB\",env:\"GITLAB_CI\"},{name:\"GoCD\",constant:\"GOCD\",env:\"GO_PIPELINE_LABEL\"},{name:\"Hudson\",constant:\"HUDSON\",env:\"HUDSON_URL\"},{name:\"Jenkins\",constant:\"JENKINS\",env:[\"JENKINS_URL\",\"BUILD_ID\"],pr:{any:[\"ghprbPullId\",\"CHANGE_ID\"]}},{name:\"Magnum CI\",constant:\"MAGNUM\",env:\"MAGNUM\"},{name:\"Netlify CI\",constant:\"NETLIFY\",env:\"NETLIFY_BUILD_BASE\",pr:{env:\"PULL_REQUEST\",ne:\"false\"}},{name:\"Sail CI\",constant:\"SAIL\",env:\"SAILCI\",pr:\"SAIL_PULL_REQUEST_NUMBER\"},{name:\"Semaphore\",constant:\"SEMAPHORE\",env:\"SEMAPHORE\",pr:\"PULL_REQUEST_NUMBER\"},{name:\"Shippable\",constant:\"SHIPPABLE\",env:\"SHIPPABLE\",pr:{IS_PULL_REQUEST:\"true\"}},{name:\"Solano CI\",constant:\"SOLANO\",env:\"TDDIUM\",pr:\"TDDIUM_PR_ID\"},{name:\"Strider CD\",constant:\"STRIDER\",env:\"STRIDER\"},{name:\"TaskCluster\",constant:\"TASKCLUSTER\",env:[\"TASK_ID\",\"RUN_ID\"]},{name:\"TeamCity\",constant:\"TEAMCITY\",env:\"TEAMCITY_VERSION\"},{name:\"Travis CI\",constant:\"TRAVIS\",env:\"TRAVIS\",pr:{env:\"TRAVIS_PULL_REQUEST\",ne:\"false\"}}]});var mEe=_(dl=>{\"use strict\";var dEe=hEe(),pA=process.env;Object.defineProperty(dl,\"_vendors\",{value:dEe.map(function(t){return t.constant})});dl.name=null;dl.isPR=null;dEe.forEach(function(t){var e=Array.isArray(t.env)?t.env:[t.env],r=e.every(function(o){return gEe(o)});if(dl[t.constant]=r,r)switch(dl.name=t.name,typeof t.pr){case\"string\":dl.isPR=!!pA[t.pr];break;case\"object\":\"env\"in t.pr?dl.isPR=t.pr.env in pA&&pA[t.pr.env]!==t.pr.ne:\"any\"in t.pr?dl.isPR=t.pr.any.some(function(o){return!!pA[o]}):dl.isPR=gEe(t.pr);break;default:dl.isPR=null}});dl.isCI=!!(pA.CI||pA.CONTINUOUS_INTEGRATION||pA.BUILD_NUMBER||pA.RUN_ID||dl.name);function gEe(t){return typeof t==\"string\"?!!pA[t]:Object.keys(t).every(function(e){return pA[e]===t[e]})}});var EEe=_((yKt,yEe)=>{\"use strict\";yEe.exports=mEe().isCI});var wEe=_((EKt,CEe)=>{\"use strict\";var Gyt=t=>{let e=new Set;do for(let r of Reflect.ownKeys(t))e.add([t,r]);while((t=Reflect.getPrototypeOf(t))&&t!==Object.prototype);return e};CEe.exports=(t,{include:e,exclude:r}={})=>{let o=a=>{let n=u=>typeof u==\"string\"?a===u:u.test(a);return e?e.some(n):r?!r.some(n):!0};for(let[a,n]of Gyt(t.constructor.prototype)){if(n===\"constructor\"||!o(n))continue;let u=Reflect.getOwnPropertyDescriptor(a,n);u&&typeof u.value==\"function\"&&(t[n]=t[n].bind(t))}return t}});var SEe=_(kn=>{\"use strict\";Object.defineProperty(kn,\"__esModule\",{value:!0});var rC,j2,kk,Qk,m6;typeof window>\"u\"||typeof MessageChannel!=\"function\"?(tC=null,A6=null,f6=function(){if(tC!==null)try{var t=kn.unstable_now();tC(!0,t),tC=null}catch(e){throw setTimeout(f6,0),e}},IEe=Date.now(),kn.unstable_now=function(){return Date.now()-IEe},rC=function(t){tC!==null?setTimeout(rC,0,t):(tC=t,setTimeout(f6,0))},j2=function(t,e){A6=setTimeout(t,e)},kk=function(){clearTimeout(A6)},Qk=function(){return!1},m6=kn.unstable_forceFrameRate=function(){}):(Pk=window.performance,p6=window.Date,BEe=window.setTimeout,vEe=window.clearTimeout,typeof console<\"u\"&&(DEe=window.cancelAnimationFrame,typeof window.requestAnimationFrame!=\"function\"&&console.error(\"This browser doesn't support requestAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills\"),typeof DEe!=\"function\"&&console.error(\"This browser doesn't support cancelAnimationFrame. Make sure that you load a polyfill in older browsers. https://fb.me/react-polyfills\")),typeof Pk==\"object\"&&typeof Pk.now==\"function\"?kn.unstable_now=function(){return Pk.now()}:(PEe=p6.now(),kn.unstable_now=function(){return p6.now()-PEe}),H2=!1,q2=null,bk=-1,h6=5,g6=0,Qk=function(){return kn.unstable_now()>=g6},m6=function(){},kn.unstable_forceFrameRate=function(t){0>t||125<t?console.error(\"forceFrameRate takes a positive int between 0 and 125, forcing framerates higher than 125 fps is not unsupported\"):h6=0<t?Math.floor(1e3/t):5},d6=new MessageChannel,Sk=d6.port2,d6.port1.onmessage=function(){if(q2!==null){var t=kn.unstable_now();g6=t+h6;try{q2(!0,t)?Sk.postMessage(null):(H2=!1,q2=null)}catch(e){throw Sk.postMessage(null),e}}else H2=!1},rC=function(t){q2=t,H2||(H2=!0,Sk.postMessage(null))},j2=function(t,e){bk=BEe(function(){t(kn.unstable_now())},e)},kk=function(){vEe(bk),bk=-1});var tC,A6,f6,IEe,Pk,p6,BEe,vEe,DEe,PEe,H2,q2,bk,h6,g6,d6,Sk;function y6(t,e){var r=t.length;t.push(e);e:for(;;){var o=Math.floor((r-1)/2),a=t[o];if(a!==void 0&&0<xk(a,e))t[o]=e,t[r]=a,r=o;else break e}}function nc(t){return t=t[0],t===void 0?null:t}function Fk(t){var e=t[0];if(e!==void 0){var r=t.pop();if(r!==e){t[0]=r;e:for(var o=0,a=t.length;o<a;){var n=2*(o+1)-1,u=t[n],A=n+1,p=t[A];if(u!==void 0&&0>xk(u,r))p!==void 0&&0>xk(p,u)?(t[o]=p,t[A]=r,o=A):(t[o]=u,t[n]=r,o=n);else if(p!==void 0&&0>xk(p,r))t[o]=p,t[A]=r,o=A;else break e}}return e}return null}function xk(t,e){var r=t.sortIndex-e.sortIndex;return r!==0?r:t.id-e.id}var ru=[],Th=[],Yyt=1,sa=null,Lo=3,Rk=!1,zg=!1,G2=!1;function Tk(t){for(var e=nc(Th);e!==null;){if(e.callback===null)Fk(Th);else if(e.startTime<=t)Fk(Th),e.sortIndex=e.expirationTime,y6(ru,e);else break;e=nc(Th)}}function E6(t){if(G2=!1,Tk(t),!zg)if(nc(ru)!==null)zg=!0,rC(C6);else{var e=nc(Th);e!==null&&j2(E6,e.startTime-t)}}function C6(t,e){zg=!1,G2&&(G2=!1,kk()),Rk=!0;var r=Lo;try{for(Tk(e),sa=nc(ru);sa!==null&&(!(sa.expirationTime>e)||t&&!Qk());){var o=sa.callback;if(o!==null){sa.callback=null,Lo=sa.priorityLevel;var a=o(sa.expirationTime<=e);e=kn.unstable_now(),typeof a==\"function\"?sa.callback=a:sa===nc(ru)&&Fk(ru),Tk(e)}else Fk(ru);sa=nc(ru)}if(sa!==null)var n=!0;else{var u=nc(Th);u!==null&&j2(E6,u.startTime-e),n=!1}return n}finally{sa=null,Lo=r,Rk=!1}}function bEe(t){switch(t){case 1:return-1;case 2:return 250;case 5:return 1073741823;case 4:return 1e4;default:return 5e3}}var Wyt=m6;kn.unstable_ImmediatePriority=1;kn.unstable_UserBlockingPriority=2;kn.unstable_NormalPriority=3;kn.unstable_IdlePriority=5;kn.unstable_LowPriority=4;kn.unstable_runWithPriority=function(t,e){switch(t){case 1:case 2:case 3:case 4:case 5:break;default:t=3}var r=Lo;Lo=t;try{return e()}finally{Lo=r}};kn.unstable_next=function(t){switch(Lo){case 1:case 2:case 3:var e=3;break;default:e=Lo}var r=Lo;Lo=e;try{return t()}finally{Lo=r}};kn.unstable_scheduleCallback=function(t,e,r){var o=kn.unstable_now();if(typeof r==\"object\"&&r!==null){var a=r.delay;a=typeof a==\"number\"&&0<a?o+a:o,r=typeof r.timeout==\"number\"?r.timeout:bEe(t)}else r=bEe(t),a=o;return r=a+r,t={id:Yyt++,callback:e,priorityLevel:t,startTime:a,expirationTime:r,sortIndex:-1},a>o?(t.sortIndex=a,y6(Th,t),nc(ru)===null&&t===nc(Th)&&(G2?kk():G2=!0,j2(E6,a-o))):(t.sortIndex=r,y6(ru,t),zg||Rk||(zg=!0,rC(C6))),t};kn.unstable_cancelCallback=function(t){t.callback=null};kn.unstable_wrapCallback=function(t){var e=Lo;return function(){var r=Lo;Lo=e;try{return t.apply(this,arguments)}finally{Lo=r}}};kn.unstable_getCurrentPriorityLevel=function(){return Lo};kn.unstable_shouldYield=function(){var t=kn.unstable_now();Tk(t);var e=nc(ru);return e!==sa&&sa!==null&&e!==null&&e.callback!==null&&e.startTime<=t&&e.expirationTime<sa.expirationTime||Qk()};kn.unstable_requestPaint=Wyt;kn.unstable_continueExecution=function(){zg||Rk||(zg=!0,rC(C6))};kn.unstable_pauseExecution=function(){};kn.unstable_getFirstCallbackNode=function(){return nc(ru)};kn.unstable_Profiling=null});var w6=_((wKt,xEe)=>{\"use strict\";xEe.exports=SEe()});var kEe=_((IKt,Y2)=>{Y2.exports=function t(e){\"use strict\";var r=VH(),o=an(),a=w6();function n(P){for(var D=\"https://reactjs.org/docs/error-decoder.html?invariant=\"+P,T=1;T<arguments.length;T++)D+=\"&args[]=\"+encodeURIComponent(arguments[T]);return\"Minified React error #\"+P+\"; visit \"+D+\" for the full message or use the non-minified dev environment for full errors and additional helpful warnings.\"}var u=o.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED;u.hasOwnProperty(\"ReactCurrentDispatcher\")||(u.ReactCurrentDispatcher={current:null}),u.hasOwnProperty(\"ReactCurrentBatchConfig\")||(u.ReactCurrentBatchConfig={suspense:null});var A=typeof Symbol==\"function\"&&Symbol.for,p=A?Symbol.for(\"react.element\"):60103,h=A?Symbol.for(\"react.portal\"):60106,E=A?Symbol.for(\"react.fragment\"):60107,I=A?Symbol.for(\"react.strict_mode\"):60108,v=A?Symbol.for(\"react.profiler\"):60114,x=A?Symbol.for(\"react.provider\"):60109,C=A?Symbol.for(\"react.context\"):60110,R=A?Symbol.for(\"react.concurrent_mode\"):60111,L=A?Symbol.for(\"react.forward_ref\"):60112,U=A?Symbol.for(\"react.suspense\"):60113,z=A?Symbol.for(\"react.suspense_list\"):60120,te=A?Symbol.for(\"react.memo\"):60115,ae=A?Symbol.for(\"react.lazy\"):60116;A&&Symbol.for(\"react.fundamental\"),A&&Symbol.for(\"react.responder\"),A&&Symbol.for(\"react.scope\");var le=typeof Symbol==\"function\"&&Symbol.iterator;function ce(P){return P===null||typeof P!=\"object\"?null:(P=le&&P[le]||P[\"@@iterator\"],typeof P==\"function\"?P:null)}function Ce(P){if(P._status===-1){P._status=0;var D=P._ctor;D=D(),P._result=D,D.then(function(T){P._status===0&&(T=T.default,P._status=1,P._result=T)},function(T){P._status===0&&(P._status=2,P._result=T)})}}function de(P){if(P==null)return null;if(typeof P==\"function\")return P.displayName||P.name||null;if(typeof P==\"string\")return P;switch(P){case E:return\"Fragment\";case h:return\"Portal\";case v:return\"Profiler\";case I:return\"StrictMode\";case U:return\"Suspense\";case z:return\"SuspenseList\"}if(typeof P==\"object\")switch(P.$$typeof){case C:return\"Context.Consumer\";case x:return\"Context.Provider\";case L:var D=P.render;return D=D.displayName||D.name||\"\",P.displayName||(D!==\"\"?\"ForwardRef(\"+D+\")\":\"ForwardRef\");case te:return de(P.type);case ae:if(P=P._status===1?P._result:null)return de(P)}return null}function Be(P){var D=P,T=P;if(P.alternate)for(;D.return;)D=D.return;else{P=D;do D=P,D.effectTag&1026&&(T=D.return),P=D.return;while(P)}return D.tag===3?T:null}function Ee(P){if(Be(P)!==P)throw Error(n(188))}function g(P){var D=P.alternate;if(!D){if(D=Be(P),D===null)throw Error(n(188));return D!==P?null:P}for(var T=P,q=D;;){var W=T.return;if(W===null)break;var fe=W.alternate;if(fe===null){if(q=W.return,q!==null){T=q;continue}break}if(W.child===fe.child){for(fe=W.child;fe;){if(fe===T)return Ee(W),P;if(fe===q)return Ee(W),D;fe=fe.sibling}throw Error(n(188))}if(T.return!==q.return)T=W,q=fe;else{for(var De=!1,vt=W.child;vt;){if(vt===T){De=!0,T=W,q=fe;break}if(vt===q){De=!0,q=W,T=fe;break}vt=vt.sibling}if(!De){for(vt=fe.child;vt;){if(vt===T){De=!0,T=fe,q=W;break}if(vt===q){De=!0,q=fe,T=W;break}vt=vt.sibling}if(!De)throw Error(n(189))}}if(T.alternate!==q)throw Error(n(190))}if(T.tag!==3)throw Error(n(188));return T.stateNode.current===T?P:D}function me(P){if(P=g(P),!P)return null;for(var D=P;;){if(D.tag===5||D.tag===6)return D;if(D.child)D.child.return=D,D=D.child;else{if(D===P)break;for(;!D.sibling;){if(!D.return||D.return===P)return null;D=D.return}D.sibling.return=D.return,D=D.sibling}}return null}function we(P){if(P=g(P),!P)return null;for(var D=P;;){if(D.tag===5||D.tag===6)return D;if(D.child&&D.tag!==4)D.child.return=D,D=D.child;else{if(D===P)break;for(;!D.sibling;){if(!D.return||D.return===P)return null;D=D.return}D.sibling.return=D.return,D=D.sibling}}return null}var Ae=e.getPublicInstance,ne=e.getRootHostContext,Z=e.getChildHostContext,xe=e.prepareForCommit,Ne=e.resetAfterCommit,ht=e.createInstance,H=e.appendInitialChild,rt=e.finalizeInitialChildren,Te=e.prepareUpdate,Fe=e.shouldSetTextContent,ke=e.shouldDeprioritizeSubtree,Ye=e.createTextInstance,be=e.setTimeout,et=e.clearTimeout,Ue=e.noTimeout,S=e.isPrimaryRenderer,w=e.supportsMutation,b=e.supportsPersistence,y=e.supportsHydration,F=e.appendChild,J=e.appendChildToContainer,X=e.commitTextUpdate,$=e.commitMount,ie=e.commitUpdate,Se=e.insertBefore,Re=e.insertInContainerBefore,at=e.removeChild,dt=e.removeChildFromContainer,jt=e.resetTextContent,tr=e.hideInstance,bt=e.hideTextInstance,ln=e.unhideInstance,kr=e.unhideTextInstance,mr=e.cloneInstance,Sr=e.createContainerChildSet,Kr=e.appendChildToContainerChildSet,Kn=e.finalizeContainerChildren,Ms=e.replaceContainerChildren,Ri=e.cloneHiddenInstance,gs=e.cloneHiddenTextInstance,io=e.canHydrateInstance,Pi=e.canHydrateTextInstance,Os=e.isSuspenseInstancePending,so=e.isSuspenseInstanceFallback,uc=e.getNextHydratableSibling,Au=e.getFirstHydratableChild,sp=e.hydrateInstance,op=e.hydrateTextInstance,Us=e.getNextHydratableInstanceAfterSuspenseInstance,Dn=e.commitHydratedContainer,oo=e.commitHydratedSuspenseInstance,_s=/^(.*)[\\\\\\/]/;function ml(P){var D=\"\";do{e:switch(P.tag){case 3:case 4:case 6:case 7:case 10:case 9:var T=\"\";break e;default:var q=P._debugOwner,W=P._debugSource,fe=de(P.type);T=null,q&&(T=de(q.type)),q=fe,fe=\"\",W?fe=\" (at \"+W.fileName.replace(_s,\"\")+\":\"+W.lineNumber+\")\":T&&(fe=\" (created by \"+T+\")\"),T=`\n    in `+(q||\"Unknown\")+fe}D+=T,P=P.return}while(P);return D}var yl=[],ao=-1;function Vn(P){0>ao||(P.current=yl[ao],yl[ao]=null,ao--)}function Mn(P,D){ao++,yl[ao]=P.current,P.current=D}var Ti={},On={current:Ti},_i={current:!1},ir=Ti;function Me(P,D){var T=P.type.contextTypes;if(!T)return Ti;var q=P.stateNode;if(q&&q.__reactInternalMemoizedUnmaskedChildContext===D)return q.__reactInternalMemoizedMaskedChildContext;var W={},fe;for(fe in T)W[fe]=D[fe];return q&&(P=P.stateNode,P.__reactInternalMemoizedUnmaskedChildContext=D,P.__reactInternalMemoizedMaskedChildContext=W),W}function ii(P){return P=P.childContextTypes,P!=null}function Ha(P){Vn(_i,P),Vn(On,P)}function hr(P){Vn(_i,P),Vn(On,P)}function Ac(P,D,T){if(On.current!==Ti)throw Error(n(168));Mn(On,D,P),Mn(_i,T,P)}function fu(P,D,T){var q=P.stateNode;if(P=D.childContextTypes,typeof q.getChildContext!=\"function\")return T;q=q.getChildContext();for(var W in q)if(!(W in P))throw Error(n(108,de(D)||\"Unknown\",W));return r({},T,{},q)}function fc(P){var D=P.stateNode;return D=D&&D.__reactInternalMemoizedMergedChildContext||Ti,ir=On.current,Mn(On,D,P),Mn(_i,_i.current,P),!0}function El(P,D,T){var q=P.stateNode;if(!q)throw Error(n(169));T?(D=fu(P,D,ir),q.__reactInternalMemoizedMergedChildContext=D,Vn(_i,P),Vn(On,P),Mn(On,D,P)):Vn(_i,P),Mn(_i,T,P)}var vA=a.unstable_runWithPriority,pu=a.unstable_scheduleCallback,Ie=a.unstable_cancelCallback,Tt=a.unstable_shouldYield,pc=a.unstable_requestPaint,Hi=a.unstable_now,hu=a.unstable_getCurrentPriorityLevel,Yt=a.unstable_ImmediatePriority,Cl=a.unstable_UserBlockingPriority,DA=a.unstable_NormalPriority,ap=a.unstable_LowPriority,hc=a.unstable_IdlePriority,PA={},Qn=pc!==void 0?pc:function(){},hi=null,gc=null,bA=!1,aa=Hi(),Ni=1e4>aa?Hi:function(){return Hi()-aa};function _o(){switch(hu()){case Yt:return 99;case Cl:return 98;case DA:return 97;case ap:return 96;case hc:return 95;default:throw Error(n(332))}}function Xe(P){switch(P){case 99:return Yt;case 98:return Cl;case 97:return DA;case 96:return ap;case 95:return hc;default:throw Error(n(332))}}function lo(P,D){return P=Xe(P),vA(P,D)}function dc(P,D,T){return P=Xe(P),pu(P,D,T)}function gu(P){return hi===null?(hi=[P],gc=pu(Yt,du)):hi.push(P),PA}function qi(){if(gc!==null){var P=gc;gc=null,Ie(P)}du()}function du(){if(!bA&&hi!==null){bA=!0;var P=0;try{var D=hi;lo(99,function(){for(;P<D.length;P++){var T=D[P];do T=T(!0);while(T!==null)}}),hi=null}catch(T){throw hi!==null&&(hi=hi.slice(P+1)),pu(Yt,qi),T}finally{bA=!1}}}var SA=3;function qa(P,D,T){return T/=10,1073741821-(((1073741821-P+D/10)/T|0)+1)*T}function mc(P,D){return P===D&&(P!==0||1/P===1/D)||P!==P&&D!==D}var ds=typeof Object.is==\"function\"?Object.is:mc,Ht=Object.prototype.hasOwnProperty;function Fn(P,D){if(ds(P,D))return!0;if(typeof P!=\"object\"||P===null||typeof D!=\"object\"||D===null)return!1;var T=Object.keys(P),q=Object.keys(D);if(T.length!==q.length)return!1;for(q=0;q<T.length;q++)if(!Ht.call(D,T[q])||!ds(P[T[q]],D[T[q]]))return!1;return!0}function Ei(P,D){if(P&&P.defaultProps){D=r({},D),P=P.defaultProps;for(var T in P)D[T]===void 0&&(D[T]=P[T])}return D}var la={current:null},co=null,Hs=null,ca=null;function ua(){ca=Hs=co=null}function Ho(P,D){var T=P.type._context;S?(Mn(la,T._currentValue,P),T._currentValue=D):(Mn(la,T._currentValue2,P),T._currentValue2=D)}function Ci(P){var D=la.current;Vn(la,P),P=P.type._context,S?P._currentValue=D:P._currentValue2=D}function ms(P,D){for(;P!==null;){var T=P.alternate;if(P.childExpirationTime<D)P.childExpirationTime=D,T!==null&&T.childExpirationTime<D&&(T.childExpirationTime=D);else if(T!==null&&T.childExpirationTime<D)T.childExpirationTime=D;else break;P=P.return}}function ys(P,D){co=P,ca=Hs=null,P=P.dependencies,P!==null&&P.firstContext!==null&&(P.expirationTime>=D&&(jo=!0),P.firstContext=null)}function Es(P,D){if(ca!==P&&D!==!1&&D!==0)if((typeof D!=\"number\"||D===1073741823)&&(ca=P,D=1073741823),D={context:P,observedBits:D,next:null},Hs===null){if(co===null)throw Error(n(308));Hs=D,co.dependencies={expirationTime:0,firstContext:D,responders:null}}else Hs=Hs.next=D;return S?P._currentValue:P._currentValue2}var qs=!1;function Un(P){return{baseState:P,firstUpdate:null,lastUpdate:null,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Pn(P){return{baseState:P.baseState,firstUpdate:P.firstUpdate,lastUpdate:P.lastUpdate,firstCapturedUpdate:null,lastCapturedUpdate:null,firstEffect:null,lastEffect:null,firstCapturedEffect:null,lastCapturedEffect:null}}function Cs(P,D){return{expirationTime:P,suspenseConfig:D,tag:0,payload:null,callback:null,next:null,nextEffect:null}}function We(P,D){P.lastUpdate===null?P.firstUpdate=P.lastUpdate=D:(P.lastUpdate.next=D,P.lastUpdate=D)}function tt(P,D){var T=P.alternate;if(T===null){var q=P.updateQueue,W=null;q===null&&(q=P.updateQueue=Un(P.memoizedState))}else q=P.updateQueue,W=T.updateQueue,q===null?W===null?(q=P.updateQueue=Un(P.memoizedState),W=T.updateQueue=Un(T.memoizedState)):q=P.updateQueue=Pn(W):W===null&&(W=T.updateQueue=Pn(q));W===null||q===W?We(q,D):q.lastUpdate===null||W.lastUpdate===null?(We(q,D),We(W,D)):(We(q,D),W.lastUpdate=D)}function Bt(P,D){var T=P.updateQueue;T=T===null?P.updateQueue=Un(P.memoizedState):or(P,T),T.lastCapturedUpdate===null?T.firstCapturedUpdate=T.lastCapturedUpdate=D:(T.lastCapturedUpdate.next=D,T.lastCapturedUpdate=D)}function or(P,D){var T=P.alternate;return T!==null&&D===T.updateQueue&&(D=P.updateQueue=Pn(D)),D}function ee(P,D,T,q,W,fe){switch(T.tag){case 1:return P=T.payload,typeof P==\"function\"?P.call(fe,q,W):P;case 3:P.effectTag=P.effectTag&-4097|64;case 0:if(P=T.payload,W=typeof P==\"function\"?P.call(fe,q,W):P,W==null)break;return r({},q,W);case 2:qs=!0}return q}function ye(P,D,T,q,W){qs=!1,D=or(P,D);for(var fe=D.baseState,De=null,vt=0,wt=D.firstUpdate,St=fe;wt!==null;){var _r=wt.expirationTime;_r<W?(De===null&&(De=wt,fe=St),vt<_r&&(vt=_r)):(uw(_r,wt.suspenseConfig),St=ee(P,D,wt,St,T,q),wt.callback!==null&&(P.effectTag|=32,wt.nextEffect=null,D.lastEffect===null?D.firstEffect=D.lastEffect=wt:(D.lastEffect.nextEffect=wt,D.lastEffect=wt))),wt=wt.next}for(_r=null,wt=D.firstCapturedUpdate;wt!==null;){var os=wt.expirationTime;os<W?(_r===null&&(_r=wt,De===null&&(fe=St)),vt<os&&(vt=os)):(St=ee(P,D,wt,St,T,q),wt.callback!==null&&(P.effectTag|=32,wt.nextEffect=null,D.lastCapturedEffect===null?D.firstCapturedEffect=D.lastCapturedEffect=wt:(D.lastCapturedEffect.nextEffect=wt,D.lastCapturedEffect=wt))),wt=wt.next}De===null&&(D.lastUpdate=null),_r===null?D.lastCapturedUpdate=null:P.effectTag|=32,De===null&&_r===null&&(fe=St),D.baseState=fe,D.firstUpdate=De,D.firstCapturedUpdate=_r,Sd(vt),P.expirationTime=vt,P.memoizedState=St}function Le(P,D,T){D.firstCapturedUpdate!==null&&(D.lastUpdate!==null&&(D.lastUpdate.next=D.firstCapturedUpdate,D.lastUpdate=D.lastCapturedUpdate),D.firstCapturedUpdate=D.lastCapturedUpdate=null),ft(D.firstEffect,T),D.firstEffect=D.lastEffect=null,ft(D.firstCapturedEffect,T),D.firstCapturedEffect=D.lastCapturedEffect=null}function ft(P,D){for(;P!==null;){var T=P.callback;if(T!==null){P.callback=null;var q=D;if(typeof T!=\"function\")throw Error(n(191,T));T.call(q)}P=P.nextEffect}}var pt=u.ReactCurrentBatchConfig,Nt=new o.Component().refs;function rr(P,D,T,q){D=P.memoizedState,T=T(q,D),T=T==null?D:r({},D,T),P.memoizedState=T,q=P.updateQueue,q!==null&&P.expirationTime===0&&(q.baseState=T)}var $r={isMounted:function(P){return(P=P._reactInternalFiber)?Be(P)===P:!1},enqueueSetState:function(P,D,T){P=P._reactInternalFiber;var q=ma(),W=pt.suspense;q=HA(q,P,W),W=Cs(q,W),W.payload=D,T!=null&&(W.callback=T),tt(P,W),Sc(P,q)},enqueueReplaceState:function(P,D,T){P=P._reactInternalFiber;var q=ma(),W=pt.suspense;q=HA(q,P,W),W=Cs(q,W),W.tag=1,W.payload=D,T!=null&&(W.callback=T),tt(P,W),Sc(P,q)},enqueueForceUpdate:function(P,D){P=P._reactInternalFiber;var T=ma(),q=pt.suspense;T=HA(T,P,q),q=Cs(T,q),q.tag=2,D!=null&&(q.callback=D),tt(P,q),Sc(P,T)}};function ji(P,D,T,q,W,fe,De){return P=P.stateNode,typeof P.shouldComponentUpdate==\"function\"?P.shouldComponentUpdate(q,fe,De):D.prototype&&D.prototype.isPureReactComponent?!Fn(T,q)||!Fn(W,fe):!0}function rs(P,D,T){var q=!1,W=Ti,fe=D.contextType;return typeof fe==\"object\"&&fe!==null?fe=Es(fe):(W=ii(D)?ir:On.current,q=D.contextTypes,fe=(q=q!=null)?Me(P,W):Ti),D=new D(T,fe),P.memoizedState=D.state!==null&&D.state!==void 0?D.state:null,D.updater=$r,P.stateNode=D,D._reactInternalFiber=P,q&&(P=P.stateNode,P.__reactInternalMemoizedUnmaskedChildContext=W,P.__reactInternalMemoizedMaskedChildContext=fe),D}function bi(P,D,T,q){P=D.state,typeof D.componentWillReceiveProps==\"function\"&&D.componentWillReceiveProps(T,q),typeof D.UNSAFE_componentWillReceiveProps==\"function\"&&D.UNSAFE_componentWillReceiveProps(T,q),D.state!==P&&$r.enqueueReplaceState(D,D.state,null)}function qo(P,D,T,q){var W=P.stateNode;W.props=T,W.state=P.memoizedState,W.refs=Nt;var fe=D.contextType;typeof fe==\"object\"&&fe!==null?W.context=Es(fe):(fe=ii(D)?ir:On.current,W.context=Me(P,fe)),fe=P.updateQueue,fe!==null&&(ye(P,fe,T,W,q),W.state=P.memoizedState),fe=D.getDerivedStateFromProps,typeof fe==\"function\"&&(rr(P,D,fe,T),W.state=P.memoizedState),typeof D.getDerivedStateFromProps==\"function\"||typeof W.getSnapshotBeforeUpdate==\"function\"||typeof W.UNSAFE_componentWillMount!=\"function\"&&typeof W.componentWillMount!=\"function\"||(D=W.state,typeof W.componentWillMount==\"function\"&&W.componentWillMount(),typeof W.UNSAFE_componentWillMount==\"function\"&&W.UNSAFE_componentWillMount(),D!==W.state&&$r.enqueueReplaceState(W,W.state,null),fe=P.updateQueue,fe!==null&&(ye(P,fe,T,W,q),W.state=P.memoizedState)),typeof W.componentDidMount==\"function\"&&(P.effectTag|=4)}var xA=Array.isArray;function kA(P,D,T){if(P=T.ref,P!==null&&typeof P!=\"function\"&&typeof P!=\"object\"){if(T._owner){if(T=T._owner,T){if(T.tag!==1)throw Error(n(309));var q=T.stateNode}if(!q)throw Error(n(147,P));var W=\"\"+P;return D!==null&&D.ref!==null&&typeof D.ref==\"function\"&&D.ref._stringRef===W?D.ref:(D=function(fe){var De=q.refs;De===Nt&&(De=q.refs={}),fe===null?delete De[W]:De[W]=fe},D._stringRef=W,D)}if(typeof P!=\"string\")throw Error(n(284));if(!T._owner)throw Error(n(290,P))}return P}function lp(P,D){if(P.type!==\"textarea\")throw Error(n(31,Object.prototype.toString.call(D)===\"[object Object]\"?\"object with keys {\"+Object.keys(D).join(\", \")+\"}\":D,\"\"))}function e0(P){function D(nt,Ve){if(P){var At=nt.lastEffect;At!==null?(At.nextEffect=Ve,nt.lastEffect=Ve):nt.firstEffect=nt.lastEffect=Ve,Ve.nextEffect=null,Ve.effectTag=8}}function T(nt,Ve){if(!P)return null;for(;Ve!==null;)D(nt,Ve),Ve=Ve.sibling;return null}function q(nt,Ve){for(nt=new Map;Ve!==null;)Ve.key!==null?nt.set(Ve.key,Ve):nt.set(Ve.index,Ve),Ve=Ve.sibling;return nt}function W(nt,Ve,At){return nt=YA(nt,Ve,At),nt.index=0,nt.sibling=null,nt}function fe(nt,Ve,At){return nt.index=At,P?(At=nt.alternate,At!==null?(At=At.index,At<Ve?(nt.effectTag=2,Ve):At):(nt.effectTag=2,Ve)):Ve}function De(nt){return P&&nt.alternate===null&&(nt.effectTag=2),nt}function vt(nt,Ve,At,Wt){return Ve===null||Ve.tag!==6?(Ve=gw(At,nt.mode,Wt),Ve.return=nt,Ve):(Ve=W(Ve,At,Wt),Ve.return=nt,Ve)}function wt(nt,Ve,At,Wt){return Ve!==null&&Ve.elementType===At.type?(Wt=W(Ve,At.props,Wt),Wt.ref=kA(nt,Ve,At),Wt.return=nt,Wt):(Wt=xd(At.type,At.key,At.props,null,nt.mode,Wt),Wt.ref=kA(nt,Ve,At),Wt.return=nt,Wt)}function St(nt,Ve,At,Wt){return Ve===null||Ve.tag!==4||Ve.stateNode.containerInfo!==At.containerInfo||Ve.stateNode.implementation!==At.implementation?(Ve=dw(At,nt.mode,Wt),Ve.return=nt,Ve):(Ve=W(Ve,At.children||[],Wt),Ve.return=nt,Ve)}function _r(nt,Ve,At,Wt,vr){return Ve===null||Ve.tag!==7?(Ve=ku(At,nt.mode,Wt,vr),Ve.return=nt,Ve):(Ve=W(Ve,At,Wt),Ve.return=nt,Ve)}function os(nt,Ve,At){if(typeof Ve==\"string\"||typeof Ve==\"number\")return Ve=gw(\"\"+Ve,nt.mode,At),Ve.return=nt,Ve;if(typeof Ve==\"object\"&&Ve!==null){switch(Ve.$$typeof){case p:return At=xd(Ve.type,Ve.key,Ve.props,null,nt.mode,At),At.ref=kA(nt,null,Ve),At.return=nt,At;case h:return Ve=dw(Ve,nt.mode,At),Ve.return=nt,Ve}if(xA(Ve)||ce(Ve))return Ve=ku(Ve,nt.mode,At,null),Ve.return=nt,Ve;lp(nt,Ve)}return null}function di(nt,Ve,At,Wt){var vr=Ve!==null?Ve.key:null;if(typeof At==\"string\"||typeof At==\"number\")return vr!==null?null:vt(nt,Ve,\"\"+At,Wt);if(typeof At==\"object\"&&At!==null){switch(At.$$typeof){case p:return At.key===vr?At.type===E?_r(nt,Ve,At.props.children,Wt,vr):wt(nt,Ve,At,Wt):null;case h:return At.key===vr?St(nt,Ve,At,Wt):null}if(xA(At)||ce(At))return vr!==null?null:_r(nt,Ve,At,Wt,null);lp(nt,At)}return null}function po(nt,Ve,At,Wt,vr){if(typeof Wt==\"string\"||typeof Wt==\"number\")return nt=nt.get(At)||null,vt(Ve,nt,\"\"+Wt,vr);if(typeof Wt==\"object\"&&Wt!==null){switch(Wt.$$typeof){case p:return nt=nt.get(Wt.key===null?At:Wt.key)||null,Wt.type===E?_r(Ve,nt,Wt.props.children,vr,Wt.key):wt(Ve,nt,Wt,vr);case h:return nt=nt.get(Wt.key===null?At:Wt.key)||null,St(Ve,nt,Wt,vr)}if(xA(Wt)||ce(Wt))return nt=nt.get(At)||null,_r(Ve,nt,Wt,vr,null);lp(Ve,Wt)}return null}function KA(nt,Ve,At,Wt){for(var vr=null,bn=null,Qr=Ve,Sn=Ve=0,ai=null;Qr!==null&&Sn<At.length;Sn++){Qr.index>Sn?(ai=Qr,Qr=null):ai=Qr.sibling;var tn=di(nt,Qr,At[Sn],Wt);if(tn===null){Qr===null&&(Qr=ai);break}P&&Qr&&tn.alternate===null&&D(nt,Qr),Ve=fe(tn,Ve,Sn),bn===null?vr=tn:bn.sibling=tn,bn=tn,Qr=ai}if(Sn===At.length)return T(nt,Qr),vr;if(Qr===null){for(;Sn<At.length;Sn++)Qr=os(nt,At[Sn],Wt),Qr!==null&&(Ve=fe(Qr,Ve,Sn),bn===null?vr=Qr:bn.sibling=Qr,bn=Qr);return vr}for(Qr=q(nt,Qr);Sn<At.length;Sn++)ai=po(Qr,nt,Sn,At[Sn],Wt),ai!==null&&(P&&ai.alternate!==null&&Qr.delete(ai.key===null?Sn:ai.key),Ve=fe(ai,Ve,Sn),bn===null?vr=ai:bn.sibling=ai,bn=ai);return P&&Qr.forEach(function(ho){return D(nt,ho)}),vr}function Yo(nt,Ve,At,Wt){var vr=ce(At);if(typeof vr!=\"function\")throw Error(n(150));if(At=vr.call(At),At==null)throw Error(n(151));for(var bn=vr=null,Qr=Ve,Sn=Ve=0,ai=null,tn=At.next();Qr!==null&&!tn.done;Sn++,tn=At.next()){Qr.index>Sn?(ai=Qr,Qr=null):ai=Qr.sibling;var ho=di(nt,Qr,tn.value,Wt);if(ho===null){Qr===null&&(Qr=ai);break}P&&Qr&&ho.alternate===null&&D(nt,Qr),Ve=fe(ho,Ve,Sn),bn===null?vr=ho:bn.sibling=ho,bn=ho,Qr=ai}if(tn.done)return T(nt,Qr),vr;if(Qr===null){for(;!tn.done;Sn++,tn=At.next())tn=os(nt,tn.value,Wt),tn!==null&&(Ve=fe(tn,Ve,Sn),bn===null?vr=tn:bn.sibling=tn,bn=tn);return vr}for(Qr=q(nt,Qr);!tn.done;Sn++,tn=At.next())tn=po(Qr,nt,Sn,tn.value,Wt),tn!==null&&(P&&tn.alternate!==null&&Qr.delete(tn.key===null?Sn:tn.key),Ve=fe(tn,Ve,Sn),bn===null?vr=tn:bn.sibling=tn,bn=tn);return P&&Qr.forEach(function(pF){return D(nt,pF)}),vr}return function(nt,Ve,At,Wt){var vr=typeof At==\"object\"&&At!==null&&At.type===E&&At.key===null;vr&&(At=At.props.children);var bn=typeof At==\"object\"&&At!==null;if(bn)switch(At.$$typeof){case p:e:{for(bn=At.key,vr=Ve;vr!==null;){if(vr.key===bn)if(vr.tag===7?At.type===E:vr.elementType===At.type){T(nt,vr.sibling),Ve=W(vr,At.type===E?At.props.children:At.props,Wt),Ve.ref=kA(nt,vr,At),Ve.return=nt,nt=Ve;break e}else{T(nt,vr);break}else D(nt,vr);vr=vr.sibling}At.type===E?(Ve=ku(At.props.children,nt.mode,Wt,At.key),Ve.return=nt,nt=Ve):(Wt=xd(At.type,At.key,At.props,null,nt.mode,Wt),Wt.ref=kA(nt,Ve,At),Wt.return=nt,nt=Wt)}return De(nt);case h:e:{for(vr=At.key;Ve!==null;){if(Ve.key===vr)if(Ve.tag===4&&Ve.stateNode.containerInfo===At.containerInfo&&Ve.stateNode.implementation===At.implementation){T(nt,Ve.sibling),Ve=W(Ve,At.children||[],Wt),Ve.return=nt,nt=Ve;break e}else{T(nt,Ve);break}else D(nt,Ve);Ve=Ve.sibling}Ve=dw(At,nt.mode,Wt),Ve.return=nt,nt=Ve}return De(nt)}if(typeof At==\"string\"||typeof At==\"number\")return At=\"\"+At,Ve!==null&&Ve.tag===6?(T(nt,Ve.sibling),Ve=W(Ve,At,Wt),Ve.return=nt,nt=Ve):(T(nt,Ve),Ve=gw(At,nt.mode,Wt),Ve.return=nt,nt=Ve),De(nt);if(xA(At))return KA(nt,Ve,At,Wt);if(ce(At))return Yo(nt,Ve,At,Wt);if(bn&&lp(nt,At),typeof At>\"u\"&&!vr)switch(nt.tag){case 1:case 0:throw nt=nt.type,Error(n(152,nt.displayName||nt.name||\"Component\"))}return T(nt,Ve)}}var mu=e0(!0),t0=e0(!1),yu={},uo={current:yu},QA={current:yu},yc={current:yu};function Aa(P){if(P===yu)throw Error(n(174));return P}function r0(P,D){Mn(yc,D,P),Mn(QA,P,P),Mn(uo,yu,P),D=ne(D),Vn(uo,P),Mn(uo,D,P)}function Ec(P){Vn(uo,P),Vn(QA,P),Vn(yc,P)}function hd(P){var D=Aa(yc.current),T=Aa(uo.current);D=Z(T,P.type,D),T!==D&&(Mn(QA,P,P),Mn(uo,D,P))}function n0(P){QA.current===P&&(Vn(uo,P),Vn(QA,P))}var $n={current:0};function cp(P){for(var D=P;D!==null;){if(D.tag===13){var T=D.memoizedState;if(T!==null&&(T=T.dehydrated,T===null||Os(T)||so(T)))return D}else if(D.tag===19&&D.memoizedProps.revealOrder!==void 0){if(D.effectTag&64)return D}else if(D.child!==null){D.child.return=D,D=D.child;continue}if(D===P)break;for(;D.sibling===null;){if(D.return===null||D.return===P)return null;D=D.return}D.sibling.return=D.return,D=D.sibling}return null}function i0(P,D){return{responder:P,props:D}}var FA=u.ReactCurrentDispatcher,js=u.ReactCurrentBatchConfig,Eu=0,ja=null,Gi=null,fa=null,Cu=null,ws=null,Cc=null,wc=0,Y=null,Dt=0,wl=!1,Si=null,Ic=0;function ct(){throw Error(n(321))}function wu(P,D){if(D===null)return!1;for(var T=0;T<D.length&&T<P.length;T++)if(!ds(P[T],D[T]))return!1;return!0}function s0(P,D,T,q,W,fe){if(Eu=fe,ja=D,fa=P!==null?P.memoizedState:null,FA.current=fa===null?rw:md,D=T(q,W),wl){do wl=!1,Ic+=1,fa=P!==null?P.memoizedState:null,Cc=Cu,Y=ws=Gi=null,FA.current=md,D=T(q,W);while(wl);Si=null,Ic=0}if(FA.current=Bu,P=ja,P.memoizedState=Cu,P.expirationTime=wc,P.updateQueue=Y,P.effectTag|=Dt,P=Gi!==null&&Gi.next!==null,Eu=0,Cc=ws=Cu=fa=Gi=ja=null,wc=0,Y=null,Dt=0,P)throw Error(n(300));return D}function tw(){FA.current=Bu,Eu=0,Cc=ws=Cu=fa=Gi=ja=null,wc=0,Y=null,Dt=0,wl=!1,Si=null,Ic=0}function RA(){var P={memoizedState:null,baseState:null,queue:null,baseUpdate:null,next:null};return ws===null?Cu=ws=P:ws=ws.next=P,ws}function up(){if(Cc!==null)ws=Cc,Cc=ws.next,Gi=fa,fa=Gi!==null?Gi.next:null;else{if(fa===null)throw Error(n(310));Gi=fa;var P={memoizedState:Gi.memoizedState,baseState:Gi.baseState,queue:Gi.queue,baseUpdate:Gi.baseUpdate,next:null};ws=ws===null?Cu=P:ws.next=P,fa=Gi.next}return ws}function Br(P,D){return typeof D==\"function\"?D(P):D}function Is(P){var D=up(),T=D.queue;if(T===null)throw Error(n(311));if(T.lastRenderedReducer=P,0<Ic){var q=T.dispatch;if(Si!==null){var W=Si.get(T);if(W!==void 0){Si.delete(T);var fe=D.memoizedState;do fe=P(fe,W.action),W=W.next;while(W!==null);return ds(fe,D.memoizedState)||(jo=!0),D.memoizedState=fe,D.baseUpdate===T.last&&(D.baseState=fe),T.lastRenderedState=fe,[fe,q]}}return[D.memoizedState,q]}q=T.last;var De=D.baseUpdate;if(fe=D.baseState,De!==null?(q!==null&&(q.next=null),q=De.next):q=q!==null?q.next:null,q!==null){var vt=W=null,wt=q,St=!1;do{var _r=wt.expirationTime;_r<Eu?(St||(St=!0,vt=De,W=fe),_r>wc&&(wc=_r,Sd(wc))):(uw(_r,wt.suspenseConfig),fe=wt.eagerReducer===P?wt.eagerState:P(fe,wt.action)),De=wt,wt=wt.next}while(wt!==null&&wt!==q);St||(vt=De,W=fe),ds(fe,D.memoizedState)||(jo=!0),D.memoizedState=fe,D.baseUpdate=vt,D.baseState=W,T.lastRenderedState=fe}return[D.memoizedState,T.dispatch]}function o0(P){var D=RA();return typeof P==\"function\"&&(P=P()),D.memoizedState=D.baseState=P,P=D.queue={last:null,dispatch:null,lastRenderedReducer:Br,lastRenderedState:P},P=P.dispatch=A0.bind(null,ja,P),[D.memoizedState,P]}function a0(P){return Is(Br,P)}function l0(P,D,T,q){return P={tag:P,create:D,destroy:T,deps:q,next:null},Y===null?(Y={lastEffect:null},Y.lastEffect=P.next=P):(D=Y.lastEffect,D===null?Y.lastEffect=P.next=P:(T=D.next,D.next=P,P.next=T,Y.lastEffect=P)),P}function Ap(P,D,T,q){var W=RA();Dt|=P,W.memoizedState=l0(D,T,void 0,q===void 0?null:q)}function Bc(P,D,T,q){var W=up();q=q===void 0?null:q;var fe=void 0;if(Gi!==null){var De=Gi.memoizedState;if(fe=De.destroy,q!==null&&wu(q,De.deps)){l0(0,T,fe,q);return}}Dt|=P,W.memoizedState=l0(D,T,fe,q)}function Ct(P,D){return Ap(516,192,P,D)}function gd(P,D){return Bc(516,192,P,D)}function c0(P,D){if(typeof D==\"function\")return P=P(),D(P),function(){D(null)};if(D!=null)return P=P(),D.current=P,function(){D.current=null}}function u0(){}function Iu(P,D){return RA().memoizedState=[P,D===void 0?null:D],P}function dd(P,D){var T=up();D=D===void 0?null:D;var q=T.memoizedState;return q!==null&&D!==null&&wu(D,q[1])?q[0]:(T.memoizedState=[P,D],P)}function A0(P,D,T){if(!(25>Ic))throw Error(n(301));var q=P.alternate;if(P===ja||q!==null&&q===ja)if(wl=!0,P={expirationTime:Eu,suspenseConfig:null,action:T,eagerReducer:null,eagerState:null,next:null},Si===null&&(Si=new Map),T=Si.get(D),T===void 0)Si.set(D,P);else{for(D=T;D.next!==null;)D=D.next;D.next=P}else{var W=ma(),fe=pt.suspense;W=HA(W,P,fe),fe={expirationTime:W,suspenseConfig:fe,action:T,eagerReducer:null,eagerState:null,next:null};var De=D.last;if(De===null)fe.next=fe;else{var vt=De.next;vt!==null&&(fe.next=vt),De.next=fe}if(D.last=fe,P.expirationTime===0&&(q===null||q.expirationTime===0)&&(q=D.lastRenderedReducer,q!==null))try{var wt=D.lastRenderedState,St=q(wt,T);if(fe.eagerReducer=q,fe.eagerState=St,ds(St,wt))return}catch{}finally{}Sc(P,W)}}var Bu={readContext:Es,useCallback:ct,useContext:ct,useEffect:ct,useImperativeHandle:ct,useLayoutEffect:ct,useMemo:ct,useReducer:ct,useRef:ct,useState:ct,useDebugValue:ct,useResponder:ct,useDeferredValue:ct,useTransition:ct},rw={readContext:Es,useCallback:Iu,useContext:Es,useEffect:Ct,useImperativeHandle:function(P,D,T){return T=T!=null?T.concat([P]):null,Ap(4,36,c0.bind(null,D,P),T)},useLayoutEffect:function(P,D){return Ap(4,36,P,D)},useMemo:function(P,D){var T=RA();return D=D===void 0?null:D,P=P(),T.memoizedState=[P,D],P},useReducer:function(P,D,T){var q=RA();return D=T!==void 0?T(D):D,q.memoizedState=q.baseState=D,P=q.queue={last:null,dispatch:null,lastRenderedReducer:P,lastRenderedState:D},P=P.dispatch=A0.bind(null,ja,P),[q.memoizedState,P]},useRef:function(P){var D=RA();return P={current:P},D.memoizedState=P},useState:o0,useDebugValue:u0,useResponder:i0,useDeferredValue:function(P,D){var T=o0(P),q=T[0],W=T[1];return Ct(function(){a.unstable_next(function(){var fe=js.suspense;js.suspense=D===void 0?null:D;try{W(P)}finally{js.suspense=fe}})},[P,D]),q},useTransition:function(P){var D=o0(!1),T=D[0],q=D[1];return[Iu(function(W){q(!0),a.unstable_next(function(){var fe=js.suspense;js.suspense=P===void 0?null:P;try{q(!1),W()}finally{js.suspense=fe}})},[P,T]),T]}},md={readContext:Es,useCallback:dd,useContext:Es,useEffect:gd,useImperativeHandle:function(P,D,T){return T=T!=null?T.concat([P]):null,Bc(4,36,c0.bind(null,D,P),T)},useLayoutEffect:function(P,D){return Bc(4,36,P,D)},useMemo:function(P,D){var T=up();D=D===void 0?null:D;var q=T.memoizedState;return q!==null&&D!==null&&wu(D,q[1])?q[0]:(P=P(),T.memoizedState=[P,D],P)},useReducer:Is,useRef:function(){return up().memoizedState},useState:a0,useDebugValue:u0,useResponder:i0,useDeferredValue:function(P,D){var T=a0(P),q=T[0],W=T[1];return gd(function(){a.unstable_next(function(){var fe=js.suspense;js.suspense=D===void 0?null:D;try{W(P)}finally{js.suspense=fe}})},[P,D]),q},useTransition:function(P){var D=a0(!1),T=D[0],q=D[1];return[dd(function(W){q(!0),a.unstable_next(function(){var fe=js.suspense;js.suspense=P===void 0?null:P;try{q(!1),W()}finally{js.suspense=fe}})},[P,T]),T]}},pa=null,vc=null,Il=!1;function vu(P,D){var T=Dl(5,null,null,0);T.elementType=\"DELETED\",T.type=\"DELETED\",T.stateNode=D,T.return=P,T.effectTag=8,P.lastEffect!==null?(P.lastEffect.nextEffect=T,P.lastEffect=T):P.firstEffect=P.lastEffect=T}function f0(P,D){switch(P.tag){case 5:return D=io(D,P.type,P.pendingProps),D!==null?(P.stateNode=D,!0):!1;case 6:return D=Pi(D,P.pendingProps),D!==null?(P.stateNode=D,!0):!1;case 13:return!1;default:return!1}}function TA(P){if(Il){var D=vc;if(D){var T=D;if(!f0(P,D)){if(D=uc(T),!D||!f0(P,D)){P.effectTag=P.effectTag&-1025|2,Il=!1,pa=P;return}vu(pa,T)}pa=P,vc=Au(D)}else P.effectTag=P.effectTag&-1025|2,Il=!1,pa=P}}function fp(P){for(P=P.return;P!==null&&P.tag!==5&&P.tag!==3&&P.tag!==13;)P=P.return;pa=P}function Ga(P){if(!y||P!==pa)return!1;if(!Il)return fp(P),Il=!0,!1;var D=P.type;if(P.tag!==5||D!==\"head\"&&D!==\"body\"&&!Fe(D,P.memoizedProps))for(D=vc;D;)vu(P,D),D=uc(D);if(fp(P),P.tag===13){if(!y)throw Error(n(316));if(P=P.memoizedState,P=P!==null?P.dehydrated:null,!P)throw Error(n(317));vc=Us(P)}else vc=pa?uc(P.stateNode):null;return!0}function p0(){y&&(vc=pa=null,Il=!1)}var pp=u.ReactCurrentOwner,jo=!1;function Bs(P,D,T,q){D.child=P===null?t0(D,null,T,q):mu(D,P.child,T,q)}function wi(P,D,T,q,W){T=T.render;var fe=D.ref;return ys(D,W),q=s0(P,D,T,q,fe,W),P!==null&&!jo?(D.updateQueue=P.updateQueue,D.effectTag&=-517,P.expirationTime<=W&&(P.expirationTime=0),si(P,D,W)):(D.effectTag|=1,Bs(P,D,q,W),D.child)}function yd(P,D,T,q,W,fe){if(P===null){var De=T.type;return typeof De==\"function\"&&!hw(De)&&De.defaultProps===void 0&&T.compare===null&&T.defaultProps===void 0?(D.tag=15,D.type=De,Ed(P,D,De,q,W,fe)):(P=xd(T.type,null,q,null,D.mode,fe),P.ref=D.ref,P.return=D,D.child=P)}return De=P.child,W<fe&&(W=De.memoizedProps,T=T.compare,T=T!==null?T:Fn,T(W,q)&&P.ref===D.ref)?si(P,D,fe):(D.effectTag|=1,P=YA(De,q,fe),P.ref=D.ref,P.return=D,D.child=P)}function Ed(P,D,T,q,W,fe){return P!==null&&Fn(P.memoizedProps,q)&&P.ref===D.ref&&(jo=!1,W<fe)?si(P,D,fe):NA(P,D,T,q,fe)}function Go(P,D){var T=D.ref;(P===null&&T!==null||P!==null&&P.ref!==T)&&(D.effectTag|=128)}function NA(P,D,T,q,W){var fe=ii(T)?ir:On.current;return fe=Me(D,fe),ys(D,W),T=s0(P,D,T,q,fe,W),P!==null&&!jo?(D.updateQueue=P.updateQueue,D.effectTag&=-517,P.expirationTime<=W&&(P.expirationTime=0),si(P,D,W)):(D.effectTag|=1,Bs(P,D,T,W),D.child)}function hp(P,D,T,q,W){if(ii(T)){var fe=!0;fc(D)}else fe=!1;if(ys(D,W),D.stateNode===null)P!==null&&(P.alternate=null,D.alternate=null,D.effectTag|=2),rs(D,T,q,W),qo(D,T,q,W),q=!0;else if(P===null){var De=D.stateNode,vt=D.memoizedProps;De.props=vt;var wt=De.context,St=T.contextType;typeof St==\"object\"&&St!==null?St=Es(St):(St=ii(T)?ir:On.current,St=Me(D,St));var _r=T.getDerivedStateFromProps,os=typeof _r==\"function\"||typeof De.getSnapshotBeforeUpdate==\"function\";os||typeof De.UNSAFE_componentWillReceiveProps!=\"function\"&&typeof De.componentWillReceiveProps!=\"function\"||(vt!==q||wt!==St)&&bi(D,De,q,St),qs=!1;var di=D.memoizedState;wt=De.state=di;var po=D.updateQueue;po!==null&&(ye(D,po,q,De,W),wt=D.memoizedState),vt!==q||di!==wt||_i.current||qs?(typeof _r==\"function\"&&(rr(D,T,_r,q),wt=D.memoizedState),(vt=qs||ji(D,T,vt,q,di,wt,St))?(os||typeof De.UNSAFE_componentWillMount!=\"function\"&&typeof De.componentWillMount!=\"function\"||(typeof De.componentWillMount==\"function\"&&De.componentWillMount(),typeof De.UNSAFE_componentWillMount==\"function\"&&De.UNSAFE_componentWillMount()),typeof De.componentDidMount==\"function\"&&(D.effectTag|=4)):(typeof De.componentDidMount==\"function\"&&(D.effectTag|=4),D.memoizedProps=q,D.memoizedState=wt),De.props=q,De.state=wt,De.context=St,q=vt):(typeof De.componentDidMount==\"function\"&&(D.effectTag|=4),q=!1)}else De=D.stateNode,vt=D.memoizedProps,De.props=D.type===D.elementType?vt:Ei(D.type,vt),wt=De.context,St=T.contextType,typeof St==\"object\"&&St!==null?St=Es(St):(St=ii(T)?ir:On.current,St=Me(D,St)),_r=T.getDerivedStateFromProps,(os=typeof _r==\"function\"||typeof De.getSnapshotBeforeUpdate==\"function\")||typeof De.UNSAFE_componentWillReceiveProps!=\"function\"&&typeof De.componentWillReceiveProps!=\"function\"||(vt!==q||wt!==St)&&bi(D,De,q,St),qs=!1,wt=D.memoizedState,di=De.state=wt,po=D.updateQueue,po!==null&&(ye(D,po,q,De,W),di=D.memoizedState),vt!==q||wt!==di||_i.current||qs?(typeof _r==\"function\"&&(rr(D,T,_r,q),di=D.memoizedState),(_r=qs||ji(D,T,vt,q,wt,di,St))?(os||typeof De.UNSAFE_componentWillUpdate!=\"function\"&&typeof De.componentWillUpdate!=\"function\"||(typeof De.componentWillUpdate==\"function\"&&De.componentWillUpdate(q,di,St),typeof De.UNSAFE_componentWillUpdate==\"function\"&&De.UNSAFE_componentWillUpdate(q,di,St)),typeof De.componentDidUpdate==\"function\"&&(D.effectTag|=4),typeof De.getSnapshotBeforeUpdate==\"function\"&&(D.effectTag|=256)):(typeof De.componentDidUpdate!=\"function\"||vt===P.memoizedProps&&wt===P.memoizedState||(D.effectTag|=4),typeof De.getSnapshotBeforeUpdate!=\"function\"||vt===P.memoizedProps&&wt===P.memoizedState||(D.effectTag|=256),D.memoizedProps=q,D.memoizedState=di),De.props=q,De.state=di,De.context=St,q=_r):(typeof De.componentDidUpdate!=\"function\"||vt===P.memoizedProps&&wt===P.memoizedState||(D.effectTag|=4),typeof De.getSnapshotBeforeUpdate!=\"function\"||vt===P.memoizedProps&&wt===P.memoizedState||(D.effectTag|=256),q=!1);return gp(P,D,T,q,fe,W)}function gp(P,D,T,q,W,fe){Go(P,D);var De=(D.effectTag&64)!==0;if(!q&&!De)return W&&El(D,T,!1),si(P,D,fe);q=D.stateNode,pp.current=D;var vt=De&&typeof T.getDerivedStateFromError!=\"function\"?null:q.render();return D.effectTag|=1,P!==null&&De?(D.child=mu(D,P.child,null,fe),D.child=mu(D,null,vt,fe)):Bs(P,D,vt,fe),D.memoizedState=q.state,W&&El(D,T,!0),D.child}function h0(P){var D=P.stateNode;D.pendingContext?Ac(P,D.pendingContext,D.pendingContext!==D.context):D.context&&Ac(P,D.context,!1),r0(P,D.containerInfo)}var ha={dehydrated:null,retryTime:0};function cn(P,D,T){var q=D.mode,W=D.pendingProps,fe=$n.current,De=!1,vt;if((vt=(D.effectTag&64)!==0)||(vt=(fe&2)!==0&&(P===null||P.memoizedState!==null)),vt?(De=!0,D.effectTag&=-65):P!==null&&P.memoizedState===null||W.fallback===void 0||W.unstable_avoidThisFallback===!0||(fe|=1),Mn($n,fe&1,D),P===null){if(W.fallback!==void 0&&TA(D),De){if(De=W.fallback,W=ku(null,q,0,null),W.return=D,!(D.mode&2))for(P=D.memoizedState!==null?D.child.child:D.child,W.child=P;P!==null;)P.return=W,P=P.sibling;return T=ku(De,q,T,null),T.return=D,W.sibling=T,D.memoizedState=ha,D.child=W,T}return q=W.children,D.memoizedState=null,D.child=t0(D,null,q,T)}if(P.memoizedState!==null){if(P=P.child,q=P.sibling,De){if(W=W.fallback,T=YA(P,P.pendingProps,0),T.return=D,!(D.mode&2)&&(De=D.memoizedState!==null?D.child.child:D.child,De!==P.child))for(T.child=De;De!==null;)De.return=T,De=De.sibling;return q=YA(q,W,q.expirationTime),q.return=D,T.sibling=q,T.childExpirationTime=0,D.memoizedState=ha,D.child=T,q}return T=mu(D,P.child,W.children,T),D.memoizedState=null,D.child=T}if(P=P.child,De){if(De=W.fallback,W=ku(null,q,0,null),W.return=D,W.child=P,P!==null&&(P.return=W),!(D.mode&2))for(P=D.memoizedState!==null?D.child.child:D.child,W.child=P;P!==null;)P.return=W,P=P.sibling;return T=ku(De,q,T,null),T.return=D,W.sibling=T,T.effectTag|=2,W.childExpirationTime=0,D.memoizedState=ha,D.child=W,T}return D.memoizedState=null,D.child=mu(D,P,W.children,T)}function Ao(P,D){P.expirationTime<D&&(P.expirationTime=D);var T=P.alternate;T!==null&&T.expirationTime<D&&(T.expirationTime=D),ms(P.return,D)}function LA(P,D,T,q,W,fe){var De=P.memoizedState;De===null?P.memoizedState={isBackwards:D,rendering:null,last:q,tail:T,tailExpiration:0,tailMode:W,lastEffect:fe}:(De.isBackwards=D,De.rendering=null,De.last=q,De.tail=T,De.tailExpiration=0,De.tailMode=W,De.lastEffect=fe)}function Ya(P,D,T){var q=D.pendingProps,W=q.revealOrder,fe=q.tail;if(Bs(P,D,q.children,T),q=$n.current,q&2)q=q&1|2,D.effectTag|=64;else{if(P!==null&&P.effectTag&64)e:for(P=D.child;P!==null;){if(P.tag===13)P.memoizedState!==null&&Ao(P,T);else if(P.tag===19)Ao(P,T);else if(P.child!==null){P.child.return=P,P=P.child;continue}if(P===D)break e;for(;P.sibling===null;){if(P.return===null||P.return===D)break e;P=P.return}P.sibling.return=P.return,P=P.sibling}q&=1}if(Mn($n,q,D),!(D.mode&2))D.memoizedState=null;else switch(W){case\"forwards\":for(T=D.child,W=null;T!==null;)P=T.alternate,P!==null&&cp(P)===null&&(W=T),T=T.sibling;T=W,T===null?(W=D.child,D.child=null):(W=T.sibling,T.sibling=null),LA(D,!1,W,T,fe,D.lastEffect);break;case\"backwards\":for(T=null,W=D.child,D.child=null;W!==null;){if(P=W.alternate,P!==null&&cp(P)===null){D.child=W;break}P=W.sibling,W.sibling=T,T=W,W=P}LA(D,!0,T,null,fe,D.lastEffect);break;case\"together\":LA(D,!1,null,null,void 0,D.lastEffect);break;default:D.memoizedState=null}return D.child}function si(P,D,T){P!==null&&(D.dependencies=P.dependencies);var q=D.expirationTime;if(q!==0&&Sd(q),D.childExpirationTime<T)return null;if(P!==null&&D.child!==P.child)throw Error(n(153));if(D.child!==null){for(P=D.child,T=YA(P,P.pendingProps,P.expirationTime),D.child=T,T.return=D;P.sibling!==null;)P=P.sibling,T=T.sibling=YA(P,P.pendingProps,P.expirationTime),T.return=D;T.sibling=null}return D.child}function ga(P){P.effectTag|=4}var Dc,Bl,ns,Yr;if(w)Dc=function(P,D){for(var T=D.child;T!==null;){if(T.tag===5||T.tag===6)H(P,T.stateNode);else if(T.tag!==4&&T.child!==null){T.child.return=T,T=T.child;continue}if(T===D)break;for(;T.sibling===null;){if(T.return===null||T.return===D)return;T=T.return}T.sibling.return=T.return,T=T.sibling}},Bl=function(){},ns=function(P,D,T,q,W){if(P=P.memoizedProps,P!==q){var fe=D.stateNode,De=Aa(uo.current);T=Te(fe,T,P,q,W,De),(D.updateQueue=T)&&ga(D)}},Yr=function(P,D,T,q){T!==q&&ga(D)};else if(b){Dc=function(P,D,T,q){for(var W=D.child;W!==null;){if(W.tag===5){var fe=W.stateNode;T&&q&&(fe=Ri(fe,W.type,W.memoizedProps,W)),H(P,fe)}else if(W.tag===6)fe=W.stateNode,T&&q&&(fe=gs(fe,W.memoizedProps,W)),H(P,fe);else if(W.tag!==4){if(W.tag===13&&W.effectTag&4&&(fe=W.memoizedState!==null)){var De=W.child;if(De!==null&&(De.child!==null&&(De.child.return=De,Dc(P,De,!0,fe)),fe=De.sibling,fe!==null)){fe.return=W,W=fe;continue}}if(W.child!==null){W.child.return=W,W=W.child;continue}}if(W===D)break;for(;W.sibling===null;){if(W.return===null||W.return===D)return;W=W.return}W.sibling.return=W.return,W=W.sibling}};var dp=function(P,D,T,q){for(var W=D.child;W!==null;){if(W.tag===5){var fe=W.stateNode;T&&q&&(fe=Ri(fe,W.type,W.memoizedProps,W)),Kr(P,fe)}else if(W.tag===6)fe=W.stateNode,T&&q&&(fe=gs(fe,W.memoizedProps,W)),Kr(P,fe);else if(W.tag!==4){if(W.tag===13&&W.effectTag&4&&(fe=W.memoizedState!==null)){var De=W.child;if(De!==null&&(De.child!==null&&(De.child.return=De,dp(P,De,!0,fe)),fe=De.sibling,fe!==null)){fe.return=W,W=fe;continue}}if(W.child!==null){W.child.return=W,W=W.child;continue}}if(W===D)break;for(;W.sibling===null;){if(W.return===null||W.return===D)return;W=W.return}W.sibling.return=W.return,W=W.sibling}};Bl=function(P){var D=P.stateNode;if(P.firstEffect!==null){var T=D.containerInfo,q=Sr(T);dp(q,P,!1,!1),D.pendingChildren=q,ga(P),Kn(T,q)}},ns=function(P,D,T,q,W){var fe=P.stateNode,De=P.memoizedProps;if((P=D.firstEffect===null)&&De===q)D.stateNode=fe;else{var vt=D.stateNode,wt=Aa(uo.current),St=null;De!==q&&(St=Te(vt,T,De,q,W,wt)),P&&St===null?D.stateNode=fe:(fe=mr(fe,St,T,De,q,D,P,vt),rt(fe,T,q,W,wt)&&ga(D),D.stateNode=fe,P?ga(D):Dc(fe,D,!1,!1))}},Yr=function(P,D,T,q){T!==q&&(P=Aa(yc.current),T=Aa(uo.current),D.stateNode=Ye(q,P,T,D),ga(D))}}else Bl=function(){},ns=function(){},Yr=function(){};function Pc(P,D){switch(P.tailMode){case\"hidden\":D=P.tail;for(var T=null;D!==null;)D.alternate!==null&&(T=D),D=D.sibling;T===null?P.tail=null:T.sibling=null;break;case\"collapsed\":T=P.tail;for(var q=null;T!==null;)T.alternate!==null&&(q=T),T=T.sibling;q===null?D||P.tail===null?P.tail=null:P.tail.sibling=null:q.sibling=null}}function nw(P){switch(P.tag){case 1:ii(P.type)&&Ha(P);var D=P.effectTag;return D&4096?(P.effectTag=D&-4097|64,P):null;case 3:if(Ec(P),hr(P),D=P.effectTag,D&64)throw Error(n(285));return P.effectTag=D&-4097|64,P;case 5:return n0(P),null;case 13:return Vn($n,P),D=P.effectTag,D&4096?(P.effectTag=D&-4097|64,P):null;case 19:return Vn($n,P),null;case 4:return Ec(P),null;case 10:return Ci(P),null;default:return null}}function g0(P,D){return{value:P,source:D,stack:ml(D)}}var d0=typeof WeakSet==\"function\"?WeakSet:Set;function Wa(P,D){var T=D.source,q=D.stack;q===null&&T!==null&&(q=ml(T)),T!==null&&de(T.type),D=D.value,P!==null&&P.tag===1&&de(P.type);try{console.error(D)}catch(W){setTimeout(function(){throw W})}}function Cd(P,D){try{D.props=P.memoizedProps,D.state=P.memoizedState,D.componentWillUnmount()}catch(T){GA(P,T)}}function m0(P){var D=P.ref;if(D!==null)if(typeof D==\"function\")try{D(null)}catch(T){GA(P,T)}else D.current=null}function Qt(P,D){switch(D.tag){case 0:case 11:case 15:N(2,0,D);break;case 1:if(D.effectTag&256&&P!==null){var T=P.memoizedProps,q=P.memoizedState;P=D.stateNode,D=P.getSnapshotBeforeUpdate(D.elementType===D.type?T:Ei(D.type,T),q),P.__reactInternalSnapshotBeforeUpdate=D}break;case 3:case 5:case 6:case 4:case 17:break;default:throw Error(n(163))}}function N(P,D,T){if(T=T.updateQueue,T=T!==null?T.lastEffect:null,T!==null){var q=T=T.next;do{if(q.tag&P){var W=q.destroy;q.destroy=void 0,W!==void 0&&W()}q.tag&D&&(W=q.create,q.destroy=W()),q=q.next}while(q!==T)}}function K(P,D,T){switch(typeof pw==\"function\"&&pw(D),D.tag){case 0:case 11:case 14:case 15:if(P=D.updateQueue,P!==null&&(P=P.lastEffect,P!==null)){var q=P.next;lo(97<T?97:T,function(){var W=q;do{var fe=W.destroy;if(fe!==void 0){var De=D;try{fe()}catch(vt){GA(De,vt)}}W=W.next}while(W!==q)})}break;case 1:m0(D),T=D.stateNode,typeof T.componentWillUnmount==\"function\"&&Cd(D,T);break;case 5:m0(D);break;case 4:w?Cr(P,D,T):b&&ze(D)}}function re(P,D,T){for(var q=D;;)if(K(P,q,T),q.child===null||w&&q.tag===4){if(q===D)break;for(;q.sibling===null;){if(q.return===null||q.return===D)return;q=q.return}q.sibling.return=q.return,q=q.sibling}else q.child.return=q,q=q.child}function he(P){var D=P.alternate;P.return=null,P.child=null,P.memoizedState=null,P.updateQueue=null,P.dependencies=null,P.alternate=null,P.firstEffect=null,P.lastEffect=null,P.pendingProps=null,P.memoizedProps=null,D!==null&&he(D)}function ze(P){if(b){P=P.stateNode.containerInfo;var D=Sr(P);Ms(P,D)}}function mt(P){return P.tag===5||P.tag===3||P.tag===4}function fr(P){if(w){e:{for(var D=P.return;D!==null;){if(mt(D)){var T=D;break e}D=D.return}throw Error(n(160))}switch(D=T.stateNode,T.tag){case 5:var q=!1;break;case 3:D=D.containerInfo,q=!0;break;case 4:D=D.containerInfo,q=!0;break;default:throw Error(n(161))}T.effectTag&16&&(jt(D),T.effectTag&=-17);e:t:for(T=P;;){for(;T.sibling===null;){if(T.return===null||mt(T.return)){T=null;break e}T=T.return}for(T.sibling.return=T.return,T=T.sibling;T.tag!==5&&T.tag!==6&&T.tag!==18;){if(T.effectTag&2||T.child===null||T.tag===4)continue t;T.child.return=T,T=T.child}if(!(T.effectTag&2)){T=T.stateNode;break e}}for(var W=P;;){var fe=W.tag===5||W.tag===6;if(fe)fe=fe?W.stateNode:W.stateNode.instance,T?q?Re(D,fe,T):Se(D,fe,T):q?J(D,fe):F(D,fe);else if(W.tag!==4&&W.child!==null){W.child.return=W,W=W.child;continue}if(W===P)break;for(;W.sibling===null;){if(W.return===null||W.return===P)return;W=W.return}W.sibling.return=W.return,W=W.sibling}}}function Cr(P,D,T){for(var q=D,W=!1,fe,De;;){if(!W){W=q.return;e:for(;;){if(W===null)throw Error(n(160));switch(fe=W.stateNode,W.tag){case 5:De=!1;break e;case 3:fe=fe.containerInfo,De=!0;break e;case 4:fe=fe.containerInfo,De=!0;break e}W=W.return}W=!0}if(q.tag===5||q.tag===6)re(P,q,T),De?dt(fe,q.stateNode):at(fe,q.stateNode);else if(q.tag===4){if(q.child!==null){fe=q.stateNode.containerInfo,De=!0,q.child.return=q,q=q.child;continue}}else if(K(P,q,T),q.child!==null){q.child.return=q,q=q.child;continue}if(q===D)break;for(;q.sibling===null;){if(q.return===null||q.return===D)return;q=q.return,q.tag===4&&(W=!1)}q.sibling.return=q.return,q=q.sibling}}function yn(P,D){if(w)switch(D.tag){case 0:case 11:case 14:case 15:N(4,8,D);break;case 1:break;case 5:var T=D.stateNode;if(T!=null){var q=D.memoizedProps;P=P!==null?P.memoizedProps:q;var W=D.type,fe=D.updateQueue;D.updateQueue=null,fe!==null&&ie(T,fe,W,P,q,D)}break;case 6:if(D.stateNode===null)throw Error(n(162));T=D.memoizedProps,X(D.stateNode,P!==null?P.memoizedProps:T,T);break;case 3:y&&(D=D.stateNode,D.hydrate&&(D.hydrate=!1,Dn(D.containerInfo)));break;case 12:break;case 13:oi(D),Li(D);break;case 19:Li(D);break;case 17:break;case 20:break;case 21:break;default:throw Error(n(163))}else{switch(D.tag){case 0:case 11:case 14:case 15:N(4,8,D);return;case 12:return;case 13:oi(D),Li(D);return;case 19:Li(D);return;case 3:y&&(T=D.stateNode,T.hydrate&&(T.hydrate=!1,Dn(T.containerInfo)))}e:if(b)switch(D.tag){case 1:case 5:case 6:case 20:break e;case 3:case 4:D=D.stateNode,Ms(D.containerInfo,D.pendingChildren);break e;default:throw Error(n(163))}}}function oi(P){var D=P;if(P.memoizedState===null)var T=!1;else T=!0,D=P.child,ow=Ni();if(w&&D!==null){e:if(P=D,w)for(D=P;;){if(D.tag===5){var q=D.stateNode;T?tr(q):ln(D.stateNode,D.memoizedProps)}else if(D.tag===6)q=D.stateNode,T?bt(q):kr(q,D.memoizedProps);else if(D.tag===13&&D.memoizedState!==null&&D.memoizedState.dehydrated===null){q=D.child.sibling,q.return=D,D=q;continue}else if(D.child!==null){D.child.return=D,D=D.child;continue}if(D===P)break e;for(;D.sibling===null;){if(D.return===null||D.return===P)break e;D=D.return}D.sibling.return=D.return,D=D.sibling}}}function Li(P){var D=P.updateQueue;if(D!==null){P.updateQueue=null;var T=P.stateNode;T===null&&(T=P.stateNode=new d0),D.forEach(function(q){var W=aF.bind(null,P,q);T.has(q)||(T.add(q),q.then(W,W))})}}var y0=typeof WeakMap==\"function\"?WeakMap:Map;function bv(P,D,T){T=Cs(T,null),T.tag=3,T.payload={element:null};var q=D.value;return T.callback=function(){Pu||(Pu=!0,Dd=q),Wa(P,D)},T}function Sv(P,D,T){T=Cs(T,null),T.tag=3;var q=P.type.getDerivedStateFromError;if(typeof q==\"function\"){var W=D.value;T.payload=function(){return Wa(P,D),q(W)}}var fe=P.stateNode;return fe!==null&&typeof fe.componentDidCatch==\"function\"&&(T.callback=function(){typeof q!=\"function\"&&(bu===null?bu=new Set([this]):bu.add(this),Wa(P,D));var De=D.stack;this.componentDidCatch(D.value,{componentStack:De!==null?De:\"\"})}),T}var iw=Math.ceil,mp=u.ReactCurrentDispatcher,sw=u.ReactCurrentOwner,En=0,wd=8,is=16,Gs=32,Du=0,Id=1,Ii=2,da=3,vl=4,bc=5,yr=En,gi=null,Mr=null,ss=0,Yi=Du,Bd=null,Ka=1073741823,MA=1073741823,vd=null,yp=0,OA=!1,ow=0,aw=500,lr=null,Pu=!1,Dd=null,bu=null,Ep=!1,E0=null,UA=90,_A=null,C0=0,lw=null,Pd=0;function ma(){return(yr&(is|Gs))!==En?1073741821-(Ni()/10|0):Pd!==0?Pd:Pd=1073741821-(Ni()/10|0)}function HA(P,D,T){if(D=D.mode,!(D&2))return 1073741823;var q=_o();if(!(D&4))return q===99?1073741823:1073741822;if((yr&is)!==En)return ss;if(T!==null)P=qa(P,T.timeoutMs|0||5e3,250);else switch(q){case 99:P=1073741823;break;case 98:P=qa(P,150,100);break;case 97:case 96:P=qa(P,5e3,250);break;case 95:P=2;break;default:throw Error(n(326))}return gi!==null&&P===ss&&--P,P}function Sc(P,D){if(50<C0)throw C0=0,lw=null,Error(n(185));if(P=w0(P,D),P!==null){var T=_o();D===1073741823?(yr&wd)!==En&&(yr&(is|Gs))===En?cw(P):(fo(P),yr===En&&qi()):fo(P),(yr&4)===En||T!==98&&T!==99||(_A===null?_A=new Map([[P,D]]):(T=_A.get(P),(T===void 0||T>D)&&_A.set(P,D)))}}function w0(P,D){P.expirationTime<D&&(P.expirationTime=D);var T=P.alternate;T!==null&&T.expirationTime<D&&(T.expirationTime=D);var q=P.return,W=null;if(q===null&&P.tag===3)W=P.stateNode;else for(;q!==null;){if(T=q.alternate,q.childExpirationTime<D&&(q.childExpirationTime=D),T!==null&&T.childExpirationTime<D&&(T.childExpirationTime=D),q.return===null&&q.tag===3){W=q.stateNode;break}q=q.return}return W!==null&&(gi===W&&(Sd(D),Yi===vl&&WA(W,ss)),Mv(W,D)),W}function bd(P){var D=P.lastExpiredTime;return D!==0||(D=P.firstPendingTime,!Lv(P,D))?D:(D=P.lastPingedTime,P=P.nextKnownPendingLevel,D>P?D:P)}function fo(P){if(P.lastExpiredTime!==0)P.callbackExpirationTime=1073741823,P.callbackPriority=99,P.callbackNode=gu(cw.bind(null,P));else{var D=bd(P),T=P.callbackNode;if(D===0)T!==null&&(P.callbackNode=null,P.callbackExpirationTime=0,P.callbackPriority=90);else{var q=ma();if(D===1073741823?q=99:D===1||D===2?q=95:(q=10*(1073741821-D)-10*(1073741821-q),q=0>=q?99:250>=q?98:5250>=q?97:95),T!==null){var W=P.callbackPriority;if(P.callbackExpirationTime===D&&W>=q)return;T!==PA&&Ie(T)}P.callbackExpirationTime=D,P.callbackPriority=q,D=D===1073741823?gu(cw.bind(null,P)):dc(q,xv.bind(null,P),{timeout:10*(1073741821-D)-Ni()}),P.callbackNode=D}}}function xv(P,D){if(Pd=0,D)return D=ma(),kd(P,D),fo(P),null;var T=bd(P);if(T!==0){if(D=P.callbackNode,(yr&(is|Gs))!==En)throw Error(n(327));if(Cp(),P===gi&&T===ss||Su(P,T),Mr!==null){var q=yr;yr|=is;var W=jA(P);do try{rF();break}catch(vt){qA(P,vt)}while(!0);if(ua(),yr=q,mp.current=W,Yi===Id)throw D=Bd,Su(P,T),WA(P,T),fo(P),D;if(Mr===null)switch(W=P.finishedWork=P.current.alternate,P.finishedExpirationTime=T,q=Yi,gi=null,q){case Du:case Id:throw Error(n(345));case Ii:kd(P,2<T?2:T);break;case da:if(WA(P,T),q=P.lastSuspendedTime,T===q&&(P.nextKnownPendingLevel=Aw(W)),Ka===1073741823&&(W=ow+aw-Ni(),10<W)){if(OA){var fe=P.lastPingedTime;if(fe===0||fe>=T){P.lastPingedTime=T,Su(P,T);break}}if(fe=bd(P),fe!==0&&fe!==T)break;if(q!==0&&q!==T){P.lastPingedTime=q;break}P.timeoutHandle=be(xu.bind(null,P),W);break}xu(P);break;case vl:if(WA(P,T),q=P.lastSuspendedTime,T===q&&(P.nextKnownPendingLevel=Aw(W)),OA&&(W=P.lastPingedTime,W===0||W>=T)){P.lastPingedTime=T,Su(P,T);break}if(W=bd(P),W!==0&&W!==T)break;if(q!==0&&q!==T){P.lastPingedTime=q;break}if(MA!==1073741823?q=10*(1073741821-MA)-Ni():Ka===1073741823?q=0:(q=10*(1073741821-Ka)-5e3,W=Ni(),T=10*(1073741821-T)-W,q=W-q,0>q&&(q=0),q=(120>q?120:480>q?480:1080>q?1080:1920>q?1920:3e3>q?3e3:4320>q?4320:1960*iw(q/1960))-q,T<q&&(q=T)),10<q){P.timeoutHandle=be(xu.bind(null,P),q);break}xu(P);break;case bc:if(Ka!==1073741823&&vd!==null){fe=Ka;var De=vd;if(q=De.busyMinDurationMs|0,0>=q?q=0:(W=De.busyDelayMs|0,fe=Ni()-(10*(1073741821-fe)-(De.timeoutMs|0||5e3)),q=fe<=W?0:W+q-fe),10<q){WA(P,T),P.timeoutHandle=be(xu.bind(null,P),q);break}}xu(P);break;default:throw Error(n(329))}if(fo(P),P.callbackNode===D)return xv.bind(null,P)}}return null}function cw(P){var D=P.lastExpiredTime;if(D=D!==0?D:1073741823,P.finishedExpirationTime===D)xu(P);else{if((yr&(is|Gs))!==En)throw Error(n(327));if(Cp(),P===gi&&D===ss||Su(P,D),Mr!==null){var T=yr;yr|=is;var q=jA(P);do try{tF();break}catch(W){qA(P,W)}while(!0);if(ua(),yr=T,mp.current=q,Yi===Id)throw T=Bd,Su(P,D),WA(P,D),fo(P),T;if(Mr!==null)throw Error(n(261));P.finishedWork=P.current.alternate,P.finishedExpirationTime=D,gi=null,xu(P),fo(P)}}return null}function kv(P,D){kd(P,D),fo(P),(yr&(is|Gs))===En&&qi()}function eF(){if(_A!==null){var P=_A;_A=null,P.forEach(function(D,T){kd(T,D),fo(T)}),qi()}}function Qv(P,D){if((yr&(is|Gs))!==En)throw Error(n(187));var T=yr;yr|=1;try{return lo(99,P.bind(null,D))}finally{yr=T,qi()}}function Su(P,D){P.finishedWork=null,P.finishedExpirationTime=0;var T=P.timeoutHandle;if(T!==Ue&&(P.timeoutHandle=Ue,et(T)),Mr!==null)for(T=Mr.return;T!==null;){var q=T;switch(q.tag){case 1:var W=q.type.childContextTypes;W!=null&&Ha(q);break;case 3:Ec(q),hr(q);break;case 5:n0(q);break;case 4:Ec(q);break;case 13:Vn($n,q);break;case 19:Vn($n,q);break;case 10:Ci(q)}T=T.return}gi=P,Mr=YA(P.current,null,D),ss=D,Yi=Du,Bd=null,MA=Ka=1073741823,vd=null,yp=0,OA=!1}function qA(P,D){do{try{if(ua(),tw(),Mr===null||Mr.return===null)return Yi=Id,Bd=D,null;e:{var T=P,q=Mr.return,W=Mr,fe=D;if(D=ss,W.effectTag|=2048,W.firstEffect=W.lastEffect=null,fe!==null&&typeof fe==\"object\"&&typeof fe.then==\"function\"){var De=fe,vt=($n.current&1)!==0,wt=q;do{var St;if(St=wt.tag===13){var _r=wt.memoizedState;if(_r!==null)St=_r.dehydrated!==null;else{var os=wt.memoizedProps;St=os.fallback===void 0?!1:os.unstable_avoidThisFallback!==!0?!0:!vt}}if(St){var di=wt.updateQueue;if(di===null){var po=new Set;po.add(De),wt.updateQueue=po}else di.add(De);if(!(wt.mode&2)){if(wt.effectTag|=64,W.effectTag&=-2981,W.tag===1)if(W.alternate===null)W.tag=17;else{var KA=Cs(1073741823,null);KA.tag=2,tt(W,KA)}W.expirationTime=1073741823;break e}fe=void 0,W=D;var Yo=T.pingCache;if(Yo===null?(Yo=T.pingCache=new y0,fe=new Set,Yo.set(De,fe)):(fe=Yo.get(De),fe===void 0&&(fe=new Set,Yo.set(De,fe))),!fe.has(W)){fe.add(W);var nt=oF.bind(null,T,De,W);De.then(nt,nt)}wt.effectTag|=4096,wt.expirationTime=D;break e}wt=wt.return}while(wt!==null);fe=Error((de(W.type)||\"A React component\")+` suspended while rendering, but no fallback UI was specified.\n\nAdd a <Suspense fallback=...> component higher in the tree to provide a loading indicator or placeholder to display.`+ml(W))}Yi!==bc&&(Yi=Ii),fe=g0(fe,W),wt=q;do{switch(wt.tag){case 3:De=fe,wt.effectTag|=4096,wt.expirationTime=D;var Ve=bv(wt,De,D);Bt(wt,Ve);break e;case 1:De=fe;var At=wt.type,Wt=wt.stateNode;if(!(wt.effectTag&64)&&(typeof At.getDerivedStateFromError==\"function\"||Wt!==null&&typeof Wt.componentDidCatch==\"function\"&&(bu===null||!bu.has(Wt)))){wt.effectTag|=4096,wt.expirationTime=D;var vr=Sv(wt,De,D);Bt(wt,vr);break e}}wt=wt.return}while(wt!==null)}Mr=Rv(Mr)}catch(bn){D=bn;continue}break}while(!0)}function jA(){var P=mp.current;return mp.current=Bu,P===null?Bu:P}function uw(P,D){P<Ka&&2<P&&(Ka=P),D!==null&&P<MA&&2<P&&(MA=P,vd=D)}function Sd(P){P>yp&&(yp=P)}function tF(){for(;Mr!==null;)Mr=Fv(Mr)}function rF(){for(;Mr!==null&&!Tt();)Mr=Fv(Mr)}function Fv(P){var D=Nv(P.alternate,P,ss);return P.memoizedProps=P.pendingProps,D===null&&(D=Rv(P)),sw.current=null,D}function Rv(P){Mr=P;do{var D=Mr.alternate;if(P=Mr.return,Mr.effectTag&2048){if(D=nw(Mr,ss),D!==null)return D.effectTag&=2047,D;P!==null&&(P.firstEffect=P.lastEffect=null,P.effectTag|=2048)}else{e:{var T=D;D=Mr;var q=ss,W=D.pendingProps;switch(D.tag){case 2:break;case 16:break;case 15:case 0:break;case 1:ii(D.type)&&Ha(D);break;case 3:Ec(D),hr(D),W=D.stateNode,W.pendingContext&&(W.context=W.pendingContext,W.pendingContext=null),(T===null||T.child===null)&&Ga(D)&&ga(D),Bl(D);break;case 5:n0(D);var fe=Aa(yc.current);if(q=D.type,T!==null&&D.stateNode!=null)ns(T,D,q,W,fe),T.ref!==D.ref&&(D.effectTag|=128);else if(W){if(T=Aa(uo.current),Ga(D)){if(W=D,!y)throw Error(n(175));T=sp(W.stateNode,W.type,W.memoizedProps,fe,T,W),W.updateQueue=T,T=T!==null,T&&ga(D)}else{var De=ht(q,W,fe,T,D);Dc(De,D,!1,!1),D.stateNode=De,rt(De,q,W,fe,T)&&ga(D)}D.ref!==null&&(D.effectTag|=128)}else if(D.stateNode===null)throw Error(n(166));break;case 6:if(T&&D.stateNode!=null)Yr(T,D,T.memoizedProps,W);else{if(typeof W!=\"string\"&&D.stateNode===null)throw Error(n(166));if(T=Aa(yc.current),fe=Aa(uo.current),Ga(D)){if(T=D,!y)throw Error(n(176));(T=op(T.stateNode,T.memoizedProps,T))&&ga(D)}else D.stateNode=Ye(W,T,fe,D)}break;case 11:break;case 13:if(Vn($n,D),W=D.memoizedState,D.effectTag&64){D.expirationTime=q;break e}W=W!==null,fe=!1,T===null?D.memoizedProps.fallback!==void 0&&Ga(D):(q=T.memoizedState,fe=q!==null,W||q===null||(q=T.child.sibling,q!==null&&(De=D.firstEffect,De!==null?(D.firstEffect=q,q.nextEffect=De):(D.firstEffect=D.lastEffect=q,q.nextEffect=null),q.effectTag=8))),W&&!fe&&D.mode&2&&(T===null&&D.memoizedProps.unstable_avoidThisFallback!==!0||$n.current&1?Yi===Du&&(Yi=da):((Yi===Du||Yi===da)&&(Yi=vl),yp!==0&&gi!==null&&(WA(gi,ss),Mv(gi,yp)))),b&&W&&(D.effectTag|=4),w&&(W||fe)&&(D.effectTag|=4);break;case 7:break;case 8:break;case 12:break;case 4:Ec(D),Bl(D);break;case 10:Ci(D);break;case 9:break;case 14:break;case 17:ii(D.type)&&Ha(D);break;case 19:if(Vn($n,D),W=D.memoizedState,W===null)break;if(fe=(D.effectTag&64)!==0,De=W.rendering,De===null){if(fe)Pc(W,!1);else if(Yi!==Du||T!==null&&T.effectTag&64)for(T=D.child;T!==null;){if(De=cp(T),De!==null){for(D.effectTag|=64,Pc(W,!1),T=De.updateQueue,T!==null&&(D.updateQueue=T,D.effectTag|=4),W.lastEffect===null&&(D.firstEffect=null),D.lastEffect=W.lastEffect,T=q,W=D.child;W!==null;)fe=W,q=T,fe.effectTag&=2,fe.nextEffect=null,fe.firstEffect=null,fe.lastEffect=null,De=fe.alternate,De===null?(fe.childExpirationTime=0,fe.expirationTime=q,fe.child=null,fe.memoizedProps=null,fe.memoizedState=null,fe.updateQueue=null,fe.dependencies=null):(fe.childExpirationTime=De.childExpirationTime,fe.expirationTime=De.expirationTime,fe.child=De.child,fe.memoizedProps=De.memoizedProps,fe.memoizedState=De.memoizedState,fe.updateQueue=De.updateQueue,q=De.dependencies,fe.dependencies=q===null?null:{expirationTime:q.expirationTime,firstContext:q.firstContext,responders:q.responders}),W=W.sibling;Mn($n,$n.current&1|2,D),D=D.child;break e}T=T.sibling}}else{if(!fe)if(T=cp(De),T!==null){if(D.effectTag|=64,fe=!0,T=T.updateQueue,T!==null&&(D.updateQueue=T,D.effectTag|=4),Pc(W,!0),W.tail===null&&W.tailMode===\"hidden\"&&!De.alternate){D=D.lastEffect=W.lastEffect,D!==null&&(D.nextEffect=null);break}}else Ni()>W.tailExpiration&&1<q&&(D.effectTag|=64,fe=!0,Pc(W,!1),D.expirationTime=D.childExpirationTime=q-1);W.isBackwards?(De.sibling=D.child,D.child=De):(T=W.last,T!==null?T.sibling=De:D.child=De,W.last=De)}if(W.tail!==null){W.tailExpiration===0&&(W.tailExpiration=Ni()+500),T=W.tail,W.rendering=T,W.tail=T.sibling,W.lastEffect=D.lastEffect,T.sibling=null,W=$n.current,W=fe?W&1|2:W&1,Mn($n,W,D),D=T;break e}break;case 20:break;case 21:break;default:throw Error(n(156,D.tag))}D=null}if(T=Mr,ss===1||T.childExpirationTime!==1){for(W=0,fe=T.child;fe!==null;)q=fe.expirationTime,De=fe.childExpirationTime,q>W&&(W=q),De>W&&(W=De),fe=fe.sibling;T.childExpirationTime=W}if(D!==null)return D;P!==null&&!(P.effectTag&2048)&&(P.firstEffect===null&&(P.firstEffect=Mr.firstEffect),Mr.lastEffect!==null&&(P.lastEffect!==null&&(P.lastEffect.nextEffect=Mr.firstEffect),P.lastEffect=Mr.lastEffect),1<Mr.effectTag&&(P.lastEffect!==null?P.lastEffect.nextEffect=Mr:P.firstEffect=Mr,P.lastEffect=Mr))}if(D=Mr.sibling,D!==null)return D;Mr=P}while(Mr!==null);return Yi===Du&&(Yi=bc),null}function Aw(P){var D=P.expirationTime;return P=P.childExpirationTime,D>P?D:P}function xu(P){var D=_o();return lo(99,nF.bind(null,P,D)),null}function nF(P,D){do Cp();while(E0!==null);if((yr&(is|Gs))!==En)throw Error(n(327));var T=P.finishedWork,q=P.finishedExpirationTime;if(T===null)return null;if(P.finishedWork=null,P.finishedExpirationTime=0,T===P.current)throw Error(n(177));P.callbackNode=null,P.callbackExpirationTime=0,P.callbackPriority=90,P.nextKnownPendingLevel=0;var W=Aw(T);if(P.firstPendingTime=W,q<=P.lastSuspendedTime?P.firstSuspendedTime=P.lastSuspendedTime=P.nextKnownPendingLevel=0:q<=P.firstSuspendedTime&&(P.firstSuspendedTime=q-1),q<=P.lastPingedTime&&(P.lastPingedTime=0),q<=P.lastExpiredTime&&(P.lastExpiredTime=0),P===gi&&(Mr=gi=null,ss=0),1<T.effectTag?T.lastEffect!==null?(T.lastEffect.nextEffect=T,W=T.firstEffect):W=T:W=T.firstEffect,W!==null){var fe=yr;yr|=Gs,sw.current=null,xe(P.containerInfo),lr=W;do try{iF()}catch(ho){if(lr===null)throw Error(n(330));GA(lr,ho),lr=lr.nextEffect}while(lr!==null);lr=W;do try{for(var De=P,vt=D;lr!==null;){var wt=lr.effectTag;if(wt&16&&w&&jt(lr.stateNode),wt&128){var St=lr.alternate;if(St!==null){var _r=St.ref;_r!==null&&(typeof _r==\"function\"?_r(null):_r.current=null)}}switch(wt&1038){case 2:fr(lr),lr.effectTag&=-3;break;case 6:fr(lr),lr.effectTag&=-3,yn(lr.alternate,lr);break;case 1024:lr.effectTag&=-1025;break;case 1028:lr.effectTag&=-1025,yn(lr.alternate,lr);break;case 4:yn(lr.alternate,lr);break;case 8:var os=De,di=lr,po=vt;w?Cr(os,di,po):re(os,di,po),he(di)}lr=lr.nextEffect}}catch(ho){if(lr===null)throw Error(n(330));GA(lr,ho),lr=lr.nextEffect}while(lr!==null);Ne(P.containerInfo),P.current=T,lr=W;do try{for(wt=q;lr!==null;){var KA=lr.effectTag;if(KA&36){var Yo=lr.alternate;switch(St=lr,_r=wt,St.tag){case 0:case 11:case 15:N(16,32,St);break;case 1:var nt=St.stateNode;if(St.effectTag&4)if(Yo===null)nt.componentDidMount();else{var Ve=St.elementType===St.type?Yo.memoizedProps:Ei(St.type,Yo.memoizedProps);nt.componentDidUpdate(Ve,Yo.memoizedState,nt.__reactInternalSnapshotBeforeUpdate)}var At=St.updateQueue;At!==null&&Le(St,At,nt,_r);break;case 3:var Wt=St.updateQueue;if(Wt!==null){if(De=null,St.child!==null)switch(St.child.tag){case 5:De=Ae(St.child.stateNode);break;case 1:De=St.child.stateNode}Le(St,Wt,De,_r)}break;case 5:var vr=St.stateNode;Yo===null&&St.effectTag&4&&$(vr,St.type,St.memoizedProps,St);break;case 6:break;case 4:break;case 12:break;case 13:if(y&&St.memoizedState===null){var bn=St.alternate;if(bn!==null){var Qr=bn.memoizedState;if(Qr!==null){var Sn=Qr.dehydrated;Sn!==null&&oo(Sn)}}}break;case 19:case 17:case 20:case 21:break;default:throw Error(n(163))}}if(KA&128){St=void 0;var ai=lr.ref;if(ai!==null){var tn=lr.stateNode;switch(lr.tag){case 5:St=Ae(tn);break;default:St=tn}typeof ai==\"function\"?ai(St):ai.current=St}}lr=lr.nextEffect}}catch(ho){if(lr===null)throw Error(n(330));GA(lr,ho),lr=lr.nextEffect}while(lr!==null);lr=null,Qn(),yr=fe}else P.current=T;if(Ep)Ep=!1,E0=P,UA=D;else for(lr=W;lr!==null;)D=lr.nextEffect,lr.nextEffect=null,lr=D;if(D=P.firstPendingTime,D===0&&(bu=null),D===1073741823?P===lw?C0++:(C0=0,lw=P):C0=0,typeof fw==\"function\"&&fw(T.stateNode,q),fo(P),Pu)throw Pu=!1,P=Dd,Dd=null,P;return(yr&wd)!==En||qi(),null}function iF(){for(;lr!==null;){var P=lr.effectTag;P&256&&Qt(lr.alternate,lr),!(P&512)||Ep||(Ep=!0,dc(97,function(){return Cp(),null})),lr=lr.nextEffect}}function Cp(){if(UA!==90){var P=97<UA?97:UA;return UA=90,lo(P,sF)}}function sF(){if(E0===null)return!1;var P=E0;if(E0=null,(yr&(is|Gs))!==En)throw Error(n(331));var D=yr;for(yr|=Gs,P=P.current.firstEffect;P!==null;){try{var T=P;if(T.effectTag&512)switch(T.tag){case 0:case 11:case 15:N(128,0,T),N(0,64,T)}}catch(q){if(P===null)throw Error(n(330));GA(P,q)}T=P.nextEffect,P.nextEffect=null,P=T}return yr=D,qi(),!0}function Tv(P,D,T){D=g0(T,D),D=bv(P,D,1073741823),tt(P,D),P=w0(P,1073741823),P!==null&&fo(P)}function GA(P,D){if(P.tag===3)Tv(P,P,D);else for(var T=P.return;T!==null;){if(T.tag===3){Tv(T,P,D);break}else if(T.tag===1){var q=T.stateNode;if(typeof T.type.getDerivedStateFromError==\"function\"||typeof q.componentDidCatch==\"function\"&&(bu===null||!bu.has(q))){P=g0(D,P),P=Sv(T,P,1073741823),tt(T,P),T=w0(T,1073741823),T!==null&&fo(T);break}}T=T.return}}function oF(P,D,T){var q=P.pingCache;q!==null&&q.delete(D),gi===P&&ss===T?Yi===vl||Yi===da&&Ka===1073741823&&Ni()-ow<aw?Su(P,ss):OA=!0:Lv(P,T)&&(D=P.lastPingedTime,D!==0&&D<T||(P.lastPingedTime=T,P.finishedExpirationTime===T&&(P.finishedExpirationTime=0,P.finishedWork=null),fo(P)))}function aF(P,D){var T=P.stateNode;T!==null&&T.delete(D),D=0,D===0&&(D=ma(),D=HA(D,P,null)),P=w0(P,D),P!==null&&fo(P)}var Nv;Nv=function(P,D,T){var q=D.expirationTime;if(P!==null){var W=D.pendingProps;if(P.memoizedProps!==W||_i.current)jo=!0;else{if(q<T){switch(jo=!1,D.tag){case 3:h0(D),p0();break;case 5:if(hd(D),D.mode&4&&T!==1&&ke(D.type,W))return D.expirationTime=D.childExpirationTime=1,null;break;case 1:ii(D.type)&&fc(D);break;case 4:r0(D,D.stateNode.containerInfo);break;case 10:Ho(D,D.memoizedProps.value);break;case 13:if(D.memoizedState!==null)return q=D.child.childExpirationTime,q!==0&&q>=T?cn(P,D,T):(Mn($n,$n.current&1,D),D=si(P,D,T),D!==null?D.sibling:null);Mn($n,$n.current&1,D);break;case 19:if(q=D.childExpirationTime>=T,P.effectTag&64){if(q)return Ya(P,D,T);D.effectTag|=64}if(W=D.memoizedState,W!==null&&(W.rendering=null,W.tail=null),Mn($n,$n.current,D),!q)return null}return si(P,D,T)}jo=!1}}else jo=!1;switch(D.expirationTime=0,D.tag){case 2:if(q=D.type,P!==null&&(P.alternate=null,D.alternate=null,D.effectTag|=2),P=D.pendingProps,W=Me(D,On.current),ys(D,T),W=s0(null,D,q,P,W,T),D.effectTag|=1,typeof W==\"object\"&&W!==null&&typeof W.render==\"function\"&&W.$$typeof===void 0){if(D.tag=1,tw(),ii(q)){var fe=!0;fc(D)}else fe=!1;D.memoizedState=W.state!==null&&W.state!==void 0?W.state:null;var De=q.getDerivedStateFromProps;typeof De==\"function\"&&rr(D,q,De,P),W.updater=$r,D.stateNode=W,W._reactInternalFiber=D,qo(D,q,P,T),D=gp(null,D,q,!0,fe,T)}else D.tag=0,Bs(null,D,W,T),D=D.child;return D;case 16:if(W=D.elementType,P!==null&&(P.alternate=null,D.alternate=null,D.effectTag|=2),P=D.pendingProps,Ce(W),W._status!==1)throw W._result;switch(W=W._result,D.type=W,fe=D.tag=uF(W),P=Ei(W,P),fe){case 0:D=NA(null,D,W,P,T);break;case 1:D=hp(null,D,W,P,T);break;case 11:D=wi(null,D,W,P,T);break;case 14:D=yd(null,D,W,Ei(W.type,P),q,T);break;default:throw Error(n(306,W,\"\"))}return D;case 0:return q=D.type,W=D.pendingProps,W=D.elementType===q?W:Ei(q,W),NA(P,D,q,W,T);case 1:return q=D.type,W=D.pendingProps,W=D.elementType===q?W:Ei(q,W),hp(P,D,q,W,T);case 3:if(h0(D),q=D.updateQueue,q===null)throw Error(n(282));if(W=D.memoizedState,W=W!==null?W.element:null,ye(D,q,D.pendingProps,null,T),q=D.memoizedState.element,q===W)p0(),D=si(P,D,T);else{if((W=D.stateNode.hydrate)&&(y?(vc=Au(D.stateNode.containerInfo),pa=D,W=Il=!0):W=!1),W)for(T=t0(D,null,q,T),D.child=T;T;)T.effectTag=T.effectTag&-3|1024,T=T.sibling;else Bs(P,D,q,T),p0();D=D.child}return D;case 5:return hd(D),P===null&&TA(D),q=D.type,W=D.pendingProps,fe=P!==null?P.memoizedProps:null,De=W.children,Fe(q,W)?De=null:fe!==null&&Fe(q,fe)&&(D.effectTag|=16),Go(P,D),D.mode&4&&T!==1&&ke(q,W)?(D.expirationTime=D.childExpirationTime=1,D=null):(Bs(P,D,De,T),D=D.child),D;case 6:return P===null&&TA(D),null;case 13:return cn(P,D,T);case 4:return r0(D,D.stateNode.containerInfo),q=D.pendingProps,P===null?D.child=mu(D,null,q,T):Bs(P,D,q,T),D.child;case 11:return q=D.type,W=D.pendingProps,W=D.elementType===q?W:Ei(q,W),wi(P,D,q,W,T);case 7:return Bs(P,D,D.pendingProps,T),D.child;case 8:return Bs(P,D,D.pendingProps.children,T),D.child;case 12:return Bs(P,D,D.pendingProps.children,T),D.child;case 10:e:{if(q=D.type._context,W=D.pendingProps,De=D.memoizedProps,fe=W.value,Ho(D,fe),De!==null){var vt=De.value;if(fe=ds(vt,fe)?0:(typeof q._calculateChangedBits==\"function\"?q._calculateChangedBits(vt,fe):1073741823)|0,fe===0){if(De.children===W.children&&!_i.current){D=si(P,D,T);break e}}else for(vt=D.child,vt!==null&&(vt.return=D);vt!==null;){var wt=vt.dependencies;if(wt!==null){De=vt.child;for(var St=wt.firstContext;St!==null;){if(St.context===q&&St.observedBits&fe){vt.tag===1&&(St=Cs(T,null),St.tag=2,tt(vt,St)),vt.expirationTime<T&&(vt.expirationTime=T),St=vt.alternate,St!==null&&St.expirationTime<T&&(St.expirationTime=T),ms(vt.return,T),wt.expirationTime<T&&(wt.expirationTime=T);break}St=St.next}}else De=vt.tag===10&&vt.type===D.type?null:vt.child;if(De!==null)De.return=vt;else for(De=vt;De!==null;){if(De===D){De=null;break}if(vt=De.sibling,vt!==null){vt.return=De.return,De=vt;break}De=De.return}vt=De}}Bs(P,D,W.children,T),D=D.child}return D;case 9:return W=D.type,fe=D.pendingProps,q=fe.children,ys(D,T),W=Es(W,fe.unstable_observedBits),q=q(W),D.effectTag|=1,Bs(P,D,q,T),D.child;case 14:return W=D.type,fe=Ei(W,D.pendingProps),fe=Ei(W.type,fe),yd(P,D,W,fe,q,T);case 15:return Ed(P,D,D.type,D.pendingProps,q,T);case 17:return q=D.type,W=D.pendingProps,W=D.elementType===q?W:Ei(q,W),P!==null&&(P.alternate=null,D.alternate=null,D.effectTag|=2),D.tag=1,ii(q)?(P=!0,fc(D)):P=!1,ys(D,T),rs(D,q,W,T),qo(D,q,W,T),gp(null,D,q,!0,P,T);case 19:return Ya(P,D,T)}throw Error(n(156,D.tag))};var fw=null,pw=null;function lF(P){if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>\"u\")return!1;var D=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(D.isDisabled||!D.supportsFiber)return!0;try{var T=D.inject(P);fw=function(q){try{D.onCommitFiberRoot(T,q,void 0,(q.current.effectTag&64)===64)}catch{}},pw=function(q){try{D.onCommitFiberUnmount(T,q)}catch{}}}catch{}return!0}function cF(P,D,T,q){this.tag=P,this.key=T,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=D,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=q,this.effectTag=0,this.lastEffect=this.firstEffect=this.nextEffect=null,this.childExpirationTime=this.expirationTime=0,this.alternate=null}function Dl(P,D,T,q){return new cF(P,D,T,q)}function hw(P){return P=P.prototype,!(!P||!P.isReactComponent)}function uF(P){if(typeof P==\"function\")return hw(P)?1:0;if(P!=null){if(P=P.$$typeof,P===L)return 11;if(P===te)return 14}return 2}function YA(P,D){var T=P.alternate;return T===null?(T=Dl(P.tag,D,P.key,P.mode),T.elementType=P.elementType,T.type=P.type,T.stateNode=P.stateNode,T.alternate=P,P.alternate=T):(T.pendingProps=D,T.effectTag=0,T.nextEffect=null,T.firstEffect=null,T.lastEffect=null),T.childExpirationTime=P.childExpirationTime,T.expirationTime=P.expirationTime,T.child=P.child,T.memoizedProps=P.memoizedProps,T.memoizedState=P.memoizedState,T.updateQueue=P.updateQueue,D=P.dependencies,T.dependencies=D===null?null:{expirationTime:D.expirationTime,firstContext:D.firstContext,responders:D.responders},T.sibling=P.sibling,T.index=P.index,T.ref=P.ref,T}function xd(P,D,T,q,W,fe){var De=2;if(q=P,typeof P==\"function\")hw(P)&&(De=1);else if(typeof P==\"string\")De=5;else e:switch(P){case E:return ku(T.children,W,fe,D);case R:De=8,W|=7;break;case I:De=8,W|=1;break;case v:return P=Dl(12,T,D,W|8),P.elementType=v,P.type=v,P.expirationTime=fe,P;case U:return P=Dl(13,T,D,W),P.type=U,P.elementType=U,P.expirationTime=fe,P;case z:return P=Dl(19,T,D,W),P.elementType=z,P.expirationTime=fe,P;default:if(typeof P==\"object\"&&P!==null)switch(P.$$typeof){case x:De=10;break e;case C:De=9;break e;case L:De=11;break e;case te:De=14;break e;case ae:De=16,q=null;break e}throw Error(n(130,P==null?P:typeof P,\"\"))}return D=Dl(De,T,D,W),D.elementType=P,D.type=q,D.expirationTime=fe,D}function ku(P,D,T,q){return P=Dl(7,P,q,D),P.expirationTime=T,P}function gw(P,D,T){return P=Dl(6,P,null,D),P.expirationTime=T,P}function dw(P,D,T){return D=Dl(4,P.children!==null?P.children:[],P.key,D),D.expirationTime=T,D.stateNode={containerInfo:P.containerInfo,pendingChildren:null,implementation:P.implementation},D}function AF(P,D,T){this.tag=D,this.current=null,this.containerInfo=P,this.pingCache=this.pendingChildren=null,this.finishedExpirationTime=0,this.finishedWork=null,this.timeoutHandle=Ue,this.pendingContext=this.context=null,this.hydrate=T,this.callbackNode=null,this.callbackPriority=90,this.lastExpiredTime=this.lastPingedTime=this.nextKnownPendingLevel=this.lastSuspendedTime=this.firstSuspendedTime=this.firstPendingTime=0}function Lv(P,D){var T=P.firstSuspendedTime;return P=P.lastSuspendedTime,T!==0&&T>=D&&P<=D}function WA(P,D){var T=P.firstSuspendedTime,q=P.lastSuspendedTime;T<D&&(P.firstSuspendedTime=D),(q>D||T===0)&&(P.lastSuspendedTime=D),D<=P.lastPingedTime&&(P.lastPingedTime=0),D<=P.lastExpiredTime&&(P.lastExpiredTime=0)}function Mv(P,D){D>P.firstPendingTime&&(P.firstPendingTime=D);var T=P.firstSuspendedTime;T!==0&&(D>=T?P.firstSuspendedTime=P.lastSuspendedTime=P.nextKnownPendingLevel=0:D>=P.lastSuspendedTime&&(P.lastSuspendedTime=D+1),D>P.nextKnownPendingLevel&&(P.nextKnownPendingLevel=D))}function kd(P,D){var T=P.lastExpiredTime;(T===0||T>D)&&(P.lastExpiredTime=D)}function Ov(P){var D=P._reactInternalFiber;if(D===void 0)throw typeof P.render==\"function\"?Error(n(188)):Error(n(268,Object.keys(P)));return P=me(D),P===null?null:P.stateNode}function Uv(P,D){P=P.memoizedState,P!==null&&P.dehydrated!==null&&P.retryTime<D&&(P.retryTime=D)}function Qd(P,D){Uv(P,D),(P=P.alternate)&&Uv(P,D)}var _v={createContainer:function(P,D,T){return P=new AF(P,D,T),D=Dl(3,null,null,D===2?7:D===1?3:0),P.current=D,D.stateNode=P},updateContainer:function(P,D,T,q){var W=D.current,fe=ma(),De=pt.suspense;fe=HA(fe,W,De);e:if(T){T=T._reactInternalFiber;t:{if(Be(T)!==T||T.tag!==1)throw Error(n(170));var vt=T;do{switch(vt.tag){case 3:vt=vt.stateNode.context;break t;case 1:if(ii(vt.type)){vt=vt.stateNode.__reactInternalMemoizedMergedChildContext;break t}}vt=vt.return}while(vt!==null);throw Error(n(171))}if(T.tag===1){var wt=T.type;if(ii(wt)){T=fu(T,wt,vt);break e}}T=vt}else T=Ti;return D.context===null?D.context=T:D.pendingContext=T,D=Cs(fe,De),D.payload={element:P},q=q===void 0?null:q,q!==null&&(D.callback=q),tt(W,D),Sc(W,fe),fe},batchedEventUpdates:function(P,D){var T=yr;yr|=2;try{return P(D)}finally{yr=T,yr===En&&qi()}},batchedUpdates:function(P,D){var T=yr;yr|=1;try{return P(D)}finally{yr=T,yr===En&&qi()}},unbatchedUpdates:function(P,D){var T=yr;yr&=-2,yr|=wd;try{return P(D)}finally{yr=T,yr===En&&qi()}},deferredUpdates:function(P){return lo(97,P)},syncUpdates:function(P,D,T,q){return lo(99,P.bind(null,D,T,q))},discreteUpdates:function(P,D,T,q){var W=yr;yr|=4;try{return lo(98,P.bind(null,D,T,q))}finally{yr=W,yr===En&&qi()}},flushDiscreteUpdates:function(){(yr&(1|is|Gs))===En&&(eF(),Cp())},flushControlled:function(P){var D=yr;yr|=1;try{lo(99,P)}finally{yr=D,yr===En&&qi()}},flushSync:Qv,flushPassiveEffects:Cp,IsThisRendererActing:{current:!1},getPublicRootInstance:function(P){if(P=P.current,!P.child)return null;switch(P.child.tag){case 5:return Ae(P.child.stateNode);default:return P.child.stateNode}},attemptSynchronousHydration:function(P){switch(P.tag){case 3:var D=P.stateNode;D.hydrate&&kv(D,D.firstPendingTime);break;case 13:Qv(function(){return Sc(P,1073741823)}),D=qa(ma(),150,100),Qd(P,D)}},attemptUserBlockingHydration:function(P){if(P.tag===13){var D=qa(ma(),150,100);Sc(P,D),Qd(P,D)}},attemptContinuousHydration:function(P){if(P.tag===13){ma();var D=SA++;Sc(P,D),Qd(P,D)}},attemptHydrationAtCurrentPriority:function(P){if(P.tag===13){var D=ma();D=HA(D,P,null),Sc(P,D),Qd(P,D)}},findHostInstance:Ov,findHostInstanceWithWarning:function(P){return Ov(P)},findHostInstanceWithNoPortals:function(P){return P=we(P),P===null?null:P.tag===20?P.stateNode.instance:P.stateNode},shouldSuspend:function(){return!1},injectIntoDevTools:function(P){var D=P.findFiberByHostInstance;return lF(r({},P,{overrideHookState:null,overrideProps:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:u.ReactCurrentDispatcher,findHostInstanceByFiber:function(T){return T=me(T),T===null?null:T.stateNode},findFiberByHostInstance:function(T){return D?D(T):null},findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null}))}};Y2.exports=_v.default||_v;var fF=Y2.exports;return Y2.exports=t,fF}});var FEe=_((BKt,QEe)=>{\"use strict\";QEe.exports=kEe()});var TEe=_((vKt,REe)=>{\"use strict\";var Kyt={ALIGN_COUNT:8,ALIGN_AUTO:0,ALIGN_FLEX_START:1,ALIGN_CENTER:2,ALIGN_FLEX_END:3,ALIGN_STRETCH:4,ALIGN_BASELINE:5,ALIGN_SPACE_BETWEEN:6,ALIGN_SPACE_AROUND:7,DIMENSION_COUNT:2,DIMENSION_WIDTH:0,DIMENSION_HEIGHT:1,DIRECTION_COUNT:3,DIRECTION_INHERIT:0,DIRECTION_LTR:1,DIRECTION_RTL:2,DISPLAY_COUNT:2,DISPLAY_FLEX:0,DISPLAY_NONE:1,EDGE_COUNT:9,EDGE_LEFT:0,EDGE_TOP:1,EDGE_RIGHT:2,EDGE_BOTTOM:3,EDGE_START:4,EDGE_END:5,EDGE_HORIZONTAL:6,EDGE_VERTICAL:7,EDGE_ALL:8,EXPERIMENTAL_FEATURE_COUNT:1,EXPERIMENTAL_FEATURE_WEB_FLEX_BASIS:0,FLEX_DIRECTION_COUNT:4,FLEX_DIRECTION_COLUMN:0,FLEX_DIRECTION_COLUMN_REVERSE:1,FLEX_DIRECTION_ROW:2,FLEX_DIRECTION_ROW_REVERSE:3,JUSTIFY_COUNT:6,JUSTIFY_FLEX_START:0,JUSTIFY_CENTER:1,JUSTIFY_FLEX_END:2,JUSTIFY_SPACE_BETWEEN:3,JUSTIFY_SPACE_AROUND:4,JUSTIFY_SPACE_EVENLY:5,LOG_LEVEL_COUNT:6,LOG_LEVEL_ERROR:0,LOG_LEVEL_WARN:1,LOG_LEVEL_INFO:2,LOG_LEVEL_DEBUG:3,LOG_LEVEL_VERBOSE:4,LOG_LEVEL_FATAL:5,MEASURE_MODE_COUNT:3,MEASURE_MODE_UNDEFINED:0,MEASURE_MODE_EXACTLY:1,MEASURE_MODE_AT_MOST:2,NODE_TYPE_COUNT:2,NODE_TYPE_DEFAULT:0,NODE_TYPE_TEXT:1,OVERFLOW_COUNT:3,OVERFLOW_VISIBLE:0,OVERFLOW_HIDDEN:1,OVERFLOW_SCROLL:2,POSITION_TYPE_COUNT:2,POSITION_TYPE_RELATIVE:0,POSITION_TYPE_ABSOLUTE:1,PRINT_OPTIONS_COUNT:3,PRINT_OPTIONS_LAYOUT:1,PRINT_OPTIONS_STYLE:2,PRINT_OPTIONS_CHILDREN:4,UNIT_COUNT:4,UNIT_UNDEFINED:0,UNIT_POINT:1,UNIT_PERCENT:2,UNIT_AUTO:3,WRAP_COUNT:3,WRAP_NO_WRAP:0,WRAP_WRAP:1,WRAP_WRAP_REVERSE:2};REe.exports=Kyt});var OEe=_((DKt,MEe)=>{\"use strict\";var Vyt=Object.assign||function(t){for(var e=1;e<arguments.length;e++){var r=arguments[e];for(var o in r)Object.prototype.hasOwnProperty.call(r,o)&&(t[o]=r[o])}return t},Nk=function(){function t(e,r){for(var o=0;o<r.length;o++){var a=r[o];a.enumerable=a.enumerable||!1,a.configurable=!0,\"value\"in a&&(a.writable=!0),Object.defineProperty(e,a.key,a)}}return function(e,r,o){return r&&t(e.prototype,r),o&&t(e,o),e}}();function I6(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function B6(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}var nu=TEe(),zyt=function(){function t(e,r,o,a,n,u){B6(this,t),this.left=e,this.right=r,this.top=o,this.bottom=a,this.width=n,this.height=u}return Nk(t,[{key:\"fromJS\",value:function(r){r(this.left,this.right,this.top,this.bottom,this.width,this.height)}},{key:\"toString\",value:function(){return\"<Layout#\"+this.left+\":\"+this.right+\";\"+this.top+\":\"+this.bottom+\";\"+this.width+\":\"+this.height+\">\"}}]),t}(),NEe=function(){Nk(t,null,[{key:\"fromJS\",value:function(r){var o=r.width,a=r.height;return new t(o,a)}}]);function t(e,r){B6(this,t),this.width=e,this.height=r}return Nk(t,[{key:\"fromJS\",value:function(r){r(this.width,this.height)}},{key:\"toString\",value:function(){return\"<Size#\"+this.width+\"x\"+this.height+\">\"}}]),t}(),LEe=function(){function t(e,r){B6(this,t),this.unit=e,this.value=r}return Nk(t,[{key:\"fromJS\",value:function(r){r(this.unit,this.value)}},{key:\"toString\",value:function(){switch(this.unit){case nu.UNIT_POINT:return String(this.value);case nu.UNIT_PERCENT:return this.value+\"%\";case nu.UNIT_AUTO:return\"auto\";default:return this.value+\"?\"}}},{key:\"valueOf\",value:function(){return this.value}}]),t}();MEe.exports=function(t,e){function r(u,A,p){var h=u[A];u[A]=function(){for(var E=arguments.length,I=Array(E),v=0;v<E;v++)I[v]=arguments[v];return p.call.apply(p,[this,h].concat(I))}}for(var o=[\"setPosition\",\"setMargin\",\"setFlexBasis\",\"setWidth\",\"setHeight\",\"setMinWidth\",\"setMinHeight\",\"setMaxWidth\",\"setMaxHeight\",\"setPadding\"],a=function(){var A,p=o[n],h=(A={},I6(A,nu.UNIT_POINT,e.Node.prototype[p]),I6(A,nu.UNIT_PERCENT,e.Node.prototype[p+\"Percent\"]),I6(A,nu.UNIT_AUTO,e.Node.prototype[p+\"Auto\"]),A);r(e.Node.prototype,p,function(E){for(var I=arguments.length,v=Array(I>1?I-1:0),x=1;x<I;x++)v[x-1]=arguments[x];var C=v.pop(),R=void 0,L=void 0;if(C===\"auto\")R=nu.UNIT_AUTO,L=void 0;else if(C instanceof LEe)R=C.unit,L=C.valueOf();else if(R=typeof C==\"string\"&&C.endsWith(\"%\")?nu.UNIT_PERCENT:nu.UNIT_POINT,L=parseFloat(C),!Number.isNaN(C)&&Number.isNaN(L))throw new Error(\"Invalid value \"+C+\" for \"+p);if(!h[R])throw new Error('Failed to execute \"'+p+`\": Unsupported unit '`+C+\"'\");if(L!==void 0){var U;return(U=h[R]).call.apply(U,[this].concat(v,[L]))}else{var z;return(z=h[R]).call.apply(z,[this].concat(v))}})},n=0;n<o.length;n++)a();return r(e.Config.prototype,\"free\",function(){e.Config.destroy(this)}),r(e.Node,\"create\",function(u,A){return A?e.Node.createWithConfig(A):e.Node.createDefault()}),r(e.Node.prototype,\"free\",function(){e.Node.destroy(this)}),r(e.Node.prototype,\"freeRecursive\",function(){for(var u=0,A=this.getChildCount();u<A;++u)this.getChild(0).freeRecursive();this.free()}),r(e.Node.prototype,\"setMeasureFunc\",function(u,A){return A?u.call(this,function(){return NEe.fromJS(A.apply(void 0,arguments))}):this.unsetMeasureFunc()}),r(e.Node.prototype,\"calculateLayout\",function(u){var A=arguments.length>1&&arguments[1]!==void 0?arguments[1]:NaN,p=arguments.length>2&&arguments[2]!==void 0?arguments[2]:NaN,h=arguments.length>3&&arguments[3]!==void 0?arguments[3]:nu.DIRECTION_LTR;return u.call(this,A,p,h)}),Vyt({Config:e.Config,Node:e.Node,Layout:t(\"Layout\",zyt),Size:t(\"Size\",NEe),Value:t(\"Value\",LEe),getInstanceCount:function(){return e.getInstanceCount.apply(e,arguments)}},nu)}});var UEe=_((exports,module)=>{(function(t,e){typeof define==\"function\"&&define.amd?define([],function(){return e}):typeof module==\"object\"&&module.exports?module.exports=e:(t.nbind=t.nbind||{}).init=e})(exports,function(Module,cb){typeof Module==\"function\"&&(cb=Module,Module={}),Module.onRuntimeInitialized=function(t,e){return function(){t&&t.apply(this,arguments);try{Module.ccall(\"nbind_init\")}catch(r){e(r);return}e(null,{bind:Module._nbind_value,reflect:Module.NBind.reflect,queryType:Module.NBind.queryType,toggleLightGC:Module.toggleLightGC,lib:Module})}}(Module.onRuntimeInitialized,cb);var Module;Module||(Module=(typeof Module<\"u\"?Module:null)||{});var moduleOverrides={};for(var key in Module)Module.hasOwnProperty(key)&&(moduleOverrides[key]=Module[key]);var ENVIRONMENT_IS_WEB=!1,ENVIRONMENT_IS_WORKER=!1,ENVIRONMENT_IS_NODE=!1,ENVIRONMENT_IS_SHELL=!1;if(Module.ENVIRONMENT)if(Module.ENVIRONMENT===\"WEB\")ENVIRONMENT_IS_WEB=!0;else if(Module.ENVIRONMENT===\"WORKER\")ENVIRONMENT_IS_WORKER=!0;else if(Module.ENVIRONMENT===\"NODE\")ENVIRONMENT_IS_NODE=!0;else if(Module.ENVIRONMENT===\"SHELL\")ENVIRONMENT_IS_SHELL=!0;else throw new Error(\"The provided Module['ENVIRONMENT'] value is not valid. It must be one of: WEB|WORKER|NODE|SHELL.\");else ENVIRONMENT_IS_WEB=typeof window==\"object\",ENVIRONMENT_IS_WORKER=typeof importScripts==\"function\",ENVIRONMENT_IS_NODE=typeof process==\"object\"&&typeof ve==\"function\"&&!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_WORKER,ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){Module.print||(Module.print=console.log),Module.printErr||(Module.printErr=console.warn);var nodeFS,nodePath;Module.read=function(e,r){nodeFS||(nodeFS={}(\"\")),nodePath||(nodePath={}(\"\")),e=nodePath.normalize(e);var o=nodeFS.readFileSync(e);return r?o:o.toString()},Module.readBinary=function(e){var r=Module.read(e,!0);return r.buffer||(r=new Uint8Array(r)),assert(r.buffer),r},Module.load=function(e){globalEval(read(e))},Module.thisProgram||(process.argv.length>1?Module.thisProgram=process.argv[1].replace(/\\\\/g,\"/\"):Module.thisProgram=\"unknown-program\"),Module.arguments=process.argv.slice(2),typeof module<\"u\"&&(module.exports=Module),Module.inspect=function(){return\"[Emscripten Module object]\"}}else if(ENVIRONMENT_IS_SHELL)Module.print||(Module.print=print),typeof printErr<\"u\"&&(Module.printErr=printErr),typeof read<\"u\"?Module.read=read:Module.read=function(){throw\"no read() available\"},Module.readBinary=function(e){if(typeof readbuffer==\"function\")return new Uint8Array(readbuffer(e));var r=read(e,\"binary\");return assert(typeof r==\"object\"),r},typeof scriptArgs<\"u\"?Module.arguments=scriptArgs:typeof arguments<\"u\"&&(Module.arguments=arguments),typeof quit==\"function\"&&(Module.quit=function(t,e){quit(t)});else if(ENVIRONMENT_IS_WEB||ENVIRONMENT_IS_WORKER){if(Module.read=function(e){var r=new XMLHttpRequest;return r.open(\"GET\",e,!1),r.send(null),r.responseText},ENVIRONMENT_IS_WORKER&&(Module.readBinary=function(e){var r=new XMLHttpRequest;return r.open(\"GET\",e,!1),r.responseType=\"arraybuffer\",r.send(null),new Uint8Array(r.response)}),Module.readAsync=function(e,r,o){var a=new XMLHttpRequest;a.open(\"GET\",e,!0),a.responseType=\"arraybuffer\",a.onload=function(){a.status==200||a.status==0&&a.response?r(a.response):o()},a.onerror=o,a.send(null)},typeof arguments<\"u\"&&(Module.arguments=arguments),typeof console<\"u\")Module.print||(Module.print=function(e){console.log(e)}),Module.printErr||(Module.printErr=function(e){console.warn(e)});else{var TRY_USE_DUMP=!1;Module.print||(Module.print=TRY_USE_DUMP&&typeof dump<\"u\"?function(t){dump(t)}:function(t){})}ENVIRONMENT_IS_WORKER&&(Module.load=importScripts),typeof Module.setWindowTitle>\"u\"&&(Module.setWindowTitle=function(t){document.title=t})}else throw\"Unknown runtime environment. Where are we?\";function globalEval(t){eval.call(null,t)}!Module.load&&Module.read&&(Module.load=function(e){globalEval(Module.read(e))}),Module.print||(Module.print=function(){}),Module.printErr||(Module.printErr=Module.print),Module.arguments||(Module.arguments=[]),Module.thisProgram||(Module.thisProgram=\"./this.program\"),Module.quit||(Module.quit=function(t,e){throw e}),Module.print=Module.print,Module.printErr=Module.printErr,Module.preRun=[],Module.postRun=[];for(var key in moduleOverrides)moduleOverrides.hasOwnProperty(key)&&(Module[key]=moduleOverrides[key]);moduleOverrides=void 0;var Runtime={setTempRet0:function(t){return tempRet0=t,t},getTempRet0:function(){return tempRet0},stackSave:function(){return STACKTOP},stackRestore:function(t){STACKTOP=t},getNativeTypeSize:function(t){switch(t){case\"i1\":case\"i8\":return 1;case\"i16\":return 2;case\"i32\":return 4;case\"i64\":return 8;case\"float\":return 4;case\"double\":return 8;default:{if(t[t.length-1]===\"*\")return Runtime.QUANTUM_SIZE;if(t[0]===\"i\"){var e=parseInt(t.substr(1));return assert(e%8===0),e/8}else return 0}}},getNativeFieldSize:function(t){return Math.max(Runtime.getNativeTypeSize(t),Runtime.QUANTUM_SIZE)},STACK_ALIGN:16,prepVararg:function(t,e){return e===\"double\"||e===\"i64\"?t&7&&(assert((t&7)===4),t+=4):assert((t&3)===0),t},getAlignSize:function(t,e,r){return!r&&(t==\"i64\"||t==\"double\")?8:t?Math.min(e||(t?Runtime.getNativeFieldSize(t):0),Runtime.QUANTUM_SIZE):Math.min(e,8)},dynCall:function(t,e,r){return r&&r.length?Module[\"dynCall_\"+t].apply(null,[e].concat(r)):Module[\"dynCall_\"+t].call(null,e)},functionPointers:[],addFunction:function(t){for(var e=0;e<Runtime.functionPointers.length;e++)if(!Runtime.functionPointers[e])return Runtime.functionPointers[e]=t,2*(1+e);throw\"Finished up all reserved function pointers. Use a higher value for RESERVED_FUNCTION_POINTERS.\"},removeFunction:function(t){Runtime.functionPointers[(t-2)/2]=null},warnOnce:function(t){Runtime.warnOnce.shown||(Runtime.warnOnce.shown={}),Runtime.warnOnce.shown[t]||(Runtime.warnOnce.shown[t]=1,Module.printErr(t))},funcWrappers:{},getFuncWrapper:function(t,e){if(t){assert(e),Runtime.funcWrappers[e]||(Runtime.funcWrappers[e]={});var r=Runtime.funcWrappers[e];return r[t]||(e.length===1?r[t]=function(){return Runtime.dynCall(e,t)}:e.length===2?r[t]=function(a){return Runtime.dynCall(e,t,[a])}:r[t]=function(){return Runtime.dynCall(e,t,Array.prototype.slice.call(arguments))}),r[t]}},getCompilerSetting:function(t){throw\"You must build with -s RETAIN_COMPILER_SETTINGS=1 for Runtime.getCompilerSetting or emscripten_get_compiler_setting to work\"},stackAlloc:function(t){var e=STACKTOP;return STACKTOP=STACKTOP+t|0,STACKTOP=STACKTOP+15&-16,e},staticAlloc:function(t){var e=STATICTOP;return STATICTOP=STATICTOP+t|0,STATICTOP=STATICTOP+15&-16,e},dynamicAlloc:function(t){var e=HEAP32[DYNAMICTOP_PTR>>2],r=(e+t+15|0)&-16;if(HEAP32[DYNAMICTOP_PTR>>2]=r,r>=TOTAL_MEMORY){var o=enlargeMemory();if(!o)return HEAP32[DYNAMICTOP_PTR>>2]=e,0}return e},alignMemory:function(t,e){var r=t=Math.ceil(t/(e||16))*(e||16);return r},makeBigInt:function(t,e,r){var o=r?+(t>>>0)+ +(e>>>0)*4294967296:+(t>>>0)+ +(e|0)*4294967296;return o},GLOBAL_BASE:8,QUANTUM_SIZE:4,__dummy__:0};Module.Runtime=Runtime;var ABORT=0,EXITSTATUS=0;function assert(t,e){t||abort(\"Assertion failed: \"+e)}function getCFunc(ident){var func=Module[\"_\"+ident];if(!func)try{func=eval(\"_\"+ident)}catch(t){}return assert(func,\"Cannot call unknown function \"+ident+\" (perhaps LLVM optimizations or closure removed it?)\"),func}var cwrap,ccall;(function(){var JSfuncs={stackSave:function(){Runtime.stackSave()},stackRestore:function(){Runtime.stackRestore()},arrayToC:function(t){var e=Runtime.stackAlloc(t.length);return writeArrayToMemory(t,e),e},stringToC:function(t){var e=0;if(t!=null&&t!==0){var r=(t.length<<2)+1;e=Runtime.stackAlloc(r),stringToUTF8(t,e,r)}return e}},toC={string:JSfuncs.stringToC,array:JSfuncs.arrayToC};ccall=function(e,r,o,a,n){var u=getCFunc(e),A=[],p=0;if(a)for(var h=0;h<a.length;h++){var E=toC[o[h]];E?(p===0&&(p=Runtime.stackSave()),A[h]=E(a[h])):A[h]=a[h]}var I=u.apply(null,A);if(r===\"string\"&&(I=Pointer_stringify(I)),p!==0){if(n&&n.async){EmterpreterAsync.asyncFinalizers.push(function(){Runtime.stackRestore(p)});return}Runtime.stackRestore(p)}return I};var sourceRegex=/^function\\s*[a-zA-Z$_0-9]*\\s*\\(([^)]*)\\)\\s*{\\s*([^*]*?)[\\s;]*(?:return\\s*(.*?)[;\\s]*)?}$/;function parseJSFunc(t){var e=t.toString().match(sourceRegex).slice(1);return{arguments:e[0],body:e[1],returnValue:e[2]}}var JSsource=null;function ensureJSsource(){if(!JSsource){JSsource={};for(var t in JSfuncs)JSfuncs.hasOwnProperty(t)&&(JSsource[t]=parseJSFunc(JSfuncs[t]))}}cwrap=function cwrap(ident,returnType,argTypes){argTypes=argTypes||[];var cfunc=getCFunc(ident),numericArgs=argTypes.every(function(t){return t===\"number\"}),numericRet=returnType!==\"string\";if(numericRet&&numericArgs)return cfunc;var argNames=argTypes.map(function(t,e){return\"$\"+e}),funcstr=\"(function(\"+argNames.join(\",\")+\") {\",nargs=argTypes.length;if(!numericArgs){ensureJSsource(),funcstr+=\"var stack = \"+JSsource.stackSave.body+\";\";for(var i=0;i<nargs;i++){var arg=argNames[i],type=argTypes[i];if(type!==\"number\"){var convertCode=JSsource[type+\"ToC\"];funcstr+=\"var \"+convertCode.arguments+\" = \"+arg+\";\",funcstr+=convertCode.body+\";\",funcstr+=arg+\"=(\"+convertCode.returnValue+\");\"}}}var cfuncname=parseJSFunc(function(){return cfunc}).returnValue;if(funcstr+=\"var ret = \"+cfuncname+\"(\"+argNames.join(\",\")+\");\",!numericRet){var strgfy=parseJSFunc(function(){return Pointer_stringify}).returnValue;funcstr+=\"ret = \"+strgfy+\"(ret);\"}return numericArgs||(ensureJSsource(),funcstr+=JSsource.stackRestore.body.replace(\"()\",\"(stack)\")+\";\"),funcstr+=\"return ret})\",eval(funcstr)}})(),Module.ccall=ccall,Module.cwrap=cwrap;function setValue(t,e,r,o){switch(r=r||\"i8\",r.charAt(r.length-1)===\"*\"&&(r=\"i32\"),r){case\"i1\":HEAP8[t>>0]=e;break;case\"i8\":HEAP8[t>>0]=e;break;case\"i16\":HEAP16[t>>1]=e;break;case\"i32\":HEAP32[t>>2]=e;break;case\"i64\":tempI64=[e>>>0,(tempDouble=e,+Math_abs(tempDouble)>=1?tempDouble>0?(Math_min(+Math_floor(tempDouble/4294967296),4294967295)|0)>>>0:~~+Math_ceil((tempDouble-+(~~tempDouble>>>0))/4294967296)>>>0:0)],HEAP32[t>>2]=tempI64[0],HEAP32[t+4>>2]=tempI64[1];break;case\"float\":HEAPF32[t>>2]=e;break;case\"double\":HEAPF64[t>>3]=e;break;default:abort(\"invalid type for setValue: \"+r)}}Module.setValue=setValue;function getValue(t,e,r){switch(e=e||\"i8\",e.charAt(e.length-1)===\"*\"&&(e=\"i32\"),e){case\"i1\":return HEAP8[t>>0];case\"i8\":return HEAP8[t>>0];case\"i16\":return HEAP16[t>>1];case\"i32\":return HEAP32[t>>2];case\"i64\":return HEAP32[t>>2];case\"float\":return HEAPF32[t>>2];case\"double\":return HEAPF64[t>>3];default:abort(\"invalid type for setValue: \"+e)}return null}Module.getValue=getValue;var ALLOC_NORMAL=0,ALLOC_STACK=1,ALLOC_STATIC=2,ALLOC_DYNAMIC=3,ALLOC_NONE=4;Module.ALLOC_NORMAL=ALLOC_NORMAL,Module.ALLOC_STACK=ALLOC_STACK,Module.ALLOC_STATIC=ALLOC_STATIC,Module.ALLOC_DYNAMIC=ALLOC_DYNAMIC,Module.ALLOC_NONE=ALLOC_NONE;function allocate(t,e,r,o){var a,n;typeof t==\"number\"?(a=!0,n=t):(a=!1,n=t.length);var u=typeof e==\"string\"?e:null,A;if(r==ALLOC_NONE?A=o:A=[typeof _malloc==\"function\"?_malloc:Runtime.staticAlloc,Runtime.stackAlloc,Runtime.staticAlloc,Runtime.dynamicAlloc][r===void 0?ALLOC_STATIC:r](Math.max(n,u?1:e.length)),a){var o=A,p;for(assert((A&3)==0),p=A+(n&-4);o<p;o+=4)HEAP32[o>>2]=0;for(p=A+n;o<p;)HEAP8[o++>>0]=0;return A}if(u===\"i8\")return t.subarray||t.slice?HEAPU8.set(t,A):HEAPU8.set(new Uint8Array(t),A),A;for(var h=0,E,I,v;h<n;){var x=t[h];if(typeof x==\"function\"&&(x=Runtime.getFunctionIndex(x)),E=u||e[h],E===0){h++;continue}E==\"i64\"&&(E=\"i32\"),setValue(A+h,x,E),v!==E&&(I=Runtime.getNativeTypeSize(E),v=E),h+=I}return A}Module.allocate=allocate;function getMemory(t){return staticSealed?runtimeInitialized?_malloc(t):Runtime.dynamicAlloc(t):Runtime.staticAlloc(t)}Module.getMemory=getMemory;function Pointer_stringify(t,e){if(e===0||!t)return\"\";for(var r=0,o,a=0;o=HEAPU8[t+a>>0],r|=o,!(o==0&&!e||(a++,e&&a==e)););e||(e=a);var n=\"\";if(r<128){for(var u=1024,A;e>0;)A=String.fromCharCode.apply(String,HEAPU8.subarray(t,t+Math.min(e,u))),n=n?n+A:A,t+=u,e-=u;return n}return Module.UTF8ToString(t)}Module.Pointer_stringify=Pointer_stringify;function AsciiToString(t){for(var e=\"\";;){var r=HEAP8[t++>>0];if(!r)return e;e+=String.fromCharCode(r)}}Module.AsciiToString=AsciiToString;function stringToAscii(t,e){return writeAsciiToMemory(t,e,!1)}Module.stringToAscii=stringToAscii;var UTF8Decoder=typeof TextDecoder<\"u\"?new TextDecoder(\"utf8\"):void 0;function UTF8ArrayToString(t,e){for(var r=e;t[r];)++r;if(r-e>16&&t.subarray&&UTF8Decoder)return UTF8Decoder.decode(t.subarray(e,r));for(var o,a,n,u,A,p,h=\"\";;){if(o=t[e++],!o)return h;if(!(o&128)){h+=String.fromCharCode(o);continue}if(a=t[e++]&63,(o&224)==192){h+=String.fromCharCode((o&31)<<6|a);continue}if(n=t[e++]&63,(o&240)==224?o=(o&15)<<12|a<<6|n:(u=t[e++]&63,(o&248)==240?o=(o&7)<<18|a<<12|n<<6|u:(A=t[e++]&63,(o&252)==248?o=(o&3)<<24|a<<18|n<<12|u<<6|A:(p=t[e++]&63,o=(o&1)<<30|a<<24|n<<18|u<<12|A<<6|p))),o<65536)h+=String.fromCharCode(o);else{var E=o-65536;h+=String.fromCharCode(55296|E>>10,56320|E&1023)}}}Module.UTF8ArrayToString=UTF8ArrayToString;function UTF8ToString(t){return UTF8ArrayToString(HEAPU8,t)}Module.UTF8ToString=UTF8ToString;function stringToUTF8Array(t,e,r,o){if(!(o>0))return 0;for(var a=r,n=r+o-1,u=0;u<t.length;++u){var A=t.charCodeAt(u);if(A>=55296&&A<=57343&&(A=65536+((A&1023)<<10)|t.charCodeAt(++u)&1023),A<=127){if(r>=n)break;e[r++]=A}else if(A<=2047){if(r+1>=n)break;e[r++]=192|A>>6,e[r++]=128|A&63}else if(A<=65535){if(r+2>=n)break;e[r++]=224|A>>12,e[r++]=128|A>>6&63,e[r++]=128|A&63}else if(A<=2097151){if(r+3>=n)break;e[r++]=240|A>>18,e[r++]=128|A>>12&63,e[r++]=128|A>>6&63,e[r++]=128|A&63}else if(A<=67108863){if(r+4>=n)break;e[r++]=248|A>>24,e[r++]=128|A>>18&63,e[r++]=128|A>>12&63,e[r++]=128|A>>6&63,e[r++]=128|A&63}else{if(r+5>=n)break;e[r++]=252|A>>30,e[r++]=128|A>>24&63,e[r++]=128|A>>18&63,e[r++]=128|A>>12&63,e[r++]=128|A>>6&63,e[r++]=128|A&63}}return e[r]=0,r-a}Module.stringToUTF8Array=stringToUTF8Array;function stringToUTF8(t,e,r){return stringToUTF8Array(t,HEAPU8,e,r)}Module.stringToUTF8=stringToUTF8;function lengthBytesUTF8(t){for(var e=0,r=0;r<t.length;++r){var o=t.charCodeAt(r);o>=55296&&o<=57343&&(o=65536+((o&1023)<<10)|t.charCodeAt(++r)&1023),o<=127?++e:o<=2047?e+=2:o<=65535?e+=3:o<=2097151?e+=4:o<=67108863?e+=5:e+=6}return e}Module.lengthBytesUTF8=lengthBytesUTF8;var UTF16Decoder=typeof TextDecoder<\"u\"?new TextDecoder(\"utf-16le\"):void 0;function demangle(t){var e=Module.___cxa_demangle||Module.__cxa_demangle;if(e){try{var r=t.substr(1),o=lengthBytesUTF8(r)+1,a=_malloc(o);stringToUTF8(r,a,o);var n=_malloc(4),u=e(a,0,0,n);if(getValue(n,\"i32\")===0&&u)return Pointer_stringify(u)}catch{}finally{a&&_free(a),n&&_free(n),u&&_free(u)}return t}return Runtime.warnOnce(\"warning: build with  -s DEMANGLE_SUPPORT=1  to link in libcxxabi demangling\"),t}function demangleAll(t){var e=/__Z[\\w\\d_]+/g;return t.replace(e,function(r){var o=demangle(r);return r===o?r:r+\" [\"+o+\"]\"})}function jsStackTrace(){var t=new Error;if(!t.stack){try{throw new Error(0)}catch(e){t=e}if(!t.stack)return\"(no stack trace available)\"}return t.stack.toString()}function stackTrace(){var t=jsStackTrace();return Module.extraStackTrace&&(t+=`\n`+Module.extraStackTrace()),demangleAll(t)}Module.stackTrace=stackTrace;var HEAP,buffer,HEAP8,HEAPU8,HEAP16,HEAPU16,HEAP32,HEAPU32,HEAPF32,HEAPF64;function updateGlobalBufferViews(){Module.HEAP8=HEAP8=new Int8Array(buffer),Module.HEAP16=HEAP16=new Int16Array(buffer),Module.HEAP32=HEAP32=new Int32Array(buffer),Module.HEAPU8=HEAPU8=new Uint8Array(buffer),Module.HEAPU16=HEAPU16=new Uint16Array(buffer),Module.HEAPU32=HEAPU32=new Uint32Array(buffer),Module.HEAPF32=HEAPF32=new Float32Array(buffer),Module.HEAPF64=HEAPF64=new Float64Array(buffer)}var STATIC_BASE,STATICTOP,staticSealed,STACK_BASE,STACKTOP,STACK_MAX,DYNAMIC_BASE,DYNAMICTOP_PTR;STATIC_BASE=STATICTOP=STACK_BASE=STACKTOP=STACK_MAX=DYNAMIC_BASE=DYNAMICTOP_PTR=0,staticSealed=!1;function abortOnCannotGrowMemory(){abort(\"Cannot enlarge memory arrays. Either (1) compile with  -s TOTAL_MEMORY=X  with X higher than the current value \"+TOTAL_MEMORY+\", (2) compile with  -s ALLOW_MEMORY_GROWTH=1  which allows increasing the size at runtime but prevents some optimizations, (3) set Module.TOTAL_MEMORY to a higher value before the program runs, or (4) if you want malloc to return NULL (0) instead of this abort, compile with  -s ABORTING_MALLOC=0 \")}function enlargeMemory(){abortOnCannotGrowMemory()}var TOTAL_STACK=Module.TOTAL_STACK||5242880,TOTAL_MEMORY=Module.TOTAL_MEMORY||134217728;TOTAL_MEMORY<TOTAL_STACK&&Module.printErr(\"TOTAL_MEMORY should be larger than TOTAL_STACK, was \"+TOTAL_MEMORY+\"! (TOTAL_STACK=\"+TOTAL_STACK+\")\"),Module.buffer?buffer=Module.buffer:buffer=new ArrayBuffer(TOTAL_MEMORY),updateGlobalBufferViews();function getTotalMemory(){return TOTAL_MEMORY}if(HEAP32[0]=1668509029,HEAP16[1]=25459,HEAPU8[2]!==115||HEAPU8[3]!==99)throw\"Runtime error: expected the system to be little-endian!\";Module.HEAP=HEAP,Module.buffer=buffer,Module.HEAP8=HEAP8,Module.HEAP16=HEAP16,Module.HEAP32=HEAP32,Module.HEAPU8=HEAPU8,Module.HEAPU16=HEAPU16,Module.HEAPU32=HEAPU32,Module.HEAPF32=HEAPF32,Module.HEAPF64=HEAPF64;function callRuntimeCallbacks(t){for(;t.length>0;){var e=t.shift();if(typeof e==\"function\"){e();continue}var r=e.func;typeof r==\"number\"?e.arg===void 0?Module.dynCall_v(r):Module.dynCall_vi(r,e.arg):r(e.arg===void 0?null:e.arg)}}var __ATPRERUN__=[],__ATINIT__=[],__ATMAIN__=[],__ATEXIT__=[],__ATPOSTRUN__=[],runtimeInitialized=!1,runtimeExited=!1;function preRun(){if(Module.preRun)for(typeof Module.preRun==\"function\"&&(Module.preRun=[Module.preRun]);Module.preRun.length;)addOnPreRun(Module.preRun.shift());callRuntimeCallbacks(__ATPRERUN__)}function ensureInitRuntime(){runtimeInitialized||(runtimeInitialized=!0,callRuntimeCallbacks(__ATINIT__))}function preMain(){callRuntimeCallbacks(__ATMAIN__)}function exitRuntime(){callRuntimeCallbacks(__ATEXIT__),runtimeExited=!0}function postRun(){if(Module.postRun)for(typeof Module.postRun==\"function\"&&(Module.postRun=[Module.postRun]);Module.postRun.length;)addOnPostRun(Module.postRun.shift());callRuntimeCallbacks(__ATPOSTRUN__)}function addOnPreRun(t){__ATPRERUN__.unshift(t)}Module.addOnPreRun=addOnPreRun;function addOnInit(t){__ATINIT__.unshift(t)}Module.addOnInit=addOnInit;function addOnPreMain(t){__ATMAIN__.unshift(t)}Module.addOnPreMain=addOnPreMain;function addOnExit(t){__ATEXIT__.unshift(t)}Module.addOnExit=addOnExit;function addOnPostRun(t){__ATPOSTRUN__.unshift(t)}Module.addOnPostRun=addOnPostRun;function intArrayFromString(t,e,r){var o=r>0?r:lengthBytesUTF8(t)+1,a=new Array(o),n=stringToUTF8Array(t,a,0,a.length);return e&&(a.length=n),a}Module.intArrayFromString=intArrayFromString;function intArrayToString(t){for(var e=[],r=0;r<t.length;r++){var o=t[r];o>255&&(o&=255),e.push(String.fromCharCode(o))}return e.join(\"\")}Module.intArrayToString=intArrayToString;function writeStringToMemory(t,e,r){Runtime.warnOnce(\"writeStringToMemory is deprecated and should not be called! Use stringToUTF8() instead!\");var o,a;r&&(a=e+lengthBytesUTF8(t),o=HEAP8[a]),stringToUTF8(t,e,1/0),r&&(HEAP8[a]=o)}Module.writeStringToMemory=writeStringToMemory;function writeArrayToMemory(t,e){HEAP8.set(t,e)}Module.writeArrayToMemory=writeArrayToMemory;function writeAsciiToMemory(t,e,r){for(var o=0;o<t.length;++o)HEAP8[e++>>0]=t.charCodeAt(o);r||(HEAP8[e>>0]=0)}if(Module.writeAsciiToMemory=writeAsciiToMemory,(!Math.imul||Math.imul(4294967295,5)!==-5)&&(Math.imul=function t(e,r){var o=e>>>16,a=e&65535,n=r>>>16,u=r&65535;return a*u+(o*u+a*n<<16)|0}),Math.imul=Math.imul,!Math.fround){var froundBuffer=new Float32Array(1);Math.fround=function(t){return froundBuffer[0]=t,froundBuffer[0]}}Math.fround=Math.fround,Math.clz32||(Math.clz32=function(t){t=t>>>0;for(var e=0;e<32;e++)if(t&1<<31-e)return e;return 32}),Math.clz32=Math.clz32,Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)}),Math.trunc=Math.trunc;var Math_abs=Math.abs,Math_cos=Math.cos,Math_sin=Math.sin,Math_tan=Math.tan,Math_acos=Math.acos,Math_asin=Math.asin,Math_atan=Math.atan,Math_atan2=Math.atan2,Math_exp=Math.exp,Math_log=Math.log,Math_sqrt=Math.sqrt,Math_ceil=Math.ceil,Math_floor=Math.floor,Math_pow=Math.pow,Math_imul=Math.imul,Math_fround=Math.fround,Math_round=Math.round,Math_min=Math.min,Math_clz32=Math.clz32,Math_trunc=Math.trunc,runDependencies=0,runDependencyWatcher=null,dependenciesFulfilled=null;function getUniqueRunDependency(t){return t}function addRunDependency(t){runDependencies++,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies)}Module.addRunDependency=addRunDependency;function removeRunDependency(t){if(runDependencies--,Module.monitorRunDependencies&&Module.monitorRunDependencies(runDependencies),runDependencies==0&&(runDependencyWatcher!==null&&(clearInterval(runDependencyWatcher),runDependencyWatcher=null),dependenciesFulfilled)){var e=dependenciesFulfilled;dependenciesFulfilled=null,e()}}Module.removeRunDependency=removeRunDependency,Module.preloadedImages={},Module.preloadedAudios={};var ASM_CONSTS=[function(t,e,r,o,a,n,u,A){return _nbind.callbackSignatureList[t].apply(this,arguments)}];function _emscripten_asm_const_iiiiiiii(t,e,r,o,a,n,u,A){return ASM_CONSTS[t](e,r,o,a,n,u,A)}function _emscripten_asm_const_iiiii(t,e,r,o,a){return ASM_CONSTS[t](e,r,o,a)}function _emscripten_asm_const_iiidddddd(t,e,r,o,a,n,u,A,p){return ASM_CONSTS[t](e,r,o,a,n,u,A,p)}function _emscripten_asm_const_iiididi(t,e,r,o,a,n,u){return ASM_CONSTS[t](e,r,o,a,n,u)}function _emscripten_asm_const_iiii(t,e,r,o){return ASM_CONSTS[t](e,r,o)}function _emscripten_asm_const_iiiid(t,e,r,o,a){return ASM_CONSTS[t](e,r,o,a)}function _emscripten_asm_const_iiiiii(t,e,r,o,a,n){return ASM_CONSTS[t](e,r,o,a,n)}STATIC_BASE=Runtime.GLOBAL_BASE,STATICTOP=STATIC_BASE+12800,__ATINIT__.push({func:function(){__GLOBAL__sub_I_Yoga_cpp()}},{func:function(){__GLOBAL__sub_I_nbind_cc()}},{func:function(){__GLOBAL__sub_I_common_cc()}},{func:function(){__GLOBAL__sub_I_Binding_cc()}}),allocate([0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,192,127,0,0,192,127,0,0,192,127,0,0,192,127,3,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,3,0,0,0,0,0,192,127,3,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,192,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,192,127,0,0,192,127,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,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1,0,0,0,2,0,0,0,0,0,0,0,190,12,0,0,200,12,0,0,208,12,0,0,216,12,0,0,230,12,0,0,242,12,0,0,1,0,0,0,3,0,0,0,0,0,0,0,2,0,0,0,0,0,192,127,3,0,0,0,180,45,0,0,181,45,0,0,182,45,0,0,181,45,0,0,182,45,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,3,0,0,0,1,0,0,0,4,0,0,0,183,45,0,0,181,45,0,0,181,45,0,0,181,45,0,0,181,45,0,0,181,45,0,0,181,45,0,0,184,45,0,0,185,45,0,0,181,45,0,0,181,45,0,0,182,45,0,0,186,45,0,0,185,45,0,0,148,4,0,0,3,0,0,0,187,45,0,0,164,4,0,0,188,45,0,0,2,0,0,0,189,45,0,0,164,4,0,0,188,45,0,0,185,45,0,0,164,4,0,0,185,45,0,0,164,4,0,0,188,45,0,0,181,45,0,0,182,45,0,0,181,45,0,0,0,0,0,0,0,0,0,0,1,0,0,0,5,0,0,0,6,0,0,0,1,0,0,0,7,0,0,0,183,45,0,0,182,45,0,0,181,45,0,0,190,45,0,0,190,45,0,0,182,45,0,0,182,45,0,0,185,45,0,0,181,45,0,0,185,45,0,0,182,45,0,0,181,45,0,0,185,45,0,0,182,45,0,0,185,45,0,0,48,5,0,0,3,0,0,0,56,5,0,0,1,0,0,0,189,45,0,0,185,45,0,0,164,4,0,0,76,5,0,0,2,0,0,0,191,45,0,0,186,45,0,0,182,45,0,0,185,45,0,0,192,45,0,0,185,45,0,0,182,45,0,0,186,45,0,0,185,45,0,0,76,5,0,0,76,5,0,0,136,5,0,0,182,45,0,0,181,45,0,0,2,0,0,0,190,45,0,0,136,5,0,0,56,19,0,0,156,5,0,0,2,0,0,0,184,45,0,0,0,0,0,0,0,0,0,0,1,0,0,0,8,0,0,0,9,0,0,0,1,0,0,0,10,0,0,0,204,5,0,0,181,45,0,0,181,45,0,0,2,0,0,0,180,45,0,0,204,5,0,0,2,0,0,0,195,45,0,0,236,5,0,0,97,19,0,0,198,45,0,0,211,45,0,0,212,45,0,0,213,45,0,0,214,45,0,0,215,45,0,0,188,45,0,0,182,45,0,0,216,45,0,0,217,45,0,0,218,45,0,0,219,45,0,0,192,45,0,0,181,45,0,0,0,0,0,0,185,45,0,0,110,19,0,0,186,45,0,0,115,19,0,0,221,45,0,0,120,19,0,0,148,4,0,0,132,19,0,0,96,6,0,0,145,19,0,0,222,45,0,0,164,19,0,0,223,45,0,0,173,19,0,0,0,0,0,0,3,0,0,0,104,6,0,0,1,0,0,0,187,45,0,0,0,0,0,0,0,0,0,0,1,0,0,0,11,0,0,0,12,0,0,0,1,0,0,0,13,0,0,0,185,45,0,0,224,45,0,0,164,6,0,0,188,45,0,0,172,6,0,0,180,6,0,0,2,0,0,0,188,6,0,0,7,0,0,0,224,45,0,0,7,0,0,0,164,6,0,0,1,0,0,0,213,45,0,0,185,45,0,0,224,45,0,0,172,6,0,0,185,45,0,0,224,45,0,0,164,6,0,0,185,45,0,0,224,45,0,0,211,45,0,0,211,45,0,0,222,45,0,0,211,45,0,0,224,45,0,0,222,45,0,0,211,45,0,0,224,45,0,0,172,6,0,0,222,45,0,0,211,45,0,0,224,45,0,0,188,45,0,0,222,45,0,0,211,45,0,0,40,7,0,0,188,45,0,0,2,0,0,0,224,45,0,0,185,45,0,0,188,45,0,0,188,45,0,0,188,45,0,0,188,45,0,0,222,45,0,0,224,45,0,0,148,4,0,0,185,45,0,0,148,4,0,0,148,4,0,0,148,4,0,0,148,4,0,0,148,4,0,0,185,45,0,0,164,6,0,0,148,4,0,0,0,0,0,0,0,0,0,0,1,0,0,0,14,0,0,0,15,0,0,0,1,0,0,0,16,0,0,0,148,7,0,0,2,0,0,0,225,45,0,0,183,45,0,0,188,45,0,0,168,7,0,0,5,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,2,0,0,0,234,45,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,148,45,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,28,9,0,0,5,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3,0,0,0,2,0,0,0,242,45,0,0,0,4,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,10,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,67,111,117,108,100,32,110,111,116,32,97,108,108,111,99,97,116,101,32,109,101,109,111,114,121,32,102,111,114,32,110,111,100,101,0,67,97,110,110,111,116,32,114,101,115,101,116,32,97,32,110,111,100,101,32,119,104,105,99,104,32,115,116,105,108,108,32,104,97,115,32,99,104,105,108,100,114,101,110,32,97,116,116,97,99,104,101,100,0,67,97,110,110,111,116,32,114,101,115,101,116,32,97,32,110,111,100,101,32,115,116,105,108,108,32,97,116,116,97,99,104,101,100,32,116,111,32,97,32,112,97,114,101,110,116,0,67,111,117,108,100,32,110,111,116,32,97,108,108,111,99,97,116,101,32,109,101,109,111,114,121,32,102,111,114,32,99,111,110,102,105,103,0,67,97,110,110,111,116,32,115,101,116,32,109,101,97,115,117,114,101,32,102,117,110,99,116,105,111,110,58,32,78,111,100,101,115,32,119,105,116,104,32,109,101,97,115,117,114,101,32,102,117,110,99,116,105,111,110,115,32,99,97,110,110,111,116,32,104,97,118,101,32,99,104,105,108,100,114,101,110,46,0,67,104,105,108,100,32,97,108,114,101,97,100,121,32,104,97,115,32,97,32,112,97,114,101,110,116,44,32,105,116,32,109,117,115,116,32,98,101,32,114,101,109,111,118,101,100,32,102,105,114,115,116,46,0,67,97,110,110,111,116,32,97,100,100,32,99,104,105,108,100,58,32,78,111,100,101,115,32,119,105,116,104,32,109,101,97,115,117,114,101,32,102,117,110,99,116,105,111,110,115,32,99,97,110,110,111,116,32,104,97,118,101,32,99,104,105,108,100,114,101,110,46,0,79,110,108,121,32,108,101,97,102,32,110,111,100,101,115,32,119,105,116,104,32,99,117,115,116,111,109,32,109,101,97,115,117,114,101,32,102,117,110,99,116,105,111,110,115,115,104,111,117,108,100,32,109,97,110,117,97,108,108,121,32,109,97,114,107,32,116,104,101,109,115,101,108,118,101,115,32,97,115,32,100,105,114,116,121,0,67,97,110,110,111,116,32,103,101,116,32,108,97,121,111,117,116,32,112,114,111,112,101,114,116,105,101,115,32,111,102,32,109,117,108,116,105,45,101,100,103,101,32,115,104,111,114,116,104,97,110,100,115,0,37,115,37,100,46,123,91,115,107,105,112,112,101,100,93,32,0,119,109,58,32,37,115,44,32,104,109,58,32,37,115,44,32,97,119,58,32,37,102,32,97,104,58,32,37,102,32,61,62,32,100,58,32,40,37,102,44,32,37,102,41,32,37,115,10,0,37,115,37,100,46,123,37,115,0,42,0,119,109,58,32,37,115,44,32,104,109,58,32,37,115,44,32,97,119,58,32,37,102,32,97,104,58,32,37,102,32,37,115,10,0,37,115,37,100,46,125,37,115,0,119,109,58,32,37,115,44,32,104,109,58,32,37,115,44,32,100,58,32,40,37,102,44,32,37,102,41,32,37,115,10,0,79,117,116,32,111,102,32,99,97,99,104,101,32,101,110,116,114,105,101,115,33,10,0,83,99,97,108,101,32,102,97,99,116,111,114,32,115,104,111,117,108,100,32,110,111,116,32,98,101,32,108,101,115,115,32,116,104,97,110,32,122,101,114,111,0,105,110,105,116,105,97,108,0,37,115,10,0,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,32,0,85,78,68,69,70,73,78,69,68,0,69,88,65,67,84,76,89,0,65,84,95,77,79,83,84,0,76,65,89,95,85,78,68,69,70,73,78,69,68,0,76,65,89,95,69,88,65,67,84,76,89,0,76,65,89,95,65,84,95,77,79,83,84,0,97,118,97,105,108,97,98,108,101,87,105,100,116,104,32,105,115,32,105,110,100,101,102,105,110,105,116,101,32,115,111,32,119,105,100,116,104,77,101,97,115,117,114,101,77,111,100,101,32,109,117,115,116,32,98,101,32,89,71,77,101,97,115,117,114,101,77,111,100,101,85,110,100,101,102,105,110,101,100,0,97,118,97,105,108,97,98,108,101,72,101,105,103,104,116,32,105,115,32,105,110,100,101,102,105,110,105,116,101,32,115,111,32,104,101,105,103,104,116,77,101,97,115,117,114,101,77,111,100,101,32,109,117,115,116,32,98,101,32,89,71,77,101,97,115,117,114,101,77,111,100,101,85,110,100,101,102,105,110,101,100,0,102,108,101,120,0,115,116,114,101,116,99,104,0,109,117,108,116,105,108,105,110,101,45,115,116,114,101,116,99,104,0,69,120,112,101,99,116,101,100,32,110,111,100,101,32,116,111,32,104,97,118,101,32,99,117,115,116,111,109,32,109,101,97,115,117,114,101,32,102,117,110,99,116,105,111,110,0,109,101,97,115,117,114,101,0,69,120,112,101,99,116,32,99,117,115,116,111,109,32,98,97,115,101,108,105,110,101,32,102,117,110,99,116,105,111,110,32,116,111,32,110,111,116,32,114,101,116,117,114,110,32,78,97,78,0,97,98,115,45,109,101,97,115,117,114,101,0,97,98,115,45,108,97,121,111,117,116,0,78,111,100,101,0,99,114,101,97,116,101,68,101,102,97,117,108,116,0,99,114,101,97,116,101,87,105,116,104,67,111,110,102,105,103,0,100,101,115,116,114,111,121,0,114,101,115,101,116,0,99,111,112,121,83,116,121,108,101,0,115,101,116,80,111,115,105,116,105,111,110,84,121,112,101,0,115,101,116,80,111,115,105,116,105,111,110,0,115,101,116,80,111,115,105,116,105,111,110,80,101,114,99,101,110,116,0,115,101,116,65,108,105,103,110,67,111,110,116,101,110,116,0,115,101,116,65,108,105,103,110,73,116,101,109,115,0,115,101,116,65,108,105,103,110,83,101,108,102,0,115,101,116,70,108,101,120,68,105,114,101,99,116,105,111,110,0,115,101,116,70,108,101,120,87,114,97,112,0,115,101,116,74,117,115,116,105,102,121,67,111,110,116,101,110,116,0,115,101,116,77,97,114,103,105,110,0,115,101,116,77,97,114,103,105,110,80,101,114,99,101,110,116,0,115,101,116,77,97,114,103,105,110,65,117,116,111,0,115,101,116,79,118,101,114,102,108,111,119,0,115,101,116,68,105,115,112,108,97,121,0,115,101,116,70,108,101,120,0,115,101,116,70,108,101,120,66,97,115,105,115,0,115,101,116,70,108,101,120,66,97,115,105,115,80,101,114,99,101,110,116,0,115,101,116,70,108,101,120,71,114,111,119,0,115,101,116,70,108,101,120,83,104,114,105,110,107,0,115,101,116,87,105,100,116,104,0,115,101,116,87,105,100,116,104,80,101,114,99,101,110,116,0,115,101,116,87,105,100,116,104,65,117,116,111,0,115,101,116,72,101,105,103,104,116,0,115,101,116,72,101,105,103,104,116,80,101,114,99,101,110,116,0,115,101,116,72,101,105,103,104,116,65,117,116,111,0,115,101,116,77,105,110,87,105,100,116,104,0,115,101,116,77,105,110,87,105,100,116,104,80,101,114,99,101,110,116,0,115,101,116,77,105,110,72,101,105,103,104,116,0,115,101,116,77,105,110,72,101,105,103,104,116,80,101,114,99,101,110,116,0,115,101,116,77,97,120,87,105,100,116,104,0,115,101,116,77,97,120,87,105,100,116,104,80,101,114,99,101,110,116,0,115,101,116,77,97,120,72,101,105,103,104,116,0,115,101,116,77,97,120,72,101,105,103,104,116,80,101,114,99,101,110,116,0,115,101,116,65,115,112,101,99,116,82,97,116,105,111,0,115,101,116,66,111,114,100,101,114,0,115,101,116,80,97,100,100,105,110,103,0,115,101,116,80,97,100,100,105,110,103,80,101,114,99,101,110,116,0,103,101,116,80,111,115,105,116,105,111,110,84,121,112,101,0,103,101,116,80,111,115,105,116,105,111,110,0,103,101,116,65,108,105,103,110,67,111,110,116,101,110,116,0,103,101,116,65,108,105,103,110,73,116,101,109,115,0,103,101,116,65,108,105,103,110,83,101,108,102,0,103,101,116,70,108,101,120,68,105,114,101,99,116,105,111,110,0,103,101,116,70,108,101,120,87,114,97,112,0,103,101,116,74,117,115,116,105,102,121,67,111,110,116,101,110,116,0,103,101,116,77,97,114,103,105,110,0,103,101,116,70,108,101,120,66,97,115,105,115,0,103,101,116,70,108,101,120,71,114,111,119,0,103,101,116,70,108,101,120,83,104,114,105,110,107,0,103,101,116,87,105,100,116,104,0,103,101,116,72,101,105,103,104,116,0,103,101,116,77,105,110,87,105,100,116,104,0,103,101,116,77,105,110,72,101,105,103,104,116,0,103,101,116,77,97,120,87,105,100,116,104,0,103,101,116,77,97,120,72,101,105,103,104,116,0,103,101,116,65,115,112,101,99,116,82,97,116,105,111,0,103,101,116,66,111,114,100,101,114,0,103,101,116,79,118,101,114,102,108,111,119,0,103,101,116,68,105,115,112,108,97,121,0,103,101,116,80,97,100,100,105,110,103,0,105,110,115,101,114,116,67,104,105,108,100,0,114,101,109,111,118,101,67,104,105,108,100,0,103,101,116,67,104,105,108,100,67,111,117,110,116,0,103,101,116,80,97,114,101,110,116,0,103,101,116,67,104,105,108,100,0,115,101,116,77,101,97,115,117,114,101,70,117,110,99,0,117,110,115,101,116,77,101,97,115,117,114,101,70,117,110,99,0,109,97,114,107,68,105,114,116,121,0,105,115,68,105,114,116,121,0,99,97,108,99,117,108,97,116,101,76,97,121,111,117,116,0,103,101,116,67,111,109,112,117,116,101,100,76,101,102,116,0,103,101,116,67,111,109,112,117,116,101,100,82,105,103,104,116,0,103,101,116,67,111,109,112,117,116,101,100,84,111,112,0,103,101,116,67,111,109,112,117,116,101,100,66,111,116,116,111,109,0,103,101,116,67,111,109,112,117,116,101,100,87,105,100,116,104,0,103,101,116,67,111,109,112,117,116,101,100,72,101,105,103,104,116,0,103,101,116,67,111,109,112,117,116,101,100,76,97,121,111,117,116,0,103,101,116,67,111,109,112,117,116,101,100,77,97,114,103,105,110,0,103,101,116,67,111,109,112,117,116,101,100,66,111,114,100,101,114,0,103,101,116,67,111,109,112,117,116,101,100,80,97,100,100,105,110,103,0,67,111,110,102,105,103,0,99,114,101,97,116,101,0,115,101,116,69,120,112,101,114,105,109,101,110,116,97,108,70,101,97,116,117,114,101,69,110,97,98,108,101,100,0,115,101,116,80,111,105,110,116,83,99,97,108,101,70,97,99,116,111,114,0,105,115,69,120,112,101,114,105,109,101,110,116,97,108,70,101,97,116,117,114,101,69,110,97,98,108,101,100,0,86,97,108,117,101,0,76,97,121,111,117,116,0,83,105,122,101,0,103,101,116,73,110,115,116,97,110,99,101,67,111,117,110,116,0,73,110,116,54,52,0,1,1,1,2,2,4,4,4,4,8,8,4,8,118,111,105,100,0,98,111,111,108,0,115,116,100,58,58,115,116,114,105,110,103,0,99,98,70,117,110,99,116,105,111,110,32,38,0,99,111,110,115,116,32,99,98,70,117,110,99,116,105,111,110,32,38,0,69,120,116,101,114,110,97,108,0,66,117,102,102,101,114,0,78,66,105,110,100,73,68,0,78,66,105,110,100,0,98,105,110,100,95,118,97,108,117,101,0,114,101,102,108,101,99,116,0,113,117,101,114,121,84,121,112,101,0,108,97,108,108,111,99,0,108,114,101,115,101,116,0,123,114,101,116,117,114,110,40,95,110,98,105,110,100,46,99,97,108,108,98,97,99,107,83,105,103,110,97,116,117,114,101,76,105,115,116,91,36,48,93,46,97,112,112,108,121,40,116,104,105,115,44,97,114,103,117,109,101,110,116,115,41,41,59,125,0,95,110,98,105,110,100,95,110,101,119,0,17,0,10,0,17,17,17,0,0,0,0,5,0,0,0,0,0,0,9,0,0,0,0,11,0,0,0,0,0,0,0,0,17,0,15,10,17,17,17,3,10,7,0,1,19,9,11,11,0,0,9,6,11,0,0,11,0,6,17,0,0,0,17,17,17,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,17,0,10,10,17,17,17,0,10,0,0,2,0,9,11,0,0,0,9,0,11,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,12,0,0,0,0,9,12,0,0,0,0,0,12,0,0,12,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,14,0,0,0,0,0,0,0,0,0,0,0,13,0,0,0,4,13,0,0,0,0,9,14,0,0,0,0,0,14,0,0,14,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,16,0,0,0,0,0,0,0,0,0,0,0,15,0,0,0,0,15,0,0,0,0,9,16,0,0,0,0,0,16,0,0,16,0,0,18,0,0,0,18,18,18,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,18,0,0,0,18,18,18,0,0,0,0,0,0,9,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,11,0,0,0,0,0,0,0,0,0,0,0,10,0,0,0,0,10,0,0,0,0,9,11,0,0,0,0,0,11,0,0,11,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,0,0,0,0,0,0,0,12,0,0,0,0,12,0,0,0,0,9,12,0,0,0,0,0,12,0,0,12,0,0,45,43,32,32,32,48,88,48,120,0,40,110,117,108,108,41,0,45,48,88,43,48,88,32,48,88,45,48,120,43,48,120,32,48,120,0,105,110,102,0,73,78,70,0,110,97,110,0,78,65,78,0,48,49,50,51,52,53,54,55,56,57,65,66,67,68,69,70,46,0,84,33,34,25,13,1,2,3,17,75,28,12,16,4,11,29,18,30,39,104,110,111,112,113,98,32,5,6,15,19,20,21,26,8,22,7,40,36,23,24,9,10,14,27,31,37,35,131,130,125,38,42,43,60,61,62,63,67,71,74,77,88,89,90,91,92,93,94,95,96,97,99,100,101,102,103,105,106,107,108,114,115,116,121,122,123,124,0,73,108,108,101,103,97,108,32,98,121,116,101,32,115,101,113,117,101,110,99,101,0,68,111,109,97,105,110,32,101,114,114,111,114,0,82,101,115,117,108,116,32,110,111,116,32,114,101,112,114,101,115,101,110,116,97,98,108,101,0,78,111,116,32,97,32,116,116,121,0,80,101,114,109,105,115,115,105,111,110,32,100,101,110,105,101,100,0,79,112,101,114,97,116,105,111,110,32,110,111,116,32,112,101,114,109,105,116,116,101,100,0,78,111,32,115,117,99,104,32,102,105,108,101,32,111,114,32,100,105,114,101,99,116,111,114,121,0,78,111,32,115,117,99,104,32,112,114,111,99,101,115,115,0,70,105,108,101,32,101,120,105,115,116,115,0,86,97,108,117,101,32,116,111,111,32,108,97,114,103,101,32,102,111,114,32,100,97,116,97,32,116,121,112,101,0,78,111,32,115,112,97,99,101,32,108,101,102,116,32,111,110,32,100,101,118,105,99,101,0,79,117,116,32,111,102,32,109,101,109,111,114,121,0,82,101,115,111,117,114,99,101,32,98,117,115,121,0,73,110,116,101,114,114,117,112,116,101,100,32,115,121,115,116,101,109,32,99,97,108,108,0,82,101,115,111,117,114,99,101,32,116,101,109,112,111,114,97,114,105,108,121,32,117,110,97,118,97,105,108,97,98,108,101,0,73,110,118,97,108,105,100,32,115,101,101,107,0,67,114,111,115,115,45,100,101,118,105,99,101,32,108,105,110,107,0,82,101,97,100,45,111,110,108,121,32,102,105,108,101,32,115,121,115,116,101,109,0,68,105,114,101,99,116,111,114,121,32,110,111,116,32,101,109,112,116,121,0,67,111,110,110,101,99,116,105,111,110,32,114,101,115,101,116,32,98,121,32,112,101,101,114,0,79,112,101,114,97,116,105,111,110,32,116,105,109,101,100,32,111,117,116,0,67,111,110,110,101,99,116,105,111,110,32,114,101,102,117,115,101,100,0,72,111,115,116,32,105,115,32,100,111,119,110,0,72,111,115,116,32,105,115,32,117,110,114,101,97,99,104,97,98,108,101,0,65,100,100,114,101,115,115,32,105,110,32,117,115,101,0,66,114,111,107,101,110,32,112,105,112,101,0,73,47,79,32,101,114,114,111,114,0,78,111,32,115,117,99,104,32,100,101,118,105,99,101,32,111,114,32,97,100,100,114,101,115,115,0,66,108,111,99,107,32,100,101,118,105,99,101,32,114,101,113,117,105,114,101,100,0,78,111,32,115,117,99,104,32,100,101,118,105,99,101,0,78,111,116,32,97,32,100,105,114,101,99,116,111,114,121,0,73,115,32,97,32,100,105,114,101,99,116,111,114,121,0,84,101,120,116,32,102,105,108,101,32,98,117,115,121,0,69,120,101,99,32,102,111,114,109,97,116,32,101,114,114,111,114,0,73,110,118,97,108,105,100,32,97,114,103,117,109,101,110,116,0,65,114,103,117,109,101,110,116,32,108,105,115,116,32,116,111,111,32,108,111,110,103,0,83,121,109,98,111,108,105,99,32,108,105,110,107,32,108,111,111,112,0,70,105,108,101,110,97,109,101,32,116,111,111,32,108,111,110,103,0,84,111,111,32,109,97,110,121,32,111,112,101,110,32,102,105,108,101,115,32,105,110,32,115,121,115,116,101,109,0,78,111,32,102,105,108,101,32,100,101,115,99,114,105,112,116,111,114,115,32,97,118,97,105,108,97,98,108,101,0,66,97,100,32,102,105,108,101,32,100,101,115,99,114,105,112,116,111,114,0,78,111,32,99,104,105,108,100,32,112,114,111,99,101,115,115,0,66,97,100,32,97,100,100,114,101,115,115,0,70,105,108,101,32,116,111,111,32,108,97,114,103,101,0,84,111,111,32,109,97,110,121,32,108,105,110,107,115,0,78,111,32,108,111,99,107,115,32,97,118,97,105,108,97,98,108,101,0,82,101,115,111,117,114,99,101,32,100,101,97,100,108,111,99,107,32,119,111,117,108,100,32,111,99,99,117,114,0,83,116,97,116,101,32,110,111,116,32,114,101,99,111,118,101,114,97,98,108,101,0,80,114,101,118,105,111,117,115,32,111,119,110,101,114,32,100,105,101,100,0,79,112,101,114,97,116,105,111,110,32,99,97,110,99,101,108,101,100,0,70,117,110,99,116,105,111,110,32,110,111,116,32,105,109,112,108,101,109,101,110,116,101,100,0,78,111,32,109,101,115,115,97,103,101,32,111,102,32,100,101,115,105,114,101,100,32,116,121,112,101,0,73,100,101,110,116,105,102,105,101,114,32,114,101,109,111,118,101,100,0,68,101,118,105,99,101,32,110,111,116,32,97,32,115,116,114,101,97,109,0,78,111,32,100,97,116,97,32,97,118,97,105,108,97,98,108,101,0,68,101,118,105,99,101,32,116,105,109,101,111,117,116,0,79,117,116,32,111,102,32,115,116,114,101,97,109,115,32,114,101,115,111,117,114,99,101,115,0,76,105,110,107,32,104,97,115,32,98,101,101,110,32,115,101,118,101,114,101,100,0,80,114,111,116,111,99,111,108,32,101,114,114,111,114,0,66,97,100,32,109,101,115,115,97,103,101,0,70,105,108,101,32,100,101,115,99,114,105,112,116,111,114,32,105,110,32,98,97,100,32,115,116,97,116,101,0,78,111,116,32,97,32,115,111,99,107,101,116,0,68,101,115,116,105,110,97,116,105,111,110,32,97,100,100,114,101,115,115,32,114,101,113,117,105,114,101,100,0,77,101,115,115,97,103,101,32,116,111,111,32,108,97,114,103,101,0,80,114,111,116,111,99,111,108,32,119,114,111,110,103,32,116,121,112,101,32,102,111,114,32,115,111,99,107,101,116,0,80,114,111,116,111,99,111,108,32,110,111,116,32,97,118,97,105,108,97,98,108,101,0,80,114,111,116,111,99,111,108,32,110,111,116,32,115,117,112,112,111,114,116,101,100,0,83,111,99,107,101,116,32,116,121,112,101,32,110,111,116,32,115,117,112,112,111,114,116,101,100,0,78,111,116,32,115,117,112,112,111,114,116,101,100,0,80,114,111,116,111,99,111,108,32,102,97,109,105,108,121,32,110,111,116,32,115,117,112,112,111,114,116,101,100,0,65,100,100,114,101,115,115,32,102,97,109,105,108,121,32,110,111,116,32,115,117,112,112,111,114,116,101,100,32,98,121,32,112,114,111,116,111,99,111,108,0,65,100,100,114,101,115,115,32,110,111,116,32,97,118,97,105,108,97,98,108,101,0,78,101,116,119,111,114,107,32,105,115,32,100,111,119,110,0,78,101,116,119,111,114,107,32,117,110,114,101,97,99,104,97,98,108,101,0,67,111,110,110,101,99,116,105,111,110,32,114,101,115,101,116,32,98,121,32,110,101,116,119,111,114,107,0,67,111,110,110,101,99,116,105,111,110,32,97,98,111,114,116,101,100,0,78,111,32,98,117,102,102,101,114,32,115,112,97,99,101,32,97,118,97,105,108,97,98,108,101,0,83,111,99,107,101,116,32,105,115,32,99,111,110,110,101,99,116,101,100,0,83,111,99,107,101,116,32,110,111,116,32,99,111,110,110,101,99,116,101,100,0,67,97,110,110,111,116,32,115,101,110,100,32,97,102,116,101,114,32,115,111,99,107,101,116,32,115,104,117,116,100,111,119,110,0,79,112,101,114,97,116,105,111,110,32,97,108,114,101,97,100,121,32,105,110,32,112,114,111,103,114,101,115,115,0,79,112,101,114,97,116,105,111,110,32,105,110,32,112,114,111,103,114,101,115,115,0,83,116,97,108,101,32,102,105,108,101,32,104,97,110,100,108,101,0,82,101,109,111,116,101,32,73,47,79,32,101,114,114,111,114,0,81,117,111,116,97,32,101,120,99,101,101,100,101,100,0,78,111,32,109,101,100,105,117,109,32,102,111,117,110,100,0,87,114,111,110,103,32,109,101,100,105,117,109,32,116,121,112,101,0,78,111,32,101,114,114,111,114,32,105,110,102,111,114,109,97,116,105,111,110,0,0],\"i8\",ALLOC_NONE,Runtime.GLOBAL_BASE);var tempDoublePtr=STATICTOP;STATICTOP+=16;function _atexit(t,e){__ATEXIT__.unshift({func:t,arg:e})}function ___cxa_atexit(){return _atexit.apply(null,arguments)}function _abort(){Module.abort()}function __ZN8facebook4yoga14YGNodeToStringEPNSt3__212basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEP6YGNode14YGPrintOptionsj(){Module.printErr(\"missing function: _ZN8facebook4yoga14YGNodeToStringEPNSt3__212basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEP6YGNode14YGPrintOptionsj\"),abort(-1)}function __decorate(t,e,r,o){var a=arguments.length,n=a<3?e:o===null?o=Object.getOwnPropertyDescriptor(e,r):o,u;if(typeof Reflect==\"object\"&&typeof Reflect.decorate==\"function\")n=Reflect.decorate(t,e,r,o);else for(var A=t.length-1;A>=0;A--)(u=t[A])&&(n=(a<3?u(n):a>3?u(e,r,n):u(e,r))||n);return a>3&&n&&Object.defineProperty(e,r,n),n}function _defineHidden(t){return function(e,r){Object.defineProperty(e,r,{configurable:!1,enumerable:!1,value:t,writable:!0})}}var _nbind={};function __nbind_free_external(t){_nbind.externalList[t].dereference(t)}function __nbind_reference_external(t){_nbind.externalList[t].reference()}function _llvm_stackrestore(t){var e=_llvm_stacksave,r=e.LLVM_SAVEDSTACKS[t];e.LLVM_SAVEDSTACKS.splice(t,1),Runtime.stackRestore(r)}function __nbind_register_pool(t,e,r,o){_nbind.Pool.pageSize=t,_nbind.Pool.usedPtr=e/4,_nbind.Pool.rootPtr=r,_nbind.Pool.pagePtr=o/4,HEAP32[e/4]=16909060,HEAP8[e]==1&&(_nbind.bigEndian=!0),HEAP32[e/4]=0,_nbind.makeTypeKindTbl=(n={},n[1024]=_nbind.PrimitiveType,n[64]=_nbind.Int64Type,n[2048]=_nbind.BindClass,n[3072]=_nbind.BindClassPtr,n[4096]=_nbind.SharedClassPtr,n[5120]=_nbind.ArrayType,n[6144]=_nbind.ArrayType,n[7168]=_nbind.CStringType,n[9216]=_nbind.CallbackType,n[10240]=_nbind.BindType,n),_nbind.makeTypeNameTbl={Buffer:_nbind.BufferType,External:_nbind.ExternalType,Int64:_nbind.Int64Type,_nbind_new:_nbind.CreateValueType,bool:_nbind.BooleanType,\"cbFunction &\":_nbind.CallbackType,\"const cbFunction &\":_nbind.CallbackType,\"const std::string &\":_nbind.StringType,\"std::string\":_nbind.StringType},Module.toggleLightGC=_nbind.toggleLightGC,_nbind.callUpcast=Module.dynCall_ii;var a=_nbind.makeType(_nbind.constructType,{flags:2048,id:0,name:\"\"});a.proto=Module,_nbind.BindClass.list.push(a);var n}function _emscripten_set_main_loop_timing(t,e){if(Browser.mainLoop.timingMode=t,Browser.mainLoop.timingValue=e,!Browser.mainLoop.func)return 1;if(t==0)Browser.mainLoop.scheduler=function(){var u=Math.max(0,Browser.mainLoop.tickStartTime+e-_emscripten_get_now())|0;setTimeout(Browser.mainLoop.runner,u)},Browser.mainLoop.method=\"timeout\";else if(t==1)Browser.mainLoop.scheduler=function(){Browser.requestAnimationFrame(Browser.mainLoop.runner)},Browser.mainLoop.method=\"rAF\";else if(t==2){if(!window.setImmediate){let n=function(u){u.source===window&&u.data===o&&(u.stopPropagation(),r.shift()())};var a=n,r=[],o=\"setimmediate\";window.addEventListener(\"message\",n,!0),window.setImmediate=function(A){r.push(A),ENVIRONMENT_IS_WORKER?(Module.setImmediates===void 0&&(Module.setImmediates=[]),Module.setImmediates.push(A),window.postMessage({target:o})):window.postMessage(o,\"*\")}}Browser.mainLoop.scheduler=function(){window.setImmediate(Browser.mainLoop.runner)},Browser.mainLoop.method=\"immediate\"}return 0}function _emscripten_get_now(){abort()}function _emscripten_set_main_loop(t,e,r,o,a){Module.noExitRuntime=!0,assert(!Browser.mainLoop.func,\"emscripten_set_main_loop: there can only be one main loop function at once: call emscripten_cancel_main_loop to cancel the previous one before setting a new one with different parameters.\"),Browser.mainLoop.func=t,Browser.mainLoop.arg=o;var n;typeof o<\"u\"?n=function(){Module.dynCall_vi(t,o)}:n=function(){Module.dynCall_v(t)};var u=Browser.mainLoop.currentlyRunningMainloop;if(Browser.mainLoop.runner=function(){if(!ABORT){if(Browser.mainLoop.queue.length>0){var p=Date.now(),h=Browser.mainLoop.queue.shift();if(h.func(h.arg),Browser.mainLoop.remainingBlockers){var E=Browser.mainLoop.remainingBlockers,I=E%1==0?E-1:Math.floor(E);h.counted?Browser.mainLoop.remainingBlockers=I:(I=I+.5,Browser.mainLoop.remainingBlockers=(8*E+I)/9)}if(console.log('main loop blocker \"'+h.name+'\" took '+(Date.now()-p)+\" ms\"),Browser.mainLoop.updateStatus(),u<Browser.mainLoop.currentlyRunningMainloop)return;setTimeout(Browser.mainLoop.runner,0);return}if(!(u<Browser.mainLoop.currentlyRunningMainloop)){if(Browser.mainLoop.currentFrameNumber=Browser.mainLoop.currentFrameNumber+1|0,Browser.mainLoop.timingMode==1&&Browser.mainLoop.timingValue>1&&Browser.mainLoop.currentFrameNumber%Browser.mainLoop.timingValue!=0){Browser.mainLoop.scheduler();return}else Browser.mainLoop.timingMode==0&&(Browser.mainLoop.tickStartTime=_emscripten_get_now());Browser.mainLoop.method===\"timeout\"&&Module.ctx&&(Module.printErr(\"Looks like you are rendering without using requestAnimationFrame for the main loop. You should use 0 for the frame rate in emscripten_set_main_loop in order to use requestAnimationFrame, as that can greatly improve your frame rates!\"),Browser.mainLoop.method=\"\"),Browser.mainLoop.runIter(n),!(u<Browser.mainLoop.currentlyRunningMainloop)&&(typeof SDL==\"object\"&&SDL.audio&&SDL.audio.queueNewAudioData&&SDL.audio.queueNewAudioData(),Browser.mainLoop.scheduler())}}},a||(e&&e>0?_emscripten_set_main_loop_timing(0,1e3/e):_emscripten_set_main_loop_timing(1,1),Browser.mainLoop.scheduler()),r)throw\"SimulateInfiniteLoop\"}var Browser={mainLoop:{scheduler:null,method:\"\",currentlyRunningMainloop:0,func:null,arg:0,timingMode:0,timingValue:0,currentFrameNumber:0,queue:[],pause:function(){Browser.mainLoop.scheduler=null,Browser.mainLoop.currentlyRunningMainloop++},resume:function(){Browser.mainLoop.currentlyRunningMainloop++;var t=Browser.mainLoop.timingMode,e=Browser.mainLoop.timingValue,r=Browser.mainLoop.func;Browser.mainLoop.func=null,_emscripten_set_main_loop(r,0,!1,Browser.mainLoop.arg,!0),_emscripten_set_main_loop_timing(t,e),Browser.mainLoop.scheduler()},updateStatus:function(){if(Module.setStatus){var t=Module.statusMessage||\"Please wait...\",e=Browser.mainLoop.remainingBlockers,r=Browser.mainLoop.expectedBlockers;e?e<r?Module.setStatus(t+\" (\"+(r-e)+\"/\"+r+\")\"):Module.setStatus(t):Module.setStatus(\"\")}},runIter:function(t){if(!ABORT){if(Module.preMainLoop){var e=Module.preMainLoop();if(e===!1)return}try{t()}catch(r){if(r instanceof ExitStatus)return;throw r&&typeof r==\"object\"&&r.stack&&Module.printErr(\"exception thrown: \"+[r,r.stack]),r}Module.postMainLoop&&Module.postMainLoop()}}},isFullscreen:!1,pointerLock:!1,moduleContextCreatedCallbacks:[],workers:[],init:function(){if(Module.preloadPlugins||(Module.preloadPlugins=[]),Browser.initted)return;Browser.initted=!0;try{new Blob,Browser.hasBlobConstructor=!0}catch{Browser.hasBlobConstructor=!1,console.log(\"warning: no blob constructor, cannot create blobs with mimetypes\")}Browser.BlobBuilder=typeof MozBlobBuilder<\"u\"?MozBlobBuilder:typeof WebKitBlobBuilder<\"u\"?WebKitBlobBuilder:Browser.hasBlobConstructor?null:console.log(\"warning: no BlobBuilder\"),Browser.URLObject=typeof window<\"u\"?window.URL?window.URL:window.webkitURL:void 0,!Module.noImageDecoding&&typeof Browser.URLObject>\"u\"&&(console.log(\"warning: Browser does not support creating object URLs. Built-in browser image decoding will not be available.\"),Module.noImageDecoding=!0);var t={};t.canHandle=function(n){return!Module.noImageDecoding&&/\\.(jpg|jpeg|png|bmp)$/i.test(n)},t.handle=function(n,u,A,p){var h=null;if(Browser.hasBlobConstructor)try{h=new Blob([n],{type:Browser.getMimetype(u)}),h.size!==n.length&&(h=new Blob([new Uint8Array(n).buffer],{type:Browser.getMimetype(u)}))}catch(x){Runtime.warnOnce(\"Blob constructor present but fails: \"+x+\"; falling back to blob builder\")}if(!h){var E=new Browser.BlobBuilder;E.append(new Uint8Array(n).buffer),h=E.getBlob()}var I=Browser.URLObject.createObjectURL(h),v=new Image;v.onload=function(){assert(v.complete,\"Image \"+u+\" could not be decoded\");var C=document.createElement(\"canvas\");C.width=v.width,C.height=v.height;var R=C.getContext(\"2d\");R.drawImage(v,0,0),Module.preloadedImages[u]=C,Browser.URLObject.revokeObjectURL(I),A&&A(n)},v.onerror=function(C){console.log(\"Image \"+I+\" could not be decoded\"),p&&p()},v.src=I},Module.preloadPlugins.push(t);var e={};e.canHandle=function(n){return!Module.noAudioDecoding&&n.substr(-4)in{\".ogg\":1,\".wav\":1,\".mp3\":1}},e.handle=function(n,u,A,p){var h=!1;function E(R){h||(h=!0,Module.preloadedAudios[u]=R,A&&A(n))}function I(){h||(h=!0,Module.preloadedAudios[u]=new Audio,p&&p())}if(Browser.hasBlobConstructor){try{var v=new Blob([n],{type:Browser.getMimetype(u)})}catch{return I()}var x=Browser.URLObject.createObjectURL(v),C=new Audio;C.addEventListener(\"canplaythrough\",function(){E(C)},!1),C.onerror=function(L){if(h)return;console.log(\"warning: browser could not fully decode audio \"+u+\", trying slower base64 approach\");function U(z){for(var te=\"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\",ae=\"=\",le=\"\",ce=0,Ce=0,de=0;de<z.length;de++)for(ce=ce<<8|z[de],Ce+=8;Ce>=6;){var Be=ce>>Ce-6&63;Ce-=6,le+=te[Be]}return Ce==2?(le+=te[(ce&3)<<4],le+=ae+ae):Ce==4&&(le+=te[(ce&15)<<2],le+=ae),le}C.src=\"data:audio/x-\"+u.substr(-3)+\";base64,\"+U(n),E(C)},C.src=x,Browser.safeSetTimeout(function(){E(C)},1e4)}else return I()},Module.preloadPlugins.push(e);function r(){Browser.pointerLock=document.pointerLockElement===Module.canvas||document.mozPointerLockElement===Module.canvas||document.webkitPointerLockElement===Module.canvas||document.msPointerLockElement===Module.canvas}var o=Module.canvas;o&&(o.requestPointerLock=o.requestPointerLock||o.mozRequestPointerLock||o.webkitRequestPointerLock||o.msRequestPointerLock||function(){},o.exitPointerLock=document.exitPointerLock||document.mozExitPointerLock||document.webkitExitPointerLock||document.msExitPointerLock||function(){},o.exitPointerLock=o.exitPointerLock.bind(document),document.addEventListener(\"pointerlockchange\",r,!1),document.addEventListener(\"mozpointerlockchange\",r,!1),document.addEventListener(\"webkitpointerlockchange\",r,!1),document.addEventListener(\"mspointerlockchange\",r,!1),Module.elementPointerLock&&o.addEventListener(\"click\",function(a){!Browser.pointerLock&&Module.canvas.requestPointerLock&&(Module.canvas.requestPointerLock(),a.preventDefault())},!1))},createContext:function(t,e,r,o){if(e&&Module.ctx&&t==Module.canvas)return Module.ctx;var a,n;if(e){var u={antialias:!1,alpha:!1};if(o)for(var A in o)u[A]=o[A];n=GL.createContext(t,u),n&&(a=GL.getContext(n).GLctx)}else a=t.getContext(\"2d\");return a?(r&&(e||assert(typeof GLctx>\"u\",\"cannot set in module if GLctx is used, but we are a non-GL context that would replace it\"),Module.ctx=a,e&&GL.makeContextCurrent(n),Module.useWebGL=e,Browser.moduleContextCreatedCallbacks.forEach(function(p){p()}),Browser.init()),a):null},destroyContext:function(t,e,r){},fullscreenHandlersInstalled:!1,lockPointer:void 0,resizeCanvas:void 0,requestFullscreen:function(t,e,r){Browser.lockPointer=t,Browser.resizeCanvas=e,Browser.vrDevice=r,typeof Browser.lockPointer>\"u\"&&(Browser.lockPointer=!0),typeof Browser.resizeCanvas>\"u\"&&(Browser.resizeCanvas=!1),typeof Browser.vrDevice>\"u\"&&(Browser.vrDevice=null);var o=Module.canvas;function a(){Browser.isFullscreen=!1;var u=o.parentNode;(document.fullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.webkitFullscreenElement||document.webkitCurrentFullScreenElement)===u?(o.exitFullscreen=document.exitFullscreen||document.cancelFullScreen||document.mozCancelFullScreen||document.msExitFullscreen||document.webkitCancelFullScreen||function(){},o.exitFullscreen=o.exitFullscreen.bind(document),Browser.lockPointer&&o.requestPointerLock(),Browser.isFullscreen=!0,Browser.resizeCanvas&&Browser.setFullscreenCanvasSize()):(u.parentNode.insertBefore(o,u),u.parentNode.removeChild(u),Browser.resizeCanvas&&Browser.setWindowedCanvasSize()),Module.onFullScreen&&Module.onFullScreen(Browser.isFullscreen),Module.onFullscreen&&Module.onFullscreen(Browser.isFullscreen),Browser.updateCanvasDimensions(o)}Browser.fullscreenHandlersInstalled||(Browser.fullscreenHandlersInstalled=!0,document.addEventListener(\"fullscreenchange\",a,!1),document.addEventListener(\"mozfullscreenchange\",a,!1),document.addEventListener(\"webkitfullscreenchange\",a,!1),document.addEventListener(\"MSFullscreenChange\",a,!1));var n=document.createElement(\"div\");o.parentNode.insertBefore(n,o),n.appendChild(o),n.requestFullscreen=n.requestFullscreen||n.mozRequestFullScreen||n.msRequestFullscreen||(n.webkitRequestFullscreen?function(){n.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT)}:null)||(n.webkitRequestFullScreen?function(){n.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT)}:null),r?n.requestFullscreen({vrDisplay:r}):n.requestFullscreen()},requestFullScreen:function(t,e,r){return Module.printErr(\"Browser.requestFullScreen() is deprecated. Please call Browser.requestFullscreen instead.\"),Browser.requestFullScreen=function(o,a,n){return Browser.requestFullscreen(o,a,n)},Browser.requestFullscreen(t,e,r)},nextRAF:0,fakeRequestAnimationFrame:function(t){var e=Date.now();if(Browser.nextRAF===0)Browser.nextRAF=e+1e3/60;else for(;e+2>=Browser.nextRAF;)Browser.nextRAF+=1e3/60;var r=Math.max(Browser.nextRAF-e,0);setTimeout(t,r)},requestAnimationFrame:function t(e){typeof window>\"u\"?Browser.fakeRequestAnimationFrame(e):(window.requestAnimationFrame||(window.requestAnimationFrame=window.requestAnimationFrame||window.mozRequestAnimationFrame||window.webkitRequestAnimationFrame||window.msRequestAnimationFrame||window.oRequestAnimationFrame||Browser.fakeRequestAnimationFrame),window.requestAnimationFrame(e))},safeCallback:function(t){return function(){if(!ABORT)return t.apply(null,arguments)}},allowAsyncCallbacks:!0,queuedAsyncCallbacks:[],pauseAsyncCallbacks:function(){Browser.allowAsyncCallbacks=!1},resumeAsyncCallbacks:function(){if(Browser.allowAsyncCallbacks=!0,Browser.queuedAsyncCallbacks.length>0){var t=Browser.queuedAsyncCallbacks;Browser.queuedAsyncCallbacks=[],t.forEach(function(e){e()})}},safeRequestAnimationFrame:function(t){return Browser.requestAnimationFrame(function(){ABORT||(Browser.allowAsyncCallbacks?t():Browser.queuedAsyncCallbacks.push(t))})},safeSetTimeout:function(t,e){return Module.noExitRuntime=!0,setTimeout(function(){ABORT||(Browser.allowAsyncCallbacks?t():Browser.queuedAsyncCallbacks.push(t))},e)},safeSetInterval:function(t,e){return Module.noExitRuntime=!0,setInterval(function(){ABORT||Browser.allowAsyncCallbacks&&t()},e)},getMimetype:function(t){return{jpg:\"image/jpeg\",jpeg:\"image/jpeg\",png:\"image/png\",bmp:\"image/bmp\",ogg:\"audio/ogg\",wav:\"audio/wav\",mp3:\"audio/mpeg\"}[t.substr(t.lastIndexOf(\".\")+1)]},getUserMedia:function(t){window.getUserMedia||(window.getUserMedia=navigator.getUserMedia||navigator.mozGetUserMedia),window.getUserMedia(t)},getMovementX:function(t){return t.movementX||t.mozMovementX||t.webkitMovementX||0},getMovementY:function(t){return t.movementY||t.mozMovementY||t.webkitMovementY||0},getMouseWheelDelta:function(t){var e=0;switch(t.type){case\"DOMMouseScroll\":e=t.detail;break;case\"mousewheel\":e=t.wheelDelta;break;case\"wheel\":e=t.deltaY;break;default:throw\"unrecognized mouse wheel event: \"+t.type}return e},mouseX:0,mouseY:0,mouseMovementX:0,mouseMovementY:0,touches:{},lastTouches:{},calculateMouseEvent:function(t){if(Browser.pointerLock)t.type!=\"mousemove\"&&\"mozMovementX\"in t?Browser.mouseMovementX=Browser.mouseMovementY=0:(Browser.mouseMovementX=Browser.getMovementX(t),Browser.mouseMovementY=Browser.getMovementY(t)),typeof SDL<\"u\"?(Browser.mouseX=SDL.mouseX+Browser.mouseMovementX,Browser.mouseY=SDL.mouseY+Browser.mouseMovementY):(Browser.mouseX+=Browser.mouseMovementX,Browser.mouseY+=Browser.mouseMovementY);else{var e=Module.canvas.getBoundingClientRect(),r=Module.canvas.width,o=Module.canvas.height,a=typeof window.scrollX<\"u\"?window.scrollX:window.pageXOffset,n=typeof window.scrollY<\"u\"?window.scrollY:window.pageYOffset;if(t.type===\"touchstart\"||t.type===\"touchend\"||t.type===\"touchmove\"){var u=t.touch;if(u===void 0)return;var A=u.pageX-(a+e.left),p=u.pageY-(n+e.top);A=A*(r/e.width),p=p*(o/e.height);var h={x:A,y:p};if(t.type===\"touchstart\")Browser.lastTouches[u.identifier]=h,Browser.touches[u.identifier]=h;else if(t.type===\"touchend\"||t.type===\"touchmove\"){var E=Browser.touches[u.identifier];E||(E=h),Browser.lastTouches[u.identifier]=E,Browser.touches[u.identifier]=h}return}var I=t.pageX-(a+e.left),v=t.pageY-(n+e.top);I=I*(r/e.width),v=v*(o/e.height),Browser.mouseMovementX=I-Browser.mouseX,Browser.mouseMovementY=v-Browser.mouseY,Browser.mouseX=I,Browser.mouseY=v}},asyncLoad:function(t,e,r,o){var a=o?\"\":\"al \"+t;Module.readAsync(t,function(n){assert(n,'Loading data file \"'+t+'\" failed (no arrayBuffer).'),e(new Uint8Array(n)),a&&removeRunDependency(a)},function(n){if(r)r();else throw'Loading data file \"'+t+'\" failed.'}),a&&addRunDependency(a)},resizeListeners:[],updateResizeListeners:function(){var t=Module.canvas;Browser.resizeListeners.forEach(function(e){e(t.width,t.height)})},setCanvasSize:function(t,e,r){var o=Module.canvas;Browser.updateCanvasDimensions(o,t,e),r||Browser.updateResizeListeners()},windowedWidth:0,windowedHeight:0,setFullscreenCanvasSize:function(){if(typeof SDL<\"u\"){var t=HEAPU32[SDL.screen+Runtime.QUANTUM_SIZE*0>>2];t=t|8388608,HEAP32[SDL.screen+Runtime.QUANTUM_SIZE*0>>2]=t}Browser.updateResizeListeners()},setWindowedCanvasSize:function(){if(typeof SDL<\"u\"){var t=HEAPU32[SDL.screen+Runtime.QUANTUM_SIZE*0>>2];t=t&-8388609,HEAP32[SDL.screen+Runtime.QUANTUM_SIZE*0>>2]=t}Browser.updateResizeListeners()},updateCanvasDimensions:function(t,e,r){e&&r?(t.widthNative=e,t.heightNative=r):(e=t.widthNative,r=t.heightNative);var o=e,a=r;if(Module.forcedAspectRatio&&Module.forcedAspectRatio>0&&(o/a<Module.forcedAspectRatio?o=Math.round(a*Module.forcedAspectRatio):a=Math.round(o/Module.forcedAspectRatio)),(document.fullscreenElement||document.mozFullScreenElement||document.msFullscreenElement||document.webkitFullscreenElement||document.webkitCurrentFullScreenElement)===t.parentNode&&typeof screen<\"u\"){var n=Math.min(screen.width/o,screen.height/a);o=Math.round(o*n),a=Math.round(a*n)}Browser.resizeCanvas?(t.width!=o&&(t.width=o),t.height!=a&&(t.height=a),typeof t.style<\"u\"&&(t.style.removeProperty(\"width\"),t.style.removeProperty(\"height\"))):(t.width!=e&&(t.width=e),t.height!=r&&(t.height=r),typeof t.style<\"u\"&&(o!=e||a!=r?(t.style.setProperty(\"width\",o+\"px\",\"important\"),t.style.setProperty(\"height\",a+\"px\",\"important\")):(t.style.removeProperty(\"width\"),t.style.removeProperty(\"height\"))))},wgetRequests:{},nextWgetRequestHandle:0,getNextWgetRequestHandle:function(){var t=Browser.nextWgetRequestHandle;return Browser.nextWgetRequestHandle++,t}},SYSCALLS={varargs:0,get:function(t){SYSCALLS.varargs+=4;var e=HEAP32[SYSCALLS.varargs-4>>2];return e},getStr:function(){var t=Pointer_stringify(SYSCALLS.get());return t},get64:function(){var t=SYSCALLS.get(),e=SYSCALLS.get();return t>=0?assert(e===0):assert(e===-1),t},getZero:function(){assert(SYSCALLS.get()===0)}};function ___syscall6(t,e){SYSCALLS.varargs=e;try{var r=SYSCALLS.getStreamFromFD();return FS.close(r),0}catch(o){return(typeof FS>\"u\"||!(o instanceof FS.ErrnoError))&&abort(o),-o.errno}}function ___syscall54(t,e){SYSCALLS.varargs=e;try{return 0}catch(r){return(typeof FS>\"u\"||!(r instanceof FS.ErrnoError))&&abort(r),-r.errno}}function _typeModule(t){var e=[[0,1,\"X\"],[1,1,\"const X\"],[128,1,\"X *\"],[256,1,\"X &\"],[384,1,\"X &&\"],[512,1,\"std::shared_ptr<X>\"],[640,1,\"std::unique_ptr<X>\"],[5120,1,\"std::vector<X>\"],[6144,2,\"std::array<X, Y>\"],[9216,-1,\"std::function<X (Y)>\"]];function r(p,h,E,I,v,x){if(h==1){var C=I&896;(C==128||C==256||C==384)&&(p=\"X const\")}var R;return x?R=E.replace(\"X\",p).replace(\"Y\",v):R=p.replace(\"X\",E).replace(\"Y\",v),R.replace(/([*&]) (?=[*&])/g,\"$1\")}function o(p,h,E,I,v){throw new Error(p+\" type \"+E.replace(\"X\",h+\"?\")+(I?\" with flag \"+I:\"\")+\" in \"+v)}function a(p,h,E,I,v,x,C,R){x===void 0&&(x=\"X\"),R===void 0&&(R=1);var L=E(p);if(L)return L;var U=I(p),z=U.placeholderFlag,te=e[z];C&&te&&(x=r(C[2],C[0],x,te[0],\"?\",!0));var ae;z==0&&(ae=\"Unbound\"),z>=10&&(ae=\"Corrupt\"),R>20&&(ae=\"Deeply nested\"),ae&&o(ae,p,x,z,v||\"?\");var le=U.paramList[0],ce=a(le,h,E,I,v,x,te,R+1),Ce,de={flags:te[0],id:p,name:\"\",paramList:[ce]},Be=[],Ee=\"?\";switch(U.placeholderFlag){case 1:Ce=ce.spec;break;case 2:if((ce.flags&15360)==1024&&ce.spec.ptrSize==1){de.flags=7168;break}case 3:case 6:case 5:Ce=ce.spec,ce.flags&15360;break;case 8:Ee=\"\"+U.paramList[1],de.paramList.push(U.paramList[1]);break;case 9:for(var g=0,me=U.paramList[1];g<me.length;g++){var we=me[g],Ae=a(we,h,E,I,v,x,te,R+1);Be.push(Ae.name),de.paramList.push(Ae)}Ee=Be.join(\", \");break;default:break}if(de.name=r(te[2],te[0],ce.name,ce.flags,Ee),Ce){for(var ne=0,Z=Object.keys(Ce);ne<Z.length;ne++){var xe=Z[ne];de[xe]=de[xe]||Ce[xe]}de.flags|=Ce.flags}return n(h,de)}function n(p,h){var E=h.flags,I=E&896,v=E&15360;return!h.name&&v==1024&&(h.ptrSize==1?h.name=(E&16?\"\":(E&8?\"un\":\"\")+\"signed \")+\"char\":h.name=(E&8?\"u\":\"\")+(E&32?\"float\":\"int\")+(h.ptrSize*8+\"_t\")),h.ptrSize==8&&!(E&32)&&(v=64),v==2048&&(I==512||I==640?v=4096:I&&(v=3072)),p(v,h)}var u=function(){function p(h){this.id=h.id,this.name=h.name,this.flags=h.flags,this.spec=h}return p.prototype.toString=function(){return this.name},p}(),A={Type:u,getComplexType:a,makeType:n,structureList:e};return t.output=A,t.output||A}function __nbind_register_type(t,e){var r=_nbind.readAsciiString(e),o={flags:10240,id:t,name:r};_nbind.makeType(_nbind.constructType,o)}function __nbind_register_callback_signature(t,e){var r=_nbind.readTypeIdList(t,e),o=_nbind.callbackSignatureList.length;return _nbind.callbackSignatureList[o]=_nbind.makeJSCaller(r),o}function __extends(t,e){for(var r in e)e.hasOwnProperty(r)&&(t[r]=e[r]);function o(){this.constructor=t}o.prototype=e.prototype,t.prototype=new o}function __nbind_register_class(t,e,r,o,a,n,u){var A=_nbind.readAsciiString(u),p=_nbind.readPolicyList(e),h=HEAPU32.subarray(t/4,t/4+2),E={flags:2048|(p.Value?2:0),id:h[0],name:A},I=_nbind.makeType(_nbind.constructType,E);I.ptrType=_nbind.getComplexType(h[1],_nbind.constructType,_nbind.getType,_nbind.queryType),I.destroy=_nbind.makeMethodCaller(I.ptrType,{boundID:E.id,flags:0,name:\"destroy\",num:0,ptr:n,title:I.name+\".free\",typeList:[\"void\",\"uint32_t\",\"uint32_t\"]}),a&&(I.superIdList=Array.prototype.slice.call(HEAPU32.subarray(r/4,r/4+a)),I.upcastList=Array.prototype.slice.call(HEAPU32.subarray(o/4,o/4+a))),Module[I.name]=I.makeBound(p),_nbind.BindClass.list.push(I)}function _removeAccessorPrefix(t){var e=/^[Gg]et_?([A-Z]?([A-Z]?))/;return t.replace(e,function(r,o,a){return a?o:o.toLowerCase()})}function __nbind_register_function(t,e,r,o,a,n,u,A,p,h){var E=_nbind.getType(t),I=_nbind.readPolicyList(e),v=_nbind.readTypeIdList(r,o),x;if(u==5)x=[{direct:a,name:\"__nbindConstructor\",ptr:0,title:E.name+\" constructor\",typeList:[\"uint32_t\"].concat(v.slice(1))},{direct:n,name:\"__nbindValueConstructor\",ptr:0,title:E.name+\" value constructor\",typeList:[\"void\",\"uint32_t\"].concat(v.slice(1))}];else{var C=_nbind.readAsciiString(A),R=(E.name&&E.name+\".\")+C;(u==3||u==4)&&(C=_removeAccessorPrefix(C)),x=[{boundID:t,direct:n,name:C,ptr:a,title:R,typeList:v}]}for(var L=0,U=x;L<U.length;L++){var z=U[L];z.signatureType=u,z.policyTbl=I,z.num=p,z.flags=h,E.addMethod(z)}}function _nbind_value(t,e){_nbind.typeNameTbl[t]||_nbind.throwError(\"Unknown value type \"+t),Module.NBind.bind_value(t,e),_defineHidden(_nbind.typeNameTbl[t].proto.prototype.__nbindValueConstructor)(e.prototype,\"__nbindValueConstructor\")}Module._nbind_value=_nbind_value;function __nbind_get_value_object(t,e){var r=_nbind.popValue(t);if(!r.fromJS)throw new Error(\"Object \"+r+\" has no fromJS function\");r.fromJS(function(){r.__nbindValueConstructor.apply(this,Array.prototype.concat.apply([e],arguments))})}function _emscripten_memcpy_big(t,e,r){return HEAPU8.set(HEAPU8.subarray(e,e+r),t),t}function __nbind_register_primitive(t,e,r){var o={flags:1024|r,id:t,ptrSize:e};_nbind.makeType(_nbind.constructType,o)}var cttz_i8=allocate([8,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,7,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,6,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,5,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0,4,0,1,0,2,0,1,0,3,0,1,0,2,0,1,0],\"i8\",ALLOC_STATIC);function ___setErrNo(t){return Module.___errno_location&&(HEAP32[Module.___errno_location()>>2]=t),t}function _llvm_stacksave(){var t=_llvm_stacksave;return t.LLVM_SAVEDSTACKS||(t.LLVM_SAVEDSTACKS=[]),t.LLVM_SAVEDSTACKS.push(Runtime.stackSave()),t.LLVM_SAVEDSTACKS.length-1}function ___syscall140(t,e){SYSCALLS.varargs=e;try{var r=SYSCALLS.getStreamFromFD(),o=SYSCALLS.get(),a=SYSCALLS.get(),n=SYSCALLS.get(),u=SYSCALLS.get(),A=a;return FS.llseek(r,A,u),HEAP32[n>>2]=r.position,r.getdents&&A===0&&u===0&&(r.getdents=null),0}catch(p){return(typeof FS>\"u\"||!(p instanceof FS.ErrnoError))&&abort(p),-p.errno}}function ___syscall146(t,e){SYSCALLS.varargs=e;try{var r=SYSCALLS.get(),o=SYSCALLS.get(),a=SYSCALLS.get(),n=0;___syscall146.buffer||(___syscall146.buffers=[null,[],[]],___syscall146.printChar=function(E,I){var v=___syscall146.buffers[E];assert(v),I===0||I===10?((E===1?Module.print:Module.printErr)(UTF8ArrayToString(v,0)),v.length=0):v.push(I)});for(var u=0;u<a;u++){for(var A=HEAP32[o+u*8>>2],p=HEAP32[o+(u*8+4)>>2],h=0;h<p;h++)___syscall146.printChar(r,HEAPU8[A+h]);n+=p}return n}catch(E){return(typeof FS>\"u\"||!(E instanceof FS.ErrnoError))&&abort(E),-E.errno}}function __nbind_finish(){for(var t=0,e=_nbind.BindClass.list;t<e.length;t++){var r=e[t];r.finish()}}var ___dso_handle=STATICTOP;STATICTOP+=16,function(_nbind){var typeIdTbl={};_nbind.typeNameTbl={};var Pool=function(){function t(){}return t.lalloc=function(e){e=e+7&-8;var r=HEAPU32[t.usedPtr];if(e>t.pageSize/2||e>t.pageSize-r){var o=_nbind.typeNameTbl.NBind.proto;return o.lalloc(e)}else return HEAPU32[t.usedPtr]=r+e,t.rootPtr+r},t.lreset=function(e,r){var o=HEAPU32[t.pagePtr];if(o){var a=_nbind.typeNameTbl.NBind.proto;a.lreset(e,r)}else HEAPU32[t.usedPtr]=e},t}();_nbind.Pool=Pool;function constructType(t,e){var r=t==10240?_nbind.makeTypeNameTbl[e.name]||_nbind.BindType:_nbind.makeTypeKindTbl[t],o=new r(e);return typeIdTbl[e.id]=o,_nbind.typeNameTbl[e.name]=o,o}_nbind.constructType=constructType;function getType(t){return typeIdTbl[t]}_nbind.getType=getType;function queryType(t){var e=HEAPU8[t],r=_nbind.structureList[e][1];t/=4,r<0&&(++t,r=HEAPU32[t]+1);var o=Array.prototype.slice.call(HEAPU32.subarray(t+1,t+1+r));return e==9&&(o=[o[0],o.slice(1)]),{paramList:o,placeholderFlag:e}}_nbind.queryType=queryType;function getTypes(t,e){return t.map(function(r){return typeof r==\"number\"?_nbind.getComplexType(r,constructType,getType,queryType,e):_nbind.typeNameTbl[r]})}_nbind.getTypes=getTypes;function readTypeIdList(t,e){return Array.prototype.slice.call(HEAPU32,t/4,t/4+e)}_nbind.readTypeIdList=readTypeIdList;function readAsciiString(t){for(var e=t;HEAPU8[e++];);return String.fromCharCode.apply(\"\",HEAPU8.subarray(t,e-1))}_nbind.readAsciiString=readAsciiString;function readPolicyList(t){var e={};if(t)for(;;){var r=HEAPU32[t/4];if(!r)break;e[readAsciiString(r)]=!0,t+=4}return e}_nbind.readPolicyList=readPolicyList;function getDynCall(t,e){var r={float32_t:\"d\",float64_t:\"d\",int64_t:\"d\",uint64_t:\"d\",void:\"v\"},o=t.map(function(n){return r[n.name]||\"i\"}).join(\"\"),a=Module[\"dynCall_\"+o];if(!a)throw new Error(\"dynCall_\"+o+\" not found for \"+e+\"(\"+t.map(function(n){return n.name}).join(\", \")+\")\");return a}_nbind.getDynCall=getDynCall;function addMethod(t,e,r,o){var a=t[e];t.hasOwnProperty(e)&&a?((a.arity||a.arity===0)&&(a=_nbind.makeOverloader(a,a.arity),t[e]=a),a.addMethod(r,o)):(r.arity=o,t[e]=r)}_nbind.addMethod=addMethod;function throwError(t){throw new Error(t)}_nbind.throwError=throwError,_nbind.bigEndian=!1,_a=_typeModule(_typeModule),_nbind.Type=_a.Type,_nbind.makeType=_a.makeType,_nbind.getComplexType=_a.getComplexType,_nbind.structureList=_a.structureList;var BindType=function(t){__extends(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.heap=HEAPU32,r.ptrSize=4,r}return e.prototype.needsWireRead=function(r){return!!this.wireRead||!!this.makeWireRead},e.prototype.needsWireWrite=function(r){return!!this.wireWrite||!!this.makeWireWrite},e}(_nbind.Type);_nbind.BindType=BindType;var PrimitiveType=function(t){__extends(e,t);function e(r){var o=t.call(this,r)||this,a=r.flags&32?{32:HEAPF32,64:HEAPF64}:r.flags&8?{8:HEAPU8,16:HEAPU16,32:HEAPU32}:{8:HEAP8,16:HEAP16,32:HEAP32};return o.heap=a[r.ptrSize*8],o.ptrSize=r.ptrSize,o}return e.prototype.needsWireWrite=function(r){return!!r&&!!r.Strict},e.prototype.makeWireWrite=function(r,o){return o&&o.Strict&&function(a){if(typeof a==\"number\")return a;throw new Error(\"Type mismatch\")}},e}(BindType);_nbind.PrimitiveType=PrimitiveType;function pushCString(t,e){if(t==null){if(e&&e.Nullable)return 0;throw new Error(\"Type mismatch\")}if(e&&e.Strict){if(typeof t!=\"string\")throw new Error(\"Type mismatch\")}else t=t.toString();var r=Module.lengthBytesUTF8(t)+1,o=_nbind.Pool.lalloc(r);return Module.stringToUTF8Array(t,HEAPU8,o,r),o}_nbind.pushCString=pushCString;function popCString(t){return t===0?null:Module.Pointer_stringify(t)}_nbind.popCString=popCString;var CStringType=function(t){__extends(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.wireRead=popCString,r.wireWrite=pushCString,r.readResources=[_nbind.resources.pool],r.writeResources=[_nbind.resources.pool],r}return e.prototype.makeWireWrite=function(r,o){return function(a){return pushCString(a,o)}},e}(BindType);_nbind.CStringType=CStringType;var BooleanType=function(t){__extends(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.wireRead=function(o){return!!o},r}return e.prototype.needsWireWrite=function(r){return!!r&&!!r.Strict},e.prototype.makeWireRead=function(r){return\"!!(\"+r+\")\"},e.prototype.makeWireWrite=function(r,o){return o&&o.Strict&&function(a){if(typeof a==\"boolean\")return a;throw new Error(\"Type mismatch\")}||r},e}(BindType);_nbind.BooleanType=BooleanType;var Wrapper=function(){function t(){}return t.prototype.persist=function(){this.__nbindState|=1},t}();_nbind.Wrapper=Wrapper;function makeBound(t,e){var r=function(o){__extends(a,o);function a(n,u,A,p){var h=o.call(this)||this;if(!(h instanceof a))return new(Function.prototype.bind.apply(a,Array.prototype.concat.apply([null],arguments)));var E=u,I=A,v=p;if(n!==_nbind.ptrMarker){var x=h.__nbindConstructor.apply(h,arguments);E=4608,v=HEAPU32[x/4],I=HEAPU32[x/4+1]}var C={configurable:!0,enumerable:!1,value:null,writable:!1},R={__nbindFlags:E,__nbindPtr:I};v&&(R.__nbindShared=v,_nbind.mark(h));for(var L=0,U=Object.keys(R);L<U.length;L++){var z=U[L];C.value=R[z],Object.defineProperty(h,z,C)}return _defineHidden(0)(h,\"__nbindState\"),h}return a.prototype.free=function(){e.destroy.call(this,this.__nbindShared,this.__nbindFlags),this.__nbindState|=2,disableMember(this,\"__nbindShared\"),disableMember(this,\"__nbindPtr\")},a}(Wrapper);return __decorate([_defineHidden()],r.prototype,\"__nbindConstructor\",void 0),__decorate([_defineHidden()],r.prototype,\"__nbindValueConstructor\",void 0),__decorate([_defineHidden(t)],r.prototype,\"__nbindPolicies\",void 0),r}_nbind.makeBound=makeBound;function disableMember(t,e){function r(){throw new Error(\"Accessing deleted object\")}Object.defineProperty(t,e,{configurable:!1,enumerable:!1,get:r,set:r})}_nbind.ptrMarker={};var BindClass=function(t){__extends(e,t);function e(r){var o=t.call(this,r)||this;return o.wireRead=function(a){return _nbind.popValue(a,o.ptrType)},o.wireWrite=function(a){return pushPointer(a,o.ptrType,!0)},o.pendingSuperCount=0,o.ready=!1,o.methodTbl={},r.paramList?(o.classType=r.paramList[0].classType,o.proto=o.classType.proto):o.classType=o,o}return e.prototype.makeBound=function(r){var o=_nbind.makeBound(r,this);return this.proto=o,this.ptrType.proto=o,o},e.prototype.addMethod=function(r){var o=this.methodTbl[r.name]||[];o.push(r),this.methodTbl[r.name]=o},e.prototype.registerMethods=function(r,o){for(var a,n=0,u=Object.keys(r.methodTbl);n<u.length;n++)for(var A=u[n],p=r.methodTbl[A],h=0,E=p;h<E.length;h++){var I=E[h],v=void 0,x=void 0;if(v=this.proto.prototype,!(o&&I.signatureType!=1))switch(I.signatureType){case 1:v=this.proto;case 5:x=_nbind.makeCaller(I),_nbind.addMethod(v,I.name,x,I.typeList.length-1);break;case 4:a=_nbind.makeMethodCaller(r.ptrType,I);break;case 3:Object.defineProperty(v,I.name,{configurable:!0,enumerable:!1,get:_nbind.makeMethodCaller(r.ptrType,I),set:a});break;case 2:x=_nbind.makeMethodCaller(r.ptrType,I),_nbind.addMethod(v,I.name,x,I.typeList.length-1);break;default:break}}},e.prototype.registerSuperMethods=function(r,o,a){if(!a[r.name]){a[r.name]=!0;for(var n=0,u,A=0,p=r.superIdList||[];A<p.length;A++){var h=p[A],E=_nbind.getType(h);n++<o||o<0?u=-1:u=0,this.registerSuperMethods(E,u,a)}this.registerMethods(r,o<0)}},e.prototype.finish=function(){if(this.ready)return this;this.ready=!0,this.superList=(this.superIdList||[]).map(function(a){return _nbind.getType(a).finish()});var r=this.proto;if(this.superList.length){var o=function(){this.constructor=r};o.prototype=this.superList[0].proto.prototype,r.prototype=new o}return r!=Module&&(r.prototype.__nbindType=this),this.registerSuperMethods(this,1,{}),this},e.prototype.upcastStep=function(r,o){if(r==this)return o;for(var a=0;a<this.superList.length;++a){var n=this.superList[a].upcastStep(r,_nbind.callUpcast(this.upcastList[a],o));if(n)return n}return 0},e}(_nbind.BindType);BindClass.list=[],_nbind.BindClass=BindClass;function popPointer(t,e){return t?new e.proto(_nbind.ptrMarker,e.flags,t):null}_nbind.popPointer=popPointer;function pushPointer(t,e,r){if(!(t instanceof _nbind.Wrapper)){if(r)return _nbind.pushValue(t);throw new Error(\"Type mismatch\")}var o=t.__nbindPtr,a=t.__nbindType.classType,n=e.classType;if(t instanceof e.proto)for(;a!=n;)o=_nbind.callUpcast(a.upcastList[0],o),a=a.superList[0];else if(o=a.upcastStep(n,o),!o)throw new Error(\"Type mismatch\");return o}_nbind.pushPointer=pushPointer;function pushMutablePointer(t,e){var r=pushPointer(t,e);if(t.__nbindFlags&1)throw new Error(\"Passing a const value as a non-const argument\");return r}var BindClassPtr=function(t){__extends(e,t);function e(r){var o=t.call(this,r)||this;o.classType=r.paramList[0].classType,o.proto=o.classType.proto;var a=r.flags&1,n=(o.flags&896)==256&&r.flags&2,u=a?pushPointer:pushMutablePointer,A=n?_nbind.popValue:popPointer;return o.makeWireWrite=function(p,h){return h.Nullable?function(E){return E?u(E,o):0}:function(E){return u(E,o)}},o.wireRead=function(p){return A(p,o)},o.wireWrite=function(p){return u(p,o)},o}return e}(_nbind.BindType);_nbind.BindClassPtr=BindClassPtr;function popShared(t,e){var r=HEAPU32[t/4],o=HEAPU32[t/4+1];return o?new e.proto(_nbind.ptrMarker,e.flags,o,r):null}_nbind.popShared=popShared;function pushShared(t,e){if(!(t instanceof e.proto))throw new Error(\"Type mismatch\");return t.__nbindShared}function pushMutableShared(t,e){if(!(t instanceof e.proto))throw new Error(\"Type mismatch\");if(t.__nbindFlags&1)throw new Error(\"Passing a const value as a non-const argument\");return t.__nbindShared}var SharedClassPtr=function(t){__extends(e,t);function e(r){var o=t.call(this,r)||this;o.readResources=[_nbind.resources.pool],o.classType=r.paramList[0].classType,o.proto=o.classType.proto;var a=r.flags&1,n=a?pushShared:pushMutableShared;return o.wireRead=function(u){return popShared(u,o)},o.wireWrite=function(u){return n(u,o)},o}return e}(_nbind.BindType);_nbind.SharedClassPtr=SharedClassPtr,_nbind.externalList=[0];var firstFreeExternal=0,External=function(){function t(e){this.refCount=1,this.data=e}return t.prototype.register=function(){var e=firstFreeExternal;return e?firstFreeExternal=_nbind.externalList[e]:e=_nbind.externalList.length,_nbind.externalList[e]=this,e},t.prototype.reference=function(){++this.refCount},t.prototype.dereference=function(e){--this.refCount==0&&(this.free&&this.free(),_nbind.externalList[e]=firstFreeExternal,firstFreeExternal=e)},t}();_nbind.External=External;function popExternal(t){var e=_nbind.externalList[t];return e.dereference(t),e.data}function pushExternal(t){var e=new External(t);return e.reference(),e.register()}var ExternalType=function(t){__extends(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.wireRead=popExternal,r.wireWrite=pushExternal,r}return e}(_nbind.BindType);_nbind.ExternalType=ExternalType,_nbind.callbackSignatureList=[];var CallbackType=function(t){__extends(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.wireWrite=function(o){return typeof o!=\"function\"&&_nbind.throwError(\"Type mismatch\"),new _nbind.External(o).register()},r}return e}(_nbind.BindType);_nbind.CallbackType=CallbackType,_nbind.valueList=[0];var firstFreeValue=0;function pushValue(t){var e=firstFreeValue;return e?firstFreeValue=_nbind.valueList[e]:e=_nbind.valueList.length,_nbind.valueList[e]=t,e*2+1}_nbind.pushValue=pushValue;function popValue(t,e){if(t||_nbind.throwError(\"Value type JavaScript class is missing or not registered\"),t&1){t>>=1;var r=_nbind.valueList[t];return _nbind.valueList[t]=firstFreeValue,firstFreeValue=t,r}else{if(e)return _nbind.popShared(t,e);throw new Error(\"Invalid value slot \"+t)}}_nbind.popValue=popValue;var valueBase=18446744073709552e3;function push64(t){return typeof t==\"number\"?t:pushValue(t)*4096+valueBase}function pop64(t){return t<valueBase?t:popValue((t-valueBase)/4096)}var CreateValueType=function(t){__extends(e,t);function e(){return t!==null&&t.apply(this,arguments)||this}return e.prototype.makeWireWrite=function(r){return\"(_nbind.pushValue(new \"+r+\"))\"},e}(_nbind.BindType);_nbind.CreateValueType=CreateValueType;var Int64Type=function(t){__extends(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.wireWrite=push64,r.wireRead=pop64,r}return e}(_nbind.BindType);_nbind.Int64Type=Int64Type;function pushArray(t,e){if(!t)return 0;var r=t.length;if((e.size||e.size===0)&&r<e.size)throw new Error(\"Type mismatch\");var o=e.memberType.ptrSize,a=_nbind.Pool.lalloc(4+r*o);HEAPU32[a/4]=r;var n=e.memberType.heap,u=(a+4)/o,A=e.memberType.wireWrite,p=0;if(A)for(;p<r;)n[u++]=A(t[p++]);else for(;p<r;)n[u++]=t[p++];return a}_nbind.pushArray=pushArray;function popArray(t,e){if(t===0)return null;var r=HEAPU32[t/4],o=new Array(r),a=e.memberType.heap;t=(t+4)/e.memberType.ptrSize;var n=e.memberType.wireRead,u=0;if(n)for(;u<r;)o[u++]=n(a[t++]);else for(;u<r;)o[u++]=a[t++];return o}_nbind.popArray=popArray;var ArrayType=function(t){__extends(e,t);function e(r){var o=t.call(this,r)||this;return o.wireRead=function(a){return popArray(a,o)},o.wireWrite=function(a){return pushArray(a,o)},o.readResources=[_nbind.resources.pool],o.writeResources=[_nbind.resources.pool],o.memberType=r.paramList[0],r.paramList[1]&&(o.size=r.paramList[1]),o}return e}(_nbind.BindType);_nbind.ArrayType=ArrayType;function pushString(t,e){if(t==null)if(e&&e.Nullable)t=\"\";else throw new Error(\"Type mismatch\");if(e&&e.Strict){if(typeof t!=\"string\")throw new Error(\"Type mismatch\")}else t=t.toString();var r=Module.lengthBytesUTF8(t),o=_nbind.Pool.lalloc(4+r+1);return HEAPU32[o/4]=r,Module.stringToUTF8Array(t,HEAPU8,o+4,r+1),o}_nbind.pushString=pushString;function popString(t){if(t===0)return null;var e=HEAPU32[t/4];return Module.Pointer_stringify(t+4,e)}_nbind.popString=popString;var StringType=function(t){__extends(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.wireRead=popString,r.wireWrite=pushString,r.readResources=[_nbind.resources.pool],r.writeResources=[_nbind.resources.pool],r}return e.prototype.makeWireWrite=function(r,o){return function(a){return pushString(a,o)}},e}(_nbind.BindType);_nbind.StringType=StringType;function makeArgList(t){return Array.apply(null,Array(t)).map(function(e,r){return\"a\"+(r+1)})}function anyNeedsWireWrite(t,e){return t.reduce(function(r,o){return r||o.needsWireWrite(e)},!1)}function anyNeedsWireRead(t,e){return t.reduce(function(r,o){return r||!!o.needsWireRead(e)},!1)}function makeWireRead(t,e,r,o){var a=t.length;return r.makeWireRead?r.makeWireRead(o,t,a):r.wireRead?(t[a]=r.wireRead,\"(convertParamList[\"+a+\"](\"+o+\"))\"):o}function makeWireWrite(t,e,r,o){var a,n=t.length;return r.makeWireWrite?a=r.makeWireWrite(o,e,t,n):a=r.wireWrite,a?typeof a==\"string\"?a:(t[n]=a,\"(convertParamList[\"+n+\"](\"+o+\"))\"):o}function buildCallerFunction(dynCall,ptrType,ptr,num,policyTbl,needsWireWrite,prefix,returnType,argTypeList,mask,err){var argList=makeArgList(argTypeList.length),convertParamList=[],callExpression=makeWireRead(convertParamList,policyTbl,returnType,\"dynCall(\"+[prefix].concat(argList.map(function(t,e){return makeWireWrite(convertParamList,policyTbl,argTypeList[e],t)})).join(\",\")+\")\"),resourceSet=_nbind.listResources([returnType],argTypeList),sourceCode=\"function(\"+argList.join(\",\")+\"){\"+(mask?\"this.__nbindFlags&mask&&err();\":\"\")+resourceSet.makeOpen()+\"var r=\"+callExpression+\";\"+resourceSet.makeClose()+\"return r;}\";return eval(\"(\"+sourceCode+\")\")}function buildJSCallerFunction(returnType,argTypeList){var argList=makeArgList(argTypeList.length),convertParamList=[],callExpression=makeWireWrite(convertParamList,null,returnType,\"_nbind.externalList[num].data(\"+argList.map(function(t,e){return makeWireRead(convertParamList,null,argTypeList[e],t)}).join(\",\")+\")\"),resourceSet=_nbind.listResources(argTypeList,[returnType]);resourceSet.remove(_nbind.resources.pool);var sourceCode=\"function(\"+[\"dummy\",\"num\"].concat(argList).join(\",\")+\"){\"+resourceSet.makeOpen()+\"var r=\"+callExpression+\";\"+resourceSet.makeClose()+\"return r;}\";return eval(\"(\"+sourceCode+\")\")}_nbind.buildJSCallerFunction=buildJSCallerFunction;function makeJSCaller(t){var e=t.length-1,r=_nbind.getTypes(t,\"callback\"),o=r[0],a=r.slice(1),n=anyNeedsWireRead(a,null),u=o.needsWireWrite(null);if(!u&&!n)switch(e){case 0:return function(A,p){return _nbind.externalList[p].data()};case 1:return function(A,p,h){return _nbind.externalList[p].data(h)};case 2:return function(A,p,h,E){return _nbind.externalList[p].data(h,E)};case 3:return function(A,p,h,E,I){return _nbind.externalList[p].data(h,E,I)};default:break}return buildJSCallerFunction(o,a)}_nbind.makeJSCaller=makeJSCaller;function makeMethodCaller(t,e){var r=e.typeList.length-1,o=e.typeList.slice(0);o.splice(1,0,\"uint32_t\",e.boundID);var a=_nbind.getTypes(o,e.title),n=a[0],u=a.slice(3),A=n.needsWireRead(e.policyTbl),p=anyNeedsWireWrite(u,e.policyTbl),h=e.ptr,E=e.num,I=_nbind.getDynCall(a,e.title),v=~e.flags&1;function x(){throw new Error(\"Calling a non-const method on a const object\")}if(!A&&!p)switch(r){case 0:return function(){return this.__nbindFlags&v?x():I(h,E,_nbind.pushPointer(this,t))};case 1:return function(C){return this.__nbindFlags&v?x():I(h,E,_nbind.pushPointer(this,t),C)};case 2:return function(C,R){return this.__nbindFlags&v?x():I(h,E,_nbind.pushPointer(this,t),C,R)};case 3:return function(C,R,L){return this.__nbindFlags&v?x():I(h,E,_nbind.pushPointer(this,t),C,R,L)};default:break}return buildCallerFunction(I,t,h,E,e.policyTbl,p,\"ptr,num,pushPointer(this,ptrType)\",n,u,v,x)}_nbind.makeMethodCaller=makeMethodCaller;function makeCaller(t){var e=t.typeList.length-1,r=_nbind.getTypes(t.typeList,t.title),o=r[0],a=r.slice(1),n=o.needsWireRead(t.policyTbl),u=anyNeedsWireWrite(a,t.policyTbl),A=t.direct,p=t.ptr;if(t.direct&&!n&&!u){var h=_nbind.getDynCall(r,t.title);switch(e){case 0:return function(){return h(A)};case 1:return function(x){return h(A,x)};case 2:return function(x,C){return h(A,x,C)};case 3:return function(x,C,R){return h(A,x,C,R)};default:break}p=0}var E;if(p){var I=t.typeList.slice(0);I.splice(1,0,\"uint32_t\"),r=_nbind.getTypes(I,t.title),E=\"ptr,num\"}else p=A,E=\"ptr\";var v=_nbind.getDynCall(r,t.title);return buildCallerFunction(v,null,p,t.num,t.policyTbl,u,E,o,a)}_nbind.makeCaller=makeCaller;function makeOverloader(t,e){var r=[];function o(){return r[arguments.length].apply(this,arguments)}return o.addMethod=function(a,n){r[n]=a},o.addMethod(t,e),o}_nbind.makeOverloader=makeOverloader;var Resource=function(){function t(e,r){var o=this;this.makeOpen=function(){return Object.keys(o.openTbl).join(\"\")},this.makeClose=function(){return Object.keys(o.closeTbl).join(\"\")},this.openTbl={},this.closeTbl={},e&&(this.openTbl[e]=!0),r&&(this.closeTbl[r]=!0)}return t.prototype.add=function(e){for(var r=0,o=Object.keys(e.openTbl);r<o.length;r++){var a=o[r];this.openTbl[a]=!0}for(var n=0,u=Object.keys(e.closeTbl);n<u.length;n++){var a=u[n];this.closeTbl[a]=!0}},t.prototype.remove=function(e){for(var r=0,o=Object.keys(e.openTbl);r<o.length;r++){var a=o[r];delete this.openTbl[a]}for(var n=0,u=Object.keys(e.closeTbl);n<u.length;n++){var a=u[n];delete this.closeTbl[a]}},t}();_nbind.Resource=Resource;function listResources(t,e){for(var r=new Resource,o=0,a=t;o<a.length;o++)for(var n=a[o],u=0,A=n.readResources||[];u<A.length;u++){var p=A[u];r.add(p)}for(var h=0,E=e;h<E.length;h++)for(var n=E[h],I=0,v=n.writeResources||[];I<v.length;I++){var p=v[I];r.add(p)}return r}_nbind.listResources=listResources,_nbind.resources={pool:new Resource(\"var used=HEAPU32[_nbind.Pool.usedPtr],page=HEAPU32[_nbind.Pool.pagePtr];\",\"_nbind.Pool.lreset(used,page);\")};var ExternalBuffer=function(t){__extends(e,t);function e(r,o){var a=t.call(this,r)||this;return a.ptr=o,a}return e.prototype.free=function(){_free(this.ptr)},e}(_nbind.External);function getBuffer(t){return t instanceof ArrayBuffer?new Uint8Array(t):t instanceof DataView?new Uint8Array(t.buffer,t.byteOffset,t.byteLength):t}function pushBuffer(t,e){if(t==null&&e&&e.Nullable&&(t=[]),typeof t!=\"object\")throw new Error(\"Type mismatch\");var r=t,o=r.byteLength||r.length;if(!o&&o!==0&&r.byteLength!==0)throw new Error(\"Type mismatch\");var a=_nbind.Pool.lalloc(8),n=_malloc(o),u=a/4;return HEAPU32[u++]=o,HEAPU32[u++]=n,HEAPU32[u++]=new ExternalBuffer(t,n).register(),HEAPU8.set(getBuffer(t),n),a}var BufferType=function(t){__extends(e,t);function e(){var r=t!==null&&t.apply(this,arguments)||this;return r.wireWrite=pushBuffer,r.readResources=[_nbind.resources.pool],r.writeResources=[_nbind.resources.pool],r}return e.prototype.makeWireWrite=function(r,o){return function(a){return pushBuffer(a,o)}},e}(_nbind.BindType);_nbind.BufferType=BufferType;function commitBuffer(t,e,r){var o=_nbind.externalList[t].data,a=Buffer;if(typeof Buffer!=\"function\"&&(a=function(){}),!(o instanceof Array)){var n=HEAPU8.subarray(e,e+r);if(o instanceof a){var u=void 0;typeof Buffer.from==\"function\"&&Buffer.from.length>=3?u=Buffer.from(n):u=new Buffer(n),u.copy(o)}else getBuffer(o).set(n)}}_nbind.commitBuffer=commitBuffer;var dirtyList=[],gcTimer=0;function sweep(){for(var t=0,e=dirtyList;t<e.length;t++){var r=e[t];r.__nbindState&3||r.free()}dirtyList=[],gcTimer=0}_nbind.mark=function(t){};function toggleLightGC(t){t?_nbind.mark=function(e){dirtyList.push(e),gcTimer||(gcTimer=setTimeout(sweep,0))}:_nbind.mark=function(e){}}_nbind.toggleLightGC=toggleLightGC}(_nbind),Module.requestFullScreen=function t(e,r,o){Module.printErr(\"Module.requestFullScreen is deprecated. Please call Module.requestFullscreen instead.\"),Module.requestFullScreen=Module.requestFullscreen,Browser.requestFullScreen(e,r,o)},Module.requestFullscreen=function t(e,r,o){Browser.requestFullscreen(e,r,o)},Module.requestAnimationFrame=function t(e){Browser.requestAnimationFrame(e)},Module.setCanvasSize=function t(e,r,o){Browser.setCanvasSize(e,r,o)},Module.pauseMainLoop=function t(){Browser.mainLoop.pause()},Module.resumeMainLoop=function t(){Browser.mainLoop.resume()},Module.getUserMedia=function t(){Browser.getUserMedia()},Module.createContext=function t(e,r,o,a){return Browser.createContext(e,r,o,a)},ENVIRONMENT_IS_NODE?_emscripten_get_now=function(){var e=process.hrtime();return e[0]*1e3+e[1]/1e6}:typeof dateNow<\"u\"?_emscripten_get_now=dateNow:typeof self==\"object\"&&self.performance&&typeof self.performance.now==\"function\"?_emscripten_get_now=function(){return self.performance.now()}:typeof performance==\"object\"&&typeof performance.now==\"function\"?_emscripten_get_now=function(){return performance.now()}:_emscripten_get_now=Date.now,__ATEXIT__.push(function(){var t=Module._fflush;t&&t(0);var e=___syscall146.printChar;if(e){var r=___syscall146.buffers;r[1].length&&e(1,10),r[2].length&&e(2,10)}}),DYNAMICTOP_PTR=allocate(1,\"i32\",ALLOC_STATIC),STACK_BASE=STACKTOP=Runtime.alignMemory(STATICTOP),STACK_MAX=STACK_BASE+TOTAL_STACK,DYNAMIC_BASE=Runtime.alignMemory(STACK_MAX),HEAP32[DYNAMICTOP_PTR>>2]=DYNAMIC_BASE,staticSealed=!0;function invoke_viiiii(t,e,r,o,a,n){try{Module.dynCall_viiiii(t,e,r,o,a,n)}catch(u){if(typeof u!=\"number\"&&u!==\"longjmp\")throw u;Module.setThrew(1,0)}}function invoke_vif(t,e,r){try{Module.dynCall_vif(t,e,r)}catch(o){if(typeof o!=\"number\"&&o!==\"longjmp\")throw o;Module.setThrew(1,0)}}function invoke_vid(t,e,r){try{Module.dynCall_vid(t,e,r)}catch(o){if(typeof o!=\"number\"&&o!==\"longjmp\")throw o;Module.setThrew(1,0)}}function invoke_fiff(t,e,r,o){try{return Module.dynCall_fiff(t,e,r,o)}catch(a){if(typeof a!=\"number\"&&a!==\"longjmp\")throw a;Module.setThrew(1,0)}}function invoke_vi(t,e){try{Module.dynCall_vi(t,e)}catch(r){if(typeof r!=\"number\"&&r!==\"longjmp\")throw r;Module.setThrew(1,0)}}function invoke_vii(t,e,r){try{Module.dynCall_vii(t,e,r)}catch(o){if(typeof o!=\"number\"&&o!==\"longjmp\")throw o;Module.setThrew(1,0)}}function invoke_ii(t,e){try{return Module.dynCall_ii(t,e)}catch(r){if(typeof r!=\"number\"&&r!==\"longjmp\")throw r;Module.setThrew(1,0)}}function invoke_viddi(t,e,r,o,a){try{Module.dynCall_viddi(t,e,r,o,a)}catch(n){if(typeof n!=\"number\"&&n!==\"longjmp\")throw n;Module.setThrew(1,0)}}function invoke_vidd(t,e,r,o){try{Module.dynCall_vidd(t,e,r,o)}catch(a){if(typeof a!=\"number\"&&a!==\"longjmp\")throw a;Module.setThrew(1,0)}}function invoke_iiii(t,e,r,o){try{return Module.dynCall_iiii(t,e,r,o)}catch(a){if(typeof a!=\"number\"&&a!==\"longjmp\")throw a;Module.setThrew(1,0)}}function invoke_diii(t,e,r,o){try{return Module.dynCall_diii(t,e,r,o)}catch(a){if(typeof a!=\"number\"&&a!==\"longjmp\")throw a;Module.setThrew(1,0)}}function invoke_di(t,e){try{return Module.dynCall_di(t,e)}catch(r){if(typeof r!=\"number\"&&r!==\"longjmp\")throw r;Module.setThrew(1,0)}}function invoke_iid(t,e,r){try{return Module.dynCall_iid(t,e,r)}catch(o){if(typeof o!=\"number\"&&o!==\"longjmp\")throw o;Module.setThrew(1,0)}}function invoke_iii(t,e,r){try{return Module.dynCall_iii(t,e,r)}catch(o){if(typeof o!=\"number\"&&o!==\"longjmp\")throw o;Module.setThrew(1,0)}}function invoke_viiddi(t,e,r,o,a,n){try{Module.dynCall_viiddi(t,e,r,o,a,n)}catch(u){if(typeof u!=\"number\"&&u!==\"longjmp\")throw u;Module.setThrew(1,0)}}function invoke_viiiiii(t,e,r,o,a,n,u){try{Module.dynCall_viiiiii(t,e,r,o,a,n,u)}catch(A){if(typeof A!=\"number\"&&A!==\"longjmp\")throw A;Module.setThrew(1,0)}}function invoke_dii(t,e,r){try{return Module.dynCall_dii(t,e,r)}catch(o){if(typeof o!=\"number\"&&o!==\"longjmp\")throw o;Module.setThrew(1,0)}}function invoke_i(t){try{return Module.dynCall_i(t)}catch(e){if(typeof e!=\"number\"&&e!==\"longjmp\")throw e;Module.setThrew(1,0)}}function invoke_iiiiii(t,e,r,o,a,n){try{return Module.dynCall_iiiiii(t,e,r,o,a,n)}catch(u){if(typeof u!=\"number\"&&u!==\"longjmp\")throw u;Module.setThrew(1,0)}}function invoke_viiid(t,e,r,o,a){try{Module.dynCall_viiid(t,e,r,o,a)}catch(n){if(typeof n!=\"number\"&&n!==\"longjmp\")throw n;Module.setThrew(1,0)}}function invoke_viififi(t,e,r,o,a,n,u){try{Module.dynCall_viififi(t,e,r,o,a,n,u)}catch(A){if(typeof A!=\"number\"&&A!==\"longjmp\")throw A;Module.setThrew(1,0)}}function invoke_viii(t,e,r,o){try{Module.dynCall_viii(t,e,r,o)}catch(a){if(typeof a!=\"number\"&&a!==\"longjmp\")throw a;Module.setThrew(1,0)}}function invoke_v(t){try{Module.dynCall_v(t)}catch(e){if(typeof e!=\"number\"&&e!==\"longjmp\")throw e;Module.setThrew(1,0)}}function invoke_viid(t,e,r,o){try{Module.dynCall_viid(t,e,r,o)}catch(a){if(typeof a!=\"number\"&&a!==\"longjmp\")throw a;Module.setThrew(1,0)}}function invoke_idd(t,e,r){try{return Module.dynCall_idd(t,e,r)}catch(o){if(typeof o!=\"number\"&&o!==\"longjmp\")throw o;Module.setThrew(1,0)}}function invoke_viiii(t,e,r,o,a){try{Module.dynCall_viiii(t,e,r,o,a)}catch(n){if(typeof n!=\"number\"&&n!==\"longjmp\")throw n;Module.setThrew(1,0)}}Module.asmGlobalArg={Math,Int8Array,Int16Array,Int32Array,Uint8Array,Uint16Array,Uint32Array,Float32Array,Float64Array,NaN:NaN,Infinity:1/0},Module.asmLibraryArg={abort,assert,enlargeMemory,getTotalMemory,abortOnCannotGrowMemory,invoke_viiiii,invoke_vif,invoke_vid,invoke_fiff,invoke_vi,invoke_vii,invoke_ii,invoke_viddi,invoke_vidd,invoke_iiii,invoke_diii,invoke_di,invoke_iid,invoke_iii,invoke_viiddi,invoke_viiiiii,invoke_dii,invoke_i,invoke_iiiiii,invoke_viiid,invoke_viififi,invoke_viii,invoke_v,invoke_viid,invoke_idd,invoke_viiii,_emscripten_asm_const_iiiii,_emscripten_asm_const_iiidddddd,_emscripten_asm_const_iiiid,__nbind_reference_external,_emscripten_asm_const_iiiiiiii,_removeAccessorPrefix,_typeModule,__nbind_register_pool,__decorate,_llvm_stackrestore,___cxa_atexit,__extends,__nbind_get_value_object,__ZN8facebook4yoga14YGNodeToStringEPNSt3__212basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEP6YGNode14YGPrintOptionsj,_emscripten_set_main_loop_timing,__nbind_register_primitive,__nbind_register_type,_emscripten_memcpy_big,__nbind_register_function,___setErrNo,__nbind_register_class,__nbind_finish,_abort,_nbind_value,_llvm_stacksave,___syscall54,_defineHidden,_emscripten_set_main_loop,_emscripten_get_now,__nbind_register_callback_signature,_emscripten_asm_const_iiiiii,__nbind_free_external,_emscripten_asm_const_iiii,_emscripten_asm_const_iiididi,___syscall6,_atexit,___syscall140,___syscall146,DYNAMICTOP_PTR,tempDoublePtr,ABORT,STACKTOP,STACK_MAX,cttz_i8,___dso_handle};var asm=function(t,e,r){var o=new t.Int8Array(r),a=new t.Int16Array(r),n=new t.Int32Array(r),u=new t.Uint8Array(r),A=new t.Uint16Array(r),p=new t.Uint32Array(r),h=new t.Float32Array(r),E=new t.Float64Array(r),I=e.DYNAMICTOP_PTR|0,v=e.tempDoublePtr|0,x=e.ABORT|0,C=e.STACKTOP|0,R=e.STACK_MAX|0,L=e.cttz_i8|0,U=e.___dso_handle|0,z=0,te=0,ae=0,le=0,ce=t.NaN,Ce=t.Infinity,de=0,Be=0,Ee=0,g=0,me=0,we=0,Ae=t.Math.floor,ne=t.Math.abs,Z=t.Math.sqrt,xe=t.Math.pow,Ne=t.Math.cos,ht=t.Math.sin,H=t.Math.tan,rt=t.Math.acos,Te=t.Math.asin,Fe=t.Math.atan,ke=t.Math.atan2,Ye=t.Math.exp,be=t.Math.log,et=t.Math.ceil,Ue=t.Math.imul,S=t.Math.min,w=t.Math.max,b=t.Math.clz32,y=t.Math.fround,F=e.abort,J=e.assert,X=e.enlargeMemory,$=e.getTotalMemory,ie=e.abortOnCannotGrowMemory,Se=e.invoke_viiiii,Re=e.invoke_vif,at=e.invoke_vid,dt=e.invoke_fiff,jt=e.invoke_vi,tr=e.invoke_vii,bt=e.invoke_ii,ln=e.invoke_viddi,kr=e.invoke_vidd,mr=e.invoke_iiii,Sr=e.invoke_diii,Kr=e.invoke_di,Kn=e.invoke_iid,Ms=e.invoke_iii,Ri=e.invoke_viiddi,gs=e.invoke_viiiiii,io=e.invoke_dii,Pi=e.invoke_i,Os=e.invoke_iiiiii,so=e.invoke_viiid,uc=e.invoke_viififi,Au=e.invoke_viii,sp=e.invoke_v,op=e.invoke_viid,Us=e.invoke_idd,Dn=e.invoke_viiii,oo=e._emscripten_asm_const_iiiii,_s=e._emscripten_asm_const_iiidddddd,ml=e._emscripten_asm_const_iiiid,yl=e.__nbind_reference_external,ao=e._emscripten_asm_const_iiiiiiii,Vn=e._removeAccessorPrefix,Mn=e._typeModule,Ti=e.__nbind_register_pool,On=e.__decorate,_i=e._llvm_stackrestore,ir=e.___cxa_atexit,Me=e.__extends,ii=e.__nbind_get_value_object,Ha=e.__ZN8facebook4yoga14YGNodeToStringEPNSt3__212basic_stringIcNS1_11char_traitsIcEENS1_9allocatorIcEEEEP6YGNode14YGPrintOptionsj,hr=e._emscripten_set_main_loop_timing,Ac=e.__nbind_register_primitive,fu=e.__nbind_register_type,fc=e._emscripten_memcpy_big,El=e.__nbind_register_function,vA=e.___setErrNo,pu=e.__nbind_register_class,Ie=e.__nbind_finish,Tt=e._abort,pc=e._nbind_value,Hi=e._llvm_stacksave,hu=e.___syscall54,Yt=e._defineHidden,Cl=e._emscripten_set_main_loop,DA=e._emscripten_get_now,ap=e.__nbind_register_callback_signature,hc=e._emscripten_asm_const_iiiiii,PA=e.__nbind_free_external,Qn=e._emscripten_asm_const_iiii,hi=e._emscripten_asm_const_iiididi,gc=e.___syscall6,bA=e._atexit,aa=e.___syscall140,Ni=e.___syscall146,_o=y(0);let Xe=y(0);function lo(s){s=s|0;var l=0;return l=C,C=C+s|0,C=C+15&-16,l|0}function dc(){return C|0}function gu(s){s=s|0,C=s}function qi(s,l){s=s|0,l=l|0,C=s,R=l}function du(s,l){s=s|0,l=l|0,z||(z=s,te=l)}function SA(s){s=s|0,we=s}function qa(){return we|0}function mc(){var s=0,l=0;Dr(8104,8,400)|0,Dr(8504,408,540)|0,s=9044,l=s+44|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));o[9088]=0,o[9089]=1,n[2273]=0,n[2274]=948,n[2275]=948,ir(17,8104,U|0)|0}function ds(s){s=s|0,ft(s+948|0)}function Ht(s){return s=y(s),((bu(s)|0)&2147483647)>>>0>2139095040|0}function Fn(s,l,c){s=s|0,l=l|0,c=c|0;e:do if(n[s+(l<<3)+4>>2]|0)s=s+(l<<3)|0;else{if((l|2|0)==3&&n[s+60>>2]|0){s=s+56|0;break}switch(l|0){case 0:case 2:case 4:case 5:{if(n[s+52>>2]|0){s=s+48|0;break e}break}default:}if(n[s+68>>2]|0){s=s+64|0;break}else{s=(l|1|0)==5?948:c;break}}while(!1);return s|0}function Ei(s){s=s|0;var l=0;return l=Jv(1e3)|0,la(s,(l|0)!=0,2456),n[2276]=(n[2276]|0)+1,Dr(l|0,8104,1e3)|0,o[s+2>>0]|0&&(n[l+4>>2]=2,n[l+12>>2]=4),n[l+976>>2]=s,l|0}function la(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0;d=C,C=C+16|0,f=d,l||(n[f>>2]=c,g0(s,5,3197,f)),C=d}function co(){return Ei(956)|0}function Hs(s){s=s|0;var l=0;return l=Kt(1e3)|0,ca(l,s),la(n[s+976>>2]|0,1,2456),n[2276]=(n[2276]|0)+1,n[l+944>>2]=0,l|0}function ca(s,l){s=s|0,l=l|0;var c=0;Dr(s|0,l|0,948)|0,Cd(s+948|0,l+948|0),c=s+960|0,s=l+960|0,l=c+40|0;do n[c>>2]=n[s>>2],c=c+4|0,s=s+4|0;while((c|0)<(l|0))}function ua(s){s=s|0;var l=0,c=0,f=0,d=0;if(l=s+944|0,c=n[l>>2]|0,c|0&&(Ho(c+948|0,s)|0,n[l>>2]=0),c=Ci(s)|0,c|0){l=0;do n[(ms(s,l)|0)+944>>2]=0,l=l+1|0;while((l|0)!=(c|0))}c=s+948|0,f=n[c>>2]|0,d=s+952|0,l=n[d>>2]|0,(l|0)!=(f|0)&&(n[d>>2]=l+(~((l+-4-f|0)>>>2)<<2)),ys(c),Xv(s),n[2276]=(n[2276]|0)+-1}function Ho(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0;f=n[s>>2]|0,k=s+4|0,c=n[k>>2]|0,m=c;e:do if((f|0)==(c|0))d=f,B=4;else for(s=f;;){if((n[s>>2]|0)==(l|0)){d=s,B=4;break e}if(s=s+4|0,(s|0)==(c|0)){s=0;break}}while(!1);return(B|0)==4&&((d|0)!=(c|0)?(f=d+4|0,s=m-f|0,l=s>>2,l&&(ww(d|0,f|0,s|0)|0,c=n[k>>2]|0),s=d+(l<<2)|0,(c|0)==(s|0)||(n[k>>2]=c+(~((c+-4-s|0)>>>2)<<2)),s=1):s=0),s|0}function Ci(s){return s=s|0,(n[s+952>>2]|0)-(n[s+948>>2]|0)>>2|0}function ms(s,l){s=s|0,l=l|0;var c=0;return c=n[s+948>>2]|0,(n[s+952>>2]|0)-c>>2>>>0>l>>>0?s=n[c+(l<<2)>>2]|0:s=0,s|0}function ys(s){s=s|0;var l=0,c=0,f=0,d=0;f=C,C=C+32|0,l=f,d=n[s>>2]|0,c=(n[s+4>>2]|0)-d|0,((n[s+8>>2]|0)-d|0)>>>0>c>>>0&&(d=c>>2,Ep(l,d,d,s+8|0),E0(s,l),UA(l)),C=f}function Es(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0;O=Ci(s)|0;do if(O|0){if((n[(ms(s,0)|0)+944>>2]|0)==(s|0)){if(!(Ho(s+948|0,l)|0))break;Dr(l+400|0,8504,540)|0,n[l+944>>2]=0,Le(s);break}B=n[(n[s+976>>2]|0)+12>>2]|0,k=s+948|0,Q=(B|0)==0,c=0,m=0;do f=n[(n[k>>2]|0)+(m<<2)>>2]|0,(f|0)==(l|0)?Le(s):(d=Hs(f)|0,n[(n[k>>2]|0)+(c<<2)>>2]=d,n[d+944>>2]=s,Q||BR[B&15](f,d,s,c),c=c+1|0),m=m+1|0;while((m|0)!=(O|0));if(c>>>0<O>>>0){Q=s+948|0,k=s+952|0,B=c,c=n[k>>2]|0;do m=(n[Q>>2]|0)+(B<<2)|0,f=m+4|0,d=c-f|0,l=d>>2,l&&(ww(m|0,f|0,d|0)|0,c=n[k>>2]|0),d=c,f=m+(l<<2)|0,(d|0)!=(f|0)&&(c=d+(~((d+-4-f|0)>>>2)<<2)|0,n[k>>2]=c),B=B+1|0;while((B|0)!=(O|0))}}while(!1)}function qs(s){s=s|0;var l=0,c=0,f=0,d=0;Un(s,(Ci(s)|0)==0,2491),Un(s,(n[s+944>>2]|0)==0,2545),l=s+948|0,c=n[l>>2]|0,f=s+952|0,d=n[f>>2]|0,(d|0)!=(c|0)&&(n[f>>2]=d+(~((d+-4-c|0)>>>2)<<2)),ys(l),l=s+976|0,c=n[l>>2]|0,Dr(s|0,8104,1e3)|0,o[c+2>>0]|0&&(n[s+4>>2]=2,n[s+12>>2]=4),n[l>>2]=c}function Un(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0;d=C,C=C+16|0,f=d,l||(n[f>>2]=c,Ao(s,5,3197,f)),C=d}function Pn(){return n[2276]|0}function Cs(){var s=0;return s=Jv(20)|0,We((s|0)!=0,2592),n[2277]=(n[2277]|0)+1,n[s>>2]=n[239],n[s+4>>2]=n[240],n[s+8>>2]=n[241],n[s+12>>2]=n[242],n[s+16>>2]=n[243],s|0}function We(s,l){s=s|0,l=l|0;var c=0,f=0;f=C,C=C+16|0,c=f,s||(n[c>>2]=l,Ao(0,5,3197,c)),C=f}function tt(s){s=s|0,Xv(s),n[2277]=(n[2277]|0)+-1}function Bt(s,l){s=s|0,l=l|0;var c=0;l?(Un(s,(Ci(s)|0)==0,2629),c=1):(c=0,l=0),n[s+964>>2]=l,n[s+988>>2]=c}function or(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;f=C,C=C+16|0,m=f+8|0,d=f+4|0,B=f,n[d>>2]=l,Un(s,(n[l+944>>2]|0)==0,2709),Un(s,(n[s+964>>2]|0)==0,2763),ee(s),l=s+948|0,n[B>>2]=(n[l>>2]|0)+(c<<2),n[m>>2]=n[B>>2],ye(l,m,d)|0,n[(n[d>>2]|0)+944>>2]=s,Le(s),C=f}function ee(s){s=s|0;var l=0,c=0,f=0,d=0,m=0,B=0,k=0;if(c=Ci(s)|0,c|0&&(n[(ms(s,0)|0)+944>>2]|0)!=(s|0)){f=n[(n[s+976>>2]|0)+12>>2]|0,d=s+948|0,m=(f|0)==0,l=0;do B=n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,f=se+12|0,Je=n[m>>2]|0,n[m>>2]=n[f>>2],n[f>>2]=Je,UA(se),f=n[M>>2]|0;break}m=f,B=((m-d>>2)+1|0)/-2|0,k=f+(B<<2)|0,d=Q-m|0,m=d>>2,m&&(ww(k|0,f|0,d|0)|0,f=n[O>>2]|0),Je=k+(m<<2)|0,n[M>>2]=Je,n[O>>2]=f+(B<<2),f=Je}while(!1);n[f>>2]=n[c>>2],n[M>>2]=(n[M>>2]|0)+4,l=C0(s,Qe,l)|0,UA(Qe)}while(!1);return C=$e,l|0}function Le(s){s=s|0;var l=0;do{if(l=s+984|0,o[l>>0]|0)break;o[l>>0]=1,h[s+504>>2]=y(ce),s=n[s+944>>2]|0}while(s|0)}function ft(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-4-f|0)>>>2)<<2)),gt(c))}function pt(s){return s=s|0,n[s+944>>2]|0}function Nt(s){s=s|0,Un(s,(n[s+964>>2]|0)!=0,2832),Le(s)}function rr(s){return s=s|0,(o[s+984>>0]|0)!=0|0}function $r(s,l){s=s|0,l=l|0,TUe(s,l,400)|0&&(Dr(s|0,l|0,400)|0,Le(s))}function ji(s){s=s|0;var l=Xe;return l=y(h[s+44>>2]),s=Ht(l)|0,y(s?y(0):l)}function rs(s){s=s|0;var l=Xe;return l=y(h[s+48>>2]),Ht(l)|0&&(l=o[(n[s+976>>2]|0)+2>>0]|0?y(1):y(0)),y(l)}function bi(s,l){s=s|0,l=l|0,n[s+980>>2]=l}function qo(s){return s=s|0,n[s+980>>2]|0}function xA(s,l){s=s|0,l=l|0;var c=0;c=s+4|0,(n[c>>2]|0)!=(l|0)&&(n[c>>2]=l,Le(s))}function kA(s){return s=s|0,n[s+4>>2]|0}function lp(s,l){s=s|0,l=l|0;var c=0;c=s+8|0,(n[c>>2]|0)!=(l|0)&&(n[c>>2]=l,Le(s))}function e0(s){return s=s|0,n[s+8>>2]|0}function mu(s,l){s=s|0,l=l|0;var c=0;c=s+12|0,(n[c>>2]|0)!=(l|0)&&(n[c>>2]=l,Le(s))}function t0(s){return s=s|0,n[s+12>>2]|0}function yu(s,l){s=s|0,l=l|0;var c=0;c=s+16|0,(n[c>>2]|0)!=(l|0)&&(n[c>>2]=l,Le(s))}function uo(s){return s=s|0,n[s+16>>2]|0}function QA(s,l){s=s|0,l=l|0;var c=0;c=s+20|0,(n[c>>2]|0)!=(l|0)&&(n[c>>2]=l,Le(s))}function yc(s){return s=s|0,n[s+20>>2]|0}function Aa(s,l){s=s|0,l=l|0;var c=0;c=s+24|0,(n[c>>2]|0)!=(l|0)&&(n[c>>2]=l,Le(s))}function r0(s){return s=s|0,n[s+24>>2]|0}function Ec(s,l){s=s|0,l=l|0;var c=0;c=s+28|0,(n[c>>2]|0)!=(l|0)&&(n[c>>2]=l,Le(s))}function hd(s){return s=s|0,n[s+28>>2]|0}function n0(s,l){s=s|0,l=l|0;var c=0;c=s+32|0,(n[c>>2]|0)!=(l|0)&&(n[c>>2]=l,Le(s))}function $n(s){return s=s|0,n[s+32>>2]|0}function cp(s,l){s=s|0,l=l|0;var c=0;c=s+36|0,(n[c>>2]|0)!=(l|0)&&(n[c>>2]=l,Le(s))}function i0(s){return s=s|0,n[s+36>>2]|0}function FA(s,l){s=s|0,l=y(l);var c=0;c=s+40|0,y(h[c>>2])!=l&&(h[c>>2]=l,Le(s))}function js(s,l){s=s|0,l=y(l);var c=0;c=s+44|0,y(h[c>>2])!=l&&(h[c>>2]=l,Le(s))}function Eu(s,l){s=s|0,l=y(l);var c=0;c=s+48|0,y(h[c>>2])!=l&&(h[c>>2]=l,Le(s))}function ja(s,l){s=s|0,l=y(l);var c=0,f=0,d=0,m=0;m=Ht(l)|0,c=(m^1)&1,f=s+52|0,d=s+56|0,m|y(h[f>>2])==l&&(n[d>>2]|0)==(c|0)||(h[f>>2]=l,n[d>>2]=c,Le(s))}function Gi(s,l){s=s|0,l=y(l);var c=0,f=0;f=s+52|0,c=s+56|0,y(h[f>>2])==l&&(n[c>>2]|0)==2||(h[f>>2]=l,f=Ht(l)|0,n[c>>2]=f?3:2,Le(s))}function fa(s,l){s=s|0,l=l|0;var c=0,f=0;f=l+52|0,c=n[f+4>>2]|0,l=s,n[l>>2]=n[f>>2],n[l+4>>2]=c}function Cu(s,l,c){s=s|0,l=l|0,c=y(c);var f=0,d=0,m=0;m=Ht(c)|0,f=(m^1)&1,d=s+132+(l<<3)|0,l=s+132+(l<<3)+4|0,m|y(h[d>>2])==c&&(n[l>>2]|0)==(f|0)||(h[d>>2]=c,n[l>>2]=f,Le(s))}function ws(s,l,c){s=s|0,l=l|0,c=y(c);var f=0,d=0,m=0;m=Ht(c)|0,f=m?0:2,d=s+132+(l<<3)|0,l=s+132+(l<<3)+4|0,m|y(h[d>>2])==c&&(n[l>>2]|0)==(f|0)||(h[d>>2]=c,n[l>>2]=f,Le(s))}function Cc(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=l+132+(c<<3)|0,l=n[f+4>>2]|0,c=s,n[c>>2]=n[f>>2],n[c+4>>2]=l}function wc(s,l,c){s=s|0,l=l|0,c=y(c);var f=0,d=0,m=0;m=Ht(c)|0,f=(m^1)&1,d=s+60+(l<<3)|0,l=s+60+(l<<3)+4|0,m|y(h[d>>2])==c&&(n[l>>2]|0)==(f|0)||(h[d>>2]=c,n[l>>2]=f,Le(s))}function Y(s,l,c){s=s|0,l=l|0,c=y(c);var f=0,d=0,m=0;m=Ht(c)|0,f=m?0:2,d=s+60+(l<<3)|0,l=s+60+(l<<3)+4|0,m|y(h[d>>2])==c&&(n[l>>2]|0)==(f|0)||(h[d>>2]=c,n[l>>2]=f,Le(s))}function Dt(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=l+60+(c<<3)|0,l=n[f+4>>2]|0,c=s,n[c>>2]=n[f>>2],n[c+4>>2]=l}function wl(s,l){s=s|0,l=l|0;var c=0;c=s+60+(l<<3)+4|0,(n[c>>2]|0)!=3&&(h[s+60+(l<<3)>>2]=y(ce),n[c>>2]=3,Le(s))}function Si(s,l,c){s=s|0,l=l|0,c=y(c);var f=0,d=0,m=0;m=Ht(c)|0,f=(m^1)&1,d=s+204+(l<<3)|0,l=s+204+(l<<3)+4|0,m|y(h[d>>2])==c&&(n[l>>2]|0)==(f|0)||(h[d>>2]=c,n[l>>2]=f,Le(s))}function Ic(s,l,c){s=s|0,l=l|0,c=y(c);var f=0,d=0,m=0;m=Ht(c)|0,f=m?0:2,d=s+204+(l<<3)|0,l=s+204+(l<<3)+4|0,m|y(h[d>>2])==c&&(n[l>>2]|0)==(f|0)||(h[d>>2]=c,n[l>>2]=f,Le(s))}function ct(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=l+204+(c<<3)|0,l=n[f+4>>2]|0,c=s,n[c>>2]=n[f>>2],n[c+4>>2]=l}function wu(s,l,c){s=s|0,l=l|0,c=y(c);var f=0,d=0,m=0;m=Ht(c)|0,f=(m^1)&1,d=s+276+(l<<3)|0,l=s+276+(l<<3)+4|0,m|y(h[d>>2])==c&&(n[l>>2]|0)==(f|0)||(h[d>>2]=c,n[l>>2]=f,Le(s))}function s0(s,l){return s=s|0,l=l|0,y(h[s+276+(l<<3)>>2])}function tw(s,l){s=s|0,l=y(l);var c=0,f=0,d=0,m=0;m=Ht(l)|0,c=(m^1)&1,f=s+348|0,d=s+352|0,m|y(h[f>>2])==l&&(n[d>>2]|0)==(c|0)||(h[f>>2]=l,n[d>>2]=c,Le(s))}function RA(s,l){s=s|0,l=y(l);var c=0,f=0;f=s+348|0,c=s+352|0,y(h[f>>2])==l&&(n[c>>2]|0)==2||(h[f>>2]=l,f=Ht(l)|0,n[c>>2]=f?3:2,Le(s))}function up(s){s=s|0;var l=0;l=s+352|0,(n[l>>2]|0)!=3&&(h[s+348>>2]=y(ce),n[l>>2]=3,Le(s))}function Br(s,l){s=s|0,l=l|0;var c=0,f=0;f=l+348|0,c=n[f+4>>2]|0,l=s,n[l>>2]=n[f>>2],n[l+4>>2]=c}function Is(s,l){s=s|0,l=y(l);var c=0,f=0,d=0,m=0;m=Ht(l)|0,c=(m^1)&1,f=s+356|0,d=s+360|0,m|y(h[f>>2])==l&&(n[d>>2]|0)==(c|0)||(h[f>>2]=l,n[d>>2]=c,Le(s))}function o0(s,l){s=s|0,l=y(l);var c=0,f=0;f=s+356|0,c=s+360|0,y(h[f>>2])==l&&(n[c>>2]|0)==2||(h[f>>2]=l,f=Ht(l)|0,n[c>>2]=f?3:2,Le(s))}function a0(s){s=s|0;var l=0;l=s+360|0,(n[l>>2]|0)!=3&&(h[s+356>>2]=y(ce),n[l>>2]=3,Le(s))}function l0(s,l){s=s|0,l=l|0;var c=0,f=0;f=l+356|0,c=n[f+4>>2]|0,l=s,n[l>>2]=n[f>>2],n[l+4>>2]=c}function Ap(s,l){s=s|0,l=y(l);var c=0,f=0,d=0,m=0;m=Ht(l)|0,c=(m^1)&1,f=s+364|0,d=s+368|0,m|y(h[f>>2])==l&&(n[d>>2]|0)==(c|0)||(h[f>>2]=l,n[d>>2]=c,Le(s))}function Bc(s,l){s=s|0,l=y(l);var c=0,f=0,d=0,m=0;m=Ht(l)|0,c=m?0:2,f=s+364|0,d=s+368|0,m|y(h[f>>2])==l&&(n[d>>2]|0)==(c|0)||(h[f>>2]=l,n[d>>2]=c,Le(s))}function Ct(s,l){s=s|0,l=l|0;var c=0,f=0;f=l+364|0,c=n[f+4>>2]|0,l=s,n[l>>2]=n[f>>2],n[l+4>>2]=c}function gd(s,l){s=s|0,l=y(l);var c=0,f=0,d=0,m=0;m=Ht(l)|0,c=(m^1)&1,f=s+372|0,d=s+376|0,m|y(h[f>>2])==l&&(n[d>>2]|0)==(c|0)||(h[f>>2]=l,n[d>>2]=c,Le(s))}function c0(s,l){s=s|0,l=y(l);var c=0,f=0,d=0,m=0;m=Ht(l)|0,c=m?0:2,f=s+372|0,d=s+376|0,m|y(h[f>>2])==l&&(n[d>>2]|0)==(c|0)||(h[f>>2]=l,n[d>>2]=c,Le(s))}function u0(s,l){s=s|0,l=l|0;var c=0,f=0;f=l+372|0,c=n[f+4>>2]|0,l=s,n[l>>2]=n[f>>2],n[l+4>>2]=c}function Iu(s,l){s=s|0,l=y(l);var c=0,f=0,d=0,m=0;m=Ht(l)|0,c=(m^1)&1,f=s+380|0,d=s+384|0,m|y(h[f>>2])==l&&(n[d>>2]|0)==(c|0)||(h[f>>2]=l,n[d>>2]=c,Le(s))}function dd(s,l){s=s|0,l=y(l);var c=0,f=0,d=0,m=0;m=Ht(l)|0,c=m?0:2,f=s+380|0,d=s+384|0,m|y(h[f>>2])==l&&(n[d>>2]|0)==(c|0)||(h[f>>2]=l,n[d>>2]=c,Le(s))}function A0(s,l){s=s|0,l=l|0;var c=0,f=0;f=l+380|0,c=n[f+4>>2]|0,l=s,n[l>>2]=n[f>>2],n[l+4>>2]=c}function Bu(s,l){s=s|0,l=y(l);var c=0,f=0,d=0,m=0;m=Ht(l)|0,c=(m^1)&1,f=s+388|0,d=s+392|0,m|y(h[f>>2])==l&&(n[d>>2]|0)==(c|0)||(h[f>>2]=l,n[d>>2]=c,Le(s))}function rw(s,l){s=s|0,l=y(l);var c=0,f=0,d=0,m=0;m=Ht(l)|0,c=m?0:2,f=s+388|0,d=s+392|0,m|y(h[f>>2])==l&&(n[d>>2]|0)==(c|0)||(h[f>>2]=l,n[d>>2]=c,Le(s))}function md(s,l){s=s|0,l=l|0;var c=0,f=0;f=l+388|0,c=n[f+4>>2]|0,l=s,n[l>>2]=n[f>>2],n[l+4>>2]=c}function pa(s,l){s=s|0,l=y(l);var c=0;c=s+396|0,y(h[c>>2])!=l&&(h[c>>2]=l,Le(s))}function vc(s){return s=s|0,y(h[s+396>>2])}function Il(s){return s=s|0,y(h[s+400>>2])}function vu(s){return s=s|0,y(h[s+404>>2])}function f0(s){return s=s|0,y(h[s+408>>2])}function TA(s){return s=s|0,y(h[s+412>>2])}function fp(s){return s=s|0,y(h[s+416>>2])}function Ga(s){return s=s|0,y(h[s+420>>2])}function p0(s,l){switch(s=s|0,l=l|0,Un(s,(l|0)<6,2918),l|0){case 0:{l=(n[s+496>>2]|0)==2?5:4;break}case 2:{l=(n[s+496>>2]|0)==2?4:5;break}default:}return y(h[s+424+(l<<2)>>2])}function pp(s,l){switch(s=s|0,l=l|0,Un(s,(l|0)<6,2918),l|0){case 0:{l=(n[s+496>>2]|0)==2?5:4;break}case 2:{l=(n[s+496>>2]|0)==2?4:5;break}default:}return y(h[s+448+(l<<2)>>2])}function jo(s,l){switch(s=s|0,l=l|0,Un(s,(l|0)<6,2918),l|0){case 0:{l=(n[s+496>>2]|0)==2?5:4;break}case 2:{l=(n[s+496>>2]|0)==2?4:5;break}default:}return y(h[s+472+(l<<2)>>2])}function Bs(s,l){s=s|0,l=l|0;var c=0,f=Xe;return c=n[s+4>>2]|0,(c|0)==(n[l+4>>2]|0)?c?(f=y(h[s>>2]),s=y(ne(y(f-y(h[l>>2]))))<y(999999974e-13)):s=1:s=0,s|0}function wi(s,l){s=y(s),l=y(l);var c=0;return Ht(s)|0?c=Ht(l)|0:c=y(ne(y(s-l)))<y(999999974e-13),c|0}function yd(s,l){s=s|0,l=l|0,Ed(s,l)}function Ed(s,l){s=s|0,l=l|0;var c=0,f=0;c=C,C=C+16|0,f=c+4|0,n[f>>2]=0,n[f+4>>2]=0,n[f+8>>2]=0,Ha(f|0,s|0,l|0,0),Ao(s,3,(o[f+11>>0]|0)<0?n[f>>2]|0:f,c),n3e(f),C=c}function Go(s,l,c,f){s=y(s),l=y(l),c=c|0,f=f|0;var d=Xe;s=y(s*l),d=y(mR(s,y(1)));do if(wi(d,y(0))|0)s=y(s-d);else{if(s=y(s-d),wi(d,y(1))|0){s=y(s+y(1));break}if(c){s=y(s+y(1));break}f||(d>y(.5)?d=y(1):(f=wi(d,y(.5))|0,d=y(f?1:0)),s=y(s+d))}while(!1);return y(s/l)}function NA(s,l,c,f,d,m,B,k,Q,O,M,j,se){s=s|0,l=y(l),c=c|0,f=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]|0)+1|0,n[2279]=qe,Pr=s+984|0,o[Pr>>0]|0&&(n[s+512>>2]|0)!=(n[2278]|0)?Je=4:(n[s+516>>2]|0)==(f|0)?Tr=0:Je=4,(Je|0)==4&&(n[s+520>>2]=0,n[s+924>>2]=-1,n[s+928>>2]=-1,h[s+932>>2]=y(-1),h[s+936>>2]=y(-1),Tr=1);e:do if(n[s+964>>2]|0)if(Qe=y(cn(s,2,B)),$e=y(cn(s,0,B)),j=s+916|0,mo=y(h[j>>2]),go=y(h[s+920>>2]),xn=y(h[s+932>>2]),NA(d,l,m,c,n[s+924>>2]|0,mo,n[s+928>>2]|0,go,xn,y(h[s+936>>2]),Qe,$e,M)|0)Je=22;else if(je=n[s+520>>2]|0,!je)Je=21;else for(se=0;;){if(j=s+524+(se*24|0)|0,xn=y(h[j>>2]),go=y(h[s+524+(se*24|0)+4>>2]),mo=y(h[s+524+(se*24|0)+16>>2]),NA(d,l,m,c,n[s+524+(se*24|0)+8>>2]|0,xn,n[s+524+(se*24|0)+12>>2]|0,go,mo,y(h[s+524+(se*24|0)+20>>2]),Qe,$e,M)|0){Je=22;break e}if(se=se+1|0,se>>>0>=je>>>0){Je=21;break}}else{if(Q){if(j=s+916|0,!(wi(y(h[j>>2]),l)|0)){Je=21;break}if(!(wi(y(h[s+920>>2]),c)|0)){Je=21;break}if((n[s+924>>2]|0)!=(d|0)){Je=21;break}j=(n[s+928>>2]|0)==(m|0)?j:0,Je=22;break}if(je=n[s+520>>2]|0,!je)Je=21;else for(se=0;;){if(j=s+524+(se*24|0)|0,wi(y(h[j>>2]),l)|0&&wi(y(h[s+524+(se*24|0)+4>>2]),c)|0&&(n[s+524+(se*24|0)+8>>2]|0)==(d|0)&&(n[s+524+(se*24|0)+12>>2]|0)==(m|0)){Je=22;break e}if(se=se+1|0,se>>>0>=je>>>0){Je=21;break}}}while(!1);do if((Je|0)==21)o[11697]|0?(j=0,Je=28):(j=0,Je=31);else if((Je|0)==22){if(se=(o[11697]|0)!=0,!((j|0)!=0&(Tr^1)))if(se){Je=28;break}else{Je=31;break}Oe=j+16|0,n[s+908>>2]=n[Oe>>2],je=j+20|0,n[s+912>>2]=n[je>>2],(o[11698]|0)==0|se^1||(n[lt>>2]=LA(qe)|0,n[lt+4>>2]=qe,Ao(s,4,2972,lt),se=n[s+972>>2]|0,se|0&&ef[se&127](s),d=Ya(d,Q)|0,m=Ya(m,Q)|0,Ca=+y(h[Oe>>2]),yo=+y(h[je>>2]),n[Lt>>2]=d,n[Lt+4>>2]=m,E[Lt+8>>3]=+l,E[Lt+16>>3]=+c,E[Lt+24>>3]=Ca,E[Lt+32>>3]=yo,n[Lt+40>>2]=O,Ao(s,4,2989,Lt))}while(!1);return(Je|0)==28&&(se=LA(qe)|0,n[Oe>>2]=se,n[Oe+4>>2]=qe,n[Oe+8>>2]=Tr?3047:11699,Ao(s,4,3038,Oe),se=n[s+972>>2]|0,se|0&&ef[se&127](s),Lt=Ya(d,Q)|0,Je=Ya(m,Q)|0,n[_e>>2]=Lt,n[_e+4>>2]=Je,E[_e+8>>3]=+l,E[_e+16>>3]=+c,n[_e+24>>2]=O,Ao(s,4,3049,_e),Je=31),(Je|0)==31&&(si(s,l,c,f,d,m,B,k,Q,M),o[11697]|0&&(se=n[2279]|0,Lt=LA(se)|0,n[Or>>2]=Lt,n[Or+4>>2]=se,n[Or+8>>2]=Tr?3047:11699,Ao(s,4,3083,Or),se=n[s+972>>2]|0,se|0&&ef[se&127](s),Lt=Ya(d,Q)|0,Or=Ya(m,Q)|0,yo=+y(h[s+908>>2]),Ca=+y(h[s+912>>2]),n[cr>>2]=Lt,n[cr+4>>2]=Or,E[cr+8>>3]=yo,E[cr+16>>3]=Ca,n[cr+24>>2]=O,Ao(s,4,3092,cr)),n[s+516>>2]=f,j||(se=s+520|0,j=n[se>>2]|0,(j|0)==16&&(o[11697]|0&&Ao(s,4,3124,Xt),n[se>>2]=0,j=0),Q?j=s+916|0:(n[se>>2]=j+1,j=s+524+(j*24|0)|0),h[j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,B)),Qe=y(y(Yr(s+364|0,B))-xr),$e=y(y(Yr(s+380|0,B))-xr),_e=y(y(Yr(s+372|0,k))-lt),qe=y(y(Yr(s+388|0,k))-lt),Lu=zn?Qe:_e,Mu=zn?$e:qe,Fc=y(l-Fc),l=y(Fc-xr),Ht(l)|0?xr=l:xr=y(_n(y(k0(l,$e)),Qe)),af=y(c-Je),l=y(af-lt),Ht(l)|0?Eo=l:Eo=y(_n(y(k0(l,qe)),_e)),Qe=zn?xr:Eo,Rn=zn?Eo:xr;e:do if((cr|0)==1)for(f=0,j=0;;){if(M=ms(s,j)|0,!f)y(is(M))>y(0)&&y(Gs(M))>y(0)?f=M:f=0;else if(wd(M)|0){je=0;break e}if(j=j+1|0,j>>>0>=Vs>>>0){je=f;break}}else je=0;while(!1);Lt=je+500|0,Or=je+504|0,f=0,M=0,l=y(0),se=0;do{if(j=n[(n[wo>>2]|0)+(se<<2)>>2]|0,(n[j+36>>2]|0)==1)Du(j),o[j+985>>0]=1,o[j+984>>0]=0;else{Bl(j),Q&&dp(j,mt(j,bs)|0,Qe,Rn,xr);do if((n[j+24>>2]|0)!=1)if((j|0)==(je|0)){n[Lt>>2]=n[2278],h[Or>>2]=y(0);break}else{Id(s,j,xr,d,Eo,xr,Eo,m,bs,O);break}else M|0&&(n[M+960>>2]=j),n[j+960>>2]=0,M=j,f=f|0?f:j;while(!1);Ps=y(h[j+504>>2]),l=y(l+y(Ps+y(cn(j,Fr,xr))))}se=se+1|0}while((se|0)!=(Vs|0));for(mo=l>Qe,Ql=kc&((cr|0)==2&mo)?1:cr,xn=(Fl|0)==1,Ca=xn&(Q^1),xp=(Ql|0)==1,kp=(Ql|0)==2,Sl=976+(Fr<<2)|0,Qp=(Fl|2|0)==2,Tp=xn&(kc^1),Tu=1040+(ur<<2)|0,Nu=1040+(Fr<<2)|0,Fp=976+(ur<<2)|0,Rp=(Fl|0)!=1,mo=kc&((cr|0)!=0&mo),go=s+976|0,xn=xn^1,l=Qe,Tr=0,yo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){M=n[j+992+(n[Fp>>2]<<2)>>2]|0,zt=y(c+y(Yr(M,Rn))),h[Ys>>2]=zt,M=Rp&(n[M+4>>2]|0)==2,n[Wo>>2]=((Ht(zt)|0|M)^1)&1;break}else{h[Ys>>2]=Rn,n[Wo>>2]=M?0:2;break}}else zt=y(Qe-Je),Xt=y(zt/$e),zt=y($e*zt),n[Wo>>2]=1,h[Ys>>2]=y(c+(zn?Xt:zt));while(!1);yr(j,Fr,ar,xr,kl,Za),yr(j,ur,Rn,xr,Wo,Ys);do if(!(ns(j,ur,Rn)|0)&&(da(s,j)|0)==4){if((n[(vl(j,ur)|0)+4>>2]|0)==3){M=0;break}M=(n[(bc(j,ur)|0)+4>>2]|0)!=3}else M=0;while(!1);zt=y(h[Za>>2]),Xt=y(h[Ys>>2]),pf=n[kl>>2]|0,li=n[Wo>>2]|0,ha(j,zn?zt:Xt,zn?Xt:zt,bs,zn?pf:li,zn?li:pf,xr,Eo,Q&(M^1),3488,O)|0,o[xl>>0]=o[xl>>0]|o[j+508>>0],j=n[j+960>>2]|0}while(j|0)}}else l=y(0);if(l=y(Pr+l),li=l<y(0)&1,o[xl>>0]=li|u[xl>>0],kp&l>y(0)?(M=n[Sl>>2]|0,n[s+364+(M<<3)+4>>2]|0&&(Ws=y(Yr(s+364+(M<<3)|0,Co)),Ws>=y(0))?Qe=y(_n(y(0),y(Ws-y(ar-l)))):Qe=y(0)):Qe=l,Lt=Tr>>>0<cr>>>0,Lt){je=n[wo>>2]|0,se=Tr,M=0;do j=n[je+(se<<2)>>2]|0,n[j+24>>2]|0||(M=((n[(vl(j,Fr)|0)+4>>2]|0)==3&1)+M|0,M=M+((n[(bc(j,Fr)|0)+4>>2]|0)==3&1)|0),se=se+1|0;while((se|0)!=(cr|0));M?(Je=y(0),c=y(0)):Xr=101}else Xr=101;e:do if((Xr|0)==101)switch(Xr=0,Np|0){case 1:{M=0,Je=y(Qe*y(.5)),c=y(0);break e}case 2:{M=0,Je=Qe,c=y(0);break e}case 3:{if(m>>>0<=1){M=0,Je=y(0),c=y(0);break e}c=y((m+-1|0)>>>0),M=0,Je=y(0),c=y(y(_n(Qe,y(0)))/c);break e}case 5:{c=y(Qe/y((m+1|0)>>>0)),M=0,Je=c;break e}case 4:{c=y(Qe/y(m>>>0)),M=0,Je=y(c*y(.5));break e}default:{M=0,Je=y(0),c=y(0);break e}}while(!1);if(l=y(Lp+Je),Lt){$e=y(Qe/y(M|0)),se=n[wo>>2]|0,j=Tr,Qe=y(0);do{M=n[se+(j<<2)>>2]|0;e:do if((n[M+36>>2]|0)!=1){switch(n[M+24>>2]|0){case 1:{if(gi(M,Fr)|0){if(!Q)break e;zt=y(Mr(M,Fr,ar)),zt=y(zt+y(Cr(s,Fr))),zt=y(zt+y(K(M,Fr,xr))),h[M+400+(n[Nu>>2]<<2)>>2]=zt;break e}break}case 0:if(li=(n[(vl(M,Fr)|0)+4>>2]|0)==3,zt=y($e+l),l=li?zt:l,Q&&(li=M+400+(n[Nu>>2]<<2)|0,h[li>>2]=y(l+y(h[li>>2]))),li=(n[(bc(M,Fr)|0)+4>>2]|0)==3,zt=y($e+l),l=li?zt:l,Ca){zt=y(c+y(cn(M,Fr,xr))),Qe=Rn,l=y(l+y(zt+y(h[M+504>>2])));break e}else{l=y(l+y(c+y(ss(M,Fr,xr)))),Qe=y(_n(Qe,y(ss(M,ur,xr))));break e}default:}Q&&(zt=y(Je+y(Cr(s,Fr))),li=M+400+(n[Nu>>2]<<2)|0,h[li>>2]=y(zt+y(h[li>>2])))}while(!1);j=j+1|0}while((j|0)!=(cr|0))}else Qe=y(0);if(c=y(Mp+l),Qp?Je=y(y(Ii(s,ur,y(Ks+Qe),Tc,B))-Ks):Je=Rn,$e=y(y(Ii(s,ur,y(Ks+(Tp?Rn:Qe)),Tc,B))-Ks),Lt&Q){j=Tr;do{se=n[(n[wo>>2]|0)+(j<<2)>>2]|0;do if((n[se+36>>2]|0)!=1){if((n[se+24>>2]|0)==1){if(gi(se,ur)|0){if(zt=y(Mr(se,ur,Rn)),zt=y(zt+y(Cr(s,ur))),zt=y(zt+y(K(se,ur,xr))),M=n[Tu>>2]|0,h[se+400+(M<<2)>>2]=zt,!(Ht(zt)|0))break}else M=n[Tu>>2]|0;zt=y(Cr(s,ur)),h[se+400+(M<<2)>>2]=y(zt+y(K(se,ur,xr)));break}M=da(s,se)|0;do if((M|0)==4){if((n[(vl(se,ur)|0)+4>>2]|0)==3){Xr=139;break}if((n[(bc(se,ur)|0)+4>>2]|0)==3){Xr=139;break}if(ns(se,ur,Rn)|0){l=Oe;break}pf=n[se+908+(n[Sl>>2]<<2)>>2]|0,n[Ys>>2]=pf,l=y(h[se+396>>2]),li=Ht(l)|0,Qe=(n[v>>2]=pf,y(h[v>>2])),li?l=$e:(Pr=y(cn(se,ur,xr)),zt=y(Qe/l),l=y(l*Qe),l=y(Pr+(zn?zt:l))),h[Za>>2]=l,h[Ys>>2]=y(y(cn(se,Fr,xr))+Qe),n[Wo>>2]=1,n[kl>>2]=1,yr(se,Fr,ar,xr,Wo,Ys),yr(se,ur,Rn,xr,kl,Za),l=y(h[Ys>>2]),Pr=y(h[Za>>2]),zt=zn?l:Pr,l=zn?Pr:l,li=((Ht(zt)|0)^1)&1,ha(se,zt,l,bs,li,((Ht(l)|0)^1)&1,xr,Eo,1,3493,O)|0,l=Oe}else Xr=139;while(!1);e:do if((Xr|0)==139){Xr=0,l=y(Je-y(ss(se,ur,xr)));do if((n[(vl(se,ur)|0)+4>>2]|0)==3){if((n[(bc(se,ur)|0)+4>>2]|0)!=3)break;l=y(Oe+y(_n(y(0),y(l*y(.5)))));break e}while(!1);if((n[(bc(se,ur)|0)+4>>2]|0)==3){l=Oe;break}if((n[(vl(se,ur)|0)+4>>2]|0)==3){l=y(Oe+y(_n(y(0),l)));break}switch(M|0){case 1:{l=Oe;break e}case 2:{l=y(Oe+y(l*y(.5)));break e}default:{l=y(Oe+l);break e}}}while(!1);zt=y(Ps+l),li=se+400+(n[Tu>>2]<<2)|0,h[li>>2]=y(zt+y(h[li>>2]))}while(!1);j=j+1|0}while((j|0)!=(cr|0))}if(Ps=y(Ps+$e),Qc=y(_n(Qc,c)),m=yo+1|0,cr>>>0>=Vs>>>0)break;l=ar,Tr=cr,yo=m}do if(Q){if(M=m>>>0>1,!M&&!(Yi(s)|0))break;if(!(Ht(Rn)|0)){l=y(Rn-Ps);e:do switch(n[s+12>>2]|0){case 3:{Oe=y(Oe+l),_e=y(0);break}case 2:{Oe=y(Oe+y(l*y(.5))),_e=y(0);break}case 4:{Rn>Ps?_e=y(l/y(m>>>0)):_e=y(0);break}case 7:if(Rn>Ps){Oe=y(Oe+y(l/y(m<<1>>>0))),_e=y(l/y(m>>>0)),_e=M?_e:y(0);break e}else{Oe=y(Oe+y(l*y(.5))),_e=y(0);break e}case 6:{_e=y(l/y(yo>>>0)),_e=Rn>Ps&M?_e:y(0);break}default:_e=y(0)}while(!1);if(m|0)for(Lt=1040+(ur<<2)|0,Or=976+(ur<<2)|0,je=0,j=0;;){e:do if(j>>>0<Vs>>>0)for(Qe=y(0),$e=y(0),l=y(0),se=j;;){M=n[(n[wo>>2]|0)+(se<<2)>>2]|0;do if((n[M+36>>2]|0)!=1&&!(n[M+24>>2]|0)){if((n[M+940>>2]|0)!=(je|0))break e;if(Bd(M,ur)|0&&(zt=y(h[M+908+(n[Or>>2]<<2)>>2]),l=y(_n(l,y(zt+y(cn(M,ur,xr)))))),(da(s,M)|0)!=5)break;Ws=y(Ka(M)),Ws=y(Ws+y(K(M,0,xr))),zt=y(h[M+912>>2]),zt=y(y(zt+y(cn(M,0,xr)))-Ws),Ws=y(_n($e,Ws)),zt=y(_n(Qe,zt)),Qe=zt,$e=Ws,l=y(_n(l,y(Ws+zt)))}while(!1);if(M=se+1|0,M>>>0<Vs>>>0)se=M;else{se=M;break}}else $e=y(0),l=y(0),se=j;while(!1);if(lt=y(_e+l),c=Oe,Oe=y(Oe+lt),j>>>0<se>>>0){Je=y(c+$e),M=j;do{j=n[(n[wo>>2]|0)+(M<<2)>>2]|0;e:do if((n[j+36>>2]|0)!=1&&!(n[j+24>>2]|0))switch(da(s,j)|0){case 1:{zt=y(c+y(K(j,ur,xr))),h[j+400+(n[Lt>>2]<<2)>>2]=zt;break e}case 3:{zt=y(y(Oe-y(re(j,ur,xr)))-y(h[j+908+(n[Or>>2]<<2)>>2])),h[j+400+(n[Lt>>2]<<2)>>2]=zt;break e}case 2:{zt=y(c+y(y(lt-y(h[j+908+(n[Or>>2]<<2)>>2]))*y(.5))),h[j+400+(n[Lt>>2]<<2)>>2]=zt;break e}case 4:{if(zt=y(c+y(K(j,ur,xr))),h[j+400+(n[Lt>>2]<<2)>>2]=zt,ns(j,ur,Rn)|0||(zn?(Qe=y(h[j+908>>2]),l=y(Qe+y(cn(j,Fr,xr))),$e=lt):($e=y(h[j+912>>2]),$e=y($e+y(cn(j,ur,xr))),l=lt,Qe=y(h[j+908>>2])),wi(l,Qe)|0&&wi($e,y(h[j+912>>2]))|0))break e;ha(j,l,$e,bs,1,1,xr,Eo,1,3501,O)|0;break e}case 5:{h[j+404>>2]=y(y(Je-y(Ka(j)))+y(Mr(j,0,Rn)));break e}default:break e}while(!1);M=M+1|0}while((M|0)!=(se|0))}if(je=je+1|0,(je|0)==(m|0))break;j=se}}}while(!1);if(h[s+908>>2]=y(Ii(s,2,Fc,B,B)),h[s+912>>2]=y(Ii(s,0,af,k,B)),Ql|0&&(lf=n[s+32>>2]|0,cf=(Ql|0)==2,!(cf&(lf|0)!=2))?cf&(lf|0)==2&&(l=y(Rc+ar),l=y(_n(y(k0(l,y(MA(s,Fr,Qc,Co)))),Rc)),Xr=198):(l=y(Ii(s,Fr,Qc,Co,B)),Xr=198),(Xr|0)==198&&(h[s+908+(n[976+(Fr<<2)>>2]<<2)>>2]=l),Fl|0&&(Af=n[s+32>>2]|0,ff=(Fl|0)==2,!(ff&(Af|0)!=2))?ff&(Af|0)==2&&(l=y(Ks+Rn),l=y(_n(y(k0(l,y(MA(s,ur,y(Ks+Ps),Tc)))),Ks)),Xr=204):(l=y(Ii(s,ur,y(Ks+Ps),Tc,B)),Xr=204),(Xr|0)==204&&(h[s+908+(n[976+(ur<<2)>>2]<<2)>>2]=l),Q){if((n[uf>>2]|0)==2){j=976+(ur<<2)|0,se=1040+(ur<<2)|0,M=0;do je=ms(s,M)|0,n[je+24>>2]|0||(pf=n[j>>2]|0,zt=y(h[s+908+(pf<<2)>>2]),li=je+400+(n[se>>2]<<2)|0,zt=y(zt-y(h[li>>2])),h[li>>2]=y(zt-y(h[je+908+(pf<<2)>>2]))),M=M+1|0;while((M|0)!=(Vs|0))}if(f|0){M=zn?Ql:d;do vd(s,f,xr,M,Eo,bs,O),f=n[f+960>>2]|0;while(f|0)}if(M=(Fr|2|0)==3,j=(ur|2|0)==3,M|j){f=0;do se=n[(n[wo>>2]|0)+(f<<2)>>2]|0,(n[se+36>>2]|0)!=1&&(M&&yp(s,se,Fr),j&&yp(s,se,ur)),f=f+1|0;while((f|0)!=(Vs|0))}}}while(!1);C=Rl}function ga(s,l){s=s|0,l=y(l);var c=0;la(s,l>=y(0),3147),c=l==y(0),h[s+4>>2]=c?y(0):l}function Dc(s,l,c,f){s=s|0,l=y(l),c=y(c),f=f|0;var d=Xe,m=Xe,B=0,k=0,Q=0;n[2278]=(n[2278]|0)+1,Bl(s),ns(s,2,l)|0?(d=y(Yr(n[s+992>>2]|0,l)),Q=1,d=y(d+y(cn(s,2,l)))):(d=y(Yr(s+380|0,l)),d>=y(0)?Q=2:(Q=((Ht(l)|0)^1)&1,d=l)),ns(s,0,c)|0?(m=y(Yr(n[s+996>>2]|0,c)),k=1,m=y(m+y(cn(s,0,l)))):(m=y(Yr(s+388|0,c)),m>=y(0)?k=2:(k=((Ht(c)|0)^1)&1,m=c)),B=s+976|0,ha(s,d,m,f,Q,k,l,c,1,3189,n[B>>2]|0)|0&&(dp(s,n[s+496>>2]|0,l,c,l),Pc(s,y(h[(n[B>>2]|0)+4>>2]),y(0),y(0)),o[11696]|0)&&yd(s,7)}function Bl(s){s=s|0;var l=0,c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;k=C,C=C+32|0,B=k+24|0,m=k+16|0,f=k+8|0,d=k,c=0;do l=s+380+(c<<3)|0,n[s+380+(c<<3)+4>>2]|0&&(Q=l,O=n[Q+4>>2]|0,M=f,n[M>>2]=n[Q>>2],n[M+4>>2]=O,M=s+364+(c<<3)|0,O=n[M+4>>2]|0,Q=d,n[Q>>2]=n[M>>2],n[Q+4>>2]=O,n[m>>2]=n[f>>2],n[m+4>>2]=n[f+4>>2],n[B>>2]=n[d>>2],n[B+4>>2]=n[d+4>>2],Bs(m,B)|0)||(l=s+348+(c<<3)|0),n[s+992+(c<<2)>>2]=l,c=c+1|0;while((c|0)!=2);C=k}function ns(s,l,c){s=s|0,l=l|0,c=y(c);var f=0;switch(s=n[s+992+(n[976+(l<<2)>>2]<<2)>>2]|0,n[s+4>>2]|0){case 0:case 3:{s=0;break}case 1:{y(h[s>>2])<y(0)?s=0:f=5;break}case 2:{y(h[s>>2])<y(0)?s=0:s=(Ht(c)|0)^1;break}default:f=5}return(f|0)==5&&(s=1),s|0}function Yr(s,l){switch(s=s|0,l=y(l),n[s+4>>2]|0){case 2:{l=y(y(y(h[s>>2])*l)/y(100));break}case 1:{l=y(h[s>>2]);break}default:l=y(ce)}return y(l)}function dp(s,l,c,f,d){s=s|0,l=l|0,c=y(c),f=y(f),d=y(d);var m=0,B=Xe;l=n[s+944>>2]|0?l:1,m=fr(n[s+4>>2]|0,l)|0,l=iw(m,l)|0,c=y(Dd(s,m,c)),f=y(Dd(s,l,f)),B=y(c+y(K(s,m,d))),h[s+400+(n[1040+(m<<2)>>2]<<2)>>2]=B,c=y(c+y(re(s,m,d))),h[s+400+(n[1e3+(m<<2)>>2]<<2)>>2]=c,c=y(f+y(K(s,l,d))),h[s+400+(n[1040+(l<<2)>>2]<<2)>>2]=c,d=y(f+y(re(s,l,d))),h[s+400+(n[1e3+(l<<2)>>2]<<2)>>2]=d}function Pc(s,l,c,f){s=s|0,l=y(l),c=y(c),f=y(f);var d=0,m=0,B=Xe,k=Xe,Q=0,O=0,M=Xe,j=0,se=Xe,je=Xe,Oe=Xe,Qe=Xe;if(l!=y(0)&&(d=s+400|0,Qe=y(h[d>>2]),m=s+404|0,Oe=y(h[m>>2]),j=s+416|0,je=y(h[j>>2]),O=s+420|0,B=y(h[O>>2]),se=y(Qe+c),M=y(Oe+f),f=y(se+je),k=y(M+B),Q=(n[s+988>>2]|0)==1,h[d>>2]=y(Go(Qe,l,0,Q)),h[m>>2]=y(Go(Oe,l,0,Q)),c=y(mR(y(je*l),y(1))),wi(c,y(0))|0?m=0:m=(wi(c,y(1))|0)^1,c=y(mR(y(B*l),y(1))),wi(c,y(0))|0?d=0:d=(wi(c,y(1))|0)^1,Qe=y(Go(f,l,Q&m,Q&(m^1))),h[j>>2]=y(Qe-y(Go(se,l,0,Q))),Qe=y(Go(k,l,Q&d,Q&(d^1))),h[O>>2]=y(Qe-y(Go(M,l,0,Q))),m=(n[s+952>>2]|0)-(n[s+948>>2]|0)>>2,m|0)){d=0;do Pc(ms(s,d)|0,l,se,M),d=d+1|0;while((d|0)!=(m|0))}}function nw(s,l,c,f,d){switch(s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,c|0){case 5:case 0:{s=e7(n[489]|0,f,d)|0;break}default:s=$Ue(f,d)|0}return s|0}function g0(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;d=C,C=C+16|0,m=d,n[m>>2]=f,d0(s,0,l,c,m),C=d}function d0(s,l,c,f,d){if(s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,s=s|0?s:956,w7[n[s+8>>2]&1](s,l,c,f,d)|0,(c|0)==5)Tt();else return}function Wa(s,l,c){s=s|0,l=l|0,c=c|0,o[s+l>>0]=c&1}function Cd(s,l){s=s|0,l=l|0;var c=0,f=0;n[s>>2]=0,n[s+4>>2]=0,n[s+8>>2]=0,c=l+4|0,f=(n[c>>2]|0)-(n[l>>2]|0)>>2,f|0&&(m0(s,f),Qt(s,n[l>>2]|0,n[c>>2]|0,f))}function m0(s,l){s=s|0,l=l|0;var c=0;if((N(s)|0)>>>0<l>>>0&&Jr(s),l>>>0>1073741823)Tt();else{c=Kt(l<<2)|0,n[s+4>>2]=c,n[s>>2]=c,n[s+8>>2]=c+(l<<2);return}}function Qt(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,f=s+4|0,s=c-l|0,(s|0)>0&&(Dr(n[f>>2]|0,l|0,s|0)|0,n[f>>2]=(n[f>>2]|0)+(s>>>2<<2))}function N(s){return s=s|0,1073741823}function K(s,l,c){return s=s|0,l=l|0,c=y(c),he(l)|0&&n[s+96>>2]|0?s=s+92|0:s=Fn(s+60|0,n[1040+(l<<2)>>2]|0,992)|0,y(ze(s,c))}function re(s,l,c){return s=s|0,l=l|0,c=y(c),he(l)|0&&n[s+104>>2]|0?s=s+100|0:s=Fn(s+60|0,n[1e3+(l<<2)>>2]|0,992)|0,y(ze(s,c))}function he(s){return s=s|0,(s|1|0)==3|0}function ze(s,l){return s=s|0,l=y(l),(n[s+4>>2]|0)==3?l=y(0):l=y(Yr(s,l)),y(l)}function mt(s,l){return s=s|0,l=l|0,s=n[s>>2]|0,(s|0?s:(l|0)>1?l:1)|0}function fr(s,l){s=s|0,l=l|0;var c=0;e:do if((l|0)==2){switch(s|0){case 2:{s=3;break e}case 3:break;default:{c=4;break e}}s=2}else c=4;while(!1);return s|0}function Cr(s,l){s=s|0,l=l|0;var c=Xe;return he(l)|0&&n[s+312>>2]|0&&(c=y(h[s+308>>2]),c>=y(0))||(c=y(_n(y(h[(Fn(s+276|0,n[1040+(l<<2)>>2]|0,992)|0)>>2]),y(0)))),y(c)}function yn(s,l){s=s|0,l=l|0;var c=Xe;return he(l)|0&&n[s+320>>2]|0&&(c=y(h[s+316>>2]),c>=y(0))||(c=y(_n(y(h[(Fn(s+276|0,n[1e3+(l<<2)>>2]|0,992)|0)>>2]),y(0)))),y(c)}function oi(s,l,c){s=s|0,l=l|0,c=y(c);var f=Xe;return he(l)|0&&n[s+240>>2]|0&&(f=y(Yr(s+236|0,c)),f>=y(0))||(f=y(_n(y(Yr(Fn(s+204|0,n[1040+(l<<2)>>2]|0,992)|0,c)),y(0)))),y(f)}function Li(s,l,c){s=s|0,l=l|0,c=y(c);var f=Xe;return he(l)|0&&n[s+248>>2]|0&&(f=y(Yr(s+244|0,c)),f>=y(0))||(f=y(_n(y(Yr(Fn(s+204|0,n[1e3+(l<<2)>>2]|0,992)|0,c)),y(0)))),y(f)}function y0(s,l,c,f,d,m,B){s=s|0,l=y(l),c=y(c),f=f|0,d=d|0,m=y(m),B=y(B);var k=Xe,Q=Xe,O=Xe,M=Xe,j=Xe,se=Xe,je=0,Oe=0,Qe=0;Qe=C,C=C+16|0,je=Qe,Oe=s+964|0,Un(s,(n[Oe>>2]|0)!=0,3519),k=y(En(s,2,l)),Q=y(En(s,0,l)),O=y(cn(s,2,l)),M=y(cn(s,0,l)),Ht(l)|0?j=l:j=y(_n(y(0),y(y(l-O)-k))),Ht(c)|0?se=c:se=y(_n(y(0),y(y(c-M)-Q))),(f|0)==1&(d|0)==1?(h[s+908>>2]=y(Ii(s,2,y(l-O),m,m)),l=y(Ii(s,0,y(c-M),B,m))):(I7[n[Oe>>2]&1](je,s,j,f,se,d),j=y(k+y(h[je>>2])),se=y(l-O),h[s+908>>2]=y(Ii(s,2,(f|2|0)==2?j:se,m,m)),se=y(Q+y(h[je+4>>2])),l=y(c-M),l=y(Ii(s,0,(d|2|0)==2?se:l,B,m))),h[s+912>>2]=l,C=Qe}function bv(s,l,c,f,d,m,B){s=s|0,l=y(l),c=y(c),f=f|0,d=d|0,m=y(m),B=y(B);var k=Xe,Q=Xe,O=Xe,M=Xe;O=y(En(s,2,m)),k=y(En(s,0,m)),M=y(cn(s,2,m)),Q=y(cn(s,0,m)),l=y(l-M),h[s+908>>2]=y(Ii(s,2,(f|2|0)==2?O:l,m,m)),c=y(c-Q),h[s+912>>2]=y(Ii(s,0,(d|2|0)==2?k:c,B,m))}function Sv(s,l,c,f,d,m,B){s=s|0,l=y(l),c=y(c),f=f|0,d=d|0,m=y(m),B=y(B);var k=0,Q=Xe,O=Xe;return k=(f|0)==2,!(l<=y(0)&k)&&!(c<=y(0)&(d|0)==2)&&!((f|0)==1&(d|0)==1)?s=0:(Q=y(cn(s,0,m)),O=y(cn(s,2,m)),k=l<y(0)&k|(Ht(l)|0),l=y(l-O),h[s+908>>2]=y(Ii(s,2,k?y(0):l,m,m)),l=y(c-Q),k=c<y(0)&(d|0)==2|(Ht(c)|0),h[s+912>>2]=y(Ii(s,0,k?y(0):l,B,m)),s=1),s|0}function iw(s,l){return s=s|0,l=l|0,OA(s)|0?s=fr(2,l)|0:s=0,s|0}function mp(s,l,c){return s=s|0,l=l|0,c=y(c),c=y(oi(s,l,c)),y(c+y(Cr(s,l)))}function sw(s,l,c){return s=s|0,l=l|0,c=y(c),c=y(Li(s,l,c)),y(c+y(yn(s,l)))}function En(s,l,c){s=s|0,l=l|0,c=y(c);var f=Xe;return f=y(mp(s,l,c)),y(f+y(sw(s,l,c)))}function wd(s){return s=s|0,n[s+24>>2]|0?s=0:y(is(s))!=y(0)?s=1:s=y(Gs(s))!=y(0),s|0}function is(s){s=s|0;var l=Xe;if(n[s+944>>2]|0){if(l=y(h[s+44>>2]),Ht(l)|0)return l=y(h[s+40>>2]),s=l>y(0)&((Ht(l)|0)^1),y(s?l:y(0))}else l=y(0);return y(l)}function Gs(s){s=s|0;var l=Xe,c=0,f=Xe;do if(n[s+944>>2]|0){if(l=y(h[s+48>>2]),Ht(l)|0){if(c=o[(n[s+976>>2]|0)+2>>0]|0,!(c<<24>>24)&&(f=y(h[s+40>>2]),f<y(0)&((Ht(f)|0)^1))){l=y(-f);break}l=c<<24>>24?y(1):y(0)}}else l=y(0);while(!1);return y(l)}function Du(s){s=s|0;var l=0,c=0;if(Od(s+400|0,0,540)|0,o[s+985>>0]=1,ee(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]=c,n[Xt>>2]=2,je=2,Oe=c),!((se|0)==2&lt)&&Ht(j)|0&&!(Ht(d)|0)&&(h[cr>>2]=d,n[Pr>>2]=2,M=2,j=d),Qe=y(h[l+396>>2]),$e=Ht(Qe)|0;do if($e)se=je;else{if((je|0)==1&lt){h[cr>>2]=y(y(Oe-Je)/Qe),n[Pr>>2]=1,M=1,se=1;break}qe&(M|0)==1?(h[Or>>2]=y(Qe*y(j-_e)),n[Xt>>2]=1,M=1,se=1):se=je}while(!1);go=Ht(c)|0,je=(da(s,l)|0)!=4,!(qe|Lt|((f|0)!=1|go)|(je|(se|0)==1))&&(h[Or>>2]=c,n[Xt>>2]=1,!$e)&&(h[cr>>2]=y(y(c-Je)/Qe),n[Pr>>2]=1,M=1),!(Tr|lt|((k|0)!=1|(Ht(d)|0))|(je|(M|0)==1))&&(h[cr>>2]=d,n[Pr>>2]=1,!$e)&&(h[Or>>2]=y(Qe*y(d-_e)),n[Xt>>2]=1),yr(l,2,m,m,Xt,Or),yr(l,0,B,m,Pr,cr),c=y(h[Or>>2]),d=y(h[cr>>2]),ha(l,c,d,Q,n[Xt>>2]|0,n[Pr>>2]|0,m,B,0,3565,O)|0,B=y(h[l+908+(n[976+(ar<<2)>>2]<<2)>>2]),h[l+504>>2]=y(_n(B,y(En(l,ar,m))))}while(!1);n[l+500>>2]=n[2278],C=xn}function Ii(s,l,c,f,d){return s=s|0,l=l|0,c=y(c),f=y(f),d=y(d),f=y(MA(s,l,c,f)),y(_n(f,y(En(s,l,d))))}function da(s,l){return s=s|0,l=l|0,l=l+20|0,l=n[(n[l>>2]|0?l:s+16|0)>>2]|0,(l|0)==5&&OA(n[s+4>>2]|0)|0&&(l=1),l|0}function vl(s,l){return s=s|0,l=l|0,he(l)|0&&n[s+96>>2]|0?l=4:l=n[1040+(l<<2)>>2]|0,s+60+(l<<3)|0}function bc(s,l){return s=s|0,l=l|0,he(l)|0&&n[s+104>>2]|0?l=5:l=n[1e3+(l<<2)>>2]|0,s+60+(l<<3)|0}function yr(s,l,c,f,d,m){switch(s=s|0,l=l|0,c=y(c),f=y(f),d=d|0,m=m|0,c=y(Yr(s+380+(n[976+(l<<2)>>2]<<3)|0,c)),c=y(c+y(cn(s,l,f))),n[d>>2]|0){case 2:case 1:{d=Ht(c)|0,f=y(h[m>>2]),h[m>>2]=d|f<c?f:c;break}case 0:{Ht(c)|0||(n[d>>2]=2,h[m>>2]=c);break}default:}}function gi(s,l){return s=s|0,l=l|0,s=s+132|0,he(l)|0&&n[(Fn(s,4,948)|0)+4>>2]|0?s=1:s=(n[(Fn(s,n[1040+(l<<2)>>2]|0,948)|0)+4>>2]|0)!=0,s|0}function Mr(s,l,c){s=s|0,l=l|0,c=y(c);var f=0,d=0;return s=s+132|0,he(l)|0&&(f=Fn(s,4,948)|0,(n[f+4>>2]|0)!=0)?d=4:(f=Fn(s,n[1040+(l<<2)>>2]|0,948)|0,n[f+4>>2]|0?d=4:c=y(0)),(d|0)==4&&(c=y(Yr(f,c))),y(c)}function ss(s,l,c){s=s|0,l=l|0,c=y(c);var f=Xe;return f=y(h[s+908+(n[976+(l<<2)>>2]<<2)>>2]),f=y(f+y(K(s,l,c))),y(f+y(re(s,l,c)))}function Yi(s){s=s|0;var l=0,c=0,f=0;e:do if(OA(n[s+4>>2]|0)|0)l=0;else if((n[s+16>>2]|0)!=5)if(c=Ci(s)|0,!c)l=0;else for(l=0;;){if(f=ms(s,l)|0,!(n[f+24>>2]|0)&&(n[f+20>>2]|0)==5){l=1;break e}if(l=l+1|0,l>>>0>=c>>>0){l=0;break}}else l=1;while(!1);return l|0}function Bd(s,l){s=s|0,l=l|0;var c=Xe;return c=y(h[s+908+(n[976+(l<<2)>>2]<<2)>>2]),c>=y(0)&((Ht(c)|0)^1)|0}function Ka(s){s=s|0;var l=Xe,c=0,f=0,d=0,m=0,B=0,k=0,Q=Xe;if(c=n[s+968>>2]|0,c)Q=y(h[s+908>>2]),l=y(h[s+912>>2]),l=y(m7[c&0](s,Q,l)),Un(s,(Ht(l)|0)^1,3573);else{m=Ci(s)|0;do if(m|0){for(c=0,d=0;;){if(f=ms(s,d)|0,n[f+940>>2]|0){B=8;break}if((n[f+24>>2]|0)!=1)if(k=(da(s,f)|0)==5,k){c=f;break}else c=c|0?c:f;if(d=d+1|0,d>>>0>=m>>>0){B=8;break}}if((B|0)==8&&!c)break;return l=y(Ka(c)),y(l+y(h[c+404>>2]))}while(!1);l=y(h[s+912>>2])}return y(l)}function MA(s,l,c,f){s=s|0,l=l|0,c=y(c),f=y(f);var d=Xe,m=0;return OA(l)|0?(l=1,m=3):he(l)|0?(l=0,m=3):(f=y(ce),d=y(ce)),(m|0)==3&&(d=y(Yr(s+364+(l<<3)|0,f)),f=y(Yr(s+380+(l<<3)|0,f))),m=f<c&(f>=y(0)&((Ht(f)|0)^1)),c=m?f:c,m=d>=y(0)&((Ht(d)|0)^1)&c<d,y(m?d:c)}function vd(s,l,c,f,d,m,B){s=s|0,l=l|0,c=y(c),f=f|0,d=y(d),m=m|0,B=B|0;var k=Xe,Q=Xe,O=0,M=0,j=Xe,se=Xe,je=Xe,Oe=0,Qe=0,$e=0,Je=0,lt=Xe,_e=0;$e=fr(n[s+4>>2]|0,m)|0,Oe=iw($e,m)|0,Qe=he($e)|0,j=y(cn(l,2,c)),se=y(cn(l,0,c)),ns(l,2,c)|0?k=y(j+y(Yr(n[l+992>>2]|0,c))):gi(l,2)|0&&lr(l,2)|0?(k=y(h[s+908>>2]),Q=y(Cr(s,2)),Q=y(k-y(Q+y(yn(s,2)))),k=y(Mr(l,2,c)),k=y(Ii(l,2,y(Q-y(k+y(Pu(l,2,c)))),c,c))):k=y(ce),ns(l,0,d)|0?Q=y(se+y(Yr(n[l+996>>2]|0,d))):gi(l,0)|0&&lr(l,0)|0?(Q=y(h[s+912>>2]),lt=y(Cr(s,0)),lt=y(Q-y(lt+y(yn(s,0)))),Q=y(Mr(l,0,d)),Q=y(Ii(l,0,y(lt-y(Q+y(Pu(l,0,d)))),d,c))):Q=y(ce),O=Ht(k)|0,M=Ht(Q)|0;do if(O^M&&(je=y(h[l+396>>2]),!(Ht(je)|0)))if(O){k=y(j+y(y(Q-se)*je));break}else{lt=y(se+y(y(k-j)/je)),Q=M?lt:Q;break}while(!1);M=Ht(k)|0,O=Ht(Q)|0,M|O&&(_e=(M^1)&1,f=c>y(0)&((f|0)!=0&M),k=Qe?k:f?c:k,ha(l,k,Q,m,Qe?_e:f?2:_e,M&(O^1)&1,k,Q,0,3623,B)|0,k=y(h[l+908>>2]),k=y(k+y(cn(l,2,c))),Q=y(h[l+912>>2]),Q=y(Q+y(cn(l,0,c)))),ha(l,k,Q,m,1,1,k,Q,1,3635,B)|0,lr(l,$e)|0&&!(gi(l,$e)|0)?(_e=n[976+($e<<2)>>2]|0,lt=y(h[s+908+(_e<<2)>>2]),lt=y(lt-y(h[l+908+(_e<<2)>>2])),lt=y(lt-y(yn(s,$e))),lt=y(lt-y(re(l,$e,c))),lt=y(lt-y(Pu(l,$e,Qe?c:d))),h[l+400+(n[1040+($e<<2)>>2]<<2)>>2]=lt):Je=21;do if((Je|0)==21){if(!(gi(l,$e)|0)&&(n[s+8>>2]|0)==1){_e=n[976+($e<<2)>>2]|0,lt=y(h[s+908+(_e<<2)>>2]),lt=y(y(lt-y(h[l+908+(_e<<2)>>2]))*y(.5)),h[l+400+(n[1040+($e<<2)>>2]<<2)>>2]=lt;break}!(gi(l,$e)|0)&&(n[s+8>>2]|0)==2&&(_e=n[976+($e<<2)>>2]|0,lt=y(h[s+908+(_e<<2)>>2]),lt=y(lt-y(h[l+908+(_e<<2)>>2])),h[l+400+(n[1040+($e<<2)>>2]<<2)>>2]=lt)}while(!1);lr(l,Oe)|0&&!(gi(l,Oe)|0)?(_e=n[976+(Oe<<2)>>2]|0,lt=y(h[s+908+(_e<<2)>>2]),lt=y(lt-y(h[l+908+(_e<<2)>>2])),lt=y(lt-y(yn(s,Oe))),lt=y(lt-y(re(l,Oe,c))),lt=y(lt-y(Pu(l,Oe,Qe?d:c))),h[l+400+(n[1040+(Oe<<2)>>2]<<2)>>2]=lt):Je=30;do if((Je|0)==30&&!(gi(l,Oe)|0)){if((da(s,l)|0)==2){_e=n[976+(Oe<<2)>>2]|0,lt=y(h[s+908+(_e<<2)>>2]),lt=y(y(lt-y(h[l+908+(_e<<2)>>2]))*y(.5)),h[l+400+(n[1040+(Oe<<2)>>2]<<2)>>2]=lt;break}_e=(da(s,l)|0)==3,_e^(n[s+28>>2]|0)==2&&(_e=n[976+(Oe<<2)>>2]|0,lt=y(h[s+908+(_e<<2)>>2]),lt=y(lt-y(h[l+908+(_e<<2)>>2])),h[l+400+(n[1040+(Oe<<2)>>2]<<2)>>2]=lt)}while(!1)}function yp(s,l,c){s=s|0,l=l|0,c=c|0;var f=Xe,d=0;d=n[976+(c<<2)>>2]|0,f=y(h[l+908+(d<<2)>>2]),f=y(y(h[s+908+(d<<2)>>2])-f),f=y(f-y(h[l+400+(n[1040+(c<<2)>>2]<<2)>>2])),h[l+400+(n[1e3+(c<<2)>>2]<<2)>>2]=f}function OA(s){return s=s|0,(s|1|0)==1|0}function ow(s){s=s|0;var l=Xe;switch(n[s+56>>2]|0){case 0:case 3:{l=y(h[s+40>>2]),l>y(0)&((Ht(l)|0)^1)?s=o[(n[s+976>>2]|0)+2>>0]|0?1056:992:s=1056;break}default:s=s+52|0}return s|0}function aw(s,l){return s=s|0,l=l|0,(o[s+l>>0]|0)!=0|0}function lr(s,l){return s=s|0,l=l|0,s=s+132|0,he(l)|0&&n[(Fn(s,5,948)|0)+4>>2]|0?s=1:s=(n[(Fn(s,n[1e3+(l<<2)>>2]|0,948)|0)+4>>2]|0)!=0,s|0}function Pu(s,l,c){s=s|0,l=l|0,c=y(c);var f=0,d=0;return s=s+132|0,he(l)|0&&(f=Fn(s,5,948)|0,(n[f+4>>2]|0)!=0)?d=4:(f=Fn(s,n[1e3+(l<<2)>>2]|0,948)|0,n[f+4>>2]|0?d=4:c=y(0)),(d|0)==4&&(c=y(Yr(f,c))),y(c)}function Dd(s,l,c){return s=s|0,l=l|0,c=y(c),gi(s,l)|0?c=y(Mr(s,l,c)):c=y(-y(Pu(s,l,c))),y(c)}function bu(s){return s=y(s),h[v>>2]=s,n[v>>2]|0|0}function Ep(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>1073741823)Tt();else{d=Kt(l<<2)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<2)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<2)}function E0(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>2)<<2)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function UA(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-4-l|0)>>>2)<<2)),s=n[s>>2]|0,s|0&&gt(s)}function _A(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0;if(B=s+4|0,k=n[B>>2]|0,d=k-f|0,m=d>>2,s=l+(m<<2)|0,s>>>0<c>>>0){f=k;do n[f>>2]=n[s>>2],s=s+4|0,f=(n[B>>2]|0)+4|0,n[B>>2]=f;while(s>>>0<c>>>0)}m|0&&ww(k+(0-m<<2)|0,l|0,d|0)|0}function C0(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0;return k=l+4|0,Q=n[k>>2]|0,d=n[s>>2]|0,B=c,m=B-d|0,f=Q+(0-(m>>2)<<2)|0,n[k>>2]=f,(m|0)>0&&Dr(f|0,d|0,m|0)|0,d=s+4|0,m=l+8|0,f=(n[d>>2]|0)-B|0,(f|0)>0&&(Dr(n[m>>2]|0,c|0,f|0)|0,n[m>>2]=(n[m>>2]|0)+(f>>>2<<2)),B=n[s>>2]|0,n[s>>2]=n[k>>2],n[k>>2]=B,B=n[d>>2]|0,n[d>>2]=n[m>>2],n[m>>2]=B,B=s+8|0,c=l+12|0,s=n[B>>2]|0,n[B>>2]=n[c>>2],n[c>>2]=s,n[l>>2]=n[k>>2],Q|0}function lw(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;if(B=n[l>>2]|0,m=n[c>>2]|0,(B|0)!=(m|0)){d=s+8|0,c=((m+-4-B|0)>>>2)+1|0,s=B,f=n[d>>2]|0;do n[f>>2]=n[s>>2],f=(n[d>>2]|0)+4|0,n[d>>2]=f,s=s+4|0;while((s|0)!=(m|0));n[l>>2]=B+(c<<2)}}function Pd(){mc()}function ma(){var s=0;return s=Kt(4)|0,HA(s),s|0}function HA(s){s=s|0,n[s>>2]=Cs()|0}function Sc(s){s=s|0,s|0&&(w0(s),gt(s))}function w0(s){s=s|0,tt(n[s>>2]|0)}function bd(s,l,c){s=s|0,l=l|0,c=c|0,Wa(n[s>>2]|0,l,c)}function fo(s,l){s=s|0,l=y(l),ga(n[s>>2]|0,l)}function xv(s,l){return s=s|0,l=l|0,aw(n[s>>2]|0,l)|0}function cw(){var s=0;return s=Kt(8)|0,kv(s,0),s|0}function kv(s,l){s=s|0,l=l|0,l?l=Ei(n[l>>2]|0)|0:l=co()|0,n[s>>2]=l,n[s+4>>2]=0,bi(l,s)}function eF(s){s=s|0;var l=0;return l=Kt(8)|0,kv(l,s),l|0}function Qv(s){s=s|0,s|0&&(Su(s),gt(s))}function Su(s){s=s|0;var l=0;ua(n[s>>2]|0),l=s+4|0,s=n[l>>2]|0,n[l>>2]=0,s|0&&(qA(s),gt(s))}function qA(s){s=s|0,jA(s)}function jA(s){s=s|0,s=n[s>>2]|0,s|0&&PA(s|0)}function uw(s){return s=s|0,qo(s)|0}function Sd(s){s=s|0;var l=0,c=0;c=s+4|0,l=n[c>>2]|0,n[c>>2]=0,l|0&&(qA(l),gt(l)),qs(n[s>>2]|0)}function tF(s,l){s=s|0,l=l|0,$r(n[s>>2]|0,n[l>>2]|0)}function rF(s,l){s=s|0,l=l|0,Aa(n[s>>2]|0,l)}function Fv(s,l,c){s=s|0,l=l|0,c=+c,Cu(n[s>>2]|0,l,y(c))}function Rv(s,l,c){s=s|0,l=l|0,c=+c,ws(n[s>>2]|0,l,y(c))}function Aw(s,l){s=s|0,l=l|0,mu(n[s>>2]|0,l)}function xu(s,l){s=s|0,l=l|0,yu(n[s>>2]|0,l)}function nF(s,l){s=s|0,l=l|0,QA(n[s>>2]|0,l)}function iF(s,l){s=s|0,l=l|0,xA(n[s>>2]|0,l)}function Cp(s,l){s=s|0,l=l|0,Ec(n[s>>2]|0,l)}function sF(s,l){s=s|0,l=l|0,lp(n[s>>2]|0,l)}function Tv(s,l,c){s=s|0,l=l|0,c=+c,wc(n[s>>2]|0,l,y(c))}function GA(s,l,c){s=s|0,l=l|0,c=+c,Y(n[s>>2]|0,l,y(c))}function oF(s,l){s=s|0,l=l|0,wl(n[s>>2]|0,l)}function aF(s,l){s=s|0,l=l|0,n0(n[s>>2]|0,l)}function Nv(s,l){s=s|0,l=l|0,cp(n[s>>2]|0,l)}function fw(s,l){s=s|0,l=+l,FA(n[s>>2]|0,y(l))}function pw(s,l){s=s|0,l=+l,ja(n[s>>2]|0,y(l))}function lF(s,l){s=s|0,l=+l,Gi(n[s>>2]|0,y(l))}function cF(s,l){s=s|0,l=+l,js(n[s>>2]|0,y(l))}function Dl(s,l){s=s|0,l=+l,Eu(n[s>>2]|0,y(l))}function hw(s,l){s=s|0,l=+l,tw(n[s>>2]|0,y(l))}function uF(s,l){s=s|0,l=+l,RA(n[s>>2]|0,y(l))}function YA(s){s=s|0,up(n[s>>2]|0)}function xd(s,l){s=s|0,l=+l,Is(n[s>>2]|0,y(l))}function ku(s,l){s=s|0,l=+l,o0(n[s>>2]|0,y(l))}function gw(s){s=s|0,a0(n[s>>2]|0)}function dw(s,l){s=s|0,l=+l,Ap(n[s>>2]|0,y(l))}function AF(s,l){s=s|0,l=+l,Bc(n[s>>2]|0,y(l))}function Lv(s,l){s=s|0,l=+l,gd(n[s>>2]|0,y(l))}function WA(s,l){s=s|0,l=+l,c0(n[s>>2]|0,y(l))}function Mv(s,l){s=s|0,l=+l,Iu(n[s>>2]|0,y(l))}function kd(s,l){s=s|0,l=+l,dd(n[s>>2]|0,y(l))}function Ov(s,l){s=s|0,l=+l,Bu(n[s>>2]|0,y(l))}function Uv(s,l){s=s|0,l=+l,rw(n[s>>2]|0,y(l))}function Qd(s,l){s=s|0,l=+l,pa(n[s>>2]|0,y(l))}function _v(s,l,c){s=s|0,l=l|0,c=+c,wu(n[s>>2]|0,l,y(c))}function fF(s,l,c){s=s|0,l=l|0,c=+c,Si(n[s>>2]|0,l,y(c))}function P(s,l,c){s=s|0,l=l|0,c=+c,Ic(n[s>>2]|0,l,y(c))}function D(s){return s=s|0,r0(n[s>>2]|0)|0}function T(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0;f=C,C=C+16|0,d=f,Cc(d,n[l>>2]|0,c),q(s,d),C=f}function q(s,l){s=s|0,l=l|0,W(s,n[l+4>>2]|0,+y(h[l>>2]))}function W(s,l,c){s=s|0,l=l|0,c=+c,n[s>>2]=l,E[s+8>>3]=c}function fe(s){return s=s|0,t0(n[s>>2]|0)|0}function De(s){return s=s|0,uo(n[s>>2]|0)|0}function vt(s){return s=s|0,yc(n[s>>2]|0)|0}function wt(s){return s=s|0,kA(n[s>>2]|0)|0}function St(s){return s=s|0,hd(n[s>>2]|0)|0}function _r(s){return s=s|0,e0(n[s>>2]|0)|0}function os(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0;f=C,C=C+16|0,d=f,Dt(d,n[l>>2]|0,c),q(s,d),C=f}function di(s){return s=s|0,$n(n[s>>2]|0)|0}function po(s){return s=s|0,i0(n[s>>2]|0)|0}function KA(s,l){s=s|0,l=l|0;var c=0,f=0;c=C,C=C+16|0,f=c,fa(f,n[l>>2]|0),q(s,f),C=c}function Yo(s){return s=s|0,+ +y(ji(n[s>>2]|0))}function nt(s){return s=s|0,+ +y(rs(n[s>>2]|0))}function Ve(s,l){s=s|0,l=l|0;var c=0,f=0;c=C,C=C+16|0,f=c,Br(f,n[l>>2]|0),q(s,f),C=c}function At(s,l){s=s|0,l=l|0;var c=0,f=0;c=C,C=C+16|0,f=c,l0(f,n[l>>2]|0),q(s,f),C=c}function Wt(s,l){s=s|0,l=l|0;var c=0,f=0;c=C,C=C+16|0,f=c,Ct(f,n[l>>2]|0),q(s,f),C=c}function vr(s,l){s=s|0,l=l|0;var c=0,f=0;c=C,C=C+16|0,f=c,u0(f,n[l>>2]|0),q(s,f),C=c}function bn(s,l){s=s|0,l=l|0;var c=0,f=0;c=C,C=C+16|0,f=c,A0(f,n[l>>2]|0),q(s,f),C=c}function Qr(s,l){s=s|0,l=l|0;var c=0,f=0;c=C,C=C+16|0,f=c,md(f,n[l>>2]|0),q(s,f),C=c}function Sn(s){return s=s|0,+ +y(vc(n[s>>2]|0))}function ai(s,l){return s=s|0,l=l|0,+ +y(s0(n[s>>2]|0,l))}function tn(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0;f=C,C=C+16|0,d=f,ct(d,n[l>>2]|0,c),q(s,d),C=f}function ho(s,l,c){s=s|0,l=l|0,c=c|0,or(n[s>>2]|0,n[l>>2]|0,c)}function pF(s,l){s=s|0,l=l|0,Es(n[s>>2]|0,n[l>>2]|0)}function nve(s){return s=s|0,Ci(n[s>>2]|0)|0}function ive(s){return s=s|0,s=pt(n[s>>2]|0)|0,s?s=uw(s)|0:s=0,s|0}function sve(s,l){return s=s|0,l=l|0,s=ms(n[s>>2]|0,l)|0,s?s=uw(s)|0:s=0,s|0}function ove(s,l){s=s|0,l=l|0;var c=0,f=0;f=Kt(4)|0,W5(f,l),c=s+4|0,l=n[c>>2]|0,n[c>>2]=f,l|0&&(qA(l),gt(l)),Bt(n[s>>2]|0,1)}function W5(s,l){s=s|0,l=l|0,yve(s,l)}function ave(s,l,c,f,d,m){s=s|0,l=l|0,c=y(c),f=f|0,d=y(d),m=m|0;var B=0,k=0;B=C,C=C+16|0,k=B,lve(k,qo(l)|0,+c,f,+d,m),h[s>>2]=y(+E[k>>3]),h[s+4>>2]=y(+E[k+8>>3]),C=B}function lve(s,l,c,f,d,m){s=s|0,l=l|0,c=+c,f=f|0,d=+d,m=m|0;var B=0,k=0,Q=0,O=0,M=0;B=C,C=C+32|0,M=B+8|0,O=B+20|0,Q=B,k=B+16|0,E[M>>3]=c,n[O>>2]=f,E[Q>>3]=d,n[k>>2]=m,cve(s,n[l+4>>2]|0,M,O,Q,k),C=B}function cve(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0;var B=0,k=0;B=C,C=C+16|0,k=B,za(k),l=ya(l)|0,uve(s,l,+E[c>>3],n[f>>2]|0,+E[d>>3],n[m>>2]|0),Ja(k),C=B}function ya(s){return s=s|0,n[s>>2]|0}function uve(s,l,c,f,d,m){s=s|0,l=l|0,c=+c,f=f|0,d=+d,m=m|0;var B=0;B=Pl(Ave()|0)|0,c=+VA(c),f=hF(f)|0,d=+VA(d),fve(s,hi(0,B|0,l|0,+c,f|0,+d,hF(m)|0)|0)}function Ave(){var s=0;return o[7608]|0||(dve(9120),s=7608,n[s>>2]=1,n[s+4>>2]=0),9120}function Pl(s){return s=s|0,n[s+8>>2]|0}function VA(s){return s=+s,+ +gF(s)}function hF(s){return s=s|0,V5(s)|0}function fve(s,l){s=s|0,l=l|0;var c=0,f=0,d=0;d=C,C=C+32|0,c=d,f=l,f&1?(pve(c,0),ii(f|0,c|0)|0,hve(s,c),gve(c)):(n[s>>2]=n[l>>2],n[s+4>>2]=n[l+4>>2],n[s+8>>2]=n[l+8>>2],n[s+12>>2]=n[l+12>>2]),C=d}function pve(s,l){s=s|0,l=l|0,K5(s,l),n[s+8>>2]=0,o[s+24>>0]=0}function hve(s,l){s=s|0,l=l|0,l=l+8|0,n[s>>2]=n[l>>2],n[s+4>>2]=n[l+4>>2],n[s+8>>2]=n[l+8>>2],n[s+12>>2]=n[l+12>>2]}function gve(s){s=s|0,o[s+24>>0]=0}function K5(s,l){s=s|0,l=l|0,n[s>>2]=l}function V5(s){return s=s|0,s|0}function gF(s){return s=+s,+s}function dve(s){s=s|0,bl(s,mve()|0,4)}function mve(){return 1064}function bl(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c,n[s+8>>2]=ap(l|0,c+1|0)|0}function yve(s,l){s=s|0,l=l|0,l=n[l>>2]|0,n[s>>2]=l,yl(l|0)}function Eve(s){s=s|0;var l=0,c=0;c=s+4|0,l=n[c>>2]|0,n[c>>2]=0,l|0&&(qA(l),gt(l)),Bt(n[s>>2]|0,0)}function Cve(s){s=s|0,Nt(n[s>>2]|0)}function wve(s){return s=s|0,rr(n[s>>2]|0)|0}function Ive(s,l,c,f){s=s|0,l=+l,c=+c,f=f|0,Dc(n[s>>2]|0,y(l),y(c),f)}function Bve(s){return s=s|0,+ +y(Il(n[s>>2]|0))}function vve(s){return s=s|0,+ +y(f0(n[s>>2]|0))}function Dve(s){return s=s|0,+ +y(vu(n[s>>2]|0))}function Pve(s){return s=s|0,+ +y(TA(n[s>>2]|0))}function bve(s){return s=s|0,+ +y(fp(n[s>>2]|0))}function Sve(s){return s=s|0,+ +y(Ga(n[s>>2]|0))}function xve(s,l){s=s|0,l=l|0,E[s>>3]=+y(Il(n[l>>2]|0)),E[s+8>>3]=+y(f0(n[l>>2]|0)),E[s+16>>3]=+y(vu(n[l>>2]|0)),E[s+24>>3]=+y(TA(n[l>>2]|0)),E[s+32>>3]=+y(fp(n[l>>2]|0)),E[s+40>>3]=+y(Ga(n[l>>2]|0))}function kve(s,l){return s=s|0,l=l|0,+ +y(p0(n[s>>2]|0,l))}function Qve(s,l){return s=s|0,l=l|0,+ +y(pp(n[s>>2]|0,l))}function Fve(s,l){return s=s|0,l=l|0,+ +y(jo(n[s>>2]|0,l))}function Rve(){return Pn()|0}function Tve(){Nve(),Lve(),Mve(),Ove(),Uve(),_ve()}function Nve(){UNe(11713,4938,1)}function Lve(){iNe(10448)}function Mve(){UTe(10408)}function Ove(){lTe(10324)}function Uve(){dFe(10096)}function _ve(){Hve(9132)}function Hve(s){s=s|0;var l=0,c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0,je=0,Oe=0,Qe=0,$e=0,Je=0,lt=0,_e=0,qe=0,Lt=0,Or=0,cr=0,Xt=0,Pr=0,Tr=0,ar=0,xn=0,go=0,mo=0,yo=0,Ca=0,xp=0,kp=0,Sl=0,Qp=0,Tu=0,Nu=0,Fp=0,Rp=0,Tp=0,Xr=0,xl=0,Np=0,kc=0,Lp=0,Mp=0,Lu=0,Mu=0,Qc=0,Ys=0,Za=0,Wo=0,kl=0,rf=0,nf=0,Ou=0,sf=0,of=0,Ws=0,Ps=0,Ql=0,Rn=0,af=0,Eo=0,Fc=0,Co=0,Rc=0,lf=0,cf=0,Tc=0,Ks=0,Fl=0,uf=0,Af=0,ff=0,xr=0,zn=0,bs=0,wo=0,Vs=0,Fr=0,ur=0,Rl=0;l=C,C=C+672|0,c=l+656|0,Rl=l+648|0,ur=l+640|0,Fr=l+632|0,Vs=l+624|0,wo=l+616|0,bs=l+608|0,zn=l+600|0,xr=l+592|0,ff=l+584|0,Af=l+576|0,uf=l+568|0,Fl=l+560|0,Ks=l+552|0,Tc=l+544|0,cf=l+536|0,lf=l+528|0,Rc=l+520|0,Co=l+512|0,Fc=l+504|0,Eo=l+496|0,af=l+488|0,Rn=l+480|0,Ql=l+472|0,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4>>2]=0,n[c>>2]=n[M>>2],n[c+4>>2]=n[M+4>>2],JA(s,4686,c)|0,n[O>>2]=7,n[O+4>>2]=0,n[c>>2]=n[O>>2],n[c+4>>2]=n[O+4>>2],JA(s,4701,c)|0,n[Q>>2]=8,n[Q+4>>2]=0,n[c>>2]=n[Q>>2],n[c+4>>2]=n[Q+4>>2],JA(s,4719,c)|0,n[k>>2]=9,n[k+4>>2]=0,n[c>>2]=n[k>>2],n[c+4>>2]=n[k+4>>2],JA(s,4736,c)|0,n[B>>2]=21,n[B+4>>2]=0,n[c>>2]=n[B>>2],n[c+4>>2]=n[B+4>>2],tDe(s,4754,c)|0,n[m>>2]=2,n[m+4>>2]=0,n[c>>2]=n[m>>2],n[c+4>>2]=n[m+4>>2],Hv(s,4772,c)|0,n[d>>2]=3,n[d+4>>2]=0,n[c>>2]=n[d>>2],n[c+4>>2]=n[d+4>>2],Hv(s,4790,c)|0,n[f>>2]=4,n[f+4>>2]=0,n[c>>2]=n[f>>2],n[c+4>>2]=n[f+4>>2],Hv(s,4808,c)|0,C=l}function qve(s,l){s=s|0,l=l|0;var c=0;c=aFe()|0,n[s>>2]=c,lFe(c,l),Pp(n[s>>2]|0)}function jve(s,l,c){return s=s|0,l=l|0,c=c|0,KQe(s,pn(l)|0,c,0),s|0}function Gve(s,l,c){return s=s|0,l=l|0,c=c|0,QQe(s,pn(l)|0,c,0),s|0}function Yve(s,l,c){return s=s|0,l=l|0,c=c|0,mQe(s,pn(l)|0,c,0),s|0}function mw(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],tQe(s,l,d),C=f,s|0}function Wve(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],Lke(s,l,d),C=f,s|0}function Qu(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],Cke(s,l,d),C=f,s|0}function I0(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],ike(s,l,d),C=f,s|0}function vs(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],qxe(s,l,d),C=f,s|0}function zA(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],Pxe(s,l,d),C=f,s|0}function dF(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],uxe(s,l,d),C=f,s|0}function B0(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],LSe(s,l,d),C=f,s|0}function JA(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],CSe(s,l,d),C=f,s|0}function Hv(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],iSe(s,l,d),C=f,s|0}function Kve(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],qbe(s,l,d),C=f,s|0}function Vve(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],Pbe(s,l,d),C=f,s|0}function zve(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],Abe(s,l,d),C=f,s|0}function Jve(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],JPe(s,l,d),C=f,s|0}function Xve(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],RPe(s,l,d),C=f,s|0}function Zve(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],dPe(s,l,d),C=f,s|0}function $ve(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],ePe(s,l,d),C=f,s|0}function eDe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],LDe(s,l,d),C=f,s|0}function tDe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],rDe(s,l,d),C=f,s|0}function rDe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],nDe(s,c,d,1),C=f}function pn(s){return s=s|0,s|0}function nDe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=mF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=iDe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,sDe(m,f)|0,f),C=d}function mF(){var s=0,l=0;if(o[7616]|0||(X5(9136),ir(24,9136,U|0)|0,l=7616,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9136)|0)){s=9136,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));X5(9136)}return 9136}function iDe(s){return s=s|0,0}function sDe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=mF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],J5(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(lDe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function hn(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0;var B=0,k=0,Q=0,O=0,M=0,j=0,se=0,je=0;B=C,C=C+32|0,se=B+24|0,j=B+20|0,Q=B+16|0,M=B+12|0,O=B+8|0,k=B+4|0,je=B,n[j>>2]=l,n[Q>>2]=c,n[M>>2]=f,n[O>>2]=d,n[k>>2]=m,m=s+28|0,n[je>>2]=n[m>>2],n[se>>2]=n[je>>2],oDe(s+24|0,se,j,M,O,Q,k)|0,n[m>>2]=n[n[m>>2]>>2],C=B}function oDe(s,l,c,f,d,m,B){return s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0,B=B|0,s=aDe(l)|0,l=Kt(24)|0,z5(l+4|0,n[c>>2]|0,n[f>>2]|0,n[d>>2]|0,n[m>>2]|0,n[B>>2]|0),n[l>>2]=n[s>>2],n[s>>2]=l,l|0}function aDe(s){return s=s|0,n[s>>2]|0}function z5(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0,n[s>>2]=l,n[s+4>>2]=c,n[s+8>>2]=f,n[s+12>>2]=d,n[s+16>>2]=m}function gr(s,l){return s=s|0,l=l|0,l|s|0}function J5(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function lDe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=cDe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,uDe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],J5(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,ADe(s,k),fDe(k),C=O;return}}function cDe(s){return s=s|0,357913941}function uDe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function ADe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function fDe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function X5(s){s=s|0,gDe(s)}function pDe(s){s=s|0,hDe(s+24|0)}function Rr(s){return s=s|0,n[s>>2]|0}function hDe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function gDe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,3,l,dDe()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function Vr(){return 9228}function dDe(){return 1140}function mDe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0;return c=C,C=C+16|0,f=c+8|0,d=c,m=yDe(s)|0,s=n[m+4>>2]|0,n[d>>2]=n[m>>2],n[d+4>>2]=s,n[f>>2]=n[d>>2],n[f+4>>2]=n[d+4>>2],l=EDe(l,f)|0,C=c,l|0}function zr(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0,n[s>>2]=l,n[s+4>>2]=c,n[s+8>>2]=f,n[s+12>>2]=d,n[s+16>>2]=m}function yDe(s){return s=s|0,(n[(mF()|0)+24>>2]|0)+(s*12|0)|0}function EDe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0;return d=C,C=C+48|0,f=d,c=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(c=n[(n[s>>2]|0)+c>>2]|0),tf[c&31](f,s),f=CDe(f)|0,C=d,f|0}function CDe(s){s=s|0;var l=0,c=0,f=0,d=0;return d=C,C=C+32|0,l=d+12|0,c=d,f=yF(Z5()|0)|0,f?(EF(l,f),CF(c,l),wDe(s,c),s=wF(l)|0):s=IDe(s)|0,C=d,s|0}function Z5(){var s=0;return o[7632]|0||(FDe(9184),ir(25,9184,U|0)|0,s=7632,n[s>>2]=1,n[s+4>>2]=0),9184}function yF(s){return s=s|0,n[s+36>>2]|0}function EF(s,l){s=s|0,l=l|0,n[s>>2]=l,n[s+4>>2]=s,n[s+8>>2]=0}function CF(s,l){s=s|0,l=l|0,n[s>>2]=n[l>>2],n[s+4>>2]=n[l+4>>2],n[s+8>>2]=0}function wDe(s,l){s=s|0,l=l|0,PDe(l,s,s+8|0,s+16|0,s+24|0,s+32|0,s+40|0)|0}function wF(s){return s=s|0,n[(n[s+4>>2]|0)+8>>2]|0}function IDe(s){s=s|0;var l=0,c=0,f=0,d=0,m=0,B=0,k=0,Q=0;Q=C,C=C+16|0,c=Q+4|0,f=Q,d=Va(8)|0,m=d,B=Kt(48)|0,k=B,l=k+48|0;do n[k>>2]=n[s>>2],k=k+4|0,s=s+4|0;while((k|0)<(l|0));return l=m+4|0,n[l>>2]=B,k=Kt(8)|0,B=n[l>>2]|0,n[f>>2]=0,n[c>>2]=n[f>>2],$5(k,B,c),n[d>>2]=k,C=Q,m|0}function $5(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,c=Kt(16)|0,n[c+4>>2]=0,n[c+8>>2]=0,n[c>>2]=1092,n[c+12>>2]=l,n[s+4>>2]=c}function BDe(s){s=s|0,Md(s),gt(s)}function vDe(s){s=s|0,s=n[s+12>>2]|0,s|0&&gt(s)}function DDe(s){s=s|0,gt(s)}function PDe(s,l,c,f,d,m,B){return s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0,B=B|0,m=bDe(n[s>>2]|0,l,c,f,d,m,B)|0,B=s+4|0,n[(n[B>>2]|0)+8>>2]=m,n[(n[B>>2]|0)+8>>2]|0}function bDe(s,l,c,f,d,m,B){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0,B=B|0;var k=0,Q=0;return k=C,C=C+16|0,Q=k,za(Q),s=ya(s)|0,B=SDe(s,+E[l>>3],+E[c>>3],+E[f>>3],+E[d>>3],+E[m>>3],+E[B>>3])|0,Ja(Q),C=k,B|0}function SDe(s,l,c,f,d,m,B){s=s|0,l=+l,c=+c,f=+f,d=+d,m=+m,B=+B;var k=0;return k=Pl(xDe()|0)|0,l=+VA(l),c=+VA(c),f=+VA(f),d=+VA(d),m=+VA(m),_s(0,k|0,s|0,+l,+c,+f,+d,+m,+ +VA(B))|0}function xDe(){var s=0;return o[7624]|0||(kDe(9172),s=7624,n[s>>2]=1,n[s+4>>2]=0),9172}function kDe(s){s=s|0,bl(s,QDe()|0,6)}function QDe(){return 1112}function FDe(s){s=s|0,wp(s)}function RDe(s){s=s|0,eG(s+24|0),tG(s+16|0)}function eG(s){s=s|0,NDe(s)}function tG(s){s=s|0,TDe(s)}function TDe(s){s=s|0;var l=0,c=0;if(l=n[s>>2]|0,l|0)do c=l,l=n[l>>2]|0,gt(c);while(l|0);n[s>>2]=0}function NDe(s){s=s|0;var l=0,c=0;if(l=n[s>>2]|0,l|0)do c=l,l=n[l>>2]|0,gt(c);while(l|0);n[s>>2]=0}function wp(s){s=s|0;var l=0;n[s+16>>2]=0,n[s+20>>2]=0,l=s+24|0,n[l>>2]=0,n[s+28>>2]=l,n[s+36>>2]=0,o[s+40>>0]=0,o[s+41>>0]=0}function LDe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],MDe(s,c,d,0),C=f}function MDe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=IF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=ODe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,UDe(m,f)|0,f),C=d}function IF(){var s=0,l=0;if(o[7640]|0||(nG(9232),ir(26,9232,U|0)|0,l=7640,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9232)|0)){s=9232,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));nG(9232)}return 9232}function ODe(s){return s=s|0,0}function UDe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=IF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],rG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(_De(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function rG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function _De(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=HDe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,qDe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],rG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,jDe(s,k),GDe(k),C=O;return}}function HDe(s){return s=s|0,357913941}function qDe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function jDe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function GDe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function nG(s){s=s|0,KDe(s)}function YDe(s){s=s|0,WDe(s+24|0)}function WDe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function KDe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,1,l,VDe()|0,3),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function VDe(){return 1144}function zDe(s,l,c,f,d){s=s|0,l=l|0,c=+c,f=+f,d=d|0;var m=0,B=0,k=0,Q=0;m=C,C=C+16|0,B=m+8|0,k=m,Q=JDe(s)|0,s=n[Q+4>>2]|0,n[k>>2]=n[Q>>2],n[k+4>>2]=s,n[B>>2]=n[k>>2],n[B+4>>2]=n[k+4>>2],XDe(l,B,c,f,d),C=m}function JDe(s){return s=s|0,(n[(IF()|0)+24>>2]|0)+(s*12|0)|0}function XDe(s,l,c,f,d){s=s|0,l=l|0,c=+c,f=+f,d=d|0;var m=0,B=0,k=0,Q=0,O=0;O=C,C=C+16|0,B=O+2|0,k=O+1|0,Q=O,m=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(m=n[(n[s>>2]|0)+m>>2]|0),Fu(B,c),c=+Ru(B,c),Fu(k,f),f=+Ru(k,f),XA(Q,d),Q=ZA(Q,d)|0,y7[m&1](s,c,f,Q),C=O}function Fu(s,l){s=s|0,l=+l}function Ru(s,l){return s=s|0,l=+l,+ +$De(l)}function XA(s,l){s=s|0,l=l|0}function ZA(s,l){return s=s|0,l=l|0,ZDe(l)|0}function ZDe(s){return s=s|0,s|0}function $De(s){return s=+s,+s}function ePe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],tPe(s,c,d,1),C=f}function tPe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=BF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=rPe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,nPe(m,f)|0,f),C=d}function BF(){var s=0,l=0;if(o[7648]|0||(sG(9268),ir(27,9268,U|0)|0,l=7648,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9268)|0)){s=9268,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));sG(9268)}return 9268}function rPe(s){return s=s|0,0}function nPe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=BF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],iG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(iPe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function iG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function iPe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=sPe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,oPe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],iG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,aPe(s,k),lPe(k),C=O;return}}function sPe(s){return s=s|0,357913941}function oPe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function aPe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function lPe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function sG(s){s=s|0,APe(s)}function cPe(s){s=s|0,uPe(s+24|0)}function uPe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function APe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,4,l,fPe()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function fPe(){return 1160}function pPe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0;return c=C,C=C+16|0,f=c+8|0,d=c,m=hPe(s)|0,s=n[m+4>>2]|0,n[d>>2]=n[m>>2],n[d+4>>2]=s,n[f>>2]=n[d>>2],n[f+4>>2]=n[d+4>>2],l=gPe(l,f)|0,C=c,l|0}function hPe(s){return s=s|0,(n[(BF()|0)+24>>2]|0)+(s*12|0)|0}function gPe(s,l){s=s|0,l=l|0;var c=0;return c=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(c=n[(n[s>>2]|0)+c>>2]|0),oG(F0[c&31](s)|0)|0}function oG(s){return s=s|0,s&1|0}function dPe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],mPe(s,c,d,0),C=f}function mPe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=vF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=yPe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,EPe(m,f)|0,f),C=d}function vF(){var s=0,l=0;if(o[7656]|0||(lG(9304),ir(28,9304,U|0)|0,l=7656,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9304)|0)){s=9304,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));lG(9304)}return 9304}function yPe(s){return s=s|0,0}function EPe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=vF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],aG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(CPe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function aG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function CPe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=wPe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,IPe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],aG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,BPe(s,k),vPe(k),C=O;return}}function wPe(s){return s=s|0,357913941}function IPe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function BPe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function vPe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function lG(s){s=s|0,bPe(s)}function DPe(s){s=s|0,PPe(s+24|0)}function PPe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function bPe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,5,l,SPe()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function SPe(){return 1164}function xPe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;f=C,C=C+16|0,d=f+8|0,m=f,B=kPe(s)|0,s=n[B+4>>2]|0,n[m>>2]=n[B>>2],n[m+4>>2]=s,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],QPe(l,d,c),C=f}function kPe(s){return s=s|0,(n[(vF()|0)+24>>2]|0)+(s*12|0)|0}function QPe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0;m=C,C=C+16|0,d=m,f=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(f=n[(n[s>>2]|0)+f>>2]|0),Ip(d,c),c=Bp(d,c)|0,tf[f&31](s,c),vp(d),C=m}function Ip(s,l){s=s|0,l=l|0,FPe(s,l)}function Bp(s,l){return s=s|0,l=l|0,s|0}function vp(s){s=s|0,qA(s)}function FPe(s,l){s=s|0,l=l|0,DF(s,l)}function DF(s,l){s=s|0,l=l|0,n[s>>2]=l}function RPe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],TPe(s,c,d,0),C=f}function TPe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=PF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=NPe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,LPe(m,f)|0,f),C=d}function PF(){var s=0,l=0;if(o[7664]|0||(uG(9340),ir(29,9340,U|0)|0,l=7664,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9340)|0)){s=9340,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));uG(9340)}return 9340}function NPe(s){return s=s|0,0}function LPe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=PF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],cG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(MPe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function cG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function MPe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=OPe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,UPe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],cG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,_Pe(s,k),HPe(k),C=O;return}}function OPe(s){return s=s|0,357913941}function UPe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function _Pe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function HPe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function uG(s){s=s|0,GPe(s)}function qPe(s){s=s|0,jPe(s+24|0)}function jPe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function GPe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,4,l,YPe()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function YPe(){return 1180}function WPe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=KPe(s)|0,s=n[B+4>>2]|0,n[m>>2]=n[B>>2],n[m+4>>2]=s,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],c=VPe(l,d,c)|0,C=f,c|0}function KPe(s){return s=s|0,(n[(PF()|0)+24>>2]|0)+(s*12|0)|0}function VPe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0;return m=C,C=C+16|0,d=m,f=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(f=n[(n[s>>2]|0)+f>>2]|0),v0(d,c),d=D0(d,c)|0,d=qv(IR[f&15](s,d)|0)|0,C=m,d|0}function v0(s,l){s=s|0,l=l|0}function D0(s,l){return s=s|0,l=l|0,zPe(l)|0}function qv(s){return s=s|0,s|0}function zPe(s){return s=s|0,s|0}function JPe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],XPe(s,c,d,0),C=f}function XPe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=bF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=ZPe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,$Pe(m,f)|0,f),C=d}function bF(){var s=0,l=0;if(o[7672]|0||(fG(9376),ir(30,9376,U|0)|0,l=7672,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9376)|0)){s=9376,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));fG(9376)}return 9376}function ZPe(s){return s=s|0,0}function $Pe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=bF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],AG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(ebe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function AG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function ebe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=tbe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,rbe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],AG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,nbe(s,k),ibe(k),C=O;return}}function tbe(s){return s=s|0,357913941}function rbe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function nbe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function ibe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function fG(s){s=s|0,abe(s)}function sbe(s){s=s|0,obe(s+24|0)}function obe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function abe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,5,l,pG()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function pG(){return 1196}function lbe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0;return c=C,C=C+16|0,f=c+8|0,d=c,m=cbe(s)|0,s=n[m+4>>2]|0,n[d>>2]=n[m>>2],n[d+4>>2]=s,n[f>>2]=n[d>>2],n[f+4>>2]=n[d+4>>2],l=ube(l,f)|0,C=c,l|0}function cbe(s){return s=s|0,(n[(bF()|0)+24>>2]|0)+(s*12|0)|0}function ube(s,l){s=s|0,l=l|0;var c=0;return c=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(c=n[(n[s>>2]|0)+c>>2]|0),qv(F0[c&31](s)|0)|0}function Abe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],fbe(s,c,d,1),C=f}function fbe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=SF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=pbe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,hbe(m,f)|0,f),C=d}function SF(){var s=0,l=0;if(o[7680]|0||(gG(9412),ir(31,9412,U|0)|0,l=7680,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9412)|0)){s=9412,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));gG(9412)}return 9412}function pbe(s){return s=s|0,0}function hbe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=SF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],hG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(gbe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function hG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function gbe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=dbe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,mbe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],hG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,ybe(s,k),Ebe(k),C=O;return}}function dbe(s){return s=s|0,357913941}function mbe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function ybe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function Ebe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function gG(s){s=s|0,Ibe(s)}function Cbe(s){s=s|0,wbe(s+24|0)}function wbe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function Ibe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,6,l,dG()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function dG(){return 1200}function Bbe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0;return c=C,C=C+16|0,f=c+8|0,d=c,m=vbe(s)|0,s=n[m+4>>2]|0,n[d>>2]=n[m>>2],n[d+4>>2]=s,n[f>>2]=n[d>>2],n[f+4>>2]=n[d+4>>2],l=Dbe(l,f)|0,C=c,l|0}function vbe(s){return s=s|0,(n[(SF()|0)+24>>2]|0)+(s*12|0)|0}function Dbe(s,l){s=s|0,l=l|0;var c=0;return c=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(c=n[(n[s>>2]|0)+c>>2]|0),jv(F0[c&31](s)|0)|0}function jv(s){return s=s|0,s|0}function Pbe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],bbe(s,c,d,0),C=f}function bbe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=xF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=Sbe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,xbe(m,f)|0,f),C=d}function xF(){var s=0,l=0;if(o[7688]|0||(yG(9448),ir(32,9448,U|0)|0,l=7688,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9448)|0)){s=9448,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));yG(9448)}return 9448}function Sbe(s){return s=s|0,0}function xbe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=xF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],mG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(kbe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function mG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function kbe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=Qbe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,Fbe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],mG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,Rbe(s,k),Tbe(k),C=O;return}}function Qbe(s){return s=s|0,357913941}function Fbe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function Rbe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function Tbe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function yG(s){s=s|0,Mbe(s)}function Nbe(s){s=s|0,Lbe(s+24|0)}function Lbe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function Mbe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,6,l,EG()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function EG(){return 1204}function Obe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;f=C,C=C+16|0,d=f+8|0,m=f,B=Ube(s)|0,s=n[B+4>>2]|0,n[m>>2]=n[B>>2],n[m+4>>2]=s,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],_be(l,d,c),C=f}function Ube(s){return s=s|0,(n[(xF()|0)+24>>2]|0)+(s*12|0)|0}function _be(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0;m=C,C=C+16|0,d=m,f=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(f=n[(n[s>>2]|0)+f>>2]|0),kF(d,c),d=QF(d,c)|0,tf[f&31](s,d),C=m}function kF(s,l){s=s|0,l=l|0}function QF(s,l){return s=s|0,l=l|0,Hbe(l)|0}function Hbe(s){return s=s|0,s|0}function qbe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],jbe(s,c,d,0),C=f}function jbe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=FF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=Gbe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,Ybe(m,f)|0,f),C=d}function FF(){var s=0,l=0;if(o[7696]|0||(wG(9484),ir(33,9484,U|0)|0,l=7696,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9484)|0)){s=9484,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));wG(9484)}return 9484}function Gbe(s){return s=s|0,0}function Ybe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=FF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],CG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(Wbe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function CG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function Wbe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=Kbe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,Vbe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],CG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,zbe(s,k),Jbe(k),C=O;return}}function Kbe(s){return s=s|0,357913941}function Vbe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function zbe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function Jbe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function wG(s){s=s|0,$be(s)}function Xbe(s){s=s|0,Zbe(s+24|0)}function Zbe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function $be(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,1,l,eSe()|0,2),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function eSe(){return 1212}function tSe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0;d=C,C=C+16|0,m=d+8|0,B=d,k=rSe(s)|0,s=n[k+4>>2]|0,n[B>>2]=n[k>>2],n[B+4>>2]=s,n[m>>2]=n[B>>2],n[m+4>>2]=n[B+4>>2],nSe(l,m,c,f),C=d}function rSe(s){return s=s|0,(n[(FF()|0)+24>>2]|0)+(s*12|0)|0}function nSe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0;k=C,C=C+16|0,m=k+1|0,B=k,d=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(d=n[(n[s>>2]|0)+d>>2]|0),kF(m,c),m=QF(m,c)|0,v0(B,f),B=D0(B,f)|0,vw[d&15](s,m,B),C=k}function iSe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],sSe(s,c,d,1),C=f}function sSe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=RF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=oSe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,aSe(m,f)|0,f),C=d}function RF(){var s=0,l=0;if(o[7704]|0||(BG(9520),ir(34,9520,U|0)|0,l=7704,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9520)|0)){s=9520,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));BG(9520)}return 9520}function oSe(s){return s=s|0,0}function aSe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=RF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],IG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(lSe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function IG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function lSe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=cSe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,uSe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],IG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,ASe(s,k),fSe(k),C=O;return}}function cSe(s){return s=s|0,357913941}function uSe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function ASe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function fSe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function BG(s){s=s|0,gSe(s)}function pSe(s){s=s|0,hSe(s+24|0)}function hSe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function gSe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,1,l,dSe()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function dSe(){return 1224}function mSe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;return d=C,C=C+16|0,m=d+8|0,B=d,k=ySe(s)|0,s=n[k+4>>2]|0,n[B>>2]=n[k>>2],n[B+4>>2]=s,n[m>>2]=n[B>>2],n[m+4>>2]=n[B+4>>2],f=+ESe(l,m,c),C=d,+f}function ySe(s){return s=s|0,(n[(RF()|0)+24>>2]|0)+(s*12|0)|0}function ESe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return m=C,C=C+16|0,d=m,f=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(f=n[(n[s>>2]|0)+f>>2]|0),XA(d,c),d=ZA(d,c)|0,B=+gF(+C7[f&7](s,d)),C=m,+B}function CSe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],wSe(s,c,d,1),C=f}function wSe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=TF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=ISe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,BSe(m,f)|0,f),C=d}function TF(){var s=0,l=0;if(o[7712]|0||(DG(9556),ir(35,9556,U|0)|0,l=7712,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9556)|0)){s=9556,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));DG(9556)}return 9556}function ISe(s){return s=s|0,0}function BSe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=TF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],vG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(vSe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function vG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function vSe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=DSe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,PSe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],vG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,bSe(s,k),SSe(k),C=O;return}}function DSe(s){return s=s|0,357913941}function PSe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function bSe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function SSe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function DG(s){s=s|0,QSe(s)}function xSe(s){s=s|0,kSe(s+24|0)}function kSe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function QSe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,5,l,FSe()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function FSe(){return 1232}function RSe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=TSe(s)|0,s=n[B+4>>2]|0,n[m>>2]=n[B>>2],n[m+4>>2]=s,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],c=+NSe(l,d),C=f,+c}function TSe(s){return s=s|0,(n[(TF()|0)+24>>2]|0)+(s*12|0)|0}function NSe(s,l){s=s|0,l=l|0;var c=0;return c=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(c=n[(n[s>>2]|0)+c>>2]|0),+ +gF(+E7[c&15](s))}function LSe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],MSe(s,c,d,1),C=f}function MSe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=NF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=OSe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,USe(m,f)|0,f),C=d}function NF(){var s=0,l=0;if(o[7720]|0||(bG(9592),ir(36,9592,U|0)|0,l=7720,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9592)|0)){s=9592,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));bG(9592)}return 9592}function OSe(s){return s=s|0,0}function USe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=NF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],PG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(_Se(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function PG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function _Se(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=HSe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,qSe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],PG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,jSe(s,k),GSe(k),C=O;return}}function HSe(s){return s=s|0,357913941}function qSe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function jSe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function GSe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function bG(s){s=s|0,KSe(s)}function YSe(s){s=s|0,WSe(s+24|0)}function WSe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function KSe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,7,l,VSe()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function VSe(){return 1276}function zSe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0;return c=C,C=C+16|0,f=c+8|0,d=c,m=JSe(s)|0,s=n[m+4>>2]|0,n[d>>2]=n[m>>2],n[d+4>>2]=s,n[f>>2]=n[d>>2],n[f+4>>2]=n[d+4>>2],l=XSe(l,f)|0,C=c,l|0}function JSe(s){return s=s|0,(n[(NF()|0)+24>>2]|0)+(s*12|0)|0}function XSe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0;return d=C,C=C+16|0,f=d,c=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(c=n[(n[s>>2]|0)+c>>2]|0),tf[c&31](f,s),f=SG(f)|0,C=d,f|0}function SG(s){s=s|0;var l=0,c=0,f=0,d=0;return d=C,C=C+32|0,l=d+12|0,c=d,f=yF(xG()|0)|0,f?(EF(l,f),CF(c,l),ZSe(s,c),s=wF(l)|0):s=$Se(s)|0,C=d,s|0}function xG(){var s=0;return o[7736]|0||(cxe(9640),ir(25,9640,U|0)|0,s=7736,n[s>>2]=1,n[s+4>>2]=0),9640}function ZSe(s,l){s=s|0,l=l|0,nxe(l,s,s+8|0)|0}function $Se(s){s=s|0;var l=0,c=0,f=0,d=0,m=0,B=0,k=0;return c=C,C=C+16|0,d=c+4|0,B=c,f=Va(8)|0,l=f,k=Kt(16)|0,n[k>>2]=n[s>>2],n[k+4>>2]=n[s+4>>2],n[k+8>>2]=n[s+8>>2],n[k+12>>2]=n[s+12>>2],m=l+4|0,n[m>>2]=k,s=Kt(8)|0,m=n[m>>2]|0,n[B>>2]=0,n[d>>2]=n[B>>2],LF(s,m,d),n[f>>2]=s,C=c,l|0}function LF(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,c=Kt(16)|0,n[c+4>>2]=0,n[c+8>>2]=0,n[c>>2]=1244,n[c+12>>2]=l,n[s+4>>2]=c}function exe(s){s=s|0,Md(s),gt(s)}function txe(s){s=s|0,s=n[s+12>>2]|0,s|0&&gt(s)}function rxe(s){s=s|0,gt(s)}function nxe(s,l,c){return s=s|0,l=l|0,c=c|0,l=ixe(n[s>>2]|0,l,c)|0,c=s+4|0,n[(n[c>>2]|0)+8>>2]=l,n[(n[c>>2]|0)+8>>2]|0}function ixe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0;return f=C,C=C+16|0,d=f,za(d),s=ya(s)|0,c=sxe(s,n[l>>2]|0,+E[c>>3])|0,Ja(d),C=f,c|0}function sxe(s,l,c){s=s|0,l=l|0,c=+c;var f=0;return f=Pl(oxe()|0)|0,l=hF(l)|0,ml(0,f|0,s|0,l|0,+ +VA(c))|0}function oxe(){var s=0;return o[7728]|0||(axe(9628),s=7728,n[s>>2]=1,n[s+4>>2]=0),9628}function axe(s){s=s|0,bl(s,lxe()|0,2)}function lxe(){return 1264}function cxe(s){s=s|0,wp(s)}function uxe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],Axe(s,c,d,1),C=f}function Axe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=MF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=fxe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,pxe(m,f)|0,f),C=d}function MF(){var s=0,l=0;if(o[7744]|0||(QG(9684),ir(37,9684,U|0)|0,l=7744,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9684)|0)){s=9684,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));QG(9684)}return 9684}function fxe(s){return s=s|0,0}function pxe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=MF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],kG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(hxe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function kG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function hxe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=gxe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,dxe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],kG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,mxe(s,k),yxe(k),C=O;return}}function gxe(s){return s=s|0,357913941}function dxe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function mxe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function yxe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function QG(s){s=s|0,wxe(s)}function Exe(s){s=s|0,Cxe(s+24|0)}function Cxe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function wxe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,5,l,Ixe()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function Ixe(){return 1280}function Bxe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=vxe(s)|0,s=n[B+4>>2]|0,n[m>>2]=n[B>>2],n[m+4>>2]=s,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],c=Dxe(l,d,c)|0,C=f,c|0}function vxe(s){return s=s|0,(n[(MF()|0)+24>>2]|0)+(s*12|0)|0}function Dxe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return B=C,C=C+32|0,d=B,m=B+16|0,f=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(f=n[(n[s>>2]|0)+f>>2]|0),XA(m,c),m=ZA(m,c)|0,vw[f&15](d,s,m),m=SG(d)|0,C=B,m|0}function Pxe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],bxe(s,c,d,1),C=f}function bxe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=OF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=Sxe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,xxe(m,f)|0,f),C=d}function OF(){var s=0,l=0;if(o[7752]|0||(RG(9720),ir(38,9720,U|0)|0,l=7752,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9720)|0)){s=9720,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));RG(9720)}return 9720}function Sxe(s){return s=s|0,0}function xxe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=OF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],FG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(kxe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function FG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function kxe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=Qxe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,Fxe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],FG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,Rxe(s,k),Txe(k),C=O;return}}function Qxe(s){return s=s|0,357913941}function Fxe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function Rxe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function Txe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function RG(s){s=s|0,Mxe(s)}function Nxe(s){s=s|0,Lxe(s+24|0)}function Lxe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function Mxe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,8,l,Oxe()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function Oxe(){return 1288}function Uxe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0;return c=C,C=C+16|0,f=c+8|0,d=c,m=_xe(s)|0,s=n[m+4>>2]|0,n[d>>2]=n[m>>2],n[d+4>>2]=s,n[f>>2]=n[d>>2],n[f+4>>2]=n[d+4>>2],l=Hxe(l,f)|0,C=c,l|0}function _xe(s){return s=s|0,(n[(OF()|0)+24>>2]|0)+(s*12|0)|0}function Hxe(s,l){s=s|0,l=l|0;var c=0;return c=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(c=n[(n[s>>2]|0)+c>>2]|0),V5(F0[c&31](s)|0)|0}function qxe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],jxe(s,c,d,0),C=f}function jxe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=UF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=Gxe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,Yxe(m,f)|0,f),C=d}function UF(){var s=0,l=0;if(o[7760]|0||(NG(9756),ir(39,9756,U|0)|0,l=7760,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9756)|0)){s=9756,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));NG(9756)}return 9756}function Gxe(s){return s=s|0,0}function Yxe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=UF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],TG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(Wxe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function TG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function Wxe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=Kxe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,Vxe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],TG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,zxe(s,k),Jxe(k),C=O;return}}function Kxe(s){return s=s|0,357913941}function Vxe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function zxe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function Jxe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function NG(s){s=s|0,$xe(s)}function Xxe(s){s=s|0,Zxe(s+24|0)}function Zxe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function $xe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,8,l,eke()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function eke(){return 1292}function tke(s,l,c){s=s|0,l=l|0,c=+c;var f=0,d=0,m=0,B=0;f=C,C=C+16|0,d=f+8|0,m=f,B=rke(s)|0,s=n[B+4>>2]|0,n[m>>2]=n[B>>2],n[m+4>>2]=s,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],nke(l,d,c),C=f}function rke(s){return s=s|0,(n[(UF()|0)+24>>2]|0)+(s*12|0)|0}function nke(s,l,c){s=s|0,l=l|0,c=+c;var f=0,d=0,m=0;m=C,C=C+16|0,d=m,f=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(f=n[(n[s>>2]|0)+f>>2]|0),Fu(d,c),c=+Ru(d,c),d7[f&31](s,c),C=m}function ike(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],ske(s,c,d,0),C=f}function ske(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=_F()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=oke(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,ake(m,f)|0,f),C=d}function _F(){var s=0,l=0;if(o[7768]|0||(MG(9792),ir(40,9792,U|0)|0,l=7768,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9792)|0)){s=9792,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));MG(9792)}return 9792}function oke(s){return s=s|0,0}function ake(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=_F()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],LG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(lke(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function LG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function lke(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=cke(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,uke(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],LG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,Ake(s,k),fke(k),C=O;return}}function cke(s){return s=s|0,357913941}function uke(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function Ake(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function fke(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function MG(s){s=s|0,gke(s)}function pke(s){s=s|0,hke(s+24|0)}function hke(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function gke(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,1,l,dke()|0,2),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function dke(){return 1300}function mke(s,l,c,f){s=s|0,l=l|0,c=c|0,f=+f;var d=0,m=0,B=0,k=0;d=C,C=C+16|0,m=d+8|0,B=d,k=yke(s)|0,s=n[k+4>>2]|0,n[B>>2]=n[k>>2],n[B+4>>2]=s,n[m>>2]=n[B>>2],n[m+4>>2]=n[B+4>>2],Eke(l,m,c,f),C=d}function yke(s){return s=s|0,(n[(_F()|0)+24>>2]|0)+(s*12|0)|0}function Eke(s,l,c,f){s=s|0,l=l|0,c=c|0,f=+f;var d=0,m=0,B=0,k=0;k=C,C=C+16|0,m=k+1|0,B=k,d=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(d=n[(n[s>>2]|0)+d>>2]|0),XA(m,c),m=ZA(m,c)|0,Fu(B,f),f=+Ru(B,f),v7[d&15](s,m,f),C=k}function Cke(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],wke(s,c,d,0),C=f}function wke(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=HF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=Ike(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,Bke(m,f)|0,f),C=d}function HF(){var s=0,l=0;if(o[7776]|0||(UG(9828),ir(41,9828,U|0)|0,l=7776,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9828)|0)){s=9828,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));UG(9828)}return 9828}function Ike(s){return s=s|0,0}function Bke(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=HF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],OG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(vke(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function OG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function vke(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=Dke(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,Pke(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],OG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,bke(s,k),Ske(k),C=O;return}}function Dke(s){return s=s|0,357913941}function Pke(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function bke(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function Ske(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function UG(s){s=s|0,Qke(s)}function xke(s){s=s|0,kke(s+24|0)}function kke(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function Qke(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,7,l,Fke()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function Fke(){return 1312}function Rke(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;f=C,C=C+16|0,d=f+8|0,m=f,B=Tke(s)|0,s=n[B+4>>2]|0,n[m>>2]=n[B>>2],n[m+4>>2]=s,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],Nke(l,d,c),C=f}function Tke(s){return s=s|0,(n[(HF()|0)+24>>2]|0)+(s*12|0)|0}function Nke(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0;m=C,C=C+16|0,d=m,f=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(f=n[(n[s>>2]|0)+f>>2]|0),XA(d,c),d=ZA(d,c)|0,tf[f&31](s,d),C=m}function Lke(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],Mke(s,c,d,0),C=f}function Mke(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=qF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=Oke(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,Uke(m,f)|0,f),C=d}function qF(){var s=0,l=0;if(o[7784]|0||(HG(9864),ir(42,9864,U|0)|0,l=7784,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9864)|0)){s=9864,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));HG(9864)}return 9864}function Oke(s){return s=s|0,0}function Uke(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=qF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],_G(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(_ke(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function _G(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function _ke(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=Hke(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,qke(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],_G(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,jke(s,k),Gke(k),C=O;return}}function Hke(s){return s=s|0,357913941}function qke(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function jke(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function Gke(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function HG(s){s=s|0,Kke(s)}function Yke(s){s=s|0,Wke(s+24|0)}function Wke(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function Kke(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,8,l,Vke()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function Vke(){return 1320}function zke(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;f=C,C=C+16|0,d=f+8|0,m=f,B=Jke(s)|0,s=n[B+4>>2]|0,n[m>>2]=n[B>>2],n[m+4>>2]=s,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],Xke(l,d,c),C=f}function Jke(s){return s=s|0,(n[(qF()|0)+24>>2]|0)+(s*12|0)|0}function Xke(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0;m=C,C=C+16|0,d=m,f=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(f=n[(n[s>>2]|0)+f>>2]|0),Zke(d,c),d=$ke(d,c)|0,tf[f&31](s,d),C=m}function Zke(s,l){s=s|0,l=l|0}function $ke(s,l){return s=s|0,l=l|0,eQe(l)|0}function eQe(s){return s=s|0,s|0}function tQe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],rQe(s,c,d,0),C=f}function rQe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=jF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=nQe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,iQe(m,f)|0,f),C=d}function jF(){var s=0,l=0;if(o[7792]|0||(jG(9900),ir(43,9900,U|0)|0,l=7792,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9900)|0)){s=9900,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));jG(9900)}return 9900}function nQe(s){return s=s|0,0}function iQe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=jF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],qG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(sQe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function qG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function sQe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=oQe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,aQe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],qG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,lQe(s,k),cQe(k),C=O;return}}function oQe(s){return s=s|0,357913941}function aQe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function lQe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function cQe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function jG(s){s=s|0,fQe(s)}function uQe(s){s=s|0,AQe(s+24|0)}function AQe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function fQe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,22,l,pQe()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function pQe(){return 1344}function hQe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0;c=C,C=C+16|0,f=c+8|0,d=c,m=gQe(s)|0,s=n[m+4>>2]|0,n[d>>2]=n[m>>2],n[d+4>>2]=s,n[f>>2]=n[d>>2],n[f+4>>2]=n[d+4>>2],dQe(l,f),C=c}function gQe(s){return s=s|0,(n[(jF()|0)+24>>2]|0)+(s*12|0)|0}function dQe(s,l){s=s|0,l=l|0;var c=0;c=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(c=n[(n[s>>2]|0)+c>>2]|0),ef[c&127](s)}function mQe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;m=n[s>>2]|0,d=GF()|0,s=yQe(c)|0,hn(m,l,d,s,EQe(c,f)|0,f)}function GF(){var s=0,l=0;if(o[7800]|0||(YG(9936),ir(44,9936,U|0)|0,l=7800,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9936)|0)){s=9936,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));YG(9936)}return 9936}function yQe(s){return s=s|0,s|0}function EQe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return k=C,C=C+16|0,d=k,m=k+4|0,n[d>>2]=s,Q=GF()|0,B=Q+24|0,l=gr(l,4)|0,n[m>>2]=l,c=Q+28|0,f=n[c>>2]|0,f>>>0<(n[Q+32>>2]|0)>>>0?(GG(f,s,l),l=(n[c>>2]|0)+8|0,n[c>>2]=l):(CQe(B,d,m),l=n[c>>2]|0),C=k,(l-(n[B>>2]|0)>>3)+-1|0}function GG(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c}function CQe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;if(k=C,C=C+32|0,d=k,m=s+4|0,B=((n[m>>2]|0)-(n[s>>2]|0)>>3)+1|0,f=wQe(s)|0,f>>>0<B>>>0)Jr(s);else{Q=n[s>>2]|0,M=(n[s+8>>2]|0)-Q|0,O=M>>2,IQe(d,M>>3>>>0<f>>>1>>>0?O>>>0<B>>>0?B:O:f,(n[m>>2]|0)-Q>>3,s+8|0),B=d+8|0,GG(n[B>>2]|0,n[l>>2]|0,n[c>>2]|0),n[B>>2]=(n[B>>2]|0)+8,BQe(s,d),vQe(d),C=k;return}}function wQe(s){return s=s|0,536870911}function IQe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>536870911)Tt();else{d=Kt(l<<3)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<3)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<3)}function BQe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>3)<<3)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function vQe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&gt(s)}function YG(s){s=s|0,bQe(s)}function DQe(s){s=s|0,PQe(s+24|0)}function PQe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function bQe(s){s=s|0;var l=0;l=Vr()|0,zr(s,1,23,l,EG()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function SQe(s,l){s=s|0,l=l|0,kQe(n[(xQe(s)|0)>>2]|0,l)}function xQe(s){return s=s|0,(n[(GF()|0)+24>>2]|0)+(s<<3)|0}function kQe(s,l){s=s|0,l=l|0;var c=0,f=0;c=C,C=C+16|0,f=c,kF(f,l),l=QF(f,l)|0,ef[s&127](l),C=c}function QQe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;m=n[s>>2]|0,d=YF()|0,s=FQe(c)|0,hn(m,l,d,s,RQe(c,f)|0,f)}function YF(){var s=0,l=0;if(o[7808]|0||(KG(9972),ir(45,9972,U|0)|0,l=7808,n[l>>2]=1,n[l+4>>2]=0),!(Rr(9972)|0)){s=9972,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));KG(9972)}return 9972}function FQe(s){return s=s|0,s|0}function RQe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return k=C,C=C+16|0,d=k,m=k+4|0,n[d>>2]=s,Q=YF()|0,B=Q+24|0,l=gr(l,4)|0,n[m>>2]=l,c=Q+28|0,f=n[c>>2]|0,f>>>0<(n[Q+32>>2]|0)>>>0?(WG(f,s,l),l=(n[c>>2]|0)+8|0,n[c>>2]=l):(TQe(B,d,m),l=n[c>>2]|0),C=k,(l-(n[B>>2]|0)>>3)+-1|0}function WG(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c}function TQe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;if(k=C,C=C+32|0,d=k,m=s+4|0,B=((n[m>>2]|0)-(n[s>>2]|0)>>3)+1|0,f=NQe(s)|0,f>>>0<B>>>0)Jr(s);else{Q=n[s>>2]|0,M=(n[s+8>>2]|0)-Q|0,O=M>>2,LQe(d,M>>3>>>0<f>>>1>>>0?O>>>0<B>>>0?B:O:f,(n[m>>2]|0)-Q>>3,s+8|0),B=d+8|0,WG(n[B>>2]|0,n[l>>2]|0,n[c>>2]|0),n[B>>2]=(n[B>>2]|0)+8,MQe(s,d),OQe(d),C=k;return}}function NQe(s){return s=s|0,536870911}function LQe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>536870911)Tt();else{d=Kt(l<<3)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<3)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<3)}function MQe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>3)<<3)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function OQe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&gt(s)}function KG(s){s=s|0,HQe(s)}function UQe(s){s=s|0,_Qe(s+24|0)}function _Qe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function HQe(s){s=s|0;var l=0;l=Vr()|0,zr(s,1,9,l,qQe()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function qQe(){return 1348}function jQe(s,l){return s=s|0,l=l|0,YQe(n[(GQe(s)|0)>>2]|0,l)|0}function GQe(s){return s=s|0,(n[(YF()|0)+24>>2]|0)+(s<<3)|0}function YQe(s,l){s=s|0,l=l|0;var c=0,f=0;return c=C,C=C+16|0,f=c,VG(f,l),l=zG(f,l)|0,l=qv(F0[s&31](l)|0)|0,C=c,l|0}function VG(s,l){s=s|0,l=l|0}function zG(s,l){return s=s|0,l=l|0,WQe(l)|0}function WQe(s){return s=s|0,s|0}function KQe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;m=n[s>>2]|0,d=WF()|0,s=VQe(c)|0,hn(m,l,d,s,zQe(c,f)|0,f)}function WF(){var s=0,l=0;if(o[7816]|0||(XG(10008),ir(46,10008,U|0)|0,l=7816,n[l>>2]=1,n[l+4>>2]=0),!(Rr(10008)|0)){s=10008,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));XG(10008)}return 10008}function VQe(s){return s=s|0,s|0}function zQe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return k=C,C=C+16|0,d=k,m=k+4|0,n[d>>2]=s,Q=WF()|0,B=Q+24|0,l=gr(l,4)|0,n[m>>2]=l,c=Q+28|0,f=n[c>>2]|0,f>>>0<(n[Q+32>>2]|0)>>>0?(JG(f,s,l),l=(n[c>>2]|0)+8|0,n[c>>2]=l):(JQe(B,d,m),l=n[c>>2]|0),C=k,(l-(n[B>>2]|0)>>3)+-1|0}function JG(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c}function JQe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;if(k=C,C=C+32|0,d=k,m=s+4|0,B=((n[m>>2]|0)-(n[s>>2]|0)>>3)+1|0,f=XQe(s)|0,f>>>0<B>>>0)Jr(s);else{Q=n[s>>2]|0,M=(n[s+8>>2]|0)-Q|0,O=M>>2,ZQe(d,M>>3>>>0<f>>>1>>>0?O>>>0<B>>>0?B:O:f,(n[m>>2]|0)-Q>>3,s+8|0),B=d+8|0,JG(n[B>>2]|0,n[l>>2]|0,n[c>>2]|0),n[B>>2]=(n[B>>2]|0)+8,$Qe(s,d),eFe(d),C=k;return}}function XQe(s){return s=s|0,536870911}function ZQe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>536870911)Tt();else{d=Kt(l<<3)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<3)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<3)}function $Qe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>3)<<3)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function eFe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&gt(s)}function XG(s){s=s|0,nFe(s)}function tFe(s){s=s|0,rFe(s+24|0)}function rFe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function nFe(s){s=s|0;var l=0;l=Vr()|0,zr(s,1,15,l,pG()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function iFe(s){return s=s|0,oFe(n[(sFe(s)|0)>>2]|0)|0}function sFe(s){return s=s|0,(n[(WF()|0)+24>>2]|0)+(s<<3)|0}function oFe(s){return s=s|0,qv(nD[s&7]()|0)|0}function aFe(){var s=0;return o[7832]|0||(gFe(10052),ir(25,10052,U|0)|0,s=7832,n[s>>2]=1,n[s+4>>2]=0),10052}function lFe(s,l){s=s|0,l=l|0,n[s>>2]=cFe()|0,n[s+4>>2]=uFe()|0,n[s+12>>2]=l,n[s+8>>2]=AFe()|0,n[s+32>>2]=2}function cFe(){return 11709}function uFe(){return 1188}function AFe(){return Gv()|0}function fFe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,(Dp(f,896)|0)==512?c|0&&(pFe(c),gt(c)):l|0&&(Su(l),gt(l))}function Dp(s,l){return s=s|0,l=l|0,l&s|0}function pFe(s){s=s|0,s=n[s+4>>2]|0,s|0&&bp(s)}function Gv(){var s=0;return o[7824]|0||(n[2511]=hFe()|0,n[2512]=0,s=7824,n[s>>2]=1,n[s+4>>2]=0),10044}function hFe(){return 0}function gFe(s){s=s|0,wp(s)}function dFe(s){s=s|0;var l=0,c=0,f=0,d=0,m=0;l=C,C=C+32|0,c=l+24|0,m=l+16|0,d=l+8|0,f=l,mFe(s,4827),yFe(s,4834,3)|0,EFe(s,3682,47)|0,n[m>>2]=9,n[m+4>>2]=0,n[c>>2]=n[m>>2],n[c+4>>2]=n[m+4>>2],CFe(s,4841,c)|0,n[d>>2]=1,n[d+4>>2]=0,n[c>>2]=n[d>>2],n[c+4>>2]=n[d+4>>2],wFe(s,4871,c)|0,n[f>>2]=10,n[f+4>>2]=0,n[c>>2]=n[f>>2],n[c+4>>2]=n[f+4>>2],IFe(s,4891,c)|0,C=l}function mFe(s,l){s=s|0,l=l|0;var c=0;c=eTe()|0,n[s>>2]=c,tTe(c,l),Pp(n[s>>2]|0)}function yFe(s,l,c){return s=s|0,l=l|0,c=c|0,ORe(s,pn(l)|0,c,0),s|0}function EFe(s,l,c){return s=s|0,l=l|0,c=c|0,BRe(s,pn(l)|0,c,0),s|0}function CFe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],iRe(s,l,d),C=f,s|0}function wFe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],UFe(s,l,d),C=f,s|0}function IFe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=n[c+4>>2]|0,n[m>>2]=n[c>>2],n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],BFe(s,l,d),C=f,s|0}function BFe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],vFe(s,c,d,1),C=f}function vFe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=KF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=DFe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,PFe(m,f)|0,f),C=d}function KF(){var s=0,l=0;if(o[7840]|0||($G(10100),ir(48,10100,U|0)|0,l=7840,n[l>>2]=1,n[l+4>>2]=0),!(Rr(10100)|0)){s=10100,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));$G(10100)}return 10100}function DFe(s){return s=s|0,0}function PFe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=KF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],ZG(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(bFe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function ZG(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function bFe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=SFe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,xFe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],ZG(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,kFe(s,k),QFe(k),C=O;return}}function SFe(s){return s=s|0,357913941}function xFe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function kFe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function QFe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function $G(s){s=s|0,TFe(s)}function FFe(s){s=s|0,RFe(s+24|0)}function RFe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function TFe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,6,l,NFe()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function NFe(){return 1364}function LFe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;return f=C,C=C+16|0,d=f+8|0,m=f,B=MFe(s)|0,s=n[B+4>>2]|0,n[m>>2]=n[B>>2],n[m+4>>2]=s,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],c=OFe(l,d,c)|0,C=f,c|0}function MFe(s){return s=s|0,(n[(KF()|0)+24>>2]|0)+(s*12|0)|0}function OFe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0;return m=C,C=C+16|0,d=m,f=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(f=n[(n[s>>2]|0)+f>>2]|0),XA(d,c),d=ZA(d,c)|0,d=oG(IR[f&15](s,d)|0)|0,C=m,d|0}function UFe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],_Fe(s,c,d,0),C=f}function _Fe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=VF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=HFe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,qFe(m,f)|0,f),C=d}function VF(){var s=0,l=0;if(o[7848]|0||(t9(10136),ir(49,10136,U|0)|0,l=7848,n[l>>2]=1,n[l+4>>2]=0),!(Rr(10136)|0)){s=10136,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));t9(10136)}return 10136}function HFe(s){return s=s|0,0}function qFe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=VF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],e9(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(jFe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function e9(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function jFe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=GFe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,YFe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],e9(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,WFe(s,k),KFe(k),C=O;return}}function GFe(s){return s=s|0,357913941}function YFe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function WFe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function KFe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function t9(s){s=s|0,JFe(s)}function VFe(s){s=s|0,zFe(s+24|0)}function zFe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function JFe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,9,l,XFe()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function XFe(){return 1372}function ZFe(s,l,c){s=s|0,l=l|0,c=+c;var f=0,d=0,m=0,B=0;f=C,C=C+16|0,d=f+8|0,m=f,B=$Fe(s)|0,s=n[B+4>>2]|0,n[m>>2]=n[B>>2],n[m+4>>2]=s,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],eRe(l,d,c),C=f}function $Fe(s){return s=s|0,(n[(VF()|0)+24>>2]|0)+(s*12|0)|0}function eRe(s,l,c){s=s|0,l=l|0,c=+c;var f=0,d=0,m=0,B=Xe;m=C,C=C+16|0,d=m,f=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(f=n[(n[s>>2]|0)+f>>2]|0),tRe(d,c),B=y(rRe(d,c)),g7[f&1](s,B),C=m}function tRe(s,l){s=s|0,l=+l}function rRe(s,l){return s=s|0,l=+l,y(nRe(l))}function nRe(s){return s=+s,y(s)}function iRe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,d=f+8|0,m=f,k=n[c>>2]|0,B=n[c+4>>2]|0,c=pn(l)|0,n[m>>2]=k,n[m+4>>2]=B,n[d>>2]=n[m>>2],n[d+4>>2]=n[m+4>>2],sRe(s,c,d,0),C=f}function sRe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0,Q=0,O=0,M=0;d=C,C=C+32|0,m=d+16|0,M=d+8|0,k=d,O=n[c>>2]|0,Q=n[c+4>>2]|0,B=n[s>>2]|0,s=zF()|0,n[M>>2]=O,n[M+4>>2]=Q,n[m>>2]=n[M>>2],n[m+4>>2]=n[M+4>>2],c=oRe(m)|0,n[k>>2]=O,n[k+4>>2]=Q,n[m>>2]=n[k>>2],n[m+4>>2]=n[k+4>>2],hn(B,l,s,c,aRe(m,f)|0,f),C=d}function zF(){var s=0,l=0;if(o[7856]|0||(n9(10172),ir(50,10172,U|0)|0,l=7856,n[l>>2]=1,n[l+4>>2]=0),!(Rr(10172)|0)){s=10172,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));n9(10172)}return 10172}function oRe(s){return s=s|0,0}function aRe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0;return M=C,C=C+32|0,d=M+24|0,B=M+16|0,k=M,Q=M+8|0,m=n[s>>2]|0,f=n[s+4>>2]|0,n[k>>2]=m,n[k+4>>2]=f,j=zF()|0,O=j+24|0,s=gr(l,4)|0,n[Q>>2]=s,l=j+28|0,c=n[l>>2]|0,c>>>0<(n[j+32>>2]|0)>>>0?(n[B>>2]=m,n[B+4>>2]=f,n[d>>2]=n[B>>2],n[d+4>>2]=n[B+4>>2],r9(c,d,s),s=(n[l>>2]|0)+12|0,n[l>>2]=s):(lRe(O,k,Q),s=n[l>>2]|0),C=M,((s-(n[O>>2]|0)|0)/12|0)+-1|0}function r9(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=n[l+4>>2]|0,n[s>>2]=n[l>>2],n[s+4>>2]=f,n[s+8>>2]=c}function lRe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;if(O=C,C=C+48|0,f=O+32|0,B=O+24|0,k=O,Q=s+4|0,d=(((n[Q>>2]|0)-(n[s>>2]|0)|0)/12|0)+1|0,m=cRe(s)|0,m>>>0<d>>>0)Jr(s);else{M=n[s>>2]|0,se=((n[s+8>>2]|0)-M|0)/12|0,j=se<<1,uRe(k,se>>>0<m>>>1>>>0?j>>>0<d>>>0?d:j:m,((n[Q>>2]|0)-M|0)/12|0,s+8|0),Q=k+8|0,m=n[Q>>2]|0,d=n[l+4>>2]|0,c=n[c>>2]|0,n[B>>2]=n[l>>2],n[B+4>>2]=d,n[f>>2]=n[B>>2],n[f+4>>2]=n[B+4>>2],r9(m,f,c),n[Q>>2]=(n[Q>>2]|0)+12,ARe(s,k),fRe(k),C=O;return}}function cRe(s){return s=s|0,357913941}function uRe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>357913941)Tt();else{d=Kt(l*12|0)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c*12|0)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l*12|0)}function ARe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(((d|0)/-12|0)*12|0)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function fRe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~(((f+-12-l|0)>>>0)/12|0)*12|0)),s=n[s>>2]|0,s|0&&gt(s)}function n9(s){s=s|0,gRe(s)}function pRe(s){s=s|0,hRe(s+24|0)}function hRe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~(((l+-12-f|0)>>>0)/12|0)*12|0)),gt(c))}function gRe(s){s=s|0;var l=0;l=Vr()|0,zr(s,2,3,l,dRe()|0,2),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function dRe(){return 1380}function mRe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0;d=C,C=C+16|0,m=d+8|0,B=d,k=yRe(s)|0,s=n[k+4>>2]|0,n[B>>2]=n[k>>2],n[B+4>>2]=s,n[m>>2]=n[B>>2],n[m+4>>2]=n[B+4>>2],ERe(l,m,c,f),C=d}function yRe(s){return s=s|0,(n[(zF()|0)+24>>2]|0)+(s*12|0)|0}function ERe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0;k=C,C=C+16|0,m=k+1|0,B=k,d=n[l>>2]|0,l=n[l+4>>2]|0,s=s+(l>>1)|0,l&1&&(d=n[(n[s>>2]|0)+d>>2]|0),XA(m,c),m=ZA(m,c)|0,CRe(B,f),B=wRe(B,f)|0,vw[d&15](s,m,B),C=k}function CRe(s,l){s=s|0,l=l|0}function wRe(s,l){return s=s|0,l=l|0,IRe(l)|0}function IRe(s){return s=s|0,(s|0)!=0|0}function BRe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;m=n[s>>2]|0,d=JF()|0,s=vRe(c)|0,hn(m,l,d,s,DRe(c,f)|0,f)}function JF(){var s=0,l=0;if(o[7864]|0||(s9(10208),ir(51,10208,U|0)|0,l=7864,n[l>>2]=1,n[l+4>>2]=0),!(Rr(10208)|0)){s=10208,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));s9(10208)}return 10208}function vRe(s){return s=s|0,s|0}function DRe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return k=C,C=C+16|0,d=k,m=k+4|0,n[d>>2]=s,Q=JF()|0,B=Q+24|0,l=gr(l,4)|0,n[m>>2]=l,c=Q+28|0,f=n[c>>2]|0,f>>>0<(n[Q+32>>2]|0)>>>0?(i9(f,s,l),l=(n[c>>2]|0)+8|0,n[c>>2]=l):(PRe(B,d,m),l=n[c>>2]|0),C=k,(l-(n[B>>2]|0)>>3)+-1|0}function i9(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c}function PRe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;if(k=C,C=C+32|0,d=k,m=s+4|0,B=((n[m>>2]|0)-(n[s>>2]|0)>>3)+1|0,f=bRe(s)|0,f>>>0<B>>>0)Jr(s);else{Q=n[s>>2]|0,M=(n[s+8>>2]|0)-Q|0,O=M>>2,SRe(d,M>>3>>>0<f>>>1>>>0?O>>>0<B>>>0?B:O:f,(n[m>>2]|0)-Q>>3,s+8|0),B=d+8|0,i9(n[B>>2]|0,n[l>>2]|0,n[c>>2]|0),n[B>>2]=(n[B>>2]|0)+8,xRe(s,d),kRe(d),C=k;return}}function bRe(s){return s=s|0,536870911}function SRe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>536870911)Tt();else{d=Kt(l<<3)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<3)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<3)}function xRe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>3)<<3)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function kRe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&gt(s)}function s9(s){s=s|0,RRe(s)}function QRe(s){s=s|0,FRe(s+24|0)}function FRe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function RRe(s){s=s|0;var l=0;l=Vr()|0,zr(s,1,24,l,TRe()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function TRe(){return 1392}function NRe(s,l){s=s|0,l=l|0,MRe(n[(LRe(s)|0)>>2]|0,l)}function LRe(s){return s=s|0,(n[(JF()|0)+24>>2]|0)+(s<<3)|0}function MRe(s,l){s=s|0,l=l|0;var c=0,f=0;c=C,C=C+16|0,f=c,VG(f,l),l=zG(f,l)|0,ef[s&127](l),C=c}function ORe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;m=n[s>>2]|0,d=XF()|0,s=URe(c)|0,hn(m,l,d,s,_Re(c,f)|0,f)}function XF(){var s=0,l=0;if(o[7872]|0||(a9(10244),ir(52,10244,U|0)|0,l=7872,n[l>>2]=1,n[l+4>>2]=0),!(Rr(10244)|0)){s=10244,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));a9(10244)}return 10244}function URe(s){return s=s|0,s|0}function _Re(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return k=C,C=C+16|0,d=k,m=k+4|0,n[d>>2]=s,Q=XF()|0,B=Q+24|0,l=gr(l,4)|0,n[m>>2]=l,c=Q+28|0,f=n[c>>2]|0,f>>>0<(n[Q+32>>2]|0)>>>0?(o9(f,s,l),l=(n[c>>2]|0)+8|0,n[c>>2]=l):(HRe(B,d,m),l=n[c>>2]|0),C=k,(l-(n[B>>2]|0)>>3)+-1|0}function o9(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c}function HRe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;if(k=C,C=C+32|0,d=k,m=s+4|0,B=((n[m>>2]|0)-(n[s>>2]|0)>>3)+1|0,f=qRe(s)|0,f>>>0<B>>>0)Jr(s);else{Q=n[s>>2]|0,M=(n[s+8>>2]|0)-Q|0,O=M>>2,jRe(d,M>>3>>>0<f>>>1>>>0?O>>>0<B>>>0?B:O:f,(n[m>>2]|0)-Q>>3,s+8|0),B=d+8|0,o9(n[B>>2]|0,n[l>>2]|0,n[c>>2]|0),n[B>>2]=(n[B>>2]|0)+8,GRe(s,d),YRe(d),C=k;return}}function qRe(s){return s=s|0,536870911}function jRe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>536870911)Tt();else{d=Kt(l<<3)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<3)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<3)}function GRe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>3)<<3)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function YRe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&gt(s)}function a9(s){s=s|0,VRe(s)}function WRe(s){s=s|0,KRe(s+24|0)}function KRe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function VRe(s){s=s|0;var l=0;l=Vr()|0,zr(s,1,16,l,zRe()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function zRe(){return 1400}function JRe(s){return s=s|0,ZRe(n[(XRe(s)|0)>>2]|0)|0}function XRe(s){return s=s|0,(n[(XF()|0)+24>>2]|0)+(s<<3)|0}function ZRe(s){return s=s|0,$Re(nD[s&7]()|0)|0}function $Re(s){return s=s|0,s|0}function eTe(){var s=0;return o[7880]|0||(aTe(10280),ir(25,10280,U|0)|0,s=7880,n[s>>2]=1,n[s+4>>2]=0),10280}function tTe(s,l){s=s|0,l=l|0,n[s>>2]=rTe()|0,n[s+4>>2]=nTe()|0,n[s+12>>2]=l,n[s+8>>2]=iTe()|0,n[s+32>>2]=4}function rTe(){return 11711}function nTe(){return 1356}function iTe(){return Gv()|0}function sTe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,(Dp(f,896)|0)==512?c|0&&(oTe(c),gt(c)):l|0&&(w0(l),gt(l))}function oTe(s){s=s|0,s=n[s+4>>2]|0,s|0&&bp(s)}function aTe(s){s=s|0,wp(s)}function lTe(s){s=s|0,cTe(s,4920),uTe(s)|0,ATe(s)|0}function cTe(s,l){s=s|0,l=l|0;var c=0;c=xG()|0,n[s>>2]=c,FTe(c,l),Pp(n[s>>2]|0)}function uTe(s){s=s|0;var l=0;return l=n[s>>2]|0,P0(l,ITe()|0),s|0}function ATe(s){s=s|0;var l=0;return l=n[s>>2]|0,P0(l,fTe()|0),s|0}function fTe(){var s=0;return o[7888]|0||(l9(10328),ir(53,10328,U|0)|0,s=7888,n[s>>2]=1,n[s+4>>2]=0),Rr(10328)|0||l9(10328),10328}function P0(s,l){s=s|0,l=l|0,hn(s,0,l,0,0,0)}function l9(s){s=s|0,gTe(s),b0(s,10)}function pTe(s){s=s|0,hTe(s+24|0)}function hTe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function gTe(s){s=s|0;var l=0;l=Vr()|0,zr(s,5,1,l,ETe()|0,2),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function dTe(s,l,c){s=s|0,l=l|0,c=+c,mTe(s,l,c)}function b0(s,l){s=s|0,l=l|0,n[s+20>>2]=l}function mTe(s,l,c){s=s|0,l=l|0,c=+c;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+16|0,m=f+8|0,k=f+13|0,d=f,B=f+12|0,XA(k,l),n[m>>2]=ZA(k,l)|0,Fu(B,c),E[d>>3]=+Ru(B,c),yTe(s,m,d),C=f}function yTe(s,l,c){s=s|0,l=l|0,c=c|0,W(s+8|0,n[l>>2]|0,+E[c>>3]),o[s+24>>0]=1}function ETe(){return 1404}function CTe(s,l){return s=s|0,l=+l,wTe(s,l)|0}function wTe(s,l){s=s|0,l=+l;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return f=C,C=C+16|0,m=f+4|0,B=f+8|0,k=f,d=Va(8)|0,c=d,Q=Kt(16)|0,XA(m,s),s=ZA(m,s)|0,Fu(B,l),W(Q,s,+Ru(B,l)),B=c+4|0,n[B>>2]=Q,s=Kt(8)|0,B=n[B>>2]|0,n[k>>2]=0,n[m>>2]=n[k>>2],LF(s,B,m),n[d>>2]=s,C=f,c|0}function ITe(){var s=0;return o[7896]|0||(c9(10364),ir(54,10364,U|0)|0,s=7896,n[s>>2]=1,n[s+4>>2]=0),Rr(10364)|0||c9(10364),10364}function c9(s){s=s|0,DTe(s),b0(s,55)}function BTe(s){s=s|0,vTe(s+24|0)}function vTe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function DTe(s){s=s|0;var l=0;l=Vr()|0,zr(s,5,4,l,xTe()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function PTe(s){s=s|0,bTe(s)}function bTe(s){s=s|0,STe(s)}function STe(s){s=s|0,u9(s+8|0),o[s+24>>0]=1}function u9(s){s=s|0,n[s>>2]=0,E[s+8>>3]=0}function xTe(){return 1424}function kTe(){return QTe()|0}function QTe(){var s=0,l=0,c=0,f=0,d=0,m=0,B=0;return l=C,C=C+16|0,d=l+4|0,B=l,c=Va(8)|0,s=c,f=Kt(16)|0,u9(f),m=s+4|0,n[m>>2]=f,f=Kt(8)|0,m=n[m>>2]|0,n[B>>2]=0,n[d>>2]=n[B>>2],LF(f,m,d),n[c>>2]=f,C=l,s|0}function FTe(s,l){s=s|0,l=l|0,n[s>>2]=RTe()|0,n[s+4>>2]=TTe()|0,n[s+12>>2]=l,n[s+8>>2]=NTe()|0,n[s+32>>2]=5}function RTe(){return 11710}function TTe(){return 1416}function NTe(){return Yv()|0}function LTe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,(Dp(f,896)|0)==512?c|0&&(MTe(c),gt(c)):l|0&&gt(l)}function MTe(s){s=s|0,s=n[s+4>>2]|0,s|0&&bp(s)}function Yv(){var s=0;return o[7904]|0||(n[2600]=OTe()|0,n[2601]=0,s=7904,n[s>>2]=1,n[s+4>>2]=0),10400}function OTe(){return n[357]|0}function UTe(s){s=s|0,_Te(s,4926),HTe(s)|0}function _Te(s,l){s=s|0,l=l|0;var c=0;c=Z5()|0,n[s>>2]=c,ZTe(c,l),Pp(n[s>>2]|0)}function HTe(s){s=s|0;var l=0;return l=n[s>>2]|0,P0(l,qTe()|0),s|0}function qTe(){var s=0;return o[7912]|0||(A9(10412),ir(56,10412,U|0)|0,s=7912,n[s>>2]=1,n[s+4>>2]=0),Rr(10412)|0||A9(10412),10412}function A9(s){s=s|0,YTe(s),b0(s,57)}function jTe(s){s=s|0,GTe(s+24|0)}function GTe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function YTe(s){s=s|0;var l=0;l=Vr()|0,zr(s,5,5,l,zTe()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function WTe(s){s=s|0,KTe(s)}function KTe(s){s=s|0,VTe(s)}function VTe(s){s=s|0;var l=0,c=0;l=s+8|0,c=l+48|0;do n[l>>2]=0,l=l+4|0;while((l|0)<(c|0));o[s+56>>0]=1}function zTe(){return 1432}function JTe(){return XTe()|0}function XTe(){var s=0,l=0,c=0,f=0,d=0,m=0,B=0,k=0;B=C,C=C+16|0,s=B+4|0,l=B,c=Va(8)|0,f=c,d=Kt(48)|0,m=d,k=m+48|0;do n[m>>2]=0,m=m+4|0;while((m|0)<(k|0));return m=f+4|0,n[m>>2]=d,k=Kt(8)|0,m=n[m>>2]|0,n[l>>2]=0,n[s>>2]=n[l>>2],$5(k,m,s),n[c>>2]=k,C=B,f|0}function ZTe(s,l){s=s|0,l=l|0,n[s>>2]=$Te()|0,n[s+4>>2]=eNe()|0,n[s+12>>2]=l,n[s+8>>2]=tNe()|0,n[s+32>>2]=6}function $Te(){return 11704}function eNe(){return 1436}function tNe(){return Yv()|0}function rNe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,(Dp(f,896)|0)==512?c|0&&(nNe(c),gt(c)):l|0&&gt(l)}function nNe(s){s=s|0,s=n[s+4>>2]|0,s|0&&bp(s)}function iNe(s){s=s|0,sNe(s,4933),oNe(s)|0,aNe(s)|0}function sNe(s,l){s=s|0,l=l|0;var c=0;c=QNe()|0,n[s>>2]=c,FNe(c,l),Pp(n[s>>2]|0)}function oNe(s){s=s|0;var l=0;return l=n[s>>2]|0,P0(l,wNe()|0),s|0}function aNe(s){s=s|0;var l=0;return l=n[s>>2]|0,P0(l,lNe()|0),s|0}function lNe(){var s=0;return o[7920]|0||(f9(10452),ir(58,10452,U|0)|0,s=7920,n[s>>2]=1,n[s+4>>2]=0),Rr(10452)|0||f9(10452),10452}function f9(s){s=s|0,ANe(s),b0(s,1)}function cNe(s){s=s|0,uNe(s+24|0)}function uNe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function ANe(s){s=s|0;var l=0;l=Vr()|0,zr(s,5,1,l,gNe()|0,2),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function fNe(s,l,c){s=s|0,l=+l,c=+c,pNe(s,l,c)}function pNe(s,l,c){s=s|0,l=+l,c=+c;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+32|0,m=f+8|0,k=f+17|0,d=f,B=f+16|0,Fu(k,l),E[m>>3]=+Ru(k,l),Fu(B,c),E[d>>3]=+Ru(B,c),hNe(s,m,d),C=f}function hNe(s,l,c){s=s|0,l=l|0,c=c|0,p9(s+8|0,+E[l>>3],+E[c>>3]),o[s+24>>0]=1}function p9(s,l,c){s=s|0,l=+l,c=+c,E[s>>3]=l,E[s+8>>3]=c}function gNe(){return 1472}function dNe(s,l){return s=+s,l=+l,mNe(s,l)|0}function mNe(s,l){s=+s,l=+l;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return f=C,C=C+16|0,B=f+4|0,k=f+8|0,Q=f,d=Va(8)|0,c=d,m=Kt(16)|0,Fu(B,s),s=+Ru(B,s),Fu(k,l),p9(m,s,+Ru(k,l)),k=c+4|0,n[k>>2]=m,m=Kt(8)|0,k=n[k>>2]|0,n[Q>>2]=0,n[B>>2]=n[Q>>2],h9(m,k,B),n[d>>2]=m,C=f,c|0}function h9(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,c=Kt(16)|0,n[c+4>>2]=0,n[c+8>>2]=0,n[c>>2]=1452,n[c+12>>2]=l,n[s+4>>2]=c}function yNe(s){s=s|0,Md(s),gt(s)}function ENe(s){s=s|0,s=n[s+12>>2]|0,s|0&&gt(s)}function CNe(s){s=s|0,gt(s)}function wNe(){var s=0;return o[7928]|0||(g9(10488),ir(59,10488,U|0)|0,s=7928,n[s>>2]=1,n[s+4>>2]=0),Rr(10488)|0||g9(10488),10488}function g9(s){s=s|0,vNe(s),b0(s,60)}function INe(s){s=s|0,BNe(s+24|0)}function BNe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function vNe(s){s=s|0;var l=0;l=Vr()|0,zr(s,5,6,l,SNe()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function DNe(s){s=s|0,PNe(s)}function PNe(s){s=s|0,bNe(s)}function bNe(s){s=s|0,d9(s+8|0),o[s+24>>0]=1}function d9(s){s=s|0,n[s>>2]=0,n[s+4>>2]=0,n[s+8>>2]=0,n[s+12>>2]=0}function SNe(){return 1492}function xNe(){return kNe()|0}function kNe(){var s=0,l=0,c=0,f=0,d=0,m=0,B=0;return l=C,C=C+16|0,d=l+4|0,B=l,c=Va(8)|0,s=c,f=Kt(16)|0,d9(f),m=s+4|0,n[m>>2]=f,f=Kt(8)|0,m=n[m>>2]|0,n[B>>2]=0,n[d>>2]=n[B>>2],h9(f,m,d),n[c>>2]=f,C=l,s|0}function QNe(){var s=0;return o[7936]|0||(ONe(10524),ir(25,10524,U|0)|0,s=7936,n[s>>2]=1,n[s+4>>2]=0),10524}function FNe(s,l){s=s|0,l=l|0,n[s>>2]=RNe()|0,n[s+4>>2]=TNe()|0,n[s+12>>2]=l,n[s+8>>2]=NNe()|0,n[s+32>>2]=7}function RNe(){return 11700}function TNe(){return 1484}function NNe(){return Yv()|0}function LNe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,(Dp(f,896)|0)==512?c|0&&(MNe(c),gt(c)):l|0&&gt(l)}function MNe(s){s=s|0,s=n[s+4>>2]|0,s|0&&bp(s)}function ONe(s){s=s|0,wp(s)}function UNe(s,l,c){s=s|0,l=l|0,c=c|0,s=pn(l)|0,l=_Ne(c)|0,c=HNe(c,0)|0,mLe(s,l,c,ZF()|0,0)}function _Ne(s){return s=s|0,s|0}function HNe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return k=C,C=C+16|0,d=k,m=k+4|0,n[d>>2]=s,Q=ZF()|0,B=Q+24|0,l=gr(l,4)|0,n[m>>2]=l,c=Q+28|0,f=n[c>>2]|0,f>>>0<(n[Q+32>>2]|0)>>>0?(y9(f,s,l),l=(n[c>>2]|0)+8|0,n[c>>2]=l):(VNe(B,d,m),l=n[c>>2]|0),C=k,(l-(n[B>>2]|0)>>3)+-1|0}function ZF(){var s=0,l=0;if(o[7944]|0||(m9(10568),ir(61,10568,U|0)|0,l=7944,n[l>>2]=1,n[l+4>>2]=0),!(Rr(10568)|0)){s=10568,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));m9(10568)}return 10568}function m9(s){s=s|0,GNe(s)}function qNe(s){s=s|0,jNe(s+24|0)}function jNe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function GNe(s){s=s|0;var l=0;l=Vr()|0,zr(s,1,17,l,dG()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function YNe(s){return s=s|0,KNe(n[(WNe(s)|0)>>2]|0)|0}function WNe(s){return s=s|0,(n[(ZF()|0)+24>>2]|0)+(s<<3)|0}function KNe(s){return s=s|0,jv(nD[s&7]()|0)|0}function y9(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c}function VNe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;if(k=C,C=C+32|0,d=k,m=s+4|0,B=((n[m>>2]|0)-(n[s>>2]|0)>>3)+1|0,f=zNe(s)|0,f>>>0<B>>>0)Jr(s);else{Q=n[s>>2]|0,M=(n[s+8>>2]|0)-Q|0,O=M>>2,JNe(d,M>>3>>>0<f>>>1>>>0?O>>>0<B>>>0?B:O:f,(n[m>>2]|0)-Q>>3,s+8|0),B=d+8|0,y9(n[B>>2]|0,n[l>>2]|0,n[c>>2]|0),n[B>>2]=(n[B>>2]|0)+8,XNe(s,d),ZNe(d),C=k;return}}function zNe(s){return s=s|0,536870911}function JNe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>536870911)Tt();else{d=Kt(l<<3)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<3)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<3)}function XNe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>3)<<3)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function ZNe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&gt(s)}function $Ne(){eLe()}function eLe(){tLe(10604)}function tLe(s){s=s|0,rLe(s,4955)}function rLe(s,l){s=s|0,l=l|0;var c=0;c=nLe()|0,n[s>>2]=c,iLe(c,l),Pp(n[s>>2]|0)}function nLe(){var s=0;return o[7952]|0||(pLe(10612),ir(25,10612,U|0)|0,s=7952,n[s>>2]=1,n[s+4>>2]=0),10612}function iLe(s,l){s=s|0,l=l|0,n[s>>2]=lLe()|0,n[s+4>>2]=cLe()|0,n[s+12>>2]=l,n[s+8>>2]=uLe()|0,n[s+32>>2]=8}function Pp(s){s=s|0;var l=0,c=0;l=C,C=C+16|0,c=l,Fd()|0,n[c>>2]=s,sLe(10608,c),C=l}function Fd(){return o[11714]|0||(n[2652]=0,ir(62,10608,U|0)|0,o[11714]=1),10608}function sLe(s,l){s=s|0,l=l|0;var c=0;c=Kt(8)|0,n[c+4>>2]=n[l>>2],n[c>>2]=n[s>>2],n[s>>2]=c}function oLe(s){s=s|0,aLe(s)}function aLe(s){s=s|0;var l=0,c=0;if(l=n[s>>2]|0,l|0)do c=l,l=n[l>>2]|0,gt(c);while(l|0);n[s>>2]=0}function lLe(){return 11715}function cLe(){return 1496}function uLe(){return Gv()|0}function ALe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,(Dp(f,896)|0)==512?c|0&&(fLe(c),gt(c)):l|0&&gt(l)}function fLe(s){s=s|0,s=n[s+4>>2]|0,s|0&&bp(s)}function pLe(s){s=s|0,wp(s)}function hLe(s,l){s=s|0,l=l|0;var c=0,f=0;Fd()|0,c=n[2652]|0;e:do if(c|0){for(;f=n[c+4>>2]|0,!(f|0&&!($9($F(f)|0,s)|0));)if(c=n[c>>2]|0,!c)break e;gLe(f,l)}while(!1)}function $F(s){return s=s|0,n[s+12>>2]|0}function gLe(s,l){s=s|0,l=l|0;var c=0;s=s+36|0,c=n[s>>2]|0,c|0&&(qA(c),gt(c)),c=Kt(4)|0,W5(c,l),n[s>>2]=c}function eR(){return o[11716]|0||(n[2664]=0,ir(63,10656,U|0)|0,o[11716]=1),10656}function E9(){var s=0;return o[11717]|0?s=n[2665]|0:(dLe(),n[2665]=1504,o[11717]=1,s=1504),s|0}function dLe(){o[11740]|0||(o[11718]=gr(gr(8,0)|0,0)|0,o[11719]=gr(gr(0,0)|0,0)|0,o[11720]=gr(gr(0,16)|0,0)|0,o[11721]=gr(gr(8,0)|0,0)|0,o[11722]=gr(gr(0,0)|0,0)|0,o[11723]=gr(gr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qe>>2]=0,n[O>>2]=0,n[M>>2]=0;e:do if(n[f>>2]|0)for(d=0,m=0;;){if((d|0)==(m|0)?CLe(Qe,f):(n[d>>2]=n[f>>2],n[O>>2]=(n[O>>2]|0)+4),f=f+4|0,!(n[f>>2]|0))break e;d=n[O>>2]|0,m=n[j>>2]|0}while(!1);n[$e>>2]=Wv(B)|0,n[Je>>2]=Rr(k)|0,wLe(c,s,$e,Je,Oe,Qe),nR(Qe),$A(Oe)}l=n[l>>2]|0}while(l|0)}C=lt}function tR(s){return s=s|0,n[s+12>>2]|0}function yw(s){return s=s|0,n[s+12>>2]|0}function Ew(s){return s=s|0,n[s+16>>2]|0}function ELe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0;d=C,C=C+32|0,c=d,f=n[s>>2]|0,(n[s+8>>2]|0)-f>>2>>>0<l>>>0&&(x9(c,l,(n[s+4>>2]|0)-f>>2,s+8|0),k9(s,c),Q9(c)),C=d}function rR(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0;if(B=C,C=C+32|0,c=B,f=s+4|0,d=((n[f>>2]|0)-(n[s>>2]|0)>>2)+1|0,m=S9(s)|0,m>>>0<d>>>0)Jr(s);else{k=n[s>>2]|0,O=(n[s+8>>2]|0)-k|0,Q=O>>1,x9(c,O>>2>>>0<m>>>1>>>0?Q>>>0<d>>>0?d:Q:m,(n[f>>2]|0)-k>>2,s+8|0),m=c+8|0,n[n[m>>2]>>2]=n[l>>2],n[m>>2]=(n[m>>2]|0)+4,k9(s,c),Q9(c),C=B;return}}function Cw(s){return s=s|0,n[s+8>>2]|0}function CLe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0;if(B=C,C=C+32|0,c=B,f=s+4|0,d=((n[f>>2]|0)-(n[s>>2]|0)>>2)+1|0,m=b9(s)|0,m>>>0<d>>>0)Jr(s);else{k=n[s>>2]|0,O=(n[s+8>>2]|0)-k|0,Q=O>>1,_Le(c,O>>2>>>0<m>>>1>>>0?Q>>>0<d>>>0?d:Q:m,(n[f>>2]|0)-k>>2,s+8|0),m=c+8|0,n[n[m>>2]>>2]=n[l>>2],n[m>>2]=(n[m>>2]|0)+4,HLe(s,c),qLe(c),C=B;return}}function Wv(s){return s=s|0,n[s>>2]|0}function wLe(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0,ILe(s,l,c,f,d,m)}function nR(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-4-f|0)>>>2)<<2)),gt(c))}function $A(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-4-f|0)>>>2)<<2)),gt(c))}function ILe(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0;var B=0,k=0,Q=0,O=0,M=0,j=0;B=C,C=C+48|0,M=B+40|0,k=B+32|0,j=B+24|0,Q=B+12|0,O=B,za(k),s=ya(s)|0,n[j>>2]=n[l>>2],c=n[c>>2]|0,f=n[f>>2]|0,iR(Q,d),BLe(O,m),n[M>>2]=n[j>>2],vLe(s,M,c,f,Q,O),nR(O),$A(Q),Ja(k),C=B}function iR(s,l){s=s|0,l=l|0;var c=0,f=0;n[s>>2]=0,n[s+4>>2]=0,n[s+8>>2]=0,c=l+4|0,f=(n[c>>2]|0)-(n[l>>2]|0)>>2,f|0&&(OLe(s,f),ULe(s,n[l>>2]|0,n[c>>2]|0,f))}function BLe(s,l){s=s|0,l=l|0;var c=0,f=0;n[s>>2]=0,n[s+4>>2]=0,n[s+8>>2]=0,c=l+4|0,f=(n[c>>2]|0)-(n[l>>2]|0)>>2,f|0&&(LLe(s,f),MLe(s,n[l>>2]|0,n[c>>2]|0,f))}function vLe(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0;var B=0,k=0,Q=0,O=0,M=0,j=0;B=C,C=C+32|0,M=B+28|0,j=B+24|0,k=B+12|0,Q=B,O=Pl(DLe()|0)|0,n[j>>2]=n[l>>2],n[M>>2]=n[j>>2],l=S0(M)|0,c=I9(c)|0,f=sR(f)|0,n[k>>2]=n[d>>2],M=d+4|0,n[k+4>>2]=n[M>>2],j=d+8|0,n[k+8>>2]=n[j>>2],n[j>>2]=0,n[M>>2]=0,n[d>>2]=0,d=oR(k)|0,n[Q>>2]=n[m>>2],M=m+4|0,n[Q+4>>2]=n[M>>2],j=m+8|0,n[Q+8>>2]=n[j>>2],n[j>>2]=0,n[M>>2]=0,n[m>>2]=0,ao(0,O|0,s|0,l|0,c|0,f|0,d|0,PLe(Q)|0)|0,nR(Q),$A(k),C=B}function DLe(){var s=0;return o[7968]|0||(TLe(10708),s=7968,n[s>>2]=1,n[s+4>>2]=0),10708}function S0(s){return s=s|0,v9(s)|0}function I9(s){return s=s|0,B9(s)|0}function sR(s){return s=s|0,jv(s)|0}function oR(s){return s=s|0,SLe(s)|0}function PLe(s){return s=s|0,bLe(s)|0}function bLe(s){s=s|0;var l=0,c=0,f=0;if(f=(n[s+4>>2]|0)-(n[s>>2]|0)|0,c=f>>2,f=Va(f+4|0)|0,n[f>>2]=c,c|0){l=0;do n[f+4+(l<<2)>>2]=B9(n[(n[s>>2]|0)+(l<<2)>>2]|0)|0,l=l+1|0;while((l|0)!=(c|0))}return f|0}function B9(s){return s=s|0,s|0}function SLe(s){s=s|0;var l=0,c=0,f=0;if(f=(n[s+4>>2]|0)-(n[s>>2]|0)|0,c=f>>2,f=Va(f+4|0)|0,n[f>>2]=c,c|0){l=0;do n[f+4+(l<<2)>>2]=v9((n[s>>2]|0)+(l<<2)|0)|0,l=l+1|0;while((l|0)!=(c|0))}return f|0}function v9(s){s=s|0;var l=0,c=0,f=0,d=0;return d=C,C=C+32|0,l=d+12|0,c=d,f=yF(D9()|0)|0,f?(EF(l,f),CF(c,l),uUe(s,c),s=wF(l)|0):s=xLe(s)|0,C=d,s|0}function D9(){var s=0;return o[7960]|0||(RLe(10664),ir(25,10664,U|0)|0,s=7960,n[s>>2]=1,n[s+4>>2]=0),10664}function xLe(s){s=s|0;var l=0,c=0,f=0,d=0,m=0,B=0,k=0;return c=C,C=C+16|0,d=c+4|0,B=c,f=Va(8)|0,l=f,k=Kt(4)|0,n[k>>2]=n[s>>2],m=l+4|0,n[m>>2]=k,s=Kt(8)|0,m=n[m>>2]|0,n[B>>2]=0,n[d>>2]=n[B>>2],P9(s,m,d),n[f>>2]=s,C=c,l|0}function P9(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,c=Kt(16)|0,n[c+4>>2]=0,n[c+8>>2]=0,n[c>>2]=1656,n[c+12>>2]=l,n[s+4>>2]=c}function kLe(s){s=s|0,Md(s),gt(s)}function QLe(s){s=s|0,s=n[s+12>>2]|0,s|0&&gt(s)}function FLe(s){s=s|0,gt(s)}function RLe(s){s=s|0,wp(s)}function TLe(s){s=s|0,bl(s,NLe()|0,5)}function NLe(){return 1676}function LLe(s,l){s=s|0,l=l|0;var c=0;if((b9(s)|0)>>>0<l>>>0&&Jr(s),l>>>0>1073741823)Tt();else{c=Kt(l<<2)|0,n[s+4>>2]=c,n[s>>2]=c,n[s+8>>2]=c+(l<<2);return}}function MLe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,f=s+4|0,s=c-l|0,(s|0)>0&&(Dr(n[f>>2]|0,l|0,s|0)|0,n[f>>2]=(n[f>>2]|0)+(s>>>2<<2))}function b9(s){return s=s|0,1073741823}function OLe(s,l){s=s|0,l=l|0;var c=0;if((S9(s)|0)>>>0<l>>>0&&Jr(s),l>>>0>1073741823)Tt();else{c=Kt(l<<2)|0,n[s+4>>2]=c,n[s>>2]=c,n[s+8>>2]=c+(l<<2);return}}function ULe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,f=s+4|0,s=c-l|0,(s|0)>0&&(Dr(n[f>>2]|0,l|0,s|0)|0,n[f>>2]=(n[f>>2]|0)+(s>>>2<<2))}function S9(s){return s=s|0,1073741823}function _Le(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>1073741823)Tt();else{d=Kt(l<<2)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<2)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<2)}function HLe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>2)<<2)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function qLe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-4-l|0)>>>2)<<2)),s=n[s>>2]|0,s|0&&gt(s)}function x9(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>1073741823)Tt();else{d=Kt(l<<2)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<2)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<2)}function k9(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>2)<<2)|0,n[m>>2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d(n[B+4>>2]|0)|0)>>2]|0),k=n[s>>2]|0,k>>>0<(n[c>>2]|0)>>>0?(n[k>>2]=n[je>>2],n[s>>2]=(n[s>>2]|0)+4):rR(M,je),B=n[B>>2]|0;while(B|0);VLe(f,j,M),$A(M)}n[Oe>>2]=n[j>>2],O=R9(Q)|0,n[M>>2]=n[Oe>>2],w9(M,O,d),tG(se),m=n[m>>2]|0}while(m|0)}C=Qe}function GLe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,oMe(s,l,c,f)}function YLe(s,l,c){s=s|0,l=l|0,c=c|0,sMe(s,l,c)}function Rd(s){return s=s|0,s|0}function WLe(s,l,c){s=s|0,l=l|0,c=c|0,tMe(s,l,c)}function F9(s){return s=s|0,s+16|0}function KLe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;if(m=C,C=C+16|0,d=m+8|0,c=m,n[s>>2]=0,f=n[l>>2]|0,n[d>>2]=f,n[c>>2]=s,c=eMe(c)|0,f|0){if(f=Kt(12)|0,B=(T9(d)|0)+4|0,s=n[B+4>>2]|0,l=f+4|0,n[l>>2]=n[B>>2],n[l+4>>2]=s,l=n[n[d>>2]>>2]|0,n[d>>2]=l,!l)s=f;else for(l=f;s=Kt(12)|0,Q=(T9(d)|0)+4|0,k=n[Q+4>>2]|0,B=s+4|0,n[B>>2]=n[Q>>2],n[B+4>>2]=k,n[l>>2]=s,B=n[n[d>>2]>>2]|0,n[d>>2]=B,B;)l=s;n[s>>2]=n[c>>2],n[c>>2]=f}C=m}function VLe(s,l,c){s=s|0,l=l|0,c=c|0,zLe(s,l,c)}function R9(s){return s=s|0,s+24|0}function zLe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+32|0,B=f+24|0,d=f+16|0,k=f+12|0,m=f,za(d),s=ya(s)|0,n[k>>2]=n[l>>2],iR(m,c),n[B>>2]=n[k>>2],JLe(s,B,m),$A(m),Ja(d),C=f}function JLe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=C,C=C+32|0,B=f+16|0,k=f+12|0,d=f,m=Pl(XLe()|0)|0,n[k>>2]=n[l>>2],n[B>>2]=n[k>>2],l=S0(B)|0,n[d>>2]=n[c>>2],B=c+4|0,n[d+4>>2]=n[B>>2],k=c+8|0,n[d+8>>2]=n[k>>2],n[k>>2]=0,n[B>>2]=0,n[c>>2]=0,oo(0,m|0,s|0,l|0,oR(d)|0)|0,$A(d),C=f}function XLe(){var s=0;return o[7976]|0||(ZLe(10720),s=7976,n[s>>2]=1,n[s+4>>2]=0),10720}function ZLe(s){s=s|0,bl(s,$Le()|0,2)}function $Le(){return 1732}function eMe(s){return s=s|0,n[s>>2]|0}function T9(s){return s=s|0,n[s>>2]|0}function tMe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;f=C,C=C+32|0,m=f+16|0,d=f+8|0,B=f,za(d),s=ya(s)|0,n[B>>2]=n[l>>2],c=n[c>>2]|0,n[m>>2]=n[B>>2],N9(s,m,c),Ja(d),C=f}function N9(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;f=C,C=C+16|0,m=f+4|0,B=f,d=Pl(rMe()|0)|0,n[B>>2]=n[l>>2],n[m>>2]=n[B>>2],l=S0(m)|0,oo(0,d|0,s|0,l|0,I9(c)|0)|0,C=f}function rMe(){var s=0;return o[7984]|0||(nMe(10732),s=7984,n[s>>2]=1,n[s+4>>2]=0),10732}function nMe(s){s=s|0,bl(s,iMe()|0,2)}function iMe(){return 1744}function sMe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;f=C,C=C+32|0,m=f+16|0,d=f+8|0,B=f,za(d),s=ya(s)|0,n[B>>2]=n[l>>2],c=n[c>>2]|0,n[m>>2]=n[B>>2],N9(s,m,c),Ja(d),C=f}function oMe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0;d=C,C=C+32|0,B=d+16|0,m=d+8|0,k=d,za(m),s=ya(s)|0,n[k>>2]=n[l>>2],c=o[c>>0]|0,f=o[f>>0]|0,n[B>>2]=n[k>>2],aMe(s,B,c,f),Ja(m),C=d}function aMe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0;d=C,C=C+16|0,B=d+4|0,k=d,m=Pl(lMe()|0)|0,n[k>>2]=n[l>>2],n[B>>2]=n[k>>2],l=S0(B)|0,c=Td(c)|0,hc(0,m|0,s|0,l|0,c|0,Td(f)|0)|0,C=d}function lMe(){var s=0;return o[7992]|0||(uMe(10744),s=7992,n[s>>2]=1,n[s+4>>2]=0),10744}function Td(s){return s=s|0,cMe(s)|0}function cMe(s){return s=s|0,s&255|0}function uMe(s){s=s|0,bl(s,AMe()|0,3)}function AMe(){return 1756}function fMe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;switch(se=C,C=C+32|0,k=se+8|0,Q=se+4|0,O=se+20|0,M=se,DF(s,0),f=cUe(l)|0,n[k>>2]=0,j=k+4|0,n[j>>2]=0,n[k+8>>2]=0,f<<24>>24){case 0:{o[O>>0]=0,pMe(Q,c,O),Kv(s,Q)|0,jA(Q);break}case 8:{j=fR(l)|0,o[O>>0]=8,xc(M,n[j+4>>2]|0),hMe(Q,c,O,M,j+8|0),Kv(s,Q)|0,jA(Q);break}case 9:{if(m=fR(l)|0,l=n[m+4>>2]|0,l|0)for(B=k+8|0,d=m+12|0;l=l+-1|0,xc(Q,n[d>>2]|0),f=n[j>>2]|0,f>>>0<(n[B>>2]|0)>>>0?(n[f>>2]=n[Q>>2],n[j>>2]=(n[j>>2]|0)+4):rR(k,Q),l;)d=d+4|0;o[O>>0]=9,xc(M,n[m+8>>2]|0),gMe(Q,c,O,M,k),Kv(s,Q)|0,jA(Q);break}default:j=fR(l)|0,o[O>>0]=f,xc(M,n[j+4>>2]|0),dMe(Q,c,O,M),Kv(s,Q)|0,jA(Q)}$A(k),C=se}function pMe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0;f=C,C=C+16|0,d=f,za(d),l=ya(l)|0,xMe(s,l,o[c>>0]|0),Ja(d),C=f}function Kv(s,l){s=s|0,l=l|0;var c=0;return c=n[s>>2]|0,c|0&&PA(c|0),n[s>>2]=n[l>>2],n[l>>2]=0,s|0}function hMe(s,l,c,f,d){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0;var m=0,B=0,k=0,Q=0;m=C,C=C+32|0,k=m+16|0,B=m+8|0,Q=m,za(B),l=ya(l)|0,c=o[c>>0]|0,n[Q>>2]=n[f>>2],d=n[d>>2]|0,n[k>>2]=n[Q>>2],DMe(s,l,c,k,d),Ja(B),C=m}function gMe(s,l,c,f,d){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0;var m=0,B=0,k=0,Q=0,O=0;m=C,C=C+32|0,Q=m+24|0,B=m+16|0,O=m+12|0,k=m,za(B),l=ya(l)|0,c=o[c>>0]|0,n[O>>2]=n[f>>2],iR(k,d),n[Q>>2]=n[O>>2],wMe(s,l,c,Q,k),$A(k),Ja(B),C=m}function dMe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0;d=C,C=C+32|0,B=d+16|0,m=d+8|0,k=d,za(m),l=ya(l)|0,c=o[c>>0]|0,n[k>>2]=n[f>>2],n[B>>2]=n[k>>2],mMe(s,l,c,B),Ja(m),C=d}function mMe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0,B=0,k=0;d=C,C=C+16|0,m=d+4|0,k=d,B=Pl(yMe()|0)|0,c=Td(c)|0,n[k>>2]=n[f>>2],n[m>>2]=n[k>>2],Vv(s,oo(0,B|0,l|0,c|0,S0(m)|0)|0),C=d}function yMe(){var s=0;return o[8e3]|0||(EMe(10756),s=8e3,n[s>>2]=1,n[s+4>>2]=0),10756}function Vv(s,l){s=s|0,l=l|0,DF(s,l)}function EMe(s){s=s|0,bl(s,CMe()|0,2)}function CMe(){return 1772}function wMe(s,l,c,f,d){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0;var m=0,B=0,k=0,Q=0,O=0;m=C,C=C+32|0,Q=m+16|0,O=m+12|0,B=m,k=Pl(IMe()|0)|0,c=Td(c)|0,n[O>>2]=n[f>>2],n[Q>>2]=n[O>>2],f=S0(Q)|0,n[B>>2]=n[d>>2],Q=d+4|0,n[B+4>>2]=n[Q>>2],O=d+8|0,n[B+8>>2]=n[O>>2],n[O>>2]=0,n[Q>>2]=0,n[d>>2]=0,Vv(s,hc(0,k|0,l|0,c|0,f|0,oR(B)|0)|0),$A(B),C=m}function IMe(){var s=0;return o[8008]|0||(BMe(10768),s=8008,n[s>>2]=1,n[s+4>>2]=0),10768}function BMe(s){s=s|0,bl(s,vMe()|0,3)}function vMe(){return 1784}function DMe(s,l,c,f,d){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0;var m=0,B=0,k=0,Q=0;m=C,C=C+16|0,k=m+4|0,Q=m,B=Pl(PMe()|0)|0,c=Td(c)|0,n[Q>>2]=n[f>>2],n[k>>2]=n[Q>>2],f=S0(k)|0,Vv(s,hc(0,B|0,l|0,c|0,f|0,sR(d)|0)|0),C=m}function PMe(){var s=0;return o[8016]|0||(bMe(10780),s=8016,n[s>>2]=1,n[s+4>>2]=0),10780}function bMe(s){s=s|0,bl(s,SMe()|0,3)}function SMe(){return 1800}function xMe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;f=Pl(kMe()|0)|0,Vv(s,Qn(0,f|0,l|0,Td(c)|0)|0)}function kMe(){var s=0;return o[8024]|0||(QMe(10792),s=8024,n[s>>2]=1,n[s+4>>2]=0),10792}function QMe(s){s=s|0,bl(s,FMe()|0,1)}function FMe(){return 1816}function RMe(){TMe(),NMe(),LMe()}function TMe(){n[2702]=c7(65536)|0}function NMe(){rOe(10856)}function LMe(){MMe(10816)}function MMe(s){s=s|0,OMe(s,5044),UMe(s)|0}function OMe(s,l){s=s|0,l=l|0;var c=0;c=D9()|0,n[s>>2]=c,JMe(c,l),Pp(n[s>>2]|0)}function UMe(s){s=s|0;var l=0;return l=n[s>>2]|0,P0(l,_Me()|0),s|0}function _Me(){var s=0;return o[8032]|0||(L9(10820),ir(64,10820,U|0)|0,s=8032,n[s>>2]=1,n[s+4>>2]=0),Rr(10820)|0||L9(10820),10820}function L9(s){s=s|0,jMe(s),b0(s,25)}function HMe(s){s=s|0,qMe(s+24|0)}function qMe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function jMe(s){s=s|0;var l=0;l=Vr()|0,zr(s,5,18,l,KMe()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function GMe(s,l){s=s|0,l=l|0,YMe(s,l)}function YMe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0;c=C,C=C+16|0,f=c,d=c+4|0,v0(d,l),n[f>>2]=D0(d,l)|0,WMe(s,f),C=c}function WMe(s,l){s=s|0,l=l|0,M9(s+4|0,n[l>>2]|0),o[s+8>>0]=1}function M9(s,l){s=s|0,l=l|0,n[s>>2]=l}function KMe(){return 1824}function VMe(s){return s=s|0,zMe(s)|0}function zMe(s){s=s|0;var l=0,c=0,f=0,d=0,m=0,B=0,k=0;return c=C,C=C+16|0,d=c+4|0,B=c,f=Va(8)|0,l=f,k=Kt(4)|0,v0(d,s),M9(k,D0(d,s)|0),m=l+4|0,n[m>>2]=k,s=Kt(8)|0,m=n[m>>2]|0,n[B>>2]=0,n[d>>2]=n[B>>2],P9(s,m,d),n[f>>2]=s,C=c,l|0}function Va(s){s=s|0;var l=0,c=0;return s=s+7&-8,s>>>0<=32768&&(l=n[2701]|0,s>>>0<=(65536-l|0)>>>0)?(c=(n[2702]|0)+l|0,n[2701]=l+s,s=c):(s=c7(s+8|0)|0,n[s>>2]=n[2703],n[2703]=s,s=s+8|0),s|0}function JMe(s,l){s=s|0,l=l|0,n[s>>2]=XMe()|0,n[s+4>>2]=ZMe()|0,n[s+12>>2]=l,n[s+8>>2]=$Me()|0,n[s+32>>2]=9}function XMe(){return 11744}function ZMe(){return 1832}function $Me(){return Yv()|0}function eOe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,(Dp(f,896)|0)==512?c|0&&(tOe(c),gt(c)):l|0&&gt(l)}function tOe(s){s=s|0,s=n[s+4>>2]|0,s|0&&bp(s)}function rOe(s){s=s|0,nOe(s,5052),iOe(s)|0,sOe(s,5058,26)|0,oOe(s,5069,1)|0,aOe(s,5077,10)|0,lOe(s,5087,19)|0,cOe(s,5094,27)|0}function nOe(s,l){s=s|0,l=l|0;var c=0;c=tUe()|0,n[s>>2]=c,rUe(c,l),Pp(n[s>>2]|0)}function iOe(s){s=s|0;var l=0;return l=n[s>>2]|0,P0(l,H4e()|0),s|0}function sOe(s,l,c){return s=s|0,l=l|0,c=c|0,B4e(s,pn(l)|0,c,0),s|0}function oOe(s,l,c){return s=s|0,l=l|0,c=c|0,l4e(s,pn(l)|0,c,0),s|0}function aOe(s,l,c){return s=s|0,l=l|0,c=c|0,_Oe(s,pn(l)|0,c,0),s|0}function lOe(s,l,c){return s=s|0,l=l|0,c=c|0,DOe(s,pn(l)|0,c,0),s|0}function O9(s,l){s=s|0,l=l|0;var c=0,f=0;e:for(;;){for(c=n[2703]|0;;){if((c|0)==(l|0))break e;if(f=n[c>>2]|0,n[2703]=f,!c)c=f;else break}gt(c)}n[2701]=s}function cOe(s,l,c){return s=s|0,l=l|0,c=c|0,uOe(s,pn(l)|0,c,0),s|0}function uOe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;m=n[s>>2]|0,d=aR()|0,s=AOe(c)|0,hn(m,l,d,s,fOe(c,f)|0,f)}function aR(){var s=0,l=0;if(o[8040]|0||(_9(10860),ir(65,10860,U|0)|0,l=8040,n[l>>2]=1,n[l+4>>2]=0),!(Rr(10860)|0)){s=10860,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));_9(10860)}return 10860}function AOe(s){return s=s|0,s|0}function fOe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return k=C,C=C+16|0,d=k,m=k+4|0,n[d>>2]=s,Q=aR()|0,B=Q+24|0,l=gr(l,4)|0,n[m>>2]=l,c=Q+28|0,f=n[c>>2]|0,f>>>0<(n[Q+32>>2]|0)>>>0?(U9(f,s,l),l=(n[c>>2]|0)+8|0,n[c>>2]=l):(pOe(B,d,m),l=n[c>>2]|0),C=k,(l-(n[B>>2]|0)>>3)+-1|0}function U9(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c}function pOe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;if(k=C,C=C+32|0,d=k,m=s+4|0,B=((n[m>>2]|0)-(n[s>>2]|0)>>3)+1|0,f=hOe(s)|0,f>>>0<B>>>0)Jr(s);else{Q=n[s>>2]|0,M=(n[s+8>>2]|0)-Q|0,O=M>>2,gOe(d,M>>3>>>0<f>>>1>>>0?O>>>0<B>>>0?B:O:f,(n[m>>2]|0)-Q>>3,s+8|0),B=d+8|0,U9(n[B>>2]|0,n[l>>2]|0,n[c>>2]|0),n[B>>2]=(n[B>>2]|0)+8,dOe(s,d),mOe(d),C=k;return}}function hOe(s){return s=s|0,536870911}function gOe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>536870911)Tt();else{d=Kt(l<<3)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<3)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<3)}function dOe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>3)<<3)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function mOe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&gt(s)}function _9(s){s=s|0,COe(s)}function yOe(s){s=s|0,EOe(s+24|0)}function EOe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function COe(s){s=s|0;var l=0;l=Vr()|0,zr(s,1,11,l,wOe()|0,2),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function wOe(){return 1840}function IOe(s,l,c){s=s|0,l=l|0,c=c|0,vOe(n[(BOe(s)|0)>>2]|0,l,c)}function BOe(s){return s=s|0,(n[(aR()|0)+24>>2]|0)+(s<<3)|0}function vOe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0;f=C,C=C+16|0,m=f+1|0,d=f,v0(m,l),l=D0(m,l)|0,v0(d,c),c=D0(d,c)|0,tf[s&31](l,c),C=f}function DOe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;m=n[s>>2]|0,d=lR()|0,s=POe(c)|0,hn(m,l,d,s,bOe(c,f)|0,f)}function lR(){var s=0,l=0;if(o[8048]|0||(q9(10896),ir(66,10896,U|0)|0,l=8048,n[l>>2]=1,n[l+4>>2]=0),!(Rr(10896)|0)){s=10896,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));q9(10896)}return 10896}function POe(s){return s=s|0,s|0}function bOe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return k=C,C=C+16|0,d=k,m=k+4|0,n[d>>2]=s,Q=lR()|0,B=Q+24|0,l=gr(l,4)|0,n[m>>2]=l,c=Q+28|0,f=n[c>>2]|0,f>>>0<(n[Q+32>>2]|0)>>>0?(H9(f,s,l),l=(n[c>>2]|0)+8|0,n[c>>2]=l):(SOe(B,d,m),l=n[c>>2]|0),C=k,(l-(n[B>>2]|0)>>3)+-1|0}function H9(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c}function SOe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;if(k=C,C=C+32|0,d=k,m=s+4|0,B=((n[m>>2]|0)-(n[s>>2]|0)>>3)+1|0,f=xOe(s)|0,f>>>0<B>>>0)Jr(s);else{Q=n[s>>2]|0,M=(n[s+8>>2]|0)-Q|0,O=M>>2,kOe(d,M>>3>>>0<f>>>1>>>0?O>>>0<B>>>0?B:O:f,(n[m>>2]|0)-Q>>3,s+8|0),B=d+8|0,H9(n[B>>2]|0,n[l>>2]|0,n[c>>2]|0),n[B>>2]=(n[B>>2]|0)+8,QOe(s,d),FOe(d),C=k;return}}function xOe(s){return s=s|0,536870911}function kOe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>536870911)Tt();else{d=Kt(l<<3)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<3)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<3)}function QOe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>3)<<3)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function FOe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&gt(s)}function q9(s){s=s|0,NOe(s)}function ROe(s){s=s|0,TOe(s+24|0)}function TOe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function NOe(s){s=s|0;var l=0;l=Vr()|0,zr(s,1,11,l,LOe()|0,1),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function LOe(){return 1852}function MOe(s,l){return s=s|0,l=l|0,UOe(n[(OOe(s)|0)>>2]|0,l)|0}function OOe(s){return s=s|0,(n[(lR()|0)+24>>2]|0)+(s<<3)|0}function UOe(s,l){s=s|0,l=l|0;var c=0,f=0;return c=C,C=C+16|0,f=c,v0(f,l),l=D0(f,l)|0,l=jv(F0[s&31](l)|0)|0,C=c,l|0}function _Oe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;m=n[s>>2]|0,d=cR()|0,s=HOe(c)|0,hn(m,l,d,s,qOe(c,f)|0,f)}function cR(){var s=0,l=0;if(o[8056]|0||(G9(10932),ir(67,10932,U|0)|0,l=8056,n[l>>2]=1,n[l+4>>2]=0),!(Rr(10932)|0)){s=10932,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));G9(10932)}return 10932}function HOe(s){return s=s|0,s|0}function qOe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return k=C,C=C+16|0,d=k,m=k+4|0,n[d>>2]=s,Q=cR()|0,B=Q+24|0,l=gr(l,4)|0,n[m>>2]=l,c=Q+28|0,f=n[c>>2]|0,f>>>0<(n[Q+32>>2]|0)>>>0?(j9(f,s,l),l=(n[c>>2]|0)+8|0,n[c>>2]=l):(jOe(B,d,m),l=n[c>>2]|0),C=k,(l-(n[B>>2]|0)>>3)+-1|0}function j9(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c}function jOe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;if(k=C,C=C+32|0,d=k,m=s+4|0,B=((n[m>>2]|0)-(n[s>>2]|0)>>3)+1|0,f=GOe(s)|0,f>>>0<B>>>0)Jr(s);else{Q=n[s>>2]|0,M=(n[s+8>>2]|0)-Q|0,O=M>>2,YOe(d,M>>3>>>0<f>>>1>>>0?O>>>0<B>>>0?B:O:f,(n[m>>2]|0)-Q>>3,s+8|0),B=d+8|0,j9(n[B>>2]|0,n[l>>2]|0,n[c>>2]|0),n[B>>2]=(n[B>>2]|0)+8,WOe(s,d),KOe(d),C=k;return}}function GOe(s){return s=s|0,536870911}function YOe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>536870911)Tt();else{d=Kt(l<<3)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<3)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<3)}function WOe(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>3)<<3)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function KOe(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&gt(s)}function G9(s){s=s|0,JOe(s)}function VOe(s){s=s|0,zOe(s+24|0)}function zOe(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function JOe(s){s=s|0;var l=0;l=Vr()|0,zr(s,1,7,l,XOe()|0,2),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function XOe(){return 1860}function ZOe(s,l,c){return s=s|0,l=l|0,c=c|0,e4e(n[($Oe(s)|0)>>2]|0,l,c)|0}function $Oe(s){return s=s|0,(n[(cR()|0)+24>>2]|0)+(s<<3)|0}function e4e(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0;return f=C,C=C+32|0,B=f+12|0,m=f+8|0,k=f,Q=f+16|0,d=f+4|0,t4e(Q,l),r4e(k,Q,l),Ip(d,c),c=Bp(d,c)|0,n[B>>2]=n[k>>2],vw[s&15](m,B,c),c=n4e(m)|0,jA(m),vp(d),C=f,c|0}function t4e(s,l){s=s|0,l=l|0}function r4e(s,l,c){s=s|0,l=l|0,c=c|0,i4e(s,c)}function n4e(s){return s=s|0,ya(s)|0}function i4e(s,l){s=s|0,l=l|0;var c=0,f=0,d=0;d=C,C=C+16|0,c=d,f=l,f&1?(s4e(c,0),ii(f|0,c|0)|0,o4e(s,c),a4e(c)):n[s>>2]=n[l>>2],C=d}function s4e(s,l){s=s|0,l=l|0,K5(s,l),n[s+4>>2]=0,o[s+8>>0]=0}function o4e(s,l){s=s|0,l=l|0,n[s>>2]=n[l+4>>2]}function a4e(s){s=s|0,o[s+8>>0]=0}function l4e(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;m=n[s>>2]|0,d=uR()|0,s=c4e(c)|0,hn(m,l,d,s,u4e(c,f)|0,f)}function uR(){var s=0,l=0;if(o[8064]|0||(W9(10968),ir(68,10968,U|0)|0,l=8064,n[l>>2]=1,n[l+4>>2]=0),!(Rr(10968)|0)){s=10968,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));W9(10968)}return 10968}function c4e(s){return s=s|0,s|0}function u4e(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return k=C,C=C+16|0,d=k,m=k+4|0,n[d>>2]=s,Q=uR()|0,B=Q+24|0,l=gr(l,4)|0,n[m>>2]=l,c=Q+28|0,f=n[c>>2]|0,f>>>0<(n[Q+32>>2]|0)>>>0?(Y9(f,s,l),l=(n[c>>2]|0)+8|0,n[c>>2]=l):(A4e(B,d,m),l=n[c>>2]|0),C=k,(l-(n[B>>2]|0)>>3)+-1|0}function Y9(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c}function A4e(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;if(k=C,C=C+32|0,d=k,m=s+4|0,B=((n[m>>2]|0)-(n[s>>2]|0)>>3)+1|0,f=f4e(s)|0,f>>>0<B>>>0)Jr(s);else{Q=n[s>>2]|0,M=(n[s+8>>2]|0)-Q|0,O=M>>2,p4e(d,M>>3>>>0<f>>>1>>>0?O>>>0<B>>>0?B:O:f,(n[m>>2]|0)-Q>>3,s+8|0),B=d+8|0,Y9(n[B>>2]|0,n[l>>2]|0,n[c>>2]|0),n[B>>2]=(n[B>>2]|0)+8,h4e(s,d),g4e(d),C=k;return}}function f4e(s){return s=s|0,536870911}function p4e(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>536870911)Tt();else{d=Kt(l<<3)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<3)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<3)}function h4e(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>3)<<3)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function g4e(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&gt(s)}function W9(s){s=s|0,y4e(s)}function d4e(s){s=s|0,m4e(s+24|0)}function m4e(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function y4e(s){s=s|0;var l=0;l=Vr()|0,zr(s,1,1,l,E4e()|0,5),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function E4e(){return 1872}function C4e(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0,I4e(n[(w4e(s)|0)>>2]|0,l,c,f,d,m)}function w4e(s){return s=s|0,(n[(uR()|0)+24>>2]|0)+(s<<3)|0}function I4e(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0;var B=0,k=0,Q=0,O=0,M=0,j=0;B=C,C=C+32|0,k=B+16|0,Q=B+12|0,O=B+8|0,M=B+4|0,j=B,Ip(k,l),l=Bp(k,l)|0,Ip(Q,c),c=Bp(Q,c)|0,Ip(O,f),f=Bp(O,f)|0,Ip(M,d),d=Bp(M,d)|0,Ip(j,m),m=Bp(j,m)|0,h7[s&1](l,c,f,d,m),vp(j),vp(M),vp(O),vp(Q),vp(k),C=B}function B4e(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;m=n[s>>2]|0,d=AR()|0,s=v4e(c)|0,hn(m,l,d,s,D4e(c,f)|0,f)}function AR(){var s=0,l=0;if(o[8072]|0||(V9(11004),ir(69,11004,U|0)|0,l=8072,n[l>>2]=1,n[l+4>>2]=0),!(Rr(11004)|0)){s=11004,l=s+36|0;do n[s>>2]=0,s=s+4|0;while((s|0)<(l|0));V9(11004)}return 11004}function v4e(s){return s=s|0,s|0}function D4e(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0,k=0,Q=0;return k=C,C=C+16|0,d=k,m=k+4|0,n[d>>2]=s,Q=AR()|0,B=Q+24|0,l=gr(l,4)|0,n[m>>2]=l,c=Q+28|0,f=n[c>>2]|0,f>>>0<(n[Q+32>>2]|0)>>>0?(K9(f,s,l),l=(n[c>>2]|0)+8|0,n[c>>2]=l):(P4e(B,d,m),l=n[c>>2]|0),C=k,(l-(n[B>>2]|0)>>3)+-1|0}function K9(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,n[s+4>>2]=c}function P4e(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0;if(k=C,C=C+32|0,d=k,m=s+4|0,B=((n[m>>2]|0)-(n[s>>2]|0)>>3)+1|0,f=b4e(s)|0,f>>>0<B>>>0)Jr(s);else{Q=n[s>>2]|0,M=(n[s+8>>2]|0)-Q|0,O=M>>2,S4e(d,M>>3>>>0<f>>>1>>>0?O>>>0<B>>>0?B:O:f,(n[m>>2]|0)-Q>>3,s+8|0),B=d+8|0,K9(n[B>>2]|0,n[l>>2]|0,n[c>>2]|0),n[B>>2]=(n[B>>2]|0)+8,x4e(s,d),k4e(d),C=k;return}}function b4e(s){return s=s|0,536870911}function S4e(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0;n[s+12>>2]=0,n[s+16>>2]=f;do if(l)if(l>>>0>536870911)Tt();else{d=Kt(l<<3)|0;break}else d=0;while(!1);n[s>>2]=d,f=d+(c<<3)|0,n[s+8>>2]=f,n[s+4>>2]=f,n[s+12>>2]=d+(l<<3)}function x4e(s,l){s=s|0,l=l|0;var c=0,f=0,d=0,m=0,B=0;f=n[s>>2]|0,B=s+4|0,m=l+4|0,d=(n[B>>2]|0)-f|0,c=(n[m>>2]|0)+(0-(d>>3)<<3)|0,n[m>>2]=c,(d|0)>0?(Dr(c|0,f|0,d|0)|0,f=m,c=n[m>>2]|0):f=m,m=n[s>>2]|0,n[s>>2]=c,n[f>>2]=m,m=l+8|0,d=n[B>>2]|0,n[B>>2]=n[m>>2],n[m>>2]=d,m=s+8|0,B=l+12|0,s=n[m>>2]|0,n[m>>2]=n[B>>2],n[B>>2]=s,n[l>>2]=n[f>>2]}function k4e(s){s=s|0;var l=0,c=0,f=0;l=n[s+4>>2]|0,c=s+8|0,f=n[c>>2]|0,(f|0)!=(l|0)&&(n[c>>2]=f+(~((f+-8-l|0)>>>3)<<3)),s=n[s>>2]|0,s|0&&gt(s)}function V9(s){s=s|0,R4e(s)}function Q4e(s){s=s|0,F4e(s+24|0)}function F4e(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function R4e(s){s=s|0;var l=0;l=Vr()|0,zr(s,1,12,l,T4e()|0,2),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function T4e(){return 1896}function N4e(s,l,c){s=s|0,l=l|0,c=c|0,M4e(n[(L4e(s)|0)>>2]|0,l,c)}function L4e(s){return s=s|0,(n[(AR()|0)+24>>2]|0)+(s<<3)|0}function M4e(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0;f=C,C=C+16|0,m=f+4|0,d=f,O4e(m,l),l=U4e(m,l)|0,Ip(d,c),c=Bp(d,c)|0,tf[s&31](l,c),vp(d),C=f}function O4e(s,l){s=s|0,l=l|0}function U4e(s,l){return s=s|0,l=l|0,_4e(l)|0}function _4e(s){return s=s|0,s|0}function H4e(){var s=0;return o[8080]|0||(z9(11040),ir(70,11040,U|0)|0,s=8080,n[s>>2]=1,n[s+4>>2]=0),Rr(11040)|0||z9(11040),11040}function z9(s){s=s|0,G4e(s),b0(s,71)}function q4e(s){s=s|0,j4e(s+24|0)}function j4e(s){s=s|0;var l=0,c=0,f=0;c=n[s>>2]|0,f=c,c|0&&(s=s+4|0,l=n[s>>2]|0,(l|0)!=(c|0)&&(n[s>>2]=l+(~((l+-8-f|0)>>>3)<<3)),gt(c))}function G4e(s){s=s|0;var l=0;l=Vr()|0,zr(s,5,7,l,V4e()|0,0),n[s+24>>2]=0,n[s+28>>2]=0,n[s+32>>2]=0}function Y4e(s){s=s|0,W4e(s)}function W4e(s){s=s|0,K4e(s)}function K4e(s){s=s|0,o[s+8>>0]=1}function V4e(){return 1936}function z4e(){return J4e()|0}function J4e(){var s=0,l=0,c=0,f=0,d=0,m=0,B=0;return l=C,C=C+16|0,d=l+4|0,B=l,c=Va(8)|0,s=c,m=s+4|0,n[m>>2]=Kt(1)|0,f=Kt(8)|0,m=n[m>>2]|0,n[B>>2]=0,n[d>>2]=n[B>>2],X4e(f,m,d),n[c>>2]=f,C=l,s|0}function X4e(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]=l,c=Kt(16)|0,n[c+4>>2]=0,n[c+8>>2]=0,n[c>>2]=1916,n[c+12>>2]=l,n[s+4>>2]=c}function Z4e(s){s=s|0,Md(s),gt(s)}function $4e(s){s=s|0,s=n[s+12>>2]|0,s|0&&gt(s)}function eUe(s){s=s|0,gt(s)}function tUe(){var s=0;return o[8088]|0||(lUe(11076),ir(25,11076,U|0)|0,s=8088,n[s>>2]=1,n[s+4>>2]=0),11076}function rUe(s,l){s=s|0,l=l|0,n[s>>2]=nUe()|0,n[s+4>>2]=iUe()|0,n[s+12>>2]=l,n[s+8>>2]=sUe()|0,n[s+32>>2]=10}function nUe(){return 11745}function iUe(){return 1940}function sUe(){return Gv()|0}function oUe(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,(Dp(f,896)|0)==512?c|0&&(aUe(c),gt(c)):l|0&&gt(l)}function aUe(s){s=s|0,s=n[s+4>>2]|0,s|0&&bp(s)}function lUe(s){s=s|0,wp(s)}function xc(s,l){s=s|0,l=l|0,n[s>>2]=l}function fR(s){return s=s|0,n[s>>2]|0}function cUe(s){return s=s|0,o[n[s>>2]>>0]|0}function uUe(s,l){s=s|0,l=l|0;var c=0,f=0;c=C,C=C+16|0,f=c,n[f>>2]=n[s>>2],AUe(l,f)|0,C=c}function AUe(s,l){s=s|0,l=l|0;var c=0;return c=fUe(n[s>>2]|0,l)|0,l=s+4|0,n[(n[l>>2]|0)+8>>2]=c,n[(n[l>>2]|0)+8>>2]|0}function fUe(s,l){s=s|0,l=l|0;var c=0,f=0;return c=C,C=C+16|0,f=c,za(f),s=ya(s)|0,l=pUe(s,n[l>>2]|0)|0,Ja(f),C=c,l|0}function za(s){s=s|0,n[s>>2]=n[2701],n[s+4>>2]=n[2703]}function pUe(s,l){s=s|0,l=l|0;var c=0;return c=Pl(hUe()|0)|0,Qn(0,c|0,s|0,sR(l)|0)|0}function Ja(s){s=s|0,O9(n[s>>2]|0,n[s+4>>2]|0)}function hUe(){var s=0;return o[8096]|0||(gUe(11120),s=8096,n[s>>2]=1,n[s+4>>2]=0),11120}function gUe(s){s=s|0,bl(s,dUe()|0,1)}function dUe(){return 1948}function mUe(){yUe()}function yUe(){var s=0,l=0,c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0,je=0,Oe=0,Qe=0;if(Oe=C,C=C+16|0,M=Oe+4|0,j=Oe,Ti(65536,10804,n[2702]|0,10812),c=E9()|0,l=n[c>>2]|0,s=n[l>>2]|0,s|0)for(f=n[c+8>>2]|0,c=n[c+4>>2]|0;Ac(s|0,u[c>>0]|0|0,o[f>>0]|0),l=l+4|0,s=n[l>>2]|0,s;)f=f+1|0,c=c+1|0;if(s=C9()|0,l=n[s>>2]|0,l|0)do fu(l|0,n[s+4>>2]|0),s=s+8|0,l=n[s>>2]|0;while(l|0);fu(EUe()|0,5167),O=Fd()|0,s=n[O>>2]|0;e:do if(s|0){do CUe(n[s+4>>2]|0),s=n[s>>2]|0;while(s|0);if(s=n[O>>2]|0,s|0){Q=O;do{for(;d=s,s=n[s>>2]|0,d=n[d+4>>2]|0,!!(wUe(d)|0);)if(n[j>>2]=Q,n[M>>2]=n[j>>2],IUe(O,M)|0,!s)break e;if(BUe(d),Q=n[Q>>2]|0,l=J9(d)|0,m=Hi()|0,B=C,C=C+((1*(l<<2)|0)+15&-16)|0,k=C,C=C+((1*(l<<2)|0)+15&-16)|0,l=n[(F9(d)|0)>>2]|0,l|0)for(c=B,f=k;n[c>>2]=n[(Rd(n[l+4>>2]|0)|0)>>2],n[f>>2]=n[l+8>>2],l=n[l>>2]|0,l;)c=c+4|0,f=f+4|0;Qe=Rd(d)|0,l=vUe(d)|0,c=J9(d)|0,f=DUe(d)|0,pu(Qe|0,l|0,B|0,k|0,c|0,f|0,$F(d)|0),_i(m|0)}while(s|0)}}while(!1);if(s=n[(eR()|0)>>2]|0,s|0)do Qe=s+4|0,O=tR(Qe)|0,d=Cw(O)|0,m=yw(O)|0,B=(Ew(O)|0)+1|0,k=zv(O)|0,Q=X9(Qe)|0,O=Rr(O)|0,M=Wv(Qe)|0,j=pR(Qe)|0,El(0,d|0,m|0,B|0,k|0,Q|0,O|0,M|0,j|0,hR(Qe)|0),s=n[s>>2]|0;while(s|0);s=n[(Fd()|0)>>2]|0;e:do if(s|0){t:for(;;){if(l=n[s+4>>2]|0,l|0&&(se=n[(Rd(l)|0)>>2]|0,je=n[(R9(l)|0)>>2]|0,je|0)){c=je;do{l=c+4|0,f=tR(l)|0;r:do if(f|0)switch(Rr(f)|0){case 0:break t;case 4:case 3:case 2:{k=Cw(f)|0,Q=yw(f)|0,O=(Ew(f)|0)+1|0,M=zv(f)|0,j=Rr(f)|0,Qe=Wv(l)|0,El(se|0,k|0,Q|0,O|0,M|0,0,j|0,Qe|0,pR(l)|0,hR(l)|0);break r}case 1:{B=Cw(f)|0,k=yw(f)|0,Q=(Ew(f)|0)+1|0,O=zv(f)|0,M=X9(l)|0,j=Rr(f)|0,Qe=Wv(l)|0,El(se|0,B|0,k|0,Q|0,O|0,M|0,j|0,Qe|0,pR(l)|0,hR(l)|0);break r}case 5:{O=Cw(f)|0,M=yw(f)|0,j=(Ew(f)|0)+1|0,Qe=zv(f)|0,El(se|0,O|0,M|0,j|0,Qe|0,PUe(f)|0,Rr(f)|0,0,0,0);break r}default:break r}while(!1);c=n[c>>2]|0}while(c|0)}if(s=n[s>>2]|0,!s)break e}Tt()}while(!1);Ie(),C=Oe}function EUe(){return 11703}function CUe(s){s=s|0,o[s+40>>0]=0}function wUe(s){return s=s|0,(o[s+40>>0]|0)!=0|0}function IUe(s,l){return s=s|0,l=l|0,l=bUe(l)|0,s=n[l>>2]|0,n[l>>2]=n[s>>2],gt(s),n[l>>2]|0}function BUe(s){s=s|0,o[s+40>>0]=1}function J9(s){return s=s|0,n[s+20>>2]|0}function vUe(s){return s=s|0,n[s+8>>2]|0}function DUe(s){return s=s|0,n[s+32>>2]|0}function zv(s){return s=s|0,n[s+4>>2]|0}function X9(s){return s=s|0,n[s+4>>2]|0}function pR(s){return s=s|0,n[s+8>>2]|0}function hR(s){return s=s|0,n[s+16>>2]|0}function PUe(s){return s=s|0,n[s+20>>2]|0}function bUe(s){return s=s|0,n[s>>2]|0}function Jv(s){s=s|0;var l=0,c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0,je=0,Oe=0,Qe=0,$e=0,Je=0,lt=0,_e=0,qe=0,Lt=0;Lt=C,C=C+16|0,se=Lt;do if(s>>>0<245){if(O=s>>>0<11?16:s+11&-8,s=O>>>3,j=n[2783]|0,c=j>>>s,c&3|0)return l=(c&1^1)+s|0,s=11172+(l<<1<<2)|0,c=s+8|0,f=n[c>>2]|0,d=f+8|0,m=n[d>>2]|0,(s|0)==(m|0)?n[2783]=j&~(1<<l):(n[m+12>>2]=s,n[c>>2]=m),qe=l<<3,n[f+4>>2]=qe|3,qe=f+qe+4|0,n[qe>>2]=n[qe>>2]|1,qe=d,C=Lt,qe|0;if(M=n[2785]|0,O>>>0>M>>>0){if(c|0)return l=2<<s,l=c<<s&(l|0-l),l=(l&0-l)+-1|0,B=l>>>12&16,l=l>>>B,c=l>>>5&8,l=l>>>c,d=l>>>2&4,l=l>>>d,s=l>>>1&2,l=l>>>s,f=l>>>1&1,f=(c|B|d|s|f)+(l>>>f)|0,l=11172+(f<<1<<2)|0,s=l+8|0,d=n[s>>2]|0,B=d+8|0,c=n[B>>2]|0,(l|0)==(c|0)?(s=j&~(1<<f),n[2783]=s):(n[c+12>>2]=l,n[s>>2]=c,s=j),m=(f<<3)-O|0,n[d+4>>2]=O|3,f=d+O|0,n[f+4>>2]=m|1,n[f+m>>2]=m,M|0&&(d=n[2788]|0,l=M>>>3,c=11172+(l<<1<<2)|0,l=1<<l,s&l?(s=c+8|0,l=n[s>>2]|0):(n[2783]=s|l,l=c,s=c+8|0),n[s>>2]=d,n[l+12>>2]=d,n[d+8>>2]=l,n[d+12>>2]=c),n[2785]=m,n[2788]=f,qe=B,C=Lt,qe|0;if(k=n[2784]|0,k){if(c=(k&0-k)+-1|0,B=c>>>12&16,c=c>>>B,m=c>>>5&8,c=c>>>m,Q=c>>>2&4,c=c>>>Q,f=c>>>1&2,c=c>>>f,s=c>>>1&1,s=n[11436+((m|B|Q|f|s)+(c>>>s)<<2)>>2]|0,c=(n[s+4>>2]&-8)-O|0,f=n[s+16+(((n[s+16>>2]|0)==0&1)<<2)>>2]|0,!f)Q=s,m=c;else{do B=(n[f+4>>2]&-8)-O|0,Q=B>>>0<c>>>0,c=Q?B:c,s=Q?f:s,f=n[f+16+(((n[f+16>>2]|0)==0&1)<<2)>>2]|0;while(f|0);Q=s,m=c}if(B=Q+O|0,Q>>>0<B>>>0){d=n[Q+24>>2]|0,l=n[Q+12>>2]|0;do if((l|0)==(Q|0)){if(s=Q+20|0,l=n[s>>2]|0,!l&&(s=Q+16|0,l=n[s>>2]|0,!l)){c=0;break}for(;;){if(c=l+20|0,f=n[c>>2]|0,f|0){l=f,s=c;continue}if(c=l+16|0,f=n[c>>2]|0,f)l=f,s=c;else break}n[s>>2]=0,c=l}else c=n[Q+8>>2]|0,n[c+12>>2]=l,n[l+8>>2]=c,c=l;while(!1);do if(d|0){if(l=n[Q+28>>2]|0,s=11436+(l<<2)|0,(Q|0)==(n[s>>2]|0)){if(n[s>>2]=c,!c){n[2784]=k&~(1<<l);break}}else if(n[d+16+(((n[d+16>>2]|0)!=(Q|0)&1)<<2)>>2]=c,!c)break;n[c+24>>2]=d,l=n[Q+16>>2]|0,l|0&&(n[c+16>>2]=l,n[l+24>>2]=c),l=n[Q+20>>2]|0,l|0&&(n[c+20>>2]=l,n[l+24>>2]=c)}while(!1);return m>>>0<16?(qe=m+O|0,n[Q+4>>2]=qe|3,qe=Q+qe+4|0,n[qe>>2]=n[qe>>2]|1):(n[Q+4>>2]=O|3,n[B+4>>2]=m|1,n[B+m>>2]=m,M|0&&(f=n[2788]|0,l=M>>>3,c=11172+(l<<1<<2)|0,l=1<<l,j&l?(s=c+8|0,l=n[s>>2]|0):(n[2783]=j|l,l=c,s=c+8|0),n[s>>2]=f,n[l+12>>2]=f,n[f+8>>2]=l,n[f+12>>2]=c),n[2785]=m,n[2788]=B),qe=Q+8|0,C=Lt,qe|0}else j=O}else j=O}else j=O}else if(s>>>0<=4294967231)if(s=s+11|0,O=s&-8,Q=n[2784]|0,Q){f=0-O|0,s=s>>>8,s?O>>>0>16777215?k=31:(j=(s+1048320|0)>>>16&8,_e=s<<j,M=(_e+520192|0)>>>16&4,_e=_e<<M,k=(_e+245760|0)>>>16&2,k=14-(M|j|k)+(_e<<k>>>15)|0,k=O>>>(k+7|0)&1|k<<1):k=0,c=n[11436+(k<<2)>>2]|0;e:do if(!c)c=0,s=0,_e=57;else for(s=0,B=O<<((k|0)==31?0:25-(k>>>1)|0),m=0;;){if(d=(n[c+4>>2]&-8)-O|0,d>>>0<f>>>0)if(d)s=c,f=d;else{s=c,f=0,d=c,_e=61;break e}if(d=n[c+20>>2]|0,c=n[c+16+(B>>>31<<2)>>2]|0,m=(d|0)==0|(d|0)==(c|0)?m:d,d=(c|0)==0,d){c=m,_e=57;break}else B=B<<((d^1)&1)}while(!1);if((_e|0)==57){if((c|0)==0&(s|0)==0){if(s=2<<k,s=Q&(s|0-s),!s){j=O;break}j=(s&0-s)+-1|0,B=j>>>12&16,j=j>>>B,m=j>>>5&8,j=j>>>m,k=j>>>2&4,j=j>>>k,M=j>>>1&2,j=j>>>M,c=j>>>1&1,s=0,c=n[11436+((m|B|k|M|c)+(j>>>c)<<2)>>2]|0}c?(d=c,_e=61):(k=s,B=f)}if((_e|0)==61)for(;;)if(_e=0,c=(n[d+4>>2]&-8)-O|0,j=c>>>0<f>>>0,c=j?c:f,s=j?d:s,d=n[d+16+(((n[d+16>>2]|0)==0&1)<<2)>>2]|0,d)f=c,_e=61;else{k=s,B=c;break}if(k|0&&B>>>0<((n[2785]|0)-O|0)>>>0){if(m=k+O|0,k>>>0>=m>>>0)return qe=0,C=Lt,qe|0;d=n[k+24>>2]|0,l=n[k+12>>2]|0;do if((l|0)==(k|0)){if(s=k+20|0,l=n[s>>2]|0,!l&&(s=k+16|0,l=n[s>>2]|0,!l)){l=0;break}for(;;){if(c=l+20|0,f=n[c>>2]|0,f|0){l=f,s=c;continue}if(c=l+16|0,f=n[c>>2]|0,f)l=f,s=c;else break}n[s>>2]=0}else qe=n[k+8>>2]|0,n[qe+12>>2]=l,n[l+8>>2]=qe;while(!1);do if(d){if(s=n[k+28>>2]|0,c=11436+(s<<2)|0,(k|0)==(n[c>>2]|0)){if(n[c>>2]=l,!l){f=Q&~(1<<s),n[2784]=f;break}}else if(n[d+16+(((n[d+16>>2]|0)!=(k|0)&1)<<2)>>2]=l,!l){f=Q;break}n[l+24>>2]=d,s=n[k+16>>2]|0,s|0&&(n[l+16>>2]=s,n[s+24>>2]=l),s=n[k+20>>2]|0,s&&(n[l+20>>2]=s,n[s+24>>2]=l),f=Q}else f=Q;while(!1);do if(B>>>0>=16){if(n[k+4>>2]=O|3,n[m+4>>2]=B|1,n[m+B>>2]=B,l=B>>>3,B>>>0<256){c=11172+(l<<1<<2)|0,s=n[2783]|0,l=1<<l,s&l?(s=c+8|0,l=n[s>>2]|0):(n[2783]=s|l,l=c,s=c+8|0),n[s>>2]=m,n[l+12>>2]=m,n[m+8>>2]=l,n[m+12>>2]=c;break}if(l=B>>>8,l?B>>>0>16777215?l=31:(_e=(l+1048320|0)>>>16&8,qe=l<<_e,lt=(qe+520192|0)>>>16&4,qe=qe<<lt,l=(qe+245760|0)>>>16&2,l=14-(lt|_e|l)+(qe<<l>>>15)|0,l=B>>>(l+7|0)&1|l<<1):l=0,c=11436+(l<<2)|0,n[m+28>>2]=l,s=m+16|0,n[s+4>>2]=0,n[s>>2]=0,s=1<<l,!(f&s)){n[2784]=f|s,n[c>>2]=m,n[m+24>>2]=c,n[m+12>>2]=m,n[m+8>>2]=m;break}for(s=B<<((l|0)==31?0:25-(l>>>1)|0),c=n[c>>2]|0;;){if((n[c+4>>2]&-8|0)==(B|0)){_e=97;break}if(f=c+16+(s>>>31<<2)|0,l=n[f>>2]|0,l)s=s<<1,c=l;else{_e=96;break}}if((_e|0)==96){n[f>>2]=m,n[m+24>>2]=c,n[m+12>>2]=m,n[m+8>>2]=m;break}else if((_e|0)==97){_e=c+8|0,qe=n[_e>>2]|0,n[qe+12>>2]=m,n[_e>>2]=m,n[m+8>>2]=qe,n[m+12>>2]=c,n[m+24>>2]=0;break}}else qe=B+O|0,n[k+4>>2]=qe|3,qe=k+qe+4|0,n[qe>>2]=n[qe>>2]|1;while(!1);return qe=k+8|0,C=Lt,qe|0}else j=O}else j=O;else j=-1;while(!1);if(c=n[2785]|0,c>>>0>=j>>>0)return l=c-j|0,s=n[2788]|0,l>>>0>15?(qe=s+j|0,n[2788]=qe,n[2785]=l,n[qe+4>>2]=l|1,n[qe+l>>2]=l,n[s+4>>2]=j|3):(n[2785]=0,n[2788]=0,n[s+4>>2]=c|3,qe=s+c+4|0,n[qe>>2]=n[qe>>2]|1),qe=s+8|0,C=Lt,qe|0;if(B=n[2786]|0,B>>>0>j>>>0)return lt=B-j|0,n[2786]=lt,qe=n[2789]|0,_e=qe+j|0,n[2789]=_e,n[_e+4>>2]=lt|1,n[qe+4>>2]=j|3,qe=qe+8|0,C=Lt,qe|0;if(n[2901]|0?s=n[2903]|0:(n[2903]=4096,n[2902]=4096,n[2904]=-1,n[2905]=-1,n[2906]=0,n[2894]=0,s=se&-16^1431655768,n[se>>2]=s,n[2901]=s,s=4096),k=j+48|0,Q=j+47|0,m=s+Q|0,d=0-s|0,O=m&d,O>>>0<=j>>>0||(s=n[2893]|0,s|0&&(M=n[2891]|0,se=M+O|0,se>>>0<=M>>>0|se>>>0>s>>>0)))return qe=0,C=Lt,qe|0;e:do if(n[2894]&4)l=0,_e=133;else{c=n[2789]|0;t:do if(c){for(f=11580;s=n[f>>2]|0,!(s>>>0<=c>>>0&&(Qe=f+4|0,(s+(n[Qe>>2]|0)|0)>>>0>c>>>0));)if(s=n[f+8>>2]|0,s)f=s;else{_e=118;break t}if(l=m-B&d,l>>>0<2147483647)if(s=Sp(l|0)|0,(s|0)==((n[f>>2]|0)+(n[Qe>>2]|0)|0)){if((s|0)!=-1){B=l,m=s,_e=135;break e}}else f=s,_e=126;else l=0}else _e=118;while(!1);do if((_e|0)==118)if(c=Sp(0)|0,(c|0)!=-1&&(l=c,je=n[2902]|0,Oe=je+-1|0,l=(Oe&l|0?(Oe+l&0-je)-l|0:0)+O|0,je=n[2891]|0,Oe=l+je|0,l>>>0>j>>>0&l>>>0<2147483647)){if(Qe=n[2893]|0,Qe|0&&Oe>>>0<=je>>>0|Oe>>>0>Qe>>>0){l=0;break}if(s=Sp(l|0)|0,(s|0)==(c|0)){B=l,m=c,_e=135;break e}else f=s,_e=126}else l=0;while(!1);do if((_e|0)==126){if(c=0-l|0,!(k>>>0>l>>>0&(l>>>0<2147483647&(f|0)!=-1)))if((f|0)==-1){l=0;break}else{B=l,m=f,_e=135;break e}if(s=n[2903]|0,s=Q-l+s&0-s,s>>>0>=2147483647){B=l,m=f,_e=135;break e}if((Sp(s|0)|0)==-1){Sp(c|0)|0,l=0;break}else{B=s+l|0,m=f,_e=135;break e}}while(!1);n[2894]=n[2894]|4,_e=133}while(!1);if((_e|0)==133&&O>>>0<2147483647&&(lt=Sp(O|0)|0,Qe=Sp(0)|0,$e=Qe-lt|0,Je=$e>>>0>(j+40|0)>>>0,!((lt|0)==-1|Je^1|lt>>>0<Qe>>>0&((lt|0)!=-1&(Qe|0)!=-1)^1))&&(B=Je?$e:l,m=lt,_e=135),(_e|0)==135){l=(n[2891]|0)+B|0,n[2891]=l,l>>>0>(n[2892]|0)>>>0&&(n[2892]=l),Q=n[2789]|0;do if(Q){for(l=11580;;){if(s=n[l>>2]|0,c=l+4|0,f=n[c>>2]|0,(m|0)==(s+f|0)){_e=145;break}if(d=n[l+8>>2]|0,d)l=d;else break}if((_e|0)==145&&!(n[l+12>>2]&8|0)&&Q>>>0<m>>>0&Q>>>0>=s>>>0){n[c>>2]=f+B,qe=Q+8|0,qe=qe&7|0?0-qe&7:0,_e=Q+qe|0,qe=(n[2786]|0)+(B-qe)|0,n[2789]=_e,n[2786]=qe,n[_e+4>>2]=qe|1,n[_e+qe+4>>2]=40,n[2790]=n[2905];break}for(m>>>0<(n[2787]|0)>>>0&&(n[2787]=m),c=m+B|0,l=11580;;){if((n[l>>2]|0)==(c|0)){_e=153;break}if(s=n[l+8>>2]|0,s)l=s;else break}if((_e|0)==153&&!(n[l+12>>2]&8|0)){n[l>>2]=m,M=l+4|0,n[M>>2]=(n[M>>2]|0)+B,M=m+8|0,M=m+(M&7|0?0-M&7:0)|0,l=c+8|0,l=c+(l&7|0?0-l&7:0)|0,O=M+j|0,k=l-M-j|0,n[M+4>>2]=j|3;do if((l|0)!=(Q|0)){if((l|0)==(n[2788]|0)){qe=(n[2785]|0)+k|0,n[2785]=qe,n[2788]=O,n[O+4>>2]=qe|1,n[O+qe>>2]=qe;break}if(s=n[l+4>>2]|0,(s&3|0)==1){B=s&-8,f=s>>>3;e:do if(s>>>0<256)if(s=n[l+8>>2]|0,c=n[l+12>>2]|0,(c|0)==(s|0)){n[2783]=n[2783]&~(1<<f);break}else{n[s+12>>2]=c,n[c+8>>2]=s;break}else{m=n[l+24>>2]|0,s=n[l+12>>2]|0;do if((s|0)==(l|0)){if(f=l+16|0,c=f+4|0,s=n[c>>2]|0,!s)if(s=n[f>>2]|0,s)c=f;else{s=0;break}for(;;){if(f=s+20|0,d=n[f>>2]|0,d|0){s=d,c=f;continue}if(f=s+16|0,d=n[f>>2]|0,d)s=d,c=f;else break}n[c>>2]=0}else qe=n[l+8>>2]|0,n[qe+12>>2]=s,n[s+8>>2]=qe;while(!1);if(!m)break;c=n[l+28>>2]|0,f=11436+(c<<2)|0;do if((l|0)!=(n[f>>2]|0)){if(n[m+16+(((n[m+16>>2]|0)!=(l|0)&1)<<2)>>2]=s,!s)break e}else{if(n[f>>2]=s,s|0)break;n[2784]=n[2784]&~(1<<c);break e}while(!1);if(n[s+24>>2]=m,c=l+16|0,f=n[c>>2]|0,f|0&&(n[s+16>>2]=f,n[f+24>>2]=s),c=n[c+4>>2]|0,!c)break;n[s+20>>2]=c,n[c+24>>2]=s}while(!1);l=l+B|0,d=B+k|0}else d=k;if(l=l+4|0,n[l>>2]=n[l>>2]&-2,n[O+4>>2]=d|1,n[O+d>>2]=d,l=d>>>3,d>>>0<256){c=11172+(l<<1<<2)|0,s=n[2783]|0,l=1<<l,s&l?(s=c+8|0,l=n[s>>2]|0):(n[2783]=s|l,l=c,s=c+8|0),n[s>>2]=O,n[l+12>>2]=O,n[O+8>>2]=l,n[O+12>>2]=c;break}l=d>>>8;do if(!l)l=0;else{if(d>>>0>16777215){l=31;break}_e=(l+1048320|0)>>>16&8,qe=l<<_e,lt=(qe+520192|0)>>>16&4,qe=qe<<lt,l=(qe+245760|0)>>>16&2,l=14-(lt|_e|l)+(qe<<l>>>15)|0,l=d>>>(l+7|0)&1|l<<1}while(!1);if(f=11436+(l<<2)|0,n[O+28>>2]=l,s=O+16|0,n[s+4>>2]=0,n[s>>2]=0,s=n[2784]|0,c=1<<l,!(s&c)){n[2784]=s|c,n[f>>2]=O,n[O+24>>2]=f,n[O+12>>2]=O,n[O+8>>2]=O;break}for(s=d<<((l|0)==31?0:25-(l>>>1)|0),c=n[f>>2]|0;;){if((n[c+4>>2]&-8|0)==(d|0)){_e=194;break}if(f=c+16+(s>>>31<<2)|0,l=n[f>>2]|0,l)s=s<<1,c=l;else{_e=193;break}}if((_e|0)==193){n[f>>2]=O,n[O+24>>2]=c,n[O+12>>2]=O,n[O+8>>2]=O;break}else if((_e|0)==194){_e=c+8|0,qe=n[_e>>2]|0,n[qe+12>>2]=O,n[_e>>2]=O,n[O+8>>2]=qe,n[O+12>>2]=c,n[O+24>>2]=0;break}}else qe=(n[2786]|0)+k|0,n[2786]=qe,n[2789]=O,n[O+4>>2]=qe|1;while(!1);return qe=M+8|0,C=Lt,qe|0}for(l=11580;s=n[l>>2]|0,!(s>>>0<=Q>>>0&&(qe=s+(n[l+4>>2]|0)|0,qe>>>0>Q>>>0));)l=n[l+8>>2]|0;d=qe+-47|0,s=d+8|0,s=d+(s&7|0?0-s&7:0)|0,d=Q+16|0,s=s>>>0<d>>>0?Q:s,l=s+8|0,c=m+8|0,c=c&7|0?0-c&7:0,_e=m+c|0,c=B+-40-c|0,n[2789]=_e,n[2786]=c,n[_e+4>>2]=c|1,n[_e+c+4>>2]=40,n[2790]=n[2905],c=s+4|0,n[c>>2]=27,n[l>>2]=n[2895],n[l+4>>2]=n[2896],n[l+8>>2]=n[2897],n[l+12>>2]=n[2898],n[2895]=m,n[2896]=B,n[2898]=0,n[2897]=l,l=s+24|0;do _e=l,l=l+4|0,n[l>>2]=7;while((_e+8|0)>>>0<qe>>>0);if((s|0)!=(Q|0)){if(m=s-Q|0,n[c>>2]=n[c>>2]&-2,n[Q+4>>2]=m|1,n[s>>2]=m,l=m>>>3,m>>>0<256){c=11172+(l<<1<<2)|0,s=n[2783]|0,l=1<<l,s&l?(s=c+8|0,l=n[s>>2]|0):(n[2783]=s|l,l=c,s=c+8|0),n[s>>2]=Q,n[l+12>>2]=Q,n[Q+8>>2]=l,n[Q+12>>2]=c;break}if(l=m>>>8,l?m>>>0>16777215?c=31:(_e=(l+1048320|0)>>>16&8,qe=l<<_e,lt=(qe+520192|0)>>>16&4,qe=qe<<lt,c=(qe+245760|0)>>>16&2,c=14-(lt|_e|c)+(qe<<c>>>15)|0,c=m>>>(c+7|0)&1|c<<1):c=0,f=11436+(c<<2)|0,n[Q+28>>2]=c,n[Q+20>>2]=0,n[d>>2]=0,l=n[2784]|0,s=1<<c,!(l&s)){n[2784]=l|s,n[f>>2]=Q,n[Q+24>>2]=f,n[Q+12>>2]=Q,n[Q+8>>2]=Q;break}for(s=m<<((c|0)==31?0:25-(c>>>1)|0),c=n[f>>2]|0;;){if((n[c+4>>2]&-8|0)==(m|0)){_e=216;break}if(f=c+16+(s>>>31<<2)|0,l=n[f>>2]|0,l)s=s<<1,c=l;else{_e=215;break}}if((_e|0)==215){n[f>>2]=Q,n[Q+24>>2]=c,n[Q+12>>2]=Q,n[Q+8>>2]=Q;break}else if((_e|0)==216){_e=c+8|0,qe=n[_e>>2]|0,n[qe+12>>2]=Q,n[_e>>2]=Q,n[Q+8>>2]=qe,n[Q+12>>2]=c,n[Q+24>>2]=0;break}}}else{qe=n[2787]|0,(qe|0)==0|m>>>0<qe>>>0&&(n[2787]=m),n[2895]=m,n[2896]=B,n[2898]=0,n[2792]=n[2901],n[2791]=-1,l=0;do qe=11172+(l<<1<<2)|0,n[qe+12>>2]=qe,n[qe+8>>2]=qe,l=l+1|0;while((l|0)!=32);qe=m+8|0,qe=qe&7|0?0-qe&7:0,_e=m+qe|0,qe=B+-40-qe|0,n[2789]=_e,n[2786]=qe,n[_e+4>>2]=qe|1,n[_e+qe+4>>2]=40,n[2790]=n[2905]}while(!1);if(l=n[2786]|0,l>>>0>j>>>0)return lt=l-j|0,n[2786]=lt,qe=n[2789]|0,_e=qe+j|0,n[2789]=_e,n[_e+4>>2]=lt|1,n[qe+4>>2]=j|3,qe=qe+8|0,C=Lt,qe|0}return n[(Nd()|0)>>2]=12,qe=0,C=Lt,qe|0}function Xv(s){s=s|0;var l=0,c=0,f=0,d=0,m=0,B=0,k=0,Q=0;if(s){c=s+-8|0,d=n[2787]|0,s=n[s+-4>>2]|0,l=s&-8,Q=c+l|0;do if(s&1)k=c,B=c;else{if(f=n[c>>2]|0,!(s&3)||(B=c+(0-f)|0,m=f+l|0,B>>>0<d>>>0))return;if((B|0)==(n[2788]|0)){if(s=Q+4|0,l=n[s>>2]|0,(l&3|0)!=3){k=B,l=m;break}n[2785]=m,n[s>>2]=l&-2,n[B+4>>2]=m|1,n[B+m>>2]=m;return}if(c=f>>>3,f>>>0<256)if(s=n[B+8>>2]|0,l=n[B+12>>2]|0,(l|0)==(s|0)){n[2783]=n[2783]&~(1<<c),k=B,l=m;break}else{n[s+12>>2]=l,n[l+8>>2]=s,k=B,l=m;break}d=n[B+24>>2]|0,s=n[B+12>>2]|0;do if((s|0)==(B|0)){if(c=B+16|0,l=c+4|0,s=n[l>>2]|0,!s)if(s=n[c>>2]|0,s)l=c;else{s=0;break}for(;;){if(c=s+20|0,f=n[c>>2]|0,f|0){s=f,l=c;continue}if(c=s+16|0,f=n[c>>2]|0,f)s=f,l=c;else break}n[l>>2]=0}else k=n[B+8>>2]|0,n[k+12>>2]=s,n[s+8>>2]=k;while(!1);if(d){if(l=n[B+28>>2]|0,c=11436+(l<<2)|0,(B|0)==(n[c>>2]|0)){if(n[c>>2]=s,!s){n[2784]=n[2784]&~(1<<l),k=B,l=m;break}}else if(n[d+16+(((n[d+16>>2]|0)!=(B|0)&1)<<2)>>2]=s,!s){k=B,l=m;break}n[s+24>>2]=d,l=B+16|0,c=n[l>>2]|0,c|0&&(n[s+16>>2]=c,n[c+24>>2]=s),l=n[l+4>>2]|0,l?(n[s+20>>2]=l,n[l+24>>2]=s,k=B,l=m):(k=B,l=m)}else k=B,l=m}while(!1);if(!(B>>>0>=Q>>>0)&&(s=Q+4|0,f=n[s>>2]|0,!!(f&1))){if(f&2)n[s>>2]=f&-2,n[k+4>>2]=l|1,n[B+l>>2]=l,d=l;else{if(s=n[2788]|0,(Q|0)==(n[2789]|0)){if(Q=(n[2786]|0)+l|0,n[2786]=Q,n[2789]=k,n[k+4>>2]=Q|1,(k|0)!=(s|0))return;n[2788]=0,n[2785]=0;return}if((Q|0)==(s|0)){Q=(n[2785]|0)+l|0,n[2785]=Q,n[2788]=B,n[k+4>>2]=Q|1,n[B+Q>>2]=Q;return}d=(f&-8)+l|0,c=f>>>3;do if(f>>>0<256)if(l=n[Q+8>>2]|0,s=n[Q+12>>2]|0,(s|0)==(l|0)){n[2783]=n[2783]&~(1<<c);break}else{n[l+12>>2]=s,n[s+8>>2]=l;break}else{m=n[Q+24>>2]|0,s=n[Q+12>>2]|0;do if((s|0)==(Q|0)){if(c=Q+16|0,l=c+4|0,s=n[l>>2]|0,!s)if(s=n[c>>2]|0,s)l=c;else{c=0;break}for(;;){if(c=s+20|0,f=n[c>>2]|0,f|0){s=f,l=c;continue}if(c=s+16|0,f=n[c>>2]|0,f)s=f,l=c;else break}n[l>>2]=0,c=s}else c=n[Q+8>>2]|0,n[c+12>>2]=s,n[s+8>>2]=c,c=s;while(!1);if(m|0){if(s=n[Q+28>>2]|0,l=11436+(s<<2)|0,(Q|0)==(n[l>>2]|0)){if(n[l>>2]=c,!c){n[2784]=n[2784]&~(1<<s);break}}else if(n[m+16+(((n[m+16>>2]|0)!=(Q|0)&1)<<2)>>2]=c,!c)break;n[c+24>>2]=m,s=Q+16|0,l=n[s>>2]|0,l|0&&(n[c+16>>2]=l,n[l+24>>2]=c),s=n[s+4>>2]|0,s|0&&(n[c+20>>2]=s,n[s+24>>2]=c)}}while(!1);if(n[k+4>>2]=d|1,n[B+d>>2]=d,(k|0)==(n[2788]|0)){n[2785]=d;return}}if(s=d>>>3,d>>>0<256){c=11172+(s<<1<<2)|0,l=n[2783]|0,s=1<<s,l&s?(l=c+8|0,s=n[l>>2]|0):(n[2783]=l|s,s=c,l=c+8|0),n[l>>2]=k,n[s+12>>2]=k,n[k+8>>2]=s,n[k+12>>2]=c;return}s=d>>>8,s?d>>>0>16777215?s=31:(B=(s+1048320|0)>>>16&8,Q=s<<B,m=(Q+520192|0)>>>16&4,Q=Q<<m,s=(Q+245760|0)>>>16&2,s=14-(m|B|s)+(Q<<s>>>15)|0,s=d>>>(s+7|0)&1|s<<1):s=0,f=11436+(s<<2)|0,n[k+28>>2]=s,n[k+20>>2]=0,n[k+16>>2]=0,l=n[2784]|0,c=1<<s;do if(l&c){for(l=d<<((s|0)==31?0:25-(s>>>1)|0),c=n[f>>2]|0;;){if((n[c+4>>2]&-8|0)==(d|0)){s=73;break}if(f=c+16+(l>>>31<<2)|0,s=n[f>>2]|0,s)l=l<<1,c=s;else{s=72;break}}if((s|0)==72){n[f>>2]=k,n[k+24>>2]=c,n[k+12>>2]=k,n[k+8>>2]=k;break}else if((s|0)==73){B=c+8|0,Q=n[B>>2]|0,n[Q+12>>2]=k,n[B>>2]=k,n[k+8>>2]=Q,n[k+12>>2]=c,n[k+24>>2]=0;break}}else n[2784]=l|c,n[f>>2]=k,n[k+24>>2]=f,n[k+12>>2]=k,n[k+8>>2]=k;while(!1);if(Q=(n[2791]|0)+-1|0,n[2791]=Q,!Q)s=11588;else return;for(;s=n[s>>2]|0,s;)s=s+8|0;n[2791]=-1}}}function SUe(){return 11628}function xUe(s){s=s|0;var l=0,c=0;return l=C,C=C+16|0,c=l,n[c>>2]=FUe(n[s+60>>2]|0)|0,s=Zv(gc(6,c|0)|0)|0,C=l,s|0}function Z9(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0,je=0;j=C,C=C+48|0,O=j+16|0,m=j,d=j+32|0,k=s+28|0,f=n[k>>2]|0,n[d>>2]=f,Q=s+20|0,f=(n[Q>>2]|0)-f|0,n[d+4>>2]=f,n[d+8>>2]=l,n[d+12>>2]=c,f=f+c|0,B=s+60|0,n[m>>2]=n[B>>2],n[m+4>>2]=d,n[m+8>>2]=2,m=Zv(Ni(146,m|0)|0)|0;e:do if((f|0)!=(m|0)){for(l=2;!((m|0)<0);)if(f=f-m|0,je=n[d+4>>2]|0,se=m>>>0>je>>>0,d=se?d+8|0:d,l=(se<<31>>31)+l|0,je=m-(se?je:0)|0,n[d>>2]=(n[d>>2]|0)+je,se=d+4|0,n[se>>2]=(n[se>>2]|0)-je,n[O>>2]=n[B>>2],n[O+4>>2]=d,n[O+8>>2]=l,m=Zv(Ni(146,O|0)|0)|0,(f|0)==(m|0)){M=3;break e}n[s+16>>2]=0,n[k>>2]=0,n[Q>>2]=0,n[s>>2]=n[s>>2]|32,(l|0)==2?c=0:c=c-(n[d+4>>2]|0)|0}else M=3;while(!1);return(M|0)==3&&(je=n[s+44>>2]|0,n[s+16>>2]=je+(n[s+48>>2]|0),n[k>>2]=je,n[Q>>2]=je),C=j,c|0}function kUe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0;return d=C,C=C+32|0,m=d,f=d+20|0,n[m>>2]=n[s+60>>2],n[m+4>>2]=0,n[m+8>>2]=l,n[m+12>>2]=f,n[m+16>>2]=c,(Zv(aa(140,m|0)|0)|0)<0?(n[f>>2]=-1,s=-1):s=n[f>>2]|0,C=d,s|0}function Zv(s){return s=s|0,s>>>0>4294963200&&(n[(Nd()|0)>>2]=0-s,s=-1),s|0}function Nd(){return(QUe()|0)+64|0}function QUe(){return gR()|0}function gR(){return 2084}function FUe(s){return s=s|0,s|0}function RUe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0;return d=C,C=C+32|0,f=d,n[s+36>>2]=1,!(n[s>>2]&64|0)&&(n[f>>2]=n[s+60>>2],n[f+4>>2]=21523,n[f+8>>2]=d+16,hu(54,f|0)|0)&&(o[s+75>>0]=-1),f=Z9(s,l,c)|0,C=d,f|0}function $9(s,l){s=s|0,l=l|0;var c=0,f=0;if(c=o[s>>0]|0,f=o[l>>0]|0,!(c<<24>>24)||c<<24>>24!=f<<24>>24)s=f;else{do s=s+1|0,l=l+1|0,c=o[s>>0]|0,f=o[l>>0]|0;while(!(!(c<<24>>24)||c<<24>>24!=f<<24>>24));s=f}return(c&255)-(s&255)|0}function TUe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0;e:do if(!c)s=0;else{for(;f=o[s>>0]|0,d=o[l>>0]|0,f<<24>>24==d<<24>>24;)if(c=c+-1|0,c)s=s+1|0,l=l+1|0;else{s=0;break e}s=(f&255)-(d&255)|0}while(!1);return s|0}function e7(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0,je=0,Oe=0,Qe=0;Qe=C,C=C+224|0,M=Qe+120|0,j=Qe+80|0,je=Qe,Oe=Qe+136|0,f=j,d=f+40|0;do n[f>>2]=0,f=f+4|0;while((f|0)<(d|0));return n[M>>2]=n[c>>2],(dR(0,l,M,je,j)|0)<0?c=-1:((n[s+76>>2]|0)>-1?se=NUe(s)|0:se=0,c=n[s>>2]|0,O=c&32,(o[s+74>>0]|0)<1&&(n[s>>2]=c&-33),f=s+48|0,n[f>>2]|0?c=dR(s,l,M,je,j)|0:(d=s+44|0,m=n[d>>2]|0,n[d>>2]=Oe,B=s+28|0,n[B>>2]=Oe,k=s+20|0,n[k>>2]=Oe,n[f>>2]=80,Q=s+16|0,n[Q>>2]=Oe+80,c=dR(s,l,M,je,j)|0,m&&(rD[n[s+36>>2]&7](s,0,0)|0,c=n[k>>2]|0?c:-1,n[d>>2]=m,n[f>>2]=0,n[Q>>2]=0,n[B>>2]=0,n[k>>2]=0)),f=n[s>>2]|0,n[s>>2]=f|O,se|0&&LUe(s),c=f&32|0?-1:c),C=Qe,c|0}function dR(s,l,c,f,d){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0;var m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0,je=0,Oe=0,Qe=0,$e=0,Je=0,lt=0,_e=0,qe=0,Lt=0,Or=0,cr=0,Xt=0,Pr=0,Tr=0,ar=0;ar=C,C=C+64|0,cr=ar+16|0,Xt=ar,Lt=ar+24|0,Pr=ar+8|0,Tr=ar+20|0,n[cr>>2]=l,lt=(s|0)!=0,_e=Lt+40|0,qe=_e,Lt=Lt+39|0,Or=Pr+4|0,B=0,m=0,M=0;e:for(;;){do if((m|0)>-1)if((B|0)>(2147483647-m|0)){n[(Nd()|0)>>2]=75,m=-1;break}else{m=B+m|0;break}while(!1);if(B=o[l>>0]|0,B<<24>>24)k=l;else{Je=87;break}t:for(;;){switch(B<<24>>24){case 37:{B=k,Je=9;break t}case 0:{B=k;break t}default:}$e=k+1|0,n[cr>>2]=$e,B=o[$e>>0]|0,k=$e}t:do if((Je|0)==9)for(;;){if(Je=0,(o[k+1>>0]|0)!=37)break t;if(B=B+1|0,k=k+2|0,n[cr>>2]=k,(o[k>>0]|0)==37)Je=9;else break}while(!1);if(B=B-l|0,lt&&as(s,l,B),B|0){l=k;continue}Q=k+1|0,B=(o[Q>>0]|0)+-48|0,B>>>0<10?($e=(o[k+2>>0]|0)==36,Qe=$e?B:-1,M=$e?1:M,Q=$e?k+3|0:Q):Qe=-1,n[cr>>2]=Q,B=o[Q>>0]|0,k=(B<<24>>24)+-32|0;t:do if(k>>>0<32)for(O=0,j=B;;){if(B=1<<k,!(B&75913)){B=j;break t}if(O=B|O,Q=Q+1|0,n[cr>>2]=Q,B=o[Q>>0]|0,k=(B<<24>>24)+-32|0,k>>>0>=32)break;j=B}else O=0;while(!1);if(B<<24>>24==42){if(k=Q+1|0,B=(o[k>>0]|0)+-48|0,B>>>0<10&&(o[Q+2>>0]|0)==36)n[d+(B<<2)>>2]=10,B=n[f+((o[k>>0]|0)+-48<<3)>>2]|0,M=1,Q=Q+3|0;else{if(M|0){m=-1;break}lt?(M=(n[c>>2]|0)+3&-4,B=n[M>>2]|0,n[c>>2]=M+4,M=0,Q=k):(B=0,M=0,Q=k)}n[cr>>2]=Q,$e=(B|0)<0,B=$e?0-B|0:B,O=$e?O|8192:O}else{if(B=t7(cr)|0,(B|0)<0){m=-1;break}Q=n[cr>>2]|0}do if((o[Q>>0]|0)==46){if((o[Q+1>>0]|0)!=42){n[cr>>2]=Q+1,k=t7(cr)|0,Q=n[cr>>2]|0;break}if(j=Q+2|0,k=(o[j>>0]|0)+-48|0,k>>>0<10&&(o[Q+3>>0]|0)==36){n[d+(k<<2)>>2]=10,k=n[f+((o[j>>0]|0)+-48<<3)>>2]|0,Q=Q+4|0,n[cr>>2]=Q;break}if(M|0){m=-1;break e}lt?($e=(n[c>>2]|0)+3&-4,k=n[$e>>2]|0,n[c>>2]=$e+4):k=0,n[cr>>2]=j,Q=j}else k=-1;while(!1);for(Oe=0;;){if(((o[Q>>0]|0)+-65|0)>>>0>57){m=-1;break e}if($e=Q+1|0,n[cr>>2]=$e,j=o[(o[Q>>0]|0)+-65+(5178+(Oe*58|0))>>0]|0,se=j&255,(se+-1|0)>>>0<8)Oe=se,Q=$e;else break}if(!(j<<24>>24)){m=-1;break}je=(Qe|0)>-1;do if(j<<24>>24==19)if(je){m=-1;break e}else Je=49;else{if(je){n[d+(Qe<<2)>>2]=se,je=f+(Qe<<3)|0,Qe=n[je+4>>2]|0,Je=Xt,n[Je>>2]=n[je>>2],n[Je+4>>2]=Qe,Je=49;break}if(!lt){m=0;break e}r7(Xt,se,c)}while(!1);if((Je|0)==49&&(Je=0,!lt)){B=0,l=$e;continue}Q=o[Q>>0]|0,Q=(Oe|0)!=0&(Q&15|0)==3?Q&-33:Q,je=O&-65537,Qe=O&8192|0?je:O;t:do switch(Q|0){case 110:switch((Oe&255)<<24>>24){case 0:{n[n[Xt>>2]>>2]=m,B=0,l=$e;continue e}case 1:{n[n[Xt>>2]>>2]=m,B=0,l=$e;continue e}case 2:{B=n[Xt>>2]|0,n[B>>2]=m,n[B+4>>2]=((m|0)<0)<<31>>31,B=0,l=$e;continue e}case 3:{a[n[Xt>>2]>>1]=m,B=0,l=$e;continue e}case 4:{o[n[Xt>>2]>>0]=m,B=0,l=$e;continue e}case 6:{n[n[Xt>>2]>>2]=m,B=0,l=$e;continue e}case 7:{B=n[Xt>>2]|0,n[B>>2]=m,n[B+4>>2]=((m|0)<0)<<31>>31,B=0,l=$e;continue e}default:{B=0,l=$e;continue e}}case 112:{Q=120,k=k>>>0>8?k:8,l=Qe|8,Je=61;break}case 88:case 120:{l=Qe,Je=61;break}case 111:{Q=Xt,l=n[Q>>2]|0,Q=n[Q+4>>2]|0,se=OUe(l,Q,_e)|0,je=qe-se|0,O=0,j=5642,k=(Qe&8|0)==0|(k|0)>(je|0)?k:je+1|0,je=Qe,Je=67;break}case 105:case 100:if(Q=Xt,l=n[Q>>2]|0,Q=n[Q+4>>2]|0,(Q|0)<0){l=$v(0,0,l|0,Q|0)|0,Q=we,O=Xt,n[O>>2]=l,n[O+4>>2]=Q,O=1,j=5642,Je=66;break t}else{O=(Qe&2049|0)!=0&1,j=Qe&2048|0?5643:Qe&1|0?5644:5642,Je=66;break t}case 117:{Q=Xt,O=0,j=5642,l=n[Q>>2]|0,Q=n[Q+4>>2]|0,Je=66;break}case 99:{o[Lt>>0]=n[Xt>>2],l=Lt,O=0,j=5642,se=_e,Q=1,k=je;break}case 109:{Q=UUe(n[(Nd()|0)>>2]|0)|0,Je=71;break}case 115:{Q=n[Xt>>2]|0,Q=Q|0?Q:5652,Je=71;break}case 67:{n[Pr>>2]=n[Xt>>2],n[Or>>2]=0,n[Xt>>2]=Pr,se=-1,Q=Pr,Je=75;break}case 83:{l=n[Xt>>2]|0,k?(se=k,Q=l,Je=75):(Ds(s,32,B,0,Qe),l=0,Je=84);break}case 65:case 71:case 70:case 69:case 97:case 103:case 102:case 101:{B=HUe(s,+E[Xt>>3],B,k,Qe,Q)|0,l=$e;continue e}default:O=0,j=5642,se=_e,Q=k,k=Qe}while(!1);t:do if((Je|0)==61)Qe=Xt,Oe=n[Qe>>2]|0,Qe=n[Qe+4>>2]|0,se=MUe(Oe,Qe,_e,Q&32)|0,j=(l&8|0)==0|(Oe|0)==0&(Qe|0)==0,O=j?0:2,j=j?5642:5642+(Q>>4)|0,je=l,l=Oe,Q=Qe,Je=67;else if((Je|0)==66)se=Ld(l,Q,_e)|0,je=Qe,Je=67;else if((Je|0)==71)Je=0,Qe=_Ue(Q,0,k)|0,Oe=(Qe|0)==0,l=Q,O=0,j=5642,se=Oe?Q+k|0:Qe,Q=Oe?k:Qe-Q|0,k=je;else if((Je|0)==75){for(Je=0,j=Q,l=0,k=0;O=n[j>>2]|0,!(!O||(k=n7(Tr,O)|0,(k|0)<0|k>>>0>(se-l|0)>>>0));)if(l=k+l|0,se>>>0>l>>>0)j=j+4|0;else break;if((k|0)<0){m=-1;break e}if(Ds(s,32,B,l,Qe),!l)l=0,Je=84;else for(O=0;;){if(k=n[Q>>2]|0,!k){Je=84;break t}if(k=n7(Tr,k)|0,O=k+O|0,(O|0)>(l|0)){Je=84;break t}if(as(s,Tr,k),O>>>0>=l>>>0){Je=84;break}else Q=Q+4|0}}while(!1);if((Je|0)==67)Je=0,Q=(l|0)!=0|(Q|0)!=0,Qe=(k|0)!=0|Q,Q=((Q^1)&1)+(qe-se)|0,l=Qe?se:_e,se=_e,Q=Qe?(k|0)>(Q|0)?k:Q:k,k=(k|0)>-1?je&-65537:je;else if((Je|0)==84){Je=0,Ds(s,32,B,l,Qe^8192),B=(B|0)>(l|0)?B:l,l=$e;continue}Oe=se-l|0,je=(Q|0)<(Oe|0)?Oe:Q,Qe=je+O|0,B=(B|0)<(Qe|0)?Qe:B,Ds(s,32,B,Qe,k),as(s,j,O),Ds(s,48,B,Qe,k^65536),Ds(s,48,je,Oe,0),as(s,l,Oe),Ds(s,32,B,Qe,k^8192),l=$e}e:do if((Je|0)==87&&!s)if(!M)m=0;else{for(m=1;l=n[d+(m<<2)>>2]|0,!!l;)if(r7(f+(m<<3)|0,l,c),m=m+1|0,(m|0)>=10){m=1;break e}for(;;){if(n[d+(m<<2)>>2]|0){m=-1;break e}if(m=m+1|0,(m|0)>=10){m=1;break}}}while(!1);return C=ar,m|0}function NUe(s){return s=s|0,0}function LUe(s){s=s|0}function as(s,l,c){s=s|0,l=l|0,c=c|0,n[s>>2]&32||JUe(l,c,s)|0}function t7(s){s=s|0;var l=0,c=0,f=0;if(c=n[s>>2]|0,f=(o[c>>0]|0)+-48|0,f>>>0<10){l=0;do l=f+(l*10|0)|0,c=c+1|0,n[s>>2]=c,f=(o[c>>0]|0)+-48|0;while(f>>>0<10)}else l=0;return l|0}function r7(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0;e:do if(l>>>0<=20)do switch(l|0){case 9:{f=(n[c>>2]|0)+3&-4,l=n[f>>2]|0,n[c>>2]=f+4,n[s>>2]=l;break e}case 10:{f=(n[c>>2]|0)+3&-4,l=n[f>>2]|0,n[c>>2]=f+4,f=s,n[f>>2]=l,n[f+4>>2]=((l|0)<0)<<31>>31;break e}case 11:{f=(n[c>>2]|0)+3&-4,l=n[f>>2]|0,n[c>>2]=f+4,f=s,n[f>>2]=l,n[f+4>>2]=0;break e}case 12:{f=(n[c>>2]|0)+7&-8,l=f,d=n[l>>2]|0,l=n[l+4>>2]|0,n[c>>2]=f+8,f=s,n[f>>2]=d,n[f+4>>2]=l;break e}case 13:{d=(n[c>>2]|0)+3&-4,f=n[d>>2]|0,n[c>>2]=d+4,f=(f&65535)<<16>>16,d=s,n[d>>2]=f,n[d+4>>2]=((f|0)<0)<<31>>31;break e}case 14:{d=(n[c>>2]|0)+3&-4,f=n[d>>2]|0,n[c>>2]=d+4,d=s,n[d>>2]=f&65535,n[d+4>>2]=0;break e}case 15:{d=(n[c>>2]|0)+3&-4,f=n[d>>2]|0,n[c>>2]=d+4,f=(f&255)<<24>>24,d=s,n[d>>2]=f,n[d+4>>2]=((f|0)<0)<<31>>31;break e}case 16:{d=(n[c>>2]|0)+3&-4,f=n[d>>2]|0,n[c>>2]=d+4,d=s,n[d>>2]=f&255,n[d+4>>2]=0;break e}case 17:{d=(n[c>>2]|0)+7&-8,m=+E[d>>3],n[c>>2]=d+8,E[s>>3]=m;break e}case 18:{d=(n[c>>2]|0)+7&-8,m=+E[d>>3],n[c>>2]=d+8,E[s>>3]=m;break e}default:break e}while(!1);while(!1)}function MUe(s,l,c,f){if(s=s|0,l=l|0,c=c|0,f=f|0,!((s|0)==0&(l|0)==0))do c=c+-1|0,o[c>>0]=u[5694+(s&15)>>0]|0|f,s=eD(s|0,l|0,4)|0,l=we;while(!((s|0)==0&(l|0)==0));return c|0}function OUe(s,l,c){if(s=s|0,l=l|0,c=c|0,!((s|0)==0&(l|0)==0))do c=c+-1|0,o[c>>0]=s&7|48,s=eD(s|0,l|0,3)|0,l=we;while(!((s|0)==0&(l|0)==0));return c|0}function Ld(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;if(l>>>0>0|(l|0)==0&s>>>0>4294967295){for(;f=CR(s|0,l|0,10,0)|0,c=c+-1|0,o[c>>0]=f&255|48,f=s,s=ER(s|0,l|0,10,0)|0,l>>>0>9|(l|0)==9&f>>>0>4294967295;)l=we;l=s}else l=s;if(l)for(;c=c+-1|0,o[c>>0]=(l>>>0)%10|0|48,!(l>>>0<10);)l=(l>>>0)/10|0;return c|0}function UUe(s){return s=s|0,WUe(s,n[(YUe()|0)+188>>2]|0)|0}function _Ue(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;m=l&255,f=(c|0)!=0;e:do if(f&(s&3|0)!=0)for(d=l&255;;){if((o[s>>0]|0)==d<<24>>24){B=6;break e}if(s=s+1|0,c=c+-1|0,f=(c|0)!=0,!(f&(s&3|0)!=0)){B=5;break}}else B=5;while(!1);(B|0)==5&&(f?B=6:c=0);e:do if((B|0)==6&&(d=l&255,(o[s>>0]|0)!=d<<24>>24)){f=Ue(m,16843009)|0;t:do if(c>>>0>3){for(;m=n[s>>2]^f,!((m&-2139062144^-2139062144)&m+-16843009|0);)if(s=s+4|0,c=c+-4|0,c>>>0<=3){B=11;break t}}else B=11;while(!1);if((B|0)==11&&!c){c=0;break}for(;;){if((o[s>>0]|0)==d<<24>>24)break e;if(s=s+1|0,c=c+-1|0,!c){c=0;break}}}while(!1);return(c|0?s:0)|0}function Ds(s,l,c,f,d){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0;var m=0,B=0;if(B=C,C=C+256|0,m=B,(c|0)>(f|0)&(d&73728|0)==0){if(d=c-f|0,Od(m|0,l|0,(d>>>0<256?d:256)|0)|0,d>>>0>255){l=c-f|0;do as(s,m,256),d=d+-256|0;while(d>>>0>255);d=l&255}as(s,m,d)}C=B}function n7(s,l){return s=s|0,l=l|0,s?s=jUe(s,l,0)|0:s=0,s|0}function HUe(s,l,c,f,d,m){s=s|0,l=+l,c=c|0,f=f|0,d=d|0,m=m|0;var B=0,k=0,Q=0,O=0,M=0,j=0,se=0,je=0,Oe=0,Qe=0,$e=0,Je=0,lt=0,_e=0,qe=0,Lt=0,Or=0,cr=0,Xt=0,Pr=0,Tr=0,ar=0,xn=0;xn=C,C=C+560|0,Q=xn+8|0,$e=xn,ar=xn+524|0,Tr=ar,O=xn+512|0,n[$e>>2]=0,Pr=O+12|0,i7(l)|0,(we|0)<0?(l=-l,cr=1,Or=5659):(cr=(d&2049|0)!=0&1,Or=d&2048|0?5662:d&1|0?5665:5660),i7(l)|0,Xt=we&2146435072;do if(Xt>>>0<2146435072|(Xt|0)==2146435072&!1){if(je=+qUe(l,$e)*2,B=je!=0,B&&(n[$e>>2]=(n[$e>>2]|0)+-1),lt=m|32,(lt|0)==97){Oe=m&32,se=Oe|0?Or+9|0:Or,j=cr|2,B=12-f|0;do if(f>>>0>11|(B|0)==0)l=je;else{l=8;do B=B+-1|0,l=l*16;while(B|0);if((o[se>>0]|0)==45){l=-(l+(-je-l));break}else{l=je+l-l;break}}while(!1);k=n[$e>>2]|0,B=(k|0)<0?0-k|0:k,B=Ld(B,((B|0)<0)<<31>>31,Pr)|0,(B|0)==(Pr|0)&&(B=O+11|0,o[B>>0]=48),o[B+-1>>0]=(k>>31&2)+43,M=B+-2|0,o[M>>0]=m+15,O=(f|0)<1,Q=(d&8|0)==0,B=ar;do Xt=~~l,k=B+1|0,o[B>>0]=u[5694+Xt>>0]|Oe,l=(l-+(Xt|0))*16,(k-Tr|0)==1&&!(Q&(O&l==0))?(o[k>>0]=46,B=B+2|0):B=k;while(l!=0);Xt=B-Tr|0,Tr=Pr-M|0,Pr=(f|0)!=0&(Xt+-2|0)<(f|0)?f+2|0:Xt,B=Tr+j+Pr|0,Ds(s,32,c,B,d),as(s,se,j),Ds(s,48,c,B,d^65536),as(s,ar,Xt),Ds(s,48,Pr-Xt|0,0,0),as(s,M,Tr),Ds(s,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(lt|0)==103,Je=(k|0)!=0,O=k-((lt|0)!=102?Q:0)+((Je&Qe)<<31>>31)|0,(O|0)<(((f-qe>>2)*9|0)+-9|0)){if(O=O+9216|0,Oe=Xt+4+(((O|0)/9|0)+-1024<<2)|0,O=((O|0)%9|0)+1|0,(O|0)<9){M=10;do M=M*10|0,O=O+1|0;while((O|0)!=9)}else M=10;if(j=n[Oe>>2]|0,se=(j>>>0)%(M>>>0)|0,O=(Oe+4|0)==(f|0),O&(se|0)==0)O=Oe;else if(je=((j>>>0)/(M>>>0)|0)&1|0?9007199254740994:9007199254740992,_e=(M|0)/2|0,l=se>>>0<_e>>>0?.5:O&(se|0)==(_e|0)?1:1.5,cr&&(_e=(o[Or>>0]|0)==45,l=_e?-l:l,je=_e?-je:je),O=j-se|0,n[Oe>>2]=O,je+l!=je){if(_e=O+M|0,n[Oe>>2]=_e,_e>>>0>999999999)for(Q=Oe;O=Q+-4|0,n[Q>>2]=0,O>>>0<B>>>0&&(B=B+-4|0,n[B>>2]=0),_e=(n[O>>2]|0)+1|0,n[O>>2]=_e,_e>>>0>999999999;)Q=O;else O=Oe;if(Q=(qe-B>>2)*9|0,j=n[B>>2]|0,j>>>0>=10){M=10;do M=M*10|0,Q=Q+1|0;while(j>>>0>=M>>>0)}}else O=Oe;O=O+4|0,O=f>>>0>O>>>0?O:f,_e=B}else O=f,_e=B;for(lt=O;;){if(lt>>>0<=_e>>>0){$e=0;break}if(B=lt+-4|0,!(n[B>>2]|0))lt=B;else{$e=1;break}}f=0-Q|0;do if(Qe)if(B=((Je^1)&1)+k|0,(B|0)>(Q|0)&(Q|0)>-5?(M=m+-1|0,k=B+-1-Q|0):(M=m+-2|0,k=B+-1|0),B=d&8,B)Oe=B;else{if($e&&(Lt=n[lt+-4>>2]|0,(Lt|0)!=0))if((Lt>>>0)%10|0)O=0;else{O=0,B=10;do B=B*10|0,O=O+1|0;while(!((Lt>>>0)%(B>>>0)|0|0))}else O=9;if(B=((lt-qe>>2)*9|0)+-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se>>0]=48,Q=se);do if((M|0)==(_e|0)){if(O=Q+1|0,as(s,Q,1),Oe&(k|0)<1){Q=O;break}as(s,5710,1),Q=O}else{if(Q>>>0<=ar>>>0)break;Od(ar|0,48,Q+j|0)|0;do Q=Q+-1|0;while(Q>>>0>ar>>>0)}while(!1);Tr=f-Q|0,as(s,Q,(k|0)>(Tr|0)?Tr:k),k=k-Tr|0,M=M+4|0}while(M>>>0<Qe>>>0&(k|0)>-1)}Ds(s,48,k+18|0,18,0),as(s,Je,Pr-Je|0)}Ds(s,32,c,B,d^8192)}else ar=(m&32|0)!=0,B=cr+3|0,Ds(s,32,c,B,d&-65537),as(s,Or,cr),as(s,l!=l|!1?ar?5686:5690:ar?5678:5682,3),Ds(s,32,c,B,d^8192);while(!1);return C=xn,((B|0)<(c|0)?c:B)|0}function i7(s){s=+s;var l=0;return E[v>>3]=s,l=n[v>>2]|0,we=n[v+4>>2]|0,l|0}function qUe(s,l){return s=+s,l=l|0,+ +s7(s,l)}function s7(s,l){s=+s,l=l|0;var c=0,f=0,d=0;switch(E[v>>3]=s,c=n[v>>2]|0,f=n[v+4>>2]|0,d=eD(c|0,f|0,52)|0,d&2047){case 0:{s!=0?(s=+s7(s*18446744073709552e3,l),c=(n[l>>2]|0)+-64|0):c=0,n[l>>2]=c;break}case 2047:break;default:n[l>>2]=(d&2047)+-1022,n[v>>2]=c,n[v+4>>2]=f&-2146435073|1071644672,s=+E[v>>3]}return+s}function jUe(s,l,c){s=s|0,l=l|0,c=c|0;do if(s){if(l>>>0<128){o[s>>0]=l,s=1;break}if(!(n[n[(GUe()|0)+188>>2]>>2]|0))if((l&-128|0)==57216){o[s>>0]=l,s=1;break}else{n[(Nd()|0)>>2]=84,s=-1;break}if(l>>>0<2048){o[s>>0]=l>>>6|192,o[s+1>>0]=l&63|128,s=2;break}if(l>>>0<55296|(l&-8192|0)==57344){o[s>>0]=l>>>12|224,o[s+1>>0]=l>>>6&63|128,o[s+2>>0]=l&63|128,s=3;break}if((l+-65536|0)>>>0<1048576){o[s>>0]=l>>>18|240,o[s+1>>0]=l>>>12&63|128,o[s+2>>0]=l>>>6&63|128,o[s+3>>0]=l&63|128,s=4;break}else{n[(Nd()|0)>>2]=84,s=-1;break}}else s=1;while(!1);return s|0}function GUe(){return gR()|0}function YUe(){return gR()|0}function WUe(s,l){s=s|0,l=l|0;var c=0,f=0;for(f=0;;){if((u[5712+f>>0]|0)==(s|0)){s=2;break}if(c=f+1|0,(c|0)==87){c=5800,f=87,s=5;break}else f=c}if((s|0)==2&&(f?(c=5800,s=5):c=5800),(s|0)==5)for(;;){do s=c,c=c+1|0;while(o[s>>0]|0);if(f=f+-1|0,f)s=5;else break}return KUe(c,n[l+20>>2]|0)|0}function KUe(s,l){return s=s|0,l=l|0,VUe(s,l)|0}function VUe(s,l){return s=s|0,l=l|0,l?l=zUe(n[l>>2]|0,n[l+4>>2]|0,s)|0:l=0,(l|0?l:s)|0}function zUe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0;se=(n[s>>2]|0)+1794895138|0,m=x0(n[s+8>>2]|0,se)|0,f=x0(n[s+12>>2]|0,se)|0,d=x0(n[s+16>>2]|0,se)|0;e:do if(m>>>0<l>>>2>>>0&&(j=l-(m<<2)|0,f>>>0<j>>>0&d>>>0<j>>>0)&&!((d|f)&3|0)){for(j=f>>>2,M=d>>>2,O=0;;){if(k=m>>>1,Q=O+k|0,B=Q<<1,d=B+j|0,f=x0(n[s+(d<<2)>>2]|0,se)|0,d=x0(n[s+(d+1<<2)>>2]|0,se)|0,!(d>>>0<l>>>0&f>>>0<(l-d|0)>>>0)){f=0;break e}if(o[s+(d+f)>>0]|0){f=0;break e}if(f=$9(c,s+d|0)|0,!f)break;if(f=(f|0)<0,(m|0)==1){f=0;break e}else O=f?O:Q,m=f?k:m-k|0}f=B+M|0,d=x0(n[s+(f<<2)>>2]|0,se)|0,f=x0(n[s+(f+1<<2)>>2]|0,se)|0,f>>>0<l>>>0&d>>>0<(l-f|0)>>>0?f=o[s+(f+d)>>0]|0?0:s+f|0:f=0}else f=0;while(!1);return f|0}function x0(s,l){s=s|0,l=l|0;var c=0;return c=p7(s|0)|0,(l|0?c:s)|0}function JUe(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0,k=0;f=c+16|0,d=n[f>>2]|0,d?m=5:XUe(c)|0?f=0:(d=n[f>>2]|0,m=5);e:do if((m|0)==5){if(k=c+20|0,B=n[k>>2]|0,f=B,(d-B|0)>>>0<l>>>0){f=rD[n[c+36>>2]&7](c,s,l)|0;break}t:do if((o[c+75>>0]|0)>-1){for(B=l;;){if(!B){m=0,d=s;break t}if(d=B+-1|0,(o[s+d>>0]|0)==10)break;B=d}if(f=rD[n[c+36>>2]&7](c,s,B)|0,f>>>0<B>>>0)break e;m=B,d=s+B|0,l=l-B|0,f=n[k>>2]|0}else m=0,d=s;while(!1);Dr(f|0,d|0,l|0)|0,n[k>>2]=(n[k>>2]|0)+l,f=m+l|0}while(!1);return f|0}function XUe(s){s=s|0;var l=0,c=0;return l=s+74|0,c=o[l>>0]|0,o[l>>0]=c+255|c,l=n[s>>2]|0,l&8?(n[s>>2]=l|32,s=-1):(n[s+8>>2]=0,n[s+4>>2]=0,c=n[s+44>>2]|0,n[s+28>>2]=c,n[s+20>>2]=c,n[s+16>>2]=c+(n[s+48>>2]|0),s=0),s|0}function _n(s,l){s=y(s),l=y(l);var c=0,f=0;c=o7(s)|0;do if((c&2147483647)>>>0<=2139095040){if(f=o7(l)|0,(f&2147483647)>>>0<=2139095040)if((f^c|0)<0){s=(c|0)<0?l:s;break}else{s=s<l?l:s;break}}else s=l;while(!1);return y(s)}function o7(s){return s=y(s),h[v>>2]=s,n[v>>2]|0|0}function k0(s,l){s=y(s),l=y(l);var c=0,f=0;c=a7(s)|0;do if((c&2147483647)>>>0<=2139095040){if(f=a7(l)|0,(f&2147483647)>>>0<=2139095040)if((f^c|0)<0){s=(c|0)<0?s:l;break}else{s=s<l?s:l;break}}else s=l;while(!1);return y(s)}function a7(s){return s=y(s),h[v>>2]=s,n[v>>2]|0|0}function mR(s,l){s=y(s),l=y(l);var c=0,f=0,d=0,m=0,B=0,k=0,Q=0,O=0;m=(h[v>>2]=s,n[v>>2]|0),k=(h[v>>2]=l,n[v>>2]|0),c=m>>>23&255,B=k>>>23&255,Q=m&-2147483648,d=k<<1;e:do if(d|0&&!((c|0)==255|((ZUe(l)|0)&2147483647)>>>0>2139095040)){if(f=m<<1,f>>>0<=d>>>0)return l=y(s*y(0)),y((f|0)==(d|0)?l:s);if(c)f=m&8388607|8388608;else{if(c=m<<9,(c|0)>-1){f=c,c=0;do c=c+-1|0,f=f<<1;while((f|0)>-1)}else c=0;f=m<<1-c}if(B)k=k&8388607|8388608;else{if(m=k<<9,(m|0)>-1){d=0;do d=d+-1|0,m=m<<1;while((m|0)>-1)}else d=0;B=d,k=k<<1-d}d=f-k|0,m=(d|0)>-1;t:do if((c|0)>(B|0)){for(;;){if(m)if(d)f=d;else break;if(f=f<<1,c=c+-1|0,d=f-k|0,m=(d|0)>-1,(c|0)<=(B|0))break t}l=y(s*y(0));break e}while(!1);if(m)if(d)f=d;else{l=y(s*y(0));break}if(f>>>0<8388608)do f=f<<1,c=c+-1|0;while(f>>>0<8388608);(c|0)>0?c=f+-8388608|c<<23:c=f>>>(1-c|0),l=(n[v>>2]=c|Q,y(h[v>>2]))}else O=3;while(!1);return(O|0)==3&&(l=y(s*l),l=y(l/l)),y(l)}function ZUe(s){return s=y(s),h[v>>2]=s,n[v>>2]|0|0}function $Ue(s,l){return s=s|0,l=l|0,e7(n[582]|0,s,l)|0}function Jr(s){s=s|0,Tt()}function Md(s){s=s|0}function e3e(s,l){return s=s|0,l=l|0,0}function t3e(s){return s=s|0,(l7(s+4|0)|0)==-1?(ef[n[(n[s>>2]|0)+8>>2]&127](s),s=1):s=0,s|0}function l7(s){s=s|0;var l=0;return l=n[s>>2]|0,n[s>>2]=l+-1,l+-1|0}function bp(s){s=s|0,t3e(s)|0&&r3e(s)}function r3e(s){s=s|0;var l=0;l=s+8|0,n[l>>2]|0&&(l7(l)|0)!=-1||ef[n[(n[s>>2]|0)+16>>2]&127](s)}function Kt(s){s=s|0;var l=0;for(l=s|0?s:1;s=Jv(l)|0,!(s|0);){if(s=i3e()|0,!s){s=0;break}B7[s&0]()}return s|0}function c7(s){return s=s|0,Kt(s)|0}function gt(s){s=s|0,Xv(s)}function n3e(s){s=s|0,(o[s+11>>0]|0)<0&&gt(n[s>>2]|0)}function i3e(){var s=0;return s=n[2923]|0,n[2923]=s+0,s|0}function s3e(){}function $v(s,l,c,f){return s=s|0,l=l|0,c=c|0,f=f|0,f=l-f-(c>>>0>s>>>0|0)>>>0,we=f,s-c>>>0|0|0}function yR(s,l,c,f){return s=s|0,l=l|0,c=c|0,f=f|0,c=s+c>>>0,we=l+f+(c>>>0<s>>>0|0)>>>0,c|0|0}function Od(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0,B=0;if(m=s+c|0,l=l&255,(c|0)>=67){for(;s&3;)o[s>>0]=l,s=s+1|0;for(f=m&-4|0,d=f-64|0,B=l|l<<8|l<<16|l<<24;(s|0)<=(d|0);)n[s>>2]=B,n[s+4>>2]=B,n[s+8>>2]=B,n[s+12>>2]=B,n[s+16>>2]=B,n[s+20>>2]=B,n[s+24>>2]=B,n[s+28>>2]=B,n[s+32>>2]=B,n[s+36>>2]=B,n[s+40>>2]=B,n[s+44>>2]=B,n[s+48>>2]=B,n[s+52>>2]=B,n[s+56>>2]=B,n[s+60>>2]=B,s=s+64|0;for(;(s|0)<(f|0);)n[s>>2]=B,s=s+4|0}for(;(s|0)<(m|0);)o[s>>0]=l,s=s+1|0;return m-c|0}function u7(s,l,c){return s=s|0,l=l|0,c=c|0,(c|0)<32?(we=l<<c|(s&(1<<c)-1<<32-c)>>>32-c,s<<c):(we=s<<c-32,0)}function eD(s,l,c){return s=s|0,l=l|0,c=c|0,(c|0)<32?(we=l>>>c,s>>>c|(l&(1<<c)-1)<<32-c):(we=0,l>>>c-32|0)}function Dr(s,l,c){s=s|0,l=l|0,c=c|0;var f=0,d=0,m=0;if((c|0)>=8192)return fc(s|0,l|0,c|0)|0;if(m=s|0,d=s+c|0,(s&3)==(l&3)){for(;s&3;){if(!c)return m|0;o[s>>0]=o[l>>0]|0,s=s+1|0,l=l+1|0,c=c-1|0}for(c=d&-4|0,f=c-64|0;(s|0)<=(f|0);)n[s>>2]=n[l>>2],n[s+4>>2]=n[l+4>>2],n[s+8>>2]=n[l+8>>2],n[s+12>>2]=n[l+12>>2],n[s+16>>2]=n[l+16>>2],n[s+20>>2]=n[l+20>>2],n[s+24>>2]=n[l+24>>2],n[s+28>>2]=n[l+28>>2],n[s+32>>2]=n[l+32>>2],n[s+36>>2]=n[l+36>>2],n[s+40>>2]=n[l+40>>2],n[s+44>>2]=n[l+44>>2],n[s+48>>2]=n[l+48>>2],n[s+52>>2]=n[l+52>>2],n[s+56>>2]=n[l+56>>2],n[s+60>>2]=n[l+60>>2],s=s+64|0,l=l+64|0;for(;(s|0)<(c|0);)n[s>>2]=n[l>>2],s=s+4|0,l=l+4|0}else for(c=d-4|0;(s|0)<(c|0);)o[s>>0]=o[l>>0]|0,o[s+1>>0]=o[l+1>>0]|0,o[s+2>>0]=o[l+2>>0]|0,o[s+3>>0]=o[l+3>>0]|0,s=s+4|0,l=l+4|0;for(;(s|0)<(d|0);)o[s>>0]=o[l>>0]|0,s=s+1|0,l=l+1|0;return m|0}function A7(s){s=s|0;var l=0;return l=o[L+(s&255)>>0]|0,(l|0)<8?l|0:(l=o[L+(s>>8&255)>>0]|0,(l|0)<8?l+8|0:(l=o[L+(s>>16&255)>>0]|0,(l|0)<8?l+16|0:(o[L+(s>>>24)>>0]|0)+24|0))}function f7(s,l,c,f,d){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0;var m=0,B=0,k=0,Q=0,O=0,M=0,j=0,se=0,je=0,Oe=0;if(M=s,Q=l,O=Q,B=c,se=f,k=se,!O)return m=(d|0)!=0,k?m?(n[d>>2]=s|0,n[d+4>>2]=l&0,se=0,d=0,we=se,d|0):(se=0,d=0,we=se,d|0):(m&&(n[d>>2]=(M>>>0)%(B>>>0),n[d+4>>2]=0),se=0,d=(M>>>0)/(B>>>0)>>>0,we=se,d|0);m=(k|0)==0;do if(B){if(!m){if(m=(b(k|0)|0)-(b(O|0)|0)|0,m>>>0<=31){j=m+1|0,k=31-m|0,l=m-31>>31,B=j,s=M>>>(j>>>0)&l|O<<k,l=O>>>(j>>>0)&l,m=0,k=M<<k;break}return d?(n[d>>2]=s|0,n[d+4>>2]=Q|l&0,se=0,d=0,we=se,d|0):(se=0,d=0,we=se,d|0)}if(m=B-1|0,m&B|0){k=(b(B|0)|0)+33-(b(O|0)|0)|0,Oe=64-k|0,j=32-k|0,Q=j>>31,je=k-32|0,l=je>>31,B=k,s=j-1>>31&O>>>(je>>>0)|(O<<j|M>>>(k>>>0))&l,l=l&O>>>(k>>>0),m=M<<Oe&Q,k=(O<<Oe|M>>>(je>>>0))&Q|M<<j&k-33>>31;break}return d|0&&(n[d>>2]=m&M,n[d+4>>2]=0),(B|0)==1?(je=Q|l&0,Oe=s|0|0,we=je,Oe|0):(Oe=A7(B|0)|0,je=O>>>(Oe>>>0)|0,Oe=O<<32-Oe|M>>>(Oe>>>0)|0,we=je,Oe|0)}else{if(m)return d|0&&(n[d>>2]=(O>>>0)%(B>>>0),n[d+4>>2]=0),je=0,Oe=(O>>>0)/(B>>>0)>>>0,we=je,Oe|0;if(!M)return d|0&&(n[d>>2]=0,n[d+4>>2]=(O>>>0)%(k>>>0)),je=0,Oe=(O>>>0)/(k>>>0)>>>0,we=je,Oe|0;if(m=k-1|0,!(m&k))return d|0&&(n[d>>2]=s|0,n[d+4>>2]=m&O|l&0),je=0,Oe=O>>>((A7(k|0)|0)>>>0),we=je,Oe|0;if(m=(b(k|0)|0)-(b(O|0)|0)|0,m>>>0<=30){l=m+1|0,k=31-m|0,B=l,s=O<<k|M>>>(l>>>0),l=O>>>(l>>>0),m=0,k=M<<k;break}return d?(n[d>>2]=s|0,n[d+4>>2]=Q|l&0,je=0,Oe=0,we=je,Oe|0):(je=0,Oe=0,we=je,Oe|0)}while(!1);if(!B)O=k,Q=0,k=0;else{j=c|0|0,M=se|f&0,O=yR(j|0,M|0,-1,-1)|0,c=we,Q=k,k=0;do f=Q,Q=m>>>31|Q<<1,m=k|m<<1,f=s<<1|f>>>31|0,se=s>>>31|l<<1|0,$v(O|0,c|0,f|0,se|0)|0,Oe=we,je=Oe>>31|((Oe|0)<0?-1:0)<<1,k=je&1,s=$v(f|0,se|0,je&j|0,(((Oe|0)<0?-1:0)>>31|((Oe|0)<0?-1:0)<<1)&M|0)|0,l=we,B=B-1|0;while(B|0);O=Q,Q=0}return B=0,d|0&&(n[d>>2]=s,n[d+4>>2]=l),je=(m|0)>>>31|(O|B)<<1|(B<<1|m>>>31)&0|Q,Oe=(m<<1|0)&-2|k,we=je,Oe|0}function ER(s,l,c,f){return s=s|0,l=l|0,c=c|0,f=f|0,f7(s,l,c,f,0)|0}function Sp(s){s=s|0;var l=0,c=0;return c=s+15&-16|0,l=n[I>>2]|0,s=l+c|0,(c|0)>0&(s|0)<(l|0)|(s|0)<0?(ie()|0,vA(12),-1):(n[I>>2]=s,(s|0)>($()|0)&&!(X()|0)?(n[I>>2]=l,vA(12),-1):l|0)}function ww(s,l,c){s=s|0,l=l|0,c=c|0;var f=0;if((l|0)<(s|0)&(s|0)<(l+c|0)){for(f=s,l=l+c|0,s=s+c|0;(c|0)>0;)s=s-1|0,l=l-1|0,c=c-1|0,o[s>>0]=o[l>>0]|0;s=f}else Dr(s,l,c)|0;return s|0}function CR(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0;var d=0,m=0;return m=C,C=C+16|0,d=m|0,f7(s,l,c,f,d)|0,C=m,we=n[d+4>>2]|0,n[d>>2]|0|0}function p7(s){return s=s|0,(s&255)<<24|(s>>8&255)<<16|(s>>16&255)<<8|s>>>24|0}function o3e(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0,h7[s&1](l|0,c|0,f|0,d|0,m|0)}function a3e(s,l,c){s=s|0,l=l|0,c=y(c),g7[s&1](l|0,y(c))}function l3e(s,l,c){s=s|0,l=l|0,c=+c,d7[s&31](l|0,+c)}function c3e(s,l,c,f){return s=s|0,l=l|0,c=y(c),f=y(f),y(m7[s&0](l|0,y(c),y(f)))}function u3e(s,l){s=s|0,l=l|0,ef[s&127](l|0)}function A3e(s,l,c){s=s|0,l=l|0,c=c|0,tf[s&31](l|0,c|0)}function f3e(s,l){return s=s|0,l=l|0,F0[s&31](l|0)|0}function p3e(s,l,c,f,d){s=s|0,l=l|0,c=+c,f=+f,d=d|0,y7[s&1](l|0,+c,+f,d|0)}function h3e(s,l,c,f){s=s|0,l=l|0,c=+c,f=+f,V3e[s&1](l|0,+c,+f)}function g3e(s,l,c,f){return s=s|0,l=l|0,c=c|0,f=f|0,rD[s&7](l|0,c|0,f|0)|0}function d3e(s,l,c,f){return s=s|0,l=l|0,c=c|0,f=f|0,+z3e[s&1](l|0,c|0,f|0)}function m3e(s,l){return s=s|0,l=l|0,+E7[s&15](l|0)}function y3e(s,l,c){return s=s|0,l=l|0,c=+c,J3e[s&1](l|0,+c)|0}function E3e(s,l,c){return s=s|0,l=l|0,c=c|0,IR[s&15](l|0,c|0)|0}function C3e(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=+f,d=+d,m=m|0,X3e[s&1](l|0,c|0,+f,+d,m|0)}function w3e(s,l,c,f,d,m,B){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0,B=B|0,Z3e[s&1](l|0,c|0,f|0,d|0,m|0,B|0)}function I3e(s,l,c){return s=s|0,l=l|0,c=c|0,+C7[s&7](l|0,c|0)}function B3e(s){return s=s|0,nD[s&7]()|0}function v3e(s,l,c,f,d,m){return s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0,w7[s&1](l|0,c|0,f|0,d|0,m|0)|0}function D3e(s,l,c,f,d){s=s|0,l=l|0,c=c|0,f=f|0,d=+d,$3e[s&1](l|0,c|0,f|0,+d)}function P3e(s,l,c,f,d,m,B){s=s|0,l=l|0,c=c|0,f=y(f),d=d|0,m=y(m),B=B|0,I7[s&1](l|0,c|0,y(f),d|0,y(m),B|0)}function b3e(s,l,c,f){s=s|0,l=l|0,c=c|0,f=f|0,vw[s&15](l|0,c|0,f|0)}function S3e(s){s=s|0,B7[s&0]()}function x3e(s,l,c,f){s=s|0,l=l|0,c=c|0,f=+f,v7[s&15](l|0,c|0,+f)}function k3e(s,l,c){return s=s|0,l=+l,c=+c,e_e[s&1](+l,+c)|0}function Q3e(s,l,c,f,d){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,BR[s&15](l|0,c|0,f|0,d|0)}function F3e(s,l,c,f,d){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,F(0)}function R3e(s,l){s=s|0,l=y(l),F(1)}function Ea(s,l){s=s|0,l=+l,F(2)}function T3e(s,l,c){return s=s|0,l=y(l),c=y(c),F(3),Xe}function Er(s){s=s|0,F(4)}function Iw(s,l){s=s|0,l=l|0,F(5)}function Xa(s){return s=s|0,F(6),0}function N3e(s,l,c,f){s=s|0,l=+l,c=+c,f=f|0,F(7)}function L3e(s,l,c){s=s|0,l=+l,c=+c,F(8)}function M3e(s,l,c){return s=s|0,l=l|0,c=c|0,F(9),0}function O3e(s,l,c){return s=s|0,l=l|0,c=c|0,F(10),0}function Q0(s){return s=s|0,F(11),0}function U3e(s,l){return s=s|0,l=+l,F(12),0}function Bw(s,l){return s=s|0,l=l|0,F(13),0}function _3e(s,l,c,f,d){s=s|0,l=l|0,c=+c,f=+f,d=d|0,F(14)}function H3e(s,l,c,f,d,m){s=s|0,l=l|0,c=c|0,f=f|0,d=d|0,m=m|0,F(15)}function wR(s,l){return s=s|0,l=l|0,F(16),0}function q3e(){return F(17),0}function j3e(s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e,eF,D,fe,De,vt,wt,St,_r,di,po,nve,ive,wve,iFe,JRe,YNe,VMe,Va,Xa,Xa,Xa,Xa,Xa,Xa,Xa,Xa,Xa,Xa,Xa,Xa],y7=[N3e,Ive],V3e=[L3e,fNe],rD=[M3e,Z9,kUe,RUe,WPe,Bxe,LFe,ZOe],z3e=[O3e,mSe],E7=[Q0,Yo,nt,Sn,Bve,vve,Dve,Pve,bve,Sve,Q0,Q0,Q0,Q0,Q0,Q0],J3e=[U3e,CTe],IR=[Bw,e3e,sve,mDe,pPe,lbe,Bbe,zSe,Uxe,jQe,xv,MOe,Bw,Bw,Bw,Bw],X3e=[_3e,zDe],Z3e=[H3e,C4e],C7=[wR,ai,kve,Qve,Fve,RSe,wR,wR],nD=[q3e,Rve,cw,ma,kTe,JTe,xNe,z4e],w7=[j3e,nw],$3e=[G3e,mke],I7=[Y3e,ave],vw=[tD,T,os,tn,ho,xPe,Obe,Rke,zke,bd,fMe,IOe,N4e,tD,tD,tD],B7=[W3e],v7=[Ud,Fv,Rv,Tv,GA,_v,fF,P,tke,ZFe,dTe,Ud,Ud,Ud,Ud,Ud],e_e=[K3e,dNe],BR=[_d,tSe,fFe,mRe,sTe,LTe,rNe,LNe,ALe,eOe,oUe,_d,_d,_d,_d,_d];return{_llvm_bswap_i32:p7,dynCall_idd:k3e,dynCall_i:B3e,_i64Subtract:$v,___udivdi3:ER,dynCall_vif:a3e,setThrew:du,dynCall_viii:b3e,_bitshift64Lshr:eD,_bitshift64Shl:u7,dynCall_vi:u3e,dynCall_viiddi:C3e,dynCall_diii:d3e,dynCall_iii:E3e,_memset:Od,_sbrk:Sp,_memcpy:Dr,__GLOBAL__sub_I_Yoga_cpp:Pd,dynCall_vii:A3e,___uremdi3:CR,dynCall_vid:l3e,stackAlloc:lo,_nbind_init:mUe,getTempRet0:qa,dynCall_di:m3e,dynCall_iid:y3e,setTempRet0:SA,_i64Add:yR,dynCall_fiff:c3e,dynCall_iiii:g3e,_emscripten_get_global_libc:SUe,dynCall_viid:x3e,dynCall_viiid:D3e,dynCall_viififi:P3e,dynCall_ii:f3e,__GLOBAL__sub_I_Binding_cc:RMe,dynCall_viiii:Q3e,dynCall_iiiiii:v3e,stackSave:dc,dynCall_viiiii:o3e,__GLOBAL__sub_I_nbind_cc:Tve,dynCall_vidd:h3e,_free:Xv,runPostSets:s3e,dynCall_viiiiii:w3e,establishStackSpace:qi,_memmove:ww,stackRestore:gu,_malloc:Jv,__GLOBAL__sub_I_common_cc:$Ne,dynCall_viddi:p3e,dynCall_dii:I3e,dynCall_v:S3e}}(Module.asmGlobalArg,Module.asmLibraryArg,buffer),_llvm_bswap_i32=Module._llvm_bswap_i32=asm._llvm_bswap_i32,getTempRet0=Module.getTempRet0=asm.getTempRet0,___udivdi3=Module.___udivdi3=asm.___udivdi3,setThrew=Module.setThrew=asm.setThrew,_bitshift64Lshr=Module._bitshift64Lshr=asm._bitshift64Lshr,_bitshift64Shl=Module._bitshift64Shl=asm._bitshift64Shl,_memset=Module._memset=asm._memset,_sbrk=Module._sbrk=asm._sbrk,_memcpy=Module._memcpy=asm._memcpy,stackAlloc=Module.stackAlloc=asm.stackAlloc,___uremdi3=Module.___uremdi3=asm.___uremdi3,_nbind_init=Module._nbind_init=asm._nbind_init,_i64Subtract=Module._i64Subtract=asm._i64Subtract,setTempRet0=Module.setTempRet0=asm.setTempRet0,_i64Add=Module._i64Add=asm._i64Add,_emscripten_get_global_libc=Module._emscripten_get_global_libc=asm._emscripten_get_global_libc,__GLOBAL__sub_I_Yoga_cpp=Module.__GLOBAL__sub_I_Yoga_cpp=asm.__GLOBAL__sub_I_Yoga_cpp,__GLOBAL__sub_I_Binding_cc=Module.__GLOBAL__sub_I_Binding_cc=asm.__GLOBAL__sub_I_Binding_cc,stackSave=Module.stackSave=asm.stackSave,__GLOBAL__sub_I_nbind_cc=Module.__GLOBAL__sub_I_nbind_cc=asm.__GLOBAL__sub_I_nbind_cc,_free=Module._free=asm._free,runPostSets=Module.runPostSets=asm.runPostSets,establishStackSpace=Module.establishStackSpace=asm.establishStackSpace,_memmove=Module._memmove=asm._memmove,stackRestore=Module.stackRestore=asm.stackRestore,_malloc=Module._malloc=asm._malloc,__GLOBAL__sub_I_common_cc=Module.__GLOBAL__sub_I_common_cc=asm.__GLOBAL__sub_I_common_cc,dynCall_viiiii=Module.dynCall_viiiii=asm.dynCall_viiiii,dynCall_vif=Module.dynCall_vif=asm.dynCall_vif,dynCall_vid=Module.dynCall_vid=asm.dynCall_vid,dynCall_fiff=Module.dynCall_fiff=asm.dynCall_fiff,dynCall_vi=Module.dynCall_vi=asm.dynCall_vi,dynCall_vii=Module.dynCall_vii=asm.dynCall_vii,dynCall_ii=Module.dynCall_ii=asm.dynCall_ii,dynCall_viddi=Module.dynCall_viddi=asm.dynCall_viddi,dynCall_vidd=Module.dynCall_vidd=asm.dynCall_vidd,dynCall_iiii=Module.dynCall_iiii=asm.dynCall_iiii,dynCall_diii=Module.dynCall_diii=asm.dynCall_diii,dynCall_di=Module.dynCall_di=asm.dynCall_di,dynCall_iid=Module.dynCall_iid=asm.dynCall_iid,dynCall_iii=Module.dynCall_iii=asm.dynCall_iii,dynCall_viiddi=Module.dynCall_viiddi=asm.dynCall_viiddi,dynCall_viiiiii=Module.dynCall_viiiiii=asm.dynCall_viiiiii,dynCall_dii=Module.dynCall_dii=asm.dynCall_dii,dynCall_i=Module.dynCall_i=asm.dynCall_i,dynCall_iiiiii=Module.dynCall_iiiiii=asm.dynCall_iiiiii,dynCall_viiid=Module.dynCall_viiid=asm.dynCall_viiid,dynCall_viififi=Module.dynCall_viififi=asm.dynCall_viififi,dynCall_viii=Module.dynCall_viii=asm.dynCall_viii,dynCall_v=Module.dynCall_v=asm.dynCall_v,dynCall_viid=Module.dynCall_viid=asm.dynCall_viid,dynCall_idd=Module.dynCall_idd=asm.dynCall_idd,dynCall_viiii=Module.dynCall_viiii=asm.dynCall_viiii;Runtime.stackAlloc=Module.stackAlloc,Runtime.stackSave=Module.stackSave,Runtime.stackRestore=Module.stackRestore,Runtime.establishStackSpace=Module.establishStackSpace,Runtime.setTempRet0=Module.setTempRet0,Runtime.getTempRet0=Module.getTempRet0,Module.asm=asm;function ExitStatus(t){this.name=\"ExitStatus\",this.message=\"Program terminated with exit(\"+t+\")\",this.status=t}ExitStatus.prototype=new Error,ExitStatus.prototype.constructor=ExitStatus;var initialStackTop,preloadStartTime=null,calledMain=!1;dependenciesFulfilled=function t(){Module.calledRun||run(),Module.calledRun||(dependenciesFulfilled=t)},Module.callMain=Module.callMain=function t(e){e=e||[],ensureInitRuntime();var r=e.length+1;function o(){for(var p=0;p<3;p++)a.push(0)}var a=[allocate(intArrayFromString(Module.thisProgram),\"i8\",ALLOC_NORMAL)];o();for(var n=0;n<r-1;n=n+1)a.push(allocate(intArrayFromString(e[n]),\"i8\",ALLOC_NORMAL)),o();a.push(0),a=allocate(a,\"i32\",ALLOC_NORMAL);try{var u=Module._main(r,a,0);exit(u,!0)}catch(p){if(p instanceof ExitStatus)return;if(p==\"SimulateInfiniteLoop\"){Module.noExitRuntime=!0;return}else{var A=p;p&&typeof p==\"object\"&&p.stack&&(A=[p,p.stack]),Module.printErr(\"exception thrown: \"+A),Module.quit(1,p)}}finally{calledMain=!0}};function run(t){if(t=t||Module.arguments,preloadStartTime===null&&(preloadStartTime=Date.now()),runDependencies>0||(preRun(),runDependencies>0)||Module.calledRun)return;function e(){Module.calledRun||(Module.calledRun=!0,!ABORT&&(ensureInitRuntime(),preMain(),Module.onRuntimeInitialized&&Module.onRuntimeInitialized(),Module._main&&shouldRunNow&&Module.callMain(t),postRun()))}Module.setStatus?(Module.setStatus(\"Running...\"),setTimeout(function(){setTimeout(function(){Module.setStatus(\"\")},1),e()},1)):e()}Module.run=Module.run=run;function exit(t,e){e&&Module.noExitRuntime||(Module.noExitRuntime||(ABORT=!0,EXITSTATUS=t,STACKTOP=initialStackTop,exitRuntime(),Module.onExit&&Module.onExit(t)),ENVIRONMENT_IS_NODE&&process.exit(t),Module.quit(t,new ExitStatus(t)))}Module.exit=Module.exit=exit;var abortDecorators=[];function abort(t){Module.onAbort&&Module.onAbort(t),t!==void 0?(Module.print(t),Module.printErr(t),t=JSON.stringify(t)):t=\"\",ABORT=!0,EXITSTATUS=1;var e=`\nIf this abort() is unexpected, build with -s ASSERTIONS=1 which can give more information.`,r=\"abort(\"+t+\") at \"+stackTrace()+e;throw abortDecorators&&abortDecorators.forEach(function(o){r=o(r,t)}),r}if(Module.abort=Module.abort=abort,Module.preInit)for(typeof Module.preInit==\"function\"&&(Module.preInit=[Module.preInit]);Module.preInit.length>0;)Module.preInit.pop()();var shouldRunNow=!0;Module.noInitialRun&&(shouldRunNow=!1),run()})});var Jg=_((bKt,_Ee)=>{\"use strict\";var Jyt=OEe(),Xyt=UEe(),v6=!1,D6=null;Xyt({},function(t,e){if(!v6){if(v6=!0,t)throw t;D6=e}});if(!v6)throw new Error(\"Failed to load the yoga module - it needed to be loaded synchronously, but didn't\");_Ee.exports=Jyt(D6.bind,D6.lib)});var b6=_((SKt,P6)=>{\"use strict\";var HEe=t=>Number.isNaN(t)?!1:t>=4352&&(t<=4447||t===9001||t===9002||11904<=t&&t<=12871&&t!==12351||12880<=t&&t<=19903||19968<=t&&t<=42182||43360<=t&&t<=43388||44032<=t&&t<=55203||63744<=t&&t<=64255||65040<=t&&t<=65049||65072<=t&&t<=65131||65281<=t&&t<=65376||65504<=t&&t<=65510||110592<=t&&t<=110593||127488<=t&&t<=127569||131072<=t&&t<=262141);P6.exports=HEe;P6.exports.default=HEe});var jEe=_((xKt,qEe)=>{\"use strict\";qEe.exports=function(){return/\\uD83C\\uDFF4\\uDB40\\uDC67\\uDB40\\uDC62(?:\\uDB40\\uDC65\\uDB40\\uDC6E\\uDB40\\uDC67|\\uDB40\\uDC73\\uDB40\\uDC63\\uDB40\\uDC74|\\uDB40\\uDC77\\uDB40\\uDC6C\\uDB40\\uDC73)\\uDB40\\uDC7F|\\uD83D\\uDC68(?:\\uD83C\\uDFFC\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68\\uD83C\\uDFFB|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFF\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFE])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFE\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFD])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFD\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB\\uDFFC])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D)?\\uD83D\\uDC68|(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67])|(?:\\uD83D[\\uDC68\\uDC69])\\u200D(?:\\uD83D[\\uDC66\\uDC67])|[\\u2695\\u2696\\u2708]\\uFE0F|\\uD83D[\\uDC66\\uDC67]|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|(?:\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708])\\uFE0F|\\uD83C\\uDFFB\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C[\\uDFFB-\\uDFFF])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFB\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFC\\u200D\\uD83E\\uDD1D\\u200D\\uD83D\\uDC69)\\uD83C\\uDFFB|\\uD83E\\uDDD1(?:\\uD83C\\uDFFF\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1(?:\\uD83C[\\uDFFB-\\uDFFF])|\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1)|(?:\\uD83E\\uDDD1\\uD83C\\uDFFE\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFF\\u200D\\uD83E\\uDD1D\\u200D(?:\\uD83D[\\uDC68\\uDC69]))(?:\\uD83C[\\uDFFB-\\uDFFE])|(?:\\uD83E\\uDDD1\\uD83C\\uDFFC\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFD\\u200D\\uD83E\\uDD1D\\u200D\\uD83D\\uDC69)(?:\\uD83C[\\uDFFB\\uDFFC])|\\uD83D\\uDC69(?:\\uD83C\\uDFFE\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB-\\uDFFD\\uDFFF])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFC\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB\\uDFFD-\\uDFFF])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFB\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFC-\\uDFFF])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFD\\u200D(?:\\uD83E\\uDD1D\\u200D\\uD83D\\uDC68(?:\\uD83C[\\uDFFB\\uDFFC\\uDFFE\\uDFFF])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\u200D(?:\\u2764\\uFE0F\\u200D(?:\\uD83D\\uDC8B\\u200D(?:\\uD83D[\\uDC68\\uDC69])|\\uD83D[\\uDC68\\uDC69])|\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD])|\\uD83C\\uDFFF\\u200D(?:\\uD83C[\\uDF3E\\uDF73\\uDF93\\uDFA4\\uDFA8\\uDFEB\\uDFED]|\\uD83D[\\uDCBB\\uDCBC\\uDD27\\uDD2C\\uDE80\\uDE92]|\\uD83E[\\uDDAF-\\uDDB3\\uDDBC\\uDDBD]))|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67]))|(?:\\uD83E\\uDDD1\\uD83C\\uDFFD\\u200D\\uD83E\\uDD1D\\u200D\\uD83E\\uDDD1|\\uD83D\\uDC69\\uD83C\\uDFFE\\u200D\\uD83E\\uDD1D\\u200D\\uD83D\\uDC69)(?:\\uD83C[\\uDFFB-\\uDFFD])|\\uD83D\\uDC69\\u200D\\uD83D\\uDC66\\u200D\\uD83D\\uDC66|\\uD83D\\uDC69\\u200D\\uD83D\\uDC69\\u200D(?:\\uD83D[\\uDC66\\uDC67])|(?:\\uD83D\\uDC41\\uFE0F\\u200D\\uD83D\\uDDE8|\\uD83D\\uDC69(?:\\uD83C\\uDFFF\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFE\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFC\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFB\\u200D[\\u2695\\u2696\\u2708]|\\uD83C\\uDFFD\\u200D[\\u2695\\u2696\\u2708]|\\u200D[\\u2695\\u2696\\u2708])|(?:(?:\\u26F9|\\uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)\\uFE0F|\\uD83D\\uDC6F|\\uD83E[\\uDD3C\\uDDDE\\uDDDF])\\u200D[\\u2640\\u2642]|(?:\\u26F9|\\uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D[\\u2640\\u2642]|(?:\\uD83C[\\uDFC3\\uDFC4\\uDFCA]|\\uD83D[\\uDC6E\\uDC71\\uDC73\\uDC77\\uDC81\\uDC82\\uDC86\\uDC87\\uDE45-\\uDE47\\uDE4B\\uDE4D\\uDE4E\\uDEA3\\uDEB4-\\uDEB6]|\\uD83E[\\uDD26\\uDD37-\\uDD39\\uDD3D\\uDD3E\\uDDB8\\uDDB9\\uDDCD-\\uDDCF\\uDDD6-\\uDDDD])(?:(?:\\uD83C[\\uDFFB-\\uDFFF])\\u200D[\\u2640\\u2642]|\\u200D[\\u2640\\u2642])|\\uD83C\\uDFF4\\u200D\\u2620)\\uFE0F|\\uD83D\\uDC69\\u200D\\uD83D\\uDC67\\u200D(?:\\uD83D[\\uDC66\\uDC67])|\\uD83C\\uDFF3\\uFE0F\\u200D\\uD83C\\uDF08|\\uD83D\\uDC15\\u200D\\uD83E\\uDDBA|\\uD83D\\uDC69\\u200D\\uD83D\\uDC66|\\uD83D\\uDC69\\u200D\\uD83D\\uDC67|\\uD83C\\uDDFD\\uD83C\\uDDF0|\\uD83C\\uDDF4\\uD83C\\uDDF2|\\uD83C\\uDDF6\\uD83C\\uDDE6|[#\\*0-9]\\uFE0F\\u20E3|\\uD83C\\uDDE7(?:\\uD83C[\\uDDE6\\uDDE7\\uDDE9-\\uDDEF\\uDDF1-\\uDDF4\\uDD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uD83C[\\uDFCB\\uDFCC]|\\uD83D\\uDD75)(?:\\uD83C[\\uDFFB-\\uDFFF])|(?:[\\u261D\\u270A-\\u270D]|\\uD83C[\\uDF85\\uDFC2\\uDFC7]|\\uD83D[\\uDC42\\uDC43\\uDC46-\\uDC50\\uDC66\\uDC67\\uDC6B-\\uDC6D\\uDC70\\uDC72\\uDC74-\\uDC76\\uDC78\\uDC7C\\uDC83\\uDC85\\uDCAA\\uDD74\\uDD7A\\uDD90\\uDD95\\uDD96\\uDE4C\\uDE4F\\uDEC0\\uDECC]|\\uD83E[\\uDD0F\\uDD18-\\uDD1C\\uDD1E\\uDD1F\\uDD30-\\uDD36\\uDDB5\\uDDB6\\uDDBB\\uDDD2-\\uDDD5])(?:\\uD83C[\\uDFFB-\\uDFFF])|(?:[\\u231A\\u231B\\u23E9-\\u23EC\\u23F0\\u23F3\\u25FD\\u25FE\\u2614\\u2615\\u2648-\\u2653\\u267F\\u2693\\u26A1\\u26AA\\u26AB\\u26BD\\u26BE\\u26C4\\u26C5\\u26CE\\u26D4\\u26EA\\u26F2\\u26F3\\u26F5\\u26FA\\u26FD\\u2705\\u270A\\u270B\\u2728\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2795-\\u2797\\u27B0\\u27BF\\u2B1B\\u2B1C\\u2B50\\u2B55]|\\uD83C[\\uDC04\\uDCCF\\uDD8E\\uDD91-\\uDD9A\\uDDE6-\\uDDFF\\uDE01\\uDE1A\\uDE2F\\uDE32-\\uDE36\\uDE38-\\uDE3A\\uDE50\\uDE51\\uDF00-\\uDF20\\uDF2D-\\uDF35\\uDF37-\\uDF7C\\uDF7E-\\uDF93\\uDFA0-\\uDFCA\\uDFCF-\\uDFD3\\uDFE0-\\uDFF0\\uDFF4\\uDFF8-\\uDFFF]|\\uD83D[\\uDC00-\\uDC3E\\uDC40\\uDC42-\\uDCFC\\uDCFF-\\uDD3D\\uDD4B-\\uDD4E\\uDD50-\\uDD67\\uDD7A\\uDD95\\uDD96\\uDDA4\\uDDFB-\\uDE4F\\uDE80-\\uDEC5\\uDECC\\uDED0-\\uDED2\\uDED5\\uDEEB\\uDEEC\\uDEF4-\\uDEFA\\uDFE0-\\uDFEB]|\\uD83E[\\uDD0D-\\uDD3A\\uDD3C-\\uDD45\\uDD47-\\uDD71\\uDD73-\\uDD76\\uDD7A-\\uDDA2\\uDDA5-\\uDDAA\\uDDAE-\\uDDCA\\uDDCD-\\uDDFF\\uDE70-\\uDE73\\uDE78-\\uDE7A\\uDE80-\\uDE82\\uDE90-\\uDE95])|(?:[#\\*0-9\\xA9\\xAE\\u203C\\u2049\\u2122\\u2139\\u2194-\\u2199\\u21A9\\u21AA\\u231A\\u231B\\u2328\\u23CF\\u23E9-\\u23F3\\u23F8-\\u23FA\\u24C2\\u25AA\\u25AB\\u25B6\\u25C0\\u25FB-\\u25FE\\u2600-\\u2604\\u260E\\u2611\\u2614\\u2615\\u2618\\u261D\\u2620\\u2622\\u2623\\u2626\\u262A\\u262E\\u262F\\u2638-\\u263A\\u2640\\u2642\\u2648-\\u2653\\u265F\\u2660\\u2663\\u2665\\u2666\\u2668\\u267B\\u267E\\u267F\\u2692-\\u2697\\u2699\\u269B\\u269C\\u26A0\\u26A1\\u26AA\\u26AB\\u26B0\\u26B1\\u26BD\\u26BE\\u26C4\\u26C5\\u26C8\\u26CE\\u26CF\\u26D1\\u26D3\\u26D4\\u26E9\\u26EA\\u26F0-\\u26F5\\u26F7-\\u26FA\\u26FD\\u2702\\u2705\\u2708-\\u270D\\u270F\\u2712\\u2714\\u2716\\u271D\\u2721\\u2728\\u2733\\u2734\\u2744\\u2747\\u274C\\u274E\\u2753-\\u2755\\u2757\\u2763\\u2764\\u2795-\\u2797\\u27A1\\u27B0\\u27BF\\u2934\\u2935\\u2B05-\\u2B07\\u2B1B\\u2B1C\\u2B50\\u2B55\\u3030\\u303D\\u3297\\u3299]|\\uD83C[\\uDC04\\uDCCF\\uDD70\\uDD71\\uDD7E\\uDD7F\\uDD8E\\uDD91-\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\\uDD18-\\uDD1F\\uDD26\\uDD30-\\uDD39\\uDD3C-\\uDD3E\\uDDB5\\uDDB6\\uDDB8\\uDDB9\\uDDBB\\uDDCD-\\uDDCF\\uDDD1-\\uDDDD])/g}});var Lk=_((kKt,S6)=>{\"use strict\";var Zyt=BP(),$yt=b6(),eEt=jEe(),GEe=t=>{if(typeof t!=\"string\"||t.length===0||(t=Zyt(t),t.length===0))return 0;t=t.replace(eEt(),\"  \");let e=0;for(let r=0;r<t.length;r++){let o=t.codePointAt(r);o<=31||o>=127&&o<=159||o>=768&&o<=879||(o>65535&&r++,e+=$yt(o)?2:1)}return e};S6.exports=GEe;S6.exports.default=GEe});var k6=_((QKt,x6)=>{\"use strict\";var tEt=Lk(),YEe=t=>{let e=0;for(let r of t.split(`\n`))e=Math.max(e,tEt(r));return e};x6.exports=YEe;x6.exports.default=YEe});var WEe=_(W2=>{\"use strict\";var rEt=W2&&W2.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(W2,\"__esModule\",{value:!0});var nEt=rEt(k6()),Q6={};W2.default=t=>{if(t.length===0)return{width:0,height:0};if(Q6[t])return Q6[t];let e=nEt.default(t),r=t.split(`\n`).length;return Q6[t]={width:e,height:r},{width:e,height:r}}});var KEe=_(K2=>{\"use strict\";var iEt=K2&&K2.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(K2,\"__esModule\",{value:!0});var dn=iEt(Jg()),sEt=(t,e)=>{\"position\"in e&&t.setPositionType(e.position===\"absolute\"?dn.default.POSITION_TYPE_ABSOLUTE:dn.default.POSITION_TYPE_RELATIVE)},oEt=(t,e)=>{\"marginLeft\"in e&&t.setMargin(dn.default.EDGE_START,e.marginLeft||0),\"marginRight\"in e&&t.setMargin(dn.default.EDGE_END,e.marginRight||0),\"marginTop\"in e&&t.setMargin(dn.default.EDGE_TOP,e.marginTop||0),\"marginBottom\"in e&&t.setMargin(dn.default.EDGE_BOTTOM,e.marginBottom||0)},aEt=(t,e)=>{\"paddingLeft\"in e&&t.setPadding(dn.default.EDGE_LEFT,e.paddingLeft||0),\"paddingRight\"in e&&t.setPadding(dn.default.EDGE_RIGHT,e.paddingRight||0),\"paddingTop\"in e&&t.setPadding(dn.default.EDGE_TOP,e.paddingTop||0),\"paddingBottom\"in e&&t.setPadding(dn.default.EDGE_BOTTOM,e.paddingBottom||0)},lEt=(t,e)=>{var r;\"flexGrow\"in e&&t.setFlexGrow((r=e.flexGrow)!==null&&r!==void 0?r:0),\"flexShrink\"in e&&t.setFlexShrink(typeof e.flexShrink==\"number\"?e.flexShrink:1),\"flexDirection\"in e&&(e.flexDirection===\"row\"&&t.setFlexDirection(dn.default.FLEX_DIRECTION_ROW),e.flexDirection===\"row-reverse\"&&t.setFlexDirection(dn.default.FLEX_DIRECTION_ROW_REVERSE),e.flexDirection===\"column\"&&t.setFlexDirection(dn.default.FLEX_DIRECTION_COLUMN),e.flexDirection===\"column-reverse\"&&t.setFlexDirection(dn.default.FLEX_DIRECTION_COLUMN_REVERSE)),\"flexBasis\"in e&&(typeof e.flexBasis==\"number\"?t.setFlexBasis(e.flexBasis):typeof e.flexBasis==\"string\"?t.setFlexBasisPercent(Number.parseInt(e.flexBasis,10)):t.setFlexBasis(NaN)),\"alignItems\"in e&&((e.alignItems===\"stretch\"||!e.alignItems)&&t.setAlignItems(dn.default.ALIGN_STRETCH),e.alignItems===\"flex-start\"&&t.setAlignItems(dn.default.ALIGN_FLEX_START),e.alignItems===\"center\"&&t.setAlignItems(dn.default.ALIGN_CENTER),e.alignItems===\"flex-end\"&&t.setAlignItems(dn.default.ALIGN_FLEX_END)),\"alignSelf\"in e&&((e.alignSelf===\"auto\"||!e.alignSelf)&&t.setAlignSelf(dn.default.ALIGN_AUTO),e.alignSelf===\"flex-start\"&&t.setAlignSelf(dn.default.ALIGN_FLEX_START),e.alignSelf===\"center\"&&t.setAlignSelf(dn.default.ALIGN_CENTER),e.alignSelf===\"flex-end\"&&t.setAlignSelf(dn.default.ALIGN_FLEX_END)),\"justifyContent\"in e&&((e.justifyContent===\"flex-start\"||!e.justifyContent)&&t.setJustifyContent(dn.default.JUSTIFY_FLEX_START),e.justifyContent===\"center\"&&t.setJustifyContent(dn.default.JUSTIFY_CENTER),e.justifyContent===\"flex-end\"&&t.setJustifyContent(dn.default.JUSTIFY_FLEX_END),e.justifyContent===\"space-between\"&&t.setJustifyContent(dn.default.JUSTIFY_SPACE_BETWEEN),e.justifyContent===\"space-around\"&&t.setJustifyContent(dn.default.JUSTIFY_SPACE_AROUND))},cEt=(t,e)=>{var r,o;\"width\"in e&&(typeof e.width==\"number\"?t.setWidth(e.width):typeof e.width==\"string\"?t.setWidthPercent(Number.parseInt(e.width,10)):t.setWidthAuto()),\"height\"in e&&(typeof e.height==\"number\"?t.setHeight(e.height):typeof e.height==\"string\"?t.setHeightPercent(Number.parseInt(e.height,10)):t.setHeightAuto()),\"minWidth\"in e&&(typeof e.minWidth==\"string\"?t.setMinWidthPercent(Number.parseInt(e.minWidth,10)):t.setMinWidth((r=e.minWidth)!==null&&r!==void 0?r:0)),\"minHeight\"in e&&(typeof e.minHeight==\"string\"?t.setMinHeightPercent(Number.parseInt(e.minHeight,10)):t.setMinHeight((o=e.minHeight)!==null&&o!==void 0?o:0))},uEt=(t,e)=>{\"display\"in e&&t.setDisplay(e.display===\"flex\"?dn.default.DISPLAY_FLEX:dn.default.DISPLAY_NONE)},AEt=(t,e)=>{if(\"borderStyle\"in e){let r=typeof e.borderStyle==\"string\"?1:0;t.setBorder(dn.default.EDGE_TOP,r),t.setBorder(dn.default.EDGE_BOTTOM,r),t.setBorder(dn.default.EDGE_LEFT,r),t.setBorder(dn.default.EDGE_RIGHT,r)}};K2.default=(t,e={})=>{sEt(t,e),oEt(t,e),aEt(t,e),lEt(t,e),cEt(t,e),uEt(t,e),AEt(t,e)}});var JEe=_((TKt,zEe)=>{\"use strict\";var V2=Lk(),fEt=BP(),pEt=aI(),R6=new Set([\"\\x1B\",\"\\x9B\"]),hEt=39,VEe=t=>`${R6.values().next().value}[${t}m`,gEt=t=>t.split(\" \").map(e=>V2(e)),F6=(t,e,r)=>{let o=[...e],a=!1,n=V2(fEt(t[t.length-1]));for(let[u,A]of o.entries()){let p=V2(A);if(n+p<=r?t[t.length-1]+=A:(t.push(A),n=0),R6.has(A))a=!0;else if(a&&A===\"m\"){a=!1;continue}a||(n+=p,n===r&&u<o.length-1&&(t.push(\"\"),n=0))}!n&&t[t.length-1].length>0&&t.length>1&&(t[t.length-2]+=t.pop())},dEt=t=>{let e=t.split(\" \"),r=e.length;for(;r>0&&!(V2(e[r-1])>0);)r--;return r===e.length?t:e.slice(0,r).join(\" \")+e.slice(r).join(\"\")},mEt=(t,e,r={})=>{if(r.trim!==!1&&t.trim()===\"\")return\"\";let o=\"\",a=\"\",n,u=gEt(t),A=[\"\"];for(let[p,h]of t.split(\" \").entries()){r.trim!==!1&&(A[A.length-1]=A[A.length-1].trimLeft());let E=V2(A[A.length-1]);if(p!==0&&(E>=e&&(r.wordWrap===!1||r.trim===!1)&&(A.push(\"\"),E=0),(E>0||r.trim===!1)&&(A[A.length-1]+=\" \",E++)),r.hard&&u[p]>e){let I=e-E,v=1+Math.floor((u[p]-I-1)/e);Math.floor((u[p]-1)/e)<v&&A.push(\"\"),F6(A,h,e);continue}if(E+u[p]>e&&E>0&&u[p]>0){if(r.wordWrap===!1&&E<e){F6(A,h,e);continue}A.push(\"\")}if(E+u[p]>e&&r.wordWrap===!1){F6(A,h,e);continue}A[A.length-1]+=h}r.trim!==!1&&(A=A.map(dEt)),o=A.join(`\n`);for(let[p,h]of[...o].entries()){if(a+=h,R6.has(h)){let I=parseFloat(/\\d[^m]*/.exec(o.slice(p,p+4)));n=I===hEt?null:I}let E=pEt.codes.get(Number(n));n&&E&&(o[p+1]===`\n`?a+=VEe(E):h===`\n`&&(a+=VEe(n)))}return a};zEe.exports=(t,e,r)=>String(t).normalize().replace(/\\r\\n/g,`\n`).split(`\n`).map(o=>mEt(o,e,r)).join(`\n`)});var $Ee=_((NKt,ZEe)=>{\"use strict\";var XEe=\"[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]\",yEt=t=>t&&t.exact?new RegExp(`^${XEe}$`):new RegExp(XEe,\"g\");ZEe.exports=yEt});var T6=_((LKt,nCe)=>{\"use strict\";var EEt=b6(),CEt=$Ee(),eCe=aI(),rCe=[\"\\x1B\",\"\\x9B\"],Mk=t=>`${rCe[0]}[${t}m`,tCe=(t,e,r)=>{let o=[];t=[...t];for(let a of t){let n=a;a.match(\";\")&&(a=a.split(\";\")[0][0]+\"0\");let u=eCe.codes.get(parseInt(a,10));if(u){let A=t.indexOf(u.toString());A>=0?t.splice(A,1):o.push(Mk(e?u:n))}else if(e){o.push(Mk(0));break}else o.push(Mk(n))}if(e&&(o=o.filter((a,n)=>o.indexOf(a)===n),r!==void 0)){let a=Mk(eCe.codes.get(parseInt(r,10)));o=o.reduce((n,u)=>u===a?[u,...n]:[...n,u],[])}return o.join(\"\")};nCe.exports=(t,e,r)=>{let o=[...t.normalize()],a=[];r=typeof r==\"number\"?r:o.length;let n=!1,u,A=0,p=\"\";for(let[h,E]of o.entries()){let I=!1;if(rCe.includes(E)){let v=/\\d[^m]*/.exec(t.slice(h,h+18));u=v&&v.length>0?v[0]:void 0,A<r&&(n=!0,u!==void 0&&a.push(u))}else n&&E===\"m\"&&(n=!1,I=!0);if(!n&&!I&&++A,!CEt({exact:!0}).test(E)&&EEt(E.codePointAt())&&++A,A>e&&A<=r)p+=E;else if(A===e&&!n&&u!==void 0)p=tCe(a);else if(A>=r){p+=tCe(a,!0,u);break}}return p}});var sCe=_((MKt,iCe)=>{\"use strict\";var Nh=T6(),wEt=Lk();function Ok(t,e,r){if(t.charAt(e)===\" \")return e;for(let o=1;o<=3;o++)if(r){if(t.charAt(e+o)===\" \")return e+o}else if(t.charAt(e-o)===\" \")return e-o;return e}iCe.exports=(t,e,r)=>{r={position:\"end\",preferTruncationOnSpace:!1,...r};let{position:o,space:a,preferTruncationOnSpace:n}=r,u=\"\\u2026\",A=1;if(typeof t!=\"string\")throw new TypeError(`Expected \\`input\\` to be a string, got ${typeof t}`);if(typeof e!=\"number\")throw new TypeError(`Expected \\`columns\\` to be a number, got ${typeof e}`);if(e<1)return\"\";if(e===1)return u;let p=wEt(t);if(p<=e)return t;if(o===\"start\"){if(n){let h=Ok(t,p-e+1,!0);return u+Nh(t,h,p).trim()}return a===!0&&(u+=\" \",A=2),u+Nh(t,p-e+A,p)}if(o===\"middle\"){a===!0&&(u=\" \"+u+\" \",A=3);let h=Math.floor(e/2);if(n){let E=Ok(t,h),I=Ok(t,p-(e-h)+1,!0);return Nh(t,0,E)+u+Nh(t,I,p).trim()}return Nh(t,0,h)+u+Nh(t,p-(e-h)+A,p)}if(o===\"end\"){if(n){let h=Ok(t,e-1);return Nh(t,0,h)+u}return a===!0&&(u=\" \"+u,A=2),Nh(t,0,e-A)+u}throw new Error(`Expected \\`options.position\\` to be either \\`start\\`, \\`middle\\` or \\`end\\`, got ${o}`)}});var L6=_(z2=>{\"use strict\";var oCe=z2&&z2.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(z2,\"__esModule\",{value:!0});var IEt=oCe(JEe()),BEt=oCe(sCe()),N6={};z2.default=(t,e,r)=>{let o=t+String(e)+String(r);if(N6[o])return N6[o];let a=t;if(r===\"wrap\"&&(a=IEt.default(t,e,{trim:!1,hard:!0})),r.startsWith(\"truncate\")){let n=\"end\";r===\"truncate-middle\"&&(n=\"middle\"),r===\"truncate-start\"&&(n=\"start\"),a=BEt.default(t,e,{position:n})}return N6[o]=a,a}});var O6=_(M6=>{\"use strict\";Object.defineProperty(M6,\"__esModule\",{value:!0});var aCe=t=>{let e=\"\";if(t.childNodes.length>0)for(let r of t.childNodes){let o=\"\";r.nodeName===\"#text\"?o=r.nodeValue:((r.nodeName===\"ink-text\"||r.nodeName===\"ink-virtual-text\")&&(o=aCe(r)),o.length>0&&typeof r.internal_transform==\"function\"&&(o=r.internal_transform(o))),e+=o}return e};M6.default=aCe});var U6=_(pi=>{\"use strict\";var J2=pi&&pi.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pi,\"__esModule\",{value:!0});pi.setTextNodeValue=pi.createTextNode=pi.setStyle=pi.setAttribute=pi.removeChildNode=pi.insertBeforeNode=pi.appendChildNode=pi.createNode=pi.TEXT_NAME=void 0;var vEt=J2(Jg()),lCe=J2(WEe()),DEt=J2(KEe()),PEt=J2(L6()),bEt=J2(O6());pi.TEXT_NAME=\"#text\";pi.createNode=t=>{var e;let r={nodeName:t,style:{},attributes:{},childNodes:[],parentNode:null,yogaNode:t===\"ink-virtual-text\"?void 0:vEt.default.Node.create()};return t===\"ink-text\"&&((e=r.yogaNode)===null||e===void 0||e.setMeasureFunc(SEt.bind(null,r))),r};pi.appendChildNode=(t,e)=>{var r;e.parentNode&&pi.removeChildNode(e.parentNode,e),e.parentNode=t,t.childNodes.push(e),e.yogaNode&&((r=t.yogaNode)===null||r===void 0||r.insertChild(e.yogaNode,t.yogaNode.getChildCount())),(t.nodeName===\"ink-text\"||t.nodeName===\"ink-virtual-text\")&&Uk(t)};pi.insertBeforeNode=(t,e,r)=>{var o,a;e.parentNode&&pi.removeChildNode(e.parentNode,e),e.parentNode=t;let n=t.childNodes.indexOf(r);if(n>=0){t.childNodes.splice(n,0,e),e.yogaNode&&((o=t.yogaNode)===null||o===void 0||o.insertChild(e.yogaNode,n));return}t.childNodes.push(e),e.yogaNode&&((a=t.yogaNode)===null||a===void 0||a.insertChild(e.yogaNode,t.yogaNode.getChildCount())),(t.nodeName===\"ink-text\"||t.nodeName===\"ink-virtual-text\")&&Uk(t)};pi.removeChildNode=(t,e)=>{var r,o;e.yogaNode&&((o=(r=e.parentNode)===null||r===void 0?void 0:r.yogaNode)===null||o===void 0||o.removeChild(e.yogaNode)),e.parentNode=null;let a=t.childNodes.indexOf(e);a>=0&&t.childNodes.splice(a,1),(t.nodeName===\"ink-text\"||t.nodeName===\"ink-virtual-text\")&&Uk(t)};pi.setAttribute=(t,e,r)=>{t.attributes[e]=r};pi.setStyle=(t,e)=>{t.style=e,t.yogaNode&&DEt.default(t.yogaNode,e)};pi.createTextNode=t=>{let e={nodeName:\"#text\",nodeValue:t,yogaNode:void 0,parentNode:null,style:{}};return pi.setTextNodeValue(e,t),e};var SEt=function(t,e){var r,o;let a=t.nodeName===\"#text\"?t.nodeValue:bEt.default(t),n=lCe.default(a);if(n.width<=e||n.width>=1&&e>0&&e<1)return n;let u=(o=(r=t.style)===null||r===void 0?void 0:r.textWrap)!==null&&o!==void 0?o:\"wrap\",A=PEt.default(a,e,u);return lCe.default(A)},cCe=t=>{var e;if(!(!t||!t.parentNode))return(e=t.yogaNode)!==null&&e!==void 0?e:cCe(t.parentNode)},Uk=t=>{let e=cCe(t);e?.markDirty()};pi.setTextNodeValue=(t,e)=>{typeof e!=\"string\"&&(e=String(e)),t.nodeValue=e,Uk(t)}});var hCe=_(X2=>{\"use strict\";var pCe=X2&&X2.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(X2,\"__esModule\",{value:!0});var uCe=w6(),xEt=pCe(FEe()),ACe=pCe(Jg()),Mo=U6(),fCe=t=>{t?.unsetMeasureFunc(),t?.freeRecursive()};X2.default=xEt.default({schedulePassiveEffects:uCe.unstable_scheduleCallback,cancelPassiveEffects:uCe.unstable_cancelCallback,now:Date.now,getRootHostContext:()=>({isInsideText:!1}),prepareForCommit:()=>{},resetAfterCommit:t=>{if(t.isStaticDirty){t.isStaticDirty=!1,typeof t.onImmediateRender==\"function\"&&t.onImmediateRender();return}typeof t.onRender==\"function\"&&t.onRender()},getChildHostContext:(t,e)=>{let r=t.isInsideText,o=e===\"ink-text\"||e===\"ink-virtual-text\";return r===o?t:{isInsideText:o}},shouldSetTextContent:()=>!1,createInstance:(t,e,r,o)=>{if(o.isInsideText&&t===\"ink-box\")throw new Error(\"<Box> can\\u2019t be nested inside <Text> component\");let a=t===\"ink-text\"&&o.isInsideText?\"ink-virtual-text\":t,n=Mo.createNode(a);for(let[u,A]of Object.entries(e))u!==\"children\"&&(u===\"style\"?Mo.setStyle(n,A):u===\"internal_transform\"?n.internal_transform=A:u===\"internal_static\"?n.internal_static=!0:Mo.setAttribute(n,u,A));return n},createTextInstance:(t,e,r)=>{if(!r.isInsideText)throw new Error(`Text string \"${t}\" must be rendered inside <Text> component`);return Mo.createTextNode(t)},resetTextContent:()=>{},hideTextInstance:t=>{Mo.setTextNodeValue(t,\"\")},unhideTextInstance:(t,e)=>{Mo.setTextNodeValue(t,e)},getPublicInstance:t=>t,hideInstance:t=>{var e;(e=t.yogaNode)===null||e===void 0||e.setDisplay(ACe.default.DISPLAY_NONE)},unhideInstance:t=>{var e;(e=t.yogaNode)===null||e===void 0||e.setDisplay(ACe.default.DISPLAY_FLEX)},appendInitialChild:Mo.appendChildNode,appendChild:Mo.appendChildNode,insertBefore:Mo.insertBeforeNode,finalizeInitialChildren:(t,e,r,o)=>(t.internal_static&&(o.isStaticDirty=!0,o.staticNode=t),!1),supportsMutation:!0,appendChildToContainer:Mo.appendChildNode,insertInContainerBefore:Mo.insertBeforeNode,removeChildFromContainer:(t,e)=>{Mo.removeChildNode(t,e),fCe(e.yogaNode)},prepareUpdate:(t,e,r,o,a)=>{t.internal_static&&(a.isStaticDirty=!0);let n={},u=Object.keys(o);for(let A of u)if(o[A]!==r[A]){if(A===\"style\"&&typeof o.style==\"object\"&&typeof r.style==\"object\"){let h=o.style,E=r.style,I=Object.keys(h);for(let v of I){if(v===\"borderStyle\"||v===\"borderColor\"){if(typeof n.style!=\"object\"){let x={};n.style=x}n.style.borderStyle=h.borderStyle,n.style.borderColor=h.borderColor}if(h[v]!==E[v]){if(typeof n.style!=\"object\"){let x={};n.style=x}n.style[v]=h[v]}}continue}n[A]=o[A]}return n},commitUpdate:(t,e)=>{for(let[r,o]of Object.entries(e))r!==\"children\"&&(r===\"style\"?Mo.setStyle(t,o):r===\"internal_transform\"?t.internal_transform=o:r===\"internal_static\"?t.internal_static=!0:Mo.setAttribute(t,r,o))},commitTextUpdate:(t,e,r)=>{Mo.setTextNodeValue(t,r)},removeChild:(t,e)=>{Mo.removeChildNode(t,e),fCe(e.yogaNode)}})});var dCe=_((qKt,gCe)=>{\"use strict\";gCe.exports=(t,e=1,r)=>{if(r={indent:\" \",includeEmptyLines:!1,...r},typeof t!=\"string\")throw new TypeError(`Expected \\`input\\` to be a \\`string\\`, got \\`${typeof t}\\``);if(typeof e!=\"number\")throw new TypeError(`Expected \\`count\\` to be a \\`number\\`, got \\`${typeof e}\\``);if(typeof r.indent!=\"string\")throw new TypeError(`Expected \\`options.indent\\` to be a \\`string\\`, got \\`${typeof r.indent}\\``);if(e===0)return t;let o=r.includeEmptyLines?/^/gm:/^(?!\\s*$)/gm;return t.replace(o,r.indent.repeat(e))}});var mCe=_(Z2=>{\"use strict\";var kEt=Z2&&Z2.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(Z2,\"__esModule\",{value:!0});var _k=kEt(Jg());Z2.default=t=>t.getComputedWidth()-t.getComputedPadding(_k.default.EDGE_LEFT)-t.getComputedPadding(_k.default.EDGE_RIGHT)-t.getComputedBorder(_k.default.EDGE_LEFT)-t.getComputedBorder(_k.default.EDGE_RIGHT)});var yCe=_((GKt,QEt)=>{QEt.exports={single:{topLeft:\"\\u250C\",topRight:\"\\u2510\",bottomRight:\"\\u2518\",bottomLeft:\"\\u2514\",vertical:\"\\u2502\",horizontal:\"\\u2500\"},double:{topLeft:\"\\u2554\",topRight:\"\\u2557\",bottomRight:\"\\u255D\",bottomLeft:\"\\u255A\",vertical:\"\\u2551\",horizontal:\"\\u2550\"},round:{topLeft:\"\\u256D\",topRight:\"\\u256E\",bottomRight:\"\\u256F\",bottomLeft:\"\\u2570\",vertical:\"\\u2502\",horizontal:\"\\u2500\"},bold:{topLeft:\"\\u250F\",topRight:\"\\u2513\",bottomRight:\"\\u251B\",bottomLeft:\"\\u2517\",vertical:\"\\u2503\",horizontal:\"\\u2501\"},singleDouble:{topLeft:\"\\u2553\",topRight:\"\\u2556\",bottomRight:\"\\u255C\",bottomLeft:\"\\u2559\",vertical:\"\\u2551\",horizontal:\"\\u2500\"},doubleSingle:{topLeft:\"\\u2552\",topRight:\"\\u2555\",bottomRight:\"\\u255B\",bottomLeft:\"\\u2558\",vertical:\"\\u2502\",horizontal:\"\\u2550\"},classic:{topLeft:\"+\",topRight:\"+\",bottomRight:\"+\",bottomLeft:\"+\",vertical:\"|\",horizontal:\"-\"}}});var CCe=_((YKt,_6)=>{\"use strict\";var ECe=yCe();_6.exports=ECe;_6.exports.default=ECe});var ICe=_((WKt,wCe)=>{\"use strict\";var FEt=(t,e,r)=>{let o=t.indexOf(e);if(o===-1)return t;let a=e.length,n=0,u=\"\";do u+=t.substr(n,o-n)+e+r,n=o+a,o=t.indexOf(e,n);while(o!==-1);return u+=t.substr(n),u},REt=(t,e,r,o)=>{let a=0,n=\"\";do{let u=t[o-1]===\"\\r\";n+=t.substr(a,(u?o-1:o)-a)+e+(u?`\\r\n`:`\n`)+r,a=o+1,o=t.indexOf(`\n`,a)}while(o!==-1);return n+=t.substr(a),n};wCe.exports={stringReplaceAll:FEt,stringEncaseCRLFWithFirstIndex:REt}});var bCe=_((KKt,PCe)=>{\"use strict\";var TEt=/(?:\\\\(u(?:[a-f\\d]{4}|\\{[a-f\\d]{1,6}\\})|x[a-f\\d]{2}|.))|(?:\\{(~)?(\\w+(?:\\([^)]*\\))?(?:\\.\\w+(?:\\([^)]*\\))?)*)(?:[ \\t]|(?=\\r?\\n)))|(\\})|((?:.|[\\r\\n\\f])+?)/gi,BCe=/(?:^|\\.)(\\w+)(?:\\(([^)]*)\\))?/g,NEt=/^(['\"])((?:\\\\.|(?!\\1)[^\\\\])*)\\1$/,LEt=/\\\\(u(?:[a-f\\d]{4}|{[a-f\\d]{1,6}})|x[a-f\\d]{2}|.)|([^\\\\])/gi,MEt=new Map([[\"n\",`\n`],[\"r\",\"\\r\"],[\"t\",\"\t\"],[\"b\",\"\\b\"],[\"f\",\"\\f\"],[\"v\",\"\\v\"],[\"0\",\"\\0\"],[\"\\\\\",\"\\\\\"],[\"e\",\"\\x1B\"],[\"a\",\"\\x07\"]]);function DCe(t){let e=t[0]===\"u\",r=t[1]===\"{\";return e&&!r&&t.length===5||t[0]===\"x\"&&t.length===3?String.fromCharCode(parseInt(t.slice(1),16)):e&&r?String.fromCodePoint(parseInt(t.slice(2,-1),16)):MEt.get(t)||t}function OEt(t,e){let r=[],o=e.trim().split(/\\s*,\\s*/g),a;for(let n of o){let u=Number(n);if(!Number.isNaN(u))r.push(u);else if(a=n.match(NEt))r.push(a[2].replace(LEt,(A,p,h)=>p?DCe(p):h));else throw new Error(`Invalid Chalk template style argument: ${n} (in style '${t}')`)}return r}function UEt(t){BCe.lastIndex=0;let e=[],r;for(;(r=BCe.exec(t))!==null;){let o=r[1];if(r[2]){let a=OEt(o,r[2]);e.push([o].concat(a))}else e.push([o])}return e}function vCe(t,e){let r={};for(let a of e)for(let n of a.styles)r[n[0]]=a.inverse?null:n.slice(1);let o=t;for(let[a,n]of Object.entries(r))if(Array.isArray(n)){if(!(a in o))throw new Error(`Unknown Chalk style: ${a}`);o=n.length>0?o[a](...n):o[a]}return o}PCe.exports=(t,e)=>{let r=[],o=[],a=[];if(e.replace(TEt,(n,u,A,p,h,E)=>{if(u)a.push(DCe(u));else if(p){let I=a.join(\"\");a=[],o.push(r.length===0?I:vCe(t,r)(I)),r.push({inverse:A,styles:UEt(p)})}else if(h){if(r.length===0)throw new Error(\"Found extraneous } in Chalk template literal\");o.push(vCe(t,r)(a.join(\"\"))),a=[],r.pop()}else a.push(E)}),o.push(a.join(\"\")),r.length>0){let n=`Chalk template literal is missing ${r.length} closing bracket${r.length===1?\"\":\"s\"} (\\`}\\`)`;throw new Error(n)}return o.join(\"\")}});var Yk=_((VKt,RCe)=>{\"use strict\";var $2=aI(),{stdout:q6,stderr:j6}=aN(),{stringReplaceAll:_Et,stringEncaseCRLFWithFirstIndex:HEt}=ICe(),{isArray:Hk}=Array,xCe=[\"ansi\",\"ansi\",\"ansi256\",\"ansi16m\"],nC=Object.create(null),qEt=(t,e={})=>{if(e.level&&!(Number.isInteger(e.level)&&e.level>=0&&e.level<=3))throw new Error(\"The `level` option should be an integer from 0 to 3\");let r=q6?q6.level:0;t.level=e.level===void 0?r:e.level},G6=class{constructor(e){return kCe(e)}},kCe=t=>{let e={};return qEt(e,t),e.template=(...r)=>FCe(e.template,...r),Object.setPrototypeOf(e,qk.prototype),Object.setPrototypeOf(e.template,e),e.template.constructor=()=>{throw new Error(\"`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.\")},e.template.Instance=G6,e.template};function qk(t){return kCe(t)}for(let[t,e]of Object.entries($2))nC[t]={get(){let r=jk(this,Y6(e.open,e.close,this._styler),this._isEmpty);return Object.defineProperty(this,t,{value:r}),r}};nC.visible={get(){let t=jk(this,this._styler,!0);return Object.defineProperty(this,\"visible\",{value:t}),t}};var QCe=[\"rgb\",\"hex\",\"keyword\",\"hsl\",\"hsv\",\"hwb\",\"ansi\",\"ansi256\"];for(let t of QCe)nC[t]={get(){let{level:e}=this;return function(...r){let o=Y6($2.color[xCe[e]][t](...r),$2.color.close,this._styler);return jk(this,o,this._isEmpty)}}};for(let t of QCe){let e=\"bg\"+t[0].toUpperCase()+t.slice(1);nC[e]={get(){let{level:r}=this;return function(...o){let a=Y6($2.bgColor[xCe[r]][t](...o),$2.bgColor.close,this._styler);return jk(this,a,this._isEmpty)}}}}var jEt=Object.defineProperties(()=>{},{...nC,level:{enumerable:!0,get(){return this._generator.level},set(t){this._generator.level=t}}}),Y6=(t,e,r)=>{let o,a;return r===void 0?(o=t,a=e):(o=r.openAll+t,a=e+r.closeAll),{open:t,close:e,openAll:o,closeAll:a,parent:r}},jk=(t,e,r)=>{let o=(...a)=>Hk(a[0])&&Hk(a[0].raw)?SCe(o,FCe(o,...a)):SCe(o,a.length===1?\"\"+a[0]:a.join(\" \"));return Object.setPrototypeOf(o,jEt),o._generator=t,o._styler=e,o._isEmpty=r,o},SCe=(t,e)=>{if(t.level<=0||!e)return t._isEmpty?\"\":e;let r=t._styler;if(r===void 0)return e;let{openAll:o,closeAll:a}=r;if(e.indexOf(\"\\x1B\")!==-1)for(;r!==void 0;)e=_Et(e,r.close,r.open),r=r.parent;let n=e.indexOf(`\n`);return n!==-1&&(e=HEt(e,a,o,n)),o+e+a},H6,FCe=(t,...e)=>{let[r]=e;if(!Hk(r)||!Hk(r.raw))return e.join(\" \");let o=e.slice(1),a=[r.raw[0]];for(let n=1;n<r.length;n++)a.push(String(o[n-1]).replace(/[{}\\\\]/g,\"\\\\$&\"),String(r.raw[n]));return H6===void 0&&(H6=bCe()),H6(t,a.join(\"\"))};Object.defineProperties(qk.prototype,nC);var Gk=qk();Gk.supportsColor=q6;Gk.stderr=qk({level:j6?j6.level:0});Gk.stderr.supportsColor=j6;RCe.exports=Gk});var W6=_(tB=>{\"use strict\";var GEt=tB&&tB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(tB,\"__esModule\",{value:!0});var eB=GEt(Yk()),YEt=/^(rgb|hsl|hsv|hwb)\\(\\s?(\\d+),\\s?(\\d+),\\s?(\\d+)\\s?\\)$/,WEt=/^(ansi|ansi256)\\(\\s?(\\d+)\\s?\\)$/,Wk=(t,e)=>e===\"foreground\"?t:\"bg\"+t[0].toUpperCase()+t.slice(1);tB.default=(t,e,r)=>{if(!e)return t;if(e in eB.default){let a=Wk(e,r);return eB.default[a](t)}if(e.startsWith(\"#\")){let a=Wk(\"hex\",r);return eB.default[a](e)(t)}if(e.startsWith(\"ansi\")){let a=WEt.exec(e);if(!a)return t;let n=Wk(a[1],r),u=Number(a[2]);return eB.default[n](u)(t)}if(e.startsWith(\"rgb\")||e.startsWith(\"hsl\")||e.startsWith(\"hsv\")||e.startsWith(\"hwb\")){let a=YEt.exec(e);if(!a)return t;let n=Wk(a[1],r),u=Number(a[2]),A=Number(a[3]),p=Number(a[4]);return eB.default[n](u,A,p)(t)}return t}});var NCe=_(rB=>{\"use strict\";var TCe=rB&&rB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(rB,\"__esModule\",{value:!0});var KEt=TCe(CCe()),K6=TCe(W6());rB.default=(t,e,r,o)=>{if(typeof r.style.borderStyle==\"string\"){let a=r.yogaNode.getComputedWidth(),n=r.yogaNode.getComputedHeight(),u=r.style.borderColor,A=KEt.default[r.style.borderStyle],p=K6.default(A.topLeft+A.horizontal.repeat(a-2)+A.topRight,u,\"foreground\"),h=(K6.default(A.vertical,u,\"foreground\")+`\n`).repeat(n-2),E=K6.default(A.bottomLeft+A.horizontal.repeat(a-2)+A.bottomRight,u,\"foreground\");o.write(t,e,p,{transformers:[]}),o.write(t,e+1,h,{transformers:[]}),o.write(t+a-1,e+1,h,{transformers:[]}),o.write(t,e+n-1,E,{transformers:[]})}}});var MCe=_(nB=>{\"use strict\";var Xg=nB&&nB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(nB,\"__esModule\",{value:!0});var VEt=Xg(Jg()),zEt=Xg(k6()),JEt=Xg(dCe()),XEt=Xg(L6()),ZEt=Xg(mCe()),$Et=Xg(O6()),eCt=Xg(NCe()),tCt=(t,e)=>{var r;let o=(r=t.childNodes[0])===null||r===void 0?void 0:r.yogaNode;if(o){let a=o.getComputedLeft(),n=o.getComputedTop();e=`\n`.repeat(n)+JEt.default(e,a)}return e},LCe=(t,e,r)=>{var o;let{offsetX:a=0,offsetY:n=0,transformers:u=[],skipStaticElements:A}=r;if(A&&t.internal_static)return;let{yogaNode:p}=t;if(p){if(p.getDisplay()===VEt.default.DISPLAY_NONE)return;let h=a+p.getComputedLeft(),E=n+p.getComputedTop(),I=u;if(typeof t.internal_transform==\"function\"&&(I=[t.internal_transform,...u]),t.nodeName===\"ink-text\"){let v=$Et.default(t);if(v.length>0){let x=zEt.default(v),C=ZEt.default(p);if(x>C){let R=(o=t.style.textWrap)!==null&&o!==void 0?o:\"wrap\";v=XEt.default(v,C,R)}v=tCt(t,v),e.write(h,E,v,{transformers:I})}return}if(t.nodeName===\"ink-box\"&&eCt.default(h,E,t,e),t.nodeName===\"ink-root\"||t.nodeName===\"ink-box\")for(let v of t.childNodes)LCe(v,e,{offsetX:h,offsetY:E,transformers:I,skipStaticElements:A})}};nB.default=LCe});var UCe=_((ZKt,OCe)=>{\"use strict\";OCe.exports=t=>{t=Object.assign({onlyFirst:!1},t);let e=[\"[\\\\u001B\\\\u009B][[\\\\]()#;?]*(?:(?:(?:[a-zA-Z\\\\d]*(?:;[-a-zA-Z\\\\d\\\\/#&.:=?%@~_]*)*)?\\\\u0007)\",\"(?:(?:\\\\d{1,4}(?:;\\\\d{0,4})*)?[\\\\dA-PR-TZcf-ntqry=><~]))\"].join(\"|\");return new RegExp(e,t.onlyFirst?void 0:\"g\")}});var HCe=_(($Kt,V6)=>{\"use strict\";var rCt=UCe(),_Ce=t=>typeof t==\"string\"?t.replace(rCt(),\"\"):t;V6.exports=_Ce;V6.exports.default=_Ce});var GCe=_((eVt,jCe)=>{\"use strict\";var qCe=\"[\\uD800-\\uDBFF][\\uDC00-\\uDFFF]\";jCe.exports=t=>t&&t.exact?new RegExp(`^${qCe}$`):new RegExp(qCe,\"g\")});var WCe=_((tVt,z6)=>{\"use strict\";var nCt=HCe(),iCt=GCe(),YCe=t=>nCt(t).replace(iCt(),\" \").length;z6.exports=YCe;z6.exports.default=YCe});var zCe=_(iB=>{\"use strict\";var VCe=iB&&iB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(iB,\"__esModule\",{value:!0});var KCe=VCe(T6()),sCt=VCe(WCe()),J6=class{constructor(e){this.writes=[];let{width:r,height:o}=e;this.width=r,this.height=o}write(e,r,o,a){let{transformers:n}=a;o&&this.writes.push({x:e,y:r,text:o,transformers:n})}get(){let e=[];for(let o=0;o<this.height;o++)e.push(\" \".repeat(this.width));for(let o of this.writes){let{x:a,y:n,text:u,transformers:A}=o,p=u.split(`\n`),h=0;for(let E of p){let I=e[n+h];if(!I)continue;let v=sCt.default(E);for(let x of A)E=x(E);e[n+h]=KCe.default(I,0,a)+E+KCe.default(I,a+v),h++}}return{output:e.map(o=>o.trimRight()).join(`\n`),height:e.length}}};iB.default=J6});var ZCe=_(sB=>{\"use strict\";var X6=sB&&sB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(sB,\"__esModule\",{value:!0});var oCt=X6(Jg()),JCe=X6(MCe()),XCe=X6(zCe());sB.default=(t,e)=>{var r;if(t.yogaNode.setWidth(e),t.yogaNode){t.yogaNode.calculateLayout(void 0,void 0,oCt.default.DIRECTION_LTR);let o=new XCe.default({width:t.yogaNode.getComputedWidth(),height:t.yogaNode.getComputedHeight()});JCe.default(t,o,{skipStaticElements:!0});let a;!((r=t.staticNode)===null||r===void 0)&&r.yogaNode&&(a=new XCe.default({width:t.staticNode.yogaNode.getComputedWidth(),height:t.staticNode.yogaNode.getComputedHeight()}),JCe.default(t.staticNode,a,{skipStaticElements:!1}));let{output:n,height:u}=o.get();return{output:n,outputHeight:u,staticOutput:a?`${a.get().output}\n`:\"\"}}return{output:\"\",outputHeight:0,staticOutput:\"\"}}});var rwe=_((iVt,twe)=>{\"use strict\";var $Ce=ve(\"stream\"),ewe=[\"assert\",\"count\",\"countReset\",\"debug\",\"dir\",\"dirxml\",\"error\",\"group\",\"groupCollapsed\",\"groupEnd\",\"info\",\"log\",\"table\",\"time\",\"timeEnd\",\"timeLog\",\"trace\",\"warn\"],Z6={},aCt=t=>{let e=new $Ce.PassThrough,r=new $Ce.PassThrough;e.write=a=>t(\"stdout\",a),r.write=a=>t(\"stderr\",a);let o=new console.Console(e,r);for(let a of ewe)Z6[a]=console[a],console[a]=o[a];return()=>{for(let a of ewe)console[a]=Z6[a];Z6={}}};twe.exports=aCt});var eq=_($6=>{\"use strict\";Object.defineProperty($6,\"__esModule\",{value:!0});$6.default=new WeakMap});var rq=_(tq=>{\"use strict\";Object.defineProperty(tq,\"__esModule\",{value:!0});var lCt=an(),nwe=lCt.createContext({exit:()=>{}});nwe.displayName=\"InternalAppContext\";tq.default=nwe});var iq=_(nq=>{\"use strict\";Object.defineProperty(nq,\"__esModule\",{value:!0});var cCt=an(),iwe=cCt.createContext({stdin:void 0,setRawMode:()=>{},isRawModeSupported:!1,internal_exitOnCtrlC:!0});iwe.displayName=\"InternalStdinContext\";nq.default=iwe});var oq=_(sq=>{\"use strict\";Object.defineProperty(sq,\"__esModule\",{value:!0});var uCt=an(),swe=uCt.createContext({stdout:void 0,write:()=>{}});swe.displayName=\"InternalStdoutContext\";sq.default=swe});var lq=_(aq=>{\"use strict\";Object.defineProperty(aq,\"__esModule\",{value:!0});var ACt=an(),owe=ACt.createContext({stderr:void 0,write:()=>{}});owe.displayName=\"InternalStderrContext\";aq.default=owe});var Kk=_(cq=>{\"use strict\";Object.defineProperty(cq,\"__esModule\",{value:!0});var fCt=an(),awe=fCt.createContext({activeId:void 0,add:()=>{},remove:()=>{},activate:()=>{},deactivate:()=>{},enableFocus:()=>{},disableFocus:()=>{},focusNext:()=>{},focusPrevious:()=>{}});awe.displayName=\"InternalFocusContext\";cq.default=awe});var cwe=_((AVt,lwe)=>{\"use strict\";var pCt=/[|\\\\{}()[\\]^$+*?.-]/g;lwe.exports=t=>{if(typeof t!=\"string\")throw new TypeError(\"Expected a string\");return t.replace(pCt,\"\\\\$&\")}});var pwe=_((fVt,fwe)=>{\"use strict\";var hCt=cwe(),gCt=typeof process==\"object\"&&process&&typeof process.cwd==\"function\"?process.cwd():\".\",Awe=[].concat(ve(\"module\").builtinModules,\"bootstrap_node\",\"node\").map(t=>new RegExp(`(?:\\\\((?:node:)?${t}(?:\\\\.js)?:\\\\d+:\\\\d+\\\\)$|^\\\\s*at (?:node:)?${t}(?:\\\\.js)?:\\\\d+:\\\\d+$)`));Awe.push(/\\((?:node:)?internal\\/[^:]+:\\d+:\\d+\\)$/,/\\s*at (?:node:)?internal\\/[^:]+:\\d+:\\d+$/,/\\/\\.node-spawn-wrap-\\w+-\\w+\\/node:\\d+:\\d+\\)?$/);var uq=class t{constructor(e){e={ignoredPackages:[],...e},\"internals\"in e||(e.internals=t.nodeInternals()),\"cwd\"in e||(e.cwd=gCt),this._cwd=e.cwd.replace(/\\\\/g,\"/\"),this._internals=[].concat(e.internals,dCt(e.ignoredPackages)),this._wrapCallSite=e.wrapCallSite||!1}static nodeInternals(){return[...Awe]}clean(e,r=0){r=\" \".repeat(r),Array.isArray(e)||(e=e.split(`\n`)),!/^\\s*at /.test(e[0])&&/^\\s*at /.test(e[1])&&(e=e.slice(1));let o=!1,a=null,n=[];return e.forEach(u=>{if(u=u.replace(/\\\\/g,\"/\"),this._internals.some(p=>p.test(u)))return;let A=/^\\s*at /.test(u);o?u=u.trimEnd().replace(/^(\\s+)at /,\"$1\"):(u=u.trim(),A&&(u=u.slice(3))),u=u.replace(`${this._cwd}/`,\"\"),u&&(A?(a&&(n.push(a),a=null),n.push(u)):(o=!0,a=u))}),n.map(u=>`${r}${u}\n`).join(\"\")}captureString(e,r=this.captureString){typeof e==\"function\"&&(r=e,e=1/0);let{stackTraceLimit:o}=Error;e&&(Error.stackTraceLimit=e);let a={};Error.captureStackTrace(a,r);let{stack:n}=a;return Error.stackTraceLimit=o,this.clean(n)}capture(e,r=this.capture){typeof e==\"function\"&&(r=e,e=1/0);let{prepareStackTrace:o,stackTraceLimit:a}=Error;Error.prepareStackTrace=(A,p)=>this._wrapCallSite?p.map(this._wrapCallSite):p,e&&(Error.stackTraceLimit=e);let n={};Error.captureStackTrace(n,r);let{stack:u}=n;return Object.assign(Error,{prepareStackTrace:o,stackTraceLimit:a}),u}at(e=this.at){let[r]=this.capture(1,e);if(!r)return{};let o={line:r.getLineNumber(),column:r.getColumnNumber()};uwe(o,r.getFileName(),this._cwd),r.isConstructor()&&(o.constructor=!0),r.isEval()&&(o.evalOrigin=r.getEvalOrigin()),r.isNative()&&(o.native=!0);let a;try{a=r.getTypeName()}catch{}a&&a!==\"Object\"&&a!==\"[object Object]\"&&(o.type=a);let n=r.getFunctionName();n&&(o.function=n);let u=r.getMethodName();return u&&n!==u&&(o.method=u),o}parseLine(e){let r=e&&e.match(mCt);if(!r)return null;let o=r[1]===\"new\",a=r[2],n=r[3],u=r[4],A=Number(r[5]),p=Number(r[6]),h=r[7],E=r[8],I=r[9],v=r[10]===\"native\",x=r[11]===\")\",C,R={};if(E&&(R.line=Number(E)),I&&(R.column=Number(I)),x&&h){let L=0;for(let U=h.length-1;U>0;U--)if(h.charAt(U)===\")\")L++;else if(h.charAt(U)===\"(\"&&h.charAt(U-1)===\" \"&&(L--,L===-1&&h.charAt(U-1)===\" \")){let z=h.slice(0,U-1);h=h.slice(U+1),a+=` (${z}`;break}}if(a){let L=a.match(yCt);L&&(a=L[1],C=L[2])}return uwe(R,h,this._cwd),o&&(R.constructor=!0),n&&(R.evalOrigin=n,R.evalLine=A,R.evalColumn=p,R.evalFile=u&&u.replace(/\\\\/g,\"/\")),v&&(R.native=!0),a&&(R.function=a),C&&a!==C&&(R.method=C),R}};function uwe(t,e,r){e&&(e=e.replace(/\\\\/g,\"/\"),e.startsWith(`${r}/`)&&(e=e.slice(r.length+1)),t.file=e)}function dCt(t){if(t.length===0)return[];let e=t.map(r=>hCt(r));return new RegExp(`[/\\\\\\\\]node_modules[/\\\\\\\\](?:${e.join(\"|\")})[/\\\\\\\\][^:]+:\\\\d+:\\\\d+`)}var mCt=new RegExp(\"^(?:\\\\s*at )?(?:(new) )?(?:(.*?) \\\\()?(?:eval at ([^ ]+) \\\\((.+?):(\\\\d+):(\\\\d+)\\\\), )?(?:(.+?):(\\\\d+):(\\\\d+)|(native))(\\\\)?)$\"),yCt=/^(.*?) \\[as (.*?)\\]$/;fwe.exports=uq});var gwe=_((pVt,hwe)=>{\"use strict\";hwe.exports=(t,e)=>t.replace(/^\\t+/gm,r=>\" \".repeat(r.length*(e||2)))});var mwe=_((hVt,dwe)=>{\"use strict\";var ECt=gwe(),CCt=(t,e)=>{let r=[],o=t-e,a=t+e;for(let n=o;n<=a;n++)r.push(n);return r};dwe.exports=(t,e,r)=>{if(typeof t!=\"string\")throw new TypeError(\"Source code is missing.\");if(!e||e<1)throw new TypeError(\"Line number must start from `1`.\");if(t=ECt(t).split(/\\r?\\n/),!(e>t.length))return r={around:3,...r},CCt(e,r.around).filter(o=>t[o-1]!==void 0).map(o=>({line:o,value:t[o-1]}))}});var Vk=_(iu=>{\"use strict\";var wCt=iu&&iu.__createBinding||(Object.create?function(t,e,r,o){o===void 0&&(o=r),Object.defineProperty(t,o,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,o){o===void 0&&(o=r),t[o]=e[r]}),ICt=iu&&iu.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,\"default\",{enumerable:!0,value:e})}:function(t,e){t.default=e}),BCt=iu&&iu.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!==\"default\"&&Object.hasOwnProperty.call(t,r)&&wCt(e,t,r);return ICt(e,t),e},vCt=iu&&iu.__rest||function(t,e){var r={};for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.indexOf(o)<0&&(r[o]=t[o]);if(t!=null&&typeof Object.getOwnPropertySymbols==\"function\")for(var a=0,o=Object.getOwnPropertySymbols(t);a<o.length;a++)e.indexOf(o[a])<0&&Object.prototype.propertyIsEnumerable.call(t,o[a])&&(r[o[a]]=t[o[a]]);return r};Object.defineProperty(iu,\"__esModule\",{value:!0});var ywe=BCt(an()),Aq=ywe.forwardRef((t,e)=>{var{children:r}=t,o=vCt(t,[\"children\"]);let a=Object.assign(Object.assign({},o),{marginLeft:o.marginLeft||o.marginX||o.margin||0,marginRight:o.marginRight||o.marginX||o.margin||0,marginTop:o.marginTop||o.marginY||o.margin||0,marginBottom:o.marginBottom||o.marginY||o.margin||0,paddingLeft:o.paddingLeft||o.paddingX||o.padding||0,paddingRight:o.paddingRight||o.paddingX||o.padding||0,paddingTop:o.paddingTop||o.paddingY||o.padding||0,paddingBottom:o.paddingBottom||o.paddingY||o.padding||0});return ywe.default.createElement(\"ink-box\",{ref:e,style:a},r)});Aq.displayName=\"Box\";Aq.defaultProps={flexDirection:\"row\",flexGrow:0,flexShrink:1};iu.default=Aq});var hq=_(oB=>{\"use strict\";var fq=oB&&oB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(oB,\"__esModule\",{value:!0});var DCt=fq(an()),iC=fq(Yk()),Ewe=fq(W6()),pq=({color:t,backgroundColor:e,dimColor:r,bold:o,italic:a,underline:n,strikethrough:u,inverse:A,wrap:p,children:h})=>{if(h==null)return null;let E=I=>(r&&(I=iC.default.dim(I)),t&&(I=Ewe.default(I,t,\"foreground\")),e&&(I=Ewe.default(I,e,\"background\")),o&&(I=iC.default.bold(I)),a&&(I=iC.default.italic(I)),n&&(I=iC.default.underline(I)),u&&(I=iC.default.strikethrough(I)),A&&(I=iC.default.inverse(I)),I);return DCt.default.createElement(\"ink-text\",{style:{flexGrow:0,flexShrink:1,flexDirection:\"row\",textWrap:p},internal_transform:E},h)};pq.displayName=\"Text\";pq.defaultProps={dimColor:!1,bold:!1,italic:!1,underline:!1,strikethrough:!1,wrap:\"wrap\"};oB.default=pq});var Bwe=_(su=>{\"use strict\";var PCt=su&&su.__createBinding||(Object.create?function(t,e,r,o){o===void 0&&(o=r),Object.defineProperty(t,o,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,o){o===void 0&&(o=r),t[o]=e[r]}),bCt=su&&su.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,\"default\",{enumerable:!0,value:e})}:function(t,e){t.default=e}),SCt=su&&su.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!==\"default\"&&Object.hasOwnProperty.call(t,r)&&PCt(e,t,r);return bCt(e,t),e},aB=su&&su.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(su,\"__esModule\",{value:!0});var Cwe=SCt(ve(\"fs\")),hs=aB(an()),wwe=aB(pwe()),xCt=aB(mwe()),Vf=aB(Vk()),hA=aB(hq()),Iwe=new wwe.default({cwd:process.cwd(),internals:wwe.default.nodeInternals()}),kCt=({error:t})=>{let e=t.stack?t.stack.split(`\n`).slice(1):void 0,r=e?Iwe.parseLine(e[0]):void 0,o,a=0;if(r?.file&&r?.line&&Cwe.existsSync(r.file)){let n=Cwe.readFileSync(r.file,\"utf8\");if(o=xCt.default(n,r.line),o)for(let{line:u}of o)a=Math.max(a,String(u).length)}return hs.default.createElement(Vf.default,{flexDirection:\"column\",padding:1},hs.default.createElement(Vf.default,null,hs.default.createElement(hA.default,{backgroundColor:\"red\",color:\"white\"},\" \",\"ERROR\",\" \"),hs.default.createElement(hA.default,null,\" \",t.message)),r&&hs.default.createElement(Vf.default,{marginTop:1},hs.default.createElement(hA.default,{dimColor:!0},r.file,\":\",r.line,\":\",r.column)),r&&o&&hs.default.createElement(Vf.default,{marginTop:1,flexDirection:\"column\"},o.map(({line:n,value:u})=>hs.default.createElement(Vf.default,{key:n},hs.default.createElement(Vf.default,{width:a+1},hs.default.createElement(hA.default,{dimColor:n!==r.line,backgroundColor:n===r.line?\"red\":void 0,color:n===r.line?\"white\":void 0},String(n).padStart(a,\" \"),\":\")),hs.default.createElement(hA.default,{key:n,backgroundColor:n===r.line?\"red\":void 0,color:n===r.line?\"white\":void 0},\" \"+u)))),t.stack&&hs.default.createElement(Vf.default,{marginTop:1,flexDirection:\"column\"},t.stack.split(`\n`).slice(1).map(n=>{let u=Iwe.parseLine(n);return u?hs.default.createElement(Vf.default,{key:n},hs.default.createElement(hA.default,{dimColor:!0},\"- \"),hs.default.createElement(hA.default,{dimColor:!0,bold:!0},u.function),hs.default.createElement(hA.default,{dimColor:!0,color:\"gray\"},\" \",\"(\",u.file,\":\",u.line,\":\",u.column,\")\")):hs.default.createElement(Vf.default,{key:n},hs.default.createElement(hA.default,{dimColor:!0},\"- \"),hs.default.createElement(hA.default,{dimColor:!0,bold:!0},n))})))};su.default=kCt});var Dwe=_(ou=>{\"use strict\";var QCt=ou&&ou.__createBinding||(Object.create?function(t,e,r,o){o===void 0&&(o=r),Object.defineProperty(t,o,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,o){o===void 0&&(o=r),t[o]=e[r]}),FCt=ou&&ou.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,\"default\",{enumerable:!0,value:e})}:function(t,e){t.default=e}),RCt=ou&&ou.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!==\"default\"&&Object.hasOwnProperty.call(t,r)&&QCt(e,t,r);return FCt(e,t),e},$g=ou&&ou.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(ou,\"__esModule\",{value:!0});var Zg=RCt(an()),vwe=$g(u6()),TCt=$g(rq()),NCt=$g(iq()),LCt=$g(oq()),MCt=$g(lq()),OCt=$g(Kk()),UCt=$g(Bwe()),_Ct=\"\t\",HCt=\"\\x1B[Z\",qCt=\"\\x1B\",zk=class extends Zg.PureComponent{constructor(){super(...arguments),this.state={isFocusEnabled:!0,activeFocusId:void 0,focusables:[],error:void 0},this.rawModeEnabledCount=0,this.handleSetRawMode=e=>{let{stdin:r}=this.props;if(!this.isRawModeSupported())throw r===process.stdin?new Error(`Raw mode is not supported on the current process.stdin, which Ink uses as input stream by default.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`):new Error(`Raw mode is not supported on the stdin provided to Ink.\nRead about how to prevent this error on https://github.com/vadimdemedes/ink/#israwmodesupported`);if(r.setEncoding(\"utf8\"),e){this.rawModeEnabledCount===0&&(r.addListener(\"data\",this.handleInput),r.resume(),r.setRawMode(!0)),this.rawModeEnabledCount++;return}--this.rawModeEnabledCount===0&&(r.setRawMode(!1),r.removeListener(\"data\",this.handleInput),r.pause())},this.handleInput=e=>{e===\"\u0003\"&&this.props.exitOnCtrlC&&this.handleExit(),e===qCt&&this.state.activeFocusId&&this.setState({activeFocusId:void 0}),this.state.isFocusEnabled&&this.state.focusables.length>0&&(e===_Ct&&this.focusNext(),e===HCt&&this.focusPrevious())},this.handleExit=e=>{this.isRawModeSupported()&&this.handleSetRawMode(!1),this.props.onExit(e)},this.enableFocus=()=>{this.setState({isFocusEnabled:!0})},this.disableFocus=()=>{this.setState({isFocusEnabled:!1})},this.focusNext=()=>{this.setState(e=>{let r=e.focusables[0].id;return{activeFocusId:this.findNextFocusable(e)||r}})},this.focusPrevious=()=>{this.setState(e=>{let r=e.focusables[e.focusables.length-1].id;return{activeFocusId:this.findPreviousFocusable(e)||r}})},this.addFocusable=(e,{autoFocus:r})=>{this.setState(o=>{let a=o.activeFocusId;return!a&&r&&(a=e),{activeFocusId:a,focusables:[...o.focusables,{id:e,isActive:!0}]}})},this.removeFocusable=e=>{this.setState(r=>({activeFocusId:r.activeFocusId===e?void 0:r.activeFocusId,focusables:r.focusables.filter(o=>o.id!==e)}))},this.activateFocusable=e=>{this.setState(r=>({focusables:r.focusables.map(o=>o.id!==e?o:{id:e,isActive:!0})}))},this.deactivateFocusable=e=>{this.setState(r=>({activeFocusId:r.activeFocusId===e?void 0:r.activeFocusId,focusables:r.focusables.map(o=>o.id!==e?o:{id:e,isActive:!1})}))},this.findNextFocusable=e=>{let r=e.focusables.findIndex(o=>o.id===e.activeFocusId);for(let o=r+1;o<e.focusables.length;o++)if(e.focusables[o].isActive)return e.focusables[o].id},this.findPreviousFocusable=e=>{let r=e.focusables.findIndex(o=>o.id===e.activeFocusId);for(let o=r-1;o>=0;o--)if(e.focusables[o].isActive)return e.focusables[o].id}}static getDerivedStateFromError(e){return{error:e}}isRawModeSupported(){return this.props.stdin.isTTY}render(){return Zg.default.createElement(TCt.default.Provider,{value:{exit:this.handleExit}},Zg.default.createElement(NCt.default.Provider,{value:{stdin:this.props.stdin,setRawMode:this.handleSetRawMode,isRawModeSupported:this.isRawModeSupported(),internal_exitOnCtrlC:this.props.exitOnCtrlC}},Zg.default.createElement(LCt.default.Provider,{value:{stdout:this.props.stdout,write:this.props.writeToStdout}},Zg.default.createElement(MCt.default.Provider,{value:{stderr:this.props.stderr,write:this.props.writeToStderr}},Zg.default.createElement(OCt.default.Provider,{value:{activeId:this.state.activeFocusId,add:this.addFocusable,remove:this.removeFocusable,activate:this.activateFocusable,deactivate:this.deactivateFocusable,enableFocus:this.enableFocus,disableFocus:this.disableFocus,focusNext:this.focusNext,focusPrevious:this.focusPrevious}},this.state.error?Zg.default.createElement(UCt.default,{error:this.state.error}):this.props.children)))))}componentDidMount(){vwe.default.hide(this.props.stdout)}componentWillUnmount(){vwe.default.show(this.props.stdout),this.isRawModeSupported()&&this.handleSetRawMode(!1)}componentDidCatch(e){this.handleExit(e)}};ou.default=zk;zk.displayName=\"InternalApp\"});var Swe=_(au=>{\"use strict\";var jCt=au&&au.__createBinding||(Object.create?function(t,e,r,o){o===void 0&&(o=r),Object.defineProperty(t,o,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,o){o===void 0&&(o=r),t[o]=e[r]}),GCt=au&&au.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,\"default\",{enumerable:!0,value:e})}:function(t,e){t.default=e}),YCt=au&&au.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!==\"default\"&&Object.hasOwnProperty.call(t,r)&&jCt(e,t,r);return GCt(e,t),e},lu=au&&au.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(au,\"__esModule\",{value:!0});var WCt=lu(an()),Pwe=eO(),KCt=lu(pEe()),VCt=lu(s6()),zCt=lu(EEe()),JCt=lu(wEe()),gq=lu(hCe()),XCt=lu(ZCe()),ZCt=lu(c6()),$Ct=lu(rwe()),ewt=YCt(U6()),twt=lu(eq()),rwt=lu(Dwe()),sC=process.env.CI===\"false\"?!1:zCt.default,bwe=()=>{},dq=class{constructor(e){this.resolveExitPromise=()=>{},this.rejectExitPromise=()=>{},this.unsubscribeExit=()=>{},this.onRender=()=>{if(this.isUnmounted)return;let{output:r,outputHeight:o,staticOutput:a}=XCt.default(this.rootNode,this.options.stdout.columns||80),n=a&&a!==`\n`;if(this.options.debug){n&&(this.fullStaticOutput+=a),this.options.stdout.write(this.fullStaticOutput+r);return}if(sC){n&&this.options.stdout.write(a),this.lastOutput=r;return}if(n&&(this.fullStaticOutput+=a),o>=this.options.stdout.rows){this.options.stdout.write(VCt.default.clearTerminal+this.fullStaticOutput+r),this.lastOutput=r;return}n&&(this.log.clear(),this.options.stdout.write(a),this.log(r)),!n&&r!==this.lastOutput&&this.throttledLog(r),this.lastOutput=r},JCt.default(this),this.options=e,this.rootNode=ewt.createNode(\"ink-root\"),this.rootNode.onRender=e.debug?this.onRender:Pwe(this.onRender,32,{leading:!0,trailing:!0}),this.rootNode.onImmediateRender=this.onRender,this.log=KCt.default.create(e.stdout),this.throttledLog=e.debug?this.log:Pwe(this.log,void 0,{leading:!0,trailing:!0}),this.isUnmounted=!1,this.lastOutput=\"\",this.fullStaticOutput=\"\",this.container=gq.default.createContainer(this.rootNode,!1,!1),this.unsubscribeExit=ZCt.default(this.unmount,{alwaysLast:!1}),e.patchConsole&&this.patchConsole(),sC||(e.stdout.on(\"resize\",this.onRender),this.unsubscribeResize=()=>{e.stdout.off(\"resize\",this.onRender)})}render(e){let r=WCt.default.createElement(rwt.default,{stdin:this.options.stdin,stdout:this.options.stdout,stderr:this.options.stderr,writeToStdout:this.writeToStdout,writeToStderr:this.writeToStderr,exitOnCtrlC:this.options.exitOnCtrlC,onExit:this.unmount},e);gq.default.updateContainer(r,this.container,null,bwe)}writeToStdout(e){if(!this.isUnmounted){if(this.options.debug){this.options.stdout.write(e+this.fullStaticOutput+this.lastOutput);return}if(sC){this.options.stdout.write(e);return}this.log.clear(),this.options.stdout.write(e),this.log(this.lastOutput)}}writeToStderr(e){if(!this.isUnmounted){if(this.options.debug){this.options.stderr.write(e),this.options.stdout.write(this.fullStaticOutput+this.lastOutput);return}if(sC){this.options.stderr.write(e);return}this.log.clear(),this.options.stderr.write(e),this.log(this.lastOutput)}}unmount(e){this.isUnmounted||(this.onRender(),this.unsubscribeExit(),typeof this.restoreConsole==\"function\"&&this.restoreConsole(),typeof this.unsubscribeResize==\"function\"&&this.unsubscribeResize(),sC?this.options.stdout.write(this.lastOutput+`\n`):this.options.debug||this.log.done(),this.isUnmounted=!0,gq.default.updateContainer(null,this.container,null,bwe),twt.default.delete(this.options.stdout),e instanceof Error?this.rejectExitPromise(e):this.resolveExitPromise())}waitUntilExit(){return this.exitPromise||(this.exitPromise=new Promise((e,r)=>{this.resolveExitPromise=e,this.rejectExitPromise=r})),this.exitPromise}clear(){!sC&&!this.options.debug&&this.log.clear()}patchConsole(){this.options.debug||(this.restoreConsole=$Ct.default((e,r)=>{e===\"stdout\"&&this.writeToStdout(r),e===\"stderr\"&&(r.startsWith(\"The above error occurred\")||this.writeToStderr(r))}))}};au.default=dq});var kwe=_(lB=>{\"use strict\";var xwe=lB&&lB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(lB,\"__esModule\",{value:!0});var nwt=xwe(Swe()),Jk=xwe(eq()),iwt=ve(\"stream\"),swt=(t,e)=>{let r=Object.assign({stdout:process.stdout,stdin:process.stdin,stderr:process.stderr,debug:!1,exitOnCtrlC:!0,patchConsole:!0},owt(e)),o=awt(r.stdout,()=>new nwt.default(r));return o.render(t),{rerender:o.render,unmount:()=>o.unmount(),waitUntilExit:o.waitUntilExit,cleanup:()=>Jk.default.delete(r.stdout),clear:o.clear}};lB.default=swt;var owt=(t={})=>t instanceof iwt.Stream?{stdout:t,stdin:process.stdin}:t,awt=(t,e)=>{let r;return Jk.default.has(t)?r=Jk.default.get(t):(r=e(),Jk.default.set(t,r)),r}});var Fwe=_(zf=>{\"use strict\";var lwt=zf&&zf.__createBinding||(Object.create?function(t,e,r,o){o===void 0&&(o=r),Object.defineProperty(t,o,{enumerable:!0,get:function(){return e[r]}})}:function(t,e,r,o){o===void 0&&(o=r),t[o]=e[r]}),cwt=zf&&zf.__setModuleDefault||(Object.create?function(t,e){Object.defineProperty(t,\"default\",{enumerable:!0,value:e})}:function(t,e){t.default=e}),uwt=zf&&zf.__importStar||function(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)r!==\"default\"&&Object.hasOwnProperty.call(t,r)&&lwt(e,t,r);return cwt(e,t),e};Object.defineProperty(zf,\"__esModule\",{value:!0});var cB=uwt(an()),Qwe=t=>{let{items:e,children:r,style:o}=t,[a,n]=cB.useState(0),u=cB.useMemo(()=>e.slice(a),[e,a]);cB.useLayoutEffect(()=>{n(e.length)},[e.length]);let A=u.map((h,E)=>r(h,a+E)),p=cB.useMemo(()=>Object.assign({position:\"absolute\",flexDirection:\"column\"},o),[o]);return cB.default.createElement(\"ink-box\",{internal_static:!0,style:p},A)};Qwe.displayName=\"Static\";zf.default=Qwe});var Twe=_(uB=>{\"use strict\";var Awt=uB&&uB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(uB,\"__esModule\",{value:!0});var fwt=Awt(an()),Rwe=({children:t,transform:e})=>t==null?null:fwt.default.createElement(\"ink-text\",{style:{flexGrow:0,flexShrink:1,flexDirection:\"row\"},internal_transform:e},t);Rwe.displayName=\"Transform\";uB.default=Rwe});var Lwe=_(AB=>{\"use strict\";var pwt=AB&&AB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(AB,\"__esModule\",{value:!0});var hwt=pwt(an()),Nwe=({count:t=1})=>hwt.default.createElement(\"ink-text\",null,`\n`.repeat(t));Nwe.displayName=\"Newline\";AB.default=Nwe});var Uwe=_(fB=>{\"use strict\";var Mwe=fB&&fB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(fB,\"__esModule\",{value:!0});var gwt=Mwe(an()),dwt=Mwe(Vk()),Owe=()=>gwt.default.createElement(dwt.default,{flexGrow:1});Owe.displayName=\"Spacer\";fB.default=Owe});var Xk=_(pB=>{\"use strict\";var mwt=pB&&pB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(pB,\"__esModule\",{value:!0});var ywt=an(),Ewt=mwt(iq()),Cwt=()=>ywt.useContext(Ewt.default);pB.default=Cwt});var Hwe=_(hB=>{\"use strict\";var wwt=hB&&hB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(hB,\"__esModule\",{value:!0});var _we=an(),Iwt=wwt(Xk()),Bwt=(t,e={})=>{let{stdin:r,setRawMode:o,internal_exitOnCtrlC:a}=Iwt.default();_we.useEffect(()=>{if(e.isActive!==!1)return o(!0),()=>{o(!1)}},[e.isActive,o]),_we.useEffect(()=>{if(e.isActive===!1)return;let n=u=>{let A=String(u),p={upArrow:A===\"\\x1B[A\",downArrow:A===\"\\x1B[B\",leftArrow:A===\"\\x1B[D\",rightArrow:A===\"\\x1B[C\",pageDown:A===\"\\x1B[6~\",pageUp:A===\"\\x1B[5~\",return:A===\"\\r\",escape:A===\"\\x1B\",ctrl:!1,shift:!1,tab:A===\"\t\"||A===\"\\x1B[Z\",backspace:A===\"\\b\",delete:A===\"\\x7F\"||A===\"\\x1B[3~\",meta:!1};A<=\"\u001a\"&&!p.return&&(A=String.fromCharCode(A.charCodeAt(0)+97-1),p.ctrl=!0),A.startsWith(\"\\x1B\")&&(A=A.slice(1),p.meta=!0);let h=A>=\"A\"&&A<=\"Z\",E=A>=\"\\u0410\"&&A<=\"\\u042F\";A.length===1&&(h||E)&&(p.shift=!0),p.tab&&A===\"[Z\"&&(p.shift=!0),(p.tab||p.backspace||p.delete)&&(A=\"\"),(!(A===\"c\"&&p.ctrl)||!a)&&t(A,p)};return r?.on(\"data\",n),()=>{r?.off(\"data\",n)}},[e.isActive,r,a,t])};hB.default=Bwt});var qwe=_(gB=>{\"use strict\";var vwt=gB&&gB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(gB,\"__esModule\",{value:!0});var Dwt=an(),Pwt=vwt(rq()),bwt=()=>Dwt.useContext(Pwt.default);gB.default=bwt});var jwe=_(dB=>{\"use strict\";var Swt=dB&&dB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(dB,\"__esModule\",{value:!0});var xwt=an(),kwt=Swt(oq()),Qwt=()=>xwt.useContext(kwt.default);dB.default=Qwt});var Gwe=_(mB=>{\"use strict\";var Fwt=mB&&mB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(mB,\"__esModule\",{value:!0});var Rwt=an(),Twt=Fwt(lq()),Nwt=()=>Rwt.useContext(Twt.default);mB.default=Nwt});var Wwe=_(EB=>{\"use strict\";var Ywe=EB&&EB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(EB,\"__esModule\",{value:!0});var yB=an(),Lwt=Ywe(Kk()),Mwt=Ywe(Xk()),Owt=({isActive:t=!0,autoFocus:e=!1}={})=>{let{isRawModeSupported:r,setRawMode:o}=Mwt.default(),{activeId:a,add:n,remove:u,activate:A,deactivate:p}=yB.useContext(Lwt.default),h=yB.useMemo(()=>Math.random().toString().slice(2,7),[]);return yB.useEffect(()=>(n(h,{autoFocus:e}),()=>{u(h)}),[h,e]),yB.useEffect(()=>{t?A(h):p(h)},[t,h]),yB.useEffect(()=>{if(!(!r||!t))return o(!0),()=>{o(!1)}},[t]),{isFocused:!!h&&a===h}};EB.default=Owt});var Kwe=_(CB=>{\"use strict\";var Uwt=CB&&CB.__importDefault||function(t){return t&&t.__esModule?t:{default:t}};Object.defineProperty(CB,\"__esModule\",{value:!0});var _wt=an(),Hwt=Uwt(Kk()),qwt=()=>{let t=_wt.useContext(Hwt.default);return{enableFocus:t.enableFocus,disableFocus:t.disableFocus,focusNext:t.focusNext,focusPrevious:t.focusPrevious}};CB.default=qwt});var Vwe=_(mq=>{\"use strict\";Object.defineProperty(mq,\"__esModule\",{value:!0});mq.default=t=>{var e,r,o,a;return{width:(r=(e=t.yogaNode)===null||e===void 0?void 0:e.getComputedWidth())!==null&&r!==void 0?r:0,height:(a=(o=t.yogaNode)===null||o===void 0?void 0:o.getComputedHeight())!==null&&a!==void 0?a:0}}});var ic=_(ro=>{\"use strict\";Object.defineProperty(ro,\"__esModule\",{value:!0});var jwt=kwe();Object.defineProperty(ro,\"render\",{enumerable:!0,get:function(){return jwt.default}});var Gwt=Vk();Object.defineProperty(ro,\"Box\",{enumerable:!0,get:function(){return Gwt.default}});var Ywt=hq();Object.defineProperty(ro,\"Text\",{enumerable:!0,get:function(){return Ywt.default}});var Wwt=Fwe();Object.defineProperty(ro,\"Static\",{enumerable:!0,get:function(){return Wwt.default}});var Kwt=Twe();Object.defineProperty(ro,\"Transform\",{enumerable:!0,get:function(){return Kwt.default}});var Vwt=Lwe();Object.defineProperty(ro,\"Newline\",{enumerable:!0,get:function(){return Vwt.default}});var zwt=Uwe();Object.defineProperty(ro,\"Spacer\",{enumerable:!0,get:function(){return zwt.default}});var Jwt=Hwe();Object.defineProperty(ro,\"useInput\",{enumerable:!0,get:function(){return Jwt.default}});var Xwt=qwe();Object.defineProperty(ro,\"useApp\",{enumerable:!0,get:function(){return Xwt.default}});var Zwt=Xk();Object.defineProperty(ro,\"useStdin\",{enumerable:!0,get:function(){return Zwt.default}});var $wt=jwe();Object.defineProperty(ro,\"useStdout\",{enumerable:!0,get:function(){return $wt.default}});var eIt=Gwe();Object.defineProperty(ro,\"useStderr\",{enumerable:!0,get:function(){return eIt.default}});var tIt=Wwe();Object.defineProperty(ro,\"useFocus\",{enumerable:!0,get:function(){return tIt.default}});var rIt=Kwe();Object.defineProperty(ro,\"useFocusManager\",{enumerable:!0,get:function(){return rIt.default}});var nIt=Vwe();Object.defineProperty(ro,\"measureElement\",{enumerable:!0,get:function(){return nIt.default}})});var Eq={};Vt(Eq,{Gem:()=>yq});var zwe,ed,yq,Zk=Et(()=>{zwe=Ze(ic()),ed=Ze(an()),yq=(0,ed.memo)(({active:t})=>{let e=(0,ed.useMemo)(()=>t?\"\\u25C9\":\"\\u25EF\",[t]),r=(0,ed.useMemo)(()=>t?\"green\":\"yellow\",[t]);return ed.default.createElement(zwe.Text,{color:r},e)})});var Xwe={};Vt(Xwe,{useKeypress:()=>td});function td({active:t},e,r){let{stdin:o}=(0,Jwe.useStdin)(),a=(0,$k.useCallback)((n,u)=>e(n,u),r);(0,$k.useEffect)(()=>{if(!(!t||!o))return o.on(\"keypress\",a),()=>{o.off(\"keypress\",a)}},[t,a,o])}var Jwe,$k,wB=Et(()=>{Jwe=Ze(ic()),$k=Ze(an())});var $we={};Vt($we,{FocusRequest:()=>Zwe,useFocusRequest:()=>Cq});var Zwe,Cq,wq=Et(()=>{wB();Zwe=(r=>(r.BEFORE=\"before\",r.AFTER=\"after\",r))(Zwe||{}),Cq=function({active:t},e,r){td({active:t},(o,a)=>{a.name===\"tab\"&&(a.shift?e(\"before\"):e(\"after\"))},r)}});var eIe={};Vt(eIe,{useListInput:()=>IB});var IB,eQ=Et(()=>{wB();IB=function(t,e,{active:r,minus:o,plus:a,set:n,loop:u=!0}){td({active:r},(A,p)=>{let h=e.indexOf(t);switch(p.name){case o:{let E=h-1;if(u){n(e[(e.length+E)%e.length]);return}if(E<0)return;n(e[E])}break;case a:{let E=h+1;if(u){n(e[E%e.length]);return}if(E>=e.length)return;n(e[E])}break}},[e,t,a,n,u])}});var tQ={};Vt(tQ,{ScrollableItems:()=>iIt});var Lh,Oa,iIt,rQ=Et(()=>{Lh=Ze(ic()),Oa=Ze(an());wq();eQ();iIt=({active:t=!0,children:e=[],radius:r=10,size:o=1,loop:a=!0,onFocusRequest:n,willReachEnd:u})=>{let A=L=>{if(L.key===null)throw new Error(\"Expected all children to have a key\");return L.key},p=Oa.default.Children.map(e,L=>A(L)),h=p[0],[E,I]=(0,Oa.useState)(h),v=p.indexOf(E);(0,Oa.useEffect)(()=>{p.includes(E)||I(h)},[e]),(0,Oa.useEffect)(()=>{u&&v>=p.length-2&&u()},[v]),Cq({active:t&&!!n},L=>{n?.(L)},[n]),IB(E,p,{active:t,minus:\"up\",plus:\"down\",set:I,loop:a});let x=v-r,C=v+r;C>p.length&&(x-=C-p.length,C=p.length),x<0&&(C+=-x,x=0),C>=p.length&&(C=p.length-1);let R=[];for(let L=x;L<=C;++L){let U=p[L],z=t&&U===E;R.push(Oa.default.createElement(Lh.Box,{key:U,height:o},Oa.default.createElement(Lh.Box,{marginLeft:1,marginRight:1},Oa.default.createElement(Lh.Text,null,z?Oa.default.createElement(Lh.Text,{color:\"cyan\",bold:!0},\">\"):\" \")),Oa.default.createElement(Lh.Box,null,Oa.default.cloneElement(e[L],{active:z}))))}return Oa.default.createElement(Lh.Box,{flexDirection:\"column\",width:\"100%\"},R)}});var tIe,Jf,rIe,Iq,nIe,Bq=Et(()=>{tIe=Ze(ic()),Jf=Ze(an()),rIe=ve(\"readline\"),Iq=Jf.default.createContext(null),nIe=({children:t})=>{let{stdin:e,setRawMode:r}=(0,tIe.useStdin)();(0,Jf.useEffect)(()=>{r&&r(!0),e&&(0,rIe.emitKeypressEvents)(e)},[e,r]);let[o,a]=(0,Jf.useState)(new Map),n=(0,Jf.useMemo)(()=>({getAll:()=>o,get:u=>o.get(u),set:(u,A)=>a(new Map([...o,[u,A]]))}),[o,a]);return Jf.default.createElement(Iq.Provider,{value:n,children:t})}});var vq={};Vt(vq,{useMinistore:()=>sIt});function sIt(t,e){let r=(0,nQ.useContext)(Iq);if(r===null)throw new Error(\"Expected this hook to run with a ministore context attached\");if(typeof t>\"u\")return r.getAll();let o=(0,nQ.useCallback)(n=>{r.set(t,n)},[t,r.set]),a=r.get(t);return typeof a>\"u\"&&(a=e),[a,o]}var nQ,Dq=Et(()=>{nQ=Ze(an());Bq()});var sQ={};Vt(sQ,{renderForm:()=>oIt});async function oIt(t,e,{stdin:r,stdout:o,stderr:a}){let n,u=p=>{let{exit:h}=(0,iQ.useApp)();td({active:!0},(E,I)=>{I.name===\"return\"&&(n=p,h())},[h,p])},{waitUntilExit:A}=(0,iQ.render)(Pq.default.createElement(nIe,null,Pq.default.createElement(t,{...e,useSubmit:u})),{stdin:r,stdout:o,stderr:a});return await A(),n}var iQ,Pq,oQ=Et(()=>{iQ=Ze(ic()),Pq=Ze(an());Bq();wB()});var aIe=_(BB=>{\"use strict\";Object.defineProperty(BB,\"__esModule\",{value:!0});BB.UncontrolledTextInput=void 0;var sIe=an(),bq=an(),iIe=ic(),rd=Yk(),oIe=({value:t,placeholder:e=\"\",focus:r=!0,mask:o,highlightPastedText:a=!1,showCursor:n=!0,onChange:u,onSubmit:A})=>{let[{cursorOffset:p,cursorWidth:h},E]=bq.useState({cursorOffset:(t||\"\").length,cursorWidth:0});bq.useEffect(()=>{E(R=>{if(!r||!n)return R;let L=t||\"\";return R.cursorOffset>L.length-1?{cursorOffset:L.length,cursorWidth:0}:R})},[t,r,n]);let I=a?h:0,v=o?o.repeat(t.length):t,x=v,C=e?rd.grey(e):void 0;if(n&&r){C=e.length>0?rd.inverse(e[0])+rd.grey(e.slice(1)):rd.inverse(\" \"),x=v.length>0?\"\":rd.inverse(\" \");let R=0;for(let L of v)R>=p-I&&R<=p?x+=rd.inverse(L):x+=L,R++;v.length>0&&p===v.length&&(x+=rd.inverse(\" \"))}return iIe.useInput((R,L)=>{if(L.upArrow||L.downArrow||L.ctrl&&R===\"c\"||L.tab||L.shift&&L.tab)return;if(L.return){A&&A(t);return}let U=p,z=t,te=0;L.leftArrow?n&&U--:L.rightArrow?n&&U++:L.backspace||L.delete?p>0&&(z=t.slice(0,p-1)+t.slice(p,t.length),U--):(z=t.slice(0,p)+R+t.slice(p,t.length),U+=R.length,R.length>1&&(te=R.length)),p<0&&(U=0),p>t.length&&(U=t.length),E({cursorOffset:U,cursorWidth:te}),z!==t&&u(z)},{isActive:r}),sIe.createElement(iIe.Text,null,e?v.length>0?x:C:x)};BB.default=oIe;BB.UncontrolledTextInput=t=>{let[e,r]=bq.useState(\"\");return sIe.createElement(oIe,Object.assign({},t,{value:e,onChange:r}))}});var uIe={};Vt(uIe,{Pad:()=>Sq});var lIe,cIe,Sq,xq=Et(()=>{lIe=Ze(ic()),cIe=Ze(an()),Sq=({length:t,active:e})=>{if(t===0)return null;let r=t>1?` ${\"-\".repeat(t-1)}`:\" \";return cIe.default.createElement(lIe.Text,{dimColor:!e},r)}});var AIe={};Vt(AIe,{ItemOptions:()=>aIt});var DB,Mh,aIt,fIe=Et(()=>{DB=Ze(ic()),Mh=Ze(an());eQ();Zk();xq();aIt=function({active:t,skewer:e,options:r,value:o,onChange:a,sizes:n=[]}){let u=r.filter(({label:p})=>!!p).map(({value:p})=>p),A=r.findIndex(p=>p.value===o&&p.label!=\"\");return IB(o,u,{active:t,minus:\"left\",plus:\"right\",set:a}),Mh.default.createElement(Mh.default.Fragment,null,r.map(({label:p},h)=>{let E=h===A,I=n[h]-1||0,v=p.replace(/[\\u001b\\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g,\"\"),x=Math.max(0,I-v.length-2);return p?Mh.default.createElement(DB.Box,{key:p,width:I,marginLeft:1},Mh.default.createElement(DB.Text,{wrap:\"truncate\"},Mh.default.createElement(yq,{active:E}),\" \",p),e?Mh.default.createElement(Sq,{active:t,length:x}):null):Mh.default.createElement(DB.Box,{key:`spacer-${h}`,width:I,marginLeft:1})}))}});var bIe=_((rJt,PIe)=>{var Oq;PIe.exports=()=>(typeof Oq>\"u\"&&(Oq=ve(\"zlib\").brotliDecompressSync(Buffer.from(\"W+l+VsN2haE7Qar0V7bL054QhwxTNgT99Rj+mqLUkdu7oIz7CvRmL+I6141rGqqqaUllyExgpqUFgKn6/xUyh6GpUSDJkxp3dgyYUXCnuQzbaRlU7ug9w2B0VqnVZOEu5BF68ZBvXqWJceJG+FMmj4IhkOyQECcytimFV5zt7waXNFX/wn25BIkEkYSP2cN9+Ycl+oqk2om4On7J/g4CQp/03+vt+hx4rkG6bI9HfBvg5HYVDkUI2QQxB2vT59aQZ0zzaeZKsUXQ5rU3p5P5aVI3U8BKm5tRX9afRv5jW3afy+kNZdsEya8ZK2aEIYhtM+PUQnazaf3zeQVdQWyVTJkMW7heX94iQ2DXqZoA15w5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fjSHb+b2dDtq3wENG61ezbpwGSHc1bm2WuQZeAIys5S1sRPbiivk9LXEYjbtF8zclWxYl604rxtwdpmZj46zlSKgdCrXb1EReEZwG8cPJE1sznsqjQ0Y4vTnwSgpBA3xvoIYngEv1wkADRPRiM8XfbULh/yahhmeQM3TqFhhA7nG39WCpUHD5JIuVXohgpiZ+ij+aoKXW0sUe0KRHs0T49XnkaGeydgXdzB/y1ekBioVLtsehD7fQD9SwxFi9ZM2CENSqz17GGN8pdsyy0FoTdybsVSkVC5DZxRmFNl/hpYpQbGj6YVW7d3kvTSjYURzEa8SrRjL/5xJ6RfkqQJLHMwo1PDEv4irBiXTROyAVT6l1vFCM3aUlyEv06tOOh6oBBA1QVgu2uWktedWsVzTMfLVg/uO11fP/09i9ir6J8MKExJy/+Axt2B9M8WGWO2ivLMGQGoKIOVdWiWmavHlS9VzhykXT5qaJoSCT6uKeYCWK469EXha+N8itkzNILJFQCEjacBrSfOFQbkwQFJ1l3vE8u/s9ywC4vDov7KptVzQ0rprUT4QEZ2OsIaX7tOTPpC+DrCnDjkgBei7XIir3WcqAutptdh5EN2OFwiw3FgURV9z3i4gXShS8RVfffkQ1ThLsQi3pLpdy6X+cYQeszraB9cdG4gJkgwssdB2gXV8WdtcTD0zEGLl/G4O7RO7LP6ufuoYAWzL7YH+mzVS+xgjh3J1CSzz5I02Xw101cvaZc8bp2dgMIGJ4vysMTYQNcbL5TF087agcvUmSxFPbmVyPDmGaYRbzrFOra+/F3nIGD9p4Fzfz7Ezw+943D7zg/G38Pe7756NwCewD2BoV2Dc592dv7bjPVn1dTqbNHpF66D9ayyBIlJyekyDKtwePjHX+lJWLe996Ka7/OJaC0pyIcQGizBMSuniM8kDaAK5vhZmNTr+/8gEbaQe5r+J4HHmU20wl6IDK3wfN/HcW6Dpm04bnfAOZafxOm8Rsxr5KUnSQ=\",\"base64\")).toString()),Oq)});var VIe=_((bJt,KIe)=>{var Kq=Symbol(\"arg flag\"),sc=class t extends Error{constructor(e,r){super(e),this.name=\"ArgError\",this.code=r,Object.setPrototypeOf(this,t.prototype)}};function HB(t,{argv:e=process.argv.slice(2),permissive:r=!1,stopAtPositional:o=!1}={}){if(!t)throw new sc(\"argument specification object is required\",\"ARG_CONFIG_NO_SPEC\");let a={_:[]},n={},u={};for(let A of Object.keys(t)){if(!A)throw new sc(\"argument key cannot be an empty string\",\"ARG_CONFIG_EMPTY_KEY\");if(A[0]!==\"-\")throw new sc(`argument key must start with '-' but found: '${A}'`,\"ARG_CONFIG_NONOPT_KEY\");if(A.length===1)throw new sc(`argument key must have a name; singular '-' keys are not allowed: ${A}`,\"ARG_CONFIG_NONAME_KEY\");if(typeof t[A]==\"string\"){n[A]=t[A];continue}let p=t[A],h=!1;if(Array.isArray(p)&&p.length===1&&typeof p[0]==\"function\"){let[E]=p;p=(I,v,x=[])=>(x.push(E(I,v,x[x.length-1])),x),h=E===Boolean||E[Kq]===!0}else if(typeof p==\"function\")h=p===Boolean||p[Kq]===!0;else throw new sc(`type missing or not a function or valid array type: ${A}`,\"ARG_CONFIG_VAD_TYPE\");if(A[1]!==\"-\"&&A.length>2)throw new sc(`short argument keys (with a single hyphen) must have only one character: ${A}`,\"ARG_CONFIG_SHORTOPT_TOOLONG\");u[A]=[p,h]}for(let A=0,p=e.length;A<p;A++){let h=e[A];if(o&&a._.length>0){a._=a._.concat(e.slice(A));break}if(h===\"--\"){a._=a._.concat(e.slice(A+1));break}if(h.length>1&&h[0]===\"-\"){let E=h[1]===\"-\"||h.length===2?[h]:h.slice(1).split(\"\").map(I=>`-${I}`);for(let I=0;I<E.length;I++){let v=E[I],[x,C]=v[1]===\"-\"?v.split(/=(.*)/,2):[v,void 0],R=x;for(;R in n;)R=n[R];if(!(R in u))if(r){a._.push(v);continue}else throw new sc(`unknown or unexpected option: ${x}`,\"ARG_UNKNOWN_OPTION\");let[L,U]=u[R];if(!U&&I+1<E.length)throw new sc(`option requires argument (but was followed by another short argument): ${x}`,\"ARG_MISSING_REQUIRED_SHORTARG\");if(U)a[R]=L(!0,R,a[R]);else if(C===void 0){if(e.length<A+2||e[A+1].length>1&&e[A+1][0]===\"-\"&&!(e[A+1].match(/^-?\\d*(\\.(?=\\d))?\\d*$/)&&(L===Number||typeof BigInt<\"u\"&&L===BigInt))){let z=x===R?\"\":` (alias for ${R})`;throw new sc(`option requires argument: ${x}${z}`,\"ARG_MISSING_REQUIRED_LONGARG\")}a[R]=L(e[A+1],R,a[R]),++A}else a[R]=L(C,R,a[R])}}else a._.push(h)}return a}HB.flag=t=>(t[Kq]=!0,t);HB.COUNT=HB.flag((t,e,r)=>(r||0)+1);HB.ArgError=sc;KIe.exports=HB});var r1e=_((nXt,t1e)=>{var Xq;t1e.exports=()=>(typeof Xq>\"u\"&&(Xq=ve(\"zlib\").brotliDecompressSync(Buffer.from(\"W7YZIYrAeaAIofn/qpGBmjpZVwDLAvMwf4yXtBPC2k244urd2MomTN2aMogfZ4A7OVKdZytVrWdTrWmYxircma0wGjinrwi97kOIB/rfPvf++/N1nmkwua4pdU0vplRnJ8uTq4/IAsPFlgkUtfMXWn1Nm4s4/1OdO8sUK02YQ8V0UUTasGUTR54r1eZDT0Tg+dfNn2bSIN6Zw+V9selvZoGapDZBTNJtWlu8YiP8VAl4vuaHrmqbStPqWMGWi1ET+Wl8hECbrj9M79f7pp+KJEBcE6TKVEriNY6xXKgoIrpP3yOOwfyPgdESROE7cD251tzuvu9hZjDLwpDcErDkGhpVUc7ZLP5BvGEEUjaLZdHaf3p1wpI/ZW6ndipAYFTca6o+3B9iFWHICDGbsHGBmmPDDNvKKnyOtjGr2X7Xv2gIEIo0IUR9fyzr0RFHe+BekvwQ8A7azu4PX6uXTmr3kyZ3UxuE0AeEwE7s3f0LdIJcvAtlstfAn45Em6li+lMmn6NJtkeT0hrM6hZvhjO5NFsx6OvLtoz8vjLzBCE2tq38M2NRMff1r/HFdUdxSA4v2T8UzNbJfx16WEjKmYryX6bLx1Qi4KkviXx2b7rrUxmOfmjBZgdsdLqS9lR7Lqg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2dGnvpfbzPG4PhNeytzET4Ro2zS9QKCtBWB8Nmp3w41R2tXki5VajJjqfvNtKUPKbwWopbNQAnzu0A9E+u/3LeyukNDXcd0ZiF5iMroX9QtXMAMmyI/J1mQaJd9F5pb8xCiTOej5SKiciyILWMB6raNSfAnIMf3GWMSlyIYO7ssONgNaDTyCLTbgk0lHOuOCp8E8fFfscx/+KWTMpWLysdPfl/DdZhq8knTZ8lNX4vJZXDOy4wmgk0ZToY09zqovLVgKh6uBTCnZhAmV8BATno1QtFg2qLXiq6pKre3cSThQwdEnxCYaJZiBrIsJ+A95NLXHuFLGeWobtNr10IH/Z35+TrGxc9OCto6ZktgAkjP75M/Cz1YWMdQoABzq1dkmkA5U7gm/MSEW4Uy9+KDBdxtZm+pwiIwHcraaBSJgImm2oV9IyUo4wYXWUjwkwEYiNEzjkJw8S3FPvnBR1NuWQOiWQc3AjaZuvhJtEo5mck+daTk9PO+W2efl7FeJmv9qz71G3H/3q/4e4xNSlTCMAxa9sLYuk+AEy9XLt4puqzycsrLSi8jVWGL5QoJECvGDpZ5KOYrD88MY60/vp9nyrulyh6XkiKRA8+Qf8qK0SgBN0X/w2aJEj0A\",\"base64\")).toString()),Xq)});var a1e=_((nj,ij)=>{(function(t){nj&&typeof nj==\"object\"&&typeof ij<\"u\"?ij.exports=t():typeof define==\"function\"&&define.amd?define([],t):typeof window<\"u\"?window.isWindows=t():typeof global<\"u\"?global.isWindows=t():typeof self<\"u\"?self.isWindows=t():this.isWindows=t()})(function(){\"use strict\";return function(){return process&&(process.platform===\"win32\"||/^(msys|cygwin)$/.test(process.env.OSTYPE))}})});var A1e=_((tZt,u1e)=>{\"use strict\";sj.ifExists=i1t;var uC=ve(\"util\"),oc=ve(\"path\"),l1e=a1e(),t1t=/^#!\\s*(?:\\/usr\\/bin\\/env)?\\s*([^ \\t]+)(.*)$/,r1t={createPwshFile:!0,createCmdFile:l1e(),fs:ve(\"fs\")},n1t=new Map([[\".js\",\"node\"],[\".cjs\",\"node\"],[\".mjs\",\"node\"],[\".cmd\",\"cmd\"],[\".bat\",\"cmd\"],[\".ps1\",\"pwsh\"],[\".sh\",\"sh\"]]);function c1e(t){let e={...r1t,...t},r=e.fs;return e.fs_={chmod:r.chmod?uC.promisify(r.chmod):async()=>{},mkdir:uC.promisify(r.mkdir),readFile:uC.promisify(r.readFile),stat:uC.promisify(r.stat),unlink:uC.promisify(r.unlink),writeFile:uC.promisify(r.writeFile)},e}async function sj(t,e,r){let o=c1e(r);await o.fs_.stat(t),await o1t(t,e,o)}function i1t(t,e,r){return sj(t,e,r).catch(()=>{})}function s1t(t,e){return e.fs_.unlink(t).catch(()=>{})}async function o1t(t,e,r){let o=await A1t(t,r);return await a1t(e,r),l1t(t,e,o,r)}function a1t(t,e){return e.fs_.mkdir(oc.dirname(t),{recursive:!0})}function l1t(t,e,r,o){let a=c1e(o),n=[{generator:h1t,extension:\"\"}];return a.createCmdFile&&n.push({generator:p1t,extension:\".cmd\"}),a.createPwshFile&&n.push({generator:g1t,extension:\".ps1\"}),Promise.all(n.map(u=>f1t(t,e+u.extension,r,u.generator,a)))}function c1t(t,e){return s1t(t,e)}function u1t(t,e){return d1t(t,e)}async function A1t(t,e){let a=(await e.fs_.readFile(t,\"utf8\")).trim().split(/\\r*\\n/)[0].match(t1t);if(!a){let n=oc.extname(t).toLowerCase();return{program:n1t.get(n)||null,additionalArgs:\"\"}}return{program:a[1],additionalArgs:a[2]}}async function f1t(t,e,r,o,a){let n=a.preserveSymlinks?\"--preserve-symlinks\":\"\",u=[r.additionalArgs,n].filter(A=>A).join(\" \");return a=Object.assign({},a,{prog:r.program,args:u}),await c1t(e,a),await a.fs_.writeFile(e,o(t,e,a),\"utf8\"),u1t(e,a)}function p1t(t,e,r){let a=oc.relative(oc.dirname(e),t).split(\"/\").join(\"\\\\\"),n=oc.isAbsolute(a)?`\"${a}\"`:`\"%~dp0\\\\${a}\"`,u,A=r.prog,p=r.args||\"\",h=oj(r.nodePath).win32;A?(u=`\"%~dp0\\\\${A}.exe\"`,a=n):(A=n,p=\"\",a=\"\");let E=r.progArgs?`${r.progArgs.join(\" \")} `:\"\",I=h?`@SET NODE_PATH=${h}\\r\n`:\"\";return u?I+=`@IF EXIST ${u} (\\r\n  ${u} ${p} ${a} ${E}%*\\r\n) ELSE (\\r\n  @SETLOCAL\\r\n  @SET PATHEXT=%PATHEXT:;.JS;=;%\\r\n  ${A} ${p} ${a} ${E}%*\\r\n)\\r\n`:I+=`@${A} ${p} ${a} ${E}%*\\r\n`,I}function h1t(t,e,r){let o=oc.relative(oc.dirname(e),t),a=r.prog&&r.prog.split(\"\\\\\").join(\"/\"),n;o=o.split(\"\\\\\").join(\"/\");let u=oc.isAbsolute(o)?`\"${o}\"`:`\"$basedir/${o}\"`,A=r.args||\"\",p=oj(r.nodePath).posix;a?(n=`\"$basedir/${r.prog}\"`,o=u):(a=u,A=\"\",o=\"\");let h=r.progArgs?`${r.progArgs.join(\" \")} `:\"\",E=`#!/bin/sh\nbasedir=$(dirname \"$(echo \"$0\" | sed -e 's,\\\\\\\\,/,g')\")\n\ncase \\`uname\\` in\n    *CYGWIN*) basedir=\\`cygpath -w \"$basedir\"\\`;;\nesac\n\n`,I=r.nodePath?`export NODE_PATH=\"${p}\"\n`:\"\";return n?E+=`${I}if [ -x ${n} ]; then\n  exec ${n} ${A} ${o} ${h}\"$@\"\nelse\n  exec ${a} ${A} ${o} ${h}\"$@\"\nfi\n`:E+=`${I}${a} ${A} ${o} ${h}\"$@\"\nexit $?\n`,E}function g1t(t,e,r){let o=oc.relative(oc.dirname(e),t),a=r.prog&&r.prog.split(\"\\\\\").join(\"/\"),n=a&&`\"${a}$exe\"`,u;o=o.split(\"\\\\\").join(\"/\");let A=oc.isAbsolute(o)?`\"${o}\"`:`\"$basedir/${o}\"`,p=r.args||\"\",h=oj(r.nodePath),E=h.win32,I=h.posix;n?(u=`\"$basedir/${r.prog}$exe\"`,o=A):(n=A,p=\"\",o=\"\");let v=r.progArgs?`${r.progArgs.join(\" \")} `:\"\",x=`#!/usr/bin/env pwsh\n$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent\n\n$exe=\"\"\n${r.nodePath?`$env_node_path=$env:NODE_PATH\n$env:NODE_PATH=\"${E}\"\n`:\"\"}if ($PSVersionTable.PSVersion -lt \"6.0\" -or $IsWindows) {\n  # Fix case when both the Windows and Linux builds of Node\n  # are installed in the same directory\n  $exe=\".exe\"\n}`;return r.nodePath&&(x+=` else {\n  $env:NODE_PATH=\"${I}\"\n}`),u?x+=`\n$ret=0\nif (Test-Path ${u}) {\n  # Support pipeline input\n  if ($MyInvocation.ExpectingInput) {\n    $input | & ${u} ${p} ${o} ${v}$args\n  } else {\n    & ${u} ${p} ${o} ${v}$args\n  }\n  $ret=$LASTEXITCODE\n} else {\n  # Support pipeline input\n  if ($MyInvocation.ExpectingInput) {\n    $input | & ${n} ${p} ${o} ${v}$args\n  } else {\n    & ${n} ${p} ${o} ${v}$args\n  }\n  $ret=$LASTEXITCODE\n}\n${r.nodePath?`$env:NODE_PATH=$env_node_path\n`:\"\"}exit $ret\n`:x+=`\n# Support pipeline input\nif ($MyInvocation.ExpectingInput) {\n  $input | & ${n} ${p} ${o} ${v}$args\n} else {\n  & ${n} ${p} ${o} ${v}$args\n}\n${r.nodePath?`$env:NODE_PATH=$env_node_path\n`:\"\"}exit $LASTEXITCODE\n`,x}function d1t(t,e){return e.fs_.chmod(t,493)}function oj(t){if(!t)return{win32:\"\",posix:\"\"};let e=typeof t==\"string\"?t.split(oc.delimiter):Array.from(t),r={};for(let o=0;o<e.length;o++){let a=e[o].split(\"/\").join(\"\\\\\"),n=l1e()?e[o].split(\"\\\\\").join(\"/\").replace(/^([^:\\\\/]*):/,(u,A)=>`/mnt/${A.toLowerCase()}`):e[o];r.win32=r.win32?`${r.win32};${a}`:a,r.posix=r.posix?`${r.posix}:${n}`:n,r[o]={win32:a,posix:n}}return r}u1e.exports=sj});var Cj=_((I$t,Q1e)=>{Q1e.exports=ve(\"stream\")});var N1e=_((B$t,T1e)=>{\"use strict\";function F1e(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),r.push.apply(r,o)}return r}function j1t(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?F1e(Object(r),!0).forEach(function(o){G1t(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):F1e(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}function G1t(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}function Y1t(t,e){if(!(t instanceof e))throw new TypeError(\"Cannot call a class as a function\")}function R1e(t,e){for(var r=0;r<e.length;r++){var o=e[r];o.enumerable=o.enumerable||!1,o.configurable=!0,\"value\"in o&&(o.writable=!0),Object.defineProperty(t,o.key,o)}}function W1t(t,e,r){return e&&R1e(t.prototype,e),r&&R1e(t,r),t}var K1t=ve(\"buffer\"),yQ=K1t.Buffer,V1t=ve(\"util\"),wj=V1t.inspect,z1t=wj&&wj.custom||\"inspect\";function J1t(t,e,r){yQ.prototype.copy.call(t,e,r)}T1e.exports=function(){function t(){Y1t(this,t),this.head=null,this.tail=null,this.length=0}return W1t(t,[{key:\"push\",value:function(r){var o={data:r,next:null};this.length>0?this.tail.next=o:this.head=o,this.tail=o,++this.length}},{key:\"unshift\",value:function(r){var o={data:r,next:this.head};this.length===0&&(this.tail=o),this.head=o,++this.length}},{key:\"shift\",value:function(){if(this.length!==0){var r=this.head.data;return this.length===1?this.head=this.tail=null:this.head=this.head.next,--this.length,r}}},{key:\"clear\",value:function(){this.head=this.tail=null,this.length=0}},{key:\"join\",value:function(r){if(this.length===0)return\"\";for(var o=this.head,a=\"\"+o.data;o=o.next;)a+=r+o.data;return a}},{key:\"concat\",value:function(r){if(this.length===0)return yQ.alloc(0);for(var o=yQ.allocUnsafe(r>>>0),a=this.head,n=0;a;)J1t(a.data,o,n),n+=a.data.length,a=a.next;return o}},{key:\"consume\",value:function(r,o){var a;return r<this.head.data.length?(a=this.head.data.slice(0,r),this.head.data=this.head.data.slice(r)):r===this.head.data.length?a=this.shift():a=o?this._getString(r):this._getBuffer(r),a}},{key:\"first\",value:function(){return this.head.data}},{key:\"_getString\",value:function(r){var o=this.head,a=1,n=o.data;for(r-=n.length;o=o.next;){var u=o.data,A=r>u.length?u.length:r;if(A===u.length?n+=u:n+=u.slice(0,r),r-=A,r===0){A===u.length?(++a,o.next?this.head=o.next:this.head=this.tail=null):(this.head=o,o.data=u.slice(A));break}++a}return this.length-=a,n}},{key:\"_getBuffer\",value:function(r){var o=yQ.allocUnsafe(r),a=this.head,n=1;for(a.data.copy(o),r-=a.data.length;a=a.next;){var u=a.data,A=r>u.length?u.length:r;if(u.copy(o,o.length-r,0,A),r-=A,r===0){A===u.length?(++n,a.next?this.head=a.next:this.head=this.tail=null):(this.head=a,a.data=u.slice(A));break}++n}return this.length-=n,o}},{key:z1t,value:function(r,o){return wj(this,j1t({},o,{depth:0,customInspect:!1}))}}]),t}()});var Bj=_((v$t,M1e)=>{\"use strict\";function X1t(t,e){var r=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||a?(e?e(t):t&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(Ij,this,t)):process.nextTick(Ij,this,t)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(t||null,function(n){!e&&n?r._writableState?r._writableState.errorEmitted?process.nextTick(EQ,r):(r._writableState.errorEmitted=!0,process.nextTick(L1e,r,n)):process.nextTick(L1e,r,n):e?(process.nextTick(EQ,r),e(n)):process.nextTick(EQ,r)}),this)}function L1e(t,e){Ij(t,e),EQ(t)}function EQ(t){t._writableState&&!t._writableState.emitClose||t._readableState&&!t._readableState.emitClose||t.emit(\"close\")}function Z1t(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}function Ij(t,e){t.emit(\"error\",e)}function $1t(t,e){var r=t._readableState,o=t._writableState;r&&r.autoDestroy||o&&o.autoDestroy?t.destroy(e):t.emit(\"error\",e)}M1e.exports={destroy:X1t,undestroy:Z1t,errorOrDestroy:$1t}});var Gh=_((D$t,_1e)=>{\"use strict\";var U1e={};function lc(t,e,r){r||(r=Error);function o(n,u,A){return typeof e==\"string\"?e:e(n,u,A)}class a extends r{constructor(u,A,p){super(o(u,A,p))}}a.prototype.name=r.name,a.prototype.code=t,U1e[t]=a}function O1e(t,e){if(Array.isArray(t)){let r=t.length;return t=t.map(o=>String(o)),r>2?`one of ${e} ${t.slice(0,r-1).join(\", \")}, or `+t[r-1]:r===2?`one of ${e} ${t[0]} or ${t[1]}`:`of ${e} ${t[0]}`}else return`of ${e} ${String(t)}`}function e2t(t,e,r){return t.substr(!r||r<0?0:+r,e.length)===e}function t2t(t,e,r){return(r===void 0||r>t.length)&&(r=t.length),t.substring(r-e.length,r)===e}function r2t(t,e,r){return typeof r!=\"number\"&&(r=0),r+e.length>t.length?!1:t.indexOf(e,r)!==-1}lc(\"ERR_INVALID_OPT_VALUE\",function(t,e){return'The value \"'+e+'\" is invalid for option \"'+t+'\"'},TypeError);lc(\"ERR_INVALID_ARG_TYPE\",function(t,e,r){let o;typeof e==\"string\"&&e2t(e,\"not \")?(o=\"must not be\",e=e.replace(/^not /,\"\")):o=\"must be\";let a;if(t2t(t,\" argument\"))a=`The ${t} ${o} ${O1e(e,\"type\")}`;else{let n=r2t(t,\".\")?\"property\":\"argument\";a=`The \"${t}\" ${n} ${o} ${O1e(e,\"type\")}`}return a+=`. Received type ${typeof r}`,a},TypeError);lc(\"ERR_STREAM_PUSH_AFTER_EOF\",\"stream.push() after EOF\");lc(\"ERR_METHOD_NOT_IMPLEMENTED\",function(t){return\"The \"+t+\" method is not implemented\"});lc(\"ERR_STREAM_PREMATURE_CLOSE\",\"Premature close\");lc(\"ERR_STREAM_DESTROYED\",function(t){return\"Cannot call \"+t+\" after a stream was destroyed\"});lc(\"ERR_MULTIPLE_CALLBACK\",\"Callback called multiple times\");lc(\"ERR_STREAM_CANNOT_PIPE\",\"Cannot pipe, not readable\");lc(\"ERR_STREAM_WRITE_AFTER_END\",\"write after end\");lc(\"ERR_STREAM_NULL_VALUES\",\"May not write null values to stream\",TypeError);lc(\"ERR_UNKNOWN_ENCODING\",function(t){return\"Unknown encoding: \"+t},TypeError);lc(\"ERR_STREAM_UNSHIFT_AFTER_END_EVENT\",\"stream.unshift() after end event\");_1e.exports.codes=U1e});var vj=_((P$t,H1e)=>{\"use strict\";var n2t=Gh().codes.ERR_INVALID_OPT_VALUE;function i2t(t,e,r){return t.highWaterMark!=null?t.highWaterMark:e?t[r]:null}function s2t(t,e,r,o){var a=i2t(e,o,r);if(a!=null){if(!(isFinite(a)&&Math.floor(a)===a)||a<0){var n=o?r:\"highWaterMark\";throw new n2t(n,a)}return Math.floor(a)}return t.objectMode?16:16*1024}H1e.exports={getHighWaterMark:s2t}});var q1e=_((b$t,Dj)=>{typeof Object.create==\"function\"?Dj.exports=function(e,r){r&&(e.super_=r,e.prototype=Object.create(r.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:Dj.exports=function(e,r){if(r){e.super_=r;var o=function(){};o.prototype=r.prototype,e.prototype=new o,e.prototype.constructor=e}}});var Yh=_((S$t,bj)=>{try{if(Pj=ve(\"util\"),typeof Pj.inherits!=\"function\")throw\"\";bj.exports=Pj.inherits}catch{bj.exports=q1e()}var Pj});var G1e=_((x$t,j1e)=>{j1e.exports=ve(\"util\").deprecate});var kj=_((k$t,J1e)=>{\"use strict\";J1e.exports=Fi;function W1e(t){var e=this;this.next=null,this.entry=null,this.finish=function(){F2t(e,t)}}var gC;Fi.WritableState=$B;var o2t={deprecate:G1e()},K1e=Cj(),wQ=ve(\"buffer\").Buffer,a2t=global.Uint8Array||function(){};function l2t(t){return wQ.from(t)}function c2t(t){return wQ.isBuffer(t)||t instanceof a2t}var xj=Bj(),u2t=vj(),A2t=u2t.getHighWaterMark,Wh=Gh().codes,f2t=Wh.ERR_INVALID_ARG_TYPE,p2t=Wh.ERR_METHOD_NOT_IMPLEMENTED,h2t=Wh.ERR_MULTIPLE_CALLBACK,g2t=Wh.ERR_STREAM_CANNOT_PIPE,d2t=Wh.ERR_STREAM_DESTROYED,m2t=Wh.ERR_STREAM_NULL_VALUES,y2t=Wh.ERR_STREAM_WRITE_AFTER_END,E2t=Wh.ERR_UNKNOWN_ENCODING,dC=xj.errorOrDestroy;Yh()(Fi,K1e);function C2t(){}function $B(t,e,r){gC=gC||ld(),t=t||{},typeof r!=\"boolean\"&&(r=e instanceof gC),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.writableObjectMode),this.highWaterMark=A2t(this,t,\"writableHighWaterMark\",r),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=t.decodeStrings===!1;this.decodeStrings=!o,this.defaultEncoding=t.defaultEncoding||\"utf8\",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(a){b2t(e,a)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new W1e(this)}$B.prototype.getBuffer=function(){for(var e=this.bufferedRequest,r=[];e;)r.push(e),e=e.next;return r};(function(){try{Object.defineProperty($B.prototype,\"buffer\",{get:o2t.deprecate(function(){return this.getBuffer()},\"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.\",\"DEP0003\")})}catch{}})();var CQ;typeof Symbol==\"function\"&&Symbol.hasInstance&&typeof Function.prototype[Symbol.hasInstance]==\"function\"?(CQ=Function.prototype[Symbol.hasInstance],Object.defineProperty(Fi,Symbol.hasInstance,{value:function(e){return CQ.call(this,e)?!0:this!==Fi?!1:e&&e._writableState instanceof $B}})):CQ=function(e){return e instanceof this};function Fi(t){gC=gC||ld();var e=this instanceof gC;if(!e&&!CQ.call(Fi,this))return new Fi(t);this._writableState=new $B(t,this,e),this.writable=!0,t&&(typeof t.write==\"function\"&&(this._write=t.write),typeof t.writev==\"function\"&&(this._writev=t.writev),typeof t.destroy==\"function\"&&(this._destroy=t.destroy),typeof t.final==\"function\"&&(this._final=t.final)),K1e.call(this)}Fi.prototype.pipe=function(){dC(this,new g2t)};function w2t(t,e){var r=new y2t;dC(t,r),process.nextTick(e,r)}function I2t(t,e,r,o){var a;return r===null?a=new m2t:typeof r!=\"string\"&&!e.objectMode&&(a=new f2t(\"chunk\",[\"string\",\"Buffer\"],r)),a?(dC(t,a),process.nextTick(o,a),!1):!0}Fi.prototype.write=function(t,e,r){var o=this._writableState,a=!1,n=!o.objectMode&&c2t(t);return n&&!wQ.isBuffer(t)&&(t=l2t(t)),typeof e==\"function\"&&(r=e,e=null),n?e=\"buffer\":e||(e=o.defaultEncoding),typeof r!=\"function\"&&(r=C2t),o.ending?w2t(this,r):(n||I2t(this,o,t,r))&&(o.pendingcb++,a=v2t(this,o,n,t,e,r)),a};Fi.prototype.cork=function(){this._writableState.corked++};Fi.prototype.uncork=function(){var t=this._writableState;t.corked&&(t.corked--,!t.writing&&!t.corked&&!t.bufferProcessing&&t.bufferedRequest&&V1e(this,t))};Fi.prototype.setDefaultEncoding=function(e){if(typeof e==\"string\"&&(e=e.toLowerCase()),!([\"hex\",\"utf8\",\"utf-8\",\"ascii\",\"binary\",\"base64\",\"ucs2\",\"ucs-2\",\"utf16le\",\"utf-16le\",\"raw\"].indexOf((e+\"\").toLowerCase())>-1))throw new E2t(e);return this._writableState.defaultEncoding=e,this};Object.defineProperty(Fi.prototype,\"writableBuffer\",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});function B2t(t,e,r){return!t.objectMode&&t.decodeStrings!==!1&&typeof e==\"string\"&&(e=wQ.from(e,r)),e}Object.defineProperty(Fi.prototype,\"writableHighWaterMark\",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});function v2t(t,e,r,o,a,n){if(!r){var u=B2t(e,o,a);o!==u&&(r=!0,a=\"buffer\",o=u)}var A=e.objectMode?1:o.length;e.length+=A;var p=e.length<e.highWaterMark;if(p||(e.needDrain=!0),e.writing||e.corked){var h=e.lastBufferedRequest;e.lastBufferedRequest={chunk:o,encoding:a,isBuf:r,callback:n,next:null},h?h.next=e.lastBufferedRequest:e.bufferedRequest=e.lastBufferedRequest,e.bufferedRequestCount+=1}else Sj(t,e,!1,A,o,a,n);return p}function Sj(t,e,r,o,a,n,u){e.writelen=o,e.writecb=u,e.writing=!0,e.sync=!0,e.destroyed?e.onwrite(new d2t(\"write\")):r?t._writev(a,e.onwrite):t._write(a,n,e.onwrite),e.sync=!1}function D2t(t,e,r,o,a){--e.pendingcb,r?(process.nextTick(a,o),process.nextTick(ZB,t,e),t._writableState.errorEmitted=!0,dC(t,o)):(a(o),t._writableState.errorEmitted=!0,dC(t,o),ZB(t,e))}function P2t(t){t.writing=!1,t.writecb=null,t.length-=t.writelen,t.writelen=0}function b2t(t,e){var r=t._writableState,o=r.sync,a=r.writecb;if(typeof a!=\"function\")throw new h2t;if(P2t(r),e)D2t(t,r,o,e,a);else{var n=z1e(r)||t.destroyed;!n&&!r.corked&&!r.bufferProcessing&&r.bufferedRequest&&V1e(t,r),o?process.nextTick(Y1e,t,r,n,a):Y1e(t,r,n,a)}}function Y1e(t,e,r,o){r||S2t(t,e),e.pendingcb--,o(),ZB(t,e)}function S2t(t,e){e.length===0&&e.needDrain&&(e.needDrain=!1,t.emit(\"drain\"))}function V1e(t,e){e.bufferProcessing=!0;var r=e.bufferedRequest;if(t._writev&&r&&r.next){var o=e.bufferedRequestCount,a=new Array(o),n=e.corkedRequestsFree;n.entry=r;for(var u=0,A=!0;r;)a[u]=r,r.isBuf||(A=!1),r=r.next,u+=1;a.allBuffers=A,Sj(t,e,!0,e.length,a,\"\",n.finish),e.pendingcb++,e.lastBufferedRequest=null,n.next?(e.corkedRequestsFree=n.next,n.next=null):e.corkedRequestsFree=new W1e(e),e.bufferedRequestCount=0}else{for(;r;){var p=r.chunk,h=r.encoding,E=r.callback,I=e.objectMode?1:p.length;if(Sj(t,e,!1,I,p,h,E),r=r.next,e.bufferedRequestCount--,e.writing)break}r===null&&(e.lastBufferedRequest=null)}e.bufferedRequest=r,e.bufferProcessing=!1}Fi.prototype._write=function(t,e,r){r(new p2t(\"_write()\"))};Fi.prototype._writev=null;Fi.prototype.end=function(t,e,r){var o=this._writableState;return typeof t==\"function\"?(r=t,t=null,e=null):typeof e==\"function\"&&(r=e,e=null),t!=null&&this.write(t,e),o.corked&&(o.corked=1,this.uncork()),o.ending||Q2t(this,o,r),this};Object.defineProperty(Fi.prototype,\"writableLength\",{enumerable:!1,get:function(){return this._writableState.length}});function z1e(t){return t.ending&&t.length===0&&t.bufferedRequest===null&&!t.finished&&!t.writing}function x2t(t,e){t._final(function(r){e.pendingcb--,r&&dC(t,r),e.prefinished=!0,t.emit(\"prefinish\"),ZB(t,e)})}function k2t(t,e){!e.prefinished&&!e.finalCalled&&(typeof t._final==\"function\"&&!e.destroyed?(e.pendingcb++,e.finalCalled=!0,process.nextTick(x2t,t,e)):(e.prefinished=!0,t.emit(\"prefinish\")))}function ZB(t,e){var r=z1e(e);if(r&&(k2t(t,e),e.pendingcb===0&&(e.finished=!0,t.emit(\"finish\"),e.autoDestroy))){var o=t._readableState;(!o||o.autoDestroy&&o.endEmitted)&&t.destroy()}return r}function Q2t(t,e,r){e.ending=!0,ZB(t,e),r&&(e.finished?process.nextTick(r):t.once(\"finish\",r)),e.ended=!0,t.writable=!1}function F2t(t,e,r){var o=t.entry;for(t.entry=null;o;){var a=o.callback;e.pendingcb--,a(r),o=o.next}e.corkedRequestsFree.next=t}Object.defineProperty(Fi.prototype,\"destroyed\",{enumerable:!1,get:function(){return this._writableState===void 0?!1:this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}});Fi.prototype.destroy=xj.destroy;Fi.prototype._undestroy=xj.undestroy;Fi.prototype._destroy=function(t,e){e(t)}});var ld=_((Q$t,Z1e)=>{\"use strict\";var R2t=Object.keys||function(t){var e=[];for(var r in t)e.push(r);return e};Z1e.exports=yA;var X1e=Rj(),Fj=kj();Yh()(yA,X1e);for(Qj=R2t(Fj.prototype),IQ=0;IQ<Qj.length;IQ++)BQ=Qj[IQ],yA.prototype[BQ]||(yA.prototype[BQ]=Fj.prototype[BQ]);var Qj,BQ,IQ;function yA(t){if(!(this instanceof yA))return new yA(t);X1e.call(this,t),Fj.call(this,t),this.allowHalfOpen=!0,t&&(t.readable===!1&&(this.readable=!1),t.writable===!1&&(this.writable=!1),t.allowHalfOpen===!1&&(this.allowHalfOpen=!1,this.once(\"end\",T2t)))}Object.defineProperty(yA.prototype,\"writableHighWaterMark\",{enumerable:!1,get:function(){return this._writableState.highWaterMark}});Object.defineProperty(yA.prototype,\"writableBuffer\",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}});Object.defineProperty(yA.prototype,\"writableLength\",{enumerable:!1,get:function(){return this._writableState.length}});function T2t(){this._writableState.ended||process.nextTick(N2t,this)}function N2t(t){t.end()}Object.defineProperty(yA.prototype,\"destroyed\",{enumerable:!1,get:function(){return this._readableState===void 0||this._writableState===void 0?!1:this._readableState.destroyed&&this._writableState.destroyed},set:function(e){this._readableState===void 0||this._writableState===void 0||(this._readableState.destroyed=e,this._writableState.destroyed=e)}})});var t2e=_((Tj,e2e)=>{var vQ=ve(\"buffer\"),rp=vQ.Buffer;function $1e(t,e){for(var r in t)e[r]=t[r]}rp.from&&rp.alloc&&rp.allocUnsafe&&rp.allocUnsafeSlow?e2e.exports=vQ:($1e(vQ,Tj),Tj.Buffer=mC);function mC(t,e,r){return rp(t,e,r)}$1e(rp,mC);mC.from=function(t,e,r){if(typeof t==\"number\")throw new TypeError(\"Argument must not be a number\");return rp(t,e,r)};mC.alloc=function(t,e,r){if(typeof t!=\"number\")throw new TypeError(\"Argument must be a number\");var o=rp(t);return e!==void 0?typeof r==\"string\"?o.fill(e,r):o.fill(e):o.fill(0),o};mC.allocUnsafe=function(t){if(typeof t!=\"number\")throw new TypeError(\"Argument must be a number\");return rp(t)};mC.allocUnsafeSlow=function(t){if(typeof t!=\"number\")throw new TypeError(\"Argument must be a number\");return vQ.SlowBuffer(t)}});var Mj=_(n2e=>{\"use strict\";var Lj=t2e().Buffer,r2e=Lj.isEncoding||function(t){switch(t=\"\"+t,t&&t.toLowerCase()){case\"hex\":case\"utf8\":case\"utf-8\":case\"ascii\":case\"binary\":case\"base64\":case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":case\"raw\":return!0;default:return!1}};function L2t(t){if(!t)return\"utf8\";for(var e;;)switch(t){case\"utf8\":case\"utf-8\":return\"utf8\";case\"ucs2\":case\"ucs-2\":case\"utf16le\":case\"utf-16le\":return\"utf16le\";case\"latin1\":case\"binary\":return\"latin1\";case\"base64\":case\"ascii\":case\"hex\":return t;default:if(e)return;t=(\"\"+t).toLowerCase(),e=!0}}function M2t(t){var e=L2t(t);if(typeof e!=\"string\"&&(Lj.isEncoding===r2e||!r2e(t)))throw new Error(\"Unknown encoding: \"+t);return e||t}n2e.StringDecoder=ev;function ev(t){this.encoding=M2t(t);var e;switch(this.encoding){case\"utf16le\":this.text=j2t,this.end=G2t,e=4;break;case\"utf8\":this.fillLast=_2t,e=4;break;case\"base64\":this.text=Y2t,this.end=W2t,e=3;break;default:this.write=K2t,this.end=V2t;return}this.lastNeed=0,this.lastTotal=0,this.lastChar=Lj.allocUnsafe(e)}ev.prototype.write=function(t){if(t.length===0)return\"\";var e,r;if(this.lastNeed){if(e=this.fillLast(t),e===void 0)return\"\";r=this.lastNeed,this.lastNeed=0}else r=0;return r<t.length?e?e+this.text(t,r):this.text(t,r):e||\"\"};ev.prototype.end=q2t;ev.prototype.text=H2t;ev.prototype.fillLast=function(t){if(this.lastNeed<=t.length)return t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,this.lastTotal-this.lastNeed,0,t.length),this.lastNeed-=t.length};function Nj(t){return t<=127?0:t>>5===6?2:t>>4===14?3:t>>3===30?4:t>>6===2?-1:-2}function O2t(t,e,r){var o=e.length-1;if(o<r)return 0;var a=Nj(e[o]);return a>=0?(a>0&&(t.lastNeed=a-1),a):--o<r||a===-2?0:(a=Nj(e[o]),a>=0?(a>0&&(t.lastNeed=a-2),a):--o<r||a===-2?0:(a=Nj(e[o]),a>=0?(a>0&&(a===2?a=0:t.lastNeed=a-3),a):0))}function U2t(t,e,r){if((e[0]&192)!==128)return t.lastNeed=0,\"\\uFFFD\";if(t.lastNeed>1&&e.length>1){if((e[1]&192)!==128)return t.lastNeed=1,\"\\uFFFD\";if(t.lastNeed>2&&e.length>2&&(e[2]&192)!==128)return t.lastNeed=2,\"\\uFFFD\"}}function _2t(t){var e=this.lastTotal-this.lastNeed,r=U2t(this,t,e);if(r!==void 0)return r;if(this.lastNeed<=t.length)return t.copy(this.lastChar,e,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);t.copy(this.lastChar,e,0,t.length),this.lastNeed-=t.length}function H2t(t,e){var r=O2t(this,t,e);if(!this.lastNeed)return t.toString(\"utf8\",e);this.lastTotal=r;var o=t.length-(r-this.lastNeed);return t.copy(this.lastChar,0,o),t.toString(\"utf8\",e,o)}function q2t(t){var e=t&&t.length?this.write(t):\"\";return this.lastNeed?e+\"\\uFFFD\":e}function j2t(t,e){if((t.length-e)%2===0){var r=t.toString(\"utf16le\",e);if(r){var o=r.charCodeAt(r.length-1);if(o>=55296&&o<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1],r.slice(0,-1)}return r}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=t[t.length-1],t.toString(\"utf16le\",e,t.length-1)}function G2t(t){var e=t&&t.length?this.write(t):\"\";if(this.lastNeed){var r=this.lastTotal-this.lastNeed;return e+this.lastChar.toString(\"utf16le\",0,r)}return e}function Y2t(t,e){var r=(t.length-e)%3;return r===0?t.toString(\"base64\",e):(this.lastNeed=3-r,this.lastTotal=3,r===1?this.lastChar[0]=t[t.length-1]:(this.lastChar[0]=t[t.length-2],this.lastChar[1]=t[t.length-1]),t.toString(\"base64\",e,t.length-r))}function W2t(t){var e=t&&t.length?this.write(t):\"\";return this.lastNeed?e+this.lastChar.toString(\"base64\",0,3-this.lastNeed):e}function K2t(t){return t.toString(this.encoding)}function V2t(t){return t&&t.length?this.write(t):\"\"}});var DQ=_((R$t,o2e)=>{\"use strict\";var i2e=Gh().codes.ERR_STREAM_PREMATURE_CLOSE;function z2t(t){var e=!1;return function(){if(!e){e=!0;for(var r=arguments.length,o=new Array(r),a=0;a<r;a++)o[a]=arguments[a];t.apply(this,o)}}}function J2t(){}function X2t(t){return t.setHeader&&typeof t.abort==\"function\"}function s2e(t,e,r){if(typeof e==\"function\")return s2e(t,null,e);e||(e={}),r=z2t(r||J2t);var o=e.readable||e.readable!==!1&&t.readable,a=e.writable||e.writable!==!1&&t.writable,n=function(){t.writable||A()},u=t._writableState&&t._writableState.finished,A=function(){a=!1,u=!0,o||r.call(t)},p=t._readableState&&t._readableState.endEmitted,h=function(){o=!1,p=!0,a||r.call(t)},E=function(C){r.call(t,C)},I=function(){var C;if(o&&!p)return(!t._readableState||!t._readableState.ended)&&(C=new i2e),r.call(t,C);if(a&&!u)return(!t._writableState||!t._writableState.ended)&&(C=new i2e),r.call(t,C)},v=function(){t.req.on(\"finish\",A)};return X2t(t)?(t.on(\"complete\",A),t.on(\"abort\",I),t.req?v():t.on(\"request\",v)):a&&!t._writableState&&(t.on(\"end\",n),t.on(\"close\",n)),t.on(\"end\",h),t.on(\"finish\",A),e.error!==!1&&t.on(\"error\",E),t.on(\"close\",I),function(){t.removeListener(\"complete\",A),t.removeListener(\"abort\",I),t.removeListener(\"request\",v),t.req&&t.req.removeListener(\"finish\",A),t.removeListener(\"end\",n),t.removeListener(\"close\",n),t.removeListener(\"finish\",A),t.removeListener(\"end\",h),t.removeListener(\"error\",E),t.removeListener(\"close\",I)}}o2e.exports=s2e});var l2e=_((T$t,a2e)=>{\"use strict\";var PQ;function Kh(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}var Z2t=DQ(),Vh=Symbol(\"lastResolve\"),cd=Symbol(\"lastReject\"),tv=Symbol(\"error\"),bQ=Symbol(\"ended\"),ud=Symbol(\"lastPromise\"),Oj=Symbol(\"handlePromise\"),Ad=Symbol(\"stream\");function zh(t,e){return{value:t,done:e}}function $2t(t){var e=t[Vh];if(e!==null){var r=t[Ad].read();r!==null&&(t[ud]=null,t[Vh]=null,t[cd]=null,e(zh(r,!1)))}}function eBt(t){process.nextTick($2t,t)}function tBt(t,e){return function(r,o){t.then(function(){if(e[bQ]){r(zh(void 0,!0));return}e[Oj](r,o)},o)}}var rBt=Object.getPrototypeOf(function(){}),nBt=Object.setPrototypeOf((PQ={get stream(){return this[Ad]},next:function(){var e=this,r=this[tv];if(r!==null)return Promise.reject(r);if(this[bQ])return Promise.resolve(zh(void 0,!0));if(this[Ad].destroyed)return new Promise(function(u,A){process.nextTick(function(){e[tv]?A(e[tv]):u(zh(void 0,!0))})});var o=this[ud],a;if(o)a=new Promise(tBt(o,this));else{var n=this[Ad].read();if(n!==null)return Promise.resolve(zh(n,!1));a=new Promise(this[Oj])}return this[ud]=a,a}},Kh(PQ,Symbol.asyncIterator,function(){return this}),Kh(PQ,\"return\",function(){var e=this;return new Promise(function(r,o){e[Ad].destroy(null,function(a){if(a){o(a);return}r(zh(void 0,!0))})})}),PQ),rBt),iBt=function(e){var r,o=Object.create(nBt,(r={},Kh(r,Ad,{value:e,writable:!0}),Kh(r,Vh,{value:null,writable:!0}),Kh(r,cd,{value:null,writable:!0}),Kh(r,tv,{value:null,writable:!0}),Kh(r,bQ,{value:e._readableState.endEmitted,writable:!0}),Kh(r,Oj,{value:function(n,u){var A=o[Ad].read();A?(o[ud]=null,o[Vh]=null,o[cd]=null,n(zh(A,!1))):(o[Vh]=n,o[cd]=u)},writable:!0}),r));return o[ud]=null,Z2t(e,function(a){if(a&&a.code!==\"ERR_STREAM_PREMATURE_CLOSE\"){var n=o[cd];n!==null&&(o[ud]=null,o[Vh]=null,o[cd]=null,n(a)),o[tv]=a;return}var u=o[Vh];u!==null&&(o[ud]=null,o[Vh]=null,o[cd]=null,u(zh(void 0,!0))),o[bQ]=!0}),e.on(\"readable\",eBt.bind(null,o)),o};a2e.exports=iBt});var f2e=_((N$t,A2e)=>{\"use strict\";function c2e(t,e,r,o,a,n,u){try{var A=t[n](u),p=A.value}catch(h){r(h);return}A.done?e(p):Promise.resolve(p).then(o,a)}function sBt(t){return function(){var e=this,r=arguments;return new Promise(function(o,a){var n=t.apply(e,r);function u(p){c2e(n,o,a,u,A,\"next\",p)}function A(p){c2e(n,o,a,u,A,\"throw\",p)}u(void 0)})}}function u2e(t,e){var r=Object.keys(t);if(Object.getOwnPropertySymbols){var o=Object.getOwnPropertySymbols(t);e&&(o=o.filter(function(a){return Object.getOwnPropertyDescriptor(t,a).enumerable})),r.push.apply(r,o)}return r}function oBt(t){for(var e=1;e<arguments.length;e++){var r=arguments[e]!=null?arguments[e]:{};e%2?u2e(Object(r),!0).forEach(function(o){aBt(t,o,r[o])}):Object.getOwnPropertyDescriptors?Object.defineProperties(t,Object.getOwnPropertyDescriptors(r)):u2e(Object(r)).forEach(function(o){Object.defineProperty(t,o,Object.getOwnPropertyDescriptor(r,o))})}return t}function aBt(t,e,r){return e in t?Object.defineProperty(t,e,{value:r,enumerable:!0,configurable:!0,writable:!0}):t[e]=r,t}var lBt=Gh().codes.ERR_INVALID_ARG_TYPE;function cBt(t,e,r){var o;if(e&&typeof e.next==\"function\")o=e;else if(e&&e[Symbol.asyncIterator])o=e[Symbol.asyncIterator]();else if(e&&e[Symbol.iterator])o=e[Symbol.iterator]();else throw new lBt(\"iterable\",[\"Iterable\"],e);var a=new t(oBt({objectMode:!0},r)),n=!1;a._read=function(){n||(n=!0,u())};function u(){return A.apply(this,arguments)}function A(){return A=sBt(function*(){try{var p=yield o.next(),h=p.value,E=p.done;E?a.push(null):a.push(yield h)?u():n=!1}catch(I){a.destroy(I)}}),A.apply(this,arguments)}return a}A2e.exports=cBt});var Rj=_((M$t,I2e)=>{\"use strict\";I2e.exports=mn;var yC;mn.ReadableState=d2e;var L$t=ve(\"events\").EventEmitter,g2e=function(e,r){return e.listeners(r).length},nv=Cj(),SQ=ve(\"buffer\").Buffer,uBt=global.Uint8Array||function(){};function ABt(t){return SQ.from(t)}function fBt(t){return SQ.isBuffer(t)||t instanceof uBt}var Uj=ve(\"util\"),en;Uj&&Uj.debuglog?en=Uj.debuglog(\"stream\"):en=function(){};var pBt=N1e(),Wj=Bj(),hBt=vj(),gBt=hBt.getHighWaterMark,xQ=Gh().codes,dBt=xQ.ERR_INVALID_ARG_TYPE,mBt=xQ.ERR_STREAM_PUSH_AFTER_EOF,yBt=xQ.ERR_METHOD_NOT_IMPLEMENTED,EBt=xQ.ERR_STREAM_UNSHIFT_AFTER_END_EVENT,EC,_j,Hj;Yh()(mn,nv);var rv=Wj.errorOrDestroy,qj=[\"error\",\"close\",\"destroy\",\"pause\",\"resume\"];function CBt(t,e,r){if(typeof t.prependListener==\"function\")return t.prependListener(e,r);!t._events||!t._events[e]?t.on(e,r):Array.isArray(t._events[e])?t._events[e].unshift(r):t._events[e]=[r,t._events[e]]}function d2e(t,e,r){yC=yC||ld(),t=t||{},typeof r!=\"boolean\"&&(r=e instanceof yC),this.objectMode=!!t.objectMode,r&&(this.objectMode=this.objectMode||!!t.readableObjectMode),this.highWaterMark=gBt(this,t,\"readableHighWaterMark\",r),this.buffer=new pBt,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=t.emitClose!==!1,this.autoDestroy=!!t.autoDestroy,this.destroyed=!1,this.defaultEncoding=t.defaultEncoding||\"utf8\",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,t.encoding&&(EC||(EC=Mj().StringDecoder),this.decoder=new EC(t.encoding),this.encoding=t.encoding)}function mn(t){if(yC=yC||ld(),!(this instanceof mn))return new mn(t);var e=this instanceof yC;this._readableState=new d2e(t,this,e),this.readable=!0,t&&(typeof t.read==\"function\"&&(this._read=t.read),typeof t.destroy==\"function\"&&(this._destroy=t.destroy)),nv.call(this)}Object.defineProperty(mn.prototype,\"destroyed\",{enumerable:!1,get:function(){return this._readableState===void 0?!1:this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}});mn.prototype.destroy=Wj.destroy;mn.prototype._undestroy=Wj.undestroy;mn.prototype._destroy=function(t,e){e(t)};mn.prototype.push=function(t,e){var r=this._readableState,o;return r.objectMode?o=!0:typeof t==\"string\"&&(e=e||r.defaultEncoding,e!==r.encoding&&(t=SQ.from(t,e),e=\"\"),o=!0),m2e(this,t,e,!1,o)};mn.prototype.unshift=function(t){return m2e(this,t,null,!0,!1)};function m2e(t,e,r,o,a){en(\"readableAddChunk\",e);var n=t._readableState;if(e===null)n.reading=!1,BBt(t,n);else{var u;if(a||(u=wBt(n,e)),u)rv(t,u);else if(n.objectMode||e&&e.length>0)if(typeof e!=\"string\"&&!n.objectMode&&Object.getPrototypeOf(e)!==SQ.prototype&&(e=ABt(e)),o)n.endEmitted?rv(t,new EBt):jj(t,n,e,!0);else if(n.ended)rv(t,new mBt);else{if(n.destroyed)return!1;n.reading=!1,n.decoder&&!r?(e=n.decoder.write(e),n.objectMode||e.length!==0?jj(t,n,e,!1):Yj(t,n)):jj(t,n,e,!1)}else o||(n.reading=!1,Yj(t,n))}return!n.ended&&(n.length<n.highWaterMark||n.length===0)}function jj(t,e,r,o){e.flowing&&e.length===0&&!e.sync?(e.awaitDrain=0,t.emit(\"data\",r)):(e.length+=e.objectMode?1:r.length,o?e.buffer.unshift(r):e.buffer.push(r),e.needReadable&&kQ(t)),Yj(t,e)}function wBt(t,e){var r;return!fBt(e)&&typeof e!=\"string\"&&e!==void 0&&!t.objectMode&&(r=new dBt(\"chunk\",[\"string\",\"Buffer\",\"Uint8Array\"],e)),r}mn.prototype.isPaused=function(){return this._readableState.flowing===!1};mn.prototype.setEncoding=function(t){EC||(EC=Mj().StringDecoder);var e=new EC(t);this._readableState.decoder=e,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,o=\"\";r!==null;)o+=e.write(r.data),r=r.next;return this._readableState.buffer.clear(),o!==\"\"&&this._readableState.buffer.push(o),this._readableState.length=o.length,this};var p2e=1073741824;function IBt(t){return t>=p2e?t=p2e:(t--,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,t|=t>>>16,t++),t}function h2e(t,e){return t<=0||e.length===0&&e.ended?0:e.objectMode?1:t!==t?e.flowing&&e.length?e.buffer.head.data.length:e.length:(t>e.highWaterMark&&(e.highWaterMark=IBt(t)),t<=e.length?t:e.ended?e.length:(e.needReadable=!0,0))}mn.prototype.read=function(t){en(\"read\",t),t=parseInt(t,10);var e=this._readableState,r=t;if(t!==0&&(e.emittedReadable=!1),t===0&&e.needReadable&&((e.highWaterMark!==0?e.length>=e.highWaterMark:e.length>0)||e.ended))return en(\"read: emitReadable\",e.length,e.ended),e.length===0&&e.ended?Gj(this):kQ(this),null;if(t=h2e(t,e),t===0&&e.ended)return e.length===0&&Gj(this),null;var o=e.needReadable;en(\"need readable\",o),(e.length===0||e.length-t<e.highWaterMark)&&(o=!0,en(\"length less than watermark\",o)),e.ended||e.reading?(o=!1,en(\"reading or ended\",o)):o&&(en(\"do read\"),e.reading=!0,e.sync=!0,e.length===0&&(e.needReadable=!0),this._read(e.highWaterMark),e.sync=!1,e.reading||(t=h2e(r,e)));var a;return t>0?a=C2e(t,e):a=null,a===null?(e.needReadable=e.length<=e.highWaterMark,t=0):(e.length-=t,e.awaitDrain=0),e.length===0&&(e.ended||(e.needReadable=!0),r!==t&&e.ended&&Gj(this)),a!==null&&this.emit(\"data\",a),a};function BBt(t,e){if(en(\"onEofChunk\"),!e.ended){if(e.decoder){var r=e.decoder.end();r&&r.length&&(e.buffer.push(r),e.length+=e.objectMode?1:r.length)}e.ended=!0,e.sync?kQ(t):(e.needReadable=!1,e.emittedReadable||(e.emittedReadable=!0,y2e(t)))}}function kQ(t){var e=t._readableState;en(\"emitReadable\",e.needReadable,e.emittedReadable),e.needReadable=!1,e.emittedReadable||(en(\"emitReadable\",e.flowing),e.emittedReadable=!0,process.nextTick(y2e,t))}function y2e(t){var e=t._readableState;en(\"emitReadable_\",e.destroyed,e.length,e.ended),!e.destroyed&&(e.length||e.ended)&&(t.emit(\"readable\"),e.emittedReadable=!1),e.needReadable=!e.flowing&&!e.ended&&e.length<=e.highWaterMark,Kj(t)}function Yj(t,e){e.readingMore||(e.readingMore=!0,process.nextTick(vBt,t,e))}function vBt(t,e){for(;!e.reading&&!e.ended&&(e.length<e.highWaterMark||e.flowing&&e.length===0);){var r=e.length;if(en(\"maybeReadMore read 0\"),t.read(0),r===e.length)break}e.readingMore=!1}mn.prototype._read=function(t){rv(this,new yBt(\"_read()\"))};mn.prototype.pipe=function(t,e){var r=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=t;break;case 1:o.pipes=[o.pipes,t];break;default:o.pipes.push(t);break}o.pipesCount+=1,en(\"pipe count=%d opts=%j\",o.pipesCount,e);var a=(!e||e.end!==!1)&&t!==process.stdout&&t!==process.stderr,n=a?A:R;o.endEmitted?process.nextTick(n):r.once(\"end\",n),t.on(\"unpipe\",u);function u(L,U){en(\"onunpipe\"),L===r&&U&&U.hasUnpiped===!1&&(U.hasUnpiped=!0,E())}function A(){en(\"onend\"),t.end()}var p=DBt(r);t.on(\"drain\",p);var h=!1;function E(){en(\"cleanup\"),t.removeListener(\"close\",x),t.removeListener(\"finish\",C),t.removeListener(\"drain\",p),t.removeListener(\"error\",v),t.removeListener(\"unpipe\",u),r.removeListener(\"end\",A),r.removeListener(\"end\",R),r.removeListener(\"data\",I),h=!0,o.awaitDrain&&(!t._writableState||t._writableState.needDrain)&&p()}r.on(\"data\",I);function I(L){en(\"ondata\");var U=t.write(L);en(\"dest.write\",U),U===!1&&((o.pipesCount===1&&o.pipes===t||o.pipesCount>1&&w2e(o.pipes,t)!==-1)&&!h&&(en(\"false write response, pause\",o.awaitDrain),o.awaitDrain++),r.pause())}function v(L){en(\"onerror\",L),R(),t.removeListener(\"error\",v),g2e(t,\"error\")===0&&rv(t,L)}CBt(t,\"error\",v);function x(){t.removeListener(\"finish\",C),R()}t.once(\"close\",x);function C(){en(\"onfinish\"),t.removeListener(\"close\",x),R()}t.once(\"finish\",C);function R(){en(\"unpipe\"),r.unpipe(t)}return t.emit(\"pipe\",r),o.flowing||(en(\"pipe resume\"),r.resume()),t};function DBt(t){return function(){var r=t._readableState;en(\"pipeOnDrain\",r.awaitDrain),r.awaitDrain&&r.awaitDrain--,r.awaitDrain===0&&g2e(t,\"data\")&&(r.flowing=!0,Kj(t))}}mn.prototype.unpipe=function(t){var e=this._readableState,r={hasUnpiped:!1};if(e.pipesCount===0)return this;if(e.pipesCount===1)return t&&t!==e.pipes?this:(t||(t=e.pipes),e.pipes=null,e.pipesCount=0,e.flowing=!1,t&&t.emit(\"unpipe\",this,r),this);if(!t){var o=e.pipes,a=e.pipesCount;e.pipes=null,e.pipesCount=0,e.flowing=!1;for(var n=0;n<a;n++)o[n].emit(\"unpipe\",this,{hasUnpiped:!1});return this}var u=w2e(e.pipes,t);return u===-1?this:(e.pipes.splice(u,1),e.pipesCount-=1,e.pipesCount===1&&(e.pipes=e.pipes[0]),t.emit(\"unpipe\",this,r),this)};mn.prototype.on=function(t,e){var r=nv.prototype.on.call(this,t,e),o=this._readableState;return t===\"data\"?(o.readableListening=this.listenerCount(\"readable\")>0,o.flowing!==!1&&this.resume()):t===\"readable\"&&!o.endEmitted&&!o.readableListening&&(o.readableListening=o.needReadable=!0,o.flowing=!1,o.emittedReadable=!1,en(\"on readable\",o.length,o.reading),o.length?kQ(this):o.reading||process.nextTick(PBt,this)),r};mn.prototype.addListener=mn.prototype.on;mn.prototype.removeListener=function(t,e){var r=nv.prototype.removeListener.call(this,t,e);return t===\"readable\"&&process.nextTick(E2e,this),r};mn.prototype.removeAllListeners=function(t){var e=nv.prototype.removeAllListeners.apply(this,arguments);return(t===\"readable\"||t===void 0)&&process.nextTick(E2e,this),e};function E2e(t){var e=t._readableState;e.readableListening=t.listenerCount(\"readable\")>0,e.resumeScheduled&&!e.paused?e.flowing=!0:t.listenerCount(\"data\")>0&&t.resume()}function PBt(t){en(\"readable nexttick read 0\"),t.read(0)}mn.prototype.resume=function(){var t=this._readableState;return t.flowing||(en(\"resume\"),t.flowing=!t.readableListening,bBt(this,t)),t.paused=!1,this};function bBt(t,e){e.resumeScheduled||(e.resumeScheduled=!0,process.nextTick(SBt,t,e))}function SBt(t,e){en(\"resume\",e.reading),e.reading||t.read(0),e.resumeScheduled=!1,t.emit(\"resume\"),Kj(t),e.flowing&&!e.reading&&t.read(0)}mn.prototype.pause=function(){return en(\"call pause flowing=%j\",this._readableState.flowing),this._readableState.flowing!==!1&&(en(\"pause\"),this._readableState.flowing=!1,this.emit(\"pause\")),this._readableState.paused=!0,this};function Kj(t){var e=t._readableState;for(en(\"flow\",e.flowing);e.flowing&&t.read()!==null;);}mn.prototype.wrap=function(t){var e=this,r=this._readableState,o=!1;t.on(\"end\",function(){if(en(\"wrapped end\"),r.decoder&&!r.ended){var u=r.decoder.end();u&&u.length&&e.push(u)}e.push(null)}),t.on(\"data\",function(u){if(en(\"wrapped data\"),r.decoder&&(u=r.decoder.write(u)),!(r.objectMode&&u==null)&&!(!r.objectMode&&(!u||!u.length))){var A=e.push(u);A||(o=!0,t.pause())}});for(var a in t)this[a]===void 0&&typeof t[a]==\"function\"&&(this[a]=function(A){return function(){return t[A].apply(t,arguments)}}(a));for(var n=0;n<qj.length;n++)t.on(qj[n],this.emit.bind(this,qj[n]));return this._read=function(u){en(\"wrapped _read\",u),o&&(o=!1,t.resume())},this};typeof Symbol==\"function\"&&(mn.prototype[Symbol.asyncIterator]=function(){return _j===void 0&&(_j=l2e()),_j(this)});Object.defineProperty(mn.prototype,\"readableHighWaterMark\",{enumerable:!1,get:function(){return this._readableState.highWaterMark}});Object.defineProperty(mn.prototype,\"readableBuffer\",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}});Object.defineProperty(mn.prototype,\"readableFlowing\",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}});mn._fromList=C2e;Object.defineProperty(mn.prototype,\"readableLength\",{enumerable:!1,get:function(){return this._readableState.length}});function C2e(t,e){if(e.length===0)return null;var r;return e.objectMode?r=e.buffer.shift():!t||t>=e.length?(e.decoder?r=e.buffer.join(\"\"):e.buffer.length===1?r=e.buffer.first():r=e.buffer.concat(e.length),e.buffer.clear()):r=e.buffer.consume(t,e.decoder),r}function Gj(t){var e=t._readableState;en(\"endReadable\",e.endEmitted),e.endEmitted||(e.ended=!0,process.nextTick(xBt,e,t))}function xBt(t,e){if(en(\"endReadableNT\",t.endEmitted,t.length),!t.endEmitted&&t.length===0&&(t.endEmitted=!0,e.readable=!1,e.emit(\"end\"),t.autoDestroy)){var r=e._writableState;(!r||r.autoDestroy&&r.finished)&&e.destroy()}}typeof Symbol==\"function\"&&(mn.from=function(t,e){return Hj===void 0&&(Hj=f2e()),Hj(mn,t,e)});function w2e(t,e){for(var r=0,o=t.length;r<o;r++)if(t[r]===e)return r;return-1}});var Vj=_((O$t,v2e)=>{\"use strict\";v2e.exports=np;var QQ=Gh().codes,kBt=QQ.ERR_METHOD_NOT_IMPLEMENTED,QBt=QQ.ERR_MULTIPLE_CALLBACK,FBt=QQ.ERR_TRANSFORM_ALREADY_TRANSFORMING,RBt=QQ.ERR_TRANSFORM_WITH_LENGTH_0,FQ=ld();Yh()(np,FQ);function TBt(t,e){var r=this._transformState;r.transforming=!1;var o=r.writecb;if(o===null)return this.emit(\"error\",new QBt);r.writechunk=null,r.writecb=null,e!=null&&this.push(e),o(t);var a=this._readableState;a.reading=!1,(a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}function np(t){if(!(this instanceof np))return new np(t);FQ.call(this,t),this._transformState={afterTransform:TBt.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,t&&(typeof t.transform==\"function\"&&(this._transform=t.transform),typeof t.flush==\"function\"&&(this._flush=t.flush)),this.on(\"prefinish\",NBt)}function NBt(){var t=this;typeof this._flush==\"function\"&&!this._readableState.destroyed?this._flush(function(e,r){B2e(t,e,r)}):B2e(this,null,null)}np.prototype.push=function(t,e){return this._transformState.needTransform=!1,FQ.prototype.push.call(this,t,e)};np.prototype._transform=function(t,e,r){r(new kBt(\"_transform()\"))};np.prototype._write=function(t,e,r){var o=this._transformState;if(o.writecb=r,o.writechunk=t,o.writeencoding=e,!o.transforming){var a=this._readableState;(o.needTransform||a.needReadable||a.length<a.highWaterMark)&&this._read(a.highWaterMark)}};np.prototype._read=function(t){var e=this._transformState;e.writechunk!==null&&!e.transforming?(e.transforming=!0,this._transform(e.writechunk,e.writeencoding,e.afterTransform)):e.needTransform=!0};np.prototype._destroy=function(t,e){FQ.prototype._destroy.call(this,t,function(r){e(r)})};function B2e(t,e,r){if(e)return t.emit(\"error\",e);if(r!=null&&t.push(r),t._writableState.length)throw new RBt;if(t._transformState.transforming)throw new FBt;return t.push(null)}});var b2e=_((U$t,P2e)=>{\"use strict\";P2e.exports=iv;var D2e=Vj();Yh()(iv,D2e);function iv(t){if(!(this instanceof iv))return new iv(t);D2e.call(this,t)}iv.prototype._transform=function(t,e,r){r(null,t)}});var F2e=_((_$t,Q2e)=>{\"use strict\";var zj;function LBt(t){var e=!1;return function(){e||(e=!0,t.apply(void 0,arguments))}}var k2e=Gh().codes,MBt=k2e.ERR_MISSING_ARGS,OBt=k2e.ERR_STREAM_DESTROYED;function S2e(t){if(t)throw t}function UBt(t){return t.setHeader&&typeof t.abort==\"function\"}function _Bt(t,e,r,o){o=LBt(o);var a=!1;t.on(\"close\",function(){a=!0}),zj===void 0&&(zj=DQ()),zj(t,{readable:e,writable:r},function(u){if(u)return o(u);a=!0,o()});var n=!1;return function(u){if(!a&&!n){if(n=!0,UBt(t))return t.abort();if(typeof t.destroy==\"function\")return t.destroy();o(u||new OBt(\"pipe\"))}}}function x2e(t){t()}function HBt(t,e){return t.pipe(e)}function qBt(t){return!t.length||typeof t[t.length-1]!=\"function\"?S2e:t.pop()}function jBt(){for(var t=arguments.length,e=new Array(t),r=0;r<t;r++)e[r]=arguments[r];var o=qBt(e);if(Array.isArray(e[0])&&(e=e[0]),e.length<2)throw new MBt(\"streams\");var a,n=e.map(function(u,A){var p=A<e.length-1,h=A>0;return _Bt(u,p,h,function(E){a||(a=E),E&&n.forEach(x2e),!p&&(n.forEach(x2e),o(a))})});return e.reduce(HBt)}Q2e.exports=jBt});var CC=_((cc,ov)=>{var sv=ve(\"stream\");process.env.READABLE_STREAM===\"disable\"&&sv?(ov.exports=sv.Readable,Object.assign(ov.exports,sv),ov.exports.Stream=sv):(cc=ov.exports=Rj(),cc.Stream=sv||cc,cc.Readable=cc,cc.Writable=kj(),cc.Duplex=ld(),cc.Transform=Vj(),cc.PassThrough=b2e(),cc.finished=DQ(),cc.pipeline=F2e())});var N2e=_((H$t,T2e)=>{\"use strict\";var{Buffer:uu}=ve(\"buffer\"),R2e=Symbol.for(\"BufferList\");function ni(t){if(!(this instanceof ni))return new ni(t);ni._init.call(this,t)}ni._init=function(e){Object.defineProperty(this,R2e,{value:!0}),this._bufs=[],this.length=0,e&&this.append(e)};ni.prototype._new=function(e){return new ni(e)};ni.prototype._offset=function(e){if(e===0)return[0,0];let r=0;for(let o=0;o<this._bufs.length;o++){let a=r+this._bufs[o].length;if(e<a||o===this._bufs.length-1)return[o,e-r];r=a}};ni.prototype._reverseOffset=function(t){let e=t[0],r=t[1];for(let o=0;o<e;o++)r+=this._bufs[o].length;return r};ni.prototype.get=function(e){if(e>this.length||e<0)return;let r=this._offset(e);return this._bufs[r[0]][r[1]]};ni.prototype.slice=function(e,r){return typeof e==\"number\"&&e<0&&(e+=this.length),typeof r==\"number\"&&r<0&&(r+=this.length),this.copy(null,0,e,r)};ni.prototype.copy=function(e,r,o,a){if((typeof o!=\"number\"||o<0)&&(o=0),(typeof a!=\"number\"||a>this.length)&&(a=this.length),o>=this.length||a<=0)return e||uu.alloc(0);let n=!!e,u=this._offset(o),A=a-o,p=A,h=n&&r||0,E=u[1];if(o===0&&a===this.length){if(!n)return this._bufs.length===1?this._bufs[0]:uu.concat(this._bufs,this.length);for(let I=0;I<this._bufs.length;I++)this._bufs[I].copy(e,h),h+=this._bufs[I].length;return e}if(p<=this._bufs[u[0]].length-E)return n?this._bufs[u[0]].copy(e,r,E,E+p):this._bufs[u[0]].slice(E,E+p);n||(e=uu.allocUnsafe(A));for(let I=u[0];I<this._bufs.length;I++){let v=this._bufs[I].length-E;if(p>v)this._bufs[I].copy(e,h,E),h+=v;else{this._bufs[I].copy(e,h,E,E+p),h+=v;break}p-=v,E&&(E=0)}return e.length>h?e.slice(0,h):e};ni.prototype.shallowSlice=function(e,r){if(e=e||0,r=typeof r!=\"number\"?this.length:r,e<0&&(e+=this.length),r<0&&(r+=this.length),e===r)return this._new();let o=this._offset(e),a=this._offset(r),n=this._bufs.slice(o[0],a[0]+1);return a[1]===0?n.pop():n[n.length-1]=n[n.length-1].slice(0,a[1]),o[1]!==0&&(n[0]=n[0].slice(o[1])),this._new(n)};ni.prototype.toString=function(e,r,o){return this.slice(r,o).toString(e)};ni.prototype.consume=function(e){if(e=Math.trunc(e),Number.isNaN(e)||e<=0)return this;for(;this._bufs.length;)if(e>=this._bufs[0].length)e-=this._bufs[0].length,this.length-=this._bufs[0].length,this._bufs.shift();else{this._bufs[0]=this._bufs[0].slice(e),this.length-=e;break}return this};ni.prototype.duplicate=function(){let e=this._new();for(let r=0;r<this._bufs.length;r++)e.append(this._bufs[r]);return e};ni.prototype.append=function(e){if(e==null)return this;if(e.buffer)this._appendBuffer(uu.from(e.buffer,e.byteOffset,e.byteLength));else if(Array.isArray(e))for(let r=0;r<e.length;r++)this.append(e[r]);else if(this._isBufferList(e))for(let r=0;r<e._bufs.length;r++)this.append(e._bufs[r]);else typeof e==\"number\"&&(e=e.toString()),this._appendBuffer(uu.from(e));return this};ni.prototype._appendBuffer=function(e){this._bufs.push(e),this.length+=e.length};ni.prototype.indexOf=function(t,e,r){if(r===void 0&&typeof e==\"string\"&&(r=e,e=void 0),typeof t==\"function\"||Array.isArray(t))throw new TypeError('The \"value\" argument must be one of type string, Buffer, BufferList, or Uint8Array.');if(typeof t==\"number\"?t=uu.from([t]):typeof t==\"string\"?t=uu.from(t,r):this._isBufferList(t)?t=t.slice():Array.isArray(t.buffer)?t=uu.from(t.buffer,t.byteOffset,t.byteLength):uu.isBuffer(t)||(t=uu.from(t)),e=Number(e||0),isNaN(e)&&(e=0),e<0&&(e=this.length+e),e<0&&(e=0),t.length===0)return e>this.length?this.length:e;let o=this._offset(e),a=o[0],n=o[1];for(;a<this._bufs.length;a++){let u=this._bufs[a];for(;n<u.length;)if(u.length-n>=t.length){let p=u.indexOf(t,n);if(p!==-1)return this._reverseOffset([a,p]);n=u.length-t.length+1}else{let p=this._reverseOffset([a,n]);if(this._match(p,t))return p;n++}n=0}return-1};ni.prototype._match=function(t,e){if(this.length-t<e.length)return!1;for(let r=0;r<e.length;r++)if(this.get(t+r)!==e[r])return!1;return!0};(function(){let t={readDoubleBE:8,readDoubleLE:8,readFloatBE:4,readFloatLE:4,readInt32BE:4,readInt32LE:4,readUInt32BE:4,readUInt32LE:4,readInt16BE:2,readInt16LE:2,readUInt16BE:2,readUInt16LE:2,readInt8:1,readUInt8:1,readIntBE:null,readIntLE:null,readUIntBE:null,readUIntLE:null};for(let e in t)(function(r){t[r]===null?ni.prototype[r]=function(o,a){return this.slice(o,o+a)[r](0,a)}:ni.prototype[r]=function(o=0){return this.slice(o,o+t[r])[r](0)}})(e)})();ni.prototype._isBufferList=function(e){return e instanceof ni||ni.isBufferList(e)};ni.isBufferList=function(e){return e!=null&&e[R2e]};T2e.exports=ni});var L2e=_((q$t,RQ)=>{\"use strict\";var Jj=CC().Duplex,GBt=Yh(),av=N2e();function Uo(t){if(!(this instanceof Uo))return new Uo(t);if(typeof t==\"function\"){this._callback=t;let e=function(o){this._callback&&(this._callback(o),this._callback=null)}.bind(this);this.on(\"pipe\",function(o){o.on(\"error\",e)}),this.on(\"unpipe\",function(o){o.removeListener(\"error\",e)}),t=null}av._init.call(this,t),Jj.call(this)}GBt(Uo,Jj);Object.assign(Uo.prototype,av.prototype);Uo.prototype._new=function(e){return new Uo(e)};Uo.prototype._write=function(e,r,o){this._appendBuffer(e),typeof o==\"function\"&&o()};Uo.prototype._read=function(e){if(!this.length)return this.push(null);e=Math.min(e,this.length),this.push(this.slice(0,e)),this.consume(e)};Uo.prototype.end=function(e){Jj.prototype.end.call(this,e),this._callback&&(this._callback(null,this.slice()),this._callback=null)};Uo.prototype._destroy=function(e,r){this._bufs.length=0,this.length=0,r(e)};Uo.prototype._isBufferList=function(e){return e instanceof Uo||e instanceof av||Uo.isBufferList(e)};Uo.isBufferList=av.isBufferList;RQ.exports=Uo;RQ.exports.BufferListStream=Uo;RQ.exports.BufferList=av});var $j=_(IC=>{var YBt=Buffer.alloc,WBt=\"0000000000000000000\",KBt=\"7777777777777777777\",M2e=48,O2e=Buffer.from(\"ustar\\0\",\"binary\"),VBt=Buffer.from(\"00\",\"binary\"),zBt=Buffer.from(\"ustar \",\"binary\"),JBt=Buffer.from(\" \\0\",\"binary\"),XBt=parseInt(\"7777\",8),lv=257,Zj=263,ZBt=function(t,e,r){return typeof t!=\"number\"?r:(t=~~t,t>=e?e:t>=0||(t+=e,t>=0)?t:0)},$Bt=function(t){switch(t){case 0:return\"file\";case 1:return\"link\";case 2:return\"symlink\";case 3:return\"character-device\";case 4:return\"block-device\";case 5:return\"directory\";case 6:return\"fifo\";case 7:return\"contiguous-file\";case 72:return\"pax-header\";case 55:return\"pax-global-header\";case 27:return\"gnu-long-link-path\";case 28:case 30:return\"gnu-long-path\"}return null},evt=function(t){switch(t){case\"file\":return 0;case\"link\":return 1;case\"symlink\":return 2;case\"character-device\":return 3;case\"block-device\":return 4;case\"directory\":return 5;case\"fifo\":return 6;case\"contiguous-file\":return 7;case\"pax-header\":return 72}return 0},U2e=function(t,e,r,o){for(;r<o;r++)if(t[r]===e)return r;return o},_2e=function(t){for(var e=256,r=0;r<148;r++)e+=t[r];for(var o=156;o<512;o++)e+=t[o];return e},Jh=function(t,e){return t=t.toString(8),t.length>e?KBt.slice(0,e)+\" \":WBt.slice(0,e-t.length)+t+\" \"};function tvt(t){var e;if(t[0]===128)e=!0;else if(t[0]===255)e=!1;else return null;for(var r=[],o=t.length-1;o>0;o--){var a=t[o];e?r.push(a):r.push(255-a)}var n=0,u=r.length;for(o=0;o<u;o++)n+=r[o]*Math.pow(256,o);return e?n:-1*n}var Xh=function(t,e,r){if(t=t.slice(e,e+r),e=0,t[e]&128)return tvt(t);for(;e<t.length&&t[e]===32;)e++;for(var o=ZBt(U2e(t,32,e,t.length),t.length,t.length);e<o&&t[e]===0;)e++;return o===e?0:parseInt(t.slice(e,o).toString(),8)},wC=function(t,e,r,o){return t.slice(e,U2e(t,0,e,e+r)).toString(o)},Xj=function(t){var e=Buffer.byteLength(t),r=Math.floor(Math.log(e)/Math.log(10))+1;return e+r>=Math.pow(10,r)&&r++,e+r+t};IC.decodeLongPath=function(t,e){return wC(t,0,t.length,e)};IC.encodePax=function(t){var e=\"\";t.name&&(e+=Xj(\" path=\"+t.name+`\n`)),t.linkname&&(e+=Xj(\" linkpath=\"+t.linkname+`\n`));var r=t.pax;if(r)for(var o in r)e+=Xj(\" \"+o+\"=\"+r[o]+`\n`);return Buffer.from(e)};IC.decodePax=function(t){for(var e={};t.length;){for(var r=0;r<t.length&&t[r]!==32;)r++;var o=parseInt(t.slice(0,r).toString(),10);if(!o)return e;var a=t.slice(r+1,o-1).toString(),n=a.indexOf(\"=\");if(n===-1)return e;e[a.slice(0,n)]=a.slice(n+1),t=t.slice(o)}return e};IC.encode=function(t){var e=YBt(512),r=t.name,o=\"\";if(t.typeflag===5&&r[r.length-1]!==\"/\"&&(r+=\"/\"),Buffer.byteLength(r)!==r.length)return null;for(;Buffer.byteLength(r)>100;){var a=r.indexOf(\"/\");if(a===-1)return null;o+=o?\"/\"+r.slice(0,a):r.slice(0,a),r=r.slice(a+1)}return Buffer.byteLength(r)>100||Buffer.byteLength(o)>155||t.linkname&&Buffer.byteLength(t.linkname)>100?null:(e.write(r),e.write(Jh(t.mode&XBt,6),100),e.write(Jh(t.uid,6),108),e.write(Jh(t.gid,6),116),e.write(Jh(t.size,11),124),e.write(Jh(t.mtime.getTime()/1e3|0,11),136),e[156]=M2e+evt(t.type),t.linkname&&e.write(t.linkname,157),O2e.copy(e,lv),VBt.copy(e,Zj),t.uname&&e.write(t.uname,265),t.gname&&e.write(t.gname,297),e.write(Jh(t.devmajor||0,6),329),e.write(Jh(t.devminor||0,6),337),o&&e.write(o,345),e.write(Jh(_2e(e),6),148),e)};IC.decode=function(t,e,r){var o=t[156]===0?0:t[156]-M2e,a=wC(t,0,100,e),n=Xh(t,100,8),u=Xh(t,108,8),A=Xh(t,116,8),p=Xh(t,124,12),h=Xh(t,136,12),E=$Bt(o),I=t[157]===0?null:wC(t,157,100,e),v=wC(t,265,32),x=wC(t,297,32),C=Xh(t,329,8),R=Xh(t,337,8),L=_2e(t);if(L===8*32)return null;if(L!==Xh(t,148,8))throw new Error(\"Invalid tar header. Maybe the tar is corrupted or it needs to be gunzipped?\");if(O2e.compare(t,lv,lv+6)===0)t[345]&&(a=wC(t,345,155,e)+\"/\"+a);else if(!(zBt.compare(t,lv,lv+6)===0&&JBt.compare(t,Zj,Zj+2)===0)){if(!r)throw new Error(\"Invalid tar header: unknown format.\")}return o===0&&a&&a[a.length-1]===\"/\"&&(o=5),{name:a,mode:n,uid:u,gid:A,size:p,mtime:new Date(1e3*h),type:E,linkname:I,uname:v,gname:x,devmajor:C,devminor:R}}});var K2e=_((G$t,W2e)=>{var q2e=ve(\"util\"),rvt=L2e(),cv=$j(),j2e=CC().Writable,G2e=CC().PassThrough,Y2e=function(){},H2e=function(t){return t&=511,t&&512-t},nvt=function(t,e){var r=new TQ(t,e);return r.end(),r},ivt=function(t,e){return e.path&&(t.name=e.path),e.linkpath&&(t.linkname=e.linkpath),e.size&&(t.size=parseInt(e.size,10)),t.pax=e,t},TQ=function(t,e){this._parent=t,this.offset=e,G2e.call(this,{autoDestroy:!1})};q2e.inherits(TQ,G2e);TQ.prototype.destroy=function(t){this._parent.destroy(t)};var ip=function(t){if(!(this instanceof ip))return new ip(t);j2e.call(this,t),t=t||{},this._offset=0,this._buffer=rvt(),this._missing=0,this._partial=!1,this._onparse=Y2e,this._header=null,this._stream=null,this._overflow=null,this._cb=null,this._locked=!1,this._destroyed=!1,this._pax=null,this._paxGlobal=null,this._gnuLongPath=null,this._gnuLongLinkPath=null;var e=this,r=e._buffer,o=function(){e._continue()},a=function(v){if(e._locked=!1,v)return e.destroy(v);e._stream||o()},n=function(){e._stream=null;var v=H2e(e._header.size);v?e._parse(v,u):e._parse(512,I),e._locked||o()},u=function(){e._buffer.consume(H2e(e._header.size)),e._parse(512,I),o()},A=function(){var v=e._header.size;e._paxGlobal=cv.decodePax(r.slice(0,v)),r.consume(v),n()},p=function(){var v=e._header.size;e._pax=cv.decodePax(r.slice(0,v)),e._paxGlobal&&(e._pax=Object.assign({},e._paxGlobal,e._pax)),r.consume(v),n()},h=function(){var v=e._header.size;this._gnuLongPath=cv.decodeLongPath(r.slice(0,v),t.filenameEncoding),r.consume(v),n()},E=function(){var v=e._header.size;this._gnuLongLinkPath=cv.decodeLongPath(r.slice(0,v),t.filenameEncoding),r.consume(v),n()},I=function(){var v=e._offset,x;try{x=e._header=cv.decode(r.slice(0,512),t.filenameEncoding,t.allowUnknownFormat)}catch(C){e.emit(\"error\",C)}if(r.consume(512),!x){e._parse(512,I),o();return}if(x.type===\"gnu-long-path\"){e._parse(x.size,h),o();return}if(x.type===\"gnu-long-link-path\"){e._parse(x.size,E),o();return}if(x.type===\"pax-global-header\"){e._parse(x.size,A),o();return}if(x.type===\"pax-header\"){e._parse(x.size,p),o();return}if(e._gnuLongPath&&(x.name=e._gnuLongPath,e._gnuLongPath=null),e._gnuLongLinkPath&&(x.linkname=e._gnuLongLinkPath,e._gnuLongLinkPath=null),e._pax&&(e._header=x=ivt(x,e._pax),e._pax=null),e._locked=!0,!x.size||x.type===\"directory\"){e._parse(512,I),e.emit(\"entry\",x,nvt(e,v),a);return}e._stream=new TQ(e,v),e.emit(\"entry\",x,e._stream,a),e._parse(x.size,n),o()};this._onheader=I,this._parse(512,I)};q2e.inherits(ip,j2e);ip.prototype.destroy=function(t){this._destroyed||(this._destroyed=!0,t&&this.emit(\"error\",t),this.emit(\"close\"),this._stream&&this._stream.emit(\"close\"))};ip.prototype._parse=function(t,e){this._destroyed||(this._offset+=t,this._missing=t,e===this._onheader&&(this._partial=!1),this._onparse=e)};ip.prototype._continue=function(){if(!this._destroyed){var t=this._cb;this._cb=Y2e,this._overflow?this._write(this._overflow,void 0,t):t()}};ip.prototype._write=function(t,e,r){if(!this._destroyed){var o=this._stream,a=this._buffer,n=this._missing;if(t.length&&(this._partial=!0),t.length<n)return this._missing-=t.length,this._overflow=null,o?o.write(t,r):(a.append(t),r());this._cb=r,this._missing=0;var u=null;t.length>n&&(u=t.slice(n),t=t.slice(0,n)),o?o.end(t):a.append(t),this._overflow=u,this._onparse()}};ip.prototype._final=function(t){if(this._partial)return this.destroy(new Error(\"Unexpected end of data\"));t()};W2e.exports=ip});var z2e=_((Y$t,V2e)=>{V2e.exports=ve(\"fs\").constants||ve(\"constants\")});var eBe=_((W$t,$2e)=>{var BC=z2e(),J2e=SO(),LQ=Yh(),svt=Buffer.alloc,X2e=CC().Readable,vC=CC().Writable,ovt=ve(\"string_decoder\").StringDecoder,NQ=$j(),avt=parseInt(\"755\",8),lvt=parseInt(\"644\",8),Z2e=svt(1024),t5=function(){},e5=function(t,e){e&=511,e&&t.push(Z2e.slice(0,512-e))};function cvt(t){switch(t&BC.S_IFMT){case BC.S_IFBLK:return\"block-device\";case BC.S_IFCHR:return\"character-device\";case BC.S_IFDIR:return\"directory\";case BC.S_IFIFO:return\"fifo\";case BC.S_IFLNK:return\"symlink\"}return\"file\"}var MQ=function(t){vC.call(this),this.written=0,this._to=t,this._destroyed=!1};LQ(MQ,vC);MQ.prototype._write=function(t,e,r){if(this.written+=t.length,this._to.push(t))return r();this._to._drain=r};MQ.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit(\"close\"))};var OQ=function(){vC.call(this),this.linkname=\"\",this._decoder=new ovt(\"utf-8\"),this._destroyed=!1};LQ(OQ,vC);OQ.prototype._write=function(t,e,r){this.linkname+=this._decoder.write(t),r()};OQ.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit(\"close\"))};var uv=function(){vC.call(this),this._destroyed=!1};LQ(uv,vC);uv.prototype._write=function(t,e,r){r(new Error(\"No body allowed for this entry\"))};uv.prototype.destroy=function(){this._destroyed||(this._destroyed=!0,this.emit(\"close\"))};var EA=function(t){if(!(this instanceof EA))return new EA(t);X2e.call(this,t),this._drain=t5,this._finalized=!1,this._finalizing=!1,this._destroyed=!1,this._stream=null};LQ(EA,X2e);EA.prototype.entry=function(t,e,r){if(this._stream)throw new Error(\"already piping an entry\");if(!(this._finalized||this._destroyed)){typeof e==\"function\"&&(r=e,e=null),r||(r=t5);var o=this;if((!t.size||t.type===\"symlink\")&&(t.size=0),t.type||(t.type=cvt(t.mode)),t.mode||(t.mode=t.type===\"directory\"?avt:lvt),t.uid||(t.uid=0),t.gid||(t.gid=0),t.mtime||(t.mtime=new Date),typeof e==\"string\"&&(e=Buffer.from(e)),Buffer.isBuffer(e)){t.size=e.length,this._encode(t);var a=this.push(e);return e5(o,t.size),a?process.nextTick(r):this._drain=r,new uv}if(t.type===\"symlink\"&&!t.linkname){var n=new OQ;return J2e(n,function(A){if(A)return o.destroy(),r(A);t.linkname=n.linkname,o._encode(t),r()}),n}if(this._encode(t),t.type!==\"file\"&&t.type!==\"contiguous-file\")return process.nextTick(r),new uv;var u=new MQ(this);return this._stream=u,J2e(u,function(A){if(o._stream=null,A)return o.destroy(),r(A);if(u.written!==t.size)return o.destroy(),r(new Error(\"size mismatch\"));e5(o,t.size),o._finalizing&&o.finalize(),r()}),u}};EA.prototype.finalize=function(){if(this._stream){this._finalizing=!0;return}this._finalized||(this._finalized=!0,this.push(Z2e),this.push(null))};EA.prototype.destroy=function(t){this._destroyed||(this._destroyed=!0,t&&this.emit(\"error\",t),this.emit(\"close\"),this._stream&&this._stream.destroy&&this._stream.destroy())};EA.prototype._encode=function(t){if(!t.pax){var e=NQ.encode(t);if(e){this.push(e);return}}this._encodePax(t)};EA.prototype._encodePax=function(t){var e=NQ.encodePax({name:t.name,linkname:t.linkname,pax:t.pax}),r={name:\"PaxHeader\",mode:t.mode,uid:t.uid,gid:t.gid,size:e.length,mtime:t.mtime,type:\"pax-header\",linkname:t.linkname&&\"PaxHeader\",uname:t.uname,gname:t.gname,devmajor:t.devmajor,devminor:t.devminor};this.push(NQ.encode(r)),this.push(e),e5(this,e.length),r.size=t.size,r.type=t.type,this.push(NQ.encode(r))};EA.prototype._read=function(t){var e=this._drain;this._drain=t5,e()};$2e.exports=EA});var tBe=_(r5=>{r5.extract=K2e();r5.pack=eBe()});var pBe=_((fer,fBe)=>{\"use strict\";var Av=class t{constructor(e,r,o){this.__specs=e||{},Object.keys(this.__specs).forEach(a=>{if(typeof this.__specs[a]==\"string\"){let n=this.__specs[a],u=this.__specs[n];if(u){let A=u.aliases||[];A.push(a,n),u.aliases=[...new Set(A)],this.__specs[a]=u}else throw new Error(`Alias refers to invalid key: ${n} -> ${a}`)}}),this.__opts=r||{},this.__providers=uBe(o.filter(a=>a!=null&&typeof a==\"object\")),this.__isFiggyPudding=!0}get(e){return l5(this,e,!0)}get[Symbol.toStringTag](){return\"FiggyPudding\"}forEach(e,r=this){for(let[o,a]of this.entries())e.call(r,a,o,this)}toJSON(){let e={};return this.forEach((r,o)=>{e[o]=r}),e}*entries(e){for(let o of Object.keys(this.__specs))yield[o,this.get(o)];let r=e||this.__opts.other;if(r){let o=new Set;for(let a of this.__providers){let n=a.entries?a.entries(r):vvt(a);for(let[u,A]of n)r(u)&&!o.has(u)&&(o.add(u),yield[u,A])}}}*[Symbol.iterator](){for(let[e,r]of this.entries())yield[e,r]}*keys(){for(let[e]of this.entries())yield e}*values(){for(let[,e]of this.entries())yield e}concat(...e){return new Proxy(new t(this.__specs,this.__opts,uBe(this.__providers).concat(e)),ABe)}};try{let t=ve(\"util\");Av.prototype[t.inspect.custom]=function(e,r){return this[Symbol.toStringTag]+\" \"+t.inspect(this.toJSON(),r)}}catch{}function Ivt(t){throw Object.assign(new Error(`invalid config key requested: ${t}`),{code:\"EBADKEY\"})}function l5(t,e,r){let o=t.__specs[e];if(r&&!o&&(!t.__opts.other||!t.__opts.other(e)))Ivt(e);else{o||(o={});let a;for(let n of t.__providers){if(a=cBe(e,n),a===void 0&&o.aliases&&o.aliases.length){for(let u of o.aliases)if(u!==e&&(a=cBe(u,n),a!==void 0))break}if(a!==void 0)break}return a===void 0&&o.default!==void 0?typeof o.default==\"function\"?o.default(t):o.default:a}}function cBe(t,e){let r;return e.__isFiggyPudding?r=l5(e,t,!1):typeof e.get==\"function\"?r=e.get(t):r=e[t],r}var ABe={has(t,e){return e in t.__specs&&l5(t,e,!1)!==void 0},ownKeys(t){return Object.keys(t.__specs)},get(t,e){return typeof e==\"symbol\"||e.slice(0,2)===\"__\"||e in Av.prototype?t[e]:t.get(e)},set(t,e,r){if(typeof e==\"symbol\"||e.slice(0,2)===\"__\")return t[e]=r,!0;throw new Error(\"figgyPudding options cannot be modified. Use .concat() instead.\")},deleteProperty(){throw new Error(\"figgyPudding options cannot be deleted. Use .concat() and shadow them instead.\")}};fBe.exports=Bvt;function Bvt(t,e){function r(...o){return new Proxy(new Av(t,e,o),ABe)}return r}function uBe(t){let e=[];return t.forEach(r=>e.unshift(r)),e}function vvt(t){return Object.keys(t).map(e=>[e,t[e]])}});var dBe=_((per,IA)=>{\"use strict\";var pv=ve(\"crypto\"),Dvt=pBe(),Pvt=ve(\"stream\").Transform,hBe=[\"sha256\",\"sha384\",\"sha512\"],bvt=/^[a-z0-9+/]+(?:=?=?)$/i,Svt=/^([^-]+)-([^?]+)([?\\S*]*)$/,xvt=/^([^-]+)-([A-Za-z0-9+/=]{44,88})(\\?[\\x21-\\x7E]*)*$/,kvt=/^[\\x21-\\x7E]+$/,oa=Dvt({algorithms:{default:[\"sha512\"]},error:{default:!1},integrity:{},options:{default:[]},pickAlgorithm:{default:()=>Ovt},Promise:{default:()=>Promise},sep:{default:\" \"},single:{default:!1},size:{},strict:{default:!1}}),Zh=class{get isHash(){return!0}constructor(e,r){r=oa(r);let o=!!r.strict;this.source=e.trim();let a=this.source.match(o?xvt:Svt);if(!a||o&&!hBe.some(u=>u===a[1]))return;this.algorithm=a[1],this.digest=a[2];let n=a[3];this.options=n?n.slice(1).split(\"?\"):[]}hexDigest(){return this.digest&&Buffer.from(this.digest,\"base64\").toString(\"hex\")}toJSON(){return this.toString()}toString(e){if(e=oa(e),e.strict&&!(hBe.some(o=>o===this.algorithm)&&this.digest.match(bvt)&&(this.options||[]).every(o=>o.match(kvt))))return\"\";let r=this.options&&this.options.length?`?${this.options.join(\"?\")}`:\"\";return`${this.algorithm}-${this.digest}${r}`}},fd=class{get isIntegrity(){return!0}toJSON(){return this.toString()}toString(e){e=oa(e);let r=e.sep||\" \";return e.strict&&(r=r.replace(/\\S+/g,\" \")),Object.keys(this).map(o=>this[o].map(a=>Zh.prototype.toString.call(a,e)).filter(a=>a.length).join(r)).filter(o=>o.length).join(r)}concat(e,r){r=oa(r);let o=typeof e==\"string\"?e:fv(e,r);return wA(`${this.toString(r)} ${o}`,r)}hexDigest(){return wA(this,{single:!0}).hexDigest()}match(e,r){r=oa(r);let o=wA(e,r),a=o.pickAlgorithm(r);return this[a]&&o[a]&&this[a].find(n=>o[a].find(u=>n.digest===u.digest))||!1}pickAlgorithm(e){e=oa(e);let r=e.pickAlgorithm,o=Object.keys(this);if(!o.length)throw new Error(`No algorithms available for ${JSON.stringify(this.toString())}`);return o.reduce((a,n)=>r(a,n)||a)}};IA.exports.parse=wA;function wA(t,e){if(e=oa(e),typeof t==\"string\")return c5(t,e);if(t.algorithm&&t.digest){let r=new fd;return r[t.algorithm]=[t],c5(fv(r,e),e)}else return c5(fv(t,e),e)}function c5(t,e){return e.single?new Zh(t,e):t.trim().split(/\\s+/).reduce((r,o)=>{let a=new Zh(o,e);if(a.algorithm&&a.digest){let n=a.algorithm;r[n]||(r[n]=[]),r[n].push(a)}return r},new fd)}IA.exports.stringify=fv;function fv(t,e){return e=oa(e),t.algorithm&&t.digest?Zh.prototype.toString.call(t,e):typeof t==\"string\"?fv(wA(t,e),e):fd.prototype.toString.call(t,e)}IA.exports.fromHex=Qvt;function Qvt(t,e,r){r=oa(r);let o=r.options&&r.options.length?`?${r.options.join(\"?\")}`:\"\";return wA(`${e}-${Buffer.from(t,\"hex\").toString(\"base64\")}${o}`,r)}IA.exports.fromData=Fvt;function Fvt(t,e){e=oa(e);let r=e.algorithms,o=e.options&&e.options.length?`?${e.options.join(\"?\")}`:\"\";return r.reduce((a,n)=>{let u=pv.createHash(n).update(t).digest(\"base64\"),A=new Zh(`${n}-${u}${o}`,e);if(A.algorithm&&A.digest){let p=A.algorithm;a[p]||(a[p]=[]),a[p].push(A)}return a},new fd)}IA.exports.fromStream=Rvt;function Rvt(t,e){e=oa(e);let r=e.Promise||Promise,o=u5(e);return new r((a,n)=>{t.pipe(o),t.on(\"error\",n),o.on(\"error\",n);let u;o.on(\"integrity\",A=>{u=A}),o.on(\"end\",()=>a(u)),o.on(\"data\",()=>{})})}IA.exports.checkData=Tvt;function Tvt(t,e,r){if(r=oa(r),e=wA(e,r),!Object.keys(e).length){if(r.error)throw Object.assign(new Error(\"No valid integrity hashes to check against\"),{code:\"EINTEGRITY\"});return!1}let o=e.pickAlgorithm(r),a=pv.createHash(o).update(t).digest(\"base64\"),n=wA({algorithm:o,digest:a}),u=n.match(e,r);if(u||!r.error)return u;if(typeof r.size==\"number\"&&t.length!==r.size){let A=new Error(`data size mismatch when checking ${e}.\n  Wanted: ${r.size}\n  Found: ${t.length}`);throw A.code=\"EBADSIZE\",A.found=t.length,A.expected=r.size,A.sri=e,A}else{let A=new Error(`Integrity checksum failed when using ${o}: Wanted ${e}, but got ${n}. (${t.length} bytes)`);throw A.code=\"EINTEGRITY\",A.found=n,A.expected=e,A.algorithm=o,A.sri=e,A}}IA.exports.checkStream=Nvt;function Nvt(t,e,r){r=oa(r);let o=r.Promise||Promise,a=u5(r.concat({integrity:e}));return new o((n,u)=>{t.pipe(a),t.on(\"error\",u),a.on(\"error\",u);let A;a.on(\"verified\",p=>{A=p}),a.on(\"end\",()=>n(A)),a.on(\"data\",()=>{})})}IA.exports.integrityStream=u5;function u5(t){t=oa(t);let e=t.integrity&&wA(t.integrity,t),r=e&&Object.keys(e).length,o=r&&e.pickAlgorithm(t),a=r&&e[o],n=Array.from(new Set(t.algorithms.concat(o?[o]:[]))),u=n.map(pv.createHash),A=0,p=new Pvt({transform(h,E,I){A+=h.length,u.forEach(v=>v.update(h,E)),I(null,h,E)}}).on(\"end\",()=>{let h=t.options&&t.options.length?`?${t.options.join(\"?\")}`:\"\",E=wA(u.map((v,x)=>`${n[x]}-${v.digest(\"base64\")}${h}`).join(\" \"),t),I=r&&E.match(e,t);if(typeof t.size==\"number\"&&A!==t.size){let v=new Error(`stream size mismatch when checking ${e}.\n  Wanted: ${t.size}\n  Found: ${A}`);v.code=\"EBADSIZE\",v.found=A,v.expected=t.size,v.sri=e,p.emit(\"error\",v)}else if(t.integrity&&!I){let v=new Error(`${e} integrity checksum failed when using ${o}: wanted ${a} but got ${E}. (${A} bytes)`);v.code=\"EINTEGRITY\",v.found=E,v.expected=a,v.algorithm=o,v.sri=e,p.emit(\"error\",v)}else p.emit(\"size\",A),p.emit(\"integrity\",E),I&&p.emit(\"verified\",I)});return p}IA.exports.create=Lvt;function Lvt(t){t=oa(t);let e=t.algorithms,r=t.options.length?`?${t.options.join(\"?\")}`:\"\",o=e.map(pv.createHash);return{update:function(a,n){return o.forEach(u=>u.update(a,n)),this},digest:function(a){return e.reduce((u,A)=>{let p=o.shift().digest(\"base64\"),h=new Zh(`${A}-${p}${r}`,t);if(h.algorithm&&h.digest){let E=h.algorithm;u[E]||(u[E]=[]),u[E].push(h)}return u},new fd)}}}var Mvt=new Set(pv.getHashes()),gBe=[\"md5\",\"whirlpool\",\"sha1\",\"sha224\",\"sha256\",\"sha384\",\"sha512\",\"sha3\",\"sha3-256\",\"sha3-384\",\"sha3-512\",\"sha3_256\",\"sha3_384\",\"sha3_512\"].filter(t=>Mvt.has(t));function Ovt(t,e){return gBe.indexOf(t.toLowerCase())>=gBe.indexOf(e.toLowerCase())?t:e}});var YBe=_((dir,GBe)=>{var ODt=$N();function UDt(t){return ODt(t)?void 0:t}GBe.exports=UDt});var KBe=_((mir,WBe)=>{var _Dt=xS(),HDt=B8(),qDt=b8(),jDt=Mg(),GDt=Ag(),YDt=YBe(),WDt=m_(),KDt=I8(),VDt=1,zDt=2,JDt=4,XDt=WDt(function(t,e){var r={};if(t==null)return r;var o=!1;e=_Dt(e,function(n){return n=jDt(n,t),o||(o=n.length>1),n}),GDt(t,KDt(t),r),o&&(r=HDt(r,VDt|zDt|JDt,YDt));for(var a=e.length;a--;)qDt(r,e[a]);return r});WBe.exports=XDt});Pt();Ge();Pt();var ZBe=ve(\"child_process\"),$Be=Ze(X0());qt();var Uy=new Map([]);var W1={};Vt(W1,{BaseCommand:()=>ut,WorkspaceRequiredError:()=>sr,getCli:()=>ihe,getDynamicLibs:()=>nhe,getPluginConfiguration:()=>Hy,openWorkspace:()=>_y,pluginCommands:()=>Uy,runExit:()=>Wx});qt();var ut=class extends it{constructor(){super(...arguments);this.cwd=ge.String(\"--cwd\",{hidden:!0})}validateAndExecute(){if(typeof this.cwd<\"u\")throw new st(\"The --cwd option is ambiguous when used anywhere else than the very first parameter provided in the command line, before even the command path\");return super.validateAndExecute()}};Ge();Pt();qt();var sr=class extends st{constructor(e,r){let o=V.relative(e,r),a=V.join(e,Ut.fileName);super(`This command can only be run from within a workspace of your project (${o} isn't a workspace of ${a}).`)}};Ge();Pt();nA();Nl();g1();qt();var OAt=Ze(Jn());el();var nhe=()=>new Map([[\"@yarnpkg/cli\",W1],[\"@yarnpkg/core\",Y1],[\"@yarnpkg/fslib\",kw],[\"@yarnpkg/libzip\",p1],[\"@yarnpkg/parsers\",Ow],[\"@yarnpkg/shell\",E1],[\"clipanion\",Jw],[\"semver\",OAt],[\"typanion\",Vo]]);Ge();async function _y(t,e){let{project:r,workspace:o}=await kt.find(t,e);if(!o)throw new sr(r.cwd,e);return o}Ge();Pt();nA();Nl();g1();qt();var oPt=Ze(Jn());el();var K8={};Vt(K8,{AddCommand:()=>Yy,BinCommand:()=>Wy,CacheCleanCommand:()=>Ky,ClipanionCommand:()=>$y,ConfigCommand:()=>Xy,ConfigGetCommand:()=>Vy,ConfigSetCommand:()=>zy,ConfigUnsetCommand:()=>Jy,DedupeCommand:()=>Zy,EntryCommand:()=>tE,ExecCommand:()=>nE,ExplainCommand:()=>oE,ExplainPeerRequirementsCommand:()=>iE,HelpCommand:()=>eE,InfoCommand:()=>aE,LinkCommand:()=>cE,NodeCommand:()=>uE,PluginCheckCommand:()=>AE,PluginImportCommand:()=>hE,PluginImportSourcesCommand:()=>gE,PluginListCommand:()=>fE,PluginRemoveCommand:()=>dE,PluginRuntimeCommand:()=>mE,RebuildCommand:()=>yE,RemoveCommand:()=>EE,RunCommand:()=>wE,RunIndexCommand:()=>CE,SetResolutionCommand:()=>IE,SetVersionCommand:()=>sE,SetVersionSourcesCommand:()=>pE,UnlinkCommand:()=>BE,UpCommand:()=>vE,VersionCommand:()=>rE,WhyCommand:()=>DE,WorkspaceCommand:()=>kE,WorkspacesListCommand:()=>xE,YarnCommand:()=>lE,dedupeUtils:()=>rk,default:()=>Fgt,suggestUtils:()=>Zc});var Nde=Ze(X0());Ge();Ge();Ge();qt();var Y0e=Ze(J1());el();var Zc={};Vt(Zc,{Modifier:()=>m8,Strategy:()=>$x,Target:()=>X1,WorkspaceModifier:()=>_0e,applyModifier:()=>ipt,extractDescriptorFromPath:()=>y8,extractRangeModifier:()=>H0e,fetchDescriptorFrom:()=>E8,findProjectDescriptors:()=>G0e,getModifier:()=>Z1,getSuggestedDescriptors:()=>$1,makeWorkspaceDescriptor:()=>j0e,toWorkspaceModifier:()=>q0e});Ge();Ge();Pt();var d8=Ze(Jn()),rpt=\"workspace:\",X1=(o=>(o.REGULAR=\"dependencies\",o.DEVELOPMENT=\"devDependencies\",o.PEER=\"peerDependencies\",o))(X1||{}),m8=(o=>(o.CARET=\"^\",o.TILDE=\"~\",o.EXACT=\"\",o))(m8||{}),_0e=(o=>(o.CARET=\"^\",o.TILDE=\"~\",o.EXACT=\"*\",o))(_0e||{}),$x=(n=>(n.KEEP=\"keep\",n.REUSE=\"reuse\",n.PROJECT=\"project\",n.LATEST=\"latest\",n.CACHE=\"cache\",n))($x||{});function Z1(t,e){return t.exact?\"\":t.caret?\"^\":t.tilde?\"~\":e.configuration.get(\"defaultSemverRangePrefix\")}var npt=/^([\\^~]?)[0-9]+(?:\\.[0-9]+){0,2}(?:-\\S+)?$/;function H0e(t,{project:e}){let r=t.match(npt);return r?r[1]:e.configuration.get(\"defaultSemverRangePrefix\")}function ipt(t,e){let{protocol:r,source:o,params:a,selector:n}=G.parseRange(t.range);return d8.default.valid(n)&&(n=`${e}${t.range}`),G.makeDescriptor(t,G.makeRange({protocol:r,source:o,params:a,selector:n}))}function q0e(t){switch(t){case\"^\":return\"^\";case\"~\":return\"~\";case\"\":return\"*\";default:throw new Error(`Assertion failed: Unknown modifier: \"${t}\"`)}}function j0e(t,e){return G.makeDescriptor(t.anchoredDescriptor,`${rpt}${q0e(e)}`)}async function G0e(t,{project:e,target:r}){let o=new Map,a=n=>{let u=o.get(n.descriptorHash);return u||o.set(n.descriptorHash,u={descriptor:n,locators:[]}),u};for(let n of e.workspaces)if(r===\"peerDependencies\"){let u=n.manifest.peerDependencies.get(t.identHash);u!==void 0&&a(u).locators.push(n.anchoredLocator)}else{let u=n.manifest.dependencies.get(t.identHash),A=n.manifest.devDependencies.get(t.identHash);r===\"devDependencies\"?A!==void 0?a(A).locators.push(n.anchoredLocator):u!==void 0&&a(u).locators.push(n.anchoredLocator):u!==void 0?a(u).locators.push(n.anchoredLocator):A!==void 0&&a(A).locators.push(n.anchoredLocator)}return o}async function y8(t,{cwd:e,workspace:r}){return await spt(async o=>{V.isAbsolute(t)||(t=V.relative(r.cwd,V.resolve(e,t)),t.match(/^\\.{0,2}\\//)||(t=`./${t}`));let{project:a}=r,n=await E8(G.makeIdent(null,\"archive\"),t,{project:r.project,cache:o,workspace:r});if(!n)throw new Error(\"Assertion failed: The descriptor should have been found\");let u=new ki,A=a.configuration.makeResolver(),p=a.configuration.makeFetcher(),h={checksums:a.storedChecksums,project:a,cache:o,fetcher:p,report:u,resolver:A},E=A.bindDescriptor(n,r.anchoredLocator,h),I=G.convertDescriptorToLocator(E),v=await p.fetch(I,h),x=await Ut.find(v.prefixPath,{baseFs:v.packageFs});if(!x.name)throw new Error(\"Target path doesn't have a name\");return G.makeDescriptor(x.name,t)})}async function $1(t,{project:e,workspace:r,cache:o,target:a,fixed:n,modifier:u,strategies:A,maxResults:p=1/0}){if(!(p>=0))throw new Error(`Invalid maxResults (${p})`);let[h,E]=t.range!==\"unknown\"?n||Lr.validRange(t.range)||!t.range.match(/^[a-z0-9._-]+$/i)?[t.range,\"latest\"]:[\"unknown\",t.range]:[\"unknown\",\"latest\"];if(h!==\"unknown\")return{suggestions:[{descriptor:t,name:`Use ${G.prettyDescriptor(e.configuration,t)}`,reason:\"(unambiguous explicit request)\"}],rejections:[]};let I=typeof r<\"u\"&&r!==null&&r.manifest[a].get(t.identHash)||null,v=[],x=[],C=async R=>{try{await R()}catch(L){x.push(L)}};for(let R of A){if(v.length>=p)break;switch(R){case\"keep\":await C(async()=>{I&&v.push({descriptor:I,name:`Keep ${G.prettyDescriptor(e.configuration,I)}`,reason:\"(no changes)\"})});break;case\"reuse\":await C(async()=>{for(let{descriptor:L,locators:U}of(await G0e(t,{project:e,target:a})).values()){if(U.length===1&&U[0].locatorHash===r.anchoredLocator.locatorHash&&A.includes(\"keep\"))continue;let z=`(originally used by ${G.prettyLocator(e.configuration,U[0])}`;z+=U.length>1?` and ${U.length-1} other${U.length>2?\"s\":\"\"})`:\")\",v.push({descriptor:L,name:`Reuse ${G.prettyDescriptor(e.configuration,L)}`,reason:z})}});break;case\"cache\":await C(async()=>{for(let L of e.storedDescriptors.values())L.identHash===t.identHash&&v.push({descriptor:L,name:`Reuse ${G.prettyDescriptor(e.configuration,L)}`,reason:\"(already used somewhere in the lockfile)\"})});break;case\"project\":await C(async()=>{if(r.manifest.name!==null&&t.identHash===r.manifest.name.identHash)return;let L=e.tryWorkspaceByIdent(t);if(L===null)return;let U=j0e(L,u);v.push({descriptor:U,name:`Attach ${G.prettyDescriptor(e.configuration,U)}`,reason:`(local workspace at ${pe.pretty(e.configuration,L.relativeCwd,pe.Type.PATH)})`})});break;case\"latest\":{let L=e.configuration.get(\"enableNetwork\"),U=e.configuration.get(\"enableOfflineMode\");await C(async()=>{if(a===\"peerDependencies\")v.push({descriptor:G.makeDescriptor(t,\"*\"),name:\"Use *\",reason:\"(catch-all peer dependency pattern)\"});else if(!L&&!U)v.push({descriptor:null,name:\"Resolve from latest\",reason:pe.pretty(e.configuration,\"(unavailable because enableNetwork is toggled off)\",\"grey\")});else{let z=await E8(t,E,{project:e,cache:o,workspace:r,modifier:u});z&&v.push({descriptor:z,name:`Use ${G.prettyDescriptor(e.configuration,z)}`,reason:`(resolved from ${U?\"the cache\":\"latest\"})`})}})}break}}return{suggestions:v.slice(0,p),rejections:x.slice(0,p)}}async function E8(t,e,{project:r,cache:o,workspace:a,preserveModifier:n=!0,modifier:u}){let A=r.configuration.normalizeDependency(G.makeDescriptor(t,e)),p=new ki,h=r.configuration.makeFetcher(),E=r.configuration.makeResolver(),I={project:r,fetcher:h,cache:o,checksums:r.storedChecksums,report:p,cacheOptions:{skipIntegrityCheck:!0}},v={...I,resolver:E,fetchOptions:I},x=E.bindDescriptor(A,a.anchoredLocator,v),C=await E.getCandidates(x,{},v);if(C.length===0)return null;let R=C[0],{protocol:L,source:U,params:z,selector:te}=G.parseRange(G.convertToManifestRange(R.reference));if(L===r.configuration.get(\"defaultProtocol\")&&(L=null),d8.default.valid(te)){let ae=te;if(typeof u<\"u\")te=u+te;else if(n!==!1){let Ce=typeof n==\"string\"?n:A.range;te=H0e(Ce,{project:r})+te}let le=G.makeDescriptor(R,G.makeRange({protocol:L,source:U,params:z,selector:te}));(await E.getCandidates(r.configuration.normalizeDependency(le),{},v)).length!==1&&(te=ae)}return G.makeDescriptor(R,G.makeRange({protocol:L,source:U,params:z,selector:te}))}async function spt(t){return await oe.mktempPromise(async e=>{let r=Ke.create(e);return r.useWithSource(e,{enableMirror:!1,compressionLevel:0},e,{overwrite:!0}),await t(new Gr(e,{configuration:r,check:!1,immutable:!1}))})}var Yy=class extends ut{constructor(){super(...arguments);this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.fixed=ge.Boolean(\"-F,--fixed\",!1,{description:\"Store dependency tags as-is instead of resolving them\"});this.exact=ge.Boolean(\"-E,--exact\",!1,{description:\"Don't use any semver modifier on the resolved range\"});this.tilde=ge.Boolean(\"-T,--tilde\",!1,{description:\"Use the `~` semver modifier on the resolved range\"});this.caret=ge.Boolean(\"-C,--caret\",!1,{description:\"Use the `^` semver modifier on the resolved range\"});this.dev=ge.Boolean(\"-D,--dev\",!1,{description:\"Add a package as a dev dependency\"});this.peer=ge.Boolean(\"-P,--peer\",!1,{description:\"Add a package as a peer dependency\"});this.optional=ge.Boolean(\"-O,--optional\",!1,{description:\"Add / upgrade a package to an optional regular / peer dependency\"});this.preferDev=ge.Boolean(\"--prefer-dev\",!1,{description:\"Add / upgrade a package to a dev dependency\"});this.interactive=ge.Boolean(\"-i,--interactive\",{description:\"Reuse the specified package from other workspaces in the project\"});this.cached=ge.Boolean(\"--cached\",!1,{description:\"Reuse the highest version already used somewhere within the project\"});this.mode=ge.String(\"--mode\",{description:\"Change what artifacts installs generate\",validator:Js(hl)});this.silent=ge.Boolean(\"--silent\",{hidden:!0});this.packages=ge.Rest()}static{this.paths=[[\"add\"]]}static{this.usage=it.Usage({description:\"add dependencies to the project\",details:\"\\n      This command adds a package to the package.json for the nearest workspace.\\n\\n      - If it didn't exist before, the package will by default be added to the regular `dependencies` field, but this behavior can be overriden thanks to the `-D,--dev` flag (which will cause the dependency to be added to the `devDependencies` field instead) and the `-P,--peer` flag (which will do the same but for `peerDependencies`).\\n\\n      - If the package was already listed in your dependencies, it will by default be upgraded whether it's part of your `dependencies` or `devDependencies` (it won't ever update `peerDependencies`, though).\\n\\n      - If set, the `--prefer-dev` flag will operate as a more flexible `-D,--dev` in that it will add the package to your `devDependencies` if it isn't already listed in either `dependencies` or `devDependencies`, but it will also happily upgrade your `dependencies` if that's what you already use (whereas `-D,--dev` would throw an exception).\\n\\n      - If set, the `-O,--optional` flag will add the package to the `optionalDependencies` field and, in combination with the `-P,--peer` flag, it will add the package as an optional peer dependency. If the package was already listed in your `dependencies`, it will be upgraded to `optionalDependencies`. If the package was already listed in your `peerDependencies`, in combination with the `-P,--peer` flag, it will be upgraded to an optional peer dependency: `\\\"peerDependenciesMeta\\\": { \\\"<package>\\\": { \\\"optional\\\": true } }`\\n\\n      - If the added package doesn't specify a range at all its `latest` tag will be resolved and the returned version will be used to generate a new semver range (using the `^` modifier by default unless otherwise configured via the `defaultSemverRangePrefix` configuration, or the `~` modifier if `-T,--tilde` is specified, or no modifier at all if `-E,--exact` is specified). Two exceptions to this rule: the first one is that if the package is a workspace then its local version will be used, and the second one is that if you use `-P,--peer` the default range will be `*` and won't be resolved at all.\\n\\n      - If the added package specifies a range (such as `^1.0.0`, `latest`, or `rc`), Yarn will add this range as-is in the resulting package.json entry (in particular, tags such as `rc` will be encoded as-is rather than being converted into a semver range).\\n\\n      If the `--cached` option is used, Yarn will preferably reuse the highest version already used somewhere within the project, even if through a transitive dependency.\\n\\n      If the `-i,--interactive` option is used (or if the `preferInteractive` settings is toggled on) the command will first try to check whether other workspaces in the project use the specified package and, if so, will offer to reuse them.\\n\\n      If the `--mode=<mode>` option is set, Yarn will change which artifacts are generated. The modes currently supported are:\\n\\n      - `skip-build` will not run the build scripts at all. Note that this is different from setting `enableScripts` to false because the latter will disable build scripts, and thus affect the content of the artifacts generated on disk, whereas the former will just disable the build step - but not the scripts themselves, which just won't run.\\n\\n      - `update-lockfile` will skip the link step altogether, and only fetch packages that are missing from the lockfile (or that have no associated checksums). This mode is typically used by tools like Renovate or Dependabot to keep a lockfile up-to-date without incurring the full install cost.\\n\\n      For a compilation of all the supported protocols, please consult the dedicated page from our website: https://yarnpkg.com/protocols.\\n    \",examples:[[\"Add a regular package to the current workspace\",\"$0 add lodash\"],[\"Add a specific version for a package to the current workspace\",\"$0 add lodash@1.2.3\"],[\"Add a package from a GitHub repository (the master branch) to the current workspace using a URL\",\"$0 add lodash@https://github.com/lodash/lodash\"],[\"Add a package from a GitHub repository (the master branch) to the current workspace using the GitHub protocol\",\"$0 add lodash@github:lodash/lodash\"],[\"Add a package from a GitHub repository (the master branch) to the current workspace using the GitHub protocol (shorthand)\",\"$0 add lodash@lodash/lodash\"],[\"Add a package from a specific branch of a GitHub repository to the current workspace using the GitHub protocol (shorthand)\",\"$0 add lodash-es@lodash/lodash#es\"],[\"Add a local package (gzipped tarball format) to the current workspace\",\"$0 add local-package-name@file:../path/to/local-package-name-v0.1.2.tgz\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(!a)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState({restoreResolutions:!1});let u=this.fixed,A=r.isInteractive({interactive:this.interactive,stdout:this.context.stdout}),p=A||r.get(\"preferReuse\"),h=Z1(this,o),E=[p?\"reuse\":void 0,\"project\",this.cached?\"cache\":void 0,\"latest\"].filter(U=>typeof U<\"u\"),I=A?1/0:1,v=await Promise.all(this.packages.map(async U=>{let z=U.match(/^\\.{0,2}\\//)?await y8(U,{cwd:this.context.cwd,workspace:a}):G.tryParseDescriptor(U),te=U.match(/^(https?:|git@github)/);if(te)throw new st(`It seems you are trying to add a package using a ${pe.pretty(r,`${te[0]}...`,pe.Type.RANGE)} url; we now require package names to be explicitly specified.\nTry running the command again with the package name prefixed: ${pe.pretty(r,\"yarn add\",pe.Type.CODE)} ${pe.pretty(r,G.makeDescriptor(G.makeIdent(null,\"my-package\"),`${te[0]}...`),pe.Type.DESCRIPTOR)}`);if(!z)throw new st(`The ${pe.pretty(r,U,pe.Type.CODE)} string didn't match the required format (package-name@range). Did you perhaps forget to explicitly reference the package name?`);let ae=opt(a,z,{dev:this.dev,peer:this.peer,preferDev:this.preferDev,optional:this.optional});return await Promise.all(ae.map(async ce=>{let Ce=await $1(z,{project:o,workspace:a,cache:n,fixed:u,target:ce,modifier:h,strategies:E,maxResults:I});return{request:z,suggestedDescriptors:Ce,target:ce}}))})).then(U=>U.flat()),x=await AA.start({configuration:r,stdout:this.context.stdout,suggestInstall:!1},async U=>{for(let{request:z,suggestedDescriptors:{suggestions:te,rejections:ae}}of v)if(te.filter(ce=>ce.descriptor!==null).length===0){let[ce]=ae;if(typeof ce>\"u\")throw new Error(\"Assertion failed: Expected an error to have been set\");o.configuration.get(\"enableNetwork\")?U.reportError(27,`${G.prettyDescriptor(r,z)} can't be resolved to a satisfying range`):U.reportError(27,`${G.prettyDescriptor(r,z)} can't be resolved to a satisfying range (note: network resolution has been disabled)`),U.reportSeparator(),U.reportExceptionOnce(ce)}});if(x.hasErrors())return x.exitCode();let C=!1,R=[],L=[];for(let{suggestedDescriptors:{suggestions:U},target:z}of v){let te,ae=U.filter(de=>de.descriptor!==null),le=ae[0].descriptor,ce=ae.every(de=>G.areDescriptorsEqual(de.descriptor,le));ae.length===1||ce?te=le:(C=!0,{answer:te}=await(0,Y0e.prompt)({type:\"select\",name:\"answer\",message:\"Which range do you want to use?\",choices:U.map(({descriptor:de,name:Be,reason:Ee})=>de?{name:Be,hint:Ee,descriptor:de}:{name:Be,hint:Ee,disabled:!0}),onCancel:()=>process.exit(130),result(de){return this.find(de,\"descriptor\")},stdin:this.context.stdin,stdout:this.context.stdout}));let Ce=a.manifest[z].get(te.identHash);(typeof Ce>\"u\"||Ce.descriptorHash!==te.descriptorHash)&&(a.manifest[z].set(te.identHash,te),this.optional&&(z===\"dependencies\"?a.manifest.ensureDependencyMeta({...te,range:\"unknown\"}).optional=!0:z===\"peerDependencies\"&&(a.manifest.ensurePeerDependencyMeta({...te,range:\"unknown\"}).optional=!0)),typeof Ce>\"u\"?R.push([a,z,te,E]):L.push([a,z,Ce,te]))}return await r.triggerMultipleHooks(U=>U.afterWorkspaceDependencyAddition,R),await r.triggerMultipleHooks(U=>U.afterWorkspaceDependencyReplacement,L),C&&this.context.stdout.write(`\n`),await o.installWithNewReport({json:this.json,stdout:this.context.stdout,quiet:this.context.quiet},{cache:n,mode:this.mode})}};function opt(t,e,{dev:r,peer:o,preferDev:a,optional:n}){let u=t.manifest.dependencies.has(e.identHash),A=t.manifest.devDependencies.has(e.identHash),p=t.manifest.peerDependencies.has(e.identHash);if((r||o)&&u)throw new st(`Package \"${G.prettyIdent(t.project.configuration,e)}\" is already listed as a regular dependency - remove the -D,-P flags or remove it from your dependencies first`);if(!r&&!o&&p)throw new st(`Package \"${G.prettyIdent(t.project.configuration,e)}\" is already listed as a peer dependency - use either of -D or -P, or remove it from your peer dependencies first`);if(n&&A)throw new st(`Package \"${G.prettyIdent(t.project.configuration,e)}\" is already listed as a dev dependency - remove the -O flag or remove it from your dev dependencies first`);if(n&&!o&&p)throw new st(`Package \"${G.prettyIdent(t.project.configuration,e)}\" is already listed as a peer dependency - remove the -O flag or add the -P flag or remove it from your peer dependencies first`);if((r||a)&&n)throw new st(`Package \"${G.prettyIdent(t.project.configuration,e)}\" cannot simultaneously be a dev dependency and an optional dependency`);let h=[];return o&&h.push(\"peerDependencies\"),(r||a)&&h.push(\"devDependencies\"),n&&h.push(\"dependencies\"),h.length>0?h:A?[\"devDependencies\"]:p?[\"peerDependencies\"]:[\"dependencies\"]}Ge();Ge();qt();var Wy=class extends ut{constructor(){super(...arguments);this.verbose=ge.Boolean(\"-v,--verbose\",!1,{description:\"Print both the binary name and the locator of the package that provides the binary\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.name=ge.String({required:!1})}static{this.paths=[[\"bin\"]]}static{this.usage=it.Usage({description:\"get the path to a binary script\",details:`\n      When used without arguments, this command will print the list of all the binaries available in the current workspace. Adding the \\`-v,--verbose\\` flag will cause the output to contain both the binary name and the locator of the package that provides the binary.\n\n      When an argument is specified, this command will just print the path to the binary on the standard output and exit. Note that the reported path may be stored within a zip archive.\n    `,examples:[[\"List all the available binaries\",\"$0 bin\"],[\"Print the path to a specific binary\",\"$0 bin eslint\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,locator:a}=await kt.find(r,this.context.cwd);if(await o.restoreInstallState(),this.name){let A=(await An.getPackageAccessibleBinaries(a,{project:o})).get(this.name);if(!A)throw new st(`Couldn't find a binary named \"${this.name}\" for package \"${G.prettyLocator(r,a)}\"`);let[,p]=A;return this.context.stdout.write(`${p}\n`),0}return(await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout},async u=>{let A=await An.getPackageAccessibleBinaries(a,{project:o}),h=Array.from(A.keys()).reduce((E,I)=>Math.max(E,I.length),0);for(let[E,[I,v]]of A)u.reportJson({name:E,source:G.stringifyIdent(I),path:v});if(this.verbose)for(let[E,[I]]of A)u.reportInfo(null,`${E.padEnd(h,\" \")}   ${G.prettyLocator(r,I)}`);else for(let E of A.keys())u.reportInfo(null,E)})).exitCode()}};Ge();Pt();qt();var Ky=class extends ut{constructor(){super(...arguments);this.mirror=ge.Boolean(\"--mirror\",!1,{description:\"Remove the global cache files instead of the local cache files\"});this.all=ge.Boolean(\"--all\",!1,{description:\"Remove both the global cache files and the local cache files of the current project\"})}static{this.paths=[[\"cache\",\"clean\"],[\"cache\",\"clear\"]]}static{this.usage=it.Usage({description:\"remove the shared cache files\",details:`\n      This command will remove all the files from the cache.\n    `,examples:[[\"Remove all the local archives\",\"$0 cache clean\"],[\"Remove all the archives stored in the ~/.yarn directory\",\"$0 cache clean --mirror\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),o=await Gr.find(r);return(await Rt.start({configuration:r,stdout:this.context.stdout},async()=>{let n=(this.all||this.mirror)&&o.mirrorCwd!==null,u=!this.mirror;n&&(await oe.removePromise(o.mirrorCwd),await r.triggerHook(A=>A.cleanGlobalArtifacts,r)),u&&await oe.removePromise(o.cwd)})).exitCode()}};Ge();qt();var K0e=Ze(e2()),C8=ve(\"util\"),Vy=class extends ut{constructor(){super(...arguments);this.why=ge.Boolean(\"--why\",!1,{description:\"Print the explanation for why a setting has its value\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.unsafe=ge.Boolean(\"--no-redacted\",!1,{description:\"Don't redact secrets (such as tokens) from the output\"});this.name=ge.String()}static{this.paths=[[\"config\",\"get\"]]}static{this.usage=it.Usage({description:\"read a configuration settings\",details:`\n      This command will print a configuration setting.\n\n      Secrets (such as tokens) will be redacted from the output by default. If this behavior isn't desired, set the \\`--no-redacted\\` to get the untransformed value.\n    `,examples:[[\"Print a simple configuration setting\",\"yarn config get yarnPath\"],[\"Print a complex configuration setting\",\"yarn config get packageExtensions\"],[\"Print a nested field from the configuration\",`yarn config get 'npmScopes[\"my-company\"].npmRegistryServer'`],[\"Print a token from the configuration\",\"yarn config get npmAuthToken --no-redacted\"],[\"Print a configuration setting as JSON\",\"yarn config get packageExtensions --json\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),o=this.name.replace(/[.[].*$/,\"\"),a=this.name.replace(/^[^.[]*/,\"\");if(typeof r.settings.get(o)>\"u\")throw new st(`Couldn't find a configuration settings named \"${o}\"`);let u=r.getSpecial(o,{hideSecrets:!this.unsafe,getNativePaths:!0}),A=He.convertMapsToIndexableObjects(u),p=a?(0,K0e.default)(A,a):A,h=await Rt.start({configuration:r,includeFooter:!1,json:this.json,stdout:this.context.stdout},async E=>{E.reportJson(p)});if(!this.json){if(typeof p==\"string\")return this.context.stdout.write(`${p}\n`),h.exitCode();C8.inspect.styles.name=\"cyan\",this.context.stdout.write(`${(0,C8.inspect)(p,{depth:1/0,colors:r.get(\"enableColors\"),compact:!1})}\n`)}return h.exitCode()}};Ge();qt();var Mge=Ze(v8()),Oge=Ze(e2()),Uge=Ze(D8()),P8=ve(\"util\"),zy=class extends ut{constructor(){super(...arguments);this.json=ge.Boolean(\"--json\",!1,{description:\"Set complex configuration settings to JSON values\"});this.home=ge.Boolean(\"-H,--home\",!1,{description:\"Update the home configuration instead of the project configuration\"});this.name=ge.String();this.value=ge.String()}static{this.paths=[[\"config\",\"set\"]]}static{this.usage=it.Usage({description:\"change a configuration settings\",details:`\n      This command will set a configuration setting.\n\n      When used without the \\`--json\\` flag, it can only set a simple configuration setting (a string, a number, or a boolean).\n\n      When used with the \\`--json\\` flag, it can set both simple and complex configuration settings, including Arrays and Objects.\n    `,examples:[[\"Set a simple configuration setting (a string, a number, or a boolean)\",\"yarn config set initScope myScope\"],[\"Set a simple configuration setting (a string, a number, or a boolean) using the `--json` flag\",'yarn config set initScope --json \\\\\"myScope\\\\\"'],[\"Set a complex configuration setting (an Array) using the `--json` flag\",`yarn config set unsafeHttpWhitelist --json '[\"*.example.com\", \"example.com\"]'`],[\"Set a complex configuration setting (an Object) using the `--json` flag\",`yarn config set packageExtensions --json '{ \"@babel/parser@*\": { \"dependencies\": { \"@babel/types\": \"*\" } } }'`],[\"Set a nested configuration setting\",'yarn config set npmScopes.company.npmRegistryServer \"https://npm.example.com\"'],[\"Set a nested configuration setting using indexed access for non-simple keys\",`yarn config set 'npmRegistries[\"//npm.example.com\"].npmAuthToken' \"ffffffff-ffff-ffff-ffff-ffffffffffff\"`]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),o=()=>{if(!r.projectCwd)throw new st(\"This command must be run from within a project folder\");return r.projectCwd},a=this.name.replace(/[.[].*$/,\"\"),n=this.name.replace(/^[^.[]*\\.?/,\"\");if(typeof r.settings.get(a)>\"u\")throw new st(`Couldn't find a configuration settings named \"${a}\"`);if(a===\"enableStrictSettings\")throw new st(\"This setting only affects the file it's in, and thus cannot be set from the CLI\");let A=this.json?JSON.parse(this.value):this.value;await(this.home?C=>Ke.updateHomeConfiguration(C):C=>Ke.updateConfiguration(o(),C))(C=>{if(n){let R=(0,Mge.default)(C);return(0,Uge.default)(R,this.name,A),R}else return{...C,[a]:A}});let E=(await Ke.find(this.context.cwd,this.context.plugins)).getSpecial(a,{hideSecrets:!0,getNativePaths:!0}),I=He.convertMapsToIndexableObjects(E),v=n?(0,Oge.default)(I,n):I;return(await Rt.start({configuration:r,includeFooter:!1,stdout:this.context.stdout},async C=>{P8.inspect.styles.name=\"cyan\",C.reportInfo(0,`Successfully set ${this.name} to ${(0,P8.inspect)(v,{depth:1/0,colors:r.get(\"enableColors\"),compact:!1})}`)})).exitCode()}};Ge();qt();var Jge=Ze(v8()),Xge=Ze(jge()),Zge=Ze(S8()),Jy=class extends ut{constructor(){super(...arguments);this.home=ge.Boolean(\"-H,--home\",!1,{description:\"Update the home configuration instead of the project configuration\"});this.name=ge.String()}static{this.paths=[[\"config\",\"unset\"]]}static{this.usage=it.Usage({description:\"unset a configuration setting\",details:`\n      This command will unset a configuration setting.\n    `,examples:[[\"Unset a simple configuration setting\",\"yarn config unset initScope\"],[\"Unset a complex configuration setting\",\"yarn config unset packageExtensions\"],[\"Unset a nested configuration setting\",\"yarn config unset npmScopes.company.npmRegistryServer\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),o=()=>{if(!r.projectCwd)throw new st(\"This command must be run from within a project folder\");return r.projectCwd},a=this.name.replace(/[.[].*$/,\"\"),n=this.name.replace(/^[^.[]*\\.?/,\"\");if(typeof r.settings.get(a)>\"u\")throw new st(`Couldn't find a configuration settings named \"${a}\"`);let A=this.home?h=>Ke.updateHomeConfiguration(h):h=>Ke.updateConfiguration(o(),h);return(await Rt.start({configuration:r,includeFooter:!1,stdout:this.context.stdout},async h=>{let E=!1;await A(I=>{if(!(0,Xge.default)(I,this.name))return h.reportWarning(0,`Configuration doesn't contain setting ${this.name}; there is nothing to unset`),E=!0,I;let v=n?(0,Jge.default)(I):{...I};return(0,Zge.default)(v,this.name),v}),E||h.reportInfo(0,`Successfully unset ${this.name}`)})).exitCode()}};Ge();Pt();qt();var tk=ve(\"util\"),Xy=class extends ut{constructor(){super(...arguments);this.noDefaults=ge.Boolean(\"--no-defaults\",!1,{description:\"Omit the default values from the display\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.verbose=ge.Boolean(\"-v,--verbose\",{hidden:!0});this.why=ge.Boolean(\"--why\",{hidden:!0});this.names=ge.Rest()}static{this.paths=[[\"config\"]]}static{this.usage=it.Usage({description:\"display the current configuration\",details:`\n      This command prints the current active configuration settings.\n    `,examples:[[\"Print the active configuration settings\",\"$0 config\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins,{strict:!1}),o=await uy({configuration:r,stdout:this.context.stdout,forceError:this.json},[{option:this.verbose,message:\"The --verbose option is deprecated, the settings' descriptions are now always displayed\"},{option:this.why,message:\"The --why option is deprecated, the settings' sources are now always displayed\"}]);if(o!==null)return o;let a=this.names.length>0?[...new Set(this.names)].sort():[...r.settings.keys()].sort(),n,u=await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout,includeFooter:!1},async A=>{if(r.invalid.size>0&&!this.json){for(let[p,h]of r.invalid)A.reportError(34,`Invalid configuration key \"${p}\" in ${h}`);A.reportSeparator()}if(this.json)for(let p of a){let h=r.settings.get(p);typeof h>\"u\"&&A.reportError(34,`No configuration key named \"${p}\"`);let E=r.getSpecial(p,{hideSecrets:!0,getNativePaths:!0}),I=r.sources.get(p)??\"<default>\",v=I&&I[0]!==\"<\"?ue.fromPortablePath(I):I;A.reportJson({key:p,effective:E,source:v,...h})}else{let p={breakLength:1/0,colors:r.get(\"enableColors\"),maxArrayLength:2},h={},E={children:h};for(let I of a){if(this.noDefaults&&!r.sources.has(I))continue;let v=r.settings.get(I),x=r.sources.get(I)??\"<default>\",C=r.getSpecial(I,{hideSecrets:!0,getNativePaths:!0}),R={Description:{label:\"Description\",value:pe.tuple(pe.Type.MARKDOWN,{text:v.description,format:this.cli.format(),paragraphs:!1})},Source:{label:\"Source\",value:pe.tuple(x[0]===\"<\"?pe.Type.CODE:pe.Type.PATH,x)}};h[I]={value:pe.tuple(pe.Type.CODE,I),children:R};let L=(U,z)=>{for(let[te,ae]of z)if(ae instanceof Map){let le={};U[te]={children:le},L(le,ae)}else U[te]={label:te,value:pe.tuple(pe.Type.NO_HINT,(0,tk.inspect)(ae,p))}};C instanceof Map?L(R,C):R.Value={label:\"Value\",value:pe.tuple(pe.Type.NO_HINT,(0,tk.inspect)(C,p))}}a.length!==1&&(n=void 0),fs.emitTree(E,{configuration:r,json:this.json,stdout:this.context.stdout,separators:2})}});if(!this.json&&typeof n<\"u\"){let A=a[0],p=(0,tk.inspect)(r.getSpecial(A,{hideSecrets:!0,getNativePaths:!0}),{colors:r.get(\"enableColors\")});this.context.stdout.write(`\n`),this.context.stdout.write(`${p}\n`)}return u.exitCode()}};Ge();qt();el();var rk={};Vt(rk,{Strategy:()=>t2,acceptedStrategies:()=>q0t,dedupe:()=>x8});Ge();Ge();var $ge=Ze($o()),t2=(e=>(e.HIGHEST=\"highest\",e))(t2||{}),q0t=new Set(Object.values(t2)),j0t={highest:async(t,e,{resolver:r,fetcher:o,resolveOptions:a,fetchOptions:n})=>{let u=new Map;for(let[p,h]of t.storedResolutions){let E=t.storedDescriptors.get(p);if(typeof E>\"u\")throw new Error(`Assertion failed: The descriptor (${p}) should have been registered`);He.getSetWithDefault(u,E.identHash).add(h)}let A=new Map(He.mapAndFilter(t.storedDescriptors.values(),p=>G.isVirtualDescriptor(p)?He.mapAndFilter.skip:[p.descriptorHash,He.makeDeferred()]));for(let p of t.storedDescriptors.values()){let h=A.get(p.descriptorHash);if(typeof h>\"u\")throw new Error(`Assertion failed: The descriptor (${p.descriptorHash}) should have been registered`);let E=t.storedResolutions.get(p.descriptorHash);if(typeof E>\"u\")throw new Error(`Assertion failed: The resolution (${p.descriptorHash}) should have been registered`);let I=t.originalPackages.get(E);if(typeof I>\"u\")throw new Error(`Assertion failed: The package (${E}) should have been registered`);Promise.resolve().then(async()=>{let v=r.getResolutionDependencies(p,a),x=Object.fromEntries(await He.allSettledSafe(Object.entries(v).map(async([te,ae])=>{let le=A.get(ae.descriptorHash);if(typeof le>\"u\")throw new Error(`Assertion failed: The descriptor (${ae.descriptorHash}) should have been registered`);let ce=await le.promise;if(!ce)throw new Error(\"Assertion failed: Expected the dependency to have been through the dedupe process itself\");return[te,ce.updatedPackage]})));if(e.length&&!$ge.default.isMatch(G.stringifyIdent(p),e)||!r.shouldPersistResolution(I,a))return I;let C=u.get(p.identHash);if(typeof C>\"u\")throw new Error(`Assertion failed: The resolutions (${p.identHash}) should have been registered`);if(C.size===1)return I;let R=[...C].map(te=>{let ae=t.originalPackages.get(te);if(typeof ae>\"u\")throw new Error(`Assertion failed: The package (${te}) should have been registered`);return ae}),L=await r.getSatisfying(p,x,R,a),U=L.locators?.[0];if(typeof U>\"u\"||!L.sorted)return I;let z=t.originalPackages.get(U.locatorHash);if(typeof z>\"u\")throw new Error(`Assertion failed: The package (${U.locatorHash}) should have been registered`);return z}).then(async v=>{let x=await t.preparePackage(v,{resolver:r,resolveOptions:a});h.resolve({descriptor:p,currentPackage:I,updatedPackage:v,resolvedPackage:x})}).catch(v=>{h.reject(v)})}return[...A.values()].map(p=>p.promise)}};async function x8(t,{strategy:e,patterns:r,cache:o,report:a}){let{configuration:n}=t,u=new ki,A=n.makeResolver(),p=n.makeFetcher(),h={cache:o,checksums:t.storedChecksums,fetcher:p,project:t,report:u,cacheOptions:{skipIntegrityCheck:!0}},E={project:t,resolver:A,report:u,fetchOptions:h};return await a.startTimerPromise(\"Deduplication step\",async()=>{let I=j0t[e],v=await I(t,r,{resolver:A,resolveOptions:E,fetcher:p,fetchOptions:h}),x=Zs.progressViaCounter(v.length);await a.reportProgress(x);let C=0;await Promise.all(v.map(U=>U.then(z=>{if(z===null||z.currentPackage.locatorHash===z.updatedPackage.locatorHash)return;C++;let{descriptor:te,currentPackage:ae,updatedPackage:le}=z;a.reportInfo(0,`${G.prettyDescriptor(n,te)} can be deduped from ${G.prettyLocator(n,ae)} to ${G.prettyLocator(n,le)}`),a.reportJson({descriptor:G.stringifyDescriptor(te),currentResolution:G.stringifyLocator(ae),updatedResolution:G.stringifyLocator(le)}),t.storedResolutions.set(te.descriptorHash,le.locatorHash)}).finally(()=>x.tick())));let R;switch(C){case 0:R=\"No packages\";break;case 1:R=\"One package\";break;default:R=`${C} packages`}let L=pe.pretty(n,e,pe.Type.CODE);return a.reportInfo(0,`${R} can be deduped using the ${L} strategy`),C})}var Zy=class extends ut{constructor(){super(...arguments);this.strategy=ge.String(\"-s,--strategy\",\"highest\",{description:\"The strategy to use when deduping dependencies\",validator:Js(t2)});this.check=ge.Boolean(\"-c,--check\",!1,{description:\"Exit with exit code 1 when duplicates are found, without persisting the dependency tree\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.mode=ge.String(\"--mode\",{description:\"Change what artifacts installs generate\",validator:Js(hl)});this.patterns=ge.Rest()}static{this.paths=[[\"dedupe\"]]}static{this.usage=it.Usage({description:\"deduplicate dependencies with overlapping ranges\",details:\"\\n      Duplicates are defined as descriptors with overlapping ranges being resolved and locked to different locators. They are a natural consequence of Yarn's deterministic installs, but they can sometimes pile up and unnecessarily increase the size of your project.\\n\\n      This command dedupes dependencies in the current project using different strategies (only one is implemented at the moment):\\n\\n      - `highest`: Reuses (where possible) the locators with the highest versions. This means that dependencies can only be upgraded, never downgraded. It's also guaranteed that it never takes more than a single pass to dedupe the entire dependency tree.\\n\\n      **Note:** Even though it never produces a wrong dependency tree, this command should be used with caution, as it modifies the dependency tree, which can sometimes cause problems when packages don't strictly follow semver recommendations. Because of this, it is recommended to also review the changes manually.\\n\\n      If set, the `-c,--check` flag will only report the found duplicates, without persisting the modified dependency tree. If changes are found, the command will exit with a non-zero exit code, making it suitable for CI purposes.\\n\\n      If the `--mode=<mode>` option is set, Yarn will change which artifacts are generated. The modes currently supported are:\\n\\n      - `skip-build` will not run the build scripts at all. Note that this is different from setting `enableScripts` to false because the latter will disable build scripts, and thus affect the content of the artifacts generated on disk, whereas the former will just disable the build step - but not the scripts themselves, which just won't run.\\n\\n      - `update-lockfile` will skip the link step altogether, and only fetch packages that are missing from the lockfile (or that have no associated checksums). This mode is typically used by tools like Renovate or Dependabot to keep a lockfile up-to-date without incurring the full install cost.\\n\\n      This command accepts glob patterns as arguments (if valid Idents and supported by [micromatch](https://github.com/micromatch/micromatch)). Make sure to escape the patterns, to prevent your own shell from trying to expand them.\\n\\n      ### In-depth explanation:\\n\\n      Yarn doesn't deduplicate dependencies by default, otherwise installs wouldn't be deterministic and the lockfile would be useless. What it actually does is that it tries to not duplicate dependencies in the first place.\\n\\n      **Example:** If `foo@^2.3.4` (a dependency of a dependency) has already been resolved to `foo@2.3.4`, running `yarn add foo@*`will cause Yarn to reuse `foo@2.3.4`, even if the latest `foo` is actually `foo@2.10.14`, thus preventing unnecessary duplication.\\n\\n      Duplication happens when Yarn can't unlock dependencies that have already been locked inside the lockfile.\\n\\n      **Example:** If `foo@^2.3.4` (a dependency of a dependency) has already been resolved to `foo@2.3.4`, running `yarn add foo@2.10.14` will cause Yarn to install `foo@2.10.14` because the existing resolution doesn't satisfy the range `2.10.14`. This behavior can lead to (sometimes) unwanted duplication, since now the lockfile contains 2 separate resolutions for the 2 `foo` descriptors, even though they have overlapping ranges, which means that the lockfile can be simplified so that both descriptors resolve to `foo@2.10.14`.\\n    \",examples:[[\"Dedupe all packages\",\"$0 dedupe\"],[\"Dedupe all packages using a specific strategy\",\"$0 dedupe --strategy highest\"],[\"Dedupe a specific package\",\"$0 dedupe lodash\"],[\"Dedupe all packages with the `@babel/*` scope\",\"$0 dedupe '@babel/*'\"],[\"Check for duplicates (can be used as a CI step)\",\"$0 dedupe --check\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o}=await kt.find(r,this.context.cwd),a=await Gr.find(r);await o.restoreInstallState({restoreResolutions:!1});let n=0,u=await Rt.start({configuration:r,includeFooter:!1,stdout:this.context.stdout,json:this.json},async A=>{n=await x8(o,{strategy:this.strategy,patterns:this.patterns,cache:a,report:A})});return u.hasErrors()?u.exitCode():this.check?n?1:0:await o.installWithNewReport({json:this.json,stdout:this.context.stdout},{cache:a,mode:this.mode})}};Ge();qt();var $y=class extends ut{static{this.paths=[[\"--clipanion=definitions\"]]}async execute(){let{plugins:e}=await Ke.find(this.context.cwd,this.context.plugins),r=[];for(let u of e){let{commands:A}=u[1];if(A){let h=Jo.from(A).definitions();r.push([u[0],h])}}let o=this.cli.definitions(),a=(u,A)=>u.split(\" \").slice(1).join()===A.split(\" \").slice(1).join(),n=ede()[\"@yarnpkg/builder\"].bundles.standard;for(let u of r){let A=u[1];for(let p of A)o.find(h=>a(h.path,p.path)).plugin={name:u[0],isDefault:n.includes(u[0])}}this.context.stdout.write(`${JSON.stringify(o,null,2)}\n`)}};var eE=class extends ut{static{this.paths=[[\"help\"],[\"--help\"],[\"-h\"]]}async execute(){this.context.stdout.write(this.cli.usage(null))}};Ge();Pt();qt();var tE=class extends ut{constructor(){super(...arguments);this.leadingArgument=ge.String();this.args=ge.Proxy()}async execute(){if(this.leadingArgument.match(/[\\\\/]/)&&!G.tryParseIdent(this.leadingArgument)){let r=V.resolve(this.context.cwd,ue.toPortablePath(this.leadingArgument));return await this.cli.run(this.args,{cwd:r})}else return await this.cli.run([\"run\",this.leadingArgument,...this.args])}};Ge();var rE=class extends ut{static{this.paths=[[\"-v\"],[\"--version\"]]}async execute(){this.context.stdout.write(`${nn||\"<unknown>\"}\n`)}};Ge();Ge();qt();var nE=class extends ut{constructor(){super(...arguments);this.commandName=ge.String();this.args=ge.Proxy()}static{this.paths=[[\"exec\"]]}static{this.usage=it.Usage({description:\"execute a shell script\",details:`\n      This command simply executes a shell script within the context of the root directory of the active workspace using the portable shell.\n\n      It also makes sure to call it in a way that's compatible with the current project (for example, on PnP projects the environment will be setup in such a way that PnP will be correctly injected into the environment).\n    `,examples:[[\"Execute a single shell command\",\"$0 exec echo Hello World\"],[\"Execute a shell script\",'$0 exec \"tsc & babel src --out-dir lib\"']]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,locator:a}=await kt.find(r,this.context.cwd);return await o.restoreInstallState(),await An.executePackageShellcode(a,this.commandName,this.args,{cwd:this.context.cwd,stdin:this.context.stdin,stdout:this.context.stdout,stderr:this.context.stderr,project:o})}};Ge();qt();el();var iE=class extends ut{constructor(){super(...arguments);this.hash=ge.String({required:!1,validator:YD(om(),[qw(/^p[0-9a-f]{5}$/)])})}static{this.paths=[[\"explain\",\"peer-requirements\"]]}static{this.usage=it.Usage({description:\"explain a set of peer requirements\",details:`\n      A peer requirement represents all peer requests that a subject must satisfy when providing a requested package to requesters.\n\n      When the hash argument is specified, this command prints a detailed explanation of the peer requirement corresponding to the hash and whether it is satisfied or not.\n\n      When used without arguments, this command lists all peer requirements and the corresponding hash that can be used to get detailed information about a given requirement.\n\n      **Note:** A hash is a six-letter p-prefixed code that can be obtained from peer dependency warnings or from the list of all peer requirements (\\`yarn explain peer-requirements\\`).\n    `,examples:[[\"Explain the corresponding peer requirement for a hash\",\"$0 explain peer-requirements p1a4ed\"],[\"List all peer requirements\",\"$0 explain peer-requirements\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o}=await kt.find(r,this.context.cwd);return await o.restoreInstallState({restoreResolutions:!1}),await o.applyLightResolution(),typeof this.hash<\"u\"?await Y0t(this.hash,o,{stdout:this.context.stdout}):await W0t(o,{stdout:this.context.stdout})}};async function Y0t(t,e,r){let o=e.peerRequirementNodes.get(t);if(typeof o>\"u\")throw new Error(`No peerDependency requirements found for hash: \"${t}\"`);let a=new Set,n=p=>a.has(p.requester.locatorHash)?{value:pe.tuple(pe.Type.DEPENDENT,{locator:p.requester,descriptor:p.descriptor}),children:p.children.size>0?[{value:pe.tuple(pe.Type.NO_HINT,\"...\")}]:[]}:(a.add(p.requester.locatorHash),{value:pe.tuple(pe.Type.DEPENDENT,{locator:p.requester,descriptor:p.descriptor}),children:Object.fromEntries(Array.from(p.children.values(),h=>[G.stringifyLocator(h.requester),n(h)]))}),u=e.peerWarnings.find(p=>p.hash===t);return(await Rt.start({configuration:e.configuration,stdout:r.stdout,includeFooter:!1,includePrefix:!1},async p=>{let h=pe.mark(e.configuration),E=u?h.Cross:h.Check;if(p.reportInfo(0,`Package ${pe.pretty(e.configuration,o.subject,pe.Type.LOCATOR)} is requested to provide ${pe.pretty(e.configuration,o.ident,pe.Type.IDENT)} by its descendants`),p.reportSeparator(),p.reportInfo(0,pe.pretty(e.configuration,o.subject,pe.Type.LOCATOR)),fs.emitTree({children:Object.fromEntries(Array.from(o.requests.values(),I=>[G.stringifyLocator(I.requester),n(I)]))},{configuration:e.configuration,stdout:r.stdout,json:!1}),p.reportSeparator(),o.provided.range===\"missing:\"){let I=u?\"\":\" , but all peer requests are optional\";p.reportInfo(0,`${E} Package ${pe.pretty(e.configuration,o.subject,pe.Type.LOCATOR)} does not provide ${pe.pretty(e.configuration,o.ident,pe.Type.IDENT)}${I}.`)}else{let I=e.storedResolutions.get(o.provided.descriptorHash);if(!I)throw new Error(\"Assertion failed: Expected the descriptor to be registered\");let v=e.storedPackages.get(I);if(!v)throw new Error(\"Assertion failed: Expected the package to be registered\");p.reportInfo(0,`${E} Package ${pe.pretty(e.configuration,o.subject,pe.Type.LOCATOR)} provides ${pe.pretty(e.configuration,o.ident,pe.Type.IDENT)} with version ${G.prettyReference(e.configuration,v.version??\"0.0.0\")}, ${u?\"which does not satisfy all requests.\":\"which satisfies all requests\"}`),u?.type===3&&(u.range?p.reportInfo(0,`  The combined requested range is ${pe.pretty(e.configuration,u.range,pe.Type.RANGE)}`):p.reportInfo(0,\"  Unfortunately, the requested ranges have no overlap\"))}})).exitCode()}async function W0t(t,e){return(await Rt.start({configuration:t.configuration,stdout:e.stdout,includeFooter:!1,includePrefix:!1},async o=>{let a=pe.mark(t.configuration),n=He.sortMap(t.peerRequirementNodes,[([,u])=>G.stringifyLocator(u.subject),([,u])=>G.stringifyIdent(u.ident)]);for(let[,u]of n.values()){if(!u.root)continue;let A=t.peerWarnings.find(E=>E.hash===u.hash),p=[...G.allPeerRequests(u)],h;if(p.length>2?h=` and ${p.length-1} other dependencies`:p.length===2?h=\" and 1 other dependency\":h=\"\",u.provided.range!==\"missing:\"){let E=t.storedResolutions.get(u.provided.descriptorHash);if(!E)throw new Error(\"Assertion failed: Expected the resolution to have been registered\");let I=t.storedPackages.get(E);if(!I)throw new Error(\"Assertion failed: Expected the provided package to have been registered\");let v=`${pe.pretty(t.configuration,u.hash,pe.Type.CODE)} \\u2192 ${A?a.Cross:a.Check} ${G.prettyLocator(t.configuration,u.subject)} provides ${G.prettyLocator(t.configuration,I)} to ${G.prettyLocator(t.configuration,p[0].requester)}${h}`;A?o.reportWarning(0,v):o.reportInfo(0,v)}else{let E=`${pe.pretty(t.configuration,u.hash,pe.Type.CODE)} \\u2192 ${A?a.Cross:a.Check} ${G.prettyLocator(t.configuration,u.subject)} doesn't provide ${G.prettyIdent(t.configuration,u.ident)} to ${G.prettyLocator(t.configuration,p[0].requester)}${h}`;A?o.reportWarning(0,E):o.reportInfo(0,E)}}})).exitCode()}Ge();qt();el();Ge();Ge();Pt();qt();var tde=Ze(Jn()),sE=class extends ut{constructor(){super(...arguments);this.useYarnPath=ge.Boolean(\"--yarn-path\",{description:\"Set the yarnPath setting even if the version can be accessed by Corepack\"});this.onlyIfNeeded=ge.Boolean(\"--only-if-needed\",!1,{description:\"Only lock the Yarn version if it isn't already locked\"});this.version=ge.String()}static{this.paths=[[\"set\",\"version\"]]}static{this.usage=it.Usage({description:\"lock the Yarn version used by the project\",details:\"\\n      This command will set a specific release of Yarn to be used by Corepack: https://nodejs.org/api/corepack.html.\\n\\n      By default it only will set the `packageManager` field at the root of your project, but if the referenced release cannot be represented this way, if you already have `yarnPath` configured, or if you set the `--yarn-path` command line flag, then the release will also be downloaded from the Yarn GitHub repository, stored inside your project, and referenced via the `yarnPath` settings from your project `.yarnrc.yml` file.\\n\\n      A very good use case for this command is to enforce the version of Yarn used by any single member of your team inside the same project - by doing this you ensure that you have control over Yarn upgrades and downgrades (including on your deployment servers), and get rid of most of the headaches related to someone using a slightly different version and getting different behavior.\\n\\n      The version specifier can be:\\n\\n      - a tag:\\n        - `latest` / `berry` / `stable` -> the most recent stable berry (`>=2.0.0`) release\\n        - `canary` -> the most recent canary (release candidate) berry (`>=2.0.0`) release\\n        - `classic` -> the most recent classic (`^0.x || ^1.x`) release\\n\\n      - a semver range (e.g. `2.x`) -> the most recent version satisfying the range (limited to berry releases)\\n\\n      - a semver version (e.g. `2.4.1`, `1.22.1`)\\n\\n      - a local file referenced through either a relative or absolute path\\n\\n      - `self` -> the version used to invoke the command\\n    \",examples:[[\"Download the latest release from the Yarn repository\",\"$0 set version latest\"],[\"Download the latest canary release from the Yarn repository\",\"$0 set version canary\"],[\"Download the latest classic release from the Yarn repository\",\"$0 set version classic\"],[\"Download the most recent Yarn 3 build\",\"$0 set version 3.x\"],[\"Download a specific Yarn 2 build\",\"$0 set version 2.0.0-rc.30\"],[\"Switch back to a specific Yarn 1 release\",\"$0 set version 1.22.1\"],[\"Use a release from the local filesystem\",\"$0 set version ./yarn.cjs\"],[\"Use a release from a URL\",\"$0 set version https://repo.yarnpkg.com/3.1.0/packages/yarnpkg-cli/bin/yarn.js\"],[\"Download the version used to invoke the command\",\"$0 set version self\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins);if(this.onlyIfNeeded&&r.get(\"yarnPath\")){let A=r.sources.get(\"yarnPath\");if(!A)throw new Error(\"Assertion failed: Expected 'yarnPath' to have a source\");let p=r.projectCwd??r.startingCwd;if(V.contains(p,A))return 0}let o=()=>{if(typeof nn>\"u\")throw new st(\"The --install flag can only be used without explicit version specifier from the Yarn CLI\");return`file://${process.argv[1]}`},a,n=(A,p)=>({version:p,url:A.replace(/\\{\\}/g,p)});if(this.version===\"self\")a={url:o(),version:nn??\"self\"};else if(this.version===\"latest\"||this.version===\"berry\"||this.version===\"stable\")a=n(\"https://repo.yarnpkg.com/{}/packages/yarnpkg-cli/bin/yarn.js\",await r2(r,\"stable\"));else if(this.version===\"canary\")a=n(\"https://repo.yarnpkg.com/{}/packages/yarnpkg-cli/bin/yarn.js\",await r2(r,\"canary\"));else if(this.version===\"classic\")a={url:\"https://classic.yarnpkg.com/latest.js\",version:\"classic\"};else if(this.version.match(/^https?:/))a={url:this.version,version:\"remote\"};else if(this.version.match(/^\\.{0,2}[\\\\/]/)||ue.isAbsolute(this.version))a={url:`file://${V.resolve(ue.toPortablePath(this.version))}`,version:\"file\"};else if(Lr.satisfiesWithPrereleases(this.version,\">=2.0.0\"))a=n(\"https://repo.yarnpkg.com/{}/packages/yarnpkg-cli/bin/yarn.js\",this.version);else if(Lr.satisfiesWithPrereleases(this.version,\"^0.x || ^1.x\"))a=n(\"https://github.com/yarnpkg/yarn/releases/download/v{}/yarn-{}.js\",this.version);else if(Lr.validRange(this.version))a=n(\"https://repo.yarnpkg.com/{}/packages/yarnpkg-cli/bin/yarn.js\",await K0t(r,this.version));else throw new st(`Invalid version descriptor \"${this.version}\"`);return(await Rt.start({configuration:r,stdout:this.context.stdout,includeLogs:!this.context.quiet},async A=>{let p=async()=>{let h=\"file://\";return a.url.startsWith(h)?(A.reportInfo(0,`Retrieving ${pe.pretty(r,a.url,pe.Type.PATH)}`),await oe.readFilePromise(a.url.slice(h.length))):(A.reportInfo(0,`Downloading ${pe.pretty(r,a.url,pe.Type.URL)}`),await sn.get(a.url,{configuration:r}))};await k8(r,a.version,p,{report:A,useYarnPath:this.useYarnPath})})).exitCode()}};async function K0t(t,e){let o=(await sn.get(\"https://repo.yarnpkg.com/tags\",{configuration:t,jsonResponse:!0})).tags.filter(a=>Lr.satisfiesWithPrereleases(a,e));if(o.length===0)throw new st(`No matching release found for range ${pe.pretty(t,e,pe.Type.RANGE)}.`);return o[0]}async function r2(t,e){let r=await sn.get(\"https://repo.yarnpkg.com/tags\",{configuration:t,jsonResponse:!0});if(!r.latest[e])throw new st(`Tag ${pe.pretty(t,e,pe.Type.RANGE)} not found`);return r.latest[e]}async function k8(t,e,r,{report:o,useYarnPath:a}){let n,u=async()=>(typeof n>\"u\"&&(n=await r()),n);if(e===null){let te=await u();await oe.mktempPromise(async ae=>{let le=V.join(ae,\"yarn.cjs\");await oe.writeFilePromise(le,te);let{stdout:ce}=await Ur.execvp(process.execPath,[ue.fromPortablePath(le),\"--version\"],{cwd:ae,env:{...t.env,YARN_IGNORE_PATH:\"1\"}});if(e=ce.trim(),!tde.default.valid(e))throw new Error(`Invalid semver version. ${pe.pretty(t,\"yarn --version\",pe.Type.CODE)} returned:\n${e}`)})}let A=t.projectCwd??t.startingCwd,p=V.resolve(A,\".yarn/releases\"),h=V.resolve(p,`yarn-${e}.cjs`),E=V.relative(t.startingCwd,h),I=He.isTaggedYarnVersion(e),v=t.get(\"yarnPath\"),x=!I,C=x||!!v||!!a;if(a===!1){if(x)throw new Jt(0,\"You explicitly opted out of yarnPath usage in your command line, but the version you specified cannot be represented by Corepack\");C=!1}else!C&&!process.env.COREPACK_ROOT&&(o.reportWarning(0,`You don't seem to have ${pe.applyHyperlink(t,\"Corepack\",\"https://nodejs.org/api/corepack.html\")} enabled; we'll have to rely on ${pe.applyHyperlink(t,\"yarnPath\",\"https://yarnpkg.com/configuration/yarnrc#yarnPath\")} instead`),C=!0);if(C){let te=await u();o.reportInfo(0,`Saving the new release in ${pe.pretty(t,E,\"magenta\")}`),await oe.removePromise(V.dirname(h)),await oe.mkdirPromise(V.dirname(h),{recursive:!0}),await oe.writeFilePromise(h,te,{mode:493}),await Ke.updateConfiguration(A,{yarnPath:V.relative(A,h)})}else await oe.removePromise(V.dirname(h)),await Ke.updateConfiguration(A,{yarnPath:Ke.deleteProperty});let R=await Ut.tryFind(A)||new Ut;R.packageManager=`yarn@${I?e:await r2(t,\"stable\")}`;let L={};R.exportTo(L);let U=V.join(A,Ut.fileName),z=`${JSON.stringify(L,null,R.indent)}\n`;return await oe.changeFilePromise(U,z,{automaticNewlines:!0}),{bundleVersion:e}}function rde(t){return wr[ZD(t)]}var V0t=/## (?<code>YN[0-9]{4}) - `(?<name>[A-Z_]+)`\\n\\n(?<details>(?:.(?!##))+)/gs;async function z0t(t){let r=`https://repo.yarnpkg.com/${He.isTaggedYarnVersion(nn)?nn:await r2(t,\"canary\")}/packages/docusaurus/docs/advanced/01-general-reference/error-codes.mdx`,o=await sn.get(r,{configuration:t});return new Map(Array.from(o.toString().matchAll(V0t),({groups:a})=>{if(!a)throw new Error(\"Assertion failed: Expected the match to have been successful\");let n=rde(a.code);if(a.name!==n)throw new Error(`Assertion failed: Invalid error code data: Expected \"${a.name}\" to be named \"${n}\"`);return[a.code,a.details]}))}var oE=class extends ut{constructor(){super(...arguments);this.code=ge.String({required:!1,validator:jw(om(),[qw(/^YN[0-9]{4}$/)])});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"})}static{this.paths=[[\"explain\"]]}static{this.usage=it.Usage({description:\"explain an error code\",details:`\n      When the code argument is specified, this command prints its name and its details.\n\n      When used without arguments, this command lists all error codes and their names.\n    `,examples:[[\"Explain an error code\",\"$0 explain YN0006\"],[\"List all error codes\",\"$0 explain\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins);if(typeof this.code<\"u\"){let o=rde(this.code),a=pe.pretty(r,o,pe.Type.CODE),n=this.cli.format().header(`${this.code} - ${a}`),A=(await z0t(r)).get(this.code),p=typeof A<\"u\"?pe.jsonOrPretty(this.json,r,pe.tuple(pe.Type.MARKDOWN,{text:A,format:this.cli.format(),paragraphs:!0})):`This error code does not have a description.\n\nYou can help us by editing this page on GitHub \\u{1F642}:\n${pe.jsonOrPretty(this.json,r,pe.tuple(pe.Type.URL,\"https://github.com/yarnpkg/berry/blob/master/packages/docusaurus/docs/advanced/01-general-reference/error-codes.mdx\"))}\n`;this.json?this.context.stdout.write(`${JSON.stringify({code:this.code,name:o,details:p})}\n`):this.context.stdout.write(`${n}\n\n${p}\n`)}else{let o={children:He.mapAndFilter(Object.entries(wr),([a,n])=>Number.isNaN(Number(a))?He.mapAndFilter.skip:{label:Ku(Number(a)),value:pe.tuple(pe.Type.CODE,n)})};fs.emitTree(o,{configuration:r,stdout:this.context.stdout,json:this.json})}}};Ge();Pt();qt();var nde=Ze($o()),aE=class extends ut{constructor(){super(...arguments);this.all=ge.Boolean(\"-A,--all\",!1,{description:\"Print versions of a package from the whole project\"});this.recursive=ge.Boolean(\"-R,--recursive\",!1,{description:\"Print information for all packages, including transitive dependencies\"});this.extra=ge.Array(\"-X,--extra\",[],{description:\"An array of requests of extra data provided by plugins\"});this.cache=ge.Boolean(\"--cache\",!1,{description:\"Print information about the cache entry of a package (path, size, checksum)\"});this.dependents=ge.Boolean(\"--dependents\",!1,{description:\"Print all dependents for each matching package\"});this.manifest=ge.Boolean(\"--manifest\",!1,{description:\"Print data obtained by looking at the package archive (license, homepage, ...)\"});this.nameOnly=ge.Boolean(\"--name-only\",!1,{description:\"Only print the name for the matching packages\"});this.virtuals=ge.Boolean(\"--virtuals\",!1,{description:\"Print each instance of the virtual packages\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.patterns=ge.Rest()}static{this.paths=[[\"info\"]]}static{this.usage=it.Usage({description:\"see information related to packages\",details:\"\\n      This command prints various information related to the specified packages, accepting glob patterns.\\n\\n      By default, if the locator reference is missing, Yarn will default to print the information about all the matching direct dependencies of the package for the active workspace. To instead print all versions of the package that are direct dependencies of any of your workspaces, use the `-A,--all` flag. Adding the `-R,--recursive` flag will also report transitive dependencies.\\n\\n      Some fields will be hidden by default in order to keep the output readable, but can be selectively displayed by using additional options (`--dependents`, `--manifest`, `--virtuals`, ...) described in the option descriptions.\\n\\n      Note that this command will only print the information directly related to the selected packages - if you wish to know why the package is there in the first place, use `yarn why` which will do just that (it also provides a `-R,--recursive` flag that may be of some help).\\n    \",examples:[[\"Show information about Lodash\",\"$0 info lodash\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(!a&&!this.all)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState();let u=new Set(this.extra);this.cache&&u.add(\"cache\"),this.dependents&&u.add(\"dependents\"),this.manifest&&u.add(\"manifest\");let A=(ae,{recursive:le})=>{let ce=ae.anchoredLocator.locatorHash,Ce=new Map,de=[ce];for(;de.length>0;){let Be=de.shift();if(Ce.has(Be))continue;let Ee=o.storedPackages.get(Be);if(typeof Ee>\"u\")throw new Error(\"Assertion failed: Expected the package to be registered\");if(Ce.set(Be,Ee),G.isVirtualLocator(Ee)&&de.push(G.devirtualizeLocator(Ee).locatorHash),!(!le&&Be!==ce))for(let g of Ee.dependencies.values()){let me=o.storedResolutions.get(g.descriptorHash);if(typeof me>\"u\")throw new Error(\"Assertion failed: Expected the resolution to be registered\");de.push(me)}}return Ce.values()},p=({recursive:ae})=>{let le=new Map;for(let ce of o.workspaces)for(let Ce of A(ce,{recursive:ae}))le.set(Ce.locatorHash,Ce);return le.values()},h=({all:ae,recursive:le})=>ae&&le?o.storedPackages.values():ae?p({recursive:le}):A(a,{recursive:le}),E=({all:ae,recursive:le})=>{let ce=h({all:ae,recursive:le}),Ce=this.patterns.map(Ee=>{let g=G.parseLocator(Ee),me=nde.default.makeRe(G.stringifyIdent(g)),we=G.isVirtualLocator(g),Ae=we?G.devirtualizeLocator(g):g;return ne=>{let Z=G.stringifyIdent(ne);if(!me.test(Z))return!1;if(g.reference===\"unknown\")return!0;let xe=G.isVirtualLocator(ne),Ne=xe?G.devirtualizeLocator(ne):ne;return!(we&&xe&&g.reference!==ne.reference||Ae.reference!==Ne.reference)}}),de=He.sortMap([...ce],Ee=>G.stringifyLocator(Ee));return{selection:de.filter(Ee=>Ce.length===0||Ce.some(g=>g(Ee))),sortedLookup:de}},{selection:I,sortedLookup:v}=E({all:this.all,recursive:this.recursive});if(I.length===0)throw new st(\"No package matched your request\");let x=new Map;if(this.dependents)for(let ae of v)for(let le of ae.dependencies.values()){let ce=o.storedResolutions.get(le.descriptorHash);if(typeof ce>\"u\")throw new Error(\"Assertion failed: Expected the resolution to be registered\");He.getArrayWithDefault(x,ce).push(ae)}let C=new Map;for(let ae of v){if(!G.isVirtualLocator(ae))continue;let le=G.devirtualizeLocator(ae);He.getArrayWithDefault(C,le.locatorHash).push(ae)}let R={},L={children:R},U=r.makeFetcher(),z={project:o,fetcher:U,cache:n,checksums:o.storedChecksums,report:new ki,cacheOptions:{skipIntegrityCheck:!0}},te=[async(ae,le,ce)=>{if(!le.has(\"manifest\"))return;let Ce=await U.fetch(ae,z),de;try{de=await Ut.find(Ce.prefixPath,{baseFs:Ce.packageFs})}finally{Ce.releaseFs?.()}ce(\"Manifest\",{License:pe.tuple(pe.Type.NO_HINT,de.license),Homepage:pe.tuple(pe.Type.URL,de.raw.homepage??null)})},async(ae,le,ce)=>{if(!le.has(\"cache\"))return;let Ce=o.storedChecksums.get(ae.locatorHash)??null,de=n.getLocatorPath(ae,Ce),Be;if(de!==null)try{Be=await oe.statPromise(de)}catch{}let Ee=typeof Be<\"u\"?[Be.size,pe.Type.SIZE]:void 0;ce(\"Cache\",{Checksum:pe.tuple(pe.Type.NO_HINT,Ce),Path:pe.tuple(pe.Type.PATH,de),Size:Ee})}];for(let ae of I){let le=G.isVirtualLocator(ae);if(!this.virtuals&&le)continue;let ce={},Ce={value:[ae,pe.Type.LOCATOR],children:ce};if(R[G.stringifyLocator(ae)]=Ce,this.nameOnly){delete Ce.children;continue}let de=C.get(ae.locatorHash);typeof de<\"u\"&&(ce.Instances={label:\"Instances\",value:pe.tuple(pe.Type.NUMBER,de.length)}),ce.Version={label:\"Version\",value:pe.tuple(pe.Type.NO_HINT,ae.version)};let Be=(g,me)=>{let we={};if(ce[g]=we,Array.isArray(me))we.children=me.map(Ae=>({value:Ae}));else{let Ae={};we.children=Ae;for(let[ne,Z]of Object.entries(me))typeof Z>\"u\"||(Ae[ne]={label:ne,value:Z})}};if(!le){for(let g of te)await g(ae,u,Be);await r.triggerHook(g=>g.fetchPackageInfo,ae,u,Be)}ae.bin.size>0&&!le&&Be(\"Exported Binaries\",[...ae.bin.keys()].map(g=>pe.tuple(pe.Type.PATH,g)));let Ee=x.get(ae.locatorHash);typeof Ee<\"u\"&&Ee.length>0&&Be(\"Dependents\",Ee.map(g=>pe.tuple(pe.Type.LOCATOR,g))),ae.dependencies.size>0&&!le&&Be(\"Dependencies\",[...ae.dependencies.values()].map(g=>{let me=o.storedResolutions.get(g.descriptorHash),we=typeof me<\"u\"?o.storedPackages.get(me)??null:null;return pe.tuple(pe.Type.RESOLUTION,{descriptor:g,locator:we})})),ae.peerDependencies.size>0&&le&&Be(\"Peer dependencies\",[...ae.peerDependencies.values()].map(g=>{let me=ae.dependencies.get(g.identHash),we=typeof me<\"u\"?o.storedResolutions.get(me.descriptorHash)??null:null,Ae=we!==null?o.storedPackages.get(we)??null:null;return pe.tuple(pe.Type.RESOLUTION,{descriptor:g,locator:Ae})}))}fs.emitTree(L,{configuration:r,json:this.json,stdout:this.context.stdout,separators:this.nameOnly?0:2})}};Ge();Pt();Nl();var nk=Ze(X0());qt();var Q8=Ze(Jn());el();var J0t=[{selector:t=>t===-1,name:\"nodeLinker\",value:\"node-modules\"},{selector:t=>t!==-1&&t<8,name:\"enableGlobalCache\",value:!1},{selector:t=>t!==-1&&t<8,name:\"compressionLevel\",value:\"mixed\"}],lE=class extends ut{constructor(){super(...arguments);this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.immutable=ge.Boolean(\"--immutable\",{description:\"Abort with an error exit code if the lockfile was to be modified\"});this.immutableCache=ge.Boolean(\"--immutable-cache\",{description:\"Abort with an error exit code if the cache folder was to be modified\"});this.refreshLockfile=ge.Boolean(\"--refresh-lockfile\",{description:\"Refresh the package metadata stored in the lockfile\"});this.checkCache=ge.Boolean(\"--check-cache\",{description:\"Always refetch the packages and ensure that their checksums are consistent\"});this.checkResolutions=ge.Boolean(\"--check-resolutions\",{description:\"Validates that the package resolutions are coherent\"});this.inlineBuilds=ge.Boolean(\"--inline-builds\",{description:\"Verbosely print the output of the build steps of dependencies\"});this.mode=ge.String(\"--mode\",{description:\"Change what artifacts installs generate\",validator:Js(hl)});this.cacheFolder=ge.String(\"--cache-folder\",{hidden:!0});this.frozenLockfile=ge.Boolean(\"--frozen-lockfile\",{hidden:!0});this.ignoreEngines=ge.Boolean(\"--ignore-engines\",{hidden:!0});this.nonInteractive=ge.Boolean(\"--non-interactive\",{hidden:!0});this.preferOffline=ge.Boolean(\"--prefer-offline\",{hidden:!0});this.production=ge.Boolean(\"--production\",{hidden:!0});this.registry=ge.String(\"--registry\",{hidden:!0});this.silent=ge.Boolean(\"--silent\",{hidden:!0});this.networkTimeout=ge.String(\"--network-timeout\",{hidden:!0})}static{this.paths=[[\"install\"],it.Default]}static{this.usage=it.Usage({description:\"install the project dependencies\",details:\"\\n      This command sets up your project if needed. The installation is split into four different steps that each have their own characteristics:\\n\\n      - **Resolution:** First the package manager will resolve your dependencies. The exact way a dependency version is privileged over another isn't standardized outside of the regular semver guarantees. If a package doesn't resolve to what you would expect, check that all dependencies are correctly declared (also check our website for more information: ).\\n\\n      - **Fetch:** Then we download all the dependencies if needed, and make sure that they're all stored within our cache (check the value of `cacheFolder` in `yarn config` to see where the cache files are stored).\\n\\n      - **Link:** Then we send the dependency tree information to internal plugins tasked with writing them on the disk in some form (for example by generating the `.pnp.cjs` file you might know).\\n\\n      - **Build:** Once the dependency tree has been written on the disk, the package manager will now be free to run the build scripts for all packages that might need it, in a topological order compatible with the way they depend on one another. See https://yarnpkg.com/advanced/lifecycle-scripts for detail.\\n\\n      Note that running this command is not part of the recommended workflow. Yarn supports zero-installs, which means that as long as you store your cache and your `.pnp.cjs` file inside your repository, everything will work without requiring any install right after cloning your repository or switching branches.\\n\\n      If the `--immutable` option is set (defaults to true on CI), Yarn will abort with an error exit code if the lockfile was to be modified (other paths can be added using the `immutablePatterns` configuration setting). For backward compatibility we offer an alias under the name of `--frozen-lockfile`, but it will be removed in a later release.\\n\\n      If the `--immutable-cache` option is set, Yarn will abort with an error exit code if the cache folder was to be modified (either because files would be added, or because they'd be removed).\\n\\n      If the `--refresh-lockfile` option is set, Yarn will keep the same resolution for the packages currently in the lockfile but will refresh their metadata. If used together with `--immutable`, it can validate that the lockfile information are consistent. This flag is enabled by default when Yarn detects it runs within a pull request context.\\n\\n      If the `--check-cache` option is set, Yarn will always refetch the packages and will ensure that their checksum matches what's 1/ described in the lockfile 2/ inside the existing cache files (if present). This is recommended as part of your CI workflow if you're both following the Zero-Installs model and accepting PRs from third-parties, as they'd otherwise have the ability to alter the checked-in packages before submitting them.\\n\\n      If the `--inline-builds` option is set, Yarn will verbosely print the output of the build steps of your dependencies (instead of writing them into individual files). This is likely useful mostly for debug purposes only when using Docker-like environments.\\n\\n      If the `--mode=<mode>` option is set, Yarn will change which artifacts are generated. The modes currently supported are:\\n\\n      - `skip-build` will not run the build scripts at all. Note that this is different from setting `enableScripts` to false because the latter will disable build scripts, and thus affect the content of the artifacts generated on disk, whereas the former will just disable the build step - but not the scripts themselves, which just won't run.\\n\\n      - `update-lockfile` will skip the link step altogether, and only fetch packages that are missing from the lockfile (or that have no associated checksums). This mode is typically used by tools like Renovate or Dependabot to keep a lockfile up-to-date without incurring the full install cost.\\n    \",examples:[[\"Install the project\",\"$0 install\"],[\"Validate a project when using Zero-Installs\",\"$0 install --immutable --immutable-cache\"],[\"Validate a project when using Zero-Installs (slightly safer if you accept external PRs)\",\"$0 install --immutable --immutable-cache --check-cache\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins);typeof this.inlineBuilds<\"u\"&&r.useWithSource(\"<cli>\",{enableInlineBuilds:this.inlineBuilds},r.startingCwd,{overwrite:!0});let o=!!process.env.FUNCTION_TARGET||!!process.env.GOOGLE_RUNTIME,a=await uy({configuration:r,stdout:this.context.stdout},[{option:this.ignoreEngines,message:\"The --ignore-engines option is deprecated; engine checking isn't a core feature anymore\",error:!nk.default.VERCEL},{option:this.registry,message:\"The --registry option is deprecated; prefer setting npmRegistryServer in your .yarnrc.yml file\"},{option:this.preferOffline,message:\"The --prefer-offline flag is deprecated; use the --cached flag with 'yarn add' instead\",error:!nk.default.VERCEL},{option:this.production,message:\"The --production option is deprecated on 'install'; use 'yarn workspaces focus' instead\",error:!0},{option:this.nonInteractive,message:\"The --non-interactive option is deprecated\",error:!o},{option:this.frozenLockfile,message:\"The --frozen-lockfile option is deprecated; use --immutable and/or --immutable-cache instead\",callback:()=>this.immutable=this.frozenLockfile},{option:this.cacheFolder,message:\"The cache-folder option has been deprecated; use rc settings instead\",error:!nk.default.NETLIFY}]);if(a!==null)return a;let n=this.mode===\"update-lockfile\";if(n&&(this.immutable||this.immutableCache))throw new st(`${pe.pretty(r,\"--immutable\",pe.Type.CODE)} and ${pe.pretty(r,\"--immutable-cache\",pe.Type.CODE)} cannot be used with ${pe.pretty(r,\"--mode=update-lockfile\",pe.Type.CODE)}`);let u=(this.immutable??r.get(\"enableImmutableInstalls\"))&&!n,A=this.immutableCache&&!n;if(r.projectCwd!==null){let R=await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout,includeFooter:!1},async L=>{let U=!1;await $0t(r,u)&&(L.reportInfo(48,\"Automatically removed core plugins that are now builtins \\u{1F44D}\"),U=!0),await Z0t(r,u)&&(L.reportInfo(48,\"Automatically fixed merge conflicts \\u{1F44D}\"),U=!0),U&&L.reportSeparator()});if(R.hasErrors())return R.exitCode()}if(r.projectCwd!==null){let R=await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout,includeFooter:!1},async L=>{if(Ke.telemetry?.isNew)Ke.telemetry.commitTips(),L.reportInfo(65,\"Yarn will periodically gather anonymous telemetry: https://yarnpkg.com/advanced/telemetry\"),L.reportInfo(65,`Run ${pe.pretty(r,\"yarn config set --home enableTelemetry 0\",pe.Type.CODE)} to disable`),L.reportSeparator();else if(Ke.telemetry?.shouldShowTips){let U=await sn.get(\"https://repo.yarnpkg.com/tags\",{configuration:r,jsonResponse:!0}).catch(()=>null);if(U!==null){let z=null;if(nn!==null){let ae=Q8.default.prerelease(nn)?\"canary\":\"stable\",le=U.latest[ae];Q8.default.gt(le,nn)&&(z=[ae,le])}if(z)Ke.telemetry.commitTips(),L.reportInfo(88,`${pe.applyStyle(r,`A new ${z[0]} version of Yarn is available:`,pe.Style.BOLD)} ${G.prettyReference(r,z[1])}!`),L.reportInfo(88,`Upgrade now by running ${pe.pretty(r,`yarn set version ${z[1]}`,pe.Type.CODE)}`),L.reportSeparator();else{let te=Ke.telemetry.selectTip(U.tips);te&&(L.reportInfo(89,pe.pretty(r,te.message,pe.Type.MARKDOWN_INLINE)),te.url&&L.reportInfo(89,`Learn more at ${te.url}`),L.reportSeparator())}}}});if(R.hasErrors())return R.exitCode()}let{project:p,workspace:h}=await kt.find(r,this.context.cwd),E=p.lockfileLastVersion;if(E!==null){let R=await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout,includeFooter:!1},async L=>{let U={};for(let z of J0t)z.selector(E)&&typeof r.sources.get(z.name)>\"u\"&&(r.use(\"<compat>\",{[z.name]:z.value},p.cwd,{overwrite:!0}),U[z.name]=z.value);Object.keys(U).length>0&&(await Ke.updateConfiguration(p.cwd,U),L.reportInfo(87,\"Migrated your project to the latest Yarn version \\u{1F680}\"),L.reportSeparator())});if(R.hasErrors())return R.exitCode()}let I=await Gr.find(r,{immutable:A,check:this.checkCache});if(!h)throw new sr(p.cwd,this.context.cwd);await p.restoreInstallState({restoreResolutions:!1});let v=r.get(\"enableHardenedMode\");v&&typeof r.sources.get(\"enableHardenedMode\")>\"u\"&&await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout,includeFooter:!1},async R=>{R.reportWarning(0,\"Yarn detected that the current workflow is executed from a public pull request. For safety the hardened mode has been enabled.\"),R.reportWarning(0,`It will prevent malicious lockfile manipulations, in exchange for a slower install time. You can opt-out if necessary; check our ${pe.applyHyperlink(r,\"documentation\",\"https://yarnpkg.com/features/security#hardened-mode\")} for more details.`),R.reportSeparator()}),(this.refreshLockfile??v)&&(p.lockfileNeedsRefresh=!0);let x=this.checkResolutions??v;return(await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout,forceSectionAlignment:!0,includeLogs:!0,includeVersion:!0},async R=>{await p.install({cache:I,report:R,immutable:u,checkResolutions:x,mode:this.mode})})).exitCode()}},X0t=\"<<<<<<<\";async function Z0t(t,e){if(!t.projectCwd)return!1;let r=V.join(t.projectCwd,dr.lockfile);if(!await oe.existsPromise(r)||!(await oe.readFilePromise(r,\"utf8\")).includes(X0t))return!1;if(e)throw new Jt(47,\"Cannot autofix a lockfile when running an immutable install\");let a=await Ur.execvp(\"git\",[\"rev-parse\",\"MERGE_HEAD\",\"HEAD\"],{cwd:t.projectCwd});if(a.code!==0&&(a=await Ur.execvp(\"git\",[\"rev-parse\",\"REBASE_HEAD\",\"HEAD\"],{cwd:t.projectCwd})),a.code!==0&&(a=await Ur.execvp(\"git\",[\"rev-parse\",\"CHERRY_PICK_HEAD\",\"HEAD\"],{cwd:t.projectCwd})),a.code!==0)throw new Jt(83,\"Git returned an error when trying to find the commits pertaining to the conflict\");let n=await Promise.all(a.stdout.trim().split(/\\n/).map(async A=>{let p=await Ur.execvp(\"git\",[\"show\",`${A}:./${dr.lockfile}`],{cwd:t.projectCwd});if(p.code!==0)throw new Jt(83,`Git returned an error when trying to access the lockfile content in ${A}`);try{return Ki(p.stdout)}catch{throw new Jt(46,\"A variant of the conflicting lockfile failed to parse\")}}));n=n.filter(A=>!!A.__metadata);for(let A of n){if(A.__metadata.version<7)for(let p of Object.keys(A)){if(p===\"__metadata\")continue;let h=G.parseDescriptor(p,!0),E=t.normalizeDependency(h),I=G.stringifyDescriptor(E);I!==p&&(A[I]=A[p],delete A[p])}for(let p of Object.keys(A)){if(p===\"__metadata\")continue;let h=A[p].checksum;typeof h==\"string\"&&h.includes(\"/\")||(A[p].checksum=`${A.__metadata.cacheKey}/${h}`)}}let u=Object.assign({},...n);u.__metadata.version=`${Math.min(...n.map(A=>parseInt(A.__metadata.version??0)))}`,u.__metadata.cacheKey=\"merged\";for(let[A,p]of Object.entries(u))typeof p==\"string\"&&delete u[A];return await oe.changeFilePromise(r,Da(u),{automaticNewlines:!0}),!0}async function $0t(t,e){if(!t.projectCwd)return!1;let r=[],o=V.join(t.projectCwd,\".yarn/plugins/@yarnpkg\");return await Ke.updateConfiguration(t.projectCwd,{plugins:n=>{if(!Array.isArray(n))return n;let u=n.filter(A=>{if(!A.path)return!0;let p=V.resolve(t.projectCwd,A.path),h=l1.has(A.spec)&&V.contains(o,p);return h&&r.push(p),!h});return u.length===0?Ke.deleteProperty:u.length===n.length?n:u}},{immutable:e})?(await Promise.all(r.map(async n=>{await oe.removePromise(n)})),!0):!1}Ge();Pt();qt();var cE=class extends ut{constructor(){super(...arguments);this.all=ge.Boolean(\"-A,--all\",!1,{description:\"Link all workspaces belonging to the target projects to the current one\"});this.private=ge.Boolean(\"-p,--private\",!1,{description:\"Also link private workspaces belonging to the target projects to the current one\"});this.relative=ge.Boolean(\"-r,--relative\",!1,{description:\"Link workspaces using relative paths instead of absolute paths\"});this.destinations=ge.Rest()}static{this.paths=[[\"link\"]]}static{this.usage=it.Usage({description:\"connect the local project to another one\",details:\"\\n      This command will set a new `resolutions` field in the project-level manifest and point it to the workspace at the specified location (even if part of another project).\\n    \",examples:[[\"Register one or more remote workspaces for use in the current project\",\"$0 link ~/ts-loader ~/jest\"],[\"Register all workspaces from a remote project for use in the current project\",\"$0 link ~/jest --all\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(!a)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState({restoreResolutions:!1});let u=o.topLevelWorkspace,A=[];for(let p of this.destinations){let h=V.resolve(this.context.cwd,ue.toPortablePath(p)),E=await Ke.find(h,this.context.plugins,{useRc:!1,strict:!1}),{project:I,workspace:v}=await kt.find(E,h);if(o.cwd===I.cwd)throw new st(`Invalid destination '${p}'; Can't link the project to itself`);if(!v)throw new sr(I.cwd,h);if(this.all){let x=!1;for(let C of I.workspaces)C.manifest.name&&(!C.manifest.private||this.private)&&(A.push(C),x=!0);if(!x)throw new st(`No workspace found to be linked in the target project: ${p}`)}else{if(!v.manifest.name)throw new st(`The target workspace at '${p}' doesn't have a name and thus cannot be linked`);if(v.manifest.private&&!this.private)throw new st(`The target workspace at '${p}' is marked private - use the --private flag to link it anyway`);A.push(v)}}for(let p of A){let h=G.stringifyIdent(p.anchoredLocator),E=this.relative?V.relative(o.cwd,p.cwd):p.cwd;u.manifest.resolutions.push({pattern:{descriptor:{fullName:h}},reference:`portal:${E}`})}return await o.installWithNewReport({stdout:this.context.stdout},{cache:n})}};qt();var uE=class extends ut{constructor(){super(...arguments);this.args=ge.Proxy()}static{this.paths=[[\"node\"]]}static{this.usage=it.Usage({description:\"run node with the hook already setup\",details:`\n      This command simply runs Node. It also makes sure to call it in a way that's compatible with the current project (for example, on PnP projects the environment will be setup in such a way that PnP will be correctly injected into the environment).\n\n      The Node process will use the exact same version of Node as the one used to run Yarn itself, which might be a good way to ensure that your commands always use a consistent Node version.\n    `,examples:[[\"Run a Node script\",\"$0 node ./my-script.js\"]]})}async execute(){return this.cli.run([\"exec\",\"node\",...this.args])}};Ge();qt();var AE=class extends ut{constructor(){super(...arguments);this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"})}static{this.paths=[[\"plugin\",\"check\"]]}static{this.usage=it.Usage({category:\"Plugin-related commands\",description:\"find all third-party plugins that differ from their own spec\",details:`\n      Check only the plugins from https.\n\n      If this command detects any plugin differences in the CI environment, it will throw an error.\n    `,examples:[[\"find all third-party plugins that differ from their own spec\",\"$0 plugin check\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),o=await Ke.findRcFiles(this.context.cwd);return(await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout},async n=>{for(let u of o)if(u.data?.plugins)for(let A of u.data.plugins){if(!A.checksum||!A.spec.match(/^https?:/))continue;let p=await sn.get(A.spec,{configuration:r}),h=wn.makeHash(p);if(A.checksum===h)continue;let E=pe.pretty(r,A.path,pe.Type.PATH),I=pe.pretty(r,A.spec,pe.Type.URL),v=`${E} is different from the file provided by ${I}`;n.reportJson({...A,newChecksum:h}),n.reportError(0,v)}})).exitCode()}};Ge();Ge();Pt();qt();var lde=ve(\"os\");Ge();Pt();qt();var ide=ve(\"os\");Ge();Nl();qt();var egt=\"https://raw.githubusercontent.com/yarnpkg/berry/master/plugins.yml\";async function Hg(t,e){let r=await sn.get(egt,{configuration:t}),o=Ki(r.toString());return Object.fromEntries(Object.entries(o).filter(([a,n])=>!e||Lr.satisfiesWithPrereleases(e,n.range??\"<4.0.0-rc.1\")))}var fE=class extends ut{constructor(){super(...arguments);this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"})}static{this.paths=[[\"plugin\",\"list\"]]}static{this.usage=it.Usage({category:\"Plugin-related commands\",description:\"list the available official plugins\",details:\"\\n      This command prints the plugins available directly from the Yarn repository. Only those plugins can be referenced by name in `yarn plugin import`.\\n    \",examples:[[\"List the official plugins\",\"$0 plugin list\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins);return(await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout},async a=>{let n=await Hg(r,nn);for(let[u,{experimental:A,...p}]of Object.entries(n)){let h=u;A&&(h+=\" [experimental]\"),a.reportJson({name:u,experimental:A,...p}),a.reportInfo(null,h)}})).exitCode()}};var tgt=/^[0-9]+$/,rgt=process.platform===\"win32\";function sde(t){return tgt.test(t)?`pull/${t}/head`:t}var ngt=({repository:t,branch:e},r)=>[[\"git\",\"init\",ue.fromPortablePath(r)],[\"git\",\"remote\",\"add\",\"origin\",t],[\"git\",\"fetch\",\"origin\",\"--depth=1\",sde(e)],[\"git\",\"reset\",\"--hard\",\"FETCH_HEAD\"]],igt=({branch:t})=>[[\"git\",\"fetch\",\"origin\",\"--depth=1\",sde(t),\"--force\"],[\"git\",\"reset\",\"--hard\",\"FETCH_HEAD\"],[\"git\",\"clean\",\"-dfx\",\"-e\",\"packages/yarnpkg-cli/bundles\"]],sgt=({plugins:t,noMinify:e},r,o)=>[[\"yarn\",\"build:cli\",...new Array().concat(...t.map(a=>[\"--plugin\",V.resolve(o,a)])),...e?[\"--no-minify\"]:[],\"|\"],[rgt?\"move\":\"mv\",\"packages/yarnpkg-cli/bundles/yarn.js\",ue.fromPortablePath(r),\"|\"]],pE=class extends ut{constructor(){super(...arguments);this.installPath=ge.String(\"--path\",{description:\"The path where the repository should be cloned to\"});this.repository=ge.String(\"--repository\",\"https://github.com/yarnpkg/berry.git\",{description:\"The repository that should be cloned\"});this.branch=ge.String(\"--branch\",\"master\",{description:\"The branch of the repository that should be cloned\"});this.plugins=ge.Array(\"--plugin\",[],{description:\"An array of additional plugins that should be included in the bundle\"});this.dryRun=ge.Boolean(\"-n,--dry-run\",!1,{description:\"If set, the bundle will be built but not added to the project\"});this.noMinify=ge.Boolean(\"--no-minify\",!1,{description:\"Build a bundle for development (debugging) - non-minified and non-mangled\"});this.force=ge.Boolean(\"-f,--force\",!1,{description:\"Always clone the repository instead of trying to fetch the latest commits\"});this.skipPlugins=ge.Boolean(\"--skip-plugins\",!1,{description:\"Skip updating the contrib plugins\"})}static{this.paths=[[\"set\",\"version\",\"from\",\"sources\"]]}static{this.usage=it.Usage({description:\"build Yarn from master\",details:`\n      This command will clone the Yarn repository into a temporary folder, then build it. The resulting bundle will then be copied into the local project.\n\n      By default, it also updates all contrib plugins to the same commit the bundle is built from. This behavior can be disabled by using the \\`--skip-plugins\\` flag.\n    `,examples:[[\"Build Yarn from master\",\"$0 set version from sources\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o}=await kt.find(r,this.context.cwd),a=typeof this.installPath<\"u\"?V.resolve(this.context.cwd,ue.toPortablePath(this.installPath)):V.resolve(ue.toPortablePath((0,ide.tmpdir)()),\"yarnpkg-sources\",wn.makeHash(this.repository).slice(0,6));return(await Rt.start({configuration:r,stdout:this.context.stdout},async u=>{await F8(this,{configuration:r,report:u,target:a}),u.reportSeparator(),u.reportInfo(0,\"Building a fresh bundle\"),u.reportSeparator();let A=await Ur.execvp(\"git\",[\"rev-parse\",\"--short\",\"HEAD\"],{cwd:a,strict:!0}),p=V.join(a,`packages/yarnpkg-cli/bundles/yarn-${A.stdout.trim()}.js`);oe.existsSync(p)||(await n2(sgt(this,p,a),{configuration:r,context:this.context,target:a}),u.reportSeparator());let h=await oe.readFilePromise(p);if(!this.dryRun){let{bundleVersion:E}=await k8(r,null,async()=>h,{report:u});this.skipPlugins||await ogt(this,E,{project:o,report:u,target:a})}})).exitCode()}};async function n2(t,{configuration:e,context:r,target:o}){for(let[a,...n]of t){let u=n[n.length-1]===\"|\";if(u&&n.pop(),u)await Ur.pipevp(a,n,{cwd:o,stdin:r.stdin,stdout:r.stdout,stderr:r.stderr,strict:!0});else{r.stdout.write(`${pe.pretty(e,`  $ ${[a,...n].join(\" \")}`,\"grey\")}\n`);try{await Ur.execvp(a,n,{cwd:o,strict:!0})}catch(A){throw r.stdout.write(A.stdout||A.stack),A}}}}async function F8(t,{configuration:e,report:r,target:o}){let a=!1;if(!t.force&&oe.existsSync(V.join(o,\".git\"))){r.reportInfo(0,\"Fetching the latest commits\"),r.reportSeparator();try{await n2(igt(t),{configuration:e,context:t.context,target:o}),a=!0}catch{r.reportSeparator(),r.reportWarning(0,\"Repository update failed; we'll try to regenerate it\")}}a||(r.reportInfo(0,\"Cloning the remote repository\"),r.reportSeparator(),await oe.removePromise(o),await oe.mkdirPromise(o,{recursive:!0}),await n2(ngt(t,o),{configuration:e,context:t.context,target:o}))}async function ogt(t,e,{project:r,report:o,target:a}){let n=await Hg(r.configuration,e),u=new Set(Object.keys(n));for(let A of r.configuration.plugins.keys())u.has(A)&&await R8(A,t,{project:r,report:o,target:a})}Ge();Ge();Pt();qt();var ode=Ze(Jn()),ade=ve(\"vm\");var hE=class extends ut{constructor(){super(...arguments);this.name=ge.String();this.checksum=ge.Boolean(\"--checksum\",!0,{description:\"Whether to care if this plugin is modified\"})}static{this.paths=[[\"plugin\",\"import\"]]}static{this.usage=it.Usage({category:\"Plugin-related commands\",description:\"download a plugin\",details:`\n      This command downloads the specified plugin from its remote location and updates the configuration to reference it in further CLI invocations.\n\n      Three types of plugin references are accepted:\n\n      - If the plugin is stored within the Yarn repository, it can be referenced by name.\n      - Third-party plugins can be referenced directly through their public urls.\n      - Local plugins can be referenced by their path on the disk.\n\n      If the \\`--no-checksum\\` option is set, Yarn will no longer care if the plugin is modified.\n\n      Plugins cannot be downloaded from the npm registry, and aren't allowed to have dependencies (they need to be bundled into a single file, possibly thanks to the \\`@yarnpkg/builder\\` package).\n    `,examples:[['Download and activate the \"@yarnpkg/plugin-exec\" plugin',\"$0 plugin import @yarnpkg/plugin-exec\"],['Download and activate the \"@yarnpkg/plugin-exec\" plugin (shorthand)',\"$0 plugin import exec\"],[\"Download and activate a community plugin\",\"$0 plugin import https://example.org/path/to/plugin.js\"],[\"Activate a local plugin\",\"$0 plugin import ./path/to/plugin.js\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins);return(await Rt.start({configuration:r,stdout:this.context.stdout},async a=>{let{project:n}=await kt.find(r,this.context.cwd),u,A;if(this.name.match(/^\\.{0,2}[\\\\/]/)||ue.isAbsolute(this.name)){let p=V.resolve(this.context.cwd,ue.toPortablePath(this.name));a.reportInfo(0,`Reading ${pe.pretty(r,p,pe.Type.PATH)}`),u=V.relative(n.cwd,p),A=await oe.readFilePromise(p)}else{let p;if(this.name.match(/^https?:/)){try{new URL(this.name)}catch{throw new Jt(52,`Plugin specifier \"${this.name}\" is neither a plugin name nor a valid url`)}u=this.name,p=this.name}else{let h=G.parseLocator(this.name.replace(/^((@yarnpkg\\/)?plugin-)?/,\"@yarnpkg/plugin-\"));if(h.reference!==\"unknown\"&&!ode.default.valid(h.reference))throw new Jt(0,\"Official plugins only accept strict version references. Use an explicit URL if you wish to download them from another location.\");let E=G.stringifyIdent(h),I=await Hg(r,nn);if(!Object.hasOwn(I,E)){let v=`Couldn't find a plugin named ${G.prettyIdent(r,h)} on the remote registry.\n`;throw r.plugins.has(E)?v+=`A plugin named ${G.prettyIdent(r,h)} is already installed; possibly attempting to import a built-in plugin.`:v+=`Note that only the plugins referenced on our website (${pe.pretty(r,\"https://github.com/yarnpkg/berry/blob/master/plugins.yml\",pe.Type.URL)}) can be referenced by their name; any other plugin will have to be referenced through its public url (for example ${pe.pretty(r,\"https://github.com/yarnpkg/berry/raw/master/packages/plugin-typescript/bin/%40yarnpkg/plugin-typescript.js\",pe.Type.URL)}).`,new Jt(51,v)}u=E,p=I[E].url,h.reference!==\"unknown\"?p=p.replace(/\\/master\\//,`/${E}/${h.reference}/`):nn!==null&&(p=p.replace(/\\/master\\//,`/@yarnpkg/cli/${nn}/`))}a.reportInfo(0,`Downloading ${pe.pretty(r,p,\"green\")}`),A=await sn.get(p,{configuration:r})}await T8(u,A,{checksum:this.checksum,project:n,report:a})})).exitCode()}};async function T8(t,e,{checksum:r=!0,project:o,report:a}){let{configuration:n}=o,u={},A={exports:u};(0,ade.runInNewContext)(e.toString(),{module:A,exports:u});let h=`.yarn/plugins/${A.exports.name}.cjs`,E=V.resolve(o.cwd,h);a.reportInfo(0,`Saving the new plugin in ${pe.pretty(n,h,\"magenta\")}`),await oe.mkdirPromise(V.dirname(E),{recursive:!0}),await oe.writeFilePromise(E,e);let I={path:h,spec:t};r&&(I.checksum=wn.makeHash(e)),await Ke.addPlugin(o.cwd,[I])}var agt=({pluginName:t,noMinify:e},r)=>[[\"yarn\",`build:${t}`,...e?[\"--no-minify\"]:[],\"|\"]],gE=class extends ut{constructor(){super(...arguments);this.installPath=ge.String(\"--path\",{description:\"The path where the repository should be cloned to\"});this.repository=ge.String(\"--repository\",\"https://github.com/yarnpkg/berry.git\",{description:\"The repository that should be cloned\"});this.branch=ge.String(\"--branch\",\"master\",{description:\"The branch of the repository that should be cloned\"});this.noMinify=ge.Boolean(\"--no-minify\",!1,{description:\"Build a plugin for development (debugging) - non-minified and non-mangled\"});this.force=ge.Boolean(\"-f,--force\",!1,{description:\"Always clone the repository instead of trying to fetch the latest commits\"});this.name=ge.String()}static{this.paths=[[\"plugin\",\"import\",\"from\",\"sources\"]]}static{this.usage=it.Usage({category:\"Plugin-related commands\",description:\"build a plugin from sources\",details:`\n      This command clones the Yarn repository into a temporary folder, builds the specified contrib plugin and updates the configuration to reference it in further CLI invocations.\n\n      The plugins can be referenced by their short name if sourced from the official Yarn repository.\n    `,examples:[['Build and activate the \"@yarnpkg/plugin-exec\" plugin',\"$0 plugin import from sources @yarnpkg/plugin-exec\"],['Build and activate the \"@yarnpkg/plugin-exec\" plugin (shorthand)',\"$0 plugin import from sources exec\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),o=typeof this.installPath<\"u\"?V.resolve(this.context.cwd,ue.toPortablePath(this.installPath)):V.resolve(ue.toPortablePath((0,lde.tmpdir)()),\"yarnpkg-sources\",wn.makeHash(this.repository).slice(0,6));return(await Rt.start({configuration:r,stdout:this.context.stdout},async n=>{let{project:u}=await kt.find(r,this.context.cwd),A=G.parseIdent(this.name.replace(/^((@yarnpkg\\/)?plugin-)?/,\"@yarnpkg/plugin-\")),p=G.stringifyIdent(A),h=await Hg(r,nn);if(!Object.hasOwn(h,p))throw new Jt(51,`Couldn't find a plugin named \"${p}\" on the remote registry. Note that only the plugins referenced on our website (https://github.com/yarnpkg/berry/blob/master/plugins.yml) can be built and imported from sources.`);let E=p;await F8(this,{configuration:r,report:n,target:o}),await R8(E,this,{project:u,report:n,target:o})})).exitCode()}};async function R8(t,{context:e,noMinify:r},{project:o,report:a,target:n}){let u=t.replace(/@yarnpkg\\//,\"\"),{configuration:A}=o;a.reportSeparator(),a.reportInfo(0,`Building a fresh ${u}`),a.reportSeparator(),await n2(agt({pluginName:u,noMinify:r},n),{configuration:A,context:e,target:n}),a.reportSeparator();let p=V.resolve(n,`packages/${u}/bundles/${t}.js`),h=await oe.readFilePromise(p);await T8(t,h,{project:o,report:a})}Ge();Pt();qt();var dE=class extends ut{constructor(){super(...arguments);this.name=ge.String()}static{this.paths=[[\"plugin\",\"remove\"]]}static{this.usage=it.Usage({category:\"Plugin-related commands\",description:\"remove a plugin\",details:`\n      This command deletes the specified plugin from the .yarn/plugins folder and removes it from the configuration.\n\n      **Note:** The plugins have to be referenced by their name property, which can be obtained using the \\`yarn plugin runtime\\` command. Shorthands are not allowed.\n   `,examples:[[\"Remove a plugin imported from the Yarn repository\",\"$0 plugin remove @yarnpkg/plugin-typescript\"],[\"Remove a plugin imported from a local file\",\"$0 plugin remove my-local-plugin\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o}=await kt.find(r,this.context.cwd);return(await Rt.start({configuration:r,stdout:this.context.stdout},async n=>{let u=this.name,A=G.parseIdent(u);if(!r.plugins.has(u))throw new st(`${G.prettyIdent(r,A)} isn't referenced by the current configuration`);let p=`.yarn/plugins/${u}.cjs`,h=V.resolve(o.cwd,p);oe.existsSync(h)&&(n.reportInfo(0,`Removing ${pe.pretty(r,p,pe.Type.PATH)}...`),await oe.removePromise(h)),n.reportInfo(0,\"Updating the configuration...\"),await Ke.updateConfiguration(o.cwd,{plugins:E=>{if(!Array.isArray(E))return E;let I=E.filter(v=>v.path!==p);return I.length===0?Ke.deleteProperty:I.length===E.length?E:I}})})).exitCode()}};Ge();qt();var mE=class extends ut{constructor(){super(...arguments);this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"})}static{this.paths=[[\"plugin\",\"runtime\"]]}static{this.usage=it.Usage({category:\"Plugin-related commands\",description:\"list the active plugins\",details:`\n      This command prints the currently active plugins. Will be displayed both builtin plugins and external plugins.\n    `,examples:[[\"List the currently active plugins\",\"$0 plugin runtime\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins);return(await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout},async a=>{for(let n of r.plugins.keys()){let u=this.context.plugins.plugins.has(n),A=n;u&&(A+=\" [builtin]\"),a.reportJson({name:n,builtin:u}),a.reportInfo(null,`${A}`)}})).exitCode()}};Ge();Ge();qt();var yE=class extends ut{constructor(){super(...arguments);this.idents=ge.Rest()}static{this.paths=[[\"rebuild\"]]}static{this.usage=it.Usage({description:\"rebuild the project's native packages\",details:`\n      This command will automatically cause Yarn to forget about previous compilations of the given packages and to run them again.\n\n      Note that while Yarn forgets the compilation, the previous artifacts aren't erased from the filesystem and may affect the next builds (in good or bad). To avoid this, you may remove the .yarn/unplugged folder, or any other relevant location where packages might have been stored (Yarn may offer a way to do that automatically in the future).\n\n      By default all packages will be rebuilt, but you can filter the list by specifying the names of the packages you want to clear from memory.\n    `,examples:[[\"Rebuild all packages\",\"$0 rebuild\"],[\"Rebuild fsevents only\",\"$0 rebuild fsevents\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(!a)throw new sr(o.cwd,this.context.cwd);let u=new Set;for(let A of this.idents)u.add(G.parseIdent(A).identHash);if(await o.restoreInstallState({restoreResolutions:!1}),await o.resolveEverything({cache:n,report:new ki}),u.size>0)for(let A of o.storedPackages.values())u.has(A.identHash)&&(o.storedBuildState.delete(A.locatorHash),o.skippedBuilds.delete(A.locatorHash));else o.storedBuildState.clear(),o.skippedBuilds.clear();return await o.installWithNewReport({stdout:this.context.stdout,quiet:this.context.quiet},{cache:n})}};Ge();Ge();Ge();qt();var N8=Ze($o());el();var EE=class extends ut{constructor(){super(...arguments);this.all=ge.Boolean(\"-A,--all\",!1,{description:\"Apply the operation to all workspaces from the current project\"});this.mode=ge.String(\"--mode\",{description:\"Change what artifacts installs generate\",validator:Js(hl)});this.patterns=ge.Rest()}static{this.paths=[[\"remove\"]]}static{this.usage=it.Usage({description:\"remove dependencies from the project\",details:`\n      This command will remove the packages matching the specified patterns from the current workspace.\n\n      If the \\`--mode=<mode>\\` option is set, Yarn will change which artifacts are generated. The modes currently supported are:\n\n      - \\`skip-build\\` will not run the build scripts at all. Note that this is different from setting \\`enableScripts\\` to false because the latter will disable build scripts, and thus affect the content of the artifacts generated on disk, whereas the former will just disable the build step - but not the scripts themselves, which just won't run.\n\n      - \\`update-lockfile\\` will skip the link step altogether, and only fetch packages that are missing from the lockfile (or that have no associated checksums). This mode is typically used by tools like Renovate or Dependabot to keep a lockfile up-to-date without incurring the full install cost.\n\n      This command accepts glob patterns as arguments (if valid Idents and supported by [micromatch](https://github.com/micromatch/micromatch)). Make sure to escape the patterns, to prevent your own shell from trying to expand them.\n    `,examples:[[\"Remove a dependency from the current project\",\"$0 remove lodash\"],[\"Remove a dependency from all workspaces at once\",\"$0 remove lodash --all\"],[\"Remove all dependencies starting with `eslint-`\",\"$0 remove 'eslint-*'\"],[\"Remove all dependencies with the `@babel` scope\",\"$0 remove '@babel/*'\"],[\"Remove all dependencies matching `react-dom` or `react-helmet`\",\"$0 remove 'react-{dom,helmet}'\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(!a)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState({restoreResolutions:!1});let u=this.all?o.workspaces:[a],A=[\"dependencies\",\"devDependencies\",\"peerDependencies\"],p=[],h=!1,E=[];for(let C of this.patterns){let R=!1,L=G.parseIdent(C);for(let U of u){let z=[...U.manifest.peerDependenciesMeta.keys()];for(let te of(0,N8.default)(z,C))U.manifest.peerDependenciesMeta.delete(te),h=!0,R=!0;for(let te of A){let ae=U.manifest.getForScope(te),le=[...ae.values()].map(ce=>G.stringifyIdent(ce));for(let ce of(0,N8.default)(le,G.stringifyIdent(L))){let{identHash:Ce}=G.parseIdent(ce),de=ae.get(Ce);if(typeof de>\"u\")throw new Error(\"Assertion failed: Expected the descriptor to be registered\");U.manifest[te].delete(Ce),E.push([U,te,de]),h=!0,R=!0}}}R||p.push(C)}let I=p.length>1?\"Patterns\":\"Pattern\",v=p.length>1?\"don't\":\"doesn't\",x=this.all?\"any\":\"this\";if(p.length>0)throw new st(`${I} ${pe.prettyList(r,p,pe.Type.CODE)} ${v} match any packages referenced by ${x} workspace`);return h?(await r.triggerMultipleHooks(C=>C.afterWorkspaceDependencyRemoval,E),await o.installWithNewReport({stdout:this.context.stdout},{cache:n,mode:this.mode})):0}};Ge();Ge();qt();var cde=ve(\"util\"),CE=class extends ut{constructor(){super(...arguments);this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"})}static{this.paths=[[\"run\"]]}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!a)throw new sr(o.cwd,this.context.cwd);return(await Rt.start({configuration:r,stdout:this.context.stdout,json:this.json},async u=>{let A=a.manifest.scripts,p=He.sortMap(A.keys(),I=>I),h={breakLength:1/0,colors:r.get(\"enableColors\"),maxArrayLength:2},E=p.reduce((I,v)=>Math.max(I,v.length),0);for(let[I,v]of A.entries())u.reportInfo(null,`${I.padEnd(E,\" \")}   ${(0,cde.inspect)(v,h)}`),u.reportJson({name:I,script:v})})).exitCode()}};Ge();Ge();qt();var wE=class extends ut{constructor(){super(...arguments);this.inspect=ge.String(\"--inspect\",!1,{tolerateBoolean:!0,description:\"Forwarded to the underlying Node process when executing a binary\"});this.inspectBrk=ge.String(\"--inspect-brk\",!1,{tolerateBoolean:!0,description:\"Forwarded to the underlying Node process when executing a binary\"});this.topLevel=ge.Boolean(\"-T,--top-level\",!1,{description:\"Check the root workspace for scripts and/or binaries instead of the current one\"});this.binariesOnly=ge.Boolean(\"-B,--binaries-only\",!1,{description:\"Ignore any user defined scripts and only check for binaries\"});this.require=ge.String(\"--require\",{description:\"Forwarded to the underlying Node process when executing a binary\"});this.silent=ge.Boolean(\"--silent\",{hidden:!0});this.scriptName=ge.String();this.args=ge.Proxy()}static{this.paths=[[\"run\"]]}static{this.usage=it.Usage({description:\"run a script defined in the package.json\",details:`\n      This command will run a tool. The exact tool that will be executed will depend on the current state of your workspace:\n\n      - If the \\`scripts\\` field from your local package.json contains a matching script name, its definition will get executed.\n\n      - Otherwise, if one of the local workspace's dependencies exposes a binary with a matching name, this binary will get executed.\n\n      - Otherwise, if the specified name contains a colon character and if one of the workspaces in the project contains exactly one script with a matching name, then this script will get executed.\n\n      Whatever happens, the cwd of the spawned process will be the workspace that declares the script (which makes it possible to call commands cross-workspaces using the third syntax).\n    `,examples:[[\"Run the tests from the local workspace\",\"$0 run test\"],['Same thing, but without the \"run\" keyword',\"$0 test\"],[\"Inspect Webpack while running\",\"$0 run --inspect-brk webpack\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a,locator:n}=await kt.find(r,this.context.cwd);await o.restoreInstallState();let u=this.topLevel?o.topLevelWorkspace.anchoredLocator:n;if(!this.binariesOnly&&await An.hasPackageScript(u,this.scriptName,{project:o}))return await An.executePackageScript(u,this.scriptName,this.args,{project:o,stdin:this.context.stdin,stdout:this.context.stdout,stderr:this.context.stderr});let A=await An.getPackageAccessibleBinaries(u,{project:o});if(A.get(this.scriptName)){let h=[];return this.inspect&&(typeof this.inspect==\"string\"?h.push(`--inspect=${this.inspect}`):h.push(\"--inspect\")),this.inspectBrk&&(typeof this.inspectBrk==\"string\"?h.push(`--inspect-brk=${this.inspectBrk}`):h.push(\"--inspect-brk\")),this.require&&h.push(`--require=${this.require}`),await An.executePackageAccessibleBinary(u,this.scriptName,this.args,{cwd:this.context.cwd,project:o,stdin:this.context.stdin,stdout:this.context.stdout,stderr:this.context.stderr,nodeArgs:h,packageAccessibleBinaries:A})}if(!this.topLevel&&!this.binariesOnly&&a&&this.scriptName.includes(\":\")){let E=(await Promise.all(o.workspaces.map(async I=>I.manifest.scripts.has(this.scriptName)?I:null))).filter(I=>I!==null);if(E.length===1)return await An.executeWorkspaceScript(E[0],this.scriptName,this.args,{stdin:this.context.stdin,stdout:this.context.stdout,stderr:this.context.stderr})}if(this.topLevel)throw this.scriptName===\"node-gyp\"?new st(`Couldn't find a script name \"${this.scriptName}\" in the top-level (used by ${G.prettyLocator(r,n)}). This typically happens because some package depends on \"node-gyp\" to build itself, but didn't list it in their dependencies. To fix that, please run \"yarn add node-gyp\" into your top-level workspace. You also can open an issue on the repository of the specified package to suggest them to use an optional peer dependency.`):new st(`Couldn't find a script name \"${this.scriptName}\" in the top-level (used by ${G.prettyLocator(r,n)}).`);{if(this.scriptName===\"global\")throw new st(\"The 'yarn global' commands have been removed in 2.x - consider using 'yarn dlx' or a third-party plugin instead\");let h=[this.scriptName].concat(this.args);for(let[E,I]of Uy)for(let v of I)if(h.length>=v.length&&JSON.stringify(h.slice(0,v.length))===JSON.stringify(v))throw new st(`Couldn't find a script named \"${this.scriptName}\", but a matching command can be found in the ${E} plugin. You can install it with \"yarn plugin import ${E}\".`);throw new st(`Couldn't find a script named \"${this.scriptName}\".`)}}};Ge();Ge();qt();var IE=class extends ut{constructor(){super(...arguments);this.descriptor=ge.String();this.resolution=ge.String()}static{this.paths=[[\"set\",\"resolution\"]]}static{this.usage=it.Usage({description:\"enforce a package resolution\",details:'\\n      This command updates the resolution table so that `descriptor` is resolved by `resolution`.\\n\\n      Note that by default this command only affect the current resolution table - meaning that this \"manual override\" will disappear if you remove the lockfile, or if the package disappear from the table. If you wish to make the enforced resolution persist whatever happens, edit the `resolutions` field in your top-level manifest.\\n\\n      Note that no attempt is made at validating that `resolution` is a valid resolution entry for `descriptor`.\\n    ',examples:[[\"Force all instances of lodash@npm:^1.2.3 to resolve to 1.5.0\",\"$0 set resolution lodash@npm:^1.2.3 1.5.0\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(await o.restoreInstallState({restoreResolutions:!1}),!a)throw new sr(o.cwd,this.context.cwd);let u=G.parseDescriptor(this.descriptor,!0),A=G.makeDescriptor(u,this.resolution);return o.storedDescriptors.set(u.descriptorHash,u),o.storedDescriptors.set(A.descriptorHash,A),o.resolutionAliases.set(u.descriptorHash,A.descriptorHash),await o.installWithNewReport({stdout:this.context.stdout},{cache:n})}};Ge();Pt();qt();var ude=Ze($o()),BE=class extends ut{constructor(){super(...arguments);this.all=ge.Boolean(\"-A,--all\",!1,{description:\"Unlink all workspaces belonging to the target project from the current one\"});this.leadingArguments=ge.Rest()}static{this.paths=[[\"unlink\"]]}static{this.usage=it.Usage({description:\"disconnect the local project from another one\",details:`\n      This command will remove any resolutions in the project-level manifest that would have been added via a yarn link with similar arguments.\n    `,examples:[[\"Unregister a remote workspace in the current project\",\"$0 unlink ~/ts-loader\"],[\"Unregister all workspaces from a remote project in the current project\",\"$0 unlink ~/jest --all\"],[\"Unregister all previously linked workspaces\",\"$0 unlink --all\"],[\"Unregister all workspaces matching a glob\",\"$0 unlink '@babel/*' 'pkg-{a,b}'\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(!a)throw new sr(o.cwd,this.context.cwd);let u=o.topLevelWorkspace,A=new Set;if(this.leadingArguments.length===0&&this.all)for(let{pattern:p,reference:h}of u.manifest.resolutions)h.startsWith(\"portal:\")&&A.add(p.descriptor.fullName);if(this.leadingArguments.length>0)for(let p of this.leadingArguments){let h=V.resolve(this.context.cwd,ue.toPortablePath(p));if(He.isPathLike(p)){let E=await Ke.find(h,this.context.plugins,{useRc:!1,strict:!1}),{project:I,workspace:v}=await kt.find(E,h);if(!v)throw new sr(I.cwd,h);if(this.all){for(let x of I.workspaces)x.manifest.name&&A.add(G.stringifyIdent(x.anchoredLocator));if(A.size===0)throw new st(\"No workspace found to be unlinked in the target project\")}else{if(!v.manifest.name)throw new st(\"The target workspace doesn't have a name and thus cannot be unlinked\");A.add(G.stringifyIdent(v.anchoredLocator))}}else{let E=[...u.manifest.resolutions.map(({pattern:I})=>I.descriptor.fullName)];for(let I of(0,ude.default)(E,p))A.add(I)}}return u.manifest.resolutions=u.manifest.resolutions.filter(({pattern:p})=>!A.has(p.descriptor.fullName)),await o.installWithNewReport({stdout:this.context.stdout,quiet:this.context.quiet},{cache:n})}};Ge();Ge();Ge();qt();var Ade=Ze(J1()),L8=Ze($o());el();var vE=class extends ut{constructor(){super(...arguments);this.interactive=ge.Boolean(\"-i,--interactive\",{description:\"Offer various choices, depending on the detected upgrade paths\"});this.fixed=ge.Boolean(\"-F,--fixed\",!1,{description:\"Store dependency tags as-is instead of resolving them\"});this.exact=ge.Boolean(\"-E,--exact\",!1,{description:\"Don't use any semver modifier on the resolved range\"});this.tilde=ge.Boolean(\"-T,--tilde\",!1,{description:\"Use the `~` semver modifier on the resolved range\"});this.caret=ge.Boolean(\"-C,--caret\",!1,{description:\"Use the `^` semver modifier on the resolved range\"});this.recursive=ge.Boolean(\"-R,--recursive\",!1,{description:\"Resolve again ALL resolutions for those packages\"});this.mode=ge.String(\"--mode\",{description:\"Change what artifacts installs generate\",validator:Js(hl)});this.patterns=ge.Rest()}static{this.paths=[[\"up\"]]}static{this.usage=it.Usage({description:\"upgrade dependencies across the project\",details:\"\\n      This command upgrades the packages matching the list of specified patterns to their latest available version across the whole project (regardless of whether they're part of `dependencies` or `devDependencies` - `peerDependencies` won't be affected). This is a project-wide command: all workspaces will be upgraded in the process.\\n\\n      If `-R,--recursive` is set the command will change behavior and no other switch will be allowed. When operating under this mode `yarn up` will force all ranges matching the selected packages to be resolved again (often to the highest available versions) before being stored in the lockfile. It however won't touch your manifests anymore, so depending on your needs you might want to run both `yarn up` and `yarn up -R` to cover all bases.\\n\\n      If `-i,--interactive` is set (or if the `preferInteractive` settings is toggled on) the command will offer various choices, depending on the detected upgrade paths. Some upgrades require this flag in order to resolve ambiguities.\\n\\n      The, `-C,--caret`, `-E,--exact` and  `-T,--tilde` options have the same meaning as in the `add` command (they change the modifier used when the range is missing or a tag, and are ignored when the range is explicitly set).\\n\\n      If the `--mode=<mode>` option is set, Yarn will change which artifacts are generated. The modes currently supported are:\\n\\n      - `skip-build` will not run the build scripts at all. Note that this is different from setting `enableScripts` to false because the latter will disable build scripts, and thus affect the content of the artifacts generated on disk, whereas the former will just disable the build step - but not the scripts themselves, which just won't run.\\n\\n      - `update-lockfile` will skip the link step altogether, and only fetch packages that are missing from the lockfile (or that have no associated checksums). This mode is typically used by tools like Renovate or Dependabot to keep a lockfile up-to-date without incurring the full install cost.\\n\\n      Generally you can see `yarn up` as a counterpart to what was `yarn upgrade --latest` in Yarn 1 (ie it ignores the ranges previously listed in your manifests), but unlike `yarn upgrade` which only upgraded dependencies in the current workspace, `yarn up` will upgrade all workspaces at the same time.\\n\\n      This command accepts glob patterns as arguments (if valid Descriptors and supported by [micromatch](https://github.com/micromatch/micromatch)). Make sure to escape the patterns, to prevent your own shell from trying to expand them.\\n\\n      **Note:** The ranges have to be static, only the package scopes and names can contain glob patterns.\\n    \",examples:[[\"Upgrade all instances of lodash to the latest release\",\"$0 up lodash\"],[\"Upgrade all instances of lodash to the latest release, but ask confirmation for each\",\"$0 up lodash -i\"],[\"Upgrade all instances of lodash to 1.2.3\",\"$0 up lodash@1.2.3\"],[\"Upgrade all instances of packages with the `@babel` scope to the latest release\",\"$0 up '@babel/*'\"],[\"Upgrade all instances of packages containing the word `jest` to the latest release\",\"$0 up '*jest*'\"],[\"Upgrade all instances of packages with the `@babel` scope to 7.0.0\",\"$0 up '@babel/*@7.0.0'\"]]})}static{this.schema=[Yw(\"recursive\",Yu.Forbids,[\"interactive\",\"exact\",\"tilde\",\"caret\"],{ignore:[void 0,!1]})]}async execute(){return this.recursive?await this.executeUpRecursive():await this.executeUpClassic()}async executeUpRecursive(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(!a)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState({restoreResolutions:!1});let u=[...o.storedDescriptors.values()],A=u.map(E=>G.stringifyIdent(E)),p=new Set;for(let E of this.patterns){if(G.parseDescriptor(E).range!==\"unknown\")throw new st(\"Ranges aren't allowed when using --recursive\");for(let I of(0,L8.default)(A,E)){let v=G.parseIdent(I);p.add(v.identHash)}}let h=u.filter(E=>p.has(E.identHash));for(let E of h)o.storedDescriptors.delete(E.descriptorHash),o.storedResolutions.delete(E.descriptorHash);return await o.installWithNewReport({stdout:this.context.stdout},{cache:n,mode:this.mode})}async executeUpClassic(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(!a)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState({restoreResolutions:!1});let u=this.fixed,A=r.isInteractive({interactive:this.interactive,stdout:this.context.stdout}),p=Z1(this,o),h=A?[\"keep\",\"reuse\",\"project\",\"latest\"]:[\"project\",\"latest\"],E=[],I=[];for(let L of this.patterns){let U=!1,z=G.parseDescriptor(L),te=G.stringifyIdent(z);for(let ae of o.workspaces)for(let le of[\"dependencies\",\"devDependencies\"]){let Ce=[...ae.manifest.getForScope(le).values()].map(Be=>G.stringifyIdent(Be)),de=te===\"*\"?Ce:(0,L8.default)(Ce,te);for(let Be of de){let Ee=G.parseIdent(Be),g=ae.manifest[le].get(Ee.identHash);if(typeof g>\"u\")throw new Error(\"Assertion failed: Expected the descriptor to be registered\");let me=G.makeDescriptor(Ee,z.range);E.push(Promise.resolve().then(async()=>[ae,le,g,await $1(me,{project:o,workspace:ae,cache:n,target:le,fixed:u,modifier:p,strategies:h})])),U=!0}}U||I.push(L)}if(I.length>1)throw new st(`Patterns ${pe.prettyList(r,I,pe.Type.CODE)} don't match any packages referenced by any workspace`);if(I.length>0)throw new st(`Pattern ${pe.prettyList(r,I,pe.Type.CODE)} doesn't match any packages referenced by any workspace`);let v=await Promise.all(E),x=await AA.start({configuration:r,stdout:this.context.stdout,suggestInstall:!1},async L=>{for(let[,,U,{suggestions:z,rejections:te}]of v){let ae=z.filter(le=>le.descriptor!==null);if(ae.length===0){let[le]=te;if(typeof le>\"u\")throw new Error(\"Assertion failed: Expected an error to have been set\");let ce=this.cli.error(le);o.configuration.get(\"enableNetwork\")?L.reportError(27,`${G.prettyDescriptor(r,U)} can't be resolved to a satisfying range\n\n${ce}`):L.reportError(27,`${G.prettyDescriptor(r,U)} can't be resolved to a satisfying range (note: network resolution has been disabled)\n\n${ce}`)}else ae.length>1&&!A&&L.reportError(27,`${G.prettyDescriptor(r,U)} has multiple possible upgrade strategies; use -i to disambiguate manually`)}});if(x.hasErrors())return x.exitCode();let C=!1,R=[];for(let[L,U,,{suggestions:z}]of v){let te,ae=z.filter(de=>de.descriptor!==null),le=ae[0].descriptor,ce=ae.every(de=>G.areDescriptorsEqual(de.descriptor,le));ae.length===1||ce?te=le:(C=!0,{answer:te}=await(0,Ade.prompt)({type:\"select\",name:\"answer\",message:`Which range do you want to use in ${G.prettyWorkspace(r,L)} \\u276F ${U}?`,choices:z.map(({descriptor:de,name:Be,reason:Ee})=>de?{name:Be,hint:Ee,descriptor:de}:{name:Be,hint:Ee,disabled:!0}),onCancel:()=>process.exit(130),result(de){return this.find(de,\"descriptor\")},stdin:this.context.stdin,stdout:this.context.stdout}));let Ce=L.manifest[U].get(te.identHash);if(typeof Ce>\"u\")throw new Error(\"Assertion failed: This descriptor should have a matching entry\");if(Ce.descriptorHash!==te.descriptorHash)L.manifest[U].set(te.identHash,te),R.push([L,U,Ce,te]);else{let de=r.makeResolver(),Be={project:o,resolver:de},Ee=r.normalizeDependency(Ce),g=de.bindDescriptor(Ee,L.anchoredLocator,Be);o.forgetResolution(g)}}return await r.triggerMultipleHooks(L=>L.afterWorkspaceDependencyReplacement,R),C&&this.context.stdout.write(`\n`),await o.installWithNewReport({stdout:this.context.stdout},{cache:n,mode:this.mode})}};Ge();Ge();Ge();qt();var DE=class extends ut{constructor(){super(...arguments);this.recursive=ge.Boolean(\"-R,--recursive\",!1,{description:\"List, for each workspace, what are all the paths that lead to the dependency\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.peers=ge.Boolean(\"--peers\",!1,{description:\"Also print the peer dependencies that match the specified name\"});this.package=ge.String()}static{this.paths=[[\"why\"]]}static{this.usage=it.Usage({description:\"display the reason why a package is needed\",details:`\n      This command prints the exact reasons why a package appears in the dependency tree.\n\n      If \\`-R,--recursive\\` is set, the listing will go in depth and will list, for each workspaces, what are all the paths that lead to the dependency. Note that the display is somewhat optimized in that it will not print the package listing twice for a single package, so if you see a leaf named \"Foo\" when looking for \"Bar\", it means that \"Foo\" already got printed higher in the tree.\n    `,examples:[[\"Explain why lodash is used in your project\",\"$0 why lodash\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!a)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState();let n=G.parseIdent(this.package).identHash,u=this.recursive?cgt(o,n,{configuration:r,peers:this.peers}):lgt(o,n,{configuration:r,peers:this.peers});fs.emitTree(u,{configuration:r,stdout:this.context.stdout,json:this.json,separators:1})}};function lgt(t,e,{configuration:r,peers:o}){let a=He.sortMap(t.storedPackages.values(),A=>G.stringifyLocator(A)),n={},u={children:n};for(let A of a){let p={};for(let E of A.dependencies.values()){if(!o&&A.peerDependencies.has(E.identHash))continue;let I=t.storedResolutions.get(E.descriptorHash);if(!I)throw new Error(\"Assertion failed: The resolution should have been registered\");let v=t.storedPackages.get(I);if(!v)throw new Error(\"Assertion failed: The package should have been registered\");if(v.identHash!==e)continue;{let C=G.stringifyLocator(A);n[C]={value:[A,pe.Type.LOCATOR],children:p}}let x=G.stringifyLocator(v);p[x]={value:[{descriptor:E,locator:v},pe.Type.DEPENDENT]}}}return u}function cgt(t,e,{configuration:r,peers:o}){let a=He.sortMap(t.workspaces,v=>G.stringifyLocator(v.anchoredLocator)),n=new Set,u=new Set,A=v=>{if(n.has(v.locatorHash))return u.has(v.locatorHash);if(n.add(v.locatorHash),v.identHash===e)return u.add(v.locatorHash),!0;let x=!1;v.identHash===e&&(x=!0);for(let C of v.dependencies.values()){if(!o&&v.peerDependencies.has(C.identHash))continue;let R=t.storedResolutions.get(C.descriptorHash);if(!R)throw new Error(\"Assertion failed: The resolution should have been registered\");let L=t.storedPackages.get(R);if(!L)throw new Error(\"Assertion failed: The package should have been registered\");A(L)&&(x=!0)}return x&&u.add(v.locatorHash),x};for(let v of a)A(v.anchoredPackage);let p=new Set,h={},E={children:h},I=(v,x,C)=>{if(!u.has(v.locatorHash))return;let R=C!==null?pe.tuple(pe.Type.DEPENDENT,{locator:v,descriptor:C}):pe.tuple(pe.Type.LOCATOR,v),L={},U={value:R,children:L},z=G.stringifyLocator(v);if(x[z]=U,!(C!==null&&t.tryWorkspaceByLocator(v))&&!p.has(v.locatorHash)){p.add(v.locatorHash);for(let te of v.dependencies.values()){if(!o&&v.peerDependencies.has(te.identHash))continue;let ae=t.storedResolutions.get(te.descriptorHash);if(!ae)throw new Error(\"Assertion failed: The resolution should have been registered\");let le=t.storedPackages.get(ae);if(!le)throw new Error(\"Assertion failed: The package should have been registered\");I(le,L,te)}}};for(let v of a)I(v.anchoredPackage,h,null);return E}Ge();var W8={};Vt(W8,{GitFetcher:()=>s2,GitResolver:()=>o2,default:()=>kgt,gitUtils:()=>ia});Ge();Pt();var ia={};Vt(ia,{TreeishProtocols:()=>i2,clone:()=>Y8,fetchBase:()=>Rde,fetchChangedFiles:()=>Tde,fetchChangedWorkspaces:()=>Sgt,fetchRoot:()=>Fde,isGitUrl:()=>SE,lsRemote:()=>Qde,normalizeLocator:()=>bgt,normalizeRepoUrl:()=>PE,resolveUrl:()=>G8,splitRepoUrl:()=>Sh,validateRepoUrl:()=>j8});Ge();Pt();qt();var Sde=Ze(Dde()),xde=Ze(uU()),bE=Ze(ve(\"querystring\")),H8=Ze(Jn());function _8(t,e,r){let o=t.indexOf(r);return t.lastIndexOf(e,o>-1?o:1/0)}function Pde(t){try{return new URL(t)}catch{return}}function Dgt(t){let e=_8(t,\"@\",\"#\"),r=_8(t,\":\",\"#\");return r>e&&(t=`${t.slice(0,r)}/${t.slice(r+1)}`),_8(t,\":\",\"#\")===-1&&t.indexOf(\"//\")===-1&&(t=`ssh://${t}`),t}function bde(t){return Pde(t)||Pde(Dgt(t))}function PE(t,{git:e=!1}={}){if(t=t.replace(/^git\\+https:/,\"https:\"),t=t.replace(/^(?:github:|https:\\/\\/github\\.com\\/|git:\\/\\/github\\.com\\/)?(?!\\.{1,2}\\/)([a-zA-Z0-9._-]+)\\/(?!\\.{1,2}(?:#|$))([a-zA-Z0-9._-]+?)(?:\\.git)?(#.*)?$/,\"https://github.com/$1/$2.git$3\"),t=t.replace(/^https:\\/\\/github\\.com\\/(?!\\.{1,2}\\/)([a-zA-Z0-9._-]+)\\/(?!\\.{1,2}(?:#|$))([a-zA-Z0-9._-]+?)\\/tarball\\/(.+)?$/,\"https://github.com/$1/$2.git#$3\"),e){let r=bde(t);r&&(t=r.href),t=t.replace(/^git\\+([^:]+):/,\"$1:\")}return t}function kde(){return{...process.env,GIT_SSH_COMMAND:process.env.GIT_SSH_COMMAND||`${process.env.GIT_SSH||\"ssh\"} -o BatchMode=yes`}}var Pgt=[/^ssh:/,/^git(?:\\+[^:]+)?:/,/^(?:git\\+)?https?:[^#]+\\/[^#]+(?:\\.git)(?:#.*)?$/,/^git@[^#]+\\/[^#]+\\.git(?:#.*)?$/,/^(?:github:|https:\\/\\/github\\.com\\/)?(?!\\.{1,2}\\/)([a-zA-Z._0-9-]+)\\/(?!\\.{1,2}(?:#|$))([a-zA-Z._0-9-]+?)(?:\\.git)?(?:#.*)?$/,/^https:\\/\\/github\\.com\\/(?!\\.{1,2}\\/)([a-zA-Z0-9._-]+)\\/(?!\\.{1,2}(?:#|$))([a-zA-Z0-9._-]+?)\\/tarball\\/(.+)?$/],i2=(a=>(a.Commit=\"commit\",a.Head=\"head\",a.Tag=\"tag\",a.Semver=\"semver\",a))(i2||{});function SE(t){return t?Pgt.some(e=>!!t.match(e)):!1}function Sh(t){t=PE(t);let e=t.indexOf(\"#\");if(e===-1)return{repo:t,treeish:{protocol:\"head\",request:\"HEAD\"},extra:{}};let r=t.slice(0,e),o=t.slice(e+1);if(o.match(/^[a-z]+=/)){let a=bE.default.parse(o);for(let[p,h]of Object.entries(a))if(typeof h!=\"string\")throw new Error(`Assertion failed: The ${p} parameter must be a literal string`);let n=Object.values(i2).find(p=>Object.hasOwn(a,p)),[u,A]=typeof n<\"u\"?[n,a[n]]:[\"head\",\"HEAD\"];for(let p of Object.values(i2))delete a[p];return{repo:r,treeish:{protocol:u,request:A},extra:a}}else{let a=o.indexOf(\":\"),[n,u]=a===-1?[null,o]:[o.slice(0,a),o.slice(a+1)];return{repo:r,treeish:{protocol:n,request:u},extra:{}}}}function bgt(t){return G.makeLocator(t,PE(t.reference))}function j8(t,{configuration:e}){let r=PE(t,{git:!0});if(!sn.getNetworkSettings(`https://${(0,Sde.default)(r).resource}`,{configuration:e}).enableNetwork)throw new Jt(80,`Request to '${r}' has been blocked because of your configuration settings`);return r}async function Qde(t,e){let r=j8(t,{configuration:e}),o=await q8(\"listing refs\",[\"ls-remote\",r],{cwd:e.startingCwd,env:kde()},{configuration:e,normalizedRepoUrl:r}),a=new Map,n=/^([a-f0-9]{40})\\t([^\\n]+)/gm,u;for(;(u=n.exec(o.stdout))!==null;)a.set(u[2],u[1]);return a}async function G8(t,e){let{repo:r,treeish:{protocol:o,request:a},extra:n}=Sh(t),u=await Qde(r,e),A=(h,E)=>{switch(h){case\"commit\":{if(!E.match(/^[a-f0-9]{40}$/))throw new Error(\"Invalid commit hash\");return bE.default.stringify({...n,commit:E})}case\"head\":{let I=u.get(E===\"HEAD\"?E:`refs/heads/${E}`);if(typeof I>\"u\")throw new Error(`Unknown head (\"${E}\")`);return bE.default.stringify({...n,commit:I})}case\"tag\":{let I=u.get(`refs/tags/${E}`);if(typeof I>\"u\")throw new Error(`Unknown tag (\"${E}\")`);return bE.default.stringify({...n,commit:I})}case\"semver\":{let I=Lr.validRange(E);if(!I)throw new Error(`Invalid range (\"${E}\")`);let v=new Map([...u.entries()].filter(([C])=>C.startsWith(\"refs/tags/\")).map(([C,R])=>[H8.default.parse(C.slice(10)),R]).filter(C=>C[0]!==null)),x=H8.default.maxSatisfying([...v.keys()],I);if(x===null)throw new Error(`No matching range (\"${E}\")`);return bE.default.stringify({...n,commit:v.get(x)})}case null:{let I;if((I=p(\"commit\",E))!==null||(I=p(\"tag\",E))!==null||(I=p(\"head\",E))!==null)return I;throw E.match(/^[a-f0-9]+$/)?new Error(`Couldn't resolve \"${E}\" as either a commit, a tag, or a head - if a commit, use the 40-characters commit hash`):new Error(`Couldn't resolve \"${E}\" as either a commit, a tag, or a head`)}default:throw new Error(`Invalid Git resolution protocol (\"${h}\")`)}},p=(h,E)=>{try{return A(h,E)}catch{return null}};return PE(`${r}#${A(o,a)}`)}async function Y8(t,e){return await e.getLimit(\"cloneConcurrency\")(async()=>{let{repo:r,treeish:{protocol:o,request:a}}=Sh(t);if(o!==\"commit\")throw new Error(\"Invalid treeish protocol when cloning\");let n=j8(r,{configuration:e}),u=await oe.mktempPromise(),A={cwd:u,env:kde()};return await q8(\"cloning the repository\",[\"clone\",\"-c core.autocrlf=false\",n,ue.fromPortablePath(u)],A,{configuration:e,normalizedRepoUrl:n}),await q8(\"switching branch\",[\"checkout\",`${a}`],A,{configuration:e,normalizedRepoUrl:n}),u})}async function Fde(t){let e,r=t;do{if(e=r,await oe.existsPromise(V.join(e,\".git\")))return e;r=V.dirname(e)}while(r!==e);return null}async function Rde(t,{baseRefs:e}){if(e.length===0)throw new st(\"Can't run this command with zero base refs specified.\");let r=[];for(let A of e){let{code:p}=await Ur.execvp(\"git\",[\"merge-base\",A,\"HEAD\"],{cwd:t});p===0&&r.push(A)}if(r.length===0)throw new st(`No ancestor could be found between any of HEAD and ${e.join(\", \")}`);let{stdout:o}=await Ur.execvp(\"git\",[\"merge-base\",\"HEAD\",...r],{cwd:t,strict:!0}),a=o.trim(),{stdout:n}=await Ur.execvp(\"git\",[\"show\",\"--quiet\",\"--pretty=format:%s\",a],{cwd:t,strict:!0}),u=n.trim();return{hash:a,title:u}}async function Tde(t,{base:e,project:r}){let o=He.buildIgnorePattern(r.configuration.get(\"changesetIgnorePatterns\")),{stdout:a}=await Ur.execvp(\"git\",[\"diff\",\"--name-only\",`${e}`],{cwd:t,strict:!0}),n=a.split(/\\r\\n|\\r|\\n/).filter(h=>h.length>0).map(h=>V.resolve(t,ue.toPortablePath(h))),{stdout:u}=await Ur.execvp(\"git\",[\"ls-files\",\"--others\",\"--exclude-standard\"],{cwd:t,strict:!0}),A=u.split(/\\r\\n|\\r|\\n/).filter(h=>h.length>0).map(h=>V.resolve(t,ue.toPortablePath(h))),p=[...new Set([...n,...A].sort())];return o?p.filter(h=>!V.relative(r.cwd,h).match(o)):p}async function Sgt({ref:t,project:e}){if(e.configuration.projectCwd===null)throw new st(\"This command can only be run from within a Yarn project\");let r=[V.resolve(e.cwd,dr.lockfile),V.resolve(e.cwd,e.configuration.get(\"cacheFolder\")),V.resolve(e.cwd,e.configuration.get(\"installStatePath\")),V.resolve(e.cwd,e.configuration.get(\"virtualFolder\"))];await e.configuration.triggerHook(u=>u.populateYarnPaths,e,u=>{u!=null&&r.push(u)});let o=await Fde(e.configuration.projectCwd);if(o==null)throw new st(\"This command can only be run on Git repositories\");let a=await Rde(o,{baseRefs:typeof t==\"string\"?[t]:e.configuration.get(\"changesetBaseRefs\")}),n=await Tde(o,{base:a.hash,project:e});return new Set(He.mapAndFilter(n,u=>{let A=e.tryWorkspaceByFilePath(u);return A===null?He.mapAndFilter.skip:r.some(p=>u.startsWith(p))?He.mapAndFilter.skip:A}))}async function q8(t,e,r,{configuration:o,normalizedRepoUrl:a}){try{return await Ur.execvp(\"git\",e,{...r,strict:!0})}catch(n){if(!(n instanceof Ur.ExecError))throw n;let u=n.reportExtra,A=n.stderr.toString();throw new Jt(1,`Failed ${t}`,p=>{p.reportError(1,`  ${pe.prettyField(o,{label:\"Repository URL\",value:pe.tuple(pe.Type.URL,a)})}`);for(let h of A.matchAll(/^(.+?): (.*)$/gm)){let[,E,I]=h;E=E.toLowerCase();let v=E===\"error\"?\"Error\":`${(0,xde.default)(E)} Error`;p.reportError(1,`  ${pe.prettyField(o,{label:v,value:pe.tuple(pe.Type.NO_HINT,I)})}`)}u?.(p)})}}var s2=class{supports(e,r){return SE(e.reference)}getLocalPath(e,r){return null}async fetch(e,r){let o=r.checksums.get(e.locatorHash)||null,a=new Map(r.checksums);a.set(e.locatorHash,o);let n={...r,checksums:a},u=await this.downloadHosted(e,n);if(u!==null)return u;let[A,p,h]=await r.cache.fetchPackageFromCache(e,o,{onHit:()=>r.report.reportCacheHit(e),onMiss:()=>r.report.reportCacheMiss(e,`${G.prettyLocator(r.project.configuration,e)} can't be found in the cache and will be fetched from the remote repository`),loader:()=>this.cloneFromRemote(e,n),...r.cacheOptions});return{packageFs:A,releaseFs:p,prefixPath:G.getIdentVendorPath(e),checksum:h}}async downloadHosted(e,r){return r.project.configuration.reduceHook(o=>o.fetchHostedRepository,null,e,r)}async cloneFromRemote(e,r){let o=Sh(e.reference),a=await Y8(e.reference,r.project.configuration),n=V.resolve(a,o.extra.cwd??It.dot),u=V.join(n,\"package.tgz\");await An.prepareExternalProject(n,u,{configuration:r.project.configuration,report:r.report,workspace:o.extra.workspace,locator:e});let A=await oe.readFilePromise(u);return await He.releaseAfterUseAsync(async()=>await $i.convertToZip(A,{configuration:r.project.configuration,prefixPath:G.getIdentVendorPath(e),stripComponents:1}))}};Ge();Ge();var o2=class{supportsDescriptor(e,r){return SE(e.range)}supportsLocator(e,r){return SE(e.reference)}shouldPersistResolution(e,r){return!0}bindDescriptor(e,r,o){return e}getResolutionDependencies(e,r){return{}}async getCandidates(e,r,o){let a=await G8(e.range,o.project.configuration);return[G.makeLocator(e,a)]}async getSatisfying(e,r,o,a){let n=Sh(e.range);return{locators:o.filter(A=>{if(A.identHash!==e.identHash)return!1;let p=Sh(A.reference);return!(n.repo!==p.repo||n.treeish.protocol===\"commit\"&&n.treeish.request!==p.treeish.request)}),sorted:!1}}async resolve(e,r){if(!r.fetchOptions)throw new Error(\"Assertion failed: This resolver cannot be used unless a fetcher is configured\");let o=await r.fetchOptions.fetcher.fetch(e,r.fetchOptions),a=await He.releaseAfterUseAsync(async()=>await Ut.find(o.prefixPath,{baseFs:o.packageFs}),o.releaseFs);return{...e,version:a.version||\"0.0.0\",languageName:a.languageName||r.project.configuration.get(\"defaultLanguageName\"),linkType:\"HARD\",conditions:a.getConditions(),dependencies:r.project.configuration.normalizeDependencyMap(a.dependencies),peerDependencies:a.peerDependencies,dependenciesMeta:a.dependenciesMeta,peerDependenciesMeta:a.peerDependenciesMeta,bin:a.bin}}};var xgt={configuration:{changesetBaseRefs:{description:\"The base git refs that the current HEAD is compared against when detecting changes. Supports git branches, tags, and commits.\",type:\"STRING\",isArray:!0,isNullable:!1,default:[\"master\",\"origin/master\",\"upstream/master\",\"main\",\"origin/main\",\"upstream/main\"]},changesetIgnorePatterns:{description:\"Array of glob patterns; files matching them will be ignored when fetching the changed files\",type:\"STRING\",default:[],isArray:!0},cloneConcurrency:{description:\"Maximal number of concurrent clones\",type:\"NUMBER\",default:2}},fetchers:[s2],resolvers:[o2]};var kgt=xgt;qt();var xE=class extends ut{constructor(){super(...arguments);this.since=ge.String(\"--since\",{description:\"Only include workspaces that have been changed since the specified ref.\",tolerateBoolean:!0});this.recursive=ge.Boolean(\"-R,--recursive\",!1,{description:\"Find packages via dependencies/devDependencies instead of using the workspaces field\"});this.noPrivate=ge.Boolean(\"--no-private\",{description:\"Exclude workspaces that have the private field set to true\"});this.verbose=ge.Boolean(\"-v,--verbose\",!1,{description:\"Also return the cross-dependencies between workspaces\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"})}static{this.paths=[[\"workspaces\",\"list\"]]}static{this.usage=it.Usage({category:\"Workspace-related commands\",description:\"list all available workspaces\",details:\"\\n      This command will print the list of all workspaces in the project.\\n\\n      - If `--since` is set, Yarn will only list workspaces that have been modified since the specified ref. By default Yarn will use the refs specified by the `changesetBaseRefs` configuration option.\\n\\n      - If `-R,--recursive` is set, Yarn will find workspaces to run the command on by recursively evaluating `dependencies` and `devDependencies` fields, instead of looking at the `workspaces` fields.\\n\\n      - If `--no-private` is set, Yarn will not list any workspaces that have the `private` field set to `true`.\\n\\n      - If both the `-v,--verbose` and `--json` options are set, Yarn will also return the cross-dependencies between each workspaces (useful when you wish to automatically generate Buck / Bazel rules).\\n    \"})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o}=await kt.find(r,this.context.cwd);return(await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout},async n=>{let u=this.since?await ia.fetchChangedWorkspaces({ref:this.since,project:o}):o.workspaces,A=new Set(u);if(this.recursive)for(let p of[...u].map(h=>h.getRecursiveWorkspaceDependents()))for(let h of p)A.add(h);for(let p of A){let{manifest:h}=p;if(h.private&&this.noPrivate)continue;let E;if(this.verbose){let I=new Set,v=new Set;for(let x of Ut.hardDependencies)for(let[C,R]of h.getForScope(x)){let L=o.tryWorkspaceByDescriptor(R);L===null?o.workspacesByIdent.has(C)&&v.add(R):I.add(L)}E={workspaceDependencies:Array.from(I).map(x=>x.relativeCwd),mismatchedWorkspaceDependencies:Array.from(v).map(x=>G.stringifyDescriptor(x))}}n.reportInfo(null,`${p.relativeCwd}`),n.reportJson({location:p.relativeCwd,name:h.name?G.stringifyIdent(h.name):null,...E})}})).exitCode()}};Ge();Ge();qt();var kE=class extends ut{constructor(){super(...arguments);this.workspaceName=ge.String();this.commandName=ge.String();this.args=ge.Proxy()}static{this.paths=[[\"workspace\"]]}static{this.usage=it.Usage({category:\"Workspace-related commands\",description:\"run a command within the specified workspace\",details:`\n      This command will run a given sub-command on a single workspace.\n    `,examples:[[\"Add a package to a single workspace\",\"yarn workspace components add -D react\"],[\"Run build script on a single workspace\",\"yarn workspace components run build\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!a)throw new sr(o.cwd,this.context.cwd);let n=o.workspaces,u=new Map(n.map(p=>[G.stringifyIdent(p.anchoredLocator),p])),A=u.get(this.workspaceName);if(A===void 0){let p=Array.from(u.keys()).sort();throw new st(`Workspace '${this.workspaceName}' not found. Did you mean any of the following:\n  - ${p.join(`\n  - `)}?`)}return this.cli.run([this.commandName,...this.args],{cwd:A.cwd})}};var Qgt={configuration:{enableImmutableInstalls:{description:\"If true (the default on CI), prevents the install command from modifying the lockfile\",type:\"BOOLEAN\",default:Nde.isCI},defaultSemverRangePrefix:{description:\"The default save prefix: '^', '~' or ''\",type:\"STRING\",values:[\"^\",\"~\",\"\"],default:\"^\"},preferReuse:{description:\"If true, `yarn add` will attempt to reuse the most common dependency range in other workspaces.\",type:\"BOOLEAN\",default:!1}},commands:[Ky,Vy,zy,Jy,IE,pE,sE,xE,$y,eE,tE,rE,Yy,Wy,Xy,Zy,nE,iE,oE,aE,lE,cE,BE,uE,AE,gE,hE,dE,fE,mE,yE,EE,CE,wE,vE,DE,kE]},Fgt=Qgt;var Z8={};Vt(Z8,{default:()=>Tgt});Ge();var xt={optional:!0},V8=[[\"@tailwindcss/aspect-ratio@<0.2.1\",{peerDependencies:{tailwindcss:\"^2.0.2\"}}],[\"@tailwindcss/line-clamp@<0.2.1\",{peerDependencies:{tailwindcss:\"^2.0.2\"}}],[\"@fullhuman/postcss-purgecss@3.1.3 || 3.1.3-alpha.0\",{peerDependencies:{postcss:\"^8.0.0\"}}],[\"@samverschueren/stream-to-observable@<0.3.1\",{peerDependenciesMeta:{rxjs:xt,zenObservable:xt}}],[\"any-observable@<0.5.1\",{peerDependenciesMeta:{rxjs:xt,zenObservable:xt}}],[\"@pm2/agent@<1.0.4\",{dependencies:{debug:\"*\"}}],[\"debug@<4.2.0\",{peerDependenciesMeta:{\"supports-color\":xt}}],[\"got@<11\",{dependencies:{\"@types/responselike\":\"^1.0.0\",\"@types/keyv\":\"^3.1.1\"}}],[\"cacheable-lookup@<4.1.2\",{dependencies:{\"@types/keyv\":\"^3.1.1\"}}],[\"http-link-dataloader@*\",{peerDependencies:{graphql:\"^0.13.1 || ^14.0.0\"}}],[\"typescript-language-server@*\",{dependencies:{\"vscode-jsonrpc\":\"^5.0.1\",\"vscode-languageserver-protocol\":\"^3.15.0\"}}],[\"postcss-syntax@*\",{peerDependenciesMeta:{\"postcss-html\":xt,\"postcss-jsx\":xt,\"postcss-less\":xt,\"postcss-markdown\":xt,\"postcss-scss\":xt}}],[\"jss-plugin-rule-value-function@<=10.1.1\",{dependencies:{\"tiny-warning\":\"^1.0.2\"}}],[\"ink-select-input@<4.1.0\",{peerDependencies:{react:\"^16.8.2\"}}],[\"license-webpack-plugin@<2.3.18\",{peerDependenciesMeta:{webpack:xt}}],[\"snowpack@>=3.3.0\",{dependencies:{\"node-gyp\":\"^7.1.0\"}}],[\"promise-inflight@*\",{peerDependenciesMeta:{bluebird:xt}}],[\"reactcss@*\",{peerDependencies:{react:\"*\"}}],[\"react-color@<=2.19.0\",{peerDependencies:{react:\"*\"}}],[\"gatsby-plugin-i18n@*\",{dependencies:{ramda:\"^0.24.1\"}}],[\"useragent@^2.0.0\",{dependencies:{request:\"^2.88.0\",yamlparser:\"0.0.x\",semver:\"5.5.x\"}}],[\"@apollographql/apollo-tools@<=0.5.2\",{peerDependencies:{graphql:\"^14.2.1 || ^15.0.0\"}}],[\"material-table@^2.0.0\",{dependencies:{\"@babel/runtime\":\"^7.11.2\"}}],[\"@babel/parser@*\",{dependencies:{\"@babel/types\":\"^7.8.3\"}}],[\"fork-ts-checker-webpack-plugin@<=6.3.4\",{peerDependencies:{eslint:\">= 6\",typescript:\">= 2.7\",webpack:\">= 4\",\"vue-template-compiler\":\"*\"},peerDependenciesMeta:{eslint:xt,\"vue-template-compiler\":xt}}],[\"rc-animate@<=3.1.1\",{peerDependencies:{react:\">=16.9.0\",\"react-dom\":\">=16.9.0\"}}],[\"react-bootstrap-table2-paginator@*\",{dependencies:{classnames:\"^2.2.6\"}}],[\"react-draggable@<=4.4.3\",{peerDependencies:{react:\">= 16.3.0\",\"react-dom\":\">= 16.3.0\"}}],[\"apollo-upload-client@<14\",{peerDependencies:{graphql:\"14 - 15\"}}],[\"react-instantsearch-core@<=6.7.0\",{peerDependencies:{algoliasearch:\">= 3.1 < 5\"}}],[\"react-instantsearch-dom@<=6.7.0\",{dependencies:{\"react-fast-compare\":\"^3.0.0\"}}],[\"ws@<7.2.1\",{peerDependencies:{bufferutil:\"^4.0.1\",\"utf-8-validate\":\"^5.0.2\"},peerDependenciesMeta:{bufferutil:xt,\"utf-8-validate\":xt}}],[\"react-portal@<4.2.2\",{peerDependencies:{\"react-dom\":\"^15.0.0-0 || ^16.0.0-0 || ^17.0.0-0\"}}],[\"react-scripts@<=4.0.1\",{peerDependencies:{react:\"*\"}}],[\"testcafe@<=1.10.1\",{dependencies:{\"@babel/plugin-transform-for-of\":\"^7.12.1\",\"@babel/runtime\":\"^7.12.5\"}}],[\"testcafe-legacy-api@<=4.2.0\",{dependencies:{\"testcafe-hammerhead\":\"^17.0.1\",\"read-file-relative\":\"^1.2.0\"}}],[\"@google-cloud/firestore@<=4.9.3\",{dependencies:{protobufjs:\"^6.8.6\"}}],[\"gatsby-source-apiserver@*\",{dependencies:{\"babel-polyfill\":\"^6.26.0\"}}],[\"@webpack-cli/package-utils@<=1.0.1-alpha.4\",{dependencies:{\"cross-spawn\":\"^7.0.3\"}}],[\"gatsby-remark-prismjs@<3.3.28\",{dependencies:{lodash:\"^4\"}}],[\"gatsby-plugin-favicon@*\",{peerDependencies:{webpack:\"*\"}}],[\"gatsby-plugin-sharp@<=4.6.0-next.3\",{dependencies:{debug:\"^4.3.1\"}}],[\"gatsby-react-router-scroll@<=5.6.0-next.0\",{dependencies:{\"prop-types\":\"^15.7.2\"}}],[\"@rebass/forms@*\",{dependencies:{\"@styled-system/should-forward-prop\":\"^5.0.0\"},peerDependencies:{react:\"^16.8.6\"}}],[\"rebass@*\",{peerDependencies:{react:\"^16.8.6\"}}],[\"@ant-design/react-slick@<=0.28.3\",{peerDependencies:{react:\">=16.0.0\"}}],[\"mqtt@<4.2.7\",{dependencies:{duplexify:\"^4.1.1\"}}],[\"vue-cli-plugin-vuetify@<=2.0.3\",{dependencies:{semver:\"^6.3.0\"},peerDependenciesMeta:{\"sass-loader\":xt,\"vuetify-loader\":xt}}],[\"vue-cli-plugin-vuetify@<=2.0.4\",{dependencies:{\"null-loader\":\"^3.0.0\"}}],[\"vue-cli-plugin-vuetify@>=2.4.3\",{peerDependencies:{vue:\"*\"}}],[\"@vuetify/cli-plugin-utils@<=0.0.4\",{dependencies:{semver:\"^6.3.0\"},peerDependenciesMeta:{\"sass-loader\":xt}}],[\"@vue/cli-plugin-typescript@<=5.0.0-alpha.0\",{dependencies:{\"babel-loader\":\"^8.1.0\"}}],[\"@vue/cli-plugin-typescript@<=5.0.0-beta.0\",{dependencies:{\"@babel/core\":\"^7.12.16\"},peerDependencies:{\"vue-template-compiler\":\"^2.0.0\"},peerDependenciesMeta:{\"vue-template-compiler\":xt}}],[\"cordova-ios@<=6.3.0\",{dependencies:{underscore:\"^1.9.2\"}}],[\"cordova-lib@<=10.0.1\",{dependencies:{underscore:\"^1.9.2\"}}],[\"git-node-fs@*\",{peerDependencies:{\"js-git\":\"^0.7.8\"},peerDependenciesMeta:{\"js-git\":xt}}],[\"consolidate@<0.16.0\",{peerDependencies:{mustache:\"^3.0.0\"},peerDependenciesMeta:{mustache:xt}}],[\"consolidate@<=0.16.0\",{peerDependencies:{velocityjs:\"^2.0.1\",tinyliquid:\"^0.2.34\",\"liquid-node\":\"^3.0.1\",jade:\"^1.11.0\",\"then-jade\":\"*\",dust:\"^0.3.0\",\"dustjs-helpers\":\"^1.7.4\",\"dustjs-linkedin\":\"^2.7.5\",swig:\"^1.4.2\",\"swig-templates\":\"^2.0.3\",\"razor-tmpl\":\"^1.3.1\",atpl:\">=0.7.6\",liquor:\"^0.0.5\",twig:\"^1.15.2\",ejs:\"^3.1.5\",eco:\"^1.1.0-rc-3\",jazz:\"^0.0.18\",jqtpl:\"~1.1.0\",hamljs:\"^0.6.2\",hamlet:\"^0.3.3\",whiskers:\"^0.4.0\",\"haml-coffee\":\"^1.14.1\",\"hogan.js\":\"^3.0.2\",templayed:\">=0.2.3\",handlebars:\"^4.7.6\",underscore:\"^1.11.0\",lodash:\"^4.17.20\",pug:\"^3.0.0\",\"then-pug\":\"*\",qejs:\"^3.0.5\",walrus:\"^0.10.1\",mustache:\"^4.0.1\",just:\"^0.1.8\",ect:\"^0.5.9\",mote:\"^0.2.0\",toffee:\"^0.3.6\",dot:\"^1.1.3\",\"bracket-template\":\"^1.1.5\",ractive:\"^1.3.12\",nunjucks:\"^3.2.2\",htmling:\"^0.0.8\",\"babel-core\":\"^6.26.3\",plates:\"~0.4.11\",\"react-dom\":\"^16.13.1\",react:\"^16.13.1\",\"arc-templates\":\"^0.5.3\",vash:\"^0.13.0\",slm:\"^2.0.0\",marko:\"^3.14.4\",teacup:\"^2.0.0\",\"coffee-script\":\"^1.12.7\",squirrelly:\"^5.1.0\",twing:\"^5.0.2\"},peerDependenciesMeta:{velocityjs:xt,tinyliquid:xt,\"liquid-node\":xt,jade:xt,\"then-jade\":xt,dust:xt,\"dustjs-helpers\":xt,\"dustjs-linkedin\":xt,swig:xt,\"swig-templates\":xt,\"razor-tmpl\":xt,atpl:xt,liquor:xt,twig:xt,ejs:xt,eco:xt,jazz:xt,jqtpl:xt,hamljs:xt,hamlet:xt,whiskers:xt,\"haml-coffee\":xt,\"hogan.js\":xt,templayed:xt,handlebars:xt,underscore:xt,lodash:xt,pug:xt,\"then-pug\":xt,qejs:xt,walrus:xt,mustache:xt,just:xt,ect:xt,mote:xt,toffee:xt,dot:xt,\"bracket-template\":xt,ractive:xt,nunjucks:xt,htmling:xt,\"babel-core\":xt,plates:xt,\"react-dom\":xt,react:xt,\"arc-templates\":xt,vash:xt,slm:xt,marko:xt,teacup:xt,\"coffee-script\":xt,squirrelly:xt,twing:xt}}],[\"vue-loader@<=16.3.3\",{peerDependencies:{\"@vue/compiler-sfc\":\"^3.0.8\",webpack:\"^4.1.0 || ^5.0.0-0\"},peerDependenciesMeta:{\"@vue/compiler-sfc\":xt}}],[\"vue-loader@^16.7.0\",{peerDependencies:{\"@vue/compiler-sfc\":\"^3.0.8\",vue:\"^3.2.13\"},peerDependenciesMeta:{\"@vue/compiler-sfc\":xt,vue:xt}}],[\"scss-parser@<=1.0.5\",{dependencies:{lodash:\"^4.17.21\"}}],[\"query-ast@<1.0.5\",{dependencies:{lodash:\"^4.17.21\"}}],[\"redux-thunk@<=2.3.0\",{peerDependencies:{redux:\"^4.0.0\"}}],[\"skypack@<=0.3.2\",{dependencies:{tar:\"^6.1.0\"}}],[\"@npmcli/metavuln-calculator@<2.0.0\",{dependencies:{\"json-parse-even-better-errors\":\"^2.3.1\"}}],[\"bin-links@<2.3.0\",{dependencies:{\"mkdirp-infer-owner\":\"^1.0.2\"}}],[\"rollup-plugin-polyfill-node@<=0.8.0\",{peerDependencies:{rollup:\"^1.20.0 || ^2.0.0\"}}],[\"snowpack@<3.8.6\",{dependencies:{\"magic-string\":\"^0.25.7\"}}],[\"elm-webpack-loader@*\",{dependencies:{temp:\"^0.9.4\"}}],[\"winston-transport@<=4.4.0\",{dependencies:{logform:\"^2.2.0\"}}],[\"jest-vue-preprocessor@*\",{dependencies:{\"@babel/core\":\"7.8.7\",\"@babel/template\":\"7.8.6\"},peerDependencies:{pug:\"^2.0.4\"},peerDependenciesMeta:{pug:xt}}],[\"redux-persist@*\",{peerDependencies:{react:\">=16\"},peerDependenciesMeta:{react:xt}}],[\"sodium@>=3\",{dependencies:{\"node-gyp\":\"^3.8.0\"}}],[\"babel-plugin-graphql-tag@<=3.1.0\",{peerDependencies:{graphql:\"^14.0.0 || ^15.0.0\"}}],[\"@playwright/test@<=1.14.1\",{dependencies:{\"jest-matcher-utils\":\"^26.4.2\"}}],...[\"babel-plugin-remove-graphql-queries@<3.14.0-next.1\",\"babel-preset-gatsby-package@<1.14.0-next.1\",\"create-gatsby@<1.14.0-next.1\",\"gatsby-admin@<0.24.0-next.1\",\"gatsby-cli@<3.14.0-next.1\",\"gatsby-core-utils@<2.14.0-next.1\",\"gatsby-design-tokens@<3.14.0-next.1\",\"gatsby-legacy-polyfills@<1.14.0-next.1\",\"gatsby-plugin-benchmark-reporting@<1.14.0-next.1\",\"gatsby-plugin-graphql-config@<0.23.0-next.1\",\"gatsby-plugin-image@<1.14.0-next.1\",\"gatsby-plugin-mdx@<2.14.0-next.1\",\"gatsby-plugin-netlify-cms@<5.14.0-next.1\",\"gatsby-plugin-no-sourcemaps@<3.14.0-next.1\",\"gatsby-plugin-page-creator@<3.14.0-next.1\",\"gatsby-plugin-preact@<5.14.0-next.1\",\"gatsby-plugin-preload-fonts@<2.14.0-next.1\",\"gatsby-plugin-schema-snapshot@<2.14.0-next.1\",\"gatsby-plugin-styletron@<6.14.0-next.1\",\"gatsby-plugin-subfont@<3.14.0-next.1\",\"gatsby-plugin-utils@<1.14.0-next.1\",\"gatsby-recipes@<0.25.0-next.1\",\"gatsby-source-shopify@<5.6.0-next.1\",\"gatsby-source-wikipedia@<3.14.0-next.1\",\"gatsby-transformer-screenshot@<3.14.0-next.1\",\"gatsby-worker@<0.5.0-next.1\"].map(t=>[t,{dependencies:{\"@babel/runtime\":\"^7.14.8\"}}]),[\"gatsby-core-utils@<2.14.0-next.1\",{dependencies:{got:\"8.3.2\"}}],[\"gatsby-plugin-gatsby-cloud@<=3.1.0-next.0\",{dependencies:{\"gatsby-core-utils\":\"^2.13.0-next.0\"}}],[\"gatsby-plugin-gatsby-cloud@<=3.2.0-next.1\",{peerDependencies:{webpack:\"*\"}}],[\"babel-plugin-remove-graphql-queries@<=3.14.0-next.1\",{dependencies:{\"gatsby-core-utils\":\"^2.8.0-next.1\"}}],[\"gatsby-plugin-netlify@3.13.0-next.1\",{dependencies:{\"gatsby-core-utils\":\"^2.13.0-next.0\"}}],[\"clipanion-v3-codemod@<=0.2.0\",{peerDependencies:{jscodeshift:\"^0.11.0\"}}],[\"react-live@*\",{peerDependencies:{\"react-dom\":\"*\",react:\"*\"}}],[\"webpack@<4.44.1\",{peerDependenciesMeta:{\"webpack-cli\":xt,\"webpack-command\":xt}}],[\"webpack@<5.0.0-beta.23\",{peerDependenciesMeta:{\"webpack-cli\":xt}}],[\"webpack-dev-server@<3.10.2\",{peerDependenciesMeta:{\"webpack-cli\":xt}}],[\"@docusaurus/responsive-loader@<1.5.0\",{peerDependenciesMeta:{sharp:xt,jimp:xt}}],[\"eslint-module-utils@*\",{peerDependenciesMeta:{\"eslint-import-resolver-node\":xt,\"eslint-import-resolver-typescript\":xt,\"eslint-import-resolver-webpack\":xt,\"@typescript-eslint/parser\":xt}}],[\"eslint-plugin-import@*\",{peerDependenciesMeta:{\"@typescript-eslint/parser\":xt}}],[\"critters-webpack-plugin@<3.0.2\",{peerDependenciesMeta:{\"html-webpack-plugin\":xt}}],[\"terser@<=5.10.0\",{dependencies:{acorn:\"^8.5.0\"}}],[\"babel-preset-react-app@10.0.x <10.0.2\",{dependencies:{\"@babel/plugin-proposal-private-property-in-object\":\"^7.16.7\"}}],[\"eslint-config-react-app@*\",{peerDependenciesMeta:{typescript:xt}}],[\"@vue/eslint-config-typescript@<11.0.0\",{peerDependenciesMeta:{typescript:xt}}],[\"unplugin-vue2-script-setup@<0.9.1\",{peerDependencies:{\"@vue/composition-api\":\"^1.4.3\",\"@vue/runtime-dom\":\"^3.2.26\"}}],[\"@cypress/snapshot@*\",{dependencies:{debug:\"^3.2.7\"}}],[\"auto-relay@<=0.14.0\",{peerDependencies:{\"reflect-metadata\":\"^0.1.13\"}}],[\"vue-template-babel-compiler@<1.2.0\",{peerDependencies:{\"vue-template-compiler\":\"^2.6.0\"}}],[\"@parcel/transformer-image@<2.5.0\",{peerDependencies:{\"@parcel/core\":\"*\"}}],[\"@parcel/transformer-js@<2.5.0\",{peerDependencies:{\"@parcel/core\":\"*\"}}],[\"parcel@*\",{peerDependenciesMeta:{\"@parcel/core\":xt}}],[\"react-scripts@*\",{peerDependencies:{eslint:\"*\"}}],[\"focus-trap-react@^8.0.0\",{dependencies:{tabbable:\"^5.3.2\"}}],[\"react-rnd@<10.3.7\",{peerDependencies:{react:\">=16.3.0\",\"react-dom\":\">=16.3.0\"}}],[\"connect-mongo@<5.0.0\",{peerDependencies:{\"express-session\":\"^1.17.1\"}}],[\"vue-i18n@<9\",{peerDependencies:{vue:\"^2\"}}],[\"vue-router@<4\",{peerDependencies:{vue:\"^2\"}}],[\"unified@<10\",{dependencies:{\"@types/unist\":\"^2.0.0\"}}],[\"react-github-btn@<=1.3.0\",{peerDependencies:{react:\">=16.3.0\"}}],[\"react-dev-utils@*\",{peerDependencies:{typescript:\">=2.7\",webpack:\">=4\"},peerDependenciesMeta:{typescript:xt}}],[\"@asyncapi/react-component@<=1.0.0-next.39\",{peerDependencies:{react:\">=16.8.0\",\"react-dom\":\">=16.8.0\"}}],[\"xo@*\",{peerDependencies:{webpack:\">=1.11.0\"},peerDependenciesMeta:{webpack:xt}}],[\"babel-plugin-remove-graphql-queries@<=4.20.0-next.0\",{dependencies:{\"@babel/types\":\"^7.15.4\"}}],[\"gatsby-plugin-page-creator@<=4.20.0-next.1\",{dependencies:{\"fs-extra\":\"^10.1.0\"}}],[\"gatsby-plugin-utils@<=3.14.0-next.1\",{dependencies:{fastq:\"^1.13.0\"},peerDependencies:{graphql:\"^15.0.0\"}}],[\"gatsby-plugin-mdx@<3.1.0-next.1\",{dependencies:{mkdirp:\"^1.0.4\"}}],[\"gatsby-plugin-mdx@^2\",{peerDependencies:{gatsby:\"^3.0.0-next\"}}],[\"fdir@<=5.2.0\",{peerDependencies:{picomatch:\"2.x\"},peerDependenciesMeta:{picomatch:xt}}],[\"babel-plugin-transform-typescript-metadata@<=0.3.2\",{peerDependencies:{\"@babel/core\":\"^7\",\"@babel/traverse\":\"^7\"},peerDependenciesMeta:{\"@babel/traverse\":xt}}],[\"graphql-compose@>=9.0.10\",{peerDependencies:{graphql:\"^14.2.0 || ^15.0.0 || ^16.0.0\"}}],[\"vite-plugin-vuetify@<=1.0.2\",{peerDependencies:{vue:\"^3.0.0\"}}],[\"webpack-plugin-vuetify@<=2.0.1\",{peerDependencies:{vue:\"^3.2.6\"}}],[\"eslint-import-resolver-vite@<2.0.1\",{dependencies:{debug:\"^4.3.4\",resolve:\"^1.22.8\"}}]];var z8;function Lde(){return typeof z8>\"u\"&&(z8=ve(\"zlib\").brotliDecompressSync(Buffer.from(\"G7weAByFTVk3Vs7UfHhq4yykgEM7pbW7TI43SG2S5tvGrwHBAzdz+s/npQ6tgEvobvxisrPIadkXeUAJotBn5bDZ5kAhcRqsIHe3F75Walet5hNalwgFDtxb0BiDUjiUQkjG0yW2hto9HPgiCkm316d6bC0kST72YN7D7rfkhCE9x4J0XwB0yavalxpUu2t9xszHrmtwalOxT7VslsxWcB1qpqZwERUra4psWhTV8BgwWeizurec82Caf1ABL11YMfbf8FJ9JBceZOkgmvrQPbC9DUldX/yMbmX06UQluCEjSwUoyO+EZPIjofr+/oAZUck2enraRD+oWLlnlYnj8xB+gwSo9lmmks4fXv574qSqcWA6z21uYkzMu3EWj+K23RxeQlLqiE35/rC8GcS4CGkKHKKq+zAIQwD9iRDNfiAqueLLpicFFrNsAI4zeTD/eO9MHcnRa5m8UT+M2+V+AkFST4BlKneiAQRSdST8KEAIyFlULt6wa9EBd0Ds28VmpaxquJdVt+nwdEs5xUskI13OVtFyY0UrQIRAlCuvvWivvlSKQfTO+2Q8OyUR1W5RvetaPz4jD27hdtwHFFA1Ptx6Ee/t2cY2rg2G46M1pNDRf2pWhvpy8pqMnuI3++4OF3+7OFIWXGjh+o7Nr2jNvbiYcQdQS1h903/jVFgOpA0yJ78z+x759bFA0rq+6aY5qPB4FzS3oYoLupDUhD9nDz6F6H7hpnlMf18KNKDu4IKjTWwrAnY6MFQw1W6ymOALHlFyCZmQhldg1MQHaMVVQTVgDC60TfaBqG++Y8PEoFhN/PBTZT175KNP/BlHDYGOOBmnBdzqJKplZ/ljiVG0ZBzfqeBRrrUkn6rA54462SgiliKoYVnbeptMdXNfAuaupIEi0bApF10TlgHfmEJAPUVidRVFyDupSem5po5vErPqWKhKbUIp0LozpYsIKK57dM/HKr+nguF+7924IIWMICkQ8JUigs9D+W+c4LnNoRtPPKNRUiCYmP+Jfo2lfKCKw8qpraEeWU3uiNRO6zcyKQoXPR5htmzzLznke7b4YbXW3I1lIRzmgG02Udb58U+7TpwyN7XymCgH+wuPDthZVQvRZuEP+SnLtMicz9m5zASWOBiAcLmkuFlTKuHspSIhCBD0yUPKcxu81A+4YD78rA2vtwsUEday9WNyrShyrl60rWmA+SmbYZkQOwFJWArxRYYc5jGhA5ikxYw1rx3ei4NmeX/lKiwpZ9Ln1tV2Ae7sArvxuVLbJjqJRjW1vFXAyHpvLG+8MJ6T2Ubx5M2KDa2SN6vuIGxJ9WQM9Mk3Q7aCNiZONXllhqq24DmoLbQfW2rYWsOgHWjtOmIQMyMKdiHZDjoyIq5+U700nZ6odJAoYXPQBvFNiQ78d5jaXliBqLTJEqUCwi+LiH2mx92EmNKDsJL74Z613+3lf20pxkV1+erOrjj8pW00vsPaahKUM+05ssd5uwM7K482KWEf3TCwlg/o3e5ngto7qSMz7YteIgCsF1UOcsLk7F7MxWbvrPMY473ew0G+noVL8EPbkmEMftMSeL6HFub/zy+2JQ==\",\"base64\")).toString()),z8}var J8;function Mde(){return typeof J8>\"u\"&&(J8=ve(\"zlib\").brotliDecompressSync(Buffer.from(\"G8MSIIzURnVBnObTcvb3XE6v2S9Qgc2K801Oa5otNKEtK8BINZNcaQHy+9/vf/WXBimwutXC33P2DPc64pps5rz7NGGWaOKNSPL4Y2KRE8twut2lFOIN+OXPtRmPMRhMTILib2bEQx43az2I5d3YS8Roa5UZpF/ujHb3Djd3GDvYUfvFYSUQ39vb2cmifp/rgB4J/65JK3wRBTvMBoNBmn3mbXC63/gbBkW/2IRPri0O8bcsRBsmarF328pAln04nyJFkwUAvNu934supAqLtyerZZpJ8I8suJHhf/ocMV+scKwa8NOiDKIPXw6Ex/EEZD6TEGaW8N5zvNHYF10l6Lfooj7D5W2k3dgvQSbp2Wv8TGOayS978gxlOLVjTGXs66ozewbrjwElLtyrYNnWTfzzdEutg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FmmvBwNELgaS8z8dNZchx/Cl/xjddxhMcyqtzFyONb2Zdu90NkI8pAeufe7YlXrp53v8Dj/l8vWeVspRKBGXScBBPI/HinSTGmLDOGGOCIyH0JFdOZx0gWsacNlQLJMIrBhqRxXxHF/5pseWwejlAAvZ3klZSDSYY8mkToaWejXhgNomeGtx1DTLEUFMRkgF5yFB22WYdJnaWN14r1YJj81hGi45+jrADS5nYRhCiSlCJJ1nL8pYX+HDSMhdTEWyRcgHVp/IsUIZYMfT+YYncUQPgcxNGCHfZ88vDdrcUuaGIl6zhAsiaq7R5dfqrqXH/JcBhfjT8D0azayIyEz75Nxp6YkcyDxlJq3EXnJUpqDohJJOysL1t1uNiHESlvsxPb5cpbW0+ICZqJmUZus1BMW0F5IVBODLIo2zHHjA0=\",\"base64\")).toString()),J8}var X8;function Ode(){return typeof X8>\"u\"&&(X8=ve(\"zlib\").brotliDecompressSync(Buffer.from(\"m5N7PZNNGa6n2xAgQ91Ku8rrZrIpk710DjHQVpChzuz/qk4oImMpopscXUenLSUJ/l8bUD0ON66uHywQnCVqSDAysG3zwhbSlXzYF9KGzILCgz6HnrY4A5PNhUM3HjfeVvDwKyszGnrlmob+ClWri0TzsfzyUNV387DpSVI0dBtjdPLEyRpcoZ2B33fS0JEwMuzHAHpsHKjChSIRqlCTDMPipyn85j7z7ZjXH72SZsof9ji5gqG9Hgaa5gpIy2W27D+fV+duJbKYNTnNXprrdA1kL2pKGEs2SoxQdTfDkqpcS7XX19q0HTOkFSarcqW0FLQY2cEFNBY+PbDg3/9l89+ot5VkyCYc5AS6kNjSVemS6z9Ttd3L9EWawOWJklbW7NdtH+IDilMa0lU5hOZ5hB68nF7FN2csVNkJs78ESAhOrl2ryr4v+RD0tGjbRqskthNHRfT8cxFW+H4tVNlzIRBOBaor9MqoaZlyA9f/YD8rFiq3KGVHncAQpuphW52Sn7A5m6xSmqaB+QAn977FGu71Bd88WkHMfpamycSAQ/T/elN7txAkApwf9BM1CgS/bcJJs+IsdjRFSk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8ViZzDXuG/C9TudD8uhje7DT31ZHvFLVrF9eo6jEvvhDP+dniqsH8R6dcVPr3rXxwGftIygkvqwqLqqBXE4hc4e7fKQ4yoNnjt1WPPoW0Q6oV54f4N2fpJOtgzvxshKQhgdy1sDmoqr83oOc/fudMFKeCiuhj44jb8wOJ8rb+ge9coN9kXNziQ19s9whsj1saeTb/aKNXjC7Hpu5C1jBK2aYUJzg862sPzcxCE/oT1qX0IMsig8dcBTTFcDSzm0E172MGcsuuMLvlrfQ83ffjC5hXW53w5QtzRcYCYHEqfPvzg+LwZOn3H97c1ufKsTr/PHT6E/2RMG62yvmDDERnW3gerGlK0Q2nuffwjfSrJqs572Jy57f1Cqg2UFACBG7yQdL7B2rUpVcjDhRLd+HohSrBh9yUPl6HgoDADQ0VMc/o7J6f54IjCn57nixnInWXsfvV2K6VAGUFe5efN5fuLlnaO/MNCU4TIuiSEtAm6nOvOwFAdBdZdtl2BvTAxqleAI04KGEpzEF9D0OtGGxo0yHjo2BoyANWyiKw/Iu7E/tnTDUjd1pi0EDtYfCZxHDley+8pz3wAyU4gptfjPd+FzCiRpMV+q90ZL2i6RWTfcuM4aDndeiaey1fecKYqJrwqMfiOGb5H6wP5u7T2Gapel6tF727UrJAKApQtvMcUPzcKzUqx/EDC9J/1ooK1pY7FMU9/jNszzqnn/dWS3pwA=\",\"base64\")).toString()),X8}var Ude=new Map([[G.makeIdent(null,\"fsevents\").identHash,Lde],[G.makeIdent(null,\"resolve\").identHash,Mde],[G.makeIdent(null,\"typescript\").identHash,Ode]]),Rgt={hooks:{registerPackageExtensions:async(t,e)=>{for(let[r,o]of V8)e(G.parseDescriptor(r,!0),o)},getBuiltinPatch:async(t,e)=>{let r=\"compat/\";if(!e.startsWith(r))return;let o=G.parseIdent(e.slice(r.length)),a=Ude.get(o.identHash)?.();return typeof a<\"u\"?a:null},reduceDependency:async(t,e,r,o)=>typeof Ude.get(t.identHash)>\"u\"?t:G.makeDescriptor(t,G.makeRange({protocol:\"patch:\",source:G.stringifyDescriptor(t),selector:`optional!builtin<compat/${G.stringifyIdent(t)}>`,params:null}))}},Tgt=Rgt;var dH={};Vt(dH,{ConstraintsCheckCommand:()=>OE,ConstraintsQueryCommand:()=>LE,ConstraintsSourceCommand:()=>ME,default:()=>adt});Ge();Ge();l2();var FE=class{constructor(e){this.project=e}createEnvironment(){let e=new QE([\"cwd\",\"ident\"]),r=new QE([\"workspace\",\"type\",\"ident\"]),o=new QE([\"ident\"]),a={manifestUpdates:new Map,reportedErrors:new Map},n=new Map,u=new Map;for(let A of this.project.storedPackages.values()){let p=Array.from(A.peerDependencies.values(),h=>[G.stringifyIdent(h),h.range]);n.set(A.locatorHash,{workspace:null,ident:G.stringifyIdent(A),version:A.version,dependencies:new Map,peerDependencies:new Map(p.filter(([h])=>A.peerDependenciesMeta.get(h)?.optional!==!0)),optionalPeerDependencies:new Map(p.filter(([h])=>A.peerDependenciesMeta.get(h)?.optional===!0))})}for(let A of this.project.storedPackages.values()){let p=n.get(A.locatorHash);p.dependencies=new Map(Array.from(A.dependencies.values(),h=>{let E=this.project.storedResolutions.get(h.descriptorHash);if(typeof E>\"u\")throw new Error(\"Assertion failed: The resolution should have been registered\");let I=n.get(E);if(typeof I>\"u\")throw new Error(\"Assertion failed: The package should have been registered\");return[G.stringifyIdent(h),I]})),p.dependencies.delete(p.ident)}for(let A of this.project.workspaces){let p=G.stringifyIdent(A.anchoredLocator),h=A.manifest.exportTo({}),E=n.get(A.anchoredLocator.locatorHash);if(typeof E>\"u\")throw new Error(\"Assertion failed: The package should have been registered\");let I=(R,L,{caller:U=Xi.getCaller()}={})=>{let z=a2(R),te=He.getMapWithDefault(a.manifestUpdates,A.cwd),ae=He.getMapWithDefault(te,z),le=He.getSetWithDefault(ae,L);U!==null&&le.add(U)},v=R=>I(R,void 0,{caller:Xi.getCaller()}),x=R=>{He.getArrayWithDefault(a.reportedErrors,A.cwd).push(R)},C=e.insert({cwd:A.relativeCwd,ident:p,manifest:h,pkg:E,set:I,unset:v,error:x});u.set(A,C);for(let R of Ut.allDependencies)for(let L of A.manifest[R].values()){let U=G.stringifyIdent(L),z=()=>{I([R,U],void 0,{caller:Xi.getCaller()})},te=le=>{I([R,U],le,{caller:Xi.getCaller()})},ae=null;if(R!==\"peerDependencies\"&&(R!==\"dependencies\"||!A.manifest.devDependencies.has(L.identHash))){let le=A.anchoredPackage.dependencies.get(L.identHash);if(le){if(typeof le>\"u\")throw new Error(\"Assertion failed: The dependency should have been registered\");let ce=this.project.storedResolutions.get(le.descriptorHash);if(typeof ce>\"u\")throw new Error(\"Assertion failed: The resolution should have been registered\");let Ce=n.get(ce);if(typeof Ce>\"u\")throw new Error(\"Assertion failed: The package should have been registered\");ae=Ce}}r.insert({workspace:C,ident:U,range:L.range,type:R,resolution:ae,update:te,delete:z,error:x})}}for(let A of this.project.storedPackages.values()){let p=this.project.tryWorkspaceByLocator(A);if(!p)continue;let h=u.get(p);if(typeof h>\"u\")throw new Error(\"Assertion failed: The workspace should have been registered\");let E=n.get(A.locatorHash);if(typeof E>\"u\")throw new Error(\"Assertion failed: The package should have been registered\");E.workspace=h}return{workspaces:e,dependencies:r,packages:o,result:a}}async process(){let e=this.createEnvironment(),r={Yarn:{workspace:a=>e.workspaces.find(a)[0]??null,workspaces:a=>e.workspaces.find(a),dependency:a=>e.dependencies.find(a)[0]??null,dependencies:a=>e.dependencies.find(a),package:a=>e.packages.find(a)[0]??null,packages:a=>e.packages.find(a)}},o=await this.project.loadUserConfig();return o?.constraints?(await o.constraints(r),e.result):null}};Ge();Ge();qt();var LE=class extends ut{constructor(){super(...arguments);this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.query=ge.String()}static{this.paths=[[\"constraints\",\"query\"]]}static{this.usage=it.Usage({category:\"Constraints-related commands\",description:\"query the constraints fact database\",details:`\n      This command will output all matches to the given prolog query.\n    `,examples:[[\"List all dependencies throughout the workspace\",\"yarn constraints query 'workspace_has_dependency(_, DependencyName, _, _).'\"]]})}async execute(){let{Constraints:r}=await Promise.resolve().then(()=>(f2(),A2)),o=await Ke.find(this.context.cwd,this.context.plugins),{project:a}=await kt.find(o,this.context.cwd),n=await r.find(a),u=this.query;return u.endsWith(\".\")||(u=`${u}.`),(await Rt.start({configuration:o,json:this.json,stdout:this.context.stdout},async p=>{for await(let h of n.query(u)){let E=Array.from(Object.entries(h)),I=E.length,v=E.reduce((x,[C])=>Math.max(x,C.length),0);for(let x=0;x<I;x++){let[C,R]=E[x];p.reportInfo(null,`${sdt(x,I)}${C.padEnd(v,\" \")} = ${idt(R)}`)}p.reportJson(h)}})).exitCode()}};function idt(t){return typeof t!=\"string\"?`${t}`:t.match(/^[a-zA-Z][a-zA-Z0-9_]+$/)?t:`'${t}'`}function sdt(t,e){let r=t===0,o=t===e-1;return r&&o?\"\":r?\"\\u250C \":o?\"\\u2514 \":\"\\u2502 \"}Ge();qt();var ME=class extends ut{constructor(){super(...arguments);this.verbose=ge.Boolean(\"-v,--verbose\",!1,{description:\"Also print the fact database automatically compiled from the workspace manifests\"})}static{this.paths=[[\"constraints\",\"source\"]]}static{this.usage=it.Usage({category:\"Constraints-related commands\",description:\"print the source code for the constraints\",details:\"\\n      This command will print the Prolog source code used by the constraints engine. Adding the `-v,--verbose` flag will print the *full* source code, including the fact database automatically compiled from the workspace manifests.\\n    \",examples:[[\"Prints the source code\",\"yarn constraints source\"],[\"Print the source code and the fact database\",\"yarn constraints source -v\"]]})}async execute(){let{Constraints:r}=await Promise.resolve().then(()=>(f2(),A2)),o=await Ke.find(this.context.cwd,this.context.plugins),{project:a}=await kt.find(o,this.context.cwd),n=await r.find(a);this.context.stdout.write(this.verbose?n.fullSource:n.source)}};Ge();Ge();qt();l2();var OE=class extends ut{constructor(){super(...arguments);this.fix=ge.Boolean(\"--fix\",!1,{description:\"Attempt to automatically fix unambiguous issues, following a multi-pass process\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"})}static{this.paths=[[\"constraints\"]]}static{this.usage=it.Usage({category:\"Constraints-related commands\",description:\"check that the project constraints are met\",details:`\n      This command will run constraints on your project and emit errors for each one that is found but isn't met. If any error is emitted the process will exit with a non-zero exit code.\n\n      If the \\`--fix\\` flag is used, Yarn will attempt to automatically fix the issues the best it can, following a multi-pass process (with a maximum of 10 iterations). Some ambiguous patterns cannot be autofixed, in which case you'll have to manually specify the right resolution.\n\n      For more information as to how to write constraints, please consult our dedicated page on our website: https://yarnpkg.com/features/constraints.\n    `,examples:[[\"Check that all constraints are satisfied\",\"yarn constraints\"],[\"Autofix all unmet constraints\",\"yarn constraints --fix\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o}=await kt.find(r,this.context.cwd);await o.restoreInstallState();let a=await o.loadUserConfig(),n;if(a?.constraints)n=new FE(o);else{let{Constraints:h}=await Promise.resolve().then(()=>(f2(),A2));n=await h.find(o)}let u,A=!1,p=!1;for(let h=this.fix?10:1;h>0;--h){let E=await n.process();if(!E)break;let{changedWorkspaces:I,remainingErrors:v}=ik(o,E,{fix:this.fix}),x=[];for(let[C,R]of I){let L=C.manifest.indent;C.manifest=new Ut,C.manifest.indent=L,C.manifest.load(R),x.push(C.persistManifest())}if(await Promise.all(x),!(I.size>0&&h>1)){u=Wde(v,{configuration:r}),A=!1,p=!0;for(let[,C]of v)for(let R of C)R.fixable?A=!0:p=!1}}if(u.children.length===0)return 0;if(A){let h=p?`Those errors can all be fixed by running ${pe.pretty(r,\"yarn constraints --fix\",pe.Type.CODE)}`:`Errors prefixed by '\\u2699' can be fixed by running ${pe.pretty(r,\"yarn constraints --fix\",pe.Type.CODE)}`;await Rt.start({configuration:r,stdout:this.context.stdout,includeNames:!1,includeFooter:!1},async E=>{E.reportInfo(0,h),E.reportSeparator()})}return u.children=He.sortMap(u.children,h=>h.value[1]),fs.emitTree(u,{configuration:r,stdout:this.context.stdout,json:this.json,separators:1}),1}};l2();var odt={configuration:{enableConstraintsChecks:{description:\"If true, constraints will run during installs\",type:\"BOOLEAN\",default:!1},constraintsPath:{description:\"The path of the constraints file.\",type:\"ABSOLUTE_PATH\",default:\"./constraints.pro\"}},commands:[LE,ME,OE],hooks:{async validateProjectAfterInstall(t,{reportError:e}){if(!t.configuration.get(\"enableConstraintsChecks\"))return;let r=await t.loadUserConfig(),o;if(r?.constraints)o=new FE(t);else{let{Constraints:u}=await Promise.resolve().then(()=>(f2(),A2));o=await u.find(t)}let a=await o.process();if(!a)return;let{remainingErrors:n}=ik(t,a);if(n.size!==0)if(t.configuration.isCI)for(let[u,A]of n)for(let p of A)e(84,`${pe.pretty(t.configuration,u.anchoredLocator,pe.Type.IDENT)}: ${p.text}`);else e(84,`Constraint check failed; run ${pe.pretty(t.configuration,\"yarn constraints\",pe.Type.CODE)} for more details`)}}},adt=odt;var mH={};Vt(mH,{CreateCommand:()=>UE,DlxCommand:()=>_E,default:()=>cdt});Ge();qt();var UE=class extends ut{constructor(){super(...arguments);this.pkg=ge.String(\"-p,--package\",{description:\"The package to run the provided command from\"});this.quiet=ge.Boolean(\"-q,--quiet\",!1,{description:\"Only report critical errors instead of printing the full install logs\"});this.command=ge.String();this.args=ge.Proxy()}static{this.paths=[[\"create\"]]}async execute(){let r=[];this.pkg&&r.push(\"--package\",this.pkg),this.quiet&&r.push(\"--quiet\");let o=this.command.replace(/^(@[^@/]+)(@|$)/,\"$1/create$2\"),a=G.parseDescriptor(o),n=a.name.match(/^create(-|$)/)?a:a.scope?G.makeIdent(a.scope,`create-${a.name}`):G.makeIdent(null,`create-${a.name}`),u=G.stringifyIdent(n);return a.range!==\"unknown\"&&(u+=`@${a.range}`),this.cli.run([\"dlx\",...r,u,...this.args])}};Ge();Ge();Pt();qt();var _E=class extends ut{constructor(){super(...arguments);this.packages=ge.Array(\"-p,--package\",{description:\"The package(s) to install before running the command\"});this.quiet=ge.Boolean(\"-q,--quiet\",!1,{description:\"Only report critical errors instead of printing the full install logs\"});this.command=ge.String();this.args=ge.Proxy()}static{this.paths=[[\"dlx\"]]}static{this.usage=it.Usage({description:\"run a package in a temporary environment\",details:\"\\n      This command will install a package within a temporary environment, and run its binary script if it contains any. The binary will run within the current cwd.\\n\\n      By default Yarn will download the package named `command`, but this can be changed through the use of the `-p,--package` flag which will instruct Yarn to still run the same command but from a different package.\\n\\n      Using `yarn dlx` as a replacement of `yarn add` isn't recommended, as it makes your project non-deterministic (Yarn doesn't keep track of the packages installed through `dlx` - neither their name, nor their version).\\n    \",examples:[[\"Use create-react-app to create a new React app\",\"yarn dlx create-react-app ./my-app\"],[\"Install multiple packages for a single command\",`yarn dlx -p typescript -p ts-node ts-node --transpile-only -e \"console.log('hello!')\"`]]})}async execute(){return Ke.telemetry=null,await oe.mktempPromise(async r=>{let o=V.join(r,`dlx-${process.pid}`);await oe.mkdirPromise(o),await oe.writeFilePromise(V.join(o,\"package.json\"),`{}\n`),await oe.writeFilePromise(V.join(o,\"yarn.lock\"),\"\");let a=V.join(o,\".yarnrc.yml\"),n=await Ke.findProjectCwd(this.context.cwd),A={enableGlobalCache:!(await Ke.find(this.context.cwd,null,{strict:!1})).get(\"enableGlobalCache\"),enableTelemetry:!1,logFilters:[{code:Ku(68),level:pe.LogLevel.Discard}]},p=n!==null?V.join(n,\".yarnrc.yml\"):null;p!==null&&oe.existsSync(p)?(await oe.copyFilePromise(p,a),await Ke.updateConfiguration(o,L=>{let U=He.toMerged(L,A);return Array.isArray(L.plugins)&&(U.plugins=L.plugins.map(z=>{let te=typeof z==\"string\"?z:z.path,ae=ue.isAbsolute(te)?te:ue.resolve(ue.fromPortablePath(n),te);return typeof z==\"string\"?ae:{path:ae,spec:z.spec}})),U})):await oe.writeJsonPromise(a,A);let h=this.packages??[this.command],E=G.parseDescriptor(this.command).name,I=await this.cli.run([\"add\",\"--fixed\",\"--\",...h],{cwd:o,quiet:this.quiet});if(I!==0)return I;this.quiet||this.context.stdout.write(`\n`);let v=await Ke.find(o,this.context.plugins),{project:x,workspace:C}=await kt.find(v,o);if(C===null)throw new sr(x.cwd,o);await x.restoreInstallState();let R=await An.getWorkspaceAccessibleBinaries(C);return R.has(E)===!1&&R.size===1&&typeof this.packages>\"u\"&&(E=Array.from(R)[0][0]),await An.executeWorkspaceAccessibleBinary(C,E,this.args,{packageAccessibleBinaries:R,cwd:this.context.cwd,stdin:this.context.stdin,stdout:this.context.stdout,stderr:this.context.stderr})})}};var ldt={commands:[UE,_E]},cdt=ldt;var CH={};Vt(CH,{ExecFetcher:()=>h2,ExecResolver:()=>g2,default:()=>fdt,execUtils:()=>lk});Ge();Ge();Pt();var fA=\"exec:\";var lk={};Vt(lk,{loadGeneratorFile:()=>p2,makeLocator:()=>EH,makeSpec:()=>yme,parseSpec:()=>yH});Ge();Pt();function yH(t){let{params:e,selector:r}=G.parseRange(t),o=ue.toPortablePath(r);return{parentLocator:e&&typeof e.locator==\"string\"?G.parseLocator(e.locator):null,path:o}}function yme({parentLocator:t,path:e,generatorHash:r,protocol:o}){let a=t!==null?{locator:G.stringifyLocator(t)}:{},n=typeof r<\"u\"?{hash:r}:{};return G.makeRange({protocol:o,source:e,selector:e,params:{...n,...a}})}function EH(t,{parentLocator:e,path:r,generatorHash:o,protocol:a}){return G.makeLocator(t,yme({parentLocator:e,path:r,generatorHash:o,protocol:a}))}async function p2(t,e,r){let{parentLocator:o,path:a}=G.parseFileStyleRange(t,{protocol:e}),n=V.isAbsolute(a)?{packageFs:new gn(It.root),prefixPath:It.dot,localPath:It.root}:await r.fetcher.fetch(o,r),u=n.localPath?{packageFs:new gn(It.root),prefixPath:V.relative(It.root,n.localPath)}:n;n!==u&&n.releaseFs&&n.releaseFs();let A=u.packageFs,p=V.join(u.prefixPath,a);return await A.readFilePromise(p,\"utf8\")}var h2=class{supports(e,r){return!!e.reference.startsWith(fA)}getLocalPath(e,r){let{parentLocator:o,path:a}=G.parseFileStyleRange(e.reference,{protocol:fA});if(V.isAbsolute(a))return a;let n=r.fetcher.getLocalPath(o,r);return n===null?null:V.resolve(n,a)}async fetch(e,r){let o=r.checksums.get(e.locatorHash)||null,[a,n,u]=await r.cache.fetchPackageFromCache(e,o,{onHit:()=>r.report.reportCacheHit(e),onMiss:()=>r.report.reportCacheMiss(e),loader:()=>this.fetchFromDisk(e,r),...r.cacheOptions});return{packageFs:a,releaseFs:n,prefixPath:G.getIdentVendorPath(e),localPath:this.getLocalPath(e,r),checksum:u}}async fetchFromDisk(e,r){let o=await p2(e.reference,fA,r);return oe.mktempPromise(async a=>{let n=V.join(a,\"generator.js\");return await oe.writeFilePromise(n,o),oe.mktempPromise(async u=>{if(await this.generatePackage(u,e,n,r),!oe.existsSync(V.join(u,\"build\")))throw new Error(\"The script should have generated a build directory\");return await $i.makeArchiveFromDirectory(V.join(u,\"build\"),{prefixPath:G.getIdentVendorPath(e),compressionLevel:r.project.configuration.get(\"compressionLevel\")})})})}async generatePackage(e,r,o,a){return await oe.mktempPromise(async n=>{let u=await An.makeScriptEnv({project:a.project,binFolder:n}),A=V.join(e,\"runtime.js\");return await oe.mktempPromise(async p=>{let h=V.join(p,\"buildfile.log\"),E=V.join(e,\"generator\"),I=V.join(e,\"build\");await oe.mkdirPromise(E),await oe.mkdirPromise(I);let v={tempDir:ue.fromPortablePath(E),buildDir:ue.fromPortablePath(I),locator:G.stringifyLocator(r)};await oe.writeFilePromise(A,`\n          // Expose 'Module' as a global variable\n          Object.defineProperty(global, 'Module', {\n            get: () => require('module'),\n            configurable: true,\n            enumerable: false,\n          });\n\n          // Expose non-hidden built-in modules as global variables\n          for (const name of Module.builtinModules.filter((name) => name !== 'module' && !name.startsWith('_'))) {\n            Object.defineProperty(global, name, {\n              get: () => require(name),\n              configurable: true,\n              enumerable: false,\n            });\n          }\n\n          // Expose the 'execEnv' global variable\n          Object.defineProperty(global, 'execEnv', {\n            value: {\n              ...${JSON.stringify(v)},\n            },\n            enumerable: true,\n          });\n        `);let x=u.NODE_OPTIONS||\"\",C=/\\s*--require\\s+\\S*\\.pnp\\.c?js\\s*/g;x=x.replace(C,\" \").trim(),u.NODE_OPTIONS=x;let{stdout:R,stderr:L}=a.project.configuration.getSubprocessStreams(h,{header:`# This file contains the result of Yarn generating a package (${G.stringifyLocator(r)})\n`,prefix:G.prettyLocator(a.project.configuration,r),report:a.report}),{code:U}=await Ur.pipevp(process.execPath,[\"--require\",ue.fromPortablePath(A),ue.fromPortablePath(o),G.stringifyIdent(r)],{cwd:e,env:u,stdin:null,stdout:R,stderr:L});if(U!==0)throw oe.detachTemp(p),new Error(`Package generation failed (exit code ${U}, logs can be found here: ${pe.pretty(a.project.configuration,h,pe.Type.PATH)})`)})})}};Ge();Ge();var udt=2,g2=class{supportsDescriptor(e,r){return!!e.range.startsWith(fA)}supportsLocator(e,r){return!!e.reference.startsWith(fA)}shouldPersistResolution(e,r){return!1}bindDescriptor(e,r,o){return G.bindDescriptor(e,{locator:G.stringifyLocator(r)})}getResolutionDependencies(e,r){return{}}async getCandidates(e,r,o){if(!o.fetchOptions)throw new Error(\"Assertion failed: This resolver cannot be used unless a fetcher is configured\");let{path:a,parentLocator:n}=yH(e.range);if(n===null)throw new Error(\"Assertion failed: The descriptor should have been bound\");let u=await p2(G.makeRange({protocol:fA,source:a,selector:a,params:{locator:G.stringifyLocator(n)}}),fA,o.fetchOptions),A=wn.makeHash(`${udt}`,u).slice(0,6);return[EH(e,{parentLocator:n,path:a,generatorHash:A,protocol:fA})]}async getSatisfying(e,r,o,a){let[n]=await this.getCandidates(e,r,a);return{locators:o.filter(u=>u.locatorHash===n.locatorHash),sorted:!1}}async resolve(e,r){if(!r.fetchOptions)throw new Error(\"Assertion failed: This resolver cannot be used unless a fetcher is configured\");let o=await r.fetchOptions.fetcher.fetch(e,r.fetchOptions),a=await He.releaseAfterUseAsync(async()=>await Ut.find(o.prefixPath,{baseFs:o.packageFs}),o.releaseFs);return{...e,version:a.version||\"0.0.0\",languageName:a.languageName||r.project.configuration.get(\"defaultLanguageName\"),linkType:\"HARD\",conditions:a.getConditions(),dependencies:r.project.configuration.normalizeDependencyMap(a.dependencies),peerDependencies:a.peerDependencies,dependenciesMeta:a.dependenciesMeta,peerDependenciesMeta:a.peerDependenciesMeta,bin:a.bin}}};var Adt={fetchers:[h2],resolvers:[g2]},fdt=Adt;var IH={};Vt(IH,{FileFetcher:()=>E2,FileResolver:()=>C2,TarballFileFetcher:()=>w2,TarballFileResolver:()=>I2,default:()=>gdt,fileUtils:()=>Yg});Ge();Pt();var HE=/^(?:[a-zA-Z]:[\\\\/]|\\.{0,2}\\/)/,d2=/^[^?]*\\.(?:tar\\.gz|tgz)(?:::.*)?$/,Ui=\"file:\";var Yg={};Vt(Yg,{fetchArchiveFromLocator:()=>y2,makeArchiveFromLocator:()=>ck,makeBufferFromLocator:()=>wH,makeLocator:()=>qE,makeSpec:()=>Eme,parseSpec:()=>m2});Ge();Pt();function m2(t){let{params:e,selector:r}=G.parseRange(t),o=ue.toPortablePath(r);return{parentLocator:e&&typeof e.locator==\"string\"?G.parseLocator(e.locator):null,path:o}}function Eme({parentLocator:t,path:e,hash:r,protocol:o}){let a=t!==null?{locator:G.stringifyLocator(t)}:{},n=typeof r<\"u\"?{hash:r}:{};return G.makeRange({protocol:o,source:e,selector:e,params:{...n,...a}})}function qE(t,{parentLocator:e,path:r,hash:o,protocol:a}){return G.makeLocator(t,Eme({parentLocator:e,path:r,hash:o,protocol:a}))}async function y2(t,e){let{parentLocator:r,path:o}=G.parseFileStyleRange(t.reference,{protocol:Ui}),a=V.isAbsolute(o)?{packageFs:new gn(It.root),prefixPath:It.dot,localPath:It.root}:await e.fetcher.fetch(r,e),n=a.localPath?{packageFs:new gn(It.root),prefixPath:V.relative(It.root,a.localPath)}:a;a!==n&&a.releaseFs&&a.releaseFs();let u=n.packageFs,A=V.join(n.prefixPath,o);return await He.releaseAfterUseAsync(async()=>await u.readFilePromise(A),n.releaseFs)}async function ck(t,{protocol:e,fetchOptions:r,inMemory:o=!1}){let{parentLocator:a,path:n}=G.parseFileStyleRange(t.reference,{protocol:e}),u=V.isAbsolute(n)?{packageFs:new gn(It.root),prefixPath:It.dot,localPath:It.root}:await r.fetcher.fetch(a,r),A=u.localPath?{packageFs:new gn(It.root),prefixPath:V.relative(It.root,u.localPath)}:u;u!==A&&u.releaseFs&&u.releaseFs();let p=A.packageFs,h=V.join(A.prefixPath,n);return await He.releaseAfterUseAsync(async()=>await $i.makeArchiveFromDirectory(h,{baseFs:p,prefixPath:G.getIdentVendorPath(t),compressionLevel:r.project.configuration.get(\"compressionLevel\"),inMemory:o}),A.releaseFs)}async function wH(t,{protocol:e,fetchOptions:r}){return(await ck(t,{protocol:e,fetchOptions:r,inMemory:!0})).getBufferAndClose()}var E2=class{supports(e,r){return!!e.reference.startsWith(Ui)}getLocalPath(e,r){let{parentLocator:o,path:a}=G.parseFileStyleRange(e.reference,{protocol:Ui});if(V.isAbsolute(a))return a;let n=r.fetcher.getLocalPath(o,r);return n===null?null:V.resolve(n,a)}async fetch(e,r){let o=r.checksums.get(e.locatorHash)||null,[a,n,u]=await r.cache.fetchPackageFromCache(e,o,{onHit:()=>r.report.reportCacheHit(e),onMiss:()=>r.report.reportCacheMiss(e,`${G.prettyLocator(r.project.configuration,e)} can't be found in the cache and will be fetched from the disk`),loader:()=>this.fetchFromDisk(e,r),...r.cacheOptions});return{packageFs:a,releaseFs:n,prefixPath:G.getIdentVendorPath(e),localPath:this.getLocalPath(e,r),checksum:u}}async fetchFromDisk(e,r){return ck(e,{protocol:Ui,fetchOptions:r})}};Ge();Ge();var pdt=2,C2=class{supportsDescriptor(e,r){return e.range.match(HE)?!0:!!e.range.startsWith(Ui)}supportsLocator(e,r){return!!e.reference.startsWith(Ui)}shouldPersistResolution(e,r){return!1}bindDescriptor(e,r,o){return HE.test(e.range)&&(e=G.makeDescriptor(e,`${Ui}${e.range}`)),G.bindDescriptor(e,{locator:G.stringifyLocator(r)})}getResolutionDependencies(e,r){return{}}async getCandidates(e,r,o){if(!o.fetchOptions)throw new Error(\"Assertion failed: This resolver cannot be used unless a fetcher is configured\");let{path:a,parentLocator:n}=m2(e.range);if(n===null)throw new Error(\"Assertion failed: The descriptor should have been bound\");let u=await wH(G.makeLocator(e,G.makeRange({protocol:Ui,source:a,selector:a,params:{locator:G.stringifyLocator(n)}})),{protocol:Ui,fetchOptions:o.fetchOptions}),A=wn.makeHash(`${pdt}`,u).slice(0,6);return[qE(e,{parentLocator:n,path:a,hash:A,protocol:Ui})]}async getSatisfying(e,r,o,a){let[n]=await this.getCandidates(e,r,a);return{locators:o.filter(u=>u.locatorHash===n.locatorHash),sorted:!1}}async resolve(e,r){if(!r.fetchOptions)throw new Error(\"Assertion failed: This resolver cannot be used unless a fetcher is configured\");let o=await r.fetchOptions.fetcher.fetch(e,r.fetchOptions),a=await He.releaseAfterUseAsync(async()=>await Ut.find(o.prefixPath,{baseFs:o.packageFs}),o.releaseFs);return{...e,version:a.version||\"0.0.0\",languageName:a.languageName||r.project.configuration.get(\"defaultLanguageName\"),linkType:\"HARD\",conditions:a.getConditions(),dependencies:r.project.configuration.normalizeDependencyMap(a.dependencies),peerDependencies:a.peerDependencies,dependenciesMeta:a.dependenciesMeta,peerDependenciesMeta:a.peerDependenciesMeta,bin:a.bin}}};Ge();var w2=class{supports(e,r){return d2.test(e.reference)?!!e.reference.startsWith(Ui):!1}getLocalPath(e,r){return null}async fetch(e,r){let o=r.checksums.get(e.locatorHash)||null,[a,n,u]=await r.cache.fetchPackageFromCache(e,o,{onHit:()=>r.report.reportCacheHit(e),onMiss:()=>r.report.reportCacheMiss(e,`${G.prettyLocator(r.project.configuration,e)} can't be found in the cache and will be fetched from the disk`),loader:()=>this.fetchFromDisk(e,r),...r.cacheOptions});return{packageFs:a,releaseFs:n,prefixPath:G.getIdentVendorPath(e),checksum:u}}async fetchFromDisk(e,r){let o=await y2(e,r);return await $i.convertToZip(o,{configuration:r.project.configuration,prefixPath:G.getIdentVendorPath(e),stripComponents:1})}};Ge();Ge();Ge();var I2=class{supportsDescriptor(e,r){return d2.test(e.range)?!!(e.range.startsWith(Ui)||HE.test(e.range)):!1}supportsLocator(e,r){return d2.test(e.reference)?!!e.reference.startsWith(Ui):!1}shouldPersistResolution(e,r){return!1}bindDescriptor(e,r,o){return HE.test(e.range)&&(e=G.makeDescriptor(e,`${Ui}${e.range}`)),G.bindDescriptor(e,{locator:G.stringifyLocator(r)})}getResolutionDependencies(e,r){return{}}async getCandidates(e,r,o){if(!o.fetchOptions)throw new Error(\"Assertion failed: This resolver cannot be used unless a fetcher is configured\");let{path:a,parentLocator:n}=m2(e.range);if(n===null)throw new Error(\"Assertion failed: The descriptor should have been bound\");let u=qE(e,{parentLocator:n,path:a,hash:\"\",protocol:Ui}),A=await y2(u,o.fetchOptions),p=wn.makeHash(A).slice(0,6);return[qE(e,{parentLocator:n,path:a,hash:p,protocol:Ui})]}async getSatisfying(e,r,o,a){let[n]=await this.getCandidates(e,r,a);return{locators:o.filter(u=>u.locatorHash===n.locatorHash),sorted:!1}}async resolve(e,r){if(!r.fetchOptions)throw new Error(\"Assertion failed: This resolver cannot be used unless a fetcher is configured\");let o=await r.fetchOptions.fetcher.fetch(e,r.fetchOptions),a=await He.releaseAfterUseAsync(async()=>await Ut.find(o.prefixPath,{baseFs:o.packageFs}),o.releaseFs);return{...e,version:a.version||\"0.0.0\",languageName:a.languageName||r.project.configuration.get(\"defaultLanguageName\"),linkType:\"HARD\",conditions:a.getConditions(),dependencies:r.project.configuration.normalizeDependencyMap(a.dependencies),peerDependencies:a.peerDependencies,dependenciesMeta:a.dependenciesMeta,peerDependenciesMeta:a.peerDependenciesMeta,bin:a.bin}}};var hdt={fetchers:[w2,E2],resolvers:[I2,C2]},gdt=hdt;var DH={};Vt(DH,{GithubFetcher:()=>B2,default:()=>mdt,githubUtils:()=>uk});Ge();Pt();var uk={};Vt(uk,{invalidGithubUrlMessage:()=>Ime,isGithubUrl:()=>BH,parseGithubUrl:()=>vH});var Cme=Ze(ve(\"querystring\")),wme=[/^https?:\\/\\/(?:([^/]+?)@)?github.com\\/([^/#]+)\\/([^/#]+)\\/tarball\\/([^/#]+)(?:#(.*))?$/,/^https?:\\/\\/(?:([^/]+?)@)?github.com\\/([^/#]+)\\/([^/#]+?)(?:\\.git)?(?:#(.*))?$/];function BH(t){return t?wme.some(e=>!!t.match(e)):!1}function vH(t){let e;for(let A of wme)if(e=t.match(A),e)break;if(!e)throw new Error(Ime(t));let[,r,o,a,n=\"master\"]=e,{commit:u}=Cme.default.parse(n);return n=u||n.replace(/[^:]*:/,\"\"),{auth:r,username:o,reponame:a,treeish:n}}function Ime(t){return`Input cannot be parsed as a valid GitHub URL ('${t}').`}var B2=class{supports(e,r){return!!BH(e.reference)}getLocalPath(e,r){return null}async fetch(e,r){let o=r.checksums.get(e.locatorHash)||null,[a,n,u]=await r.cache.fetchPackageFromCache(e,o,{onHit:()=>r.report.reportCacheHit(e),onMiss:()=>r.report.reportCacheMiss(e,`${G.prettyLocator(r.project.configuration,e)} can't be found in the cache and will be fetched from GitHub`),loader:()=>this.fetchFromNetwork(e,r),...r.cacheOptions});return{packageFs:a,releaseFs:n,prefixPath:G.getIdentVendorPath(e),checksum:u}}async fetchFromNetwork(e,r){let o=await sn.get(this.getLocatorUrl(e,r),{configuration:r.project.configuration});return await oe.mktempPromise(async a=>{let n=new gn(a);await $i.extractArchiveTo(o,n,{stripComponents:1});let u=ia.splitRepoUrl(e.reference),A=V.join(a,\"package.tgz\");await An.prepareExternalProject(a,A,{configuration:r.project.configuration,report:r.report,workspace:u.extra.workspace,locator:e});let p=await oe.readFilePromise(A);return await $i.convertToZip(p,{configuration:r.project.configuration,prefixPath:G.getIdentVendorPath(e),stripComponents:1})})}getLocatorUrl(e,r){let{auth:o,username:a,reponame:n,treeish:u}=vH(e.reference);return`https://${o?`${o}@`:\"\"}github.com/${a}/${n}/archive/${u}.tar.gz`}};var ddt={hooks:{async fetchHostedRepository(t,e,r){if(t!==null)return t;let o=new B2;if(!o.supports(e,r))return null;try{return await o.fetch(e,r)}catch{return null}}}},mdt=ddt;var PH={};Vt(PH,{TarballHttpFetcher:()=>D2,TarballHttpResolver:()=>P2,default:()=>Edt});Ge();function v2(t){let e;try{e=new URL(t)}catch{return!1}return!(e.protocol!==\"http:\"&&e.protocol!==\"https:\"||!e.pathname.match(/(\\.tar\\.gz|\\.tgz|\\/[^.]+)$/))}var D2=class{supports(e,r){return v2(e.reference)}getLocalPath(e,r){return null}async fetch(e,r){let o=r.checksums.get(e.locatorHash)||null,[a,n,u]=await r.cache.fetchPackageFromCache(e,o,{onHit:()=>r.report.reportCacheHit(e),onMiss:()=>r.report.reportCacheMiss(e,`${G.prettyLocator(r.project.configuration,e)} can't be found in the cache and will be fetched from the remote server`),loader:()=>this.fetchFromNetwork(e,r),...r.cacheOptions});return{packageFs:a,releaseFs:n,prefixPath:G.getIdentVendorPath(e),checksum:u}}async fetchFromNetwork(e,r){let o=await sn.get(e.reference,{configuration:r.project.configuration});return await $i.convertToZip(o,{configuration:r.project.configuration,prefixPath:G.getIdentVendorPath(e),stripComponents:1})}};Ge();Ge();var P2=class{supportsDescriptor(e,r){return v2(e.range)}supportsLocator(e,r){return v2(e.reference)}shouldPersistResolution(e,r){return!0}bindDescriptor(e,r,o){return e}getResolutionDependencies(e,r){return{}}async getCandidates(e,r,o){return[G.convertDescriptorToLocator(e)]}async getSatisfying(e,r,o,a){let[n]=await this.getCandidates(e,r,a);return{locators:o.filter(u=>u.locatorHash===n.locatorHash),sorted:!1}}async resolve(e,r){if(!r.fetchOptions)throw new Error(\"Assertion failed: This resolver cannot be used unless a fetcher is configured\");let o=await r.fetchOptions.fetcher.fetch(e,r.fetchOptions),a=await He.releaseAfterUseAsync(async()=>await Ut.find(o.prefixPath,{baseFs:o.packageFs}),o.releaseFs);return{...e,version:a.version||\"0.0.0\",languageName:a.languageName||r.project.configuration.get(\"defaultLanguageName\"),linkType:\"HARD\",conditions:a.getConditions(),dependencies:r.project.configuration.normalizeDependencyMap(a.dependencies),peerDependencies:a.peerDependencies,dependenciesMeta:a.dependenciesMeta,peerDependenciesMeta:a.peerDependenciesMeta,bin:a.bin}}};var ydt={fetchers:[D2],resolvers:[P2]},Edt=ydt;var bH={};Vt(bH,{InitCommand:()=>jE,default:()=>wdt});Ge();Ge();Pt();qt();var jE=class extends ut{constructor(){super(...arguments);this.private=ge.Boolean(\"-p,--private\",!1,{description:\"Initialize a private package\"});this.workspace=ge.Boolean(\"-w,--workspace\",!1,{description:\"Initialize a workspace root with a `packages/` directory\"});this.install=ge.String(\"-i,--install\",!1,{tolerateBoolean:!0,description:\"Initialize a package with a specific bundle that will be locked in the project\"});this.name=ge.String(\"-n,--name\",{description:\"Initialize a package with the given name\"});this.usev2=ge.Boolean(\"-2\",!1,{hidden:!0});this.yes=ge.Boolean(\"-y,--yes\",{hidden:!0})}static{this.paths=[[\"init\"]]}static{this.usage=it.Usage({description:\"create a new package\",details:\"\\n      This command will setup a new package in your local directory.\\n\\n      If the `-p,--private` or `-w,--workspace` options are set, the package will be private by default.\\n\\n      If the `-w,--workspace` option is set, the package will be configured to accept a set of workspaces in the `packages/` directory.\\n\\n      If the `-i,--install` option is given a value, Yarn will first download it using `yarn set version` and only then forward the init call to the newly downloaded bundle. Without arguments, the downloaded bundle will be `latest`.\\n\\n      The initial settings of the manifest can be changed by using the `initScope` and `initFields` configuration values. Additionally, Yarn will generate an EditorConfig file whose rules can be altered via `initEditorConfig`, and will initialize a Git repository in the current directory.\\n    \",examples:[[\"Create a new package in the local directory\",\"yarn init\"],[\"Create a new private package in the local directory\",\"yarn init -p\"],[\"Create a new package and store the Yarn release inside\",\"yarn init -i=latest\"],[\"Create a new private package and defines it as a workspace root\",\"yarn init -w\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),o=typeof this.install==\"string\"?this.install:this.usev2||this.install===!0?\"latest\":null;return o!==null?await this.executeProxy(r,o):await this.executeRegular(r)}async executeProxy(r,o){if(r.projectCwd!==null&&r.projectCwd!==this.context.cwd)throw new st(\"Cannot use the --install flag from within a project subdirectory\");oe.existsSync(this.context.cwd)||await oe.mkdirPromise(this.context.cwd,{recursive:!0});let a=V.join(this.context.cwd,dr.lockfile);oe.existsSync(a)||await oe.writeFilePromise(a,\"\");let n=await this.cli.run([\"set\",\"version\",o],{quiet:!0});if(n!==0)return n;let u=[];return this.private&&u.push(\"-p\"),this.workspace&&u.push(\"-w\"),this.name&&u.push(`-n=${this.name}`),this.yes&&u.push(\"-y\"),await oe.mktempPromise(async A=>{let{code:p}=await Ur.pipevp(\"yarn\",[\"init\",...u],{cwd:this.context.cwd,stdin:this.context.stdin,stdout:this.context.stdout,stderr:this.context.stderr,env:await An.makeScriptEnv({binFolder:A})});return p})}async executeRegular(r){let o=null;try{o=(await kt.find(r,this.context.cwd)).project}catch{o=null}oe.existsSync(this.context.cwd)||await oe.mkdirPromise(this.context.cwd,{recursive:!0});let a=await Ut.tryFind(this.context.cwd),n=a??new Ut,u=Object.fromEntries(r.get(\"initFields\").entries());n.load(u),n.name=n.name??G.makeIdent(r.get(\"initScope\"),this.name??V.basename(this.context.cwd)),n.packageManager=nn&&He.isTaggedYarnVersion(nn)?`yarn@${nn}`:null,(!a&&this.workspace||this.private)&&(n.private=!0),this.workspace&&n.workspaceDefinitions.length===0&&(await oe.mkdirPromise(V.join(this.context.cwd,\"packages\"),{recursive:!0}),n.workspaceDefinitions=[{pattern:\"packages/*\"}]);let A={};n.exportTo(A);let p=V.join(this.context.cwd,Ut.fileName);await oe.changeFilePromise(p,`${JSON.stringify(A,null,2)}\n`,{automaticNewlines:!0});let h=[p],E=V.join(this.context.cwd,\"README.md\");if(oe.existsSync(E)||(await oe.writeFilePromise(E,`# ${G.stringifyIdent(n.name)}\n`),h.push(E)),!o||o.cwd===this.context.cwd){let I=V.join(this.context.cwd,dr.lockfile);oe.existsSync(I)||(await oe.writeFilePromise(I,\"\"),h.push(I));let x=[\".yarn/*\",\"!.yarn/patches\",\"!.yarn/plugins\",\"!.yarn/releases\",\"!.yarn/sdks\",\"!.yarn/versions\",\"\",\"# Swap the comments on the following lines if you wish to use zero-installs\",\"# In that case, don't forget to run `yarn config set enableGlobalCache false`!\",\"# Documentation here: https://yarnpkg.com/features/caching#zero-installs\",\"\",\"#!.yarn/cache\",\".pnp.*\"].map(le=>`${le}\n`).join(\"\"),C=V.join(this.context.cwd,\".gitignore\");oe.existsSync(C)||(await oe.writeFilePromise(C,x),h.push(C));let L=[\"/.yarn/**            linguist-vendored\",\"/.yarn/releases/*    binary\",\"/.yarn/plugins/**/*  binary\",\"/.pnp.*              binary linguist-generated\"].map(le=>`${le}\n`).join(\"\"),U=V.join(this.context.cwd,\".gitattributes\");oe.existsSync(U)||(await oe.writeFilePromise(U,L),h.push(U));let z={\"*\":{endOfLine:\"lf\",insertFinalNewline:!0},\"*.{js,json,yml}\":{charset:\"utf-8\",indentStyle:\"space\",indentSize:2}};He.mergeIntoTarget(z,r.get(\"initEditorConfig\"));let te=`root = true\n`;for(let[le,ce]of Object.entries(z)){te+=`\n[${le}]\n`;for(let[Ce,de]of Object.entries(ce)){let Be=Ce.replace(/[A-Z]/g,Ee=>`_${Ee.toLowerCase()}`);te+=`${Be} = ${de}\n`}}let ae=V.join(this.context.cwd,\".editorconfig\");oe.existsSync(ae)||(await oe.writeFilePromise(ae,te),h.push(ae)),await this.cli.run([\"install\"],{quiet:!0}),oe.existsSync(V.join(this.context.cwd,\".git\"))||(await Ur.execvp(\"git\",[\"init\"],{cwd:this.context.cwd}),await Ur.execvp(\"git\",[\"add\",\"--\",...h],{cwd:this.context.cwd}),await Ur.execvp(\"git\",[\"commit\",\"--allow-empty\",\"-m\",\"First commit\"],{cwd:this.context.cwd}))}}};var Cdt={configuration:{initScope:{description:\"Scope used when creating packages via the init command\",type:\"STRING\",default:null},initFields:{description:\"Additional fields to set when creating packages via the init command\",type:\"MAP\",valueDefinition:{description:\"\",type:\"ANY\"}},initEditorConfig:{description:\"Extra rules to define in the generator editorconfig\",type:\"MAP\",valueDefinition:{description:\"\",type:\"ANY\"}}},commands:[jE]},wdt=Cdt;var kq={};Vt(kq,{SearchCommand:()=>oC,UpgradeInteractiveCommand:()=>aC,default:()=>cIt});Ge();var vme=Ze(ve(\"os\"));function GE({stdout:t}){if(vme.default.endianness()===\"BE\")throw new Error(\"Interactive commands cannot be used on big-endian systems because ink depends on yoga-layout-prebuilt which only supports little-endian architectures\");if(!t.isTTY)throw new Error(\"Interactive commands can only be used inside a TTY environment\")}qt();var Lye=Ze(YH()),WH={appId:\"OFCNCOG2CU\",apiKey:\"6fe4476ee5a1832882e326b506d14126\",indexName:\"npm-search\"},yyt=(0,Lye.default)(WH.appId,WH.apiKey).initIndex(WH.indexName),KH=async(t,e=0)=>await yyt.search(t,{analyticsTags:[\"yarn-plugin-interactive-tools\"],attributesToRetrieve:[\"name\",\"version\",\"owner\",\"repository\",\"humanDownloadsLast30Days\"],page:e,hitsPerPage:10});var vB=[\"regular\",\"dev\",\"peer\"],oC=class extends ut{static{this.paths=[[\"search\"]]}static{this.usage=it.Usage({category:\"Interactive commands\",description:\"open the search interface\",details:`\n    This command opens a fullscreen terminal interface where you can search for and install packages from the npm registry.\n    `,examples:[[\"Open the search window\",\"yarn search\"]]})}async execute(){GE(this.context);let{Gem:e}=await Promise.resolve().then(()=>(Zk(),Eq)),{ScrollableItems:r}=await Promise.resolve().then(()=>(rQ(),tQ)),{useKeypress:o}=await Promise.resolve().then(()=>(wB(),Xwe)),{useMinistore:a}=await Promise.resolve().then(()=>(Dq(),vq)),{renderForm:n}=await Promise.resolve().then(()=>(oQ(),sQ)),{default:u}=await Promise.resolve().then(()=>Ze(aIe())),{Box:A,Text:p}=await Promise.resolve().then(()=>Ze(ic())),{default:h,useEffect:E,useState:I}=await Promise.resolve().then(()=>Ze(an())),v=await Ke.find(this.context.cwd,this.context.plugins),x=()=>h.createElement(A,{flexDirection:\"row\"},h.createElement(A,{flexDirection:\"column\",width:48},h.createElement(A,null,h.createElement(p,null,\"Press \",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<up>\"),\"/\",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<down>\"),\" to move between packages.\")),h.createElement(A,null,h.createElement(p,null,\"Press \",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<space>\"),\" to select a package.\")),h.createElement(A,null,h.createElement(p,null,\"Press \",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<space>\"),\" again to change the target.\"))),h.createElement(A,{flexDirection:\"column\"},h.createElement(A,{marginLeft:1},h.createElement(p,null,\"Press \",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<enter>\"),\" to install the selected packages.\")),h.createElement(A,{marginLeft:1},h.createElement(p,null,\"Press \",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<ctrl+c>\"),\" to abort.\")))),C=()=>h.createElement(h.Fragment,null,h.createElement(A,{width:15},h.createElement(p,{bold:!0,underline:!0,color:\"gray\"},\"Owner\")),h.createElement(A,{width:11},h.createElement(p,{bold:!0,underline:!0,color:\"gray\"},\"Version\")),h.createElement(A,{width:10},h.createElement(p,{bold:!0,underline:!0,color:\"gray\"},\"Downloads\"))),R=()=>h.createElement(A,{width:17},h.createElement(p,{bold:!0,underline:!0,color:\"gray\"},\"Target\")),L=({hit:de,active:Be})=>{let[Ee,g]=a(de.name,null);o({active:Be},(Ae,ne)=>{if(ne.name!==\"space\")return;if(!Ee){g(vB[0]);return}let Z=vB.indexOf(Ee)+1;Z===vB.length?g(null):g(vB[Z])},[Ee,g]);let me=G.parseIdent(de.name),we=G.prettyIdent(v,me);return h.createElement(A,null,h.createElement(A,{width:45},h.createElement(p,{bold:!0,wrap:\"wrap\"},we)),h.createElement(A,{width:14,marginLeft:1},h.createElement(p,{bold:!0,wrap:\"truncate\"},de.owner.name)),h.createElement(A,{width:10,marginLeft:1},h.createElement(p,{italic:!0,wrap:\"truncate\"},de.version)),h.createElement(A,{width:16,marginLeft:1},h.createElement(p,null,de.humanDownloadsLast30Days)))},U=({name:de,active:Be})=>{let[Ee]=a(de,null),g=G.parseIdent(de);return h.createElement(A,null,h.createElement(A,{width:47},h.createElement(p,{bold:!0},\" - \",G.prettyIdent(v,g))),vB.map(me=>h.createElement(A,{key:me,width:14,marginLeft:1},h.createElement(p,null,\" \",h.createElement(e,{active:Ee===me}),\" \",h.createElement(p,{bold:!0},me)))))},z=()=>h.createElement(A,{marginTop:1},h.createElement(p,null,\"Powered by Algolia.\")),ae=await n(({useSubmit:de})=>{let Be=a();de(Be);let Ee=Array.from(Be.keys()).filter(H=>Be.get(H)!==null),[g,me]=I(\"\"),[we,Ae]=I(0),[ne,Z]=I([]),xe=H=>{H.match(/\\t| /)||me(H)},Ne=async()=>{Ae(0);let H=await KH(g);H.query===g&&Z(H.hits)},ht=async()=>{let H=await KH(g,we+1);H.query===g&&H.page-1===we&&(Ae(H.page),Z([...ne,...H.hits]))};return E(()=>{g?Ne():Z([])},[g]),h.createElement(A,{flexDirection:\"column\"},h.createElement(x,null),h.createElement(A,{flexDirection:\"row\",marginTop:1},h.createElement(p,{bold:!0},\"Search: \"),h.createElement(A,{width:41},h.createElement(u,{value:g,onChange:xe,placeholder:\"i.e. babel, webpack, react...\",showCursor:!1})),h.createElement(C,null)),ne.length?h.createElement(r,{radius:2,loop:!1,children:ne.map(H=>h.createElement(L,{key:H.name,hit:H,active:!1})),willReachEnd:ht}):h.createElement(p,{color:\"gray\"},\"Start typing...\"),h.createElement(A,{flexDirection:\"row\",marginTop:1},h.createElement(A,{width:49},h.createElement(p,{bold:!0},\"Selected:\")),h.createElement(R,null)),Ee.length?Ee.map(H=>h.createElement(U,{key:H,name:H,active:!1})):h.createElement(p,{color:\"gray\"},\"No selected packages...\"),h.createElement(z,null))},{},{stdin:this.context.stdin,stdout:this.context.stdout,stderr:this.context.stderr});if(typeof ae>\"u\")return 1;let le=Array.from(ae.keys()).filter(de=>ae.get(de)===\"regular\"),ce=Array.from(ae.keys()).filter(de=>ae.get(de)===\"dev\"),Ce=Array.from(ae.keys()).filter(de=>ae.get(de)===\"peer\");return le.length&&await this.cli.run([\"add\",...le]),ce.length&&await this.cli.run([\"add\",\"--dev\",...ce]),Ce&&await this.cli.run([\"add\",\"--peer\",...Ce]),0}};Ge();qt();f_();var hIe=Ze(Jn()),pIe=/^((?:[\\^~]|>=?)?)([0-9]+)(\\.[0-9]+)(\\.[0-9]+)((?:-\\S+)?)$/,gIe=(t,e)=>t.length>0?[t.slice(0,e)].concat(gIe(t.slice(e),e)):[],aC=class extends ut{static{this.paths=[[\"upgrade-interactive\"]]}static{this.usage=it.Usage({category:\"Interactive commands\",description:\"open the upgrade interface\",details:`\n      This command opens a fullscreen terminal interface where you can see any out of date packages used by your application, their status compared to the latest versions available on the remote registry, and select packages to upgrade.\n    `,examples:[[\"Open the upgrade window\",\"yarn upgrade-interactive\"]]})}async execute(){GE(this.context);let{ItemOptions:e}=await Promise.resolve().then(()=>(fIe(),AIe)),{Pad:r}=await Promise.resolve().then(()=>(xq(),uIe)),{ScrollableItems:o}=await Promise.resolve().then(()=>(rQ(),tQ)),{useMinistore:a}=await Promise.resolve().then(()=>(Dq(),vq)),{renderForm:n}=await Promise.resolve().then(()=>(oQ(),sQ)),{Box:u,Text:A}=await Promise.resolve().then(()=>Ze(ic())),{default:p,useEffect:h,useRef:E,useState:I}=await Promise.resolve().then(()=>Ze(an())),v=await Ke.find(this.context.cwd,this.context.plugins),{project:x,workspace:C}=await kt.find(v,this.context.cwd),R=await Gr.find(v);if(!C)throw new sr(x.cwd,this.context.cwd);await x.restoreInstallState({restoreResolutions:!1});let L=this.context.stdout.rows-7,U=(me,we)=>{let Ae=gpe(me,we),ne=\"\";for(let Z of Ae)Z.added?ne+=pe.pretty(v,Z.value,\"green\"):Z.removed||(ne+=Z.value);return ne},z=(me,we)=>{if(me===we)return we;let Ae=G.parseRange(me),ne=G.parseRange(we),Z=Ae.selector.match(pIe),xe=ne.selector.match(pIe);if(!Z||!xe)return U(me,we);let Ne=[\"gray\",\"red\",\"yellow\",\"green\",\"magenta\"],ht=null,H=\"\";for(let rt=1;rt<Ne.length;++rt)ht!==null||Z[rt]!==xe[rt]?(ht===null&&(ht=Ne[rt-1]),H+=pe.pretty(v,xe[rt],ht)):H+=xe[rt];return H},te=async(me,we,Ae)=>{let ne=await Zc.fetchDescriptorFrom(me,Ae,{project:x,cache:R,preserveModifier:we,workspace:C});return ne!==null?ne.range:me.range},ae=async me=>{let we=hIe.default.valid(me.range)?`^${me.range}`:me.range,[Ae,ne]=await Promise.all([te(me,me.range,we).catch(()=>null),te(me,me.range,\"latest\").catch(()=>null)]),Z=[{value:null,label:me.range}];return Ae&&Ae!==me.range?Z.push({value:Ae,label:z(me.range,Ae)}):Z.push({value:null,label:\"\"}),ne&&ne!==Ae&&ne!==me.range?Z.push({value:ne,label:z(me.range,ne)}):Z.push({value:null,label:\"\"}),Z},le=()=>p.createElement(u,{flexDirection:\"row\"},p.createElement(u,{flexDirection:\"column\",width:49},p.createElement(u,{marginLeft:1},p.createElement(A,null,\"Press \",p.createElement(A,{bold:!0,color:\"cyanBright\"},\"<up>\"),\"/\",p.createElement(A,{bold:!0,color:\"cyanBright\"},\"<down>\"),\" to select packages.\")),p.createElement(u,{marginLeft:1},p.createElement(A,null,\"Press \",p.createElement(A,{bold:!0,color:\"cyanBright\"},\"<left>\"),\"/\",p.createElement(A,{bold:!0,color:\"cyanBright\"},\"<right>\"),\" to select versions.\"))),p.createElement(u,{flexDirection:\"column\"},p.createElement(u,{marginLeft:1},p.createElement(A,null,\"Press \",p.createElement(A,{bold:!0,color:\"cyanBright\"},\"<enter>\"),\" to install.\")),p.createElement(u,{marginLeft:1},p.createElement(A,null,\"Press \",p.createElement(A,{bold:!0,color:\"cyanBright\"},\"<ctrl+c>\"),\" to abort.\")))),ce=()=>p.createElement(u,{flexDirection:\"row\",paddingTop:1,paddingBottom:1},p.createElement(u,{width:50},p.createElement(A,{bold:!0},p.createElement(A,{color:\"greenBright\"},\"?\"),\" Pick the packages you want to upgrade.\")),p.createElement(u,{width:17},p.createElement(A,{bold:!0,underline:!0,color:\"gray\"},\"Current\")),p.createElement(u,{width:17},p.createElement(A,{bold:!0,underline:!0,color:\"gray\"},\"Range\")),p.createElement(u,{width:17},p.createElement(A,{bold:!0,underline:!0,color:\"gray\"},\"Latest\"))),Ce=({active:me,descriptor:we,suggestions:Ae})=>{let[ne,Z]=a(we.descriptorHash,null),xe=G.stringifyIdent(we),Ne=Math.max(0,45-xe.length);return p.createElement(p.Fragment,null,p.createElement(u,null,p.createElement(u,{width:45},p.createElement(A,{bold:!0},G.prettyIdent(v,we)),p.createElement(r,{active:me,length:Ne})),p.createElement(e,{active:me,options:Ae,value:ne,skewer:!0,onChange:Z,sizes:[17,17,17]})))},de=({dependencies:me})=>{let[we,Ae]=I(me.map(()=>null)),ne=E(!0),Z=async xe=>{let Ne=await ae(xe);return Ne.filter(ht=>ht.label!==\"\").length<=1?null:{descriptor:xe,suggestions:Ne}};return h(()=>()=>{ne.current=!1},[]),h(()=>{let xe=Math.trunc(L*1.75),Ne=me.slice(0,xe),ht=me.slice(xe),H=gIe(ht,L),rt=Ne.map(Z).reduce(async(Te,Fe)=>{await Te;let ke=await Fe;ke!==null&&ne.current&&Ae(Ye=>{let be=Ye.findIndex(Ue=>Ue===null),et=[...Ye];return et[be]=ke,et})},Promise.resolve());H.reduce((Te,Fe)=>Promise.all(Fe.map(ke=>Promise.resolve().then(()=>Z(ke)))).then(async ke=>{ke=ke.filter(Ye=>Ye!==null),await Te,ne.current&&Ae(Ye=>{let be=Ye.findIndex(et=>et===null);return Ye.slice(0,be).concat(ke).concat(Ye.slice(be+ke.length))})}),rt).then(()=>{ne.current&&Ae(Te=>Te.filter(Fe=>Fe!==null))})},[]),we.length?p.createElement(o,{radius:L>>1,children:we.map((xe,Ne)=>xe!==null?p.createElement(Ce,{key:Ne,active:!1,descriptor:xe.descriptor,suggestions:xe.suggestions}):p.createElement(A,{key:Ne},\"Loading...\"))}):p.createElement(A,null,\"No upgrades found\")},Ee=await n(({useSubmit:me})=>{me(a());let we=new Map;for(let ne of x.workspaces)for(let Z of[\"dependencies\",\"devDependencies\"])for(let xe of ne.manifest[Z].values())x.tryWorkspaceByDescriptor(xe)===null&&(xe.range.startsWith(\"link:\")||we.set(xe.descriptorHash,xe));let Ae=He.sortMap(we.values(),ne=>G.stringifyDescriptor(ne));return p.createElement(u,{flexDirection:\"column\"},p.createElement(le,null),p.createElement(ce,null),p.createElement(de,{dependencies:Ae}))},{},{stdin:this.context.stdin,stdout:this.context.stdout,stderr:this.context.stderr});if(typeof Ee>\"u\")return 1;let g=!1;for(let me of x.workspaces)for(let we of[\"dependencies\",\"devDependencies\"]){let Ae=me.manifest[we];for(let ne of Ae.values()){let Z=Ee.get(ne.descriptorHash);typeof Z<\"u\"&&Z!==null&&(Ae.set(ne.identHash,G.makeDescriptor(ne,Z)),g=!0)}}return g?await x.installWithNewReport({quiet:this.context.quiet,stdout:this.context.stdout},{cache:R}):0}};var lIt={commands:[oC,aC]},cIt=lIt;var Qq={};Vt(Qq,{LinkFetcher:()=>PB,LinkResolver:()=>bB,PortalFetcher:()=>SB,PortalResolver:()=>xB,default:()=>AIt});Ge();Pt();var Xf=\"portal:\",Zf=\"link:\";var PB=class{supports(e,r){return!!e.reference.startsWith(Zf)}getLocalPath(e,r){let{parentLocator:o,path:a}=G.parseFileStyleRange(e.reference,{protocol:Zf});if(V.isAbsolute(a))return a;let n=r.fetcher.getLocalPath(o,r);return n===null?null:V.resolve(n,a)}async fetch(e,r){let{parentLocator:o,path:a}=G.parseFileStyleRange(e.reference,{protocol:Zf}),n=V.isAbsolute(a)?{packageFs:new gn(It.root),prefixPath:It.dot,localPath:It.root}:await r.fetcher.fetch(o,r),u=n.localPath?{packageFs:new gn(It.root),prefixPath:V.relative(It.root,n.localPath),localPath:It.root}:n;n!==u&&n.releaseFs&&n.releaseFs();let A=u.packageFs,p=V.resolve(u.localPath??u.packageFs.getRealPath(),u.prefixPath,a);return n.localPath?{packageFs:new gn(p,{baseFs:A}),releaseFs:u.releaseFs,prefixPath:It.dot,discardFromLookup:!0,localPath:p}:{packageFs:new qu(p,{baseFs:A}),releaseFs:u.releaseFs,prefixPath:It.dot,discardFromLookup:!0}}};Ge();Pt();var bB=class{supportsDescriptor(e,r){return!!e.range.startsWith(Zf)}supportsLocator(e,r){return!!e.reference.startsWith(Zf)}shouldPersistResolution(e,r){return!1}bindDescriptor(e,r,o){return G.bindDescriptor(e,{locator:G.stringifyLocator(r)})}getResolutionDependencies(e,r){return{}}async getCandidates(e,r,o){let a=e.range.slice(Zf.length);return[G.makeLocator(e,`${Zf}${ue.toPortablePath(a)}`)]}async getSatisfying(e,r,o,a){let[n]=await this.getCandidates(e,r,a);return{locators:o.filter(u=>u.locatorHash===n.locatorHash),sorted:!1}}async resolve(e,r){return{...e,version:\"0.0.0\",languageName:r.project.configuration.get(\"defaultLanguageName\"),linkType:\"SOFT\",conditions:null,dependencies:new Map,peerDependencies:new Map,dependenciesMeta:new Map,peerDependenciesMeta:new Map,bin:new Map}}};Ge();Pt();var SB=class{supports(e,r){return!!e.reference.startsWith(Xf)}getLocalPath(e,r){let{parentLocator:o,path:a}=G.parseFileStyleRange(e.reference,{protocol:Xf});if(V.isAbsolute(a))return a;let n=r.fetcher.getLocalPath(o,r);return n===null?null:V.resolve(n,a)}async fetch(e,r){let{parentLocator:o,path:a}=G.parseFileStyleRange(e.reference,{protocol:Xf}),n=V.isAbsolute(a)?{packageFs:new gn(It.root),prefixPath:It.dot,localPath:It.root}:await r.fetcher.fetch(o,r),u=n.localPath?{packageFs:new gn(It.root),prefixPath:V.relative(It.root,n.localPath),localPath:It.root}:n;n!==u&&n.releaseFs&&n.releaseFs();let A=u.packageFs,p=V.resolve(u.localPath??u.packageFs.getRealPath(),u.prefixPath,a);return n.localPath?{packageFs:new gn(p,{baseFs:A}),releaseFs:u.releaseFs,prefixPath:It.dot,localPath:p}:{packageFs:new qu(p,{baseFs:A}),releaseFs:u.releaseFs,prefixPath:It.dot}}};Ge();Ge();Pt();var xB=class{supportsDescriptor(e,r){return!!e.range.startsWith(Xf)}supportsLocator(e,r){return!!e.reference.startsWith(Xf)}shouldPersistResolution(e,r){return!1}bindDescriptor(e,r,o){return G.bindDescriptor(e,{locator:G.stringifyLocator(r)})}getResolutionDependencies(e,r){return{}}async getCandidates(e,r,o){let a=e.range.slice(Xf.length);return[G.makeLocator(e,`${Xf}${ue.toPortablePath(a)}`)]}async getSatisfying(e,r,o,a){let[n]=await this.getCandidates(e,r,a);return{locators:o.filter(u=>u.locatorHash===n.locatorHash),sorted:!1}}async resolve(e,r){if(!r.fetchOptions)throw new Error(\"Assertion failed: This resolver cannot be used unless a fetcher is configured\");let o=await r.fetchOptions.fetcher.fetch(e,r.fetchOptions),a=await He.releaseAfterUseAsync(async()=>await Ut.find(o.prefixPath,{baseFs:o.packageFs}),o.releaseFs);return{...e,version:a.version||\"0.0.0\",languageName:a.languageName||r.project.configuration.get(\"defaultLanguageName\"),linkType:\"SOFT\",conditions:a.getConditions(),dependencies:r.project.configuration.normalizeDependencyMap(a.dependencies),peerDependencies:a.peerDependencies,dependenciesMeta:a.dependenciesMeta,peerDependenciesMeta:a.peerDependenciesMeta,bin:a.bin}}};var uIt={fetchers:[PB,SB],resolvers:[bB,xB]},AIt=uIt;var hj={};Vt(hj,{NodeModulesLinker:()=>GB,NodeModulesMode:()=>uj,PnpLooseLinker:()=>YB,default:()=>b1t});Pt();Ge();Pt();Pt();var Rq=(t,e)=>`${t}@${e}`,dIe=(t,e)=>{let r=e.indexOf(\"#\"),o=r>=0?e.substring(r+1):e;return Rq(t,o)};var yIe=(t,e={})=>{let r=e.debugLevel||Number(process.env.NM_DEBUG_LEVEL||-1),o=e.check||r>=9,a=e.hoistingLimits||new Map,n={check:o,debugLevel:r,hoistingLimits:a,fastLookupPossible:!0},u;n.debugLevel>=0&&(u=Date.now());let A=yIt(t,n),p=!1,h=0;do p=Tq(A,[A],new Set([A.locator]),new Map,n).anotherRoundNeeded,n.fastLookupPossible=!1,h++;while(p);if(n.debugLevel>=0&&console.log(`hoist time: ${Date.now()-u}ms, rounds: ${h}`),n.debugLevel>=1){let E=kB(A);if(Tq(A,[A],new Set([A.locator]),new Map,n).isGraphChanged)throw new Error(`The hoisting result is not terminal, prev tree:\n${E}, next tree:\n${kB(A)}`);let v=EIe(A);if(v)throw new Error(`${v}, after hoisting finished:\n${kB(A)}`)}return n.debugLevel>=2&&console.log(kB(A)),EIt(A)},fIt=t=>{let e=t[t.length-1],r=new Map,o=new Set,a=n=>{if(!o.has(n)){o.add(n);for(let u of n.hoistedDependencies.values())r.set(u.name,u);for(let u of n.dependencies.values())n.peerNames.has(u.name)||a(u)}};return a(e),r},pIt=t=>{let e=t[t.length-1],r=new Map,o=new Set,a=new Set,n=(u,A)=>{if(o.has(u))return;o.add(u);for(let h of u.hoistedDependencies.values())if(!A.has(h.name)){let E;for(let I of t)E=I.dependencies.get(h.name),E&&r.set(E.name,E)}let p=new Set;for(let h of u.dependencies.values())p.add(h.name);for(let h of u.dependencies.values())u.peerNames.has(h.name)||n(h,p)};return n(e,a),r},mIe=(t,e)=>{if(e.decoupled)return e;let{name:r,references:o,ident:a,locator:n,dependencies:u,originalDependencies:A,hoistedDependencies:p,peerNames:h,reasons:E,isHoistBorder:I,hoistPriority:v,dependencyKind:x,hoistedFrom:C,hoistedTo:R}=e,L={name:r,references:new Set(o),ident:a,locator:n,dependencies:new Map(u),originalDependencies:new Map(A),hoistedDependencies:new Map(p),peerNames:new Set(h),reasons:new Map(E),decoupled:!0,isHoistBorder:I,hoistPriority:v,dependencyKind:x,hoistedFrom:new Map(C),hoistedTo:new Map(R)},U=L.dependencies.get(r);return U&&U.ident==L.ident&&L.dependencies.set(r,L),t.dependencies.set(L.name,L),L},hIt=(t,e)=>{let r=new Map([[t.name,[t.ident]]]);for(let a of t.dependencies.values())t.peerNames.has(a.name)||r.set(a.name,[a.ident]);let o=Array.from(e.keys());o.sort((a,n)=>{let u=e.get(a),A=e.get(n);return A.hoistPriority!==u.hoistPriority?A.hoistPriority-u.hoistPriority:A.peerDependents.size!==u.peerDependents.size?A.peerDependents.size-u.peerDependents.size:A.dependents.size-u.dependents.size});for(let a of o){let n=a.substring(0,a.indexOf(\"@\",1)),u=a.substring(n.length+1);if(!t.peerNames.has(n)){let A=r.get(n);A||(A=[],r.set(n,A)),A.indexOf(u)<0&&A.push(u)}}return r},Fq=t=>{let e=new Set,r=(o,a=new Set)=>{if(!a.has(o)){a.add(o);for(let n of o.peerNames)if(!t.peerNames.has(n)){let u=t.dependencies.get(n);u&&!e.has(u)&&r(u,a)}e.add(o)}};for(let o of t.dependencies.values())t.peerNames.has(o.name)||r(o);return e},Tq=(t,e,r,o,a,n=new Set)=>{let u=e[e.length-1];if(n.has(u))return{anotherRoundNeeded:!1,isGraphChanged:!1};n.add(u);let A=CIt(u),p=hIt(u,A),h=t==u?new Map:a.fastLookupPossible?fIt(e):pIt(e),E,I=!1,v=!1,x=new Map(Array.from(p.entries()).map(([R,L])=>[R,L[0]])),C=new Map;do{let R=mIt(t,e,r,h,x,p,o,C,a);R.isGraphChanged&&(v=!0),R.anotherRoundNeeded&&(I=!0),E=!1;for(let[L,U]of p)U.length>1&&!u.dependencies.has(L)&&(x.delete(L),U.shift(),x.set(L,U[0]),E=!0)}while(E);for(let R of u.dependencies.values())if(!u.peerNames.has(R.name)&&!r.has(R.locator)){r.add(R.locator);let L=Tq(t,[...e,R],r,C,a);L.isGraphChanged&&(v=!0),L.anotherRoundNeeded&&(I=!0),r.delete(R.locator)}return{anotherRoundNeeded:I,isGraphChanged:v}},gIt=t=>{for(let[e,r]of t.dependencies)if(!t.peerNames.has(e)&&r.ident!==t.ident)return!0;return!1},dIt=(t,e,r,o,a,n,u,A,{outputReason:p,fastLookupPossible:h})=>{let E,I=null,v=new Set;p&&(E=`${Array.from(e).map(L=>no(L)).join(\"\\u2192\")}`);let x=r[r.length-1],R=!(o.ident===x.ident);if(p&&!R&&(I=\"- self-reference\"),R&&(R=o.dependencyKind!==1,p&&!R&&(I=\"- workspace\")),R&&o.dependencyKind===2&&(R=!gIt(o),p&&!R&&(I=\"- external soft link with unhoisted dependencies\")),R&&(R=x.dependencyKind!==1||x.hoistedFrom.has(o.name)||e.size===1,p&&!R&&(I=x.reasons.get(o.name))),R&&(R=!t.peerNames.has(o.name),p&&!R&&(I=`- cannot shadow peer: ${no(t.originalDependencies.get(o.name).locator)} at ${E}`)),R){let L=!1,U=a.get(o.name);if(L=!U||U.ident===o.ident,p&&!L&&(I=`- filled by: ${no(U.locator)} at ${E}`),L)for(let z=r.length-1;z>=1;z--){let ae=r[z].dependencies.get(o.name);if(ae&&ae.ident!==o.ident){L=!1;let le=A.get(x);le||(le=new Set,A.set(x,le)),le.add(o.name),p&&(I=`- filled by ${no(ae.locator)} at ${r.slice(0,z).map(ce=>no(ce.locator)).join(\"\\u2192\")}`);break}}R=L}if(R&&(R=n.get(o.name)===o.ident,p&&!R&&(I=`- filled by: ${no(u.get(o.name)[0])} at ${E}`)),R){let L=!0,U=new Set(o.peerNames);for(let z=r.length-1;z>=1;z--){let te=r[z];for(let ae of U){if(te.peerNames.has(ae)&&te.originalDependencies.has(ae))continue;let le=te.dependencies.get(ae);le&&t.dependencies.get(ae)!==le&&(z===r.length-1?v.add(le):(v=null,L=!1,p&&(I=`- peer dependency ${no(le.locator)} from parent ${no(te.locator)} was not hoisted to ${E}`))),U.delete(ae)}if(!L)break}R=L}if(R&&!h)for(let L of o.hoistedDependencies.values()){let U=a.get(L.name)||t.dependencies.get(L.name);if(!U||L.ident!==U.ident){R=!1,p&&(I=`- previously hoisted dependency mismatch, needed: ${no(L.locator)}, available: ${no(U?.locator)}`);break}}return v!==null&&v.size>0?{isHoistable:2,dependsOn:v,reason:I}:{isHoistable:R?0:1,reason:I}},aQ=t=>`${t.name}@${t.locator}`,mIt=(t,e,r,o,a,n,u,A,p)=>{let h=e[e.length-1],E=new Set,I=!1,v=!1,x=(U,z,te,ae,le)=>{if(E.has(ae))return;let ce=[...z,aQ(ae)],Ce=[...te,aQ(ae)],de=new Map,Be=new Map;for(let Ae of Fq(ae)){let ne=dIt(h,r,[h,...U,ae],Ae,o,a,n,A,{outputReason:p.debugLevel>=2,fastLookupPossible:p.fastLookupPossible});if(Be.set(Ae,ne),ne.isHoistable===2)for(let Z of ne.dependsOn){let xe=de.get(Z.name)||new Set;xe.add(Ae.name),de.set(Z.name,xe)}}let Ee=new Set,g=(Ae,ne,Z)=>{if(!Ee.has(Ae)){Ee.add(Ae),Be.set(Ae,{isHoistable:1,reason:Z});for(let xe of de.get(Ae.name)||[])g(ae.dependencies.get(xe),ne,p.debugLevel>=2?`- peer dependency ${no(Ae.locator)} from parent ${no(ae.locator)} was not hoisted`:\"\")}};for(let[Ae,ne]of Be)ne.isHoistable===1&&g(Ae,ne,ne.reason);let me=!1;for(let Ae of Be.keys())if(!Ee.has(Ae)){v=!0;let ne=u.get(ae);ne&&ne.has(Ae.name)&&(I=!0),me=!0,ae.dependencies.delete(Ae.name),ae.hoistedDependencies.set(Ae.name,Ae),ae.reasons.delete(Ae.name);let Z=h.dependencies.get(Ae.name);if(p.debugLevel>=2){let xe=Array.from(z).concat([ae.locator]).map(ht=>no(ht)).join(\"\\u2192\"),Ne=h.hoistedFrom.get(Ae.name);Ne||(Ne=[],h.hoistedFrom.set(Ae.name,Ne)),Ne.push(xe),ae.hoistedTo.set(Ae.name,Array.from(e).map(ht=>no(ht.locator)).join(\"\\u2192\"))}if(!Z)h.ident!==Ae.ident&&(h.dependencies.set(Ae.name,Ae),le.add(Ae));else for(let xe of Ae.references)Z.references.add(xe)}if(ae.dependencyKind===2&&me&&(I=!0),p.check){let Ae=EIe(t);if(Ae)throw new Error(`${Ae}, after hoisting dependencies of ${[h,...U,ae].map(ne=>no(ne.locator)).join(\"\\u2192\")}:\n${kB(t)}`)}let we=Fq(ae);for(let Ae of we)if(Ee.has(Ae)){let ne=Be.get(Ae);if((a.get(Ae.name)===Ae.ident||!ae.reasons.has(Ae.name))&&ne.isHoistable!==0&&ae.reasons.set(Ae.name,ne.reason),!Ae.isHoistBorder&&Ce.indexOf(aQ(Ae))<0){E.add(ae);let xe=mIe(ae,Ae);x([...U,ae],ce,Ce,xe,R),E.delete(ae)}}},C,R=new Set(Fq(h)),L=Array.from(e).map(U=>aQ(U));do{C=R,R=new Set;for(let U of C){if(U.locator===h.locator||U.isHoistBorder)continue;let z=mIe(h,U);x([],Array.from(r),L,z,R)}}while(R.size>0);return{anotherRoundNeeded:I,isGraphChanged:v}},EIe=t=>{let e=[],r=new Set,o=new Set,a=(n,u,A)=>{if(r.has(n)||(r.add(n),o.has(n)))return;let p=new Map(u);for(let h of n.dependencies.values())n.peerNames.has(h.name)||p.set(h.name,h);for(let h of n.originalDependencies.values()){let E=p.get(h.name),I=()=>`${Array.from(o).concat([n]).map(v=>no(v.locator)).join(\"\\u2192\")}`;if(n.peerNames.has(h.name)){let v=u.get(h.name);(v!==E||!v||v.ident!==h.ident)&&e.push(`${I()} - broken peer promise: expected ${h.ident} but found ${v&&v.ident}`)}else{let v=A.hoistedFrom.get(n.name),x=n.hoistedTo.get(h.name),C=`${v?` hoisted from ${v.join(\", \")}`:\"\"}`,R=`${x?` hoisted to ${x}`:\"\"}`,L=`${I()}${C}`;E?E.ident!==h.ident&&e.push(`${L} - broken require promise for ${h.name}${R}: expected ${h.ident}, but found: ${E.ident}`):e.push(`${L} - broken require promise: no required dependency ${h.name}${R} found`)}}o.add(n);for(let h of n.dependencies.values())n.peerNames.has(h.name)||a(h,p,n);o.delete(n)};return a(t,t.dependencies,t),e.join(`\n`)},yIt=(t,e)=>{let{identName:r,name:o,reference:a,peerNames:n}=t,u={name:o,references:new Set([a]),locator:Rq(r,a),ident:dIe(r,a),dependencies:new Map,originalDependencies:new Map,hoistedDependencies:new Map,peerNames:new Set(n),reasons:new Map,decoupled:!0,isHoistBorder:!0,hoistPriority:0,dependencyKind:1,hoistedFrom:new Map,hoistedTo:new Map},A=new Map([[t,u]]),p=(h,E)=>{let I=A.get(h),v=!!I;if(!I){let{name:x,identName:C,reference:R,peerNames:L,hoistPriority:U,dependencyKind:z}=h,te=e.hoistingLimits.get(E.locator);I={name:x,references:new Set([R]),locator:Rq(C,R),ident:dIe(C,R),dependencies:new Map,originalDependencies:new Map,hoistedDependencies:new Map,peerNames:new Set(L),reasons:new Map,decoupled:!0,isHoistBorder:te?te.has(x):!1,hoistPriority:U||0,dependencyKind:z||0,hoistedFrom:new Map,hoistedTo:new Map},A.set(h,I)}if(E.dependencies.set(h.name,I),E.originalDependencies.set(h.name,I),v){let x=new Set,C=R=>{if(!x.has(R)){x.add(R),R.decoupled=!1;for(let L of R.dependencies.values())R.peerNames.has(L.name)||C(L)}};C(I)}else for(let x of h.dependencies)p(x,I)};for(let h of t.dependencies)p(h,u);return u},Nq=t=>t.substring(0,t.indexOf(\"@\",1)),EIt=t=>{let e={name:t.name,identName:Nq(t.locator),references:new Set(t.references),dependencies:new Set},r=new Set([t]),o=(a,n,u)=>{let A=r.has(a),p;if(n===a)p=u;else{let{name:h,references:E,locator:I}=a;p={name:h,identName:Nq(I),references:E,dependencies:new Set}}if(u.dependencies.add(p),!A){r.add(a);for(let h of a.dependencies.values())a.peerNames.has(h.name)||o(h,a,p);r.delete(a)}};for(let a of t.dependencies.values())o(a,t,e);return e},CIt=t=>{let e=new Map,r=new Set([t]),o=u=>`${u.name}@${u.ident}`,a=u=>{let A=o(u),p=e.get(A);return p||(p={dependents:new Set,peerDependents:new Set,hoistPriority:0},e.set(A,p)),p},n=(u,A)=>{let p=!!r.has(A);if(a(A).dependents.add(u.ident),!p){r.add(A);for(let E of A.dependencies.values()){let I=a(E);I.hoistPriority=Math.max(I.hoistPriority,E.hoistPriority),A.peerNames.has(E.name)?I.peerDependents.add(A.ident):n(A,E)}}};for(let u of t.dependencies.values())t.peerNames.has(u.name)||n(t,u);return e},no=t=>{if(!t)return\"none\";let e=t.indexOf(\"@\",1),r=t.substring(0,e);r.endsWith(\"$wsroot$\")&&(r=`wh:${r.replace(\"$wsroot$\",\"\")}`);let o=t.substring(e+1);if(o===\"workspace:.\")return\".\";if(o){let a=(o.indexOf(\"#\")>0?o.split(\"#\")[1]:o).replace(\"npm:\",\"\");return o.startsWith(\"virtual\")&&(r=`v:${r}`),a.startsWith(\"workspace\")&&(r=`w:${r}`,a=\"\"),`${r}${a?`@${a}`:\"\"}`}else return`${r}`};var kB=t=>{let e=0,r=(a,n,u=\"\")=>{if(e>5e4||n.has(a))return\"\";e++;let A=Array.from(a.dependencies.values()).sort((h,E)=>h.name===E.name?0:h.name>E.name?1:-1),p=\"\";n.add(a);for(let h=0;h<A.length;h++){let E=A[h];if(!a.peerNames.has(E.name)&&E!==a){let I=a.reasons.get(E.name),v=Nq(E.locator);p+=`${u}${h<A.length-1?\"\\u251C\\u2500\":\"\\u2514\\u2500\"}${(n.has(E)?\">\":\"\")+(v!==E.name?`a:${E.name}:`:\"\")+no(E.locator)+(I?` ${I}`:\"\")}\n`,p+=r(E,n,`${u}${h<A.length-1?\"\\u2502 \":\"  \"}`)}}return n.delete(a),p};return r(t,new Set)+(e>5e4?`\nTree is too large, part of the tree has been dunped\n`:\"\")};var QB=(o=>(o.WORKSPACES=\"workspaces\",o.DEPENDENCIES=\"dependencies\",o.NONE=\"none\",o))(QB||{}),CIe=\"node_modules\",Oh=\"$wsroot$\";var FB=(t,e)=>{let{packageTree:r,hoistingLimits:o,errors:a,preserveSymlinksRequired:n}=IIt(t,e),u=null;if(a.length===0){let A=yIe(r,{hoistingLimits:o});u=vIt(t,A,e)}return{tree:u,errors:a,preserveSymlinksRequired:n}},gA=t=>`${t.name}@${t.reference}`,Mq=t=>{let e=new Map;for(let[r,o]of t.entries())if(!o.dirList){let a=e.get(o.locator);a||(a={target:o.target,linkType:o.linkType,locations:[],aliases:o.aliases},e.set(o.locator,a)),a.locations.push(r)}for(let r of e.values())r.locations=r.locations.sort((o,a)=>{let n=o.split(V.delimiter).length,u=a.split(V.delimiter).length;return a===o?0:n!==u?u-n:a>o?1:-1});return e},wIe=(t,e)=>{let r=G.isVirtualLocator(t)?G.devirtualizeLocator(t):t,o=G.isVirtualLocator(e)?G.devirtualizeLocator(e):e;return G.areLocatorsEqual(r,o)},Lq=(t,e,r,o)=>{if(t.linkType!==\"SOFT\")return!1;let a=ue.toPortablePath(r.resolveVirtual&&e.reference&&e.reference.startsWith(\"virtual:\")?r.resolveVirtual(t.packageLocation):t.packageLocation);return V.contains(o,a)===null},wIt=t=>{let e=t.getPackageInformation(t.topLevel);if(e===null)throw new Error(\"Assertion failed: Expected the top-level package to have been registered\");if(t.findPackageLocator(e.packageLocation)===null)throw new Error(\"Assertion failed: Expected the top-level package to have a physical locator\");let o=ue.toPortablePath(e.packageLocation.slice(0,-1)),a=new Map,n={children:new Map},u=t.getDependencyTreeRoots(),A=new Map,p=new Set,h=(v,x)=>{let C=gA(v);if(p.has(C))return;p.add(C);let R=t.getPackageInformation(v);if(R){let L=x?gA(x):\"\";if(gA(v)!==L&&R.linkType===\"SOFT\"&&!v.reference.startsWith(\"link:\")&&!Lq(R,v,t,o)){let U=IIe(R,v,t);(!A.get(U)||v.reference.startsWith(\"workspace:\"))&&A.set(U,v)}for(let[U,z]of R.packageDependencies)z!==null&&(R.packagePeers.has(U)||h(t.getLocator(U,z),v))}};for(let v of u)h(v,null);let E=o.split(V.sep);for(let v of A.values()){let x=t.getPackageInformation(v),R=ue.toPortablePath(x.packageLocation.slice(0,-1)).split(V.sep).slice(E.length),L=n;for(let U of R){let z=L.children.get(U);z||(z={children:new Map},L.children.set(U,z)),L=z}L.workspaceLocator=v}let I=(v,x)=>{if(v.workspaceLocator){let C=gA(x),R=a.get(C);R||(R=new Set,a.set(C,R)),R.add(v.workspaceLocator)}for(let C of v.children.values())I(C,v.workspaceLocator||x)};for(let v of n.children.values())I(v,n.workspaceLocator);return a},IIt=(t,e)=>{let r=[],o=!1,a=new Map,n=wIt(t),u=t.getPackageInformation(t.topLevel);if(u===null)throw new Error(\"Assertion failed: Expected the top-level package to have been registered\");let A=t.findPackageLocator(u.packageLocation);if(A===null)throw new Error(\"Assertion failed: Expected the top-level package to have a physical locator\");let p=ue.toPortablePath(u.packageLocation.slice(0,-1)),h={name:A.name,identName:A.name,reference:A.reference,peerNames:u.packagePeers,dependencies:new Set,dependencyKind:1},E=new Map,I=(x,C)=>`${gA(C)}:${x}`,v=(x,C,R,L,U,z,te,ae)=>{let le=I(x,R),ce=E.get(le),Ce=!!ce;!Ce&&R.name===A.name&&R.reference===A.reference&&(ce=h,E.set(le,h));let de=Lq(C,R,t,p);if(!ce){let Ae=0;de?Ae=2:C.linkType===\"SOFT\"&&R.name.endsWith(Oh)&&(Ae=1),ce={name:x,identName:R.name,reference:R.reference,dependencies:new Set,peerNames:Ae===1?new Set:C.packagePeers,dependencyKind:Ae},E.set(le,ce)}let Be;if(de?Be=2:U.linkType===\"SOFT\"?Be=1:Be=0,ce.hoistPriority=Math.max(ce.hoistPriority||0,Be),ae&&!de){let Ae=gA({name:L.identName,reference:L.reference}),ne=a.get(Ae)||new Set;a.set(Ae,ne),ne.add(ce.name)}let Ee=new Map(C.packageDependencies);if(e.project){let Ae=e.project.workspacesByCwd.get(ue.toPortablePath(C.packageLocation.slice(0,-1)));if(Ae){let ne=new Set([...Array.from(Ae.manifest.peerDependencies.values(),Z=>G.stringifyIdent(Z)),...Array.from(Ae.manifest.peerDependenciesMeta.keys())]);for(let Z of ne)Ee.has(Z)||(Ee.set(Z,z.get(Z)||null),ce.peerNames.add(Z))}}let g=gA({name:R.name.replace(Oh,\"\"),reference:R.reference}),me=n.get(g);if(me)for(let Ae of me)Ee.set(`${Ae.name}${Oh}`,Ae.reference);(C!==U||C.linkType!==\"SOFT\"||!de&&(!e.selfReferencesByCwd||e.selfReferencesByCwd.get(te)))&&L.dependencies.add(ce);let we=R!==A&&C.linkType===\"SOFT\"&&!R.name.endsWith(Oh)&&!de;if(!Ce&&!we){let Ae=new Map;for(let[ne,Z]of Ee)if(Z!==null){let xe=t.getLocator(ne,Z),Ne=t.getLocator(ne.replace(Oh,\"\"),Z),ht=t.getPackageInformation(Ne);if(ht===null)throw new Error(\"Assertion failed: Expected the package to have been registered\");let H=Lq(ht,xe,t,p);if(e.validateExternalSoftLinks&&e.project&&H){ht.packageDependencies.size>0&&(o=!0);for(let[Ye,be]of ht.packageDependencies)if(be!==null){let et=G.parseLocator(Array.isArray(be)?`${be[0]}@${be[1]}`:`${Ye}@${be}`);if(gA(et)!==gA(xe)){let Ue=Ee.get(Ye);if(Ue){let S=G.parseLocator(Array.isArray(Ue)?`${Ue[0]}@${Ue[1]}`:`${Ye}@${Ue}`);wIe(S,et)||r.push({messageName:71,text:`Cannot link ${G.prettyIdent(e.project.configuration,G.parseIdent(xe.name))} into ${G.prettyLocator(e.project.configuration,G.parseLocator(`${R.name}@${R.reference}`))} dependency ${G.prettyLocator(e.project.configuration,et)} conflicts with parent dependency ${G.prettyLocator(e.project.configuration,S)}`})}else{let S=Ae.get(Ye);if(S){let w=S.target,b=G.parseLocator(Array.isArray(w)?`${w[0]}@${w[1]}`:`${Ye}@${w}`);wIe(b,et)||r.push({messageName:71,text:`Cannot link ${G.prettyIdent(e.project.configuration,G.parseIdent(xe.name))} into ${G.prettyLocator(e.project.configuration,G.parseLocator(`${R.name}@${R.reference}`))} dependency ${G.prettyLocator(e.project.configuration,et)} conflicts with dependency ${G.prettyLocator(e.project.configuration,b)} from sibling portal ${G.prettyIdent(e.project.configuration,G.parseIdent(S.portal.name))}`})}else Ae.set(Ye,{target:et.reference,portal:xe})}}}}let rt=e.hoistingLimitsByCwd?.get(te),Te=H?te:V.relative(p,ue.toPortablePath(ht.packageLocation))||It.dot,Fe=e.hoistingLimitsByCwd?.get(Te);v(ne,ht,xe,ce,C,Ee,Te,rt===\"dependencies\"||Fe===\"dependencies\"||Fe===\"workspaces\")}}};return v(A.name,u,A,h,u,u.packageDependencies,It.dot,!1),{packageTree:h,hoistingLimits:a,errors:r,preserveSymlinksRequired:o}};function IIe(t,e,r){let o=r.resolveVirtual&&e.reference&&e.reference.startsWith(\"virtual:\")?r.resolveVirtual(t.packageLocation):t.packageLocation;return ue.toPortablePath(o||t.packageLocation)}function BIt(t,e,r){let o=e.getLocator(t.name.replace(Oh,\"\"),t.reference),a=e.getPackageInformation(o);if(a===null)throw new Error(\"Assertion failed: Expected the package to be registered\");return r.pnpifyFs?{linkType:\"SOFT\",target:ue.toPortablePath(a.packageLocation)}:{linkType:a.linkType,target:IIe(a,t,e)}}var vIt=(t,e,r)=>{let o=new Map,a=(E,I,v)=>{let{linkType:x,target:C}=BIt(E,t,r);return{locator:gA(E),nodePath:I,target:C,linkType:x,aliases:v}},n=E=>{let[I,v]=E.split(\"/\");return v?{scope:I,name:v}:{scope:null,name:I}},u=new Set,A=(E,I,v)=>{if(u.has(E))return;u.add(E);let x=Array.from(E.references).sort().join(\"#\");for(let C of E.dependencies){let R=Array.from(C.references).sort().join(\"#\");if(C.identName===E.identName.replace(Oh,\"\")&&R===x)continue;let L=Array.from(C.references).sort(),U={name:C.identName,reference:L[0]},{name:z,scope:te}=n(C.name),ae=te?[te,z]:[z],le=V.join(I,CIe),ce=V.join(le,...ae),Ce=`${v}/${U.name}`,de=a(U,v,L.slice(1)),Be=!1;if(de.linkType===\"SOFT\"&&r.project){let Ee=r.project.workspacesByCwd.get(de.target.slice(0,-1));Be=!!(Ee&&!Ee.manifest.name)}if(!C.name.endsWith(Oh)&&!Be){let Ee=o.get(ce);if(Ee){if(Ee.dirList)throw new Error(`Assertion failed: ${ce} cannot merge dir node with leaf node`);{let we=G.parseLocator(Ee.locator),Ae=G.parseLocator(de.locator);if(Ee.linkType!==de.linkType)throw new Error(`Assertion failed: ${ce} cannot merge nodes with different link types ${Ee.nodePath}/${G.stringifyLocator(we)} and ${v}/${G.stringifyLocator(Ae)}`);if(we.identHash!==Ae.identHash)throw new Error(`Assertion failed: ${ce} cannot merge nodes with different idents ${Ee.nodePath}/${G.stringifyLocator(we)} and ${v}/s${G.stringifyLocator(Ae)}`);de.aliases=[...de.aliases,...Ee.aliases,G.parseLocator(Ee.locator).reference]}}o.set(ce,de);let g=ce.split(\"/\"),me=g.indexOf(CIe);for(let we=g.length-1;me>=0&&we>me;we--){let Ae=ue.toPortablePath(g.slice(0,we).join(V.sep)),ne=g[we],Z=o.get(Ae);if(!Z)o.set(Ae,{dirList:new Set([ne])});else if(Z.dirList){if(Z.dirList.has(ne))break;Z.dirList.add(ne)}}}A(C,de.linkType===\"SOFT\"?de.target:ce,Ce)}},p=a({name:e.name,reference:Array.from(e.references)[0]},\"\",[]),h=p.target;return o.set(h,p),A(e,h,\"\"),o};Ge();Ge();Pt();Pt();nA();Nl();var rj={};Vt(rj,{PnpInstaller:()=>sd,PnpLinker:()=>Hh,UnplugCommand:()=>cC,default:()=>e1t,getPnpPath:()=>qh,jsInstallUtils:()=>mA,pnpUtils:()=>jB,quotePathIfNeeded:()=>o1e});Pt();var s1e=ve(\"url\");Ge();Ge();Pt();Pt();var BIe={DEFAULT:{collapsed:!1,next:{\"*\":\"DEFAULT\"}},TOP_LEVEL:{collapsed:!1,next:{fallbackExclusionList:\"FALLBACK_EXCLUSION_LIST\",packageRegistryData:\"PACKAGE_REGISTRY_DATA\",\"*\":\"DEFAULT\"}},FALLBACK_EXCLUSION_LIST:{collapsed:!1,next:{\"*\":\"FALLBACK_EXCLUSION_ENTRIES\"}},FALLBACK_EXCLUSION_ENTRIES:{collapsed:!0,next:{\"*\":\"FALLBACK_EXCLUSION_DATA\"}},FALLBACK_EXCLUSION_DATA:{collapsed:!0,next:{\"*\":\"DEFAULT\"}},PACKAGE_REGISTRY_DATA:{collapsed:!1,next:{\"*\":\"PACKAGE_REGISTRY_ENTRIES\"}},PACKAGE_REGISTRY_ENTRIES:{collapsed:!0,next:{\"*\":\"PACKAGE_STORE_DATA\"}},PACKAGE_STORE_DATA:{collapsed:!1,next:{\"*\":\"PACKAGE_STORE_ENTRIES\"}},PACKAGE_STORE_ENTRIES:{collapsed:!0,next:{\"*\":\"PACKAGE_INFORMATION_DATA\"}},PACKAGE_INFORMATION_DATA:{collapsed:!1,next:{packageDependencies:\"PACKAGE_DEPENDENCIES\",\"*\":\"DEFAULT\"}},PACKAGE_DEPENDENCIES:{collapsed:!1,next:{\"*\":\"PACKAGE_DEPENDENCY\"}},PACKAGE_DEPENDENCY:{collapsed:!0,next:{\"*\":\"DEFAULT\"}}};function DIt(t,e,r){let o=\"\";o+=\"[\";for(let a=0,n=t.length;a<n;++a)o+=lQ(String(a),t[a],e,r).replace(/^ +/g,\"\"),a+1<n&&(o+=\", \");return o+=\"]\",o}function PIt(t,e,r){let o=`${r}  `,a=\"\";a+=r,a+=`[\n`;for(let n=0,u=t.length;n<u;++n)a+=o+lQ(String(n),t[n],e,o).replace(/^ +/,\"\"),n+1<u&&(a+=\",\"),a+=`\n`;return a+=r,a+=\"]\",a}function bIt(t,e,r){let o=Object.keys(t),a=\"\";a+=\"{\";for(let n=0,u=o.length,A=0;n<u;++n){let p=o[n],h=t[p];typeof h>\"u\"||(A!==0&&(a+=\", \"),a+=JSON.stringify(p),a+=\": \",a+=lQ(p,h,e,r).replace(/^ +/g,\"\"),A+=1)}return a+=\"}\",a}function SIt(t,e,r){let o=Object.keys(t),a=`${r}  `,n=\"\";n+=r,n+=`{\n`;let u=0;for(let A=0,p=o.length;A<p;++A){let h=o[A],E=t[h];typeof E>\"u\"||(u!==0&&(n+=\",\",n+=`\n`),n+=a,n+=JSON.stringify(h),n+=\": \",n+=lQ(h,E,e,a).replace(/^ +/g,\"\"),u+=1)}return u!==0&&(n+=`\n`),n+=r,n+=\"}\",n}function lQ(t,e,r,o){let{next:a}=BIe[r],n=a[t]||a[\"*\"];return vIe(e,n,o)}function vIe(t,e,r){let{collapsed:o}=BIe[e];return Array.isArray(t)?o?DIt(t,e,r):PIt(t,e,r):typeof t==\"object\"&&t!==null?o?bIt(t,e,r):SIt(t,e,r):JSON.stringify(t)}function DIe(t){return vIe(t,\"TOP_LEVEL\",\"\")}function RB(t,e){let r=Array.from(t);Array.isArray(e)||(e=[e]);let o=[];for(let n of e)o.push(r.map(u=>n(u)));let a=r.map((n,u)=>u);return a.sort((n,u)=>{for(let A of o){let p=A[n]<A[u]?-1:A[n]>A[u]?1:0;if(p!==0)return p}return 0}),a.map(n=>r[n])}function xIt(t){let e=new Map,r=RB(t.fallbackExclusionList||[],[({name:o,reference:a})=>o,({name:o,reference:a})=>a]);for(let{name:o,reference:a}of r){let n=e.get(o);typeof n>\"u\"&&e.set(o,n=new Set),n.add(a)}return Array.from(e).map(([o,a])=>[o,Array.from(a)])}function kIt(t){return RB(t.fallbackPool||[],([e])=>e)}function QIt(t){let e=[];for(let[r,o]of RB(t.packageRegistry,([a])=>a===null?\"0\":`1${a}`)){let a=[];e.push([r,a]);for(let[n,{packageLocation:u,packageDependencies:A,packagePeers:p,linkType:h,discardFromLookup:E}]of RB(o,([I])=>I===null?\"0\":`1${I}`)){let I=[];r!==null&&n!==null&&!A.has(r)&&I.push([r,n]);for(let[C,R]of RB(A.entries(),([L])=>L))I.push([C,R]);let v=p&&p.size>0?Array.from(p):void 0,x=E||void 0;a.push([n,{packageLocation:u,packageDependencies:I,packagePeers:v,linkType:h,discardFromLookup:x}])}}return e}function TB(t){return{__info:[\"This file is automatically generated. Do not touch it, or risk\",\"your modifications being lost.\"],dependencyTreeRoots:t.dependencyTreeRoots,enableTopLevelFallback:t.enableTopLevelFallback||!1,ignorePatternData:t.ignorePattern||null,fallbackExclusionList:xIt(t),fallbackPool:kIt(t),packageRegistryData:QIt(t)}}var SIe=Ze(bIe());function xIe(t,e){return[t?`${t}\n`:\"\",`/* eslint-disable */\n`,`// @ts-nocheck\n`,`\"use strict\";\n`,`\n`,e,`\n`,(0,SIe.default)()].join(\"\")}function FIt(t){return JSON.stringify(t,null,2)}function RIt(t){return`'${t.replace(/\\\\/g,\"\\\\\\\\\").replace(/'/g,\"\\\\'\").replace(/\\n/g,`\\\\\n`)}'`}function TIt(t){return[`const RAW_RUNTIME_STATE =\n`,`${RIt(DIe(t))};\n\n`,`function $$SETUP_STATE(hydrateRuntimeState, basePath) {\n`,`  return hydrateRuntimeState(JSON.parse(RAW_RUNTIME_STATE), {basePath: basePath || __dirname});\n`,`}\n`].join(\"\")}function NIt(){return[`function $$SETUP_STATE(hydrateRuntimeState, basePath) {\n`,`  const fs = require('fs');\n`,`  const path = require('path');\n`,`  const pnpDataFilepath = path.resolve(__dirname, ${JSON.stringify(dr.pnpData)});\n`,`  return hydrateRuntimeState(JSON.parse(fs.readFileSync(pnpDataFilepath, 'utf8')), {basePath: basePath || __dirname});\n`,`}\n`].join(\"\")}function kIe(t){let e=TB(t),r=TIt(e);return xIe(t.shebang,r)}function QIe(t){let e=TB(t),r=NIt(),o=xIe(t.shebang,r);return{dataFile:FIt(e),loaderFile:o}}Pt();function Uq(t,{basePath:e}){let r=ue.toPortablePath(e),o=V.resolve(r),a=t.ignorePatternData!==null?new RegExp(t.ignorePatternData):null,n=new Map,u=new Map(t.packageRegistryData.map(([I,v])=>[I,new Map(v.map(([x,C])=>{if(I===null!=(x===null))throw new Error(\"Assertion failed: The name and reference should be null, or neither should\");let R=C.discardFromLookup??!1,L={name:I,reference:x},U=n.get(C.packageLocation);U?(U.discardFromLookup=U.discardFromLookup&&R,R||(U.locator=L)):n.set(C.packageLocation,{locator:L,discardFromLookup:R});let z=null;return[x,{packageDependencies:new Map(C.packageDependencies),packagePeers:new Set(C.packagePeers),linkType:C.linkType,discardFromLookup:R,get packageLocation(){return z||(z=V.join(o,C.packageLocation))}}]}))])),A=new Map(t.fallbackExclusionList.map(([I,v])=>[I,new Set(v)])),p=new Map(t.fallbackPool),h=t.dependencyTreeRoots,E=t.enableTopLevelFallback;return{basePath:r,dependencyTreeRoots:h,enableTopLevelFallback:E,fallbackExclusionList:A,fallbackPool:p,ignorePattern:a,packageLocatorsByLocations:n,packageRegistry:u}}Pt();Pt();var ep=ve(\"module\"),id=ve(\"url\"),zq=ve(\"util\");var Oo=ve(\"url\");var NIe=Ze(ve(\"assert\"));var _q=Array.isArray,NB=JSON.stringify,LB=Object.getOwnPropertyNames,nd=(t,e)=>Object.prototype.hasOwnProperty.call(t,e),Hq=(t,e)=>RegExp.prototype.exec.call(t,e),qq=(t,...e)=>RegExp.prototype[Symbol.replace].apply(t,e),Uh=(t,...e)=>String.prototype.endsWith.apply(t,e),jq=(t,...e)=>String.prototype.includes.apply(t,e),Gq=(t,...e)=>String.prototype.lastIndexOf.apply(t,e),MB=(t,...e)=>String.prototype.indexOf.apply(t,e),FIe=(t,...e)=>String.prototype.replace.apply(t,e),_h=(t,...e)=>String.prototype.slice.apply(t,e),dA=(t,...e)=>String.prototype.startsWith.apply(t,e),RIe=Map,TIe=JSON.parse;function OB(t,e,r){return class extends r{constructor(...o){super(e(...o)),this.code=t,this.name=`${r.name} [${t}]`}}}var LIe=OB(\"ERR_PACKAGE_IMPORT_NOT_DEFINED\",(t,e,r)=>`Package import specifier \"${t}\" is not defined${e?` in package ${e}package.json`:\"\"} imported from ${r}`,TypeError),Yq=OB(\"ERR_INVALID_MODULE_SPECIFIER\",(t,e,r=void 0)=>`Invalid module \"${t}\" ${e}${r?` imported from ${r}`:\"\"}`,TypeError),MIe=OB(\"ERR_INVALID_PACKAGE_TARGET\",(t,e,r,o=!1,a=void 0)=>{let n=typeof r==\"string\"&&!o&&r.length&&!dA(r,\"./\");return e===\".\"?((0,NIe.default)(o===!1),`Invalid \"exports\" main target ${NB(r)} defined in the package config ${t}package.json${a?` imported from ${a}`:\"\"}${n?'; targets must start with \"./\"':\"\"}`):`Invalid \"${o?\"imports\":\"exports\"}\" target ${NB(r)} defined for '${e}' in the package config ${t}package.json${a?` imported from ${a}`:\"\"}${n?'; targets must start with \"./\"':\"\"}`},Error),UB=OB(\"ERR_INVALID_PACKAGE_CONFIG\",(t,e,r)=>`Invalid package config ${t}${e?` while importing ${e}`:\"\"}${r?`. ${r}`:\"\"}`,Error),OIe=OB(\"ERR_PACKAGE_PATH_NOT_EXPORTED\",(t,e,r=void 0)=>e===\".\"?`No \"exports\" main defined in ${t}package.json${r?` imported from ${r}`:\"\"}`:`Package subpath '${e}' is not defined by \"exports\" in ${t}package.json${r?` imported from ${r}`:\"\"}`,Error);var uQ=ve(\"url\");function UIe(t,e){let r=Object.create(null);for(let o=0;o<e.length;o++){let a=e[o];nd(t,a)&&(r[a]=t[a])}return r}var cQ=new RIe;function LIt(t,e,r,o){let a=cQ.get(t);if(a!==void 0)return a;let n=o(t);if(n===void 0){let x={pjsonPath:t,exists:!1,main:void 0,name:void 0,type:\"none\",exports:void 0,imports:void 0};return cQ.set(t,x),x}let u;try{u=TIe(n)}catch(x){throw new UB(t,(r?`\"${e}\" from `:\"\")+(0,uQ.fileURLToPath)(r||e),x.message)}let{imports:A,main:p,name:h,type:E}=UIe(u,[\"imports\",\"main\",\"name\",\"type\"]),I=nd(u,\"exports\")?u.exports:void 0;(typeof A!=\"object\"||A===null)&&(A=void 0),typeof p!=\"string\"&&(p=void 0),typeof h!=\"string\"&&(h=void 0),E!==\"module\"&&E!==\"commonjs\"&&(E=\"none\");let v={pjsonPath:t,exists:!0,main:p,name:h,type:E,exports:I,imports:A};return cQ.set(t,v),v}function _Ie(t,e){let r=new URL(\"./package.json\",t);for(;;){let n=r.pathname;if(Uh(n,\"node_modules/package.json\"))break;let u=LIt((0,uQ.fileURLToPath)(r),t,void 0,e);if(u.exists)return u;let A=r;if(r=new URL(\"../package.json\",r),r.pathname===A.pathname)break}let o=(0,uQ.fileURLToPath)(r),a={pjsonPath:o,exists:!1,main:void 0,name:void 0,type:\"none\",exports:void 0,imports:void 0};return cQ.set(o,a),a}function MIt(t,e,r){throw new LIe(t,e&&(0,Oo.fileURLToPath)(new URL(\".\",e)),(0,Oo.fileURLToPath)(r))}function OIt(t,e,r,o){let a=`request is not a valid subpath for the \"${r?\"imports\":\"exports\"}\" resolution of ${(0,Oo.fileURLToPath)(e)}`;throw new Yq(t,a,o&&(0,Oo.fileURLToPath)(o))}function _B(t,e,r,o,a){throw typeof e==\"object\"&&e!==null?e=NB(e,null,\"\"):e=`${e}`,new MIe((0,Oo.fileURLToPath)(new URL(\".\",r)),t,e,o,a&&(0,Oo.fileURLToPath)(a))}var HIe=/(^|\\\\|\\/)((\\.|%2e)(\\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\\\|\\/|$)/i,qIe=/\\*/g;function UIt(t,e,r,o,a,n,u,A){if(e!==\"\"&&!n&&t[t.length-1]!==\"/\"&&_B(r,t,o,u,a),!dA(t,\"./\")){if(u&&!dA(t,\"../\")&&!dA(t,\"/\")){let I=!1;try{new URL(t),I=!0}catch{}if(!I)return n?qq(qIe,t,()=>e):t+e}_B(r,t,o,u,a)}Hq(HIe,_h(t,2))!==null&&_B(r,t,o,u,a);let p=new URL(t,o),h=p.pathname,E=new URL(\".\",o).pathname;if(dA(h,E)||_B(r,t,o,u,a),e===\"\")return p;if(Hq(HIe,e)!==null){let I=n?FIe(r,\"*\",()=>e):r+e;OIt(I,o,u,a)}return n?new URL(qq(qIe,p.href,()=>e)):new URL(e,p)}function _It(t){let e=+t;return`${e}`!==t?!1:e>=0&&e<4294967295}function lC(t,e,r,o,a,n,u,A){if(typeof e==\"string\")return UIt(e,r,o,t,a,n,u,A);if(_q(e)){if(e.length===0)return null;let p;for(let h=0;h<e.length;h++){let E=e[h],I;try{I=lC(t,E,r,o,a,n,u,A)}catch(v){if(p=v,v.code===\"ERR_INVALID_PACKAGE_TARGET\")continue;throw v}if(I!==void 0){if(I===null){p=null;continue}return I}}if(p==null)return p;throw p}else if(typeof e==\"object\"&&e!==null){let p=LB(e);for(let h=0;h<p.length;h++){let E=p[h];if(_It(E))throw new UB((0,Oo.fileURLToPath)(t),a,'\"exports\" cannot contain numeric property keys.')}for(let h=0;h<p.length;h++){let E=p[h];if(E===\"default\"||A.has(E)){let I=e[E],v=lC(t,I,r,o,a,n,u,A);if(v===void 0)continue;return v}}return}else if(e===null)return null;_B(o,e,t,u,a)}function GIe(t,e){let r=MB(t,\"*\"),o=MB(e,\"*\"),a=r===-1?t.length:r+1,n=o===-1?e.length:o+1;return a>n?-1:n>a||r===-1?1:o===-1||t.length>e.length?-1:e.length>t.length?1:0}function HIt(t,e,r){if(typeof t==\"string\"||_q(t))return!0;if(typeof t!=\"object\"||t===null)return!1;let o=LB(t),a=!1,n=0;for(let u=0;u<o.length;u++){let A=o[u],p=A===\"\"||A[0]!==\".\";if(n++===0)a=p;else if(a!==p)throw new UB((0,Oo.fileURLToPath)(e),r,`\"exports\" cannot contain some keys starting with '.' and some not. The exports object must either be an object of package subpath keys or an object of main entry condition name keys only.`)}return a}function Wq(t,e,r){throw new OIe((0,Oo.fileURLToPath)(new URL(\".\",e)),t,r&&(0,Oo.fileURLToPath)(r))}var jIe=new Set;function qIt(t,e,r){let o=(0,Oo.fileURLToPath)(e);jIe.has(o+\"|\"+t)||(jIe.add(o+\"|\"+t),process.emitWarning(`Use of deprecated trailing slash pattern mapping \"${t}\" in the \"exports\" field module resolution of the package at ${o}${r?` imported from ${(0,Oo.fileURLToPath)(r)}`:\"\"}. Mapping specifiers ending in \"/\" is no longer supported.`,\"DeprecationWarning\",\"DEP0155\"))}function YIe({packageJSONUrl:t,packageSubpath:e,exports:r,base:o,conditions:a}){if(HIt(r,t,o)&&(r={\".\":r}),nd(r,e)&&!jq(e,\"*\")&&!Uh(e,\"/\")){let p=r[e],h=lC(t,p,\"\",e,o,!1,!1,a);return h==null&&Wq(e,t,o),h}let n=\"\",u,A=LB(r);for(let p=0;p<A.length;p++){let h=A[p],E=MB(h,\"*\");if(E!==-1&&dA(e,_h(h,0,E))){Uh(e,\"/\")&&qIt(e,t,o);let I=_h(h,E+1);e.length>=h.length&&Uh(e,I)&&GIe(n,h)===1&&Gq(h,\"*\")===E&&(n=h,u=_h(e,E,e.length-I.length))}}if(n){let p=r[n],h=lC(t,p,u,n,o,!0,!1,a);return h==null&&Wq(e,t,o),h}Wq(e,t,o)}function WIe({name:t,base:e,conditions:r,readFileSyncFn:o}){if(t===\"#\"||dA(t,\"#/\")||Uh(t,\"/\")){let u=\"is not a valid internal imports specifier name\";throw new Yq(t,u,(0,Oo.fileURLToPath)(e))}let a,n=_Ie(e,o);if(n.exists){a=(0,Oo.pathToFileURL)(n.pjsonPath);let u=n.imports;if(u)if(nd(u,t)&&!jq(t,\"*\")){let A=lC(a,u[t],\"\",t,e,!1,!0,r);if(A!=null)return A}else{let A=\"\",p,h=LB(u);for(let E=0;E<h.length;E++){let I=h[E],v=MB(I,\"*\");if(v!==-1&&dA(t,_h(I,0,v))){let x=_h(I,v+1);t.length>=I.length&&Uh(t,x)&&GIe(A,I)===1&&Gq(I,\"*\")===v&&(A=I,p=_h(t,v,t.length-x.length))}}if(A){let E=u[A],I=lC(a,E,p,A,e,!0,!0,r);if(I!=null)return I}}}MIt(t,a,e)}Pt();var jIt=new Set([\"BUILTIN_NODE_RESOLUTION_FAILED\",\"MISSING_DEPENDENCY\",\"MISSING_PEER_DEPENDENCY\",\"QUALIFIED_PATH_RESOLUTION_FAILED\",\"UNDECLARED_DEPENDENCY\"]);function ts(t,e,r={},o){o??=jIt.has(t)?\"MODULE_NOT_FOUND\":t;let a={configurable:!0,writable:!0,enumerable:!1};return Object.defineProperties(new Error(e),{code:{...a,value:o},pnpCode:{...a,value:t},data:{...a,value:r}})}function cu(t){return ue.normalize(ue.fromPortablePath(t))}var JIe=Ze(VIe());function XIe(t){return GIt(),Vq[t]}var Vq;function GIt(){Vq||(Vq={\"--conditions\":[],...zIe(YIt()),...zIe(process.execArgv)})}function zIe(t){return(0,JIe.default)({\"--conditions\":[String],\"-C\":\"--conditions\"},{argv:t,permissive:!0})}function YIt(){let t=[],e=WIt(process.env.NODE_OPTIONS||\"\",t);return t.length,e}function WIt(t,e){let r=[],o=!1,a=!0;for(let n=0;n<t.length;++n){let u=t[n];if(u===\"\\\\\"&&o){if(n+1===t.length)return e.push(`invalid value for NODE_OPTIONS (invalid escape)\n`),r;u=t[++n]}else if(u===\" \"&&!o){a=!0;continue}else if(u==='\"'){o=!o;continue}a?(r.push(u),a=!1):r[r.length-1]+=u}return o&&e.push(`invalid value for NODE_OPTIONS (unterminated string)\n`),r}Pt();var[Ua,$f]=process.versions.node.split(\".\").map(t=>parseInt(t,10)),ZIe=Ua>19||Ua===19&&$f>=2||Ua===18&&$f>=13,xJt=Ua===20&&$f<6||Ua===19&&$f>=3,kJt=Ua>19||Ua===19&&$f>=6,QJt=Ua>=21||Ua===20&&$f>=10||Ua===18&&$f>=19,FJt=Ua>=21||Ua===20&&$f>=10||Ua===18&&$f>=20,RJt=Ua>=22;function $Ie(t){if(process.env.WATCH_REPORT_DEPENDENCIES&&process.send)if(t=t.map(e=>ue.fromPortablePath(zs.resolveVirtual(ue.toPortablePath(e)))),ZIe)process.send({\"watch:require\":t});else for(let e of t)process.send({\"watch:require\":e})}function Jq(t,e){let r=Number(process.env.PNP_ALWAYS_WARN_ON_FALLBACK)>0,o=Number(process.env.PNP_DEBUG_LEVEL),a=/^(?![a-zA-Z]:[\\\\/]|\\\\\\\\|\\.{0,2}(?:\\/|$))((?:node:)?(?:@[^/]+\\/)?[^/]+)\\/*(.*|)$/,n=/^(\\/|\\.{1,2}(\\/|$))/,u=/\\/$/,A=/^\\.{0,2}\\//,p={name:null,reference:null},h=[],E=new Set;if(t.enableTopLevelFallback===!0&&h.push(p),e.compatibilityMode!==!1)for(let Te of[\"react-scripts\",\"gatsby\"]){let Fe=t.packageRegistry.get(Te);if(Fe)for(let ke of Fe.keys()){if(ke===null)throw new Error(\"Assertion failed: This reference shouldn't be null\");h.push({name:Te,reference:ke})}}let{ignorePattern:I,packageRegistry:v,packageLocatorsByLocations:x}=t;function C(Te,Fe){return{fn:Te,args:Fe,error:null,result:null}}function R(Te){let Fe=process.stderr?.hasColors?.()??process.stdout.isTTY,ke=(et,Ue)=>`\\x1B[${et}m${Ue}\\x1B[0m`,Ye=Te.error;console.error(Ye?ke(\"31;1\",`\\u2716 ${Te.error?.message.replace(/\\n.*/s,\"\")}`):ke(\"33;1\",\"\\u203C Resolution\")),Te.args.length>0&&console.error();for(let et of Te.args)console.error(`  ${ke(\"37;1\",\"In \\u2190\")} ${(0,zq.inspect)(et,{colors:Fe,compact:!0})}`);Te.result&&(console.error(),console.error(`  ${ke(\"37;1\",\"Out \\u2192\")} ${(0,zq.inspect)(Te.result,{colors:Fe,compact:!0})}`));let be=new Error().stack.match(/(?<=^ +)at.*/gm)?.slice(2)??[];if(be.length>0){console.error();for(let et of be)console.error(`  ${ke(\"38;5;244\",et)}`)}console.error()}function L(Te,Fe){if(e.allowDebug===!1)return Fe;if(Number.isFinite(o)){if(o>=2)return(...ke)=>{let Ye=C(Te,ke);try{return Ye.result=Fe(...ke)}catch(be){throw Ye.error=be}finally{R(Ye)}};if(o>=1)return(...ke)=>{try{return Fe(...ke)}catch(Ye){let be=C(Te,ke);throw be.error=Ye,R(be),Ye}}}return Fe}function U(Te){let Fe=g(Te);if(!Fe)throw ts(\"INTERNAL\",\"Couldn't find a matching entry in the dependency tree for the specified parent (this is probably an internal error)\");return Fe}function z(Te){if(Te.name===null)return!0;for(let Fe of t.dependencyTreeRoots)if(Fe.name===Te.name&&Fe.reference===Te.reference)return!0;return!1}let te=new Set([\"node\",\"require\",...XIe(\"--conditions\")]);function ae(Te,Fe=te,ke){let Ye=Ae(V.join(Te,\"internal.js\"),{resolveIgnored:!0,includeDiscardFromLookup:!0});if(Ye===null)throw ts(\"INTERNAL\",`The locator that owns the \"${Te}\" path can't be found inside the dependency tree (this is probably an internal error)`);let{packageLocation:be}=U(Ye),et=V.join(be,dr.manifest);if(!e.fakeFs.existsSync(et))return null;let Ue=JSON.parse(e.fakeFs.readFileSync(et,\"utf8\"));if(Ue.exports==null)return null;let S=V.contains(be,Te);if(S===null)throw ts(\"INTERNAL\",\"unqualifiedPath doesn't contain the packageLocation (this is probably an internal error)\");S!==\".\"&&!A.test(S)&&(S=`./${S}`);try{let w=YIe({packageJSONUrl:(0,id.pathToFileURL)(ue.fromPortablePath(et)),packageSubpath:S,exports:Ue.exports,base:ke?(0,id.pathToFileURL)(ue.fromPortablePath(ke)):null,conditions:Fe});return ue.toPortablePath((0,id.fileURLToPath)(w))}catch(w){throw ts(\"EXPORTS_RESOLUTION_FAILED\",w.message,{unqualifiedPath:cu(Te),locator:Ye,pkgJson:Ue,subpath:cu(S),conditions:Fe},w.code)}}function le(Te,Fe,{extensions:ke}){let Ye;try{Fe.push(Te),Ye=e.fakeFs.statSync(Te)}catch{}if(Ye&&!Ye.isDirectory())return e.fakeFs.realpathSync(Te);if(Ye&&Ye.isDirectory()){let be;try{be=JSON.parse(e.fakeFs.readFileSync(V.join(Te,dr.manifest),\"utf8\"))}catch{}let et;if(be&&be.main&&(et=V.resolve(Te,be.main)),et&&et!==Te){let Ue=le(et,Fe,{extensions:ke});if(Ue!==null)return Ue}}for(let be=0,et=ke.length;be<et;be++){let Ue=`${Te}${ke[be]}`;if(Fe.push(Ue),e.fakeFs.existsSync(Ue))return Ue}if(Ye&&Ye.isDirectory())for(let be=0,et=ke.length;be<et;be++){let Ue=V.format({dir:Te,name:\"index\",ext:ke[be]});if(Fe.push(Ue),e.fakeFs.existsSync(Ue))return Ue}return null}function ce(Te){let Fe=new ep.Module(Te,null);return Fe.filename=Te,Fe.paths=ep.Module._nodeModulePaths(Te),Fe}function Ce(Te,Fe){return Fe.endsWith(\"/\")&&(Fe=V.join(Fe,\"internal.js\")),ep.Module._resolveFilename(ue.fromPortablePath(Te),ce(ue.fromPortablePath(Fe)),!1,{plugnplay:!1})}function de(Te){if(I===null)return!1;let Fe=V.contains(t.basePath,Te);return Fe===null?!1:!!I.test(Fe.replace(/\\/$/,\"\"))}let Be={std:3,resolveVirtual:1,getAllLocators:1},Ee=p;function g({name:Te,reference:Fe}){let ke=v.get(Te);if(!ke)return null;let Ye=ke.get(Fe);return Ye||null}function me({name:Te,reference:Fe}){let ke=[];for(let[Ye,be]of v)if(Ye!==null)for(let[et,Ue]of be)et===null||Ue.packageDependencies.get(Te)!==Fe||Ye===Te&&et===Fe||ke.push({name:Ye,reference:et});return ke}function we(Te,Fe){let ke=new Map,Ye=new Set,be=Ue=>{let S=JSON.stringify(Ue.name);if(Ye.has(S))return;Ye.add(S);let w=me(Ue);for(let b of w)if(U(b).packagePeers.has(Te))be(b);else{let F=ke.get(b.name);typeof F>\"u\"&&ke.set(b.name,F=new Set),F.add(b.reference)}};be(Fe);let et=[];for(let Ue of[...ke.keys()].sort())for(let S of[...ke.get(Ue)].sort())et.push({name:Ue,reference:S});return et}function Ae(Te,{resolveIgnored:Fe=!1,includeDiscardFromLookup:ke=!1}={}){if(de(Te)&&!Fe)return null;let Ye=V.relative(t.basePath,Te);Ye.match(n)||(Ye=`./${Ye}`),Ye.endsWith(\"/\")||(Ye=`${Ye}/`);do{let be=x.get(Ye);if(typeof be>\"u\"||be.discardFromLookup&&!ke){Ye=Ye.substring(0,Ye.lastIndexOf(\"/\",Ye.length-2)+1);continue}return be.locator}while(Ye!==\"\");return null}function ne(Te){try{return e.fakeFs.readFileSync(ue.toPortablePath(Te),\"utf8\")}catch(Fe){if(Fe.code===\"ENOENT\")return;throw Fe}}function Z(Te,Fe,{considerBuiltins:ke=!0}={}){if(Te.startsWith(\"#\"))throw new Error(\"resolveToUnqualified can not handle private import mappings\");if(Te===\"pnpapi\")return ue.toPortablePath(e.pnpapiResolution);if(ke&&(0,ep.isBuiltin)(Te))return null;let Ye=cu(Te),be=Fe&&cu(Fe);if(Fe&&de(Fe)&&(!V.isAbsolute(Te)||Ae(Te)===null)){let S=Ce(Te,Fe);if(S===!1)throw ts(\"BUILTIN_NODE_RESOLUTION_FAILED\",`The builtin node resolution algorithm was unable to resolve the requested module (it didn't go through the pnp resolver because the issuer was explicitely ignored by the regexp)\n\nRequire request: \"${Ye}\"\nRequired by: ${be}\n`,{request:Ye,issuer:be});return ue.toPortablePath(S)}let et,Ue=Te.match(a);if(Ue){if(!Fe)throw ts(\"API_ERROR\",\"The resolveToUnqualified function must be called with a valid issuer when the path isn't a builtin nor absolute\",{request:Ye,issuer:be});let[,S,w]=Ue,b=Ae(Fe);if(!b){let Re=Ce(Te,Fe);if(Re===!1)throw ts(\"BUILTIN_NODE_RESOLUTION_FAILED\",`The builtin node resolution algorithm was unable to resolve the requested module (it didn't go through the pnp resolver because the issuer doesn't seem to be part of the Yarn-managed dependency tree).\n\nRequire path: \"${Ye}\"\nRequired by: ${be}\n`,{request:Ye,issuer:be});return ue.toPortablePath(Re)}let F=U(b).packageDependencies.get(S),J=null;if(F==null&&b.name!==null){let Re=t.fallbackExclusionList.get(b.name);if(!Re||!Re.has(b.reference)){for(let dt=0,jt=h.length;dt<jt;++dt){let bt=U(h[dt]).packageDependencies.get(S);if(bt!=null){r?J=bt:F=bt;break}}if(t.enableTopLevelFallback&&F==null&&J===null){let dt=t.fallbackPool.get(S);dt!=null&&(J=dt)}}}let X=null;if(F===null)if(z(b))X=ts(\"MISSING_PEER_DEPENDENCY\",`Your application tried to access ${S} (a peer dependency); this isn't allowed as there is no ancestor to satisfy the requirement. Use a devDependency if needed.\n\nRequired package: ${S}${S!==Ye?` (via \"${Ye}\")`:\"\"}\nRequired by: ${be}\n`,{request:Ye,issuer:be,dependencyName:S});else{let Re=we(S,b);Re.every(at=>z(at))?X=ts(\"MISSING_PEER_DEPENDENCY\",`${b.name} tried to access ${S} (a peer dependency) but it isn't provided by your application; this makes the require call ambiguous and unsound.\n\nRequired package: ${S}${S!==Ye?` (via \"${Ye}\")`:\"\"}\nRequired by: ${b.name}@${b.reference} (via ${be})\n${Re.map(at=>`Ancestor breaking the chain: ${at.name}@${at.reference}\n`).join(\"\")}\n`,{request:Ye,issuer:be,issuerLocator:Object.assign({},b),dependencyName:S,brokenAncestors:Re}):X=ts(\"MISSING_PEER_DEPENDENCY\",`${b.name} tried to access ${S} (a peer dependency) but it isn't provided by its ancestors; this makes the require call ambiguous and unsound.\n\nRequired package: ${S}${S!==Ye?` (via \"${Ye}\")`:\"\"}\nRequired by: ${b.name}@${b.reference} (via ${be})\n\n${Re.map(at=>`Ancestor breaking the chain: ${at.name}@${at.reference}\n`).join(\"\")}\n`,{request:Ye,issuer:be,issuerLocator:Object.assign({},b),dependencyName:S,brokenAncestors:Re})}else F===void 0&&(!ke&&(0,ep.isBuiltin)(Te)?z(b)?X=ts(\"UNDECLARED_DEPENDENCY\",`Your application tried to access ${S}. While this module is usually interpreted as a Node builtin, your resolver is running inside a non-Node resolution context where such builtins are ignored. Since ${S} isn't otherwise declared in your dependencies, this makes the require call ambiguous and unsound.\n\nRequired package: ${S}${S!==Ye?` (via \"${Ye}\")`:\"\"}\nRequired by: ${be}\n`,{request:Ye,issuer:be,dependencyName:S}):X=ts(\"UNDECLARED_DEPENDENCY\",`${b.name} tried to access ${S}. While this module is usually interpreted as a Node builtin, your resolver is running inside a non-Node resolution context where such builtins are ignored. Since ${S} isn't otherwise declared in ${b.name}'s dependencies, this makes the require call ambiguous and unsound.\n\nRequired package: ${S}${S!==Ye?` (via \"${Ye}\")`:\"\"}\nRequired by: ${be}\n`,{request:Ye,issuer:be,issuerLocator:Object.assign({},b),dependencyName:S}):z(b)?X=ts(\"UNDECLARED_DEPENDENCY\",`Your application tried to access ${S}, but it isn't declared in your dependencies; this makes the require call ambiguous and unsound.\n\nRequired package: ${S}${S!==Ye?` (via \"${Ye}\")`:\"\"}\nRequired by: ${be}\n`,{request:Ye,issuer:be,dependencyName:S}):X=ts(\"UNDECLARED_DEPENDENCY\",`${b.name} tried to access ${S}, but it isn't declared in its dependencies; this makes the require call ambiguous and unsound.\n\nRequired package: ${S}${S!==Ye?` (via \"${Ye}\")`:\"\"}\nRequired by: ${b.name}@${b.reference} (via ${be})\n`,{request:Ye,issuer:be,issuerLocator:Object.assign({},b),dependencyName:S}));if(F==null){if(J===null||X===null)throw X||new Error(\"Assertion failed: Expected an error to have been set\");F=J;let Re=X.message.replace(/\\n.*/g,\"\");X.message=Re,!E.has(Re)&&o!==0&&(E.add(Re),process.emitWarning(X))}let $=Array.isArray(F)?{name:F[0],reference:F[1]}:{name:S,reference:F},ie=U($);if(!ie.packageLocation)throw ts(\"MISSING_DEPENDENCY\",`A dependency seems valid but didn't get installed for some reason. This might be caused by a partial install, such as dev vs prod.\n\nRequired package: ${$.name}@${$.reference}${$.name!==Ye?` (via \"${Ye}\")`:\"\"}\nRequired by: ${b.name}@${b.reference} (via ${be})\n`,{request:Ye,issuer:be,dependencyLocator:Object.assign({},$)});let Se=ie.packageLocation;w?et=V.join(Se,w):et=Se}else if(V.isAbsolute(Te))et=V.normalize(Te);else{if(!Fe)throw ts(\"API_ERROR\",\"The resolveToUnqualified function must be called with a valid issuer when the path isn't a builtin nor absolute\",{request:Ye,issuer:be});let S=V.resolve(Fe);Fe.match(u)?et=V.normalize(V.join(S,Te)):et=V.normalize(V.join(V.dirname(S),Te))}return V.normalize(et)}function xe(Te,Fe,ke=te,Ye){if(n.test(Te))return Fe;let be=ae(Fe,ke,Ye);return be?V.normalize(be):Fe}function Ne(Te,{extensions:Fe=Object.keys(ep.Module._extensions)}={}){let ke=[],Ye=le(Te,ke,{extensions:Fe});if(Ye)return V.normalize(Ye);{$Ie(ke.map(Ue=>ue.fromPortablePath(Ue)));let be=cu(Te),et=Ae(Te);if(et){let{packageLocation:Ue}=U(et),S=!0;try{e.fakeFs.accessSync(Ue)}catch(w){if(w?.code===\"ENOENT\")S=!1;else{let b=(w?.message??w??\"empty exception thrown\").replace(/^[A-Z]/,y=>y.toLowerCase());throw ts(\"QUALIFIED_PATH_RESOLUTION_FAILED\",`Required package exists but could not be accessed (${b}).\n\nMissing package: ${et.name}@${et.reference}\nExpected package location: ${cu(Ue)}\n`,{unqualifiedPath:be,extensions:Fe})}}if(!S){let w=Ue.includes(\"/unplugged/\")?\"Required unplugged package missing from disk. This may happen when switching branches without running installs (unplugged packages must be fully materialized on disk to work).\":\"Required package missing from disk. If you keep your packages inside your repository then restarting the Node process may be enough. Otherwise, try to run an install first.\";throw ts(\"QUALIFIED_PATH_RESOLUTION_FAILED\",`${w}\n\nMissing package: ${et.name}@${et.reference}\nExpected package location: ${cu(Ue)}\n`,{unqualifiedPath:be,extensions:Fe})}}throw ts(\"QUALIFIED_PATH_RESOLUTION_FAILED\",`Qualified path resolution failed: we looked for the following paths, but none could be accessed.\n\nSource path: ${be}\n${ke.map(Ue=>`Not found: ${cu(Ue)}\n`).join(\"\")}`,{unqualifiedPath:be,extensions:Fe})}}function ht(Te,Fe,ke){if(!Fe)throw new Error(\"Assertion failed: An issuer is required to resolve private import mappings\");let Ye=WIe({name:Te,base:(0,id.pathToFileURL)(ue.fromPortablePath(Fe)),conditions:ke.conditions??te,readFileSyncFn:ne});if(Ye instanceof URL)return Ne(ue.toPortablePath((0,id.fileURLToPath)(Ye)),{extensions:ke.extensions});if(Ye.startsWith(\"#\"))throw new Error(\"Mapping from one private import to another isn't allowed\");return H(Ye,Fe,ke)}function H(Te,Fe,ke={}){try{if(Te.startsWith(\"#\"))return ht(Te,Fe,ke);let{considerBuiltins:Ye,extensions:be,conditions:et}=ke,Ue=Z(Te,Fe,{considerBuiltins:Ye});if(Te===\"pnpapi\")return Ue;if(Ue===null)return null;let S=()=>Fe!==null?de(Fe):!1,w=(!Ye||!(0,ep.isBuiltin)(Te))&&!S()?xe(Te,Ue,et,Fe):Ue;return Ne(w,{extensions:be})}catch(Ye){throw Object.hasOwn(Ye,\"pnpCode\")&&Object.assign(Ye.data,{request:cu(Te),issuer:Fe&&cu(Fe)}),Ye}}function rt(Te){let Fe=V.normalize(Te),ke=zs.resolveVirtual(Fe);return ke!==Fe?ke:null}return{VERSIONS:Be,topLevel:Ee,getLocator:(Te,Fe)=>Array.isArray(Fe)?{name:Fe[0],reference:Fe[1]}:{name:Te,reference:Fe},getDependencyTreeRoots:()=>[...t.dependencyTreeRoots],getAllLocators(){let Te=[];for(let[Fe,ke]of v)for(let Ye of ke.keys())Fe!==null&&Ye!==null&&Te.push({name:Fe,reference:Ye});return Te},getPackageInformation:Te=>{let Fe=g(Te);if(Fe===null)return null;let ke=ue.fromPortablePath(Fe.packageLocation);return{...Fe,packageLocation:ke}},findPackageLocator:Te=>Ae(ue.toPortablePath(Te)),resolveToUnqualified:L(\"resolveToUnqualified\",(Te,Fe,ke)=>{let Ye=Fe!==null?ue.toPortablePath(Fe):null,be=Z(ue.toPortablePath(Te),Ye,ke);return be===null?null:ue.fromPortablePath(be)}),resolveUnqualified:L(\"resolveUnqualified\",(Te,Fe)=>ue.fromPortablePath(Ne(ue.toPortablePath(Te),Fe))),resolveRequest:L(\"resolveRequest\",(Te,Fe,ke)=>{let Ye=Fe!==null?ue.toPortablePath(Fe):null,be=H(ue.toPortablePath(Te),Ye,ke);return be===null?null:ue.fromPortablePath(be)}),resolveVirtual:L(\"resolveVirtual\",Te=>{let Fe=rt(ue.toPortablePath(Te));return Fe!==null?ue.fromPortablePath(Fe):null})}}Pt();var e1e=(t,e,r)=>{let o=TB(t),a=Uq(o,{basePath:e}),n=ue.join(e,dr.pnpCjs);return Jq(a,{fakeFs:r,pnpapiResolution:n})};var Zq=Ze(r1e());qt();var mA={};Vt(mA,{checkManifestCompatibility:()=>n1e,extractBuildRequest:()=>AQ,getExtractHint:()=>$q,hasBindingGyp:()=>ej});Ge();Pt();function n1e(t){return G.isPackageCompatible(t,Xi.getArchitectureSet())}function AQ(t,e,r,{configuration:o}){let a=[];for(let n of[\"preinstall\",\"install\",\"postinstall\"])e.manifest.scripts.has(n)&&a.push({type:0,script:n});return!e.manifest.scripts.has(\"install\")&&e.misc.hasBindingGyp&&a.push({type:1,script:\"node-gyp rebuild\"}),a.length===0?null:t.linkType!==\"HARD\"?{skipped:!0,explain:n=>n.reportWarningOnce(6,`${G.prettyLocator(o,t)} lists build scripts, but is referenced through a soft link. Soft links don't support build scripts, so they'll be ignored.`)}:r&&r.built===!1?{skipped:!0,explain:n=>n.reportInfoOnce(5,`${G.prettyLocator(o,t)} lists build scripts, but its build has been explicitly disabled through configuration.`)}:!o.get(\"enableScripts\")&&!r.built?{skipped:!0,explain:n=>n.reportWarningOnce(4,`${G.prettyLocator(o,t)} lists build scripts, but all build scripts have been disabled.`)}:n1e(t)?{skipped:!1,directives:a}:{skipped:!0,explain:n=>n.reportWarningOnce(76,`${G.prettyLocator(o,t)} The ${Xi.getArchitectureName()} architecture is incompatible with this package, build skipped.`)}}var VIt=new Set([\".exe\",\".bin\",\".h\",\".hh\",\".hpp\",\".c\",\".cc\",\".cpp\",\".java\",\".jar\",\".node\"]);function $q(t){return t.packageFs.getExtractHint({relevantExtensions:VIt})}function ej(t){let e=V.join(t.prefixPath,\"binding.gyp\");return t.packageFs.existsSync(e)}var jB={};Vt(jB,{getUnpluggedPath:()=>qB});Ge();Pt();function qB(t,{configuration:e}){return V.resolve(e.get(\"pnpUnpluggedFolder\"),G.slugifyLocator(t))}var zIt=new Set([G.makeIdent(null,\"open\").identHash,G.makeIdent(null,\"opn\").identHash]),Hh=class{constructor(){this.mode=\"strict\";this.pnpCache=new Map}getCustomDataKey(){return JSON.stringify({name:\"PnpLinker\",version:2})}supportsPackage(e,r){return this.isEnabled(r)}async findPackageLocation(e,r){if(!this.isEnabled(r))throw new Error(\"Assertion failed: Expected the PnP linker to be enabled\");let o=qh(r.project).cjs;if(!oe.existsSync(o))throw new st(`The project in ${pe.pretty(r.project.configuration,`${r.project.cwd}/package.json`,pe.Type.PATH)} doesn't seem to have been installed - running an install there might help`);let a=He.getFactoryWithDefault(this.pnpCache,o,()=>He.dynamicRequire(o,{cachingStrategy:He.CachingStrategy.FsTime})),n={name:G.stringifyIdent(e),reference:e.reference},u=a.getPackageInformation(n);if(!u)throw new st(`Couldn't find ${G.prettyLocator(r.project.configuration,e)} in the currently installed PnP map - running an install might help`);return ue.toPortablePath(u.packageLocation)}async findPackageLocator(e,r){if(!this.isEnabled(r))return null;let o=qh(r.project).cjs;if(!oe.existsSync(o))return null;let n=He.getFactoryWithDefault(this.pnpCache,o,()=>He.dynamicRequire(o,{cachingStrategy:He.CachingStrategy.FsTime})).findPackageLocator(ue.fromPortablePath(e));return n?G.makeLocator(G.parseIdent(n.name),n.reference):null}makeInstaller(e){return new sd(e)}isEnabled(e){return!(e.project.configuration.get(\"nodeLinker\")!==\"pnp\"||e.project.configuration.get(\"pnpMode\")!==this.mode)}},sd=class{constructor(e){this.opts=e;this.mode=\"strict\";this.asyncActions=new He.AsyncActions(10);this.packageRegistry=new Map;this.virtualTemplates=new Map;this.isESMLoaderRequired=!1;this.customData={store:new Map};this.unpluggedPaths=new Set;this.opts=e}attachCustomData(e){this.customData=e}async installPackage(e,r,o){let a=G.stringifyIdent(e),n=e.reference,u=!!this.opts.project.tryWorkspaceByLocator(e),A=G.isVirtualLocator(e),p=e.peerDependencies.size>0&&!A,h=!p&&!u,E=!p&&e.linkType!==\"SOFT\",I,v;if(h||E){let te=A?G.devirtualizeLocator(e):e;I=this.customData.store.get(te.locatorHash),typeof I>\"u\"&&(I=await JIt(r),e.linkType===\"HARD\"&&this.customData.store.set(te.locatorHash,I)),I.manifest.type===\"module\"&&(this.isESMLoaderRequired=!0),v=this.opts.project.getDependencyMeta(te,e.version)}let x=h?AQ(e,I,v,{configuration:this.opts.project.configuration}):null,C=E?await this.unplugPackageIfNeeded(e,I,r,v,o):r.packageFs;if(V.isAbsolute(r.prefixPath))throw new Error(`Assertion failed: Expected the prefix path (${r.prefixPath}) to be relative to the parent`);let R=V.resolve(C.getRealPath(),r.prefixPath),L=tj(this.opts.project.cwd,R),U=new Map,z=new Set;if(A){for(let te of e.peerDependencies.values())U.set(G.stringifyIdent(te),null),z.add(G.stringifyIdent(te));if(!u){let te=G.devirtualizeLocator(e);this.virtualTemplates.set(te.locatorHash,{location:tj(this.opts.project.cwd,zs.resolveVirtual(R)),locator:te})}}return He.getMapWithDefault(this.packageRegistry,a).set(n,{packageLocation:L,packageDependencies:U,packagePeers:z,linkType:e.linkType,discardFromLookup:r.discardFromLookup||!1}),{packageLocation:R,buildRequest:x}}async attachInternalDependencies(e,r){let o=this.getPackageInformation(e);for(let[a,n]of r){let u=G.areIdentsEqual(a,n)?n.reference:[G.stringifyIdent(n),n.reference];o.packageDependencies.set(G.stringifyIdent(a),u)}}async attachExternalDependents(e,r){for(let o of r)this.getDiskInformation(o).packageDependencies.set(G.stringifyIdent(e),e.reference)}async finalizeInstall(){if(this.opts.project.configuration.get(\"pnpMode\")!==this.mode)return;let e=qh(this.opts.project);if(this.isEsmEnabled()||await oe.removePromise(e.esmLoader),this.opts.project.configuration.get(\"nodeLinker\")!==\"pnp\"){await oe.removePromise(e.cjs),await oe.removePromise(e.data),await oe.removePromise(e.esmLoader),await oe.removePromise(this.opts.project.configuration.get(\"pnpUnpluggedFolder\"));return}for(let{locator:E,location:I}of this.virtualTemplates.values())He.getMapWithDefault(this.packageRegistry,G.stringifyIdent(E)).set(E.reference,{packageLocation:I,packageDependencies:new Map,packagePeers:new Set,linkType:\"SOFT\",discardFromLookup:!1});this.packageRegistry.set(null,new Map([[null,this.getPackageInformation(this.opts.project.topLevelWorkspace.anchoredLocator)]]));let r=this.opts.project.configuration.get(\"pnpFallbackMode\"),o=this.opts.project.workspaces.map(({anchoredLocator:E})=>({name:G.stringifyIdent(E),reference:E.reference})),a=r!==\"none\",n=[],u=new Map,A=He.buildIgnorePattern([\".yarn/sdks/**\",...this.opts.project.configuration.get(\"pnpIgnorePatterns\")]),p=this.packageRegistry,h=this.opts.project.configuration.get(\"pnpShebang\");if(r===\"dependencies-only\")for(let E of this.opts.project.storedPackages.values())this.opts.project.tryWorkspaceByLocator(E)&&n.push({name:G.stringifyIdent(E),reference:E.reference});return await this.asyncActions.wait(),await this.finalizeInstallWithPnp({dependencyTreeRoots:o,enableTopLevelFallback:a,fallbackExclusionList:n,fallbackPool:u,ignorePattern:A,packageRegistry:p,shebang:h}),{customData:this.customData}}async transformPnpSettings(e){}isEsmEnabled(){if(this.opts.project.configuration.sources.has(\"pnpEnableEsmLoader\"))return this.opts.project.configuration.get(\"pnpEnableEsmLoader\");if(this.isESMLoaderRequired)return!0;for(let e of this.opts.project.workspaces)if(e.manifest.type===\"module\")return!0;return!1}async finalizeInstallWithPnp(e){let r=qh(this.opts.project),o=await this.locateNodeModules(e.ignorePattern);if(o.length>0){this.opts.report.reportWarning(31,\"One or more node_modules have been detected and will be removed. This operation may take some time.\");for(let n of o)await oe.removePromise(n)}if(await this.transformPnpSettings(e),this.opts.project.configuration.get(\"pnpEnableInlining\")){let n=kIe(e);await oe.changeFilePromise(r.cjs,n,{automaticNewlines:!0,mode:493}),await oe.removePromise(r.data)}else{let{dataFile:n,loaderFile:u}=QIe(e);await oe.changeFilePromise(r.cjs,u,{automaticNewlines:!0,mode:493}),await oe.changeFilePromise(r.data,n,{automaticNewlines:!0,mode:420})}this.isEsmEnabled()&&(this.opts.report.reportWarning(0,\"ESM support for PnP uses the experimental loader API and is therefore experimental\"),await oe.changeFilePromise(r.esmLoader,(0,Zq.default)(),{automaticNewlines:!0,mode:420}));let a=this.opts.project.configuration.get(\"pnpUnpluggedFolder\");if(this.unpluggedPaths.size===0)await oe.removePromise(a);else for(let n of await oe.readdirPromise(a)){let u=V.resolve(a,n);this.unpluggedPaths.has(u)||await oe.removePromise(u)}}async locateNodeModules(e){let r=[],o=e?new RegExp(e):null;for(let a of this.opts.project.workspaces){let n=V.join(a.cwd,\"node_modules\");if(o&&o.test(V.relative(this.opts.project.cwd,a.cwd))||!oe.existsSync(n))continue;let u=await oe.readdirPromise(n,{withFileTypes:!0}),A=u.filter(p=>!p.isDirectory()||p.name===\".bin\"||!p.name.startsWith(\".\"));if(A.length===u.length)r.push(n);else for(let p of A)r.push(V.join(n,p.name))}return r}async unplugPackageIfNeeded(e,r,o,a,n){return this.shouldBeUnplugged(e,r,a)?this.unplugPackage(e,o,n):o.packageFs}shouldBeUnplugged(e,r,o){return typeof o.unplugged<\"u\"?o.unplugged:zIt.has(e.identHash)||e.conditions!=null?!0:r.manifest.preferUnplugged!==null?r.manifest.preferUnplugged:!!(AQ(e,r,o,{configuration:this.opts.project.configuration})?.skipped===!1||r.misc.extractHint)}async unplugPackage(e,r,o){let a=qB(e,{configuration:this.opts.project.configuration});return this.opts.project.disabledLocators.has(e.locatorHash)?new Hu(a,{baseFs:r.packageFs,pathUtils:V}):(this.unpluggedPaths.add(a),o.holdFetchResult(this.asyncActions.set(e.locatorHash,async()=>{let n=V.join(a,r.prefixPath,\".ready\");await oe.existsPromise(n)||(this.opts.project.storedBuildState.delete(e.locatorHash),await oe.mkdirPromise(a,{recursive:!0}),await oe.copyPromise(a,It.dot,{baseFs:r.packageFs,overwrite:!1}),await oe.writeFilePromise(n,\"\"))})),new gn(a))}getPackageInformation(e){let r=G.stringifyIdent(e),o=e.reference,a=this.packageRegistry.get(r);if(!a)throw new Error(`Assertion failed: The package information store should have been available (for ${G.prettyIdent(this.opts.project.configuration,e)})`);let n=a.get(o);if(!n)throw new Error(`Assertion failed: The package information should have been available (for ${G.prettyLocator(this.opts.project.configuration,e)})`);return n}getDiskInformation(e){let r=He.getMapWithDefault(this.packageRegistry,\"@@disk\"),o=tj(this.opts.project.cwd,e);return He.getFactoryWithDefault(r,o,()=>({packageLocation:o,packageDependencies:new Map,packagePeers:new Set,linkType:\"SOFT\",discardFromLookup:!1}))}};function tj(t,e){let r=V.relative(t,e);return r.match(/^\\.{0,2}\\//)||(r=`./${r}`),r.replace(/\\/?$/,\"/\")}async function JIt(t){let e=await Ut.tryFind(t.prefixPath,{baseFs:t.packageFs})??new Ut,r=new Set([\"preinstall\",\"install\",\"postinstall\"]);for(let o of e.scripts.keys())r.has(o)||e.scripts.delete(o);return{manifest:{scripts:e.scripts,preferUnplugged:e.preferUnplugged,type:e.type},misc:{extractHint:$q(t),hasBindingGyp:ej(t)}}}Ge();Ge();qt();var i1e=Ze($o());var cC=class extends ut{constructor(){super(...arguments);this.all=ge.Boolean(\"-A,--all\",!1,{description:\"Unplug direct dependencies from the entire project\"});this.recursive=ge.Boolean(\"-R,--recursive\",!1,{description:\"Unplug both direct and transitive dependencies\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.patterns=ge.Rest()}static{this.paths=[[\"unplug\"]]}static{this.usage=it.Usage({description:\"force the unpacking of a list of packages\",details:\"\\n      This command will add the selectors matching the specified patterns to the list of packages that must be unplugged when installed.\\n\\n      A package being unplugged means that instead of being referenced directly through its archive, it will be unpacked at install time in the directory configured via `pnpUnpluggedFolder`. Note that unpacking packages this way is generally not recommended because it'll make it harder to store your packages within the repository. However, it's a good approach to quickly and safely debug some packages, and can even sometimes be required depending on the context (for example when the package contains shellscripts).\\n\\n      Running the command will set a persistent flag inside your top-level `package.json`, in the `dependenciesMeta` field. As such, to undo its effects, you'll need to revert the changes made to the manifest and run `yarn install` to apply the modification.\\n\\n      By default, only direct dependencies from the current workspace are affected. If `-A,--all` is set, direct dependencies from the entire project are affected. Using the `-R,--recursive` flag will affect transitive dependencies as well as direct ones.\\n\\n      This command accepts glob patterns inside the scope and name components (not the range). Make sure to escape the patterns to prevent your own shell from trying to expand them.\\n    \",examples:[[\"Unplug the lodash dependency from the active workspace\",\"yarn unplug lodash\"],[\"Unplug all instances of lodash referenced by any workspace\",\"yarn unplug lodash -A\"],[\"Unplug all instances of lodash referenced by the active workspace and its dependencies\",\"yarn unplug lodash -R\"],[\"Unplug all instances of lodash, anywhere\",\"yarn unplug lodash -AR\"],[\"Unplug one specific version of lodash\",\"yarn unplug lodash@1.2.3\"],[\"Unplug all packages with the `@babel` scope\",\"yarn unplug '@babel/*'\"],[\"Unplug all packages (only for testing, not recommended)\",\"yarn unplug -R '*'\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(!a)throw new sr(o.cwd,this.context.cwd);if(r.get(\"nodeLinker\")!==\"pnp\")throw new st(\"This command can only be used if the `nodeLinker` option is set to `pnp`\");await o.restoreInstallState();let u=new Set(this.patterns),A=this.patterns.map(x=>{let C=G.parseDescriptor(x),R=C.range!==\"unknown\"?C:G.makeDescriptor(C,\"*\");if(!Lr.validRange(R.range))throw new st(`The range of the descriptor patterns must be a valid semver range (${G.prettyDescriptor(r,R)})`);return L=>{let U=G.stringifyIdent(L);return!i1e.default.isMatch(U,G.stringifyIdent(R))||L.version&&!Lr.satisfiesWithPrereleases(L.version,R.range)?!1:(u.delete(x),!0)}}),p=()=>{let x=[];for(let C of o.storedPackages.values())!o.tryWorkspaceByLocator(C)&&!G.isVirtualLocator(C)&&A.some(R=>R(C))&&x.push(C);return x},h=x=>{let C=new Set,R=[],L=(U,z)=>{if(C.has(U.locatorHash))return;let te=!!o.tryWorkspaceByLocator(U);if(!(z>0&&!this.recursive&&te)&&(C.add(U.locatorHash),!o.tryWorkspaceByLocator(U)&&A.some(ae=>ae(U))&&R.push(U),!(z>0&&!this.recursive)))for(let ae of U.dependencies.values()){let le=o.storedResolutions.get(ae.descriptorHash);if(!le)throw new Error(\"Assertion failed: The resolution should have been registered\");let ce=o.storedPackages.get(le);if(!ce)throw new Error(\"Assertion failed: The package should have been registered\");L(ce,z+1)}};for(let U of x)L(U.anchoredPackage,0);return R},E,I;if(this.all&&this.recursive?(E=p(),I=\"the project\"):this.all?(E=h(o.workspaces),I=\"any workspace\"):(E=h([a]),I=\"this workspace\"),u.size>1)throw new st(`Patterns ${pe.prettyList(r,u,pe.Type.CODE)} don't match any packages referenced by ${I}`);if(u.size>0)throw new st(`Pattern ${pe.prettyList(r,u,pe.Type.CODE)} doesn't match any packages referenced by ${I}`);E=He.sortMap(E,x=>G.stringifyLocator(x));let v=await Rt.start({configuration:r,stdout:this.context.stdout,json:this.json},async x=>{for(let C of E){let R=C.version??\"unknown\",L=o.topLevelWorkspace.manifest.ensureDependencyMeta(G.makeDescriptor(C,R));L.unplugged=!0,x.reportInfo(0,`Will unpack ${G.prettyLocator(r,C)} to ${pe.pretty(r,qB(C,{configuration:r}),pe.Type.PATH)}`),x.reportJson({locator:G.stringifyLocator(C),version:R})}await o.topLevelWorkspace.persistManifest(),this.json||x.reportSeparator()});return v.hasErrors()?v.exitCode():await o.installWithNewReport({json:this.json,stdout:this.context.stdout},{cache:n})}};var qh=t=>({cjs:V.join(t.cwd,dr.pnpCjs),data:V.join(t.cwd,dr.pnpData),esmLoader:V.join(t.cwd,dr.pnpEsmLoader)}),o1e=t=>/\\s/.test(t)?JSON.stringify(t):t;async function XIt(t,e,r){let o=/\\s*--require\\s+\\S*\\.pnp\\.c?js\\s*/g,a=/\\s*--experimental-loader\\s+\\S*\\.pnp\\.loader\\.mjs\\s*/,n=(e.NODE_OPTIONS??\"\").replace(o,\" \").replace(a,\" \").trim();if(t.configuration.get(\"nodeLinker\")!==\"pnp\"){e.NODE_OPTIONS=n||void 0;return}let u=qh(t),A=`--require ${o1e(ue.fromPortablePath(u.cjs))}`;oe.existsSync(u.esmLoader)&&(A=`${A} --experimental-loader ${(0,s1e.pathToFileURL)(ue.fromPortablePath(u.esmLoader)).href}`),oe.existsSync(u.cjs)&&(e.NODE_OPTIONS=n?`${A} ${n}`:A)}async function ZIt(t,e){let r=qh(t);e(r.cjs),e(r.data),e(r.esmLoader),e(t.configuration.get(\"pnpUnpluggedFolder\"))}var $It={hooks:{populateYarnPaths:ZIt,setupScriptEnvironment:XIt},configuration:{nodeLinker:{description:'The linker used for installing Node packages, one of: \"pnp\", \"pnpm\", or \"node-modules\"',type:\"STRING\",default:\"pnp\"},winLinkType:{description:\"Whether Yarn should use Windows Junctions or symlinks when creating links on Windows.\",type:\"STRING\",values:[\"junctions\",\"symlinks\"],default:\"junctions\"},pnpMode:{description:\"If 'strict', generates standard PnP maps. If 'loose', merges them with the n_m resolution.\",type:\"STRING\",default:\"strict\"},pnpShebang:{description:\"String to prepend to the generated PnP script\",type:\"STRING\",default:\"#!/usr/bin/env node\"},pnpIgnorePatterns:{description:\"Array of glob patterns; files matching them will use the classic resolution\",type:\"STRING\",default:[],isArray:!0},pnpEnableEsmLoader:{description:\"If true, Yarn will generate an ESM loader (`.pnp.loader.mjs`). If this is not explicitly set Yarn tries to automatically detect whether ESM support is required.\",type:\"BOOLEAN\",default:!1},pnpEnableInlining:{description:\"If true, the PnP data will be inlined along with the generated loader\",type:\"BOOLEAN\",default:!0},pnpFallbackMode:{description:\"If true, the generated PnP loader will follow the top-level fallback rule\",type:\"STRING\",default:\"dependencies-only\"},pnpUnpluggedFolder:{description:\"Folder where the unplugged packages must be stored\",type:\"ABSOLUTE_PATH\",default:\"./.yarn/unplugged\"}},linkers:[Hh],commands:[cC]},e1t=$It;var h1e=Ze(A1e());qt();var cj=Ze(ve(\"crypto\")),g1e=Ze(ve(\"fs\")),d1e=1,Di=\"node_modules\",fQ=\".bin\",m1e=\".yarn-state.yml\",m1t=1e3,uj=(o=>(o.CLASSIC=\"classic\",o.HARDLINKS_LOCAL=\"hardlinks-local\",o.HARDLINKS_GLOBAL=\"hardlinks-global\",o))(uj||{}),GB=class{constructor(){this.installStateCache=new Map}getCustomDataKey(){return JSON.stringify({name:\"NodeModulesLinker\",version:3})}supportsPackage(e,r){return this.isEnabled(r)}async findPackageLocation(e,r){if(!this.isEnabled(r))throw new Error(\"Assertion failed: Expected the node-modules linker to be enabled\");let o=r.project.tryWorkspaceByLocator(e);if(o)return o.cwd;let a=await He.getFactoryWithDefault(this.installStateCache,r.project.cwd,async()=>await lj(r.project,{unrollAliases:!0}));if(a===null)throw new st(\"Couldn't find the node_modules state file - running an install might help (findPackageLocation)\");let n=a.locatorMap.get(G.stringifyLocator(e));if(!n){let p=new st(`Couldn't find ${G.prettyLocator(r.project.configuration,e)} in the currently installed node_modules map - running an install might help`);throw p.code=\"LOCATOR_NOT_INSTALLED\",p}let u=n.locations.sort((p,h)=>p.split(V.sep).length-h.split(V.sep).length),A=V.join(r.project.configuration.startingCwd,Di);return u.find(p=>V.contains(A,p))||n.locations[0]}async findPackageLocator(e,r){if(!this.isEnabled(r))return null;let o=await He.getFactoryWithDefault(this.installStateCache,r.project.cwd,async()=>await lj(r.project,{unrollAliases:!0}));if(o===null)return null;let{locationRoot:a,segments:n}=pQ(V.resolve(e),{skipPrefix:r.project.cwd}),u=o.locationTree.get(a);if(!u)return null;let A=u.locator;for(let p of n){if(u=u.children.get(p),!u)break;A=u.locator||A}return G.parseLocator(A)}makeInstaller(e){return new aj(e)}isEnabled(e){return e.project.configuration.get(\"nodeLinker\")===\"node-modules\"}},aj=class{constructor(e){this.opts=e;this.localStore=new Map;this.realLocatorChecksums=new Map;this.customData={store:new Map}}attachCustomData(e){this.customData=e}async installPackage(e,r){let o=V.resolve(r.packageFs.getRealPath(),r.prefixPath),a=this.customData.store.get(e.locatorHash);if(typeof a>\"u\"&&(a=await y1t(e,r),e.linkType===\"HARD\"&&this.customData.store.set(e.locatorHash,a)),!G.isPackageCompatible(e,this.opts.project.configuration.getSupportedArchitectures()))return{packageLocation:null,buildRequest:null};let n=new Map,u=new Set;n.has(G.stringifyIdent(e))||n.set(G.stringifyIdent(e),e.reference);let A=e;if(G.isVirtualLocator(e)){A=G.devirtualizeLocator(e);for(let E of e.peerDependencies.values())n.set(G.stringifyIdent(E),null),u.add(G.stringifyIdent(E))}let p={packageLocation:`${ue.fromPortablePath(o)}/`,packageDependencies:n,packagePeers:u,linkType:e.linkType,discardFromLookup:r.discardFromLookup??!1};this.localStore.set(e.locatorHash,{pkg:e,customPackageData:a,dependencyMeta:this.opts.project.getDependencyMeta(e,e.version),pnpNode:p});let h=r.checksum?r.checksum.substring(r.checksum.indexOf(\"/\")+1):null;return this.realLocatorChecksums.set(A.locatorHash,h),{packageLocation:o,buildRequest:null}}async attachInternalDependencies(e,r){let o=this.localStore.get(e.locatorHash);if(typeof o>\"u\")throw new Error(\"Assertion failed: Expected information object to have been registered\");for(let[a,n]of r){let u=G.areIdentsEqual(a,n)?n.reference:[G.stringifyIdent(n),n.reference];o.pnpNode.packageDependencies.set(G.stringifyIdent(a),u)}}async attachExternalDependents(e,r){throw new Error(\"External dependencies haven't been implemented for the node-modules linker\")}async finalizeInstall(){if(this.opts.project.configuration.get(\"nodeLinker\")!==\"node-modules\")return;let e=new zs({baseFs:new rA({maxOpenFiles:80,readOnlyArchives:!0})}),r=await lj(this.opts.project),o=this.opts.project.configuration.get(\"nmMode\");(r===null||o!==r.nmMode)&&(this.opts.project.storedBuildState.clear(),r={locatorMap:new Map,binSymlinks:new Map,locationTree:new Map,nmMode:o,mtimeMs:0});let a=new Map(this.opts.project.workspaces.map(v=>{let x=this.opts.project.configuration.get(\"nmHoistingLimits\");try{x=He.validateEnum(QB,v.manifest.installConfig?.hoistingLimits??x)}catch{let R=G.prettyWorkspace(this.opts.project.configuration,v);this.opts.report.reportWarning(57,`${R}: Invalid 'installConfig.hoistingLimits' value. Expected one of ${Object.values(QB).join(\", \")}, using default: \"${x}\"`)}return[v.relativeCwd,x]})),n=new Map(this.opts.project.workspaces.map(v=>{let x=this.opts.project.configuration.get(\"nmSelfReferences\");return x=v.manifest.installConfig?.selfReferences??x,[v.relativeCwd,x]})),u={VERSIONS:{std:1},topLevel:{name:null,reference:null},getLocator:(v,x)=>Array.isArray(x)?{name:x[0],reference:x[1]}:{name:v,reference:x},getDependencyTreeRoots:()=>this.opts.project.workspaces.map(v=>{let x=v.anchoredLocator;return{name:G.stringifyIdent(x),reference:x.reference}}),getPackageInformation:v=>{let x=v.reference===null?this.opts.project.topLevelWorkspace.anchoredLocator:G.makeLocator(G.parseIdent(v.name),v.reference),C=this.localStore.get(x.locatorHash);if(typeof C>\"u\")throw new Error(\"Assertion failed: Expected the package reference to have been registered\");return C.pnpNode},findPackageLocator:v=>{let x=this.opts.project.tryWorkspaceByCwd(ue.toPortablePath(v));if(x!==null){let C=x.anchoredLocator;return{name:G.stringifyIdent(C),reference:C.reference}}throw new Error(\"Assertion failed: Unimplemented\")},resolveToUnqualified:()=>{throw new Error(\"Assertion failed: Unimplemented\")},resolveUnqualified:()=>{throw new Error(\"Assertion failed: Unimplemented\")},resolveRequest:()=>{throw new Error(\"Assertion failed: Unimplemented\")},resolveVirtual:v=>ue.fromPortablePath(zs.resolveVirtual(ue.toPortablePath(v)))},{tree:A,errors:p,preserveSymlinksRequired:h}=FB(u,{pnpifyFs:!1,validateExternalSoftLinks:!0,hoistingLimitsByCwd:a,project:this.opts.project,selfReferencesByCwd:n});if(!A){for(let{messageName:v,text:x}of p)this.opts.report.reportError(v,x);return}let E=Mq(A);await v1t(r,E,{baseFs:e,project:this.opts.project,report:this.opts.report,realLocatorChecksums:this.realLocatorChecksums,loadManifest:async v=>{let x=G.parseLocator(v),C=this.localStore.get(x.locatorHash);if(typeof C>\"u\")throw new Error(\"Assertion failed: Expected the slot to exist\");return C.customPackageData.manifest}});let I=[];for(let[v,x]of E.entries()){if(C1e(v))continue;let C=G.parseLocator(v),R=this.localStore.get(C.locatorHash);if(typeof R>\"u\")throw new Error(\"Assertion failed: Expected the slot to exist\");if(this.opts.project.tryWorkspaceByLocator(R.pkg))continue;let L=mA.extractBuildRequest(R.pkg,R.customPackageData,R.dependencyMeta,{configuration:this.opts.project.configuration});L&&I.push({buildLocations:x.locations,locator:C,buildRequest:L})}return h&&this.opts.report.reportWarning(72,`The application uses portals and that's why ${pe.pretty(this.opts.project.configuration,\"--preserve-symlinks\",pe.Type.CODE)} Node option is required for launching it`),{customData:this.customData,records:I}}};async function y1t(t,e){let r=await Ut.tryFind(e.prefixPath,{baseFs:e.packageFs})??new Ut,o=new Set([\"preinstall\",\"install\",\"postinstall\"]);for(let a of r.scripts.keys())o.has(a)||r.scripts.delete(a);return{manifest:{bin:r.bin,scripts:r.scripts},misc:{hasBindingGyp:mA.hasBindingGyp(e)}}}async function E1t(t,e,r,o,{installChangedByUser:a}){let n=\"\";n+=`# Warning: This file is automatically generated. Removing it is fine, but will\n`,n+=`# cause your node_modules installation to become invalidated.\n`,n+=`\n`,n+=`__metadata:\n`,n+=`  version: ${d1e}\n`,n+=`  nmMode: ${o.value}\n`;let u=Array.from(e.keys()).sort(),A=G.stringifyLocator(t.topLevelWorkspace.anchoredLocator);for(let E of u){let I=e.get(E);n+=`\n`,n+=`${JSON.stringify(E)}:\n`,n+=`  locations:\n`;for(let v of I.locations){let x=V.contains(t.cwd,v);if(x===null)throw new Error(`Assertion failed: Expected the path to be within the project (${v})`);n+=`    - ${JSON.stringify(x)}\n`}if(I.aliases.length>0){n+=`  aliases:\n`;for(let v of I.aliases)n+=`    - ${JSON.stringify(v)}\n`}if(E===A&&r.size>0){n+=`  bin:\n`;for(let[v,x]of r){let C=V.contains(t.cwd,v);if(C===null)throw new Error(`Assertion failed: Expected the path to be within the project (${v})`);n+=`    ${JSON.stringify(C)}:\n`;for(let[R,L]of x){let U=V.relative(V.join(v,Di),L);n+=`      ${JSON.stringify(R)}: ${JSON.stringify(U)}\n`}}}}let p=t.cwd,h=V.join(p,Di,m1e);a&&await oe.removePromise(h),await oe.changeFilePromise(h,n,{automaticNewlines:!0})}async function lj(t,{unrollAliases:e=!1}={}){let r=t.cwd,o=V.join(r,Di,m1e),a;try{a=await oe.statPromise(o)}catch{}if(!a)return null;let n=Ki(await oe.readFilePromise(o,\"utf8\"));if(n.__metadata.version>d1e)return null;let u=n.__metadata.nmMode||\"classic\",A=new Map,p=new Map;delete n.__metadata;for(let[h,E]of Object.entries(n)){let I=E.locations.map(x=>V.join(r,x)),v=E.bin;if(v)for(let[x,C]of Object.entries(v)){let R=V.join(r,ue.toPortablePath(x)),L=He.getMapWithDefault(p,R);for(let[U,z]of Object.entries(C))L.set(U,ue.toPortablePath([R,Di,z].join(V.sep)))}if(A.set(h,{target:It.dot,linkType:\"HARD\",locations:I,aliases:E.aliases||[]}),e&&E.aliases)for(let x of E.aliases){let{scope:C,name:R}=G.parseLocator(h),L=G.makeLocator(G.makeIdent(C,R),x),U=G.stringifyLocator(L);A.set(U,{target:It.dot,linkType:\"HARD\",locations:I,aliases:[]})}}return{locatorMap:A,binSymlinks:p,locationTree:y1e(A,{skipPrefix:t.cwd}),nmMode:u,mtimeMs:a.mtimeMs}}var AC=async(t,e)=>{if(t.split(V.sep).indexOf(Di)<0)throw new Error(`Assertion failed: trying to remove dir that doesn't contain node_modules: ${t}`);try{let r;if(!e.innerLoop&&(r=await oe.lstatPromise(t),!r.isDirectory()&&!r.isSymbolicLink()||r.isSymbolicLink()&&!e.isWorkspaceDir)){await oe.unlinkPromise(t);return}let o=await oe.readdirPromise(t,{withFileTypes:!0});for(let n of o){let u=V.join(t,n.name);n.isDirectory()?(n.name!==Di||e&&e.innerLoop)&&await AC(u,{innerLoop:!0,contentsOnly:!1}):await oe.unlinkPromise(u)}let a=!e.innerLoop&&e.isWorkspaceDir&&r?.isSymbolicLink();!e.contentsOnly&&!a&&await oe.rmdirPromise(t)}catch(r){if(r.code!==\"ENOENT\"&&r.code!==\"ENOTEMPTY\")throw r}},f1e=4,pQ=(t,{skipPrefix:e})=>{let r=V.contains(e,t);if(r===null)throw new Error(`Assertion failed: Writing attempt prevented to ${t} which is outside project root: ${e}`);let o=r.split(V.sep).filter(p=>p!==\"\"),a=o.indexOf(Di),n=o.slice(0,a).join(V.sep),u=V.join(e,n),A=o.slice(a);return{locationRoot:u,segments:A}},y1e=(t,{skipPrefix:e})=>{let r=new Map;if(t===null)return r;let o=()=>({children:new Map,linkType:\"HARD\"});for(let[a,n]of t.entries()){if(n.linkType===\"SOFT\"&&V.contains(e,n.target)!==null){let A=He.getFactoryWithDefault(r,n.target,o);A.locator=a,A.linkType=n.linkType}for(let u of n.locations){let{locationRoot:A,segments:p}=pQ(u,{skipPrefix:e}),h=He.getFactoryWithDefault(r,A,o);for(let E=0;E<p.length;++E){let I=p[E];if(I!==\".\"){let v=He.getFactoryWithDefault(h.children,I,o);h.children.set(I,v),h=v}E===p.length-1&&(h.locator=a,h.linkType=n.linkType)}}}return r},Aj=async(t,e,r)=>{if(process.platform===\"win32\"&&r===\"junctions\"){let o;try{o=await oe.lstatPromise(t)}catch{}if(!o||o.isDirectory()){await oe.symlinkPromise(t,e,\"junction\");return}}await oe.symlinkPromise(V.relative(V.dirname(e),t),e)};async function E1e(t,e,r){let o=V.join(t,`${cj.default.randomBytes(16).toString(\"hex\")}.tmp`);try{await oe.writeFilePromise(o,r);try{await oe.linkPromise(o,e)}catch{}}finally{await oe.unlinkPromise(o)}}async function C1t({srcPath:t,dstPath:e,entry:r,globalHardlinksStore:o,baseFs:a,nmMode:n}){if(r.kind===\"file\"){if(n.value===\"hardlinks-global\"&&o&&r.digest){let A=V.join(o,r.digest.substring(0,2),`${r.digest.substring(2)}.dat`),p;try{let h=await oe.statPromise(A);if(h&&(!r.mtimeMs||h.mtimeMs>r.mtimeMs||h.mtimeMs<r.mtimeMs-m1t))if(await wn.checksumFile(A,{baseFs:oe,algorithm:\"sha1\"})!==r.digest){let I=V.join(o,`${cj.default.randomBytes(16).toString(\"hex\")}.tmp`);await oe.renamePromise(A,I);let v=await a.readFilePromise(t);await oe.writeFilePromise(I,v);try{await oe.linkPromise(I,A),r.mtimeMs=new Date().getTime(),await oe.unlinkPromise(I)}catch{}}else r.mtimeMs||(r.mtimeMs=Math.ceil(h.mtimeMs));await oe.linkPromise(A,e),p=!0}catch{p=!1}if(!p){let h=await a.readFilePromise(t);await E1e(o,A,h),r.mtimeMs=new Date().getTime();try{await oe.linkPromise(A,e)}catch(E){E&&E.code&&E.code==\"EXDEV\"&&(n.value=\"hardlinks-local\",await a.copyFilePromise(t,e))}}}else await a.copyFilePromise(t,e);let u=r.mode&511;u!==420&&await oe.chmodPromise(e,u)}}var w1t=async(t,e,{baseFs:r,globalHardlinksStore:o,nmMode:a,windowsLinkType:n,packageChecksum:u})=>{await oe.mkdirPromise(t,{recursive:!0});let A=async(E=It.dot)=>{let I=V.join(e,E),v=await r.readdirPromise(I,{withFileTypes:!0}),x=new Map;for(let C of v){let R=V.join(E,C.name),L,U=V.join(I,C.name);if(C.isFile()){if(L={kind:\"file\",mode:(await r.lstatPromise(U)).mode},a.value===\"hardlinks-global\"){let z=await wn.checksumFile(U,{baseFs:r,algorithm:\"sha1\"});L.digest=z}}else if(C.isDirectory())L={kind:\"directory\"};else if(C.isSymbolicLink())L={kind:\"symlink\",symlinkTo:await r.readlinkPromise(U)};else throw new Error(`Unsupported file type (file: ${U}, mode: 0o${await r.statSync(U).mode.toString(8).padStart(6,\"0\")})`);if(x.set(R,L),C.isDirectory()&&R!==Di){let z=await A(R);for(let[te,ae]of z)x.set(te,ae)}}return x},p;if(a.value===\"hardlinks-global\"&&o&&u){let E=V.join(o,u.substring(0,2),`${u.substring(2)}.json`);try{p=new Map(Object.entries(JSON.parse(await oe.readFilePromise(E,\"utf8\"))))}catch{p=await A()}}else p=await A();let h=!1;for(let[E,I]of p){let v=V.join(e,E),x=V.join(t,E);if(I.kind===\"directory\")await oe.mkdirPromise(x,{recursive:!0});else if(I.kind===\"file\"){let C=I.mtimeMs;await C1t({srcPath:v,dstPath:x,entry:I,nmMode:a,baseFs:r,globalHardlinksStore:o}),I.mtimeMs!==C&&(h=!0)}else I.kind===\"symlink\"&&await Aj(V.resolve(V.dirname(x),I.symlinkTo),x,n)}if(a.value===\"hardlinks-global\"&&o&&h&&u){let E=V.join(o,u.substring(0,2),`${u.substring(2)}.json`);await oe.removePromise(E),await E1e(o,E,Buffer.from(JSON.stringify(Object.fromEntries(p))))}};function I1t(t,e,r,o){let a=new Map,n=new Map,u=new Map,A=!1,p=(h,E,I,v,x)=>{let C=!0,R=V.join(h,E),L=new Set;if(E===Di||E.startsWith(\"@\")){let z;try{z=oe.statSync(R)}catch{}C=!!z,z?z.mtimeMs>r?(A=!0,L=new Set(oe.readdirSync(R))):L=new Set(I.children.get(E).children.keys()):A=!0;let te=e.get(h);if(te){let ae=V.join(h,Di,fQ),le;try{le=oe.statSync(ae)}catch{}if(!le)A=!0;else if(le.mtimeMs>r){A=!0;let ce=new Set(oe.readdirSync(ae)),Ce=new Map;n.set(h,Ce);for(let[de,Be]of te)ce.has(de)&&Ce.set(de,Be)}else n.set(h,te)}}else C=x.has(E);let U=I.children.get(E);if(C){let{linkType:z,locator:te}=U,ae={children:new Map,linkType:z,locator:te};if(v.children.set(E,ae),te){let le=He.getSetWithDefault(u,te);le.add(R),u.set(te,le)}for(let le of U.children.keys())p(R,le,U,ae,L)}else U.locator&&o.storedBuildState.delete(G.parseLocator(U.locator).locatorHash)};for(let[h,E]of t){let{linkType:I,locator:v}=E,x={children:new Map,linkType:I,locator:v};if(a.set(h,x),v){let C=He.getSetWithDefault(u,E.locator);C.add(h),u.set(E.locator,C)}E.children.has(Di)&&p(h,Di,E,x,new Set)}return{locationTree:a,binSymlinks:n,locatorLocations:u,installChangedByUser:A}}function C1e(t){let e=G.parseDescriptor(t);return G.isVirtualDescriptor(e)&&(e=G.devirtualizeDescriptor(e)),e.range.startsWith(\"link:\")}async function B1t(t,e,r,{loadManifest:o}){let a=new Map;for(let[A,{locations:p}]of t){let h=C1e(A)?null:await o(A,p[0]),E=new Map;if(h)for(let[I,v]of h.bin){let x=V.join(p[0],v);v!==\"\"&&oe.existsSync(x)&&E.set(I,v)}a.set(A,E)}let n=new Map,u=(A,p,h)=>{let E=new Map,I=V.contains(r,A);if(h.locator&&I!==null){let v=a.get(h.locator);for(let[x,C]of v){let R=V.join(A,ue.toPortablePath(C));E.set(x,R)}for(let[x,C]of h.children){let R=V.join(A,x),L=u(R,R,C);L.size>0&&n.set(A,new Map([...n.get(A)||new Map,...L]))}}else for(let[v,x]of h.children){let C=u(V.join(A,v),p,x);for(let[R,L]of C)E.set(R,L)}return E};for(let[A,p]of e){let h=u(A,A,p);h.size>0&&n.set(A,new Map([...n.get(A)||new Map,...h]))}return n}var p1e=(t,e)=>{if(!t||!e)return t===e;let r=G.parseLocator(t);G.isVirtualLocator(r)&&(r=G.devirtualizeLocator(r));let o=G.parseLocator(e);return G.isVirtualLocator(o)&&(o=G.devirtualizeLocator(o)),G.areLocatorsEqual(r,o)};function fj(t){return V.join(t.get(\"globalFolder\"),\"store\")}async function v1t(t,e,{baseFs:r,project:o,report:a,loadManifest:n,realLocatorChecksums:u}){let A=V.join(o.cwd,Di),{locationTree:p,binSymlinks:h,locatorLocations:E,installChangedByUser:I}=I1t(t.locationTree,t.binSymlinks,t.mtimeMs,o),v=y1e(e,{skipPrefix:o.cwd}),x=[],C=async({srcDir:Be,dstDir:Ee,linkType:g,globalHardlinksStore:me,nmMode:we,windowsLinkType:Ae,packageChecksum:ne})=>{let Z=(async()=>{try{g===\"SOFT\"?(await oe.mkdirPromise(V.dirname(Ee),{recursive:!0}),await Aj(V.resolve(Be),Ee,Ae)):await w1t(Ee,Be,{baseFs:r,globalHardlinksStore:me,nmMode:we,windowsLinkType:Ae,packageChecksum:ne})}catch(xe){throw xe.message=`While persisting ${Be} -> ${Ee} ${xe.message}`,xe}finally{ae.tick()}})().then(()=>x.splice(x.indexOf(Z),1));x.push(Z),x.length>f1e&&await Promise.race(x)},R=async(Be,Ee,g)=>{let me=(async()=>{let we=async(Ae,ne,Z)=>{try{Z.innerLoop||await oe.mkdirPromise(ne,{recursive:!0});let xe=await oe.readdirPromise(Ae,{withFileTypes:!0});for(let Ne of xe){if(!Z.innerLoop&&Ne.name===fQ)continue;let ht=V.join(Ae,Ne.name),H=V.join(ne,Ne.name);Ne.isDirectory()?(Ne.name!==Di||Z&&Z.innerLoop)&&(await oe.mkdirPromise(H,{recursive:!0}),await we(ht,H,{...Z,innerLoop:!0})):Ce.value===\"hardlinks-local\"||Ce.value===\"hardlinks-global\"?await oe.linkPromise(ht,H):await oe.copyFilePromise(ht,H,g1e.default.constants.COPYFILE_FICLONE)}}catch(xe){throw Z.innerLoop||(xe.message=`While cloning ${Ae} -> ${ne} ${xe.message}`),xe}finally{Z.innerLoop||ae.tick()}};await we(Be,Ee,g)})().then(()=>x.splice(x.indexOf(me),1));x.push(me),x.length>f1e&&await Promise.race(x)},L=async(Be,Ee,g)=>{if(g)for(let[me,we]of Ee.children){let Ae=g.children.get(me);await L(V.join(Be,me),we,Ae)}else{Ee.children.has(Di)&&await AC(V.join(Be,Di),{contentsOnly:!1});let me=V.basename(Be)===Di&&p.has(V.join(V.dirname(Be)));await AC(Be,{contentsOnly:Be===A,isWorkspaceDir:me})}};for(let[Be,Ee]of p){let g=v.get(Be);for(let[me,we]of Ee.children){if(me===\".\")continue;let Ae=g&&g.children.get(me),ne=V.join(Be,me);await L(ne,we,Ae)}}let U=async(Be,Ee,g)=>{if(g){p1e(Ee.locator,g.locator)||await AC(Be,{contentsOnly:Ee.linkType===\"HARD\"});for(let[me,we]of Ee.children){let Ae=g.children.get(me);await U(V.join(Be,me),we,Ae)}}else{Ee.children.has(Di)&&await AC(V.join(Be,Di),{contentsOnly:!0});let me=V.basename(Be)===Di&&v.has(V.join(V.dirname(Be)));await AC(Be,{contentsOnly:Ee.linkType===\"HARD\",isWorkspaceDir:me})}};for(let[Be,Ee]of v){let g=p.get(Be);for(let[me,we]of Ee.children){if(me===\".\")continue;let Ae=g&&g.children.get(me);await U(V.join(Be,me),we,Ae)}}let z=new Map,te=[];for(let[Be,Ee]of E)for(let g of Ee){let{locationRoot:me,segments:we}=pQ(g,{skipPrefix:o.cwd}),Ae=v.get(me),ne=me;if(Ae){for(let Z of we)if(ne=V.join(ne,Z),Ae=Ae.children.get(Z),!Ae)break;if(Ae){let Z=p1e(Ae.locator,Be),xe=e.get(Ae.locator),Ne=xe.target,ht=ne,H=xe.linkType;if(Z)z.has(Ne)||z.set(Ne,ht);else if(Ne!==ht){let rt=G.parseLocator(Ae.locator);G.isVirtualLocator(rt)&&(rt=G.devirtualizeLocator(rt)),te.push({srcDir:Ne,dstDir:ht,linkType:H,realLocatorHash:rt.locatorHash})}}}}for(let[Be,{locations:Ee}]of e.entries())for(let g of Ee){let{locationRoot:me,segments:we}=pQ(g,{skipPrefix:o.cwd}),Ae=p.get(me),ne=v.get(me),Z=me,xe=e.get(Be),Ne=G.parseLocator(Be);G.isVirtualLocator(Ne)&&(Ne=G.devirtualizeLocator(Ne));let ht=Ne.locatorHash,H=xe.target,rt=g;if(H===rt)continue;let Te=xe.linkType;for(let Fe of we)ne=ne.children.get(Fe);if(!Ae)te.push({srcDir:H,dstDir:rt,linkType:Te,realLocatorHash:ht});else for(let Fe of we)if(Z=V.join(Z,Fe),Ae=Ae.children.get(Fe),!Ae){te.push({srcDir:H,dstDir:rt,linkType:Te,realLocatorHash:ht});break}}let ae=Zs.progressViaCounter(te.length),le=a.reportProgress(ae),ce=o.configuration.get(\"nmMode\"),Ce={value:ce},de=o.configuration.get(\"winLinkType\");try{let Be=Ce.value===\"hardlinks-global\"?`${fj(o.configuration)}/v1`:null;if(Be&&!await oe.existsPromise(Be)){await oe.mkdirpPromise(Be);for(let g=0;g<256;g++)await oe.mkdirPromise(V.join(Be,g.toString(16).padStart(2,\"0\")))}for(let g of te)(g.linkType===\"SOFT\"||!z.has(g.srcDir))&&(z.set(g.srcDir,g.dstDir),await C({...g,globalHardlinksStore:Be,nmMode:Ce,windowsLinkType:de,packageChecksum:u.get(g.realLocatorHash)||null}));await Promise.all(x),x.length=0;for(let g of te){let me=z.get(g.srcDir);g.linkType!==\"SOFT\"&&g.dstDir!==me&&await R(me,g.dstDir,{nmMode:Ce})}await Promise.all(x),await oe.mkdirPromise(A,{recursive:!0});let Ee=await B1t(e,v,o.cwd,{loadManifest:n});await D1t(h,Ee,o.cwd,de),await E1t(o,e,Ee,Ce,{installChangedByUser:I}),ce==\"hardlinks-global\"&&Ce.value==\"hardlinks-local\"&&a.reportWarningOnce(74,\"'nmMode' has been downgraded to 'hardlinks-local' due to global cache and install folder being on different devices\")}finally{le.stop()}}async function D1t(t,e,r,o){for(let a of t.keys()){if(V.contains(r,a)===null)throw new Error(`Assertion failed. Excepted bin symlink location to be inside project dir, instead it was at ${a}`);if(!e.has(a)){let n=V.join(a,Di,fQ);await oe.removePromise(n)}}for(let[a,n]of e){if(V.contains(r,a)===null)throw new Error(`Assertion failed. Excepted bin symlink location to be inside project dir, instead it was at ${a}`);let u=V.join(a,Di,fQ),A=t.get(a)||new Map;await oe.mkdirPromise(u,{recursive:!0});for(let p of A.keys())n.has(p)||(await oe.removePromise(V.join(u,p)),process.platform===\"win32\"&&await oe.removePromise(V.join(u,`${p}.cmd`)));for(let[p,h]of n){let E=A.get(p),I=V.join(u,p);E!==h&&(process.platform===\"win32\"?await(0,h1e.default)(ue.fromPortablePath(h),ue.fromPortablePath(I),{createPwshFile:!1}):(await oe.removePromise(I),await Aj(h,I,o),V.contains(r,await oe.realpathPromise(h))!==null&&await oe.chmodPromise(h,493)))}}}Ge();Pt();nA();var YB=class extends Hh{constructor(){super(...arguments);this.mode=\"loose\"}makeInstaller(r){return new pj(r)}},pj=class extends sd{constructor(){super(...arguments);this.mode=\"loose\"}async transformPnpSettings(r){let o=new zs({baseFs:new rA({maxOpenFiles:80,readOnlyArchives:!0})}),a=e1e(r,this.opts.project.cwd,o),{tree:n,errors:u}=FB(a,{pnpifyFs:!1,project:this.opts.project});if(!n){for(let{messageName:I,text:v}of u)this.opts.report.reportError(I,v);return}let A=new Map;r.fallbackPool=A;let p=(I,v)=>{let x=G.parseLocator(v.locator),C=G.stringifyIdent(x);C===I?A.set(I,x.reference):A.set(I,[C,x.reference])},h=V.join(this.opts.project.cwd,dr.nodeModules),E=n.get(h);if(!(typeof E>\"u\")){if(\"target\"in E)throw new Error(\"Assertion failed: Expected the root junction point to be a directory\");for(let I of E.dirList){let v=V.join(h,I),x=n.get(v);if(typeof x>\"u\")throw new Error(\"Assertion failed: Expected the child to have been registered\");if(\"target\"in x)p(I,x);else for(let C of x.dirList){let R=V.join(v,C),L=n.get(R);if(typeof L>\"u\")throw new Error(\"Assertion failed: Expected the subchild to have been registered\");if(\"target\"in L)p(`${I}/${C}`,L);else throw new Error(\"Assertion failed: Expected the leaf junction to be a package\")}}}}};var P1t={hooks:{cleanGlobalArtifacts:async t=>{let e=fj(t);await oe.removePromise(e)}},configuration:{nmHoistingLimits:{description:\"Prevents packages to be hoisted past specific levels\",type:\"STRING\",values:[\"workspaces\",\"dependencies\",\"none\"],default:\"none\"},nmMode:{description:\"Defines in which measure Yarn must use hardlinks and symlinks when generated `node_modules` directories.\",type:\"STRING\",values:[\"classic\",\"hardlinks-local\",\"hardlinks-global\"],default:\"classic\"},nmSelfReferences:{description:\"Defines whether the linker should generate self-referencing symlinks for workspaces.\",type:\"BOOLEAN\",default:!0}},linkers:[GB,YB]},b1t=P1t;var f5={};Vt(f5,{NpmHttpFetcher:()=>VB,NpmRemapResolver:()=>zB,NpmSemverFetcher:()=>tp,NpmSemverResolver:()=>JB,NpmTagResolver:()=>XB,default:()=>qvt,npmConfigUtils:()=>Zn,npmHttpUtils:()=>Zr,npmPublishUtils:()=>PC});Ge();var S1e=Ze(Jn());var Wn=\"npm:\";var Zr={};Vt(Zr,{AuthType:()=>D1e,customPackageError:()=>od,del:()=>U1t,get:()=>ad,getIdentUrl:()=>hQ,getPackageMetadata:()=>hC,handleInvalidAuthenticationError:()=>jh,post:()=>M1t,put:()=>O1t});Ge();Ge();Pt();var mj=Ze(J1()),B1e=Ze(y_()),v1e=Ze(Jn());var Zn={};Vt(Zn,{RegistryType:()=>w1e,getAuditRegistry:()=>S1t,getAuthConfiguration:()=>dj,getDefaultRegistry:()=>WB,getPublishRegistry:()=>x1t,getRegistryConfiguration:()=>I1e,getScopeConfiguration:()=>gj,getScopeRegistry:()=>fC,normalizeRegistry:()=>ac});var w1e=(o=>(o.AUDIT_REGISTRY=\"npmAuditRegistry\",o.FETCH_REGISTRY=\"npmRegistryServer\",o.PUBLISH_REGISTRY=\"npmPublishRegistry\",o))(w1e||{});function ac(t){return t.replace(/\\/$/,\"\")}function S1t({configuration:t}){return WB({configuration:t,type:\"npmAuditRegistry\"})}function x1t(t,{configuration:e}){return t.publishConfig?.registry?ac(t.publishConfig.registry):t.name?fC(t.name.scope,{configuration:e,type:\"npmPublishRegistry\"}):WB({configuration:e,type:\"npmPublishRegistry\"})}function fC(t,{configuration:e,type:r=\"npmRegistryServer\"}){let o=gj(t,{configuration:e});if(o===null)return WB({configuration:e,type:r});let a=o.get(r);return a===null?WB({configuration:e,type:r}):ac(a)}function WB({configuration:t,type:e=\"npmRegistryServer\"}){let r=t.get(e);return ac(r!==null?r:t.get(\"npmRegistryServer\"))}function I1e(t,{configuration:e}){let r=e.get(\"npmRegistries\"),o=ac(t),a=r.get(o);if(typeof a<\"u\")return a;let n=r.get(o.replace(/^[a-z]+:/,\"\"));return typeof n<\"u\"?n:null}function gj(t,{configuration:e}){if(t===null)return null;let o=e.get(\"npmScopes\").get(t);return o||null}function dj(t,{configuration:e,ident:r}){let o=r&&gj(r.scope,{configuration:e});return o?.get(\"npmAuthIdent\")||o?.get(\"npmAuthToken\")?o:I1e(t,{configuration:e})||e}var D1e=(a=>(a[a.NO_AUTH=0]=\"NO_AUTH\",a[a.BEST_EFFORT=1]=\"BEST_EFFORT\",a[a.CONFIGURATION=2]=\"CONFIGURATION\",a[a.ALWAYS_AUTH=3]=\"ALWAYS_AUTH\",a))(D1e||{});async function jh(t,{attemptedAs:e,registry:r,headers:o,configuration:a}){if(dQ(t))throw new Jt(41,\"Invalid OTP token\");if(t.originalError?.name===\"HTTPError\"&&t.originalError?.response.statusCode===401)throw new Jt(41,`Invalid authentication (${typeof e!=\"string\"?`as ${await H1t(r,o,{configuration:a})}`:`attempted as ${e}`})`)}function od(t,e){let r=t.response?.statusCode;return r?r===404?\"Package not found\":r>=500&&r<600?`The registry appears to be down (using a ${pe.applyHyperlink(e,\"local cache\",\"https://yarnpkg.com/advanced/lexicon#local-cache\")} might have protected you against such outages)`:null:null}function hQ(t){return t.scope?`/@${t.scope}%2f${t.name}`:`/${t.name}`}var P1e=new Map,k1t=new Map;async function Q1t(t){return await He.getFactoryWithDefault(P1e,t,async()=>{let e=null;try{e=await oe.readJsonPromise(t)}catch{}return e})}async function F1t(t,e,{configuration:r,cached:o,registry:a,headers:n,version:u,...A}){return await He.getFactoryWithDefault(k1t,t,async()=>await ad(hQ(e),{...A,customErrorMessage:od,configuration:r,registry:a,ident:e,headers:{...n,\"If-None-Match\":o?.etag,\"If-Modified-Since\":o?.lastModified},wrapNetworkRequest:async p=>async()=>{let h=await p();if(h.statusCode===304){if(o===null)throw new Error(\"Assertion failed: cachedMetadata should not be null\");return{...h,body:o.metadata}}let E=R1t(JSON.parse(h.body.toString())),I={metadata:E,etag:h.headers.etag,lastModified:h.headers[\"last-modified\"]};return P1e.set(t,Promise.resolve(I)),Promise.resolve().then(async()=>{let v=`${t}-${process.pid}.tmp`;await oe.mkdirPromise(V.dirname(v),{recursive:!0}),await oe.writeJsonPromise(v,I,{compact:!0}),await oe.renamePromise(v,t)}).catch(()=>{}),{...h,body:E}}}))}async function hC(t,{cache:e,project:r,registry:o,headers:a,version:n,...u}){let{configuration:A}=r;o=KB(A,{ident:t,registry:o});let p=N1t(A,o),h=V.join(p,`${G.slugifyIdent(t)}.json`),E=null;if(!r.lockfileNeedsRefresh&&(E=await Q1t(h),E)){if(typeof n<\"u\"&&typeof E.metadata.versions[n]<\"u\")return E.metadata;if(A.get(\"enableOfflineMode\")){let I=structuredClone(E.metadata),v=new Set;if(e){for(let C of Object.keys(I.versions)){let R=G.makeLocator(t,`npm:${C}`),L=e.getLocatorMirrorPath(R);(!L||!oe.existsSync(L))&&(delete I.versions[C],v.add(C))}let x=I[\"dist-tags\"].latest;if(v.has(x)){let C=Object.keys(E.metadata.versions).sort(v1e.default.compare),R=C.indexOf(x);for(;v.has(C[R])&&R>=0;)R-=1;R>=0?I[\"dist-tags\"].latest=C[R]:delete I[\"dist-tags\"].latest}}return I}}return await F1t(h,t,{...u,configuration:A,cached:E,registry:o,headers:a,version:n})}var b1e=[\"name\",\"dist.tarball\",\"bin\",\"scripts\",\"os\",\"cpu\",\"libc\",\"dependencies\",\"dependenciesMeta\",\"optionalDependencies\",\"peerDependencies\",\"peerDependenciesMeta\",\"deprecated\"];function R1t(t){return{\"dist-tags\":t[\"dist-tags\"],versions:Object.fromEntries(Object.entries(t.versions).map(([e,r])=>[e,(0,B1e.default)(r,b1e)]))}}var T1t=wn.makeHash(...b1e).slice(0,6);function N1t(t,e){let r=L1t(t),o=new URL(e);return V.join(r,T1t,o.hostname)}function L1t(t){return V.join(t.get(\"globalFolder\"),\"metadata/npm\")}async function ad(t,{configuration:e,headers:r,ident:o,authType:a,registry:n,...u}){n=KB(e,{ident:o,registry:n}),o&&o.scope&&typeof a>\"u\"&&(a=1);let A=await gQ(n,{authType:a,configuration:e,ident:o});A&&(r={...r,authorization:A});try{return await sn.get(t.charAt(0)===\"/\"?`${n}${t}`:t,{configuration:e,headers:r,...u})}catch(p){throw await jh(p,{registry:n,configuration:e,headers:r}),p}}async function M1t(t,e,{attemptedAs:r,configuration:o,headers:a,ident:n,authType:u=3,registry:A,otp:p,...h}){A=KB(o,{ident:n,registry:A});let E=await gQ(A,{authType:u,configuration:o,ident:n});E&&(a={...a,authorization:E}),p&&(a={...a,...pC(p)});try{return await sn.post(A+t,e,{configuration:o,headers:a,...h})}catch(I){if(!dQ(I)||p)throw await jh(I,{attemptedAs:r,registry:A,configuration:o,headers:a}),I;p=await yj(I,{configuration:o});let v={...a,...pC(p)};try{return await sn.post(`${A}${t}`,e,{configuration:o,headers:v,...h})}catch(x){throw await jh(x,{attemptedAs:r,registry:A,configuration:o,headers:a}),x}}}async function O1t(t,e,{attemptedAs:r,configuration:o,headers:a,ident:n,authType:u=3,registry:A,otp:p,...h}){A=KB(o,{ident:n,registry:A});let E=await gQ(A,{authType:u,configuration:o,ident:n});E&&(a={...a,authorization:E}),p&&(a={...a,...pC(p)});try{return await sn.put(A+t,e,{configuration:o,headers:a,...h})}catch(I){if(!dQ(I))throw await jh(I,{attemptedAs:r,registry:A,configuration:o,headers:a}),I;p=await yj(I,{configuration:o});let v={...a,...pC(p)};try{return await sn.put(`${A}${t}`,e,{configuration:o,headers:v,...h})}catch(x){throw await jh(x,{attemptedAs:r,registry:A,configuration:o,headers:a}),x}}}async function U1t(t,{attemptedAs:e,configuration:r,headers:o,ident:a,authType:n=3,registry:u,otp:A,...p}){u=KB(r,{ident:a,registry:u});let h=await gQ(u,{authType:n,configuration:r,ident:a});h&&(o={...o,authorization:h}),A&&(o={...o,...pC(A)});try{return await sn.del(u+t,{configuration:r,headers:o,...p})}catch(E){if(!dQ(E)||A)throw await jh(E,{attemptedAs:e,registry:u,configuration:r,headers:o}),E;A=await yj(E,{configuration:r});let I={...o,...pC(A)};try{return await sn.del(`${u}${t}`,{configuration:r,headers:I,...p})}catch(v){throw await jh(v,{attemptedAs:e,registry:u,configuration:r,headers:o}),v}}}function KB(t,{ident:e,registry:r}){if(typeof r>\"u\"&&e)return fC(e.scope,{configuration:t});if(typeof r!=\"string\")throw new Error(\"Assertion failed: The registry should be a string\");return ac(r)}async function gQ(t,{authType:e=2,configuration:r,ident:o}){let a=dj(t,{configuration:r,ident:o}),n=_1t(a,e);if(!n)return null;let u=await r.reduceHook(A=>A.getNpmAuthenticationHeader,void 0,t,{configuration:r,ident:o});if(u)return u;if(a.get(\"npmAuthToken\"))return`Bearer ${a.get(\"npmAuthToken\")}`;if(a.get(\"npmAuthIdent\")){let A=a.get(\"npmAuthIdent\");return A.includes(\":\")?`Basic ${Buffer.from(A).toString(\"base64\")}`:`Basic ${A}`}if(n&&e!==1)throw new Jt(33,\"No authentication configured for request\");return null}function _1t(t,e){switch(e){case 2:return t.get(\"npmAlwaysAuth\");case 1:case 3:return!0;case 0:return!1;default:throw new Error(\"Unreachable\")}}async function H1t(t,e,{configuration:r}){if(typeof e>\"u\"||typeof e.authorization>\"u\")return\"an anonymous user\";try{return(await sn.get(new URL(`${t}/-/whoami`).href,{configuration:r,headers:e,jsonResponse:!0})).username??\"an unknown user\"}catch{return\"an unknown user\"}}async function yj(t,{configuration:e}){let r=t.originalError?.response.headers[\"npm-notice\"];if(r&&(await Rt.start({configuration:e,stdout:process.stdout,includeFooter:!1},async a=>{if(a.reportInfo(0,r.replace(/(https?:\\/\\/\\S+)/g,pe.pretty(e,\"$1\",pe.Type.URL))),!process.env.YARN_IS_TEST_ENV){let n=r.match(/open (https?:\\/\\/\\S+)/i);if(n&&Xi.openUrl){let{openNow:u}=await(0,mj.prompt)({type:\"confirm\",name:\"openNow\",message:\"Do you want to try to open this url now?\",required:!0,initial:!0,onCancel:()=>process.exit(130)});u&&(await Xi.openUrl(n[1])||(a.reportSeparator(),a.reportWarning(0,\"We failed to automatically open the url; you'll have to open it yourself in your browser of choice.\")))}}}),process.stdout.write(`\n`)),process.env.YARN_IS_TEST_ENV)return process.env.YARN_INJECT_NPM_2FA_TOKEN||\"\";let{otp:o}=await(0,mj.prompt)({type:\"password\",name:\"otp\",message:\"One-time password:\",required:!0,onCancel:()=>process.exit(130)});return process.stdout.write(`\n`),o}function dQ(t){if(t.originalError?.name!==\"HTTPError\")return!1;try{return(t.originalError?.response.headers[\"www-authenticate\"].split(/,\\s*/).map(r=>r.toLowerCase())).includes(\"otp\")}catch{return!1}}function pC(t){return{\"npm-otp\":t}}var VB=class{supports(e,r){if(!e.reference.startsWith(Wn))return!1;let{selector:o,params:a}=G.parseRange(e.reference);return!(!S1e.default.valid(o)||a===null||typeof a.__archiveUrl!=\"string\")}getLocalPath(e,r){return null}async fetch(e,r){let o=r.checksums.get(e.locatorHash)||null,[a,n,u]=await r.cache.fetchPackageFromCache(e,o,{onHit:()=>r.report.reportCacheHit(e),onMiss:()=>r.report.reportCacheMiss(e,`${G.prettyLocator(r.project.configuration,e)} can't be found in the cache and will be fetched from the remote server`),loader:()=>this.fetchFromNetwork(e,r),...r.cacheOptions});return{packageFs:a,releaseFs:n,prefixPath:G.getIdentVendorPath(e),checksum:u}}async fetchFromNetwork(e,r){let{params:o}=G.parseRange(e.reference);if(o===null||typeof o.__archiveUrl!=\"string\")throw new Error(\"Assertion failed: The archiveUrl querystring parameter should have been available\");let a=await ad(o.__archiveUrl,{customErrorMessage:od,configuration:r.project.configuration,ident:e});return await $i.convertToZip(a,{configuration:r.project.configuration,prefixPath:G.getIdentVendorPath(e),stripComponents:1})}};Ge();var zB=class{supportsDescriptor(e,r){return!(!e.range.startsWith(Wn)||!G.tryParseDescriptor(e.range.slice(Wn.length),!0))}supportsLocator(e,r){return!1}shouldPersistResolution(e,r){throw new Error(\"Unreachable\")}bindDescriptor(e,r,o){return e}getResolutionDependencies(e,r){let o=r.project.configuration.normalizeDependency(G.parseDescriptor(e.range.slice(Wn.length),!0));return r.resolver.getResolutionDependencies(o,r)}async getCandidates(e,r,o){let a=o.project.configuration.normalizeDependency(G.parseDescriptor(e.range.slice(Wn.length),!0));return await o.resolver.getCandidates(a,r,o)}async getSatisfying(e,r,o,a){let n=a.project.configuration.normalizeDependency(G.parseDescriptor(e.range.slice(Wn.length),!0));return a.resolver.getSatisfying(n,r,o,a)}resolve(e,r){throw new Error(\"Unreachable\")}};Ge();Ge();var x1e=Ze(Jn());var tp=class t{supports(e,r){if(!e.reference.startsWith(Wn))return!1;let o=new URL(e.reference);return!(!x1e.default.valid(o.pathname)||o.searchParams.has(\"__archiveUrl\"))}getLocalPath(e,r){return null}async fetch(e,r){let o=r.checksums.get(e.locatorHash)||null,[a,n,u]=await r.cache.fetchPackageFromCache(e,o,{onHit:()=>r.report.reportCacheHit(e),onMiss:()=>r.report.reportCacheMiss(e,`${G.prettyLocator(r.project.configuration,e)} can't be found in the cache and will be fetched from the remote registry`),loader:()=>this.fetchFromNetwork(e,r),...r.cacheOptions});return{packageFs:a,releaseFs:n,prefixPath:G.getIdentVendorPath(e),checksum:u}}async fetchFromNetwork(e,r){let o;try{o=await ad(t.getLocatorUrl(e),{customErrorMessage:od,configuration:r.project.configuration,ident:e})}catch{o=await ad(t.getLocatorUrl(e).replace(/%2f/g,\"/\"),{customErrorMessage:od,configuration:r.project.configuration,ident:e})}return await $i.convertToZip(o,{configuration:r.project.configuration,prefixPath:G.getIdentVendorPath(e),stripComponents:1})}static isConventionalTarballUrl(e,r,{configuration:o}){let a=fC(e.scope,{configuration:o}),n=t.getLocatorUrl(e);return r=r.replace(/^https?:(\\/\\/(?:[^/]+\\.)?npmjs.org(?:$|\\/))/,\"https:$1\"),a=a.replace(/^https:\\/\\/registry\\.npmjs\\.org($|\\/)/,\"https://registry.yarnpkg.com$1\"),r=r.replace(/^https:\\/\\/registry\\.npmjs\\.org($|\\/)/,\"https://registry.yarnpkg.com$1\"),r===a+n||r===a+n.replace(/%2f/g,\"/\")}static getLocatorUrl(e){let r=Lr.clean(e.reference.slice(Wn.length));if(r===null)throw new Jt(10,\"The npm semver resolver got selected, but the version isn't semver\");return`${hQ(e)}/-/${e.name}-${r}.tgz`}};Ge();Ge();Ge();var Ej=Ze(Jn());var mQ=G.makeIdent(null,\"node-gyp\"),q1t=/\\b(node-gyp|prebuild-install)\\b/,JB=class{supportsDescriptor(e,r){return e.range.startsWith(Wn)?!!Lr.validRange(e.range.slice(Wn.length)):!1}supportsLocator(e,r){if(!e.reference.startsWith(Wn))return!1;let{selector:o}=G.parseRange(e.reference);return!!Ej.default.valid(o)}shouldPersistResolution(e,r){return!0}bindDescriptor(e,r,o){return e}getResolutionDependencies(e,r){return{}}async getCandidates(e,r,o){let a=Lr.validRange(e.range.slice(Wn.length));if(a===null)throw new Error(`Expected a valid range, got ${e.range.slice(Wn.length)}`);let n=await hC(e,{cache:o.fetchOptions?.cache,project:o.project,version:Ej.default.valid(a.raw)?a.raw:void 0}),u=He.mapAndFilter(Object.keys(n.versions),h=>{try{let E=new Lr.SemVer(h);if(a.test(E))return E}catch{}return He.mapAndFilter.skip}),A=u.filter(h=>!n.versions[h.raw].deprecated),p=A.length>0?A:u;return p.sort((h,E)=>-h.compare(E)),p.map(h=>{let E=G.makeLocator(e,`${Wn}${h.raw}`),I=n.versions[h.raw].dist.tarball;return tp.isConventionalTarballUrl(E,I,{configuration:o.project.configuration})?E:G.bindLocator(E,{__archiveUrl:I})})}async getSatisfying(e,r,o,a){let n=Lr.validRange(e.range.slice(Wn.length));if(n===null)throw new Error(`Expected a valid range, got ${e.range.slice(Wn.length)}`);return{locators:He.mapAndFilter(o,p=>{if(p.identHash!==e.identHash)return He.mapAndFilter.skip;let h=G.tryParseRange(p.reference,{requireProtocol:Wn});if(!h)return He.mapAndFilter.skip;let E=new Lr.SemVer(h.selector);return n.test(E)?{locator:p,version:E}:He.mapAndFilter.skip}).sort((p,h)=>-p.version.compare(h.version)).map(({locator:p})=>p),sorted:!0}}async resolve(e,r){let{selector:o}=G.parseRange(e.reference),a=Lr.clean(o);if(a===null)throw new Jt(10,\"The npm semver resolver got selected, but the version isn't semver\");let n=await hC(e,{cache:r.fetchOptions?.cache,project:r.project,version:a});if(!Object.hasOwn(n,\"versions\"))throw new Jt(15,'Registry returned invalid data for - missing \"versions\" field');if(!Object.hasOwn(n.versions,a))throw new Jt(16,`Registry failed to return reference \"${a}\"`);let u=new Ut;if(u.load(n.versions[a]),!u.dependencies.has(mQ.identHash)&&!u.peerDependencies.has(mQ.identHash)){for(let A of u.scripts.values())if(A.match(q1t)){u.dependencies.set(mQ.identHash,G.makeDescriptor(mQ,\"latest\"));break}}return{...e,version:a,languageName:\"node\",linkType:\"HARD\",conditions:u.getConditions(),dependencies:r.project.configuration.normalizeDependencyMap(u.dependencies),peerDependencies:u.peerDependencies,dependenciesMeta:u.dependenciesMeta,peerDependenciesMeta:u.peerDependenciesMeta,bin:u.bin}}};Ge();Ge();var k1e=Ze(Jn());var XB=class{supportsDescriptor(e,r){return!(!e.range.startsWith(Wn)||!ly.test(e.range.slice(Wn.length)))}supportsLocator(e,r){return!1}shouldPersistResolution(e,r){throw new Error(\"Unreachable\")}bindDescriptor(e,r,o){return e}getResolutionDependencies(e,r){return{}}async getCandidates(e,r,o){let a=e.range.slice(Wn.length),n=await hC(e,{cache:o.fetchOptions?.cache,project:o.project});if(!Object.hasOwn(n,\"dist-tags\"))throw new Jt(15,'Registry returned invalid data - missing \"dist-tags\" field');let u=n[\"dist-tags\"];if(!Object.hasOwn(u,a))throw new Jt(16,`Registry failed to return tag \"${a}\"`);let A=u[a],p=G.makeLocator(e,`${Wn}${A}`),h=n.versions[A].dist.tarball;return tp.isConventionalTarballUrl(p,h,{configuration:o.project.configuration})?[p]:[G.bindLocator(p,{__archiveUrl:h})]}async getSatisfying(e,r,o,a){let n=[];for(let u of o){if(u.identHash!==e.identHash)continue;let A=G.tryParseRange(u.reference,{requireProtocol:Wn});if(!(!A||!k1e.default.valid(A.selector))){if(A.params?.__archiveUrl){let p=G.makeRange({protocol:Wn,selector:A.selector,source:null,params:null}),[h]=await a.resolver.getCandidates(G.makeDescriptor(e,p),r,a);if(u.reference!==h.reference)continue}n.push(u)}}return{locators:n,sorted:!1}}async resolve(e,r){throw new Error(\"Unreachable\")}};var PC={};Vt(PC,{getGitHead:()=>_vt,getPublishAccess:()=>EBe,getReadmeContent:()=>CBe,makePublishBody:()=>Uvt});Ge();Ge();Pt();var a5={};Vt(a5,{PackCommand:()=>DC,default:()=>wvt,packUtils:()=>CA});Ge();Ge();Ge();Pt();qt();var CA={};Vt(CA,{genPackList:()=>_Q,genPackStream:()=>o5,genPackageManifest:()=>aBe,hasPackScripts:()=>i5,prepareForPack:()=>s5});Ge();Pt();var n5=Ze($o()),sBe=Ze(tBe()),oBe=ve(\"zlib\"),uvt=[\"/package.json\",\"/readme\",\"/readme.*\",\"/license\",\"/license.*\",\"/licence\",\"/licence.*\",\"/changelog\",\"/changelog.*\"],Avt=[\"/package.tgz\",\".github\",\".git\",\".hg\",\"node_modules\",\".npmignore\",\".gitignore\",\".#*\",\".DS_Store\"];async function i5(t){return!!(An.hasWorkspaceScript(t,\"prepack\")||An.hasWorkspaceScript(t,\"postpack\"))}async function s5(t,{report:e},r){await An.maybeExecuteWorkspaceLifecycleScript(t,\"prepack\",{report:e});try{let o=V.join(t.cwd,Ut.fileName);await oe.existsPromise(o)&&await t.manifest.loadFile(o,{baseFs:oe}),await r()}finally{await An.maybeExecuteWorkspaceLifecycleScript(t,\"postpack\",{report:e})}}async function o5(t,e){typeof e>\"u\"&&(e=await _Q(t));let r=new Set;for(let n of t.manifest.publishConfig?.executableFiles??new Set)r.add(V.normalize(n));for(let n of t.manifest.bin.values())r.add(V.normalize(n));let o=sBe.default.pack();process.nextTick(async()=>{for(let n of e){let u=V.normalize(n),A=V.resolve(t.cwd,u),p=V.join(\"package\",u),h=await oe.lstatPromise(A),E={name:p,mtime:new Date(Bi.SAFE_TIME*1e3)},I=r.has(u)?493:420,v,x,C=new Promise((L,U)=>{v=L,x=U}),R=L=>{L?x(L):v()};if(h.isFile()){let L;u===\"package.json\"?L=Buffer.from(JSON.stringify(await aBe(t),null,2)):L=await oe.readFilePromise(A),o.entry({...E,mode:I,type:\"file\"},L,R)}else h.isSymbolicLink()?o.entry({...E,mode:I,type:\"symlink\",linkname:await oe.readlinkPromise(A)},R):R(new Error(`Unsupported file type ${h.mode} for ${ue.fromPortablePath(u)}`));await C}o.finalize()});let a=(0,oBe.createGzip)();return o.pipe(a),a}async function aBe(t){let e=JSON.parse(JSON.stringify(t.manifest.raw));return await t.project.configuration.triggerHook(r=>r.beforeWorkspacePacking,t,e),e}async function _Q(t){let e=t.project,r=e.configuration,o={accept:[],reject:[]};for(let I of Avt)o.reject.push(I);for(let I of uvt)o.accept.push(I);o.reject.push(r.get(\"rcFilename\"));let a=I=>{if(I===null||!I.startsWith(`${t.cwd}/`))return;let v=V.relative(t.cwd,I),x=V.resolve(It.root,v);o.reject.push(x)};a(V.resolve(e.cwd,dr.lockfile)),a(r.get(\"cacheFolder\")),a(r.get(\"globalFolder\")),a(r.get(\"installStatePath\")),a(r.get(\"virtualFolder\")),a(r.get(\"yarnPath\")),await r.triggerHook(I=>I.populateYarnPaths,e,I=>{a(I)});for(let I of e.workspaces){let v=V.relative(t.cwd,I.cwd);v!==\"\"&&!v.match(/^(\\.\\.)?\\//)&&o.reject.push(`/${v}`)}let n={accept:[],reject:[]},u=t.manifest.publishConfig?.main??t.manifest.main,A=t.manifest.publishConfig?.module??t.manifest.module,p=t.manifest.publishConfig?.browser??t.manifest.browser,h=t.manifest.publishConfig?.bin??t.manifest.bin;u!=null&&n.accept.push(V.resolve(It.root,u)),A!=null&&n.accept.push(V.resolve(It.root,A)),typeof p==\"string\"&&n.accept.push(V.resolve(It.root,p));for(let I of h.values())n.accept.push(V.resolve(It.root,I));if(p instanceof Map)for(let[I,v]of p.entries())n.accept.push(V.resolve(It.root,I)),typeof v==\"string\"&&n.accept.push(V.resolve(It.root,v));let E=t.manifest.files!==null;if(E){n.reject.push(\"/*\");for(let I of t.manifest.files)lBe(n.accept,I,{cwd:It.root})}return await fvt(t.cwd,{hasExplicitFileList:E,globalList:o,ignoreList:n})}async function fvt(t,{hasExplicitFileList:e,globalList:r,ignoreList:o}){let a=[],n=new qu(t),u=[[It.root,[o]]];for(;u.length>0;){let[A,p]=u.pop(),h=await n.lstatPromise(A);if(!nBe(A,{globalList:r,ignoreLists:h.isDirectory()?null:p}))if(h.isDirectory()){let E=await n.readdirPromise(A),I=!1,v=!1;if(!e||A!==It.root)for(let R of E)I=I||R===\".gitignore\",v=v||R===\".npmignore\";let x=v?await rBe(n,A,\".npmignore\"):I?await rBe(n,A,\".gitignore\"):null,C=x!==null?[x].concat(p):p;nBe(A,{globalList:r,ignoreLists:p})&&(C=[...p,{accept:[],reject:[\"**/*\"]}]);for(let R of E)u.push([V.resolve(A,R),C])}else(h.isFile()||h.isSymbolicLink())&&a.push(V.relative(It.root,A))}return a.sort()}async function rBe(t,e,r){let o={accept:[],reject:[]},a=await t.readFilePromise(V.join(e,r),\"utf8\");for(let n of a.split(/\\n/g))lBe(o.reject,n,{cwd:e});return o}function pvt(t,{cwd:e}){let r=t[0]===\"!\";return r&&(t=t.slice(1)),t.match(/\\.{0,1}\\//)&&(t=V.resolve(e,t)),r&&(t=`!${t}`),t}function lBe(t,e,{cwd:r}){let o=e.trim();o===\"\"||o[0]===\"#\"||t.push(pvt(o,{cwd:r}))}function nBe(t,{globalList:e,ignoreLists:r}){let o=UQ(t,e.accept);if(o!==0)return o===2;let a=UQ(t,e.reject);if(a!==0)return a===1;if(r!==null)for(let n of r){let u=UQ(t,n.accept);if(u!==0)return u===2;let A=UQ(t,n.reject);if(A!==0)return A===1}return!1}function UQ(t,e){let r=e,o=[];for(let a=0;a<e.length;++a)e[a][0]!==\"!\"?r!==e&&r.push(e[a]):(r===e&&(r=e.slice(0,a)),o.push(e[a].slice(1)));return iBe(t,o)?2:iBe(t,r)?1:0}function iBe(t,e){let r=e,o=[];for(let a=0;a<e.length;++a)e[a].includes(\"/\")?r!==e&&r.push(e[a]):(r===e&&(r=e.slice(0,a)),o.push(e[a]));return!!(n5.default.isMatch(t,r,{dot:!0,nocase:!0})||n5.default.isMatch(t,o,{dot:!0,basename:!0,nocase:!0}))}var DC=class extends ut{constructor(){super(...arguments);this.installIfNeeded=ge.Boolean(\"--install-if-needed\",!1,{description:\"Run a preliminary `yarn install` if the package contains build scripts\"});this.dryRun=ge.Boolean(\"-n,--dry-run\",!1,{description:\"Print the file paths without actually generating the package archive\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.out=ge.String(\"-o,--out\",{description:\"Create the archive at the specified path\"});this.filename=ge.String(\"--filename\",{hidden:!0})}static{this.paths=[[\"pack\"]]}static{this.usage=it.Usage({description:\"generate a tarball from the active workspace\",details:\"\\n      This command will turn the active workspace into a compressed archive suitable for publishing. The archive will by default be stored at the root of the workspace (`package.tgz`).\\n\\n      If the `-o,---out` is set the archive will be created at the specified path. The `%s` and `%v` variables can be used within the path and will be respectively replaced by the package name and version.\\n    \",examples:[[\"Create an archive from the active workspace\",\"yarn pack\"],[\"List the files that would be made part of the workspace's archive\",\"yarn pack --dry-run\"],[\"Name and output the archive in a dedicated folder\",\"yarn pack --out /artifacts/%s-%v.tgz\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!a)throw new sr(o.cwd,this.context.cwd);await i5(a)&&(this.installIfNeeded?await o.install({cache:await Gr.find(r),report:new ki}):await o.restoreInstallState());let n=this.out??this.filename,u=typeof n<\"u\"?V.resolve(this.context.cwd,hvt(n,{workspace:a})):V.resolve(a.cwd,\"package.tgz\");return(await Rt.start({configuration:r,stdout:this.context.stdout,json:this.json},async p=>{await s5(a,{report:p},async()=>{p.reportJson({base:ue.fromPortablePath(a.cwd)});let h=await _Q(a);for(let E of h)p.reportInfo(null,ue.fromPortablePath(E)),p.reportJson({location:ue.fromPortablePath(E)});if(!this.dryRun){let E=await o5(a,h),I=oe.createWriteStream(u);E.pipe(I),await new Promise(v=>{I.on(\"finish\",v)})}}),this.dryRun||(p.reportInfo(0,`Package archive generated in ${pe.pretty(r,u,pe.Type.PATH)}`),p.reportJson({output:ue.fromPortablePath(u)}))})).exitCode()}};function hvt(t,{workspace:e}){let r=t.replace(\"%s\",gvt(e)).replace(\"%v\",dvt(e));return ue.toPortablePath(r)}function gvt(t){return t.manifest.name!==null?G.slugifyIdent(t.manifest.name):\"package\"}function dvt(t){return t.manifest.version!==null?t.manifest.version:\"unknown\"}var mvt=[\"dependencies\",\"devDependencies\",\"peerDependencies\"],yvt=\"workspace:\",Evt=(t,e)=>{e.publishConfig&&(e.publishConfig.type&&(e.type=e.publishConfig.type),e.publishConfig.main&&(e.main=e.publishConfig.main),e.publishConfig.browser&&(e.browser=e.publishConfig.browser),e.publishConfig.module&&(e.module=e.publishConfig.module),e.publishConfig.exports&&(e.exports=e.publishConfig.exports),e.publishConfig.imports&&(e.imports=e.publishConfig.imports),e.publishConfig.bin&&(e.bin=e.publishConfig.bin));let r=t.project;for(let o of mvt)for(let a of t.manifest.getForScope(o).values()){let n=r.tryWorkspaceByDescriptor(a),u=G.parseRange(a.range);if(u.protocol===yvt)if(n===null){if(r.tryWorkspaceByIdent(a)===null)throw new Jt(21,`${G.prettyDescriptor(r.configuration,a)}: No local workspace found for this range`)}else{let A;G.areDescriptorsEqual(a,n.anchoredDescriptor)||u.selector===\"*\"?A=n.manifest.version??\"0.0.0\":u.selector===\"~\"||u.selector===\"^\"?A=`${u.selector}${n.manifest.version??\"0.0.0\"}`:A=u.selector;let p=o===\"dependencies\"?G.makeDescriptor(a,\"unknown\"):null,h=p!==null&&t.manifest.ensureDependencyMeta(p).optional?\"optionalDependencies\":o;e[h][G.stringifyIdent(a)]=A}}},Cvt={hooks:{beforeWorkspacePacking:Evt},commands:[DC]},wvt=Cvt;var mBe=ve(\"crypto\"),yBe=Ze(dBe());async function Uvt(t,e,{access:r,tag:o,registry:a,gitHead:n}){let u=t.manifest.name,A=t.manifest.version,p=G.stringifyIdent(u),h=(0,mBe.createHash)(\"sha1\").update(e).digest(\"hex\"),E=yBe.default.fromData(e).toString(),I=r??EBe(t,u),v=await CBe(t),x=await CA.genPackageManifest(t),C=`${p}-${A}.tgz`,R=new URL(`${ac(a)}/${p}/-/${C}`);return{_id:p,_attachments:{[C]:{content_type:\"application/octet-stream\",data:e.toString(\"base64\"),length:e.length}},name:p,access:I,\"dist-tags\":{[o]:A},versions:{[A]:{...x,_id:`${p}@${A}`,name:p,version:A,gitHead:n,dist:{shasum:h,integrity:E,tarball:R.toString()}}},readme:v}}async function _vt(t){try{let{stdout:e}=await Ur.execvp(\"git\",[\"rev-parse\",\"--revs-only\",\"HEAD\"],{cwd:t});return e.trim()===\"\"?void 0:e.trim()}catch{return}}function EBe(t,e){let r=t.project.configuration;return t.manifest.publishConfig&&typeof t.manifest.publishConfig.access==\"string\"?t.manifest.publishConfig.access:r.get(\"npmPublishAccess\")!==null?r.get(\"npmPublishAccess\"):e.scope?\"restricted\":\"public\"}async function CBe(t){let e=ue.toPortablePath(`${t.cwd}/README.md`),r=t.manifest.name,a=`# ${G.stringifyIdent(r)}\n`;try{a=await oe.readFilePromise(e,\"utf8\")}catch(n){if(n.code===\"ENOENT\")return a;throw n}return a}var A5={npmAlwaysAuth:{description:\"URL of the selected npm registry (note: npm enterprise isn't supported)\",type:\"BOOLEAN\",default:!1},npmAuthIdent:{description:\"Authentication identity for the npm registry (_auth in npm and yarn v1)\",type:\"SECRET\",default:null},npmAuthToken:{description:\"Authentication token for the npm registry (_authToken in npm and yarn v1)\",type:\"SECRET\",default:null}},wBe={npmAuditRegistry:{description:\"Registry to query for audit reports\",type:\"STRING\",default:null},npmPublishRegistry:{description:\"Registry to push packages to\",type:\"STRING\",default:null},npmRegistryServer:{description:\"URL of the selected npm registry (note: npm enterprise isn't supported)\",type:\"STRING\",default:\"https://registry.yarnpkg.com\"}},Hvt={configuration:{...A5,...wBe,npmScopes:{description:\"Settings per package scope\",type:\"MAP\",valueDefinition:{description:\"\",type:\"SHAPE\",properties:{...A5,...wBe}}},npmRegistries:{description:\"Settings per registry\",type:\"MAP\",normalizeKeys:ac,valueDefinition:{description:\"\",type:\"SHAPE\",properties:{...A5}}}},fetchers:[VB,tp],resolvers:[zB,JB,XB]},qvt=Hvt;var w5={};Vt(w5,{NpmAuditCommand:()=>SC,NpmInfoCommand:()=>xC,NpmLoginCommand:()=>kC,NpmLogoutCommand:()=>FC,NpmPublishCommand:()=>RC,NpmTagAddCommand:()=>NC,NpmTagListCommand:()=>TC,NpmTagRemoveCommand:()=>LC,NpmWhoamiCommand:()=>MC,default:()=>zvt,npmAuditTypes:()=>dv,npmAuditUtils:()=>HQ});Ge();Ge();qt();var m5=Ze($o());el();var dv={};Vt(dv,{Environment:()=>hv,Severity:()=>gv});var hv=(o=>(o.All=\"all\",o.Production=\"production\",o.Development=\"development\",o))(hv||{}),gv=(n=>(n.Info=\"info\",n.Low=\"low\",n.Moderate=\"moderate\",n.High=\"high\",n.Critical=\"critical\",n))(gv||{});var HQ={};Vt(HQ,{allSeverities:()=>bC,getPackages:()=>d5,getReportTree:()=>h5,getSeverityInclusions:()=>p5,getTopLevelDependencies:()=>g5});Ge();var IBe=Ze(Jn());var bC=[\"info\",\"low\",\"moderate\",\"high\",\"critical\"];function p5(t){if(typeof t>\"u\")return new Set(bC);let e=bC.indexOf(t),r=bC.slice(e);return new Set(r)}function h5(t){let e={},r={children:e};for(let[o,a]of He.sortMap(Object.entries(t),n=>n[0]))for(let n of He.sortMap(a,u=>`${u.id}`))e[`${o}/${n.id}`]={value:pe.tuple(pe.Type.IDENT,G.parseIdent(o)),children:{ID:typeof n.id<\"u\"&&{label:\"ID\",value:pe.tuple(pe.Type.ID,n.id)},Issue:{label:\"Issue\",value:pe.tuple(pe.Type.NO_HINT,n.title)},URL:typeof n.url<\"u\"&&{label:\"URL\",value:pe.tuple(pe.Type.URL,n.url)},Severity:{label:\"Severity\",value:pe.tuple(pe.Type.NO_HINT,n.severity)},\"Vulnerable Versions\":{label:\"Vulnerable Versions\",value:pe.tuple(pe.Type.RANGE,n.vulnerable_versions)},\"Tree Versions\":{label:\"Tree Versions\",children:[...n.versions].sort(IBe.default.compare).map(u=>({value:pe.tuple(pe.Type.REFERENCE,u)}))},Dependents:{label:\"Dependents\",children:He.sortMap(n.dependents,u=>G.stringifyLocator(u)).map(u=>({value:pe.tuple(pe.Type.LOCATOR,u)}))}}};return r}function g5(t,e,{all:r,environment:o}){let a=[],n=r?t.workspaces:[e],u=[\"all\",\"production\"].includes(o),A=[\"all\",\"development\"].includes(o);for(let p of n)for(let h of p.anchoredPackage.dependencies.values())(p.manifest.devDependencies.has(h.identHash)?!A:!u)||a.push({workspace:p,dependency:h});return a}function d5(t,e,{recursive:r}){let o=new Map,a=new Set,n=[],u=(A,p)=>{let h=t.storedResolutions.get(p.descriptorHash);if(typeof h>\"u\")throw new Error(\"Assertion failed: The resolution should have been registered\");if(!a.has(h))a.add(h);else return;let E=t.storedPackages.get(h);if(typeof E>\"u\")throw new Error(\"Assertion failed: The package should have been registered\");if(G.ensureDevirtualizedLocator(E).reference.startsWith(\"npm:\")&&E.version!==null){let v=G.stringifyIdent(E),x=He.getMapWithDefault(o,v);He.getArrayWithDefault(x,E.version).push(A)}if(r)for(let v of E.dependencies.values())n.push([E,v])};for(let{workspace:A,dependency:p}of e)n.push([A.anchoredLocator,p]);for(;n.length>0;){let[A,p]=n.shift();u(A,p)}return o}var SC=class extends ut{constructor(){super(...arguments);this.all=ge.Boolean(\"-A,--all\",!1,{description:\"Audit dependencies from all workspaces\"});this.recursive=ge.Boolean(\"-R,--recursive\",!1,{description:\"Audit transitive dependencies as well\"});this.environment=ge.String(\"--environment\",\"all\",{description:\"Which environments to cover\",validator:Js(hv)});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.noDeprecations=ge.Boolean(\"--no-deprecations\",!1,{description:\"Don't warn about deprecated packages\"});this.severity=ge.String(\"--severity\",\"info\",{description:\"Minimal severity requested for packages to be displayed\",validator:Js(gv)});this.excludes=ge.Array(\"--exclude\",[],{description:\"Array of glob patterns of packages to exclude from audit\"});this.ignores=ge.Array(\"--ignore\",[],{description:\"Array of glob patterns of advisory ID's to ignore in the audit report\"})}static{this.paths=[[\"npm\",\"audit\"]]}static{this.usage=it.Usage({description:\"perform a vulnerability audit against the installed packages\",details:`\n      This command checks for known security reports on the packages you use. The reports are by default extracted from the npm registry, and may or may not be relevant to your actual program (not all vulnerabilities affect all code paths).\n\n      For consistency with our other commands the default is to only check the direct dependencies for the active workspace. To extend this search to all workspaces, use \\`-A,--all\\`. To extend this search to both direct and transitive dependencies, use \\`-R,--recursive\\`.\n\n      Applying the \\`--severity\\` flag will limit the audit table to vulnerabilities of the corresponding severity and above. Valid values are ${bC.map(r=>`\\`${r}\\``).join(\", \")}.\n\n      If the \\`--json\\` flag is set, Yarn will print the output exactly as received from the registry. Regardless of this flag, the process will exit with a non-zero exit code if a report is found for the selected packages.\n\n      If certain packages produce false positives for a particular environment, the \\`--exclude\\` flag can be used to exclude any number of packages from the audit. This can also be set in the configuration file with the \\`npmAuditExcludePackages\\` option.\n\n      If particular advisories are needed to be ignored, the \\`--ignore\\` flag can be used with Advisory ID's to ignore any number of advisories in the audit report. This can also be set in the configuration file with the \\`npmAuditIgnoreAdvisories\\` option.\n\n      To understand the dependency tree requiring vulnerable packages, check the raw report with the \\`--json\\` flag or use \\`yarn why package\\` to get more information as to who depends on them.\n    `,examples:[[\"Checks for known security issues with the installed packages. The output is a list of known issues.\",\"yarn npm audit\"],[\"Audit dependencies in all workspaces\",\"yarn npm audit --all\"],[\"Limit auditing to `dependencies` (excludes `devDependencies`)\",\"yarn npm audit --environment production\"],[\"Show audit report as valid JSON\",\"yarn npm audit --json\"],[\"Audit all direct and transitive dependencies\",\"yarn npm audit --recursive\"],[\"Output moderate (or more severe) vulnerabilities\",\"yarn npm audit --severity moderate\"],[\"Exclude certain packages\",\"yarn npm audit --exclude package1 --exclude package2\"],[\"Ignore specific advisories\",\"yarn npm audit --ignore 1234567 --ignore 7654321\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!a)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState();let n=g5(o,a,{all:this.all,environment:this.environment}),u=d5(o,n,{recursive:this.recursive}),A=Array.from(new Set([...r.get(\"npmAuditExcludePackages\"),...this.excludes])),p=Object.create(null);for(let[L,U]of u)A.some(z=>m5.default.isMatch(L,z))||(p[L]=[...U.keys()]);let h=Zn.getAuditRegistry({configuration:r}),E,I=await AA.start({configuration:r,stdout:this.context.stdout},async()=>{let L=Zr.post(\"/-/npm/v1/security/advisories/bulk\",p,{authType:Zr.AuthType.BEST_EFFORT,configuration:r,jsonResponse:!0,registry:h}),U=this.noDeprecations?[]:await Promise.all(Array.from(Object.entries(p),async([te,ae])=>{let le=await Zr.getPackageMetadata(G.parseIdent(te),{project:o});return He.mapAndFilter(ae,ce=>{let{deprecated:Ce}=le.versions[ce];return Ce?[te,ce,Ce]:He.mapAndFilter.skip})})),z=await L;for(let[te,ae,le]of U.flat(1))Object.hasOwn(z,te)&&z[te].some(ce=>Lr.satisfiesWithPrereleases(ae,ce.vulnerable_versions))||(z[te]??=[],z[te].push({id:`${te} (deprecation)`,title:le.trim()||\"This package has been deprecated.\",severity:\"moderate\",vulnerable_versions:ae}));E=z});if(I.hasErrors())return I.exitCode();let v=p5(this.severity),x=Array.from(new Set([...r.get(\"npmAuditIgnoreAdvisories\"),...this.ignores])),C=Object.create(null);for(let[L,U]of Object.entries(E)){let z=U.filter(te=>!m5.default.isMatch(`${te.id}`,x)&&v.has(te.severity));z.length>0&&(C[L]=z.map(te=>{let ae=u.get(L);if(typeof ae>\"u\")throw new Error(\"Assertion failed: Expected the registry to only return packages that were requested\");let le=[...ae.keys()].filter(Ce=>Lr.satisfiesWithPrereleases(Ce,te.vulnerable_versions)),ce=new Map;for(let Ce of le)for(let de of ae.get(Ce))ce.set(de.locatorHash,de);return{...te,versions:le,dependents:[...ce.values()]}}))}let R=Object.keys(C).length>0;return R?(fs.emitTree(h5(C),{configuration:r,json:this.json,stdout:this.context.stdout,separators:2}),1):(await Rt.start({configuration:r,includeFooter:!1,json:this.json,stdout:this.context.stdout},async L=>{L.reportInfo(1,\"No audit suggestions\")}),R?1:0)}};Ge();Ge();Pt();qt();var y5=Ze(Jn()),E5=ve(\"util\"),xC=class extends ut{constructor(){super(...arguments);this.fields=ge.String(\"-f,--fields\",{description:\"A comma-separated list of manifest fields that should be displayed\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.packages=ge.Rest()}static{this.paths=[[\"npm\",\"info\"]]}static{this.usage=it.Usage({category:\"Npm-related commands\",description:\"show information about a package\",details:\"\\n      This command fetches information about a package from the npm registry and prints it in a tree format.\\n\\n      The package does not have to be installed locally, but needs to have been published (in particular, local changes will be ignored even for workspaces).\\n\\n      Append `@<range>` to the package argument to provide information specific to the latest version that satisfies the range or to the corresponding tagged version. If the range is invalid or if there is no version satisfying the range, the command will print a warning and fall back to the latest version.\\n\\n      If the `-f,--fields` option is set, it's a comma-separated list of fields which will be used to only display part of the package information.\\n\\n      By default, this command won't return the `dist`, `readme`, and `users` fields, since they are often very long. To explicitly request those fields, explicitly list them with the `--fields` flag or request the output in JSON mode.\\n    \",examples:[[\"Show all available information about react (except the `dist`, `readme`, and `users` fields)\",\"yarn npm info react\"],[\"Show all available information about react as valid JSON (including the `dist`, `readme`, and `users` fields)\",\"yarn npm info react --json\"],[\"Show all available information about react@16.12.0\",\"yarn npm info react@16.12.0\"],[\"Show all available information about react@next\",\"yarn npm info react@next\"],[\"Show the description of react\",\"yarn npm info react --fields description\"],[\"Show all available versions of react\",\"yarn npm info react --fields versions\"],[\"Show the readme of react\",\"yarn npm info react --fields readme\"],[\"Show a few fields of react\",\"yarn npm info react --fields homepage,repository\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o}=await kt.find(r,this.context.cwd),a=typeof this.fields<\"u\"?new Set([\"name\",...this.fields.split(/\\s*,\\s*/)]):null,n=[],u=!1,A=await Rt.start({configuration:r,includeFooter:!1,json:this.json,stdout:this.context.stdout},async p=>{for(let h of this.packages){let E;if(h===\".\"){let ae=o.topLevelWorkspace;if(!ae.manifest.name)throw new st(`Missing ${pe.pretty(r,\"name\",pe.Type.CODE)} field in ${ue.fromPortablePath(V.join(ae.cwd,dr.manifest))}`);E=G.makeDescriptor(ae.manifest.name,\"unknown\")}else E=G.parseDescriptor(h);let I=Zr.getIdentUrl(E),v=C5(await Zr.get(I,{configuration:r,ident:E,jsonResponse:!0,customErrorMessage:Zr.customPackageError})),x=Object.keys(v.versions).sort(y5.default.compareLoose),R=v[\"dist-tags\"].latest||x[x.length-1],L=Lr.validRange(E.range);if(L){let ae=y5.default.maxSatisfying(x,L);ae!==null?R=ae:(p.reportWarning(0,`Unmet range ${G.prettyRange(r,E.range)}; falling back to the latest version`),u=!0)}else Object.hasOwn(v[\"dist-tags\"],E.range)?R=v[\"dist-tags\"][E.range]:E.range!==\"unknown\"&&(p.reportWarning(0,`Unknown tag ${G.prettyRange(r,E.range)}; falling back to the latest version`),u=!0);let U=v.versions[R],z={...v,...U,version:R,versions:x},te;if(a!==null){te={};for(let ae of a){let le=z[ae];if(typeof le<\"u\")te[ae]=le;else{p.reportWarning(1,`The ${pe.pretty(r,ae,pe.Type.CODE)} field doesn't exist inside ${G.prettyIdent(r,E)}'s information`),u=!0;continue}}}else this.json||(delete z.dist,delete z.readme,delete z.users),te=z;p.reportJson(te),this.json||n.push(te)}});E5.inspect.styles.name=\"cyan\";for(let p of n)(p!==n[0]||u)&&this.context.stdout.write(`\n`),this.context.stdout.write(`${(0,E5.inspect)(p,{depth:1/0,colors:!0,compact:!1})}\n`);return A.exitCode()}};function C5(t){if(Array.isArray(t)){let e=[];for(let r of t)r=C5(r),r&&e.push(r);return e}else if(typeof t==\"object\"&&t!==null){let e={};for(let r of Object.keys(t)){if(r.startsWith(\"_\"))continue;let o=C5(t[r]);o&&(e[r]=o)}return e}else return t||null}Ge();Ge();qt();var BBe=Ze(J1()),kC=class extends ut{constructor(){super(...arguments);this.scope=ge.String(\"-s,--scope\",{description:\"Login to the registry configured for a given scope\"});this.publish=ge.Boolean(\"--publish\",!1,{description:\"Login to the publish registry\"});this.alwaysAuth=ge.Boolean(\"--always-auth\",{description:\"Set the npmAlwaysAuth configuration\"})}static{this.paths=[[\"npm\",\"login\"]]}static{this.usage=it.Usage({category:\"Npm-related commands\",description:\"store new login info to access the npm registry\",details:\"\\n      This command will ask you for your username, password, and 2FA One-Time-Password (when it applies). It will then modify your local configuration (in your home folder, never in the project itself) to reference the new tokens thus generated.\\n\\n      Adding the `-s,--scope` flag will cause the authentication to be done against whatever registry is configured for the associated scope (see also `npmScopes`).\\n\\n      Adding the `--publish` flag will cause the authentication to be done against the registry used when publishing the package (see also `publishConfig.registry` and `npmPublishRegistry`).\\n    \",examples:[[\"Login to the default registry\",\"yarn npm login\"],[\"Login to the registry linked to the @my-scope registry\",\"yarn npm login --scope my-scope\"],[\"Login to the publish registry for the current package\",\"yarn npm login --publish\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),o=await qQ({configuration:r,cwd:this.context.cwd,publish:this.publish,scope:this.scope});return(await Rt.start({configuration:r,stdout:this.context.stdout,includeFooter:!1},async n=>{let u=await Yvt({configuration:r,registry:o,report:n,stdin:this.context.stdin,stdout:this.context.stdout}),A=await jvt(o,u,r);return await Gvt(o,A,{alwaysAuth:this.alwaysAuth,scope:this.scope}),n.reportInfo(0,\"Successfully logged in\")})).exitCode()}};async function qQ({scope:t,publish:e,configuration:r,cwd:o}){return t&&e?Zn.getScopeRegistry(t,{configuration:r,type:Zn.RegistryType.PUBLISH_REGISTRY}):t?Zn.getScopeRegistry(t,{configuration:r}):e?Zn.getPublishRegistry((await _y(r,o)).manifest,{configuration:r}):Zn.getDefaultRegistry({configuration:r})}async function jvt(t,e,r){let o=`/-/user/org.couchdb.user:${encodeURIComponent(e.name)}`,a={_id:`org.couchdb.user:${e.name}`,name:e.name,password:e.password,type:\"user\",roles:[],date:new Date().toISOString()},n={attemptedAs:e.name,configuration:r,registry:t,jsonResponse:!0,authType:Zr.AuthType.NO_AUTH};try{return(await Zr.put(o,a,n)).token}catch(E){if(!(E.originalError?.name===\"HTTPError\"&&E.originalError?.response.statusCode===409))throw E}let u={...n,authType:Zr.AuthType.NO_AUTH,headers:{authorization:`Basic ${Buffer.from(`${e.name}:${e.password}`).toString(\"base64\")}`}},A=await Zr.get(o,u);for(let[E,I]of Object.entries(A))(!a[E]||E===\"roles\")&&(a[E]=I);let p=`${o}/-rev/${a._rev}`;return(await Zr.put(p,a,u)).token}async function Gvt(t,e,{alwaysAuth:r,scope:o}){let a=u=>A=>{let p=He.isIndexableObject(A)?A:{},h=p[u],E=He.isIndexableObject(h)?h:{};return{...p,[u]:{...E,...r!==void 0?{npmAlwaysAuth:r}:{},npmAuthToken:e}}},n=o?{npmScopes:a(o)}:{npmRegistries:a(t)};return await Ke.updateHomeConfiguration(n)}async function Yvt({configuration:t,registry:e,report:r,stdin:o,stdout:a}){r.reportInfo(0,`Logging in to ${pe.pretty(t,e,pe.Type.URL)}`);let n=!1;if(e.match(/^https:\\/\\/npm\\.pkg\\.github\\.com(\\/|$)/)&&(r.reportInfo(0,\"You seem to be using the GitHub Package Registry. Tokens must be generated with the 'repo', 'write:packages', and 'read:packages' permissions.\"),n=!0),r.reportSeparator(),t.env.YARN_IS_TEST_ENV)return{name:t.env.YARN_INJECT_NPM_USER||\"\",password:t.env.YARN_INJECT_NPM_PASSWORD||\"\"};let u=await(0,BBe.prompt)([{type:\"input\",name:\"name\",message:\"Username:\",required:!0,onCancel:()=>process.exit(130),stdin:o,stdout:a},{type:\"password\",name:\"password\",message:n?\"Token:\":\"Password:\",required:!0,onCancel:()=>process.exit(130),stdin:o,stdout:a}]);return r.reportSeparator(),u}Ge();Ge();qt();var QC=new Set([\"npmAuthIdent\",\"npmAuthToken\"]),FC=class extends ut{constructor(){super(...arguments);this.scope=ge.String(\"-s,--scope\",{description:\"Logout of the registry configured for a given scope\"});this.publish=ge.Boolean(\"--publish\",!1,{description:\"Logout of the publish registry\"});this.all=ge.Boolean(\"-A,--all\",!1,{description:\"Logout of all registries\"})}static{this.paths=[[\"npm\",\"logout\"]]}static{this.usage=it.Usage({category:\"Npm-related commands\",description:\"logout of the npm registry\",details:\"\\n      This command will log you out by modifying your local configuration (in your home folder, never in the project itself) to delete all credentials linked to a registry.\\n\\n      Adding the `-s,--scope` flag will cause the deletion to be done against whatever registry is configured for the associated scope (see also `npmScopes`).\\n\\n      Adding the `--publish` flag will cause the deletion to be done against the registry used when publishing the package (see also `publishConfig.registry` and `npmPublishRegistry`).\\n\\n      Adding the `-A,--all` flag will cause the deletion to be done against all registries and scopes.\\n    \",examples:[[\"Logout of the default registry\",\"yarn npm logout\"],[\"Logout of the @my-scope scope\",\"yarn npm logout --scope my-scope\"],[\"Logout of the publish registry for the current package\",\"yarn npm logout --publish\"],[\"Logout of all registries\",\"yarn npm logout --all\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),o=async()=>{let n=await qQ({configuration:r,cwd:this.context.cwd,publish:this.publish,scope:this.scope}),u=await Ke.find(this.context.cwd,this.context.plugins),A=G.makeIdent(this.scope??null,\"pkg\");return!Zn.getAuthConfiguration(n,{configuration:u,ident:A}).get(\"npmAuthToken\")};return(await Rt.start({configuration:r,stdout:this.context.stdout},async n=>{if(this.all&&(await Kvt(),n.reportInfo(0,\"Successfully logged out from everything\")),this.scope){await vBe(\"npmScopes\",this.scope),await o()?n.reportInfo(0,`Successfully logged out from ${this.scope}`):n.reportWarning(0,\"Scope authentication settings removed, but some other ones settings still apply to it\");return}let u=await qQ({configuration:r,cwd:this.context.cwd,publish:this.publish});await vBe(\"npmRegistries\",u),await o()?n.reportInfo(0,`Successfully logged out from ${u}`):n.reportWarning(0,\"Registry authentication settings removed, but some other ones settings still apply to it\")})).exitCode()}};function Wvt(t,e){let r=t[e];if(!He.isIndexableObject(r))return!1;let o=new Set(Object.keys(r));if([...QC].every(n=>!o.has(n)))return!1;for(let n of QC)o.delete(n);if(o.size===0)return t[e]=void 0,!0;let a={...r};for(let n of QC)delete a[n];return t[e]=a,!0}async function Kvt(){let t=e=>{let r=!1,o=He.isIndexableObject(e)?{...e}:{};o.npmAuthToken&&(delete o.npmAuthToken,r=!0);for(let a of Object.keys(o))Wvt(o,a)&&(r=!0);if(Object.keys(o).length!==0)return r?o:e};return await Ke.updateHomeConfiguration({npmRegistries:t,npmScopes:t})}async function vBe(t,e){return await Ke.updateHomeConfiguration({[t]:r=>{let o=He.isIndexableObject(r)?r:{};if(!Object.hasOwn(o,e))return r;let a=o[e],n=He.isIndexableObject(a)?a:{},u=new Set(Object.keys(n));if([...QC].every(p=>!u.has(p)))return r;for(let p of QC)u.delete(p);if(u.size===0)return Object.keys(o).length===1?void 0:{...o,[e]:void 0};let A={};for(let p of QC)A[p]=void 0;return{...o,[e]:{...n,...A}}}})}Ge();qt();var RC=class extends ut{constructor(){super(...arguments);this.access=ge.String(\"--access\",{description:\"The access for the published package (public or restricted)\"});this.tag=ge.String(\"--tag\",\"latest\",{description:\"The tag on the registry that the package should be attached to\"});this.tolerateRepublish=ge.Boolean(\"--tolerate-republish\",!1,{description:\"Warn and exit when republishing an already existing version of a package\"});this.otp=ge.String(\"--otp\",{description:\"The OTP token to use with the command\"})}static{this.paths=[[\"npm\",\"publish\"]]}static{this.usage=it.Usage({category:\"Npm-related commands\",description:\"publish the active workspace to the npm registry\",details:'\\n      This command will pack the active workspace into a fresh archive and upload it to the npm registry.\\n\\n      The package will by default be attached to the `latest` tag on the registry, but this behavior can be overridden by using the `--tag` option.\\n\\n      Note that for legacy reasons scoped packages are by default published with an access set to `restricted` (aka \"private packages\"). This requires you to register for a paid npm plan. In case you simply wish to publish a public scoped package to the registry (for free), just add the `--access public` flag. This behavior can be enabled by default through the `npmPublishAccess` settings.\\n    ',examples:[[\"Publish the active workspace\",\"yarn npm publish\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!a)throw new sr(o.cwd,this.context.cwd);if(a.manifest.private)throw new st(\"Private workspaces cannot be published\");if(a.manifest.name===null||a.manifest.version===null)throw new st(\"Workspaces must have valid names and versions to be published on an external registry\");await o.restoreInstallState();let n=a.manifest.name,u=a.manifest.version,A=Zn.getPublishRegistry(a.manifest,{configuration:r});return(await Rt.start({configuration:r,stdout:this.context.stdout},async h=>{if(this.tolerateRepublish)try{let E=await Zr.get(Zr.getIdentUrl(n),{configuration:r,registry:A,ident:n,jsonResponse:!0});if(!Object.hasOwn(E,\"versions\"))throw new Jt(15,'Registry returned invalid data for - missing \"versions\" field');if(Object.hasOwn(E.versions,u)){h.reportWarning(0,`Registry already knows about version ${u}; skipping.`);return}}catch(E){if(E.originalError?.response?.statusCode!==404)throw E}await An.maybeExecuteWorkspaceLifecycleScript(a,\"prepublish\",{report:h}),await CA.prepareForPack(a,{report:h},async()=>{let E=await CA.genPackList(a);for(let R of E)h.reportInfo(null,R);let I=await CA.genPackStream(a,E),v=await He.bufferStream(I),x=await PC.getGitHead(a.cwd),C=await PC.makePublishBody(a,v,{access:this.access,tag:this.tag,registry:A,gitHead:x});await Zr.put(Zr.getIdentUrl(n),C,{configuration:r,registry:A,ident:n,otp:this.otp,jsonResponse:!0})}),h.reportInfo(0,\"Package archive published\")})).exitCode()}};Ge();qt();var DBe=Ze(Jn());Ge();Pt();qt();var TC=class extends ut{constructor(){super(...arguments);this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.package=ge.String({required:!1})}static{this.paths=[[\"npm\",\"tag\",\"list\"]]}static{this.usage=it.Usage({category:\"Npm-related commands\",description:\"list all dist-tags of a package\",details:`\n      This command will list all tags of a package from the npm registry.\n\n      If the package is not specified, Yarn will default to the current workspace.\n    `,examples:[[\"List all tags of package `my-pkg`\",\"yarn npm tag list my-pkg\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n;if(typeof this.package<\"u\")n=G.parseIdent(this.package);else{if(!a)throw new sr(o.cwd,this.context.cwd);if(!a.manifest.name)throw new st(`Missing 'name' field in ${ue.fromPortablePath(V.join(a.cwd,dr.manifest))}`);n=a.manifest.name}let u=await mv(n,r),p={children:He.sortMap(Object.entries(u),([h])=>h).map(([h,E])=>({value:pe.tuple(pe.Type.RESOLUTION,{descriptor:G.makeDescriptor(n,h),locator:G.makeLocator(n,E)})}))};return fs.emitTree(p,{configuration:r,json:this.json,stdout:this.context.stdout})}};async function mv(t,e){let r=`/-/package${Zr.getIdentUrl(t)}/dist-tags`;return Zr.get(r,{configuration:e,ident:t,jsonResponse:!0,customErrorMessage:Zr.customPackageError})}var NC=class extends ut{constructor(){super(...arguments);this.package=ge.String();this.tag=ge.String()}static{this.paths=[[\"npm\",\"tag\",\"add\"]]}static{this.usage=it.Usage({category:\"Npm-related commands\",description:\"add a tag for a specific version of a package\",details:`\n      This command will add a tag to the npm registry for a specific version of a package. If the tag already exists, it will be overwritten.\n    `,examples:[[\"Add a `beta` tag for version `2.3.4-beta.4` of package `my-pkg`\",\"yarn npm tag add my-pkg@2.3.4-beta.4 beta\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!a)throw new sr(o.cwd,this.context.cwd);let n=G.parseDescriptor(this.package,!0),u=n.range;if(!DBe.default.valid(u))throw new st(`The range ${pe.pretty(r,n.range,pe.Type.RANGE)} must be a valid semver version`);let A=Zn.getPublishRegistry(a.manifest,{configuration:r}),p=pe.pretty(r,n,pe.Type.IDENT),h=pe.pretty(r,u,pe.Type.RANGE),E=pe.pretty(r,this.tag,pe.Type.CODE);return(await Rt.start({configuration:r,stdout:this.context.stdout},async v=>{let x=await mv(n,r);Object.hasOwn(x,this.tag)&&x[this.tag]===u&&v.reportWarning(0,`Tag ${E} is already set to version ${h}`);let C=`/-/package${Zr.getIdentUrl(n)}/dist-tags/${encodeURIComponent(this.tag)}`;await Zr.put(C,u,{configuration:r,registry:A,ident:n,jsonRequest:!0,jsonResponse:!0}),v.reportInfo(0,`Tag ${E} added to version ${h} of package ${p}`)})).exitCode()}};Ge();qt();var LC=class extends ut{constructor(){super(...arguments);this.package=ge.String();this.tag=ge.String()}static{this.paths=[[\"npm\",\"tag\",\"remove\"]]}static{this.usage=it.Usage({category:\"Npm-related commands\",description:\"remove a tag from a package\",details:`\n      This command will remove a tag from a package from the npm registry.\n    `,examples:[[\"Remove the `beta` tag from package `my-pkg`\",\"yarn npm tag remove my-pkg beta\"]]})}async execute(){if(this.tag===\"latest\")throw new st(\"The 'latest' tag cannot be removed.\");let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!a)throw new sr(o.cwd,this.context.cwd);let n=G.parseIdent(this.package),u=Zn.getPublishRegistry(a.manifest,{configuration:r}),A=pe.pretty(r,this.tag,pe.Type.CODE),p=pe.pretty(r,n,pe.Type.IDENT),h=await mv(n,r);if(!Object.hasOwn(h,this.tag))throw new st(`${A} is not a tag of package ${p}`);return(await Rt.start({configuration:r,stdout:this.context.stdout},async I=>{let v=`/-/package${Zr.getIdentUrl(n)}/dist-tags/${encodeURIComponent(this.tag)}`;await Zr.del(v,{configuration:r,registry:u,ident:n,jsonResponse:!0}),I.reportInfo(0,`Tag ${A} removed from package ${p}`)})).exitCode()}};Ge();Ge();qt();var MC=class extends ut{constructor(){super(...arguments);this.scope=ge.String(\"-s,--scope\",{description:\"Print username for the registry configured for a given scope\"});this.publish=ge.Boolean(\"--publish\",!1,{description:\"Print username for the publish registry\"})}static{this.paths=[[\"npm\",\"whoami\"]]}static{this.usage=it.Usage({category:\"Npm-related commands\",description:\"display the name of the authenticated user\",details:\"\\n      Print the username associated with the current authentication settings to the standard output.\\n\\n      When using `-s,--scope`, the username printed will be the one that matches the authentication settings of the registry associated with the given scope (those settings can be overriden using the `npmRegistries` map, and the registry associated with the scope is configured via the `npmScopes` map).\\n\\n      When using `--publish`, the registry we'll select will by default be the one used when publishing packages (`publishConfig.registry` or `npmPublishRegistry` if available, otherwise we'll fallback to the regular `npmRegistryServer`).\\n    \",examples:[[\"Print username for the default registry\",\"yarn npm whoami\"],[\"Print username for the registry on a given scope\",\"yarn npm whoami --scope company\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),o;return this.scope&&this.publish?o=Zn.getScopeRegistry(this.scope,{configuration:r,type:Zn.RegistryType.PUBLISH_REGISTRY}):this.scope?o=Zn.getScopeRegistry(this.scope,{configuration:r}):this.publish?o=Zn.getPublishRegistry((await _y(r,this.context.cwd)).manifest,{configuration:r}):o=Zn.getDefaultRegistry({configuration:r}),(await Rt.start({configuration:r,stdout:this.context.stdout},async n=>{let u;try{u=await Zr.get(\"/-/whoami\",{configuration:r,registry:o,authType:Zr.AuthType.ALWAYS_AUTH,jsonResponse:!0,ident:this.scope?G.makeIdent(this.scope,\"\"):void 0})}catch(A){if(A.response?.statusCode===401||A.response?.statusCode===403){n.reportError(41,\"Authentication failed - your credentials may have expired\");return}else throw A}n.reportInfo(0,u.username)})).exitCode()}};var Vvt={configuration:{npmPublishAccess:{description:\"Default access of the published packages\",type:\"STRING\",default:null},npmAuditExcludePackages:{description:\"Array of glob patterns of packages to exclude from npm audit\",type:\"STRING\",default:[],isArray:!0},npmAuditIgnoreAdvisories:{description:\"Array of glob patterns of advisory IDs to exclude from npm audit\",type:\"STRING\",default:[],isArray:!0}},commands:[SC,xC,kC,FC,RC,NC,TC,LC,MC]},zvt=Vvt;var S5={};Vt(S5,{PatchCommand:()=>jC,PatchCommitCommand:()=>qC,PatchFetcher:()=>Iv,PatchResolver:()=>Bv,default:()=>pDt,patchUtils:()=>pd});Ge();Ge();Pt();nA();var pd={};Vt(pd,{applyPatchFile:()=>GQ,diffFolders:()=>P5,ensureUnpatchedDescriptor:()=>I5,ensureUnpatchedLocator:()=>WQ,extractPackageToDisk:()=>D5,extractPatchFlags:()=>FBe,isParentRequired:()=>v5,isPatchDescriptor:()=>YQ,isPatchLocator:()=>$h,loadPatchFiles:()=>wv,makeDescriptor:()=>KQ,makeLocator:()=>B5,makePatchHash:()=>b5,parseDescriptor:()=>Ev,parseLocator:()=>Cv,parsePatchFile:()=>yv,unpatchDescriptor:()=>uDt,unpatchLocator:()=>ADt});Ge();Pt();Ge();Pt();var Jvt=/^@@ -(\\d+)(,(\\d+))? \\+(\\d+)(,(\\d+))? @@.*/;function OC(t){return V.relative(It.root,V.resolve(It.root,ue.toPortablePath(t)))}function Xvt(t){let e=t.trim().match(Jvt);if(!e)throw new Error(`Bad header line: '${t}'`);return{original:{start:Math.max(Number(e[1]),1),length:Number(e[3]||1)},patched:{start:Math.max(Number(e[4]),1),length:Number(e[6]||1)}}}var Zvt=420,$vt=493;var PBe=()=>({semverExclusivity:null,diffLineFromPath:null,diffLineToPath:null,oldMode:null,newMode:null,deletedFileMode:null,newFileMode:null,renameFrom:null,renameTo:null,beforeHash:null,afterHash:null,fromPath:null,toPath:null,hunks:null}),eDt=t=>({header:Xvt(t),parts:[]}),tDt={\"@\":\"header\",\"-\":\"deletion\",\"+\":\"insertion\",\" \":\"context\",\"\\\\\":\"pragma\",undefined:\"context\"};function rDt(t){let e=[],r=PBe(),o=\"parsing header\",a=null,n=null;function u(){a&&(n&&(a.parts.push(n),n=null),r.hunks.push(a),a=null)}function A(){u(),e.push(r),r=PBe()}for(let p=0;p<t.length;p++){let h=t[p];if(o===\"parsing header\")if(h.startsWith(\"@@\"))o=\"parsing hunks\",r.hunks=[],p-=1;else if(h.startsWith(\"diff --git \")){r&&r.diffLineFromPath&&A();let E=h.match(/^diff --git a\\/(.*?) b\\/(.*?)\\s*$/);if(!E)throw new Error(`Bad diff line: ${h}`);r.diffLineFromPath=E[1],r.diffLineToPath=E[2]}else if(h.startsWith(\"old mode \"))r.oldMode=h.slice(9).trim();else if(h.startsWith(\"new mode \"))r.newMode=h.slice(9).trim();else if(h.startsWith(\"deleted file mode \"))r.deletedFileMode=h.slice(18).trim();else if(h.startsWith(\"new file mode \"))r.newFileMode=h.slice(14).trim();else if(h.startsWith(\"rename from \"))r.renameFrom=h.slice(12).trim();else if(h.startsWith(\"rename to \"))r.renameTo=h.slice(10).trim();else if(h.startsWith(\"index \")){let E=h.match(/(\\w+)\\.\\.(\\w+)/);if(!E)continue;r.beforeHash=E[1],r.afterHash=E[2]}else h.startsWith(\"semver exclusivity \")?r.semverExclusivity=h.slice(19).trim():h.startsWith(\"--- \")?r.fromPath=h.slice(6).trim():h.startsWith(\"+++ \")&&(r.toPath=h.slice(6).trim());else{let E=tDt[h[0]]||null;switch(E){case\"header\":u(),a=eDt(h);break;case null:o=\"parsing header\",A(),p-=1;break;case\"pragma\":{if(!h.startsWith(\"\\\\ No newline at end of file\"))throw new Error(`Unrecognized pragma in patch file: ${h}`);if(!n)throw new Error(\"Bad parser state: No newline at EOF pragma encountered without context\");n.noNewlineAtEndOfFile=!0}break;case\"context\":case\"deletion\":case\"insertion\":{if(!a)throw new Error(\"Bad parser state: Hunk lines encountered before hunk header\");n&&n.type!==E&&(a.parts.push(n),n=null),n||(n={type:E,lines:[],noNewlineAtEndOfFile:!1}),n.lines.push(h.slice(1))}break;default:He.assertNever(E);break}}}A();for(let{hunks:p}of e)if(p)for(let h of p)iDt(h);return e}function nDt(t){let e=[];for(let r of t){let{semverExclusivity:o,diffLineFromPath:a,diffLineToPath:n,oldMode:u,newMode:A,deletedFileMode:p,newFileMode:h,renameFrom:E,renameTo:I,beforeHash:v,afterHash:x,fromPath:C,toPath:R,hunks:L}=r,U=E?\"rename\":p?\"file deletion\":h?\"file creation\":L&&L.length>0?\"patch\":\"mode change\",z=null;switch(U){case\"rename\":{if(!E||!I)throw new Error(\"Bad parser state: rename from & to not given\");e.push({type:\"rename\",semverExclusivity:o,fromPath:OC(E),toPath:OC(I)}),z=I}break;case\"file deletion\":{let te=a||C;if(!te)throw new Error(\"Bad parse state: no path given for file deletion\");e.push({type:\"file deletion\",semverExclusivity:o,hunk:L&&L[0]||null,path:OC(te),mode:jQ(p),hash:v})}break;case\"file creation\":{let te=n||R;if(!te)throw new Error(\"Bad parse state: no path given for file creation\");e.push({type:\"file creation\",semverExclusivity:o,hunk:L&&L[0]||null,path:OC(te),mode:jQ(h),hash:x})}break;case\"patch\":case\"mode change\":z=R||n;break;default:He.assertNever(U);break}z&&u&&A&&u!==A&&e.push({type:\"mode change\",semverExclusivity:o,path:OC(z),oldMode:jQ(u),newMode:jQ(A)}),z&&L&&L.length&&e.push({type:\"patch\",semverExclusivity:o,path:OC(z),hunks:L,beforeHash:v,afterHash:x})}if(e.length===0)throw new Error(\"Unable to parse patch file: No changes found. Make sure the patch is a valid UTF8 encoded string\");return e}function jQ(t){let e=parseInt(t,8)&511;if(e!==Zvt&&e!==$vt)throw new Error(`Unexpected file mode string: ${t}`);return e}function yv(t){let e=t.split(/\\n/g);return e[e.length-1]===\"\"&&e.pop(),nDt(rDt(e))}function iDt(t){let e=0,r=0;for(let{type:o,lines:a}of t.parts)switch(o){case\"context\":r+=a.length,e+=a.length;break;case\"deletion\":e+=a.length;break;case\"insertion\":r+=a.length;break;default:He.assertNever(o);break}if(e!==t.header.original.length||r!==t.header.patched.length){let o=a=>a<0?a:`+${a}`;throw new Error(`hunk header integrity check failed (expected @@ ${o(t.header.original.length)} ${o(t.header.patched.length)} @@, got @@ ${o(e)} ${o(r)} @@)`)}}Ge();Pt();var UC=class extends Error{constructor(r,o){super(`Cannot apply hunk #${r+1}`);this.hunk=o}};async function _C(t,e,r){let o=await t.lstatPromise(e),a=await r();typeof a<\"u\"&&(e=a),await t.lutimesPromise(e,o.atime,o.mtime)}async function GQ(t,{baseFs:e=new Tn,dryRun:r=!1,version:o=null}={}){for(let a of t)if(!(a.semverExclusivity!==null&&o!==null&&!Lr.satisfiesWithPrereleases(o,a.semverExclusivity)))switch(a.type){case\"file deletion\":if(r){if(!e.existsSync(a.path))throw new Error(`Trying to delete a file that doesn't exist: ${a.path}`)}else await _C(e,V.dirname(a.path),async()=>{await e.unlinkPromise(a.path)});break;case\"rename\":if(r){if(!e.existsSync(a.fromPath))throw new Error(`Trying to move a file that doesn't exist: ${a.fromPath}`)}else await _C(e,V.dirname(a.fromPath),async()=>{await _C(e,V.dirname(a.toPath),async()=>{await _C(e,a.fromPath,async()=>(await e.movePromise(a.fromPath,a.toPath),a.toPath))})});break;case\"file creation\":if(r){if(e.existsSync(a.path))throw new Error(`Trying to create a file that already exists: ${a.path}`)}else{let n=a.hunk?a.hunk.parts[0].lines.join(`\n`)+(a.hunk.parts[0].noNewlineAtEndOfFile?\"\":`\n`):\"\";await e.mkdirpPromise(V.dirname(a.path),{chmod:493,utimes:[Bi.SAFE_TIME,Bi.SAFE_TIME]}),await e.writeFilePromise(a.path,n,{mode:a.mode}),await e.utimesPromise(a.path,Bi.SAFE_TIME,Bi.SAFE_TIME)}break;case\"patch\":await _C(e,a.path,async()=>{await aDt(a,{baseFs:e,dryRun:r})});break;case\"mode change\":{let u=(await e.statPromise(a.path)).mode;if(bBe(a.newMode)!==bBe(u))continue;await _C(e,a.path,async()=>{await e.chmodPromise(a.path,a.newMode)})}break;default:He.assertNever(a);break}}function bBe(t){return(t&64)>0}function SBe(t){return t.replace(/\\s+$/,\"\")}function oDt(t,e){return SBe(t)===SBe(e)}async function aDt({hunks:t,path:e},{baseFs:r,dryRun:o=!1}){let a=await r.statSync(e).mode,u=(await r.readFileSync(e,\"utf8\")).split(/\\n/),A=[],p=0,h=0;for(let I of t){let v=Math.max(h,I.header.patched.start+p),x=Math.max(0,v-h),C=Math.max(0,u.length-v-I.header.original.length),R=Math.max(x,C),L=0,U=0,z=null;for(;L<=R;){if(L<=x&&(U=v-L,z=xBe(I,u,U),z!==null)){L=-L;break}if(L<=C&&(U=v+L,z=xBe(I,u,U),z!==null))break;L+=1}if(z===null)throw new UC(t.indexOf(I),I);A.push(z),p+=L,h=U+I.header.original.length}if(o)return;let E=0;for(let I of A)for(let v of I)switch(v.type){case\"splice\":{let x=v.index+E;u.splice(x,v.numToDelete,...v.linesToInsert),E+=v.linesToInsert.length-v.numToDelete}break;case\"pop\":u.pop();break;case\"push\":u.push(v.line);break;default:He.assertNever(v);break}await r.writeFilePromise(e,u.join(`\n`),{mode:a})}function xBe(t,e,r){let o=[];for(let a of t.parts)switch(a.type){case\"context\":case\"deletion\":{for(let n of a.lines){let u=e[r];if(u==null||!oDt(u,n))return null;r+=1}a.type===\"deletion\"&&(o.push({type:\"splice\",index:r-a.lines.length,numToDelete:a.lines.length,linesToInsert:[]}),a.noNewlineAtEndOfFile&&o.push({type:\"push\",line:\"\"}))}break;case\"insertion\":o.push({type:\"splice\",index:r,numToDelete:0,linesToInsert:a.lines}),a.noNewlineAtEndOfFile&&o.push({type:\"pop\"});break;default:He.assertNever(a.type);break}return o}var cDt=/^builtin<([^>]+)>$/;function HC(t,e){let{protocol:r,source:o,selector:a,params:n}=G.parseRange(t);if(r!==\"patch:\")throw new Error(\"Invalid patch range\");if(o===null)throw new Error(\"Patch locators must explicitly define their source\");let u=a?a.split(/&/).map(E=>ue.toPortablePath(E)):[],A=n&&typeof n.locator==\"string\"?G.parseLocator(n.locator):null,p=n&&typeof n.version==\"string\"?n.version:null,h=e(o);return{parentLocator:A,sourceItem:h,patchPaths:u,sourceVersion:p}}function YQ(t){return t.range.startsWith(\"patch:\")}function $h(t){return t.reference.startsWith(\"patch:\")}function Ev(t){let{sourceItem:e,...r}=HC(t.range,G.parseDescriptor);return{...r,sourceDescriptor:e}}function Cv(t){let{sourceItem:e,...r}=HC(t.reference,G.parseLocator);return{...r,sourceLocator:e}}function uDt(t){let{sourceItem:e}=HC(t.range,G.parseDescriptor);return e}function ADt(t){let{sourceItem:e}=HC(t.reference,G.parseLocator);return e}function I5(t){if(!YQ(t))return t;let{sourceItem:e}=HC(t.range,G.parseDescriptor);return e}function WQ(t){if(!$h(t))return t;let{sourceItem:e}=HC(t.reference,G.parseLocator);return e}function kBe({parentLocator:t,sourceItem:e,patchPaths:r,sourceVersion:o,patchHash:a},n){let u=t!==null?{locator:G.stringifyLocator(t)}:{},A=typeof o<\"u\"?{version:o}:{},p=typeof a<\"u\"?{hash:a}:{};return G.makeRange({protocol:\"patch:\",source:n(e),selector:r.join(\"&\"),params:{...A,...p,...u}})}function KQ(t,{parentLocator:e,sourceDescriptor:r,patchPaths:o}){return G.makeDescriptor(t,kBe({parentLocator:e,sourceItem:r,patchPaths:o},G.stringifyDescriptor))}function B5(t,{parentLocator:e,sourcePackage:r,patchPaths:o,patchHash:a}){return G.makeLocator(t,kBe({parentLocator:e,sourceItem:r,sourceVersion:r.version,patchPaths:o,patchHash:a},G.stringifyLocator))}function QBe({onAbsolute:t,onRelative:e,onProject:r,onBuiltin:o},a){let n=a.lastIndexOf(\"!\");n!==-1&&(a=a.slice(n+1));let u=a.match(cDt);return u!==null?o(u[1]):a.startsWith(\"~/\")?r(a.slice(2)):V.isAbsolute(a)?t(a):e(a)}function FBe(t){let e=t.lastIndexOf(\"!\");return{optional:(e!==-1?new Set(t.slice(0,e).split(/!/)):new Set).has(\"optional\")}}function v5(t){return QBe({onAbsolute:()=>!1,onRelative:()=>!0,onProject:()=>!1,onBuiltin:()=>!1},t)}async function wv(t,e,r){let o=t!==null?await r.fetcher.fetch(t,r):null,a=o&&o.localPath?{packageFs:new gn(It.root),prefixPath:V.relative(It.root,o.localPath)}:o;o&&o!==a&&o.releaseFs&&o.releaseFs();let n=await He.releaseAfterUseAsync(async()=>await Promise.all(e.map(async u=>{let A=FBe(u),p=await QBe({onAbsolute:async h=>await oe.readFilePromise(h,\"utf8\"),onRelative:async h=>{if(a===null)throw new Error(\"Assertion failed: The parent locator should have been fetched\");return await a.packageFs.readFilePromise(V.join(a.prefixPath,h),\"utf8\")},onProject:async h=>await oe.readFilePromise(V.join(r.project.cwd,h),\"utf8\"),onBuiltin:async h=>await r.project.configuration.firstHook(E=>E.getBuiltinPatch,r.project,h)},u);return{...A,source:p}})));for(let u of n)typeof u.source==\"string\"&&(u.source=u.source.replace(/\\r\\n?/g,`\n`));return n}async function D5(t,{cache:e,project:r}){let o=r.storedPackages.get(t.locatorHash);if(typeof o>\"u\")throw new Error(\"Assertion failed: Expected the package to be registered\");let a=WQ(t),n=r.storedChecksums,u=new ki,A=await oe.mktempPromise(),p=V.join(A,\"source\"),h=V.join(A,\"user\"),E=V.join(A,\".yarn-patch.json\"),I=r.configuration.makeFetcher(),v=[];try{let x,C;if(t.locatorHash===a.locatorHash){let R=await I.fetch(t,{cache:e,project:r,fetcher:I,checksums:n,report:u});v.push(()=>R.releaseFs?.()),x=R,C=R}else x=await I.fetch(t,{cache:e,project:r,fetcher:I,checksums:n,report:u}),v.push(()=>x.releaseFs?.()),C=await I.fetch(t,{cache:e,project:r,fetcher:I,checksums:n,report:u}),v.push(()=>C.releaseFs?.());await Promise.all([oe.copyPromise(p,x.prefixPath,{baseFs:x.packageFs}),oe.copyPromise(h,C.prefixPath,{baseFs:C.packageFs}),oe.writeJsonPromise(E,{locator:G.stringifyLocator(t),version:o.version})])}finally{for(let x of v)x()}return oe.detachTemp(A),h}async function P5(t,e){let r=ue.fromPortablePath(t).replace(/\\\\/g,\"/\"),o=ue.fromPortablePath(e).replace(/\\\\/g,\"/\"),{stdout:a,stderr:n}=await Ur.execvp(\"git\",[\"-c\",\"core.safecrlf=false\",\"diff\",\"--src-prefix=a/\",\"--dst-prefix=b/\",\"--ignore-cr-at-eol\",\"--full-index\",\"--no-index\",\"--no-renames\",\"--text\",r,o],{cwd:ue.toPortablePath(process.cwd()),env:{...process.env,GIT_CONFIG_NOSYSTEM:\"1\",HOME:\"\",XDG_CONFIG_HOME:\"\",USERPROFILE:\"\"}});if(n.length>0)throw new Error(`Unable to diff directories. Make sure you have a recent version of 'git' available in PATH.\nThe following error was reported by 'git':\n${n}`);let u=r.startsWith(\"/\")?A=>A.slice(1):A=>A;return a.replace(new RegExp(`(a|b)(${He.escapeRegExp(`/${u(r)}/`)})`,\"g\"),\"$1/\").replace(new RegExp(`(a|b)${He.escapeRegExp(`/${u(o)}/`)}`,\"g\"),\"$1/\").replace(new RegExp(He.escapeRegExp(`${r}/`),\"g\"),\"\").replace(new RegExp(He.escapeRegExp(`${o}/`),\"g\"),\"\")}function b5(t,e){let r=[];for(let{source:o}of t){if(o===null)continue;let a=yv(o);for(let n of a){let{semverExclusivity:u,...A}=n;u!==null&&e!==null&&!Lr.satisfiesWithPrereleases(e,u)||r.push(JSON.stringify(A))}}return wn.makeHash(`${3}`,...r).slice(0,6)}Ge();function RBe(t,{configuration:e,report:r}){for(let o of t.parts)for(let a of o.lines)switch(o.type){case\"context\":r.reportInfo(null,`  ${pe.pretty(e,a,\"grey\")}`);break;case\"deletion\":r.reportError(28,`- ${pe.pretty(e,a,pe.Type.REMOVED)}`);break;case\"insertion\":r.reportError(28,`+ ${pe.pretty(e,a,pe.Type.ADDED)}`);break;default:He.assertNever(o.type)}}var Iv=class{supports(e,r){return!!$h(e)}getLocalPath(e,r){return null}async fetch(e,r){let o=r.checksums.get(e.locatorHash)||null,[a,n,u]=await r.cache.fetchPackageFromCache(e,o,{onHit:()=>r.report.reportCacheHit(e),onMiss:()=>r.report.reportCacheMiss(e,`${G.prettyLocator(r.project.configuration,e)} can't be found in the cache and will be fetched from the disk`),loader:()=>this.patchPackage(e,r),...r.cacheOptions});return{packageFs:a,releaseFs:n,prefixPath:G.getIdentVendorPath(e),localPath:this.getLocalPath(e,r),checksum:u}}async patchPackage(e,r){let{parentLocator:o,sourceLocator:a,sourceVersion:n,patchPaths:u}=Cv(e),A=await wv(o,u,r),p=await oe.mktempPromise(),h=V.join(p,\"current.zip\"),E=await r.fetcher.fetch(a,r),I=G.getIdentVendorPath(e),v=new Zi(h,{create:!0,level:r.project.configuration.get(\"compressionLevel\")});await He.releaseAfterUseAsync(async()=>{await v.copyPromise(I,E.prefixPath,{baseFs:E.packageFs,stableSort:!0})},E.releaseFs),v.saveAndClose();for(let{source:x,optional:C}of A){if(x===null)continue;let R=new Zi(h,{level:r.project.configuration.get(\"compressionLevel\")}),L=new gn(V.resolve(It.root,I),{baseFs:R});try{await GQ(yv(x),{baseFs:L,version:n})}catch(U){if(!(U instanceof UC))throw U;let z=r.project.configuration.get(\"enableInlineHunks\"),te=!z&&!C?\" (set enableInlineHunks for details)\":\"\",ae=`${G.prettyLocator(r.project.configuration,e)}: ${U.message}${te}`,le=ce=>{z&&RBe(U.hunk,{configuration:r.project.configuration,report:ce})};if(R.discardAndClose(),C){r.report.reportWarningOnce(66,ae,{reportExtra:le});continue}else throw new Jt(66,ae,le)}R.saveAndClose()}return new Zi(h,{level:r.project.configuration.get(\"compressionLevel\")})}};Ge();var Bv=class{supportsDescriptor(e,r){return!!YQ(e)}supportsLocator(e,r){return!!$h(e)}shouldPersistResolution(e,r){return!1}bindDescriptor(e,r,o){let{patchPaths:a}=Ev(e);return a.every(n=>!v5(n))?e:G.bindDescriptor(e,{locator:G.stringifyLocator(r)})}getResolutionDependencies(e,r){let{sourceDescriptor:o}=Ev(e);return{sourceDescriptor:r.project.configuration.normalizeDependency(o)}}async getCandidates(e,r,o){if(!o.fetchOptions)throw new Error(\"Assertion failed: This resolver cannot be used unless a fetcher is configured\");let{parentLocator:a,patchPaths:n}=Ev(e),u=await wv(a,n,o.fetchOptions),A=r.sourceDescriptor;if(typeof A>\"u\")throw new Error(\"Assertion failed: The dependency should have been resolved\");let p=b5(u,A.version);return[B5(e,{parentLocator:a,sourcePackage:A,patchPaths:n,patchHash:p})]}async getSatisfying(e,r,o,a){let[n]=await this.getCandidates(e,r,a);return{locators:o.filter(u=>u.locatorHash===n.locatorHash),sorted:!1}}async resolve(e,r){let{sourceLocator:o}=Cv(e);return{...await r.resolver.resolve(o,r),...e}}};Ge();Pt();qt();var qC=class extends ut{constructor(){super(...arguments);this.save=ge.Boolean(\"-s,--save\",!1,{description:\"Add the patch to your resolution entries\"});this.patchFolder=ge.String()}static{this.paths=[[\"patch-commit\"]]}static{this.usage=it.Usage({description:\"generate a patch out of a directory\",details:\"\\n      By default, this will print a patchfile on stdout based on the diff between the folder passed in and the original version of the package. Such file is suitable for consumption with the `patch:` protocol.\\n\\n      With the `-s,--save` option set, the patchfile won't be printed on stdout anymore and will instead be stored within a local file (by default kept within `.yarn/patches`, but configurable via the `patchFolder` setting). A `resolutions` entry will also be added to your top-level manifest, referencing the patched package via the `patch:` protocol.\\n\\n      Note that only folders generated by `yarn patch` are accepted as valid input for `yarn patch-commit`.\\n    \"})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!a)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState();let n=V.resolve(this.context.cwd,ue.toPortablePath(this.patchFolder)),u=V.join(n,\"../source\"),A=V.join(n,\"../.yarn-patch.json\");if(!oe.existsSync(u))throw new st(\"The argument folder didn't get created by 'yarn patch'\");let p=await P5(u,n),h=await oe.readJsonPromise(A),E=G.parseLocator(h.locator,!0);if(!o.storedPackages.has(E.locatorHash))throw new st(\"No package found in the project for the given locator\");if(!this.save){this.context.stdout.write(p);return}let I=r.get(\"patchFolder\"),v=V.join(I,`${G.slugifyLocator(E)}.patch`);await oe.mkdirPromise(I,{recursive:!0}),await oe.writeFilePromise(v,p);let x=[],C=new Map;for(let R of o.storedPackages.values()){if(G.isVirtualLocator(R))continue;let L=R.dependencies.get(E.identHash);if(!L)continue;let U=G.ensureDevirtualizedDescriptor(L),z=I5(U),te=o.storedResolutions.get(z.descriptorHash);if(!te)throw new Error(\"Assertion failed: Expected the resolution to have been registered\");if(!o.storedPackages.get(te))throw new Error(\"Assertion failed: Expected the package to have been registered\");let le=o.tryWorkspaceByLocator(R);if(le)x.push(le);else{let ce=o.originalPackages.get(R.locatorHash);if(!ce)throw new Error(\"Assertion failed: Expected the original package to have been registered\");let Ce=ce.dependencies.get(L.identHash);if(!Ce)throw new Error(\"Assertion failed: Expected the original dependency to have been registered\");C.set(Ce.descriptorHash,Ce)}}for(let R of x)for(let L of Ut.hardDependencies){let U=R.manifest[L].get(E.identHash);if(!U)continue;let z=KQ(U,{parentLocator:null,sourceDescriptor:G.convertLocatorToDescriptor(E),patchPaths:[V.join(dr.home,V.relative(o.cwd,v))]});R.manifest[L].set(U.identHash,z)}for(let R of C.values()){let L=KQ(R,{parentLocator:null,sourceDescriptor:G.convertLocatorToDescriptor(E),patchPaths:[V.join(dr.home,V.relative(o.cwd,v))]});o.topLevelWorkspace.manifest.resolutions.push({pattern:{descriptor:{fullName:G.stringifyIdent(L),description:R.range}},reference:L.range})}await o.persist()}};Ge();Pt();qt();var jC=class extends ut{constructor(){super(...arguments);this.update=ge.Boolean(\"-u,--update\",!1,{description:\"Reapply local patches that already apply to this packages\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.package=ge.String()}static{this.paths=[[\"patch\"]]}static{this.usage=it.Usage({description:\"prepare a package for patching\",details:\"\\n      This command will cause a package to be extracted in a temporary directory intended to be editable at will.\\n\\n      Once you're done with your changes, run `yarn patch-commit -s path` (with `path` being the temporary directory you received) to generate a patchfile and register it into your top-level manifest via the `patch:` protocol. Run `yarn patch-commit -h` for more details.\\n\\n      Calling the command when you already have a patch won't import it by default (in other words, the default behavior is to reset existing patches). However, adding the `-u,--update` flag will import any current patch.\\n    \"})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(!a)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState();let u=G.parseLocator(this.package);if(u.reference===\"unknown\"){let A=He.mapAndFilter([...o.storedPackages.values()],p=>p.identHash!==u.identHash?He.mapAndFilter.skip:G.isVirtualLocator(p)?He.mapAndFilter.skip:$h(p)!==this.update?He.mapAndFilter.skip:p);if(A.length===0)throw new st(\"No package found in the project for the given locator\");if(A.length>1)throw new st(`Multiple candidate packages found; explicitly choose one of them (use \\`yarn why <package>\\` to get more information as to who depends on them):\n${A.map(p=>`\n- ${G.prettyLocator(r,p)}`).join(\"\")}`);u=A[0]}if(!o.storedPackages.has(u.locatorHash))throw new st(\"No package found in the project for the given locator\");await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout},async A=>{let p=WQ(u),h=await D5(u,{cache:n,project:o});A.reportJson({locator:G.stringifyLocator(p),path:ue.fromPortablePath(h)});let E=this.update?\" along with its current modifications\":\"\";A.reportInfo(0,`Package ${G.prettyLocator(r,p)} got extracted with success${E}!`),A.reportInfo(0,`You can now edit the following folder: ${pe.pretty(r,ue.fromPortablePath(h),\"magenta\")}`),A.reportInfo(0,`Once you are done run ${pe.pretty(r,`yarn patch-commit -s ${process.platform===\"win32\"?'\"':\"\"}${ue.fromPortablePath(h)}${process.platform===\"win32\"?'\"':\"\"}`,\"cyan\")} and Yarn will store a patchfile based on your changes.`)})}};var fDt={configuration:{enableInlineHunks:{description:\"If true, the installs will print unmatched patch hunks\",type:\"BOOLEAN\",default:!1},patchFolder:{description:\"Folder where the patch files must be written\",type:\"ABSOLUTE_PATH\",default:\"./.yarn/patches\"}},commands:[qC,jC],fetchers:[Iv],resolvers:[Bv]},pDt=fDt;var Q5={};Vt(Q5,{PnpmLinker:()=>vv,default:()=>yDt});Ge();Pt();qt();var vv=class{getCustomDataKey(){return JSON.stringify({name:\"PnpmLinker\",version:3})}supportsPackage(e,r){return this.isEnabled(r)}async findPackageLocation(e,r){if(!this.isEnabled(r))throw new Error(\"Assertion failed: Expected the pnpm linker to be enabled\");let o=this.getCustomDataKey(),a=r.project.linkersCustomData.get(o);if(!a)throw new st(`The project in ${pe.pretty(r.project.configuration,`${r.project.cwd}/package.json`,pe.Type.PATH)} doesn't seem to have been installed - running an install there might help`);let n=a.pathsByLocator.get(e.locatorHash);if(typeof n>\"u\")throw new st(`Couldn't find ${G.prettyLocator(r.project.configuration,e)} in the currently installed pnpm map - running an install might help`);return n.packageLocation}async findPackageLocator(e,r){if(!this.isEnabled(r))return null;let o=this.getCustomDataKey(),a=r.project.linkersCustomData.get(o);if(!a)throw new st(`The project in ${pe.pretty(r.project.configuration,`${r.project.cwd}/package.json`,pe.Type.PATH)} doesn't seem to have been installed - running an install there might help`);let n=e.match(/(^.*\\/node_modules\\/(@[^/]*\\/)?[^/]+)(\\/.*$)/);if(n){let p=a.locatorByPath.get(n[1]);if(p)return p}let u=e,A=e;do{A=u,u=V.dirname(A);let p=a.locatorByPath.get(A);if(p)return p}while(u!==A);return null}makeInstaller(e){return new x5(e)}isEnabled(e){return e.project.configuration.get(\"nodeLinker\")===\"pnpm\"}},x5=class{constructor(e){this.opts=e;this.asyncActions=new He.AsyncActions(10);this.customData={pathsByLocator:new Map,locatorByPath:new Map};this.indexFolderPromise=cD(oe,{indexPath:V.join(e.project.configuration.get(\"globalFolder\"),\"index\")})}attachCustomData(e){}async installPackage(e,r,o){switch(e.linkType){case\"SOFT\":return this.installPackageSoft(e,r,o);case\"HARD\":return this.installPackageHard(e,r,o)}throw new Error(\"Assertion failed: Unsupported package link type\")}async installPackageSoft(e,r,o){let a=V.resolve(r.packageFs.getRealPath(),r.prefixPath),n=this.opts.project.tryWorkspaceByLocator(e)?V.join(a,dr.nodeModules):null;return this.customData.pathsByLocator.set(e.locatorHash,{packageLocation:a,dependenciesLocation:n}),{packageLocation:a,buildRequest:null}}async installPackageHard(e,r,o){let a=hDt(e,{project:this.opts.project}),n=a.packageLocation;this.customData.locatorByPath.set(n,G.stringifyLocator(e)),this.customData.pathsByLocator.set(e.locatorHash,a),o.holdFetchResult(this.asyncActions.set(e.locatorHash,async()=>{await oe.mkdirPromise(n,{recursive:!0}),await oe.copyPromise(n,r.prefixPath,{baseFs:r.packageFs,overwrite:!1,linkStrategy:{type:\"HardlinkFromIndex\",indexPath:await this.indexFolderPromise,autoRepair:!0}})}));let A=G.isVirtualLocator(e)?G.devirtualizeLocator(e):e,p={manifest:await Ut.tryFind(r.prefixPath,{baseFs:r.packageFs})??new Ut,misc:{hasBindingGyp:mA.hasBindingGyp(r)}},h=this.opts.project.getDependencyMeta(A,e.version),E=mA.extractBuildRequest(e,p,h,{configuration:this.opts.project.configuration});return{packageLocation:n,buildRequest:E}}async attachInternalDependencies(e,r){if(this.opts.project.configuration.get(\"nodeLinker\")!==\"pnpm\"||!TBe(e,{project:this.opts.project}))return;let o=this.customData.pathsByLocator.get(e.locatorHash);if(typeof o>\"u\")throw new Error(`Assertion failed: Expected the package to have been registered (${G.stringifyLocator(e)})`);let{dependenciesLocation:a}=o;a&&this.asyncActions.reduce(e.locatorHash,async n=>{await oe.mkdirPromise(a,{recursive:!0});let u=await gDt(a),A=new Map(u),p=[n],h=(I,v)=>{let x=v;TBe(v,{project:this.opts.project})||(this.opts.report.reportWarningOnce(0,\"The pnpm linker doesn't support providing different versions to workspaces' peer dependencies\"),x=G.devirtualizeLocator(v));let C=this.customData.pathsByLocator.get(x.locatorHash);if(typeof C>\"u\")throw new Error(`Assertion failed: Expected the package to have been registered (${G.stringifyLocator(v)})`);let R=G.stringifyIdent(I),L=V.join(a,R),U=V.relative(V.dirname(L),C.packageLocation),z=A.get(R);A.delete(R),p.push(Promise.resolve().then(async()=>{if(z){if(z.isSymbolicLink()&&await oe.readlinkPromise(L)===U)return;await oe.removePromise(L)}await oe.mkdirpPromise(V.dirname(L)),process.platform==\"win32\"&&this.opts.project.configuration.get(\"winLinkType\")===\"junctions\"?await oe.symlinkPromise(C.packageLocation,L,\"junction\"):await oe.symlinkPromise(U,L)}))},E=!1;for(let[I,v]of r)I.identHash===e.identHash&&(E=!0),h(I,v);!E&&!this.opts.project.tryWorkspaceByLocator(e)&&h(G.convertLocatorToDescriptor(e),e),p.push(dDt(a,A)),await Promise.all(p)})}async attachExternalDependents(e,r){throw new Error(\"External dependencies haven't been implemented for the pnpm linker\")}async finalizeInstall(){let e=LBe(this.opts.project);if(this.opts.project.configuration.get(\"nodeLinker\")!==\"pnpm\")await oe.removePromise(e);else{let r;try{r=new Set(await oe.readdirPromise(e))}catch{r=new Set}for(let{dependenciesLocation:o}of this.customData.pathsByLocator.values()){if(!o)continue;let a=V.contains(e,o);if(a===null)continue;let[n]=a.split(V.sep);r.delete(n)}await Promise.all([...r].map(async o=>{await oe.removePromise(V.join(e,o))}))}return await this.asyncActions.wait(),await k5(e),this.opts.project.configuration.get(\"nodeLinker\")!==\"node-modules\"&&await k5(NBe(this.opts.project)),{customData:this.customData}}};function NBe(t){return V.join(t.cwd,dr.nodeModules)}function LBe(t){return V.join(NBe(t),\".store\")}function hDt(t,{project:e}){let r=G.slugifyLocator(t),o=LBe(e),a=V.join(o,r,\"package\"),n=V.join(o,r,dr.nodeModules);return{packageLocation:a,dependenciesLocation:n}}function TBe(t,{project:e}){return!G.isVirtualLocator(t)||!e.tryWorkspaceByLocator(t)}async function gDt(t){let e=new Map,r=[];try{r=await oe.readdirPromise(t,{withFileTypes:!0})}catch(o){if(o.code!==\"ENOENT\")throw o}try{for(let o of r)if(!o.name.startsWith(\".\"))if(o.name.startsWith(\"@\")){let a=await oe.readdirPromise(V.join(t,o.name),{withFileTypes:!0});if(a.length===0)e.set(o.name,o);else for(let n of a)e.set(`${o.name}/${n.name}`,n)}else e.set(o.name,o)}catch(o){if(o.code!==\"ENOENT\")throw o}return e}async function dDt(t,e){let r=[],o=new Set;for(let a of e.keys()){r.push(oe.removePromise(V.join(t,a)));let n=G.tryParseIdent(a)?.scope;n&&o.add(`@${n}`)}return Promise.all(r).then(()=>Promise.all([...o].map(a=>k5(V.join(t,a)))))}async function k5(t){try{await oe.rmdirPromise(t)}catch(e){if(e.code!==\"ENOENT\"&&e.code!==\"ENOTEMPTY\")throw e}}var mDt={linkers:[vv]},yDt=mDt;var O5={};Vt(O5,{StageCommand:()=>GC,default:()=>xDt,stageUtils:()=>zQ});Ge();Pt();qt();Ge();Pt();var zQ={};Vt(zQ,{ActionType:()=>F5,checkConsensus:()=>VQ,expandDirectory:()=>N5,findConsensus:()=>L5,findVcsRoot:()=>R5,genCommitMessage:()=>M5,getCommitPrefix:()=>MBe,isYarnFile:()=>T5});Pt();var F5=(n=>(n[n.CREATE=0]=\"CREATE\",n[n.DELETE=1]=\"DELETE\",n[n.ADD=2]=\"ADD\",n[n.REMOVE=3]=\"REMOVE\",n[n.MODIFY=4]=\"MODIFY\",n))(F5||{});async function R5(t,{marker:e}){do if(!oe.existsSync(V.join(t,e)))t=V.dirname(t);else return t;while(t!==\"/\");return null}function T5(t,{roots:e,names:r}){if(r.has(V.basename(t)))return!0;do if(!e.has(t))t=V.dirname(t);else return!0;while(t!==\"/\");return!1}function N5(t){let e=[],r=[t];for(;r.length>0;){let o=r.pop(),a=oe.readdirSync(o);for(let n of a){let u=V.resolve(o,n);oe.lstatSync(u).isDirectory()?r.push(u):e.push(u)}}return e}function VQ(t,e){let r=0,o=0;for(let a of t)a!==\"wip\"&&(e.test(a)?r+=1:o+=1);return r>=o}function L5(t){let e=VQ(t,/^(\\w\\(\\w+\\):\\s*)?\\w+s/),r=VQ(t,/^(\\w\\(\\w+\\):\\s*)?[A-Z]/),o=VQ(t,/^\\w\\(\\w+\\):/);return{useThirdPerson:e,useUpperCase:r,useComponent:o}}function MBe(t){return t.useComponent?\"chore(yarn): \":\"\"}var EDt=new Map([[0,\"create\"],[1,\"delete\"],[2,\"add\"],[3,\"remove\"],[4,\"update\"]]);function M5(t,e){let r=MBe(t),o=[],a=e.slice().sort((n,u)=>n[0]-u[0]);for(;a.length>0;){let[n,u]=a.shift(),A=EDt.get(n);t.useUpperCase&&o.length===0&&(A=`${A[0].toUpperCase()}${A.slice(1)}`),t.useThirdPerson&&(A+=\"s\");let p=[u];for(;a.length>0&&a[0][0]===n;){let[,E]=a.shift();p.push(E)}p.sort();let h=p.shift();p.length===1?h+=\" (and one other)\":p.length>1&&(h+=` (and ${p.length} others)`),o.push(`${A} ${h}`)}return`${r}${o.join(\", \")}`}var CDt=\"Commit generated via `yarn stage`\",wDt=11;async function OBe(t){let{code:e,stdout:r}=await Ur.execvp(\"git\",[\"log\",\"-1\",\"--pretty=format:%H\"],{cwd:t});return e===0?r.trim():null}async function IDt(t,e){let r=[],o=e.filter(h=>V.basename(h.path)===\"package.json\");for(let{action:h,path:E}of o){let I=V.relative(t,E);if(h===4){let v=await OBe(t),{stdout:x}=await Ur.execvp(\"git\",[\"show\",`${v}:${I}`],{cwd:t,strict:!0}),C=await Ut.fromText(x),R=await Ut.fromFile(E),L=new Map([...R.dependencies,...R.devDependencies]),U=new Map([...C.dependencies,...C.devDependencies]);for(let[z,te]of U){let ae=G.stringifyIdent(te),le=L.get(z);le?le.range!==te.range&&r.push([4,`${ae} to ${le.range}`]):r.push([3,ae])}for(let[z,te]of L)U.has(z)||r.push([2,G.stringifyIdent(te)])}else if(h===0){let v=await Ut.fromFile(E);v.name?r.push([0,G.stringifyIdent(v.name)]):r.push([0,\"a package\"])}else if(h===1){let v=await OBe(t),{stdout:x}=await Ur.execvp(\"git\",[\"show\",`${v}:${I}`],{cwd:t,strict:!0}),C=await Ut.fromText(x);C.name?r.push([1,G.stringifyIdent(C.name)]):r.push([1,\"a package\"])}else throw new Error(\"Assertion failed: Unsupported action type\")}let{code:a,stdout:n}=await Ur.execvp(\"git\",[\"log\",`-${wDt}`,\"--pretty=format:%s\"],{cwd:t}),u=a===0?n.split(/\\n/g).filter(h=>h!==\"\"):[],A=L5(u);return M5(A,r)}var BDt={0:[\" A \",\"?? \"],4:[\" M \"],1:[\" D \"]},vDt={0:[\"A  \"],4:[\"M  \"],1:[\"D  \"]},UBe={async findRoot(t){return await R5(t,{marker:\".git\"})},async filterChanges(t,e,r,o){let{stdout:a}=await Ur.execvp(\"git\",[\"status\",\"-s\"],{cwd:t,strict:!0}),n=a.toString().split(/\\n/g),u=o?.staged?vDt:BDt;return[].concat(...n.map(p=>{if(p===\"\")return[];let h=p.slice(0,3),E=V.resolve(t,p.slice(3));if(!o?.staged&&h===\"?? \"&&p.endsWith(\"/\"))return N5(E).map(I=>({action:0,path:I}));{let v=[0,4,1].find(x=>u[x].includes(h));return v!==void 0?[{action:v,path:E}]:[]}})).filter(p=>T5(p.path,{roots:e,names:r}))},async genCommitMessage(t,e){return await IDt(t,e)},async makeStage(t,e){let r=e.map(o=>ue.fromPortablePath(o.path));await Ur.execvp(\"git\",[\"add\",\"--\",...r],{cwd:t,strict:!0})},async makeCommit(t,e,r){let o=e.map(a=>ue.fromPortablePath(a.path));await Ur.execvp(\"git\",[\"add\",\"-N\",\"--\",...o],{cwd:t,strict:!0}),await Ur.execvp(\"git\",[\"commit\",\"-m\",`${r}\n\n${CDt}\n`,\"--\",...o],{cwd:t,strict:!0})},async makeReset(t,e){let r=e.map(o=>ue.fromPortablePath(o.path));await Ur.execvp(\"git\",[\"reset\",\"HEAD\",\"--\",...r],{cwd:t,strict:!0})}};var DDt=[UBe],GC=class extends ut{constructor(){super(...arguments);this.commit=ge.Boolean(\"-c,--commit\",!1,{description:\"Commit the staged files\"});this.reset=ge.Boolean(\"-r,--reset\",!1,{description:\"Remove all files from the staging area\"});this.dryRun=ge.Boolean(\"-n,--dry-run\",!1,{description:\"Print the commit message and the list of modified files without staging / committing\"});this.update=ge.Boolean(\"-u,--update\",!1,{hidden:!0})}static{this.paths=[[\"stage\"]]}static{this.usage=it.Usage({description:\"add all yarn files to your vcs\",details:\"\\n      This command will add to your staging area the files belonging to Yarn (typically any modified `package.json` and `.yarnrc.yml` files, but also linker-generated files, cache data, etc). It will take your ignore list into account, so the cache files won't be added if the cache is ignored in a `.gitignore` file (assuming you use Git).\\n\\n      Running `--reset` will instead remove them from the staging area (the changes will still be there, but won't be committed until you stage them back).\\n\\n      Since the staging area is a non-existent concept in Mercurial, Yarn will always create a new commit when running this command on Mercurial repositories. You can get this behavior when using Git by using the `--commit` flag which will directly create a commit.\\n    \",examples:[[\"Adds all modified project files to the staging area\",\"yarn stage\"],[\"Creates a new commit containing all modified project files\",\"yarn stage --commit\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o}=await kt.find(r,this.context.cwd),{driver:a,root:n}=await PDt(o.cwd),u=[r.get(\"cacheFolder\"),r.get(\"globalFolder\"),r.get(\"virtualFolder\"),r.get(\"yarnPath\")];await r.triggerHook(I=>I.populateYarnPaths,o,I=>{u.push(I)});let A=new Set;for(let I of u)for(let v of bDt(n,I))A.add(v);let p=new Set([r.get(\"rcFilename\"),dr.lockfile,dr.manifest]),h=await a.filterChanges(n,A,p),E=await a.genCommitMessage(n,h);if(this.dryRun)if(this.commit)this.context.stdout.write(`${E}\n`);else for(let I of h)this.context.stdout.write(`${ue.fromPortablePath(I.path)}\n`);else if(this.reset){let I=await a.filterChanges(n,A,p,{staged:!0});I.length===0?this.context.stdout.write(\"No staged changes found!\"):await a.makeReset(n,I)}else h.length===0?this.context.stdout.write(\"No changes found!\"):this.commit?await a.makeCommit(n,h,E):(await a.makeStage(n,h),this.context.stdout.write(E))}};async function PDt(t){let e=null,r=null;for(let o of DDt)if((r=await o.findRoot(t))!==null){e=o;break}if(e===null||r===null)throw new st(\"No stage driver has been found for your current project\");return{driver:e,root:r}}function bDt(t,e){let r=[];if(e===null)return r;for(;;){(e===t||e.startsWith(`${t}/`))&&r.push(e);let o;try{o=oe.statSync(e)}catch{break}if(o.isSymbolicLink())e=V.resolve(V.dirname(e),oe.readlinkSync(e));else break}return r}var SDt={commands:[GC]},xDt=SDt;var U5={};Vt(U5,{default:()=>MDt});Ge();Ge();Pt();var qBe=Ze(Jn());Ge();var _Be=Ze(YH()),kDt=\"e8e1bd300d860104bb8c58453ffa1eb4\",QDt=\"OFCNCOG2CU\",HBe=async(t,e)=>{let r=G.stringifyIdent(t),a=FDt(e).initIndex(\"npm-search\");try{return(await a.getObject(r,{attributesToRetrieve:[\"types\"]})).types?.ts===\"definitely-typed\"}catch{return!1}},FDt=t=>(0,_Be.default)(QDt,kDt,{requester:{async send(r){try{let o=await sn.request(r.url,r.data||null,{configuration:t,headers:r.headers});return{content:o.body,isTimedOut:!1,status:o.statusCode}}catch(o){return{content:o.response.body,isTimedOut:!1,status:o.response.statusCode}}}}});var jBe=t=>t.scope?`${t.scope}__${t.name}`:`${t.name}`,RDt=async(t,e,r,o)=>{if(r.scope===\"types\")return;let{project:a}=t,{configuration:n}=a;if(!(n.get(\"tsEnableAutoTypes\")??(oe.existsSync(V.join(t.cwd,\"tsconfig.json\"))||oe.existsSync(V.join(a.cwd,\"tsconfig.json\")))))return;let A=n.makeResolver(),p={project:a,resolver:A,report:new ki};if(!await HBe(r,n))return;let E=jBe(r),I=G.parseRange(r.range).selector;if(!Lr.validRange(I)){let L=n.normalizeDependency(r),U=await A.getCandidates(L,{},p);I=G.parseRange(U[0].reference).selector}let v=qBe.default.coerce(I);if(v===null)return;let x=`${Zc.Modifier.CARET}${v.major}`,C=G.makeDescriptor(G.makeIdent(\"types\",E),x),R=He.mapAndFind(a.workspaces,L=>{let U=L.manifest.dependencies.get(r.identHash)?.descriptorHash,z=L.manifest.devDependencies.get(r.identHash)?.descriptorHash;if(U!==r.descriptorHash&&z!==r.descriptorHash)return He.mapAndFind.skip;let te=[];for(let ae of Ut.allDependencies){let le=L.manifest[ae].get(C.identHash);typeof le>\"u\"||te.push([ae,le])}return te.length===0?He.mapAndFind.skip:te});if(typeof R<\"u\")for(let[L,U]of R)t.manifest[L].set(U.identHash,U);else{try{let L=n.normalizeDependency(C);if((await A.getCandidates(L,{},p)).length===0)return}catch{return}t.manifest[Zc.Target.DEVELOPMENT].set(C.identHash,C)}},TDt=async(t,e,r)=>{if(r.scope===\"types\")return;let{project:o}=t,{configuration:a}=o;if(!(a.get(\"tsEnableAutoTypes\")??(oe.existsSync(V.join(t.cwd,\"tsconfig.json\"))||oe.existsSync(V.join(o.cwd,\"tsconfig.json\")))))return;let u=jBe(r),A=G.makeIdent(\"types\",u);for(let p of Ut.allDependencies)typeof t.manifest[p].get(A.identHash)>\"u\"||t.manifest[p].delete(A.identHash)},NDt=(t,e)=>{e.publishConfig&&e.publishConfig.typings&&(e.typings=e.publishConfig.typings),e.publishConfig&&e.publishConfig.types&&(e.types=e.publishConfig.types)},LDt={configuration:{tsEnableAutoTypes:{description:\"Whether Yarn should auto-install @types/ dependencies on 'yarn add'\",type:\"BOOLEAN\",isNullable:!0,default:null}},hooks:{afterWorkspaceDependencyAddition:RDt,afterWorkspaceDependencyRemoval:TDt,beforeWorkspacePacking:NDt}},MDt=LDt;var G5={};Vt(G5,{VersionApplyCommand:()=>zC,VersionCheckCommand:()=>JC,VersionCommand:()=>XC,default:()=>rPt,versionUtils:()=>VC});Ge();Ge();qt();var VC={};Vt(VC,{Decision:()=>WC,applyPrerelease:()=>zBe,applyReleases:()=>j5,applyStrategy:()=>XQ,clearVersionFiles:()=>_5,getUndecidedDependentWorkspaces:()=>Pv,getUndecidedWorkspaces:()=>JQ,openVersionFile:()=>KC,requireMoreDecisions:()=>$Dt,resolveVersionFiles:()=>Dv,suggestStrategy:()=>q5,updateVersionFiles:()=>H5,validateReleaseDecision:()=>YC});Ge();Pt();Nl();qt();var VBe=Ze(KBe()),BA=Ze(Jn()),ZDt=/^(>=|[~^]|)(0|[1-9]\\d*)\\.(0|[1-9]\\d*)\\.(0|[1-9]\\d*)(-(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*)(\\.(0|[1-9]\\d*|\\d*[a-zA-Z-][0-9a-zA-Z-]*))*)?(\\+[0-9a-zA-Z-]+(\\.[0-9a-zA-Z-]+)*)?$/,WC=(u=>(u.UNDECIDED=\"undecided\",u.DECLINE=\"decline\",u.MAJOR=\"major\",u.MINOR=\"minor\",u.PATCH=\"patch\",u.PRERELEASE=\"prerelease\",u))(WC||{});function YC(t){let e=BA.default.valid(t);return e||He.validateEnum((0,VBe.default)(WC,\"UNDECIDED\"),t)}async function Dv(t,{prerelease:e=null}={}){let r=new Map,o=t.configuration.get(\"deferredVersionFolder\");if(!oe.existsSync(o))return r;let a=await oe.readdirPromise(o);for(let n of a){if(!n.endsWith(\".yml\"))continue;let u=V.join(o,n),A=await oe.readFilePromise(u,\"utf8\"),p=Ki(A);for(let[h,E]of Object.entries(p.releases||{})){if(E===\"decline\")continue;let I=G.parseIdent(h),v=t.tryWorkspaceByIdent(I);if(v===null)throw new Error(`Assertion failed: Expected a release definition file to only reference existing workspaces (${V.basename(u)} references ${h})`);if(v.manifest.version===null)throw new Error(`Assertion failed: Expected the workspace to have a version (${G.prettyLocator(t.configuration,v.anchoredLocator)})`);let x=v.manifest.raw.stableVersion??v.manifest.version,C=r.get(v),R=XQ(x,YC(E));if(R===null)throw new Error(`Assertion failed: Expected ${x} to support being bumped via strategy ${E}`);let L=typeof C<\"u\"?BA.default.gt(R,C)?R:C:R;r.set(v,L)}}return e&&(r=new Map([...r].map(([n,u])=>[n,zBe(u,{current:n.manifest.version,prerelease:e})]))),r}async function _5(t){let e=t.configuration.get(\"deferredVersionFolder\");oe.existsSync(e)&&await oe.removePromise(e)}async function H5(t,e){let r=new Set(e),o=t.configuration.get(\"deferredVersionFolder\");if(!oe.existsSync(o))return;let a=await oe.readdirPromise(o);for(let n of a){if(!n.endsWith(\".yml\"))continue;let u=V.join(o,n),A=await oe.readFilePromise(u,\"utf8\"),p=Ki(A),h=p?.releases;if(h){for(let E of Object.keys(h)){let I=G.parseIdent(E),v=t.tryWorkspaceByIdent(I);(v===null||r.has(v))&&delete p.releases[E]}Object.keys(p.releases).length>0?await oe.changeFilePromise(u,Da(new Da.PreserveOrdering(p))):await oe.unlinkPromise(u)}}}async function KC(t,{allowEmpty:e=!1}={}){let r=t.configuration;if(r.projectCwd===null)throw new st(\"This command can only be run from within a Yarn project\");let o=await ia.fetchRoot(r.projectCwd),a=o!==null?await ia.fetchBase(o,{baseRefs:r.get(\"changesetBaseRefs\")}):null,n=o!==null?await ia.fetchChangedFiles(o,{base:a.hash,project:t}):[],u=r.get(\"deferredVersionFolder\"),A=n.filter(x=>V.contains(u,x)!==null);if(A.length>1)throw new st(`Your current branch contains multiple versioning files; this isn't supported:\n- ${A.map(x=>ue.fromPortablePath(x)).join(`\n- `)}`);let p=new Set(He.mapAndFilter(n,x=>{let C=t.tryWorkspaceByFilePath(x);return C===null?He.mapAndFilter.skip:C}));if(A.length===0&&p.size===0&&!e)return null;let h=A.length===1?A[0]:V.join(u,`${wn.makeHash(Math.random().toString()).slice(0,8)}.yml`),E=oe.existsSync(h)?await oe.readFilePromise(h,\"utf8\"):\"{}\",I=Ki(E),v=new Map;for(let x of I.declined||[]){let C=G.parseIdent(x),R=t.getWorkspaceByIdent(C);v.set(R,\"decline\")}for(let[x,C]of Object.entries(I.releases||{})){let R=G.parseIdent(x),L=t.getWorkspaceByIdent(R);v.set(L,YC(C))}return{project:t,root:o,baseHash:a!==null?a.hash:null,baseTitle:a!==null?a.title:null,changedFiles:new Set(n),changedWorkspaces:p,releaseRoots:new Set([...p].filter(x=>x.manifest.version!==null)),releases:v,async saveAll(){let x={},C=[],R=[];for(let L of t.workspaces){if(L.manifest.version===null)continue;let U=G.stringifyIdent(L.anchoredLocator),z=v.get(L);z===\"decline\"?C.push(U):typeof z<\"u\"?x[U]=YC(z):p.has(L)&&R.push(U)}await oe.mkdirPromise(V.dirname(h),{recursive:!0}),await oe.changeFilePromise(h,Da(new Da.PreserveOrdering({releases:Object.keys(x).length>0?x:void 0,declined:C.length>0?C:void 0,undecided:R.length>0?R:void 0})))}}}function $Dt(t){return JQ(t).size>0||Pv(t).length>0}function JQ(t){let e=new Set;for(let r of t.changedWorkspaces)r.manifest.version!==null&&(t.releases.has(r)||e.add(r));return e}function Pv(t,{include:e=new Set}={}){let r=[],o=new Map(He.mapAndFilter([...t.releases],([n,u])=>u===\"decline\"?He.mapAndFilter.skip:[n.anchoredLocator.locatorHash,n])),a=new Map(He.mapAndFilter([...t.releases],([n,u])=>u!==\"decline\"?He.mapAndFilter.skip:[n.anchoredLocator.locatorHash,n]));for(let n of t.project.workspaces)if(!(!e.has(n)&&(a.has(n.anchoredLocator.locatorHash)||o.has(n.anchoredLocator.locatorHash)))&&n.manifest.version!==null)for(let u of Ut.hardDependencies)for(let A of n.manifest.getForScope(u).values()){let p=t.project.tryWorkspaceByDescriptor(A);p!==null&&o.has(p.anchoredLocator.locatorHash)&&r.push([n,p])}return r}function q5(t,e){let r=BA.default.clean(e);for(let o of Object.values(WC))if(o!==\"undecided\"&&o!==\"decline\"&&BA.default.inc(t,o)===r)return o;return null}function XQ(t,e){if(BA.default.valid(e))return e;if(t===null)throw new st(`Cannot apply the release strategy \"${e}\" unless the workspace already has a valid version`);if(!BA.default.valid(t))throw new st(`Cannot apply the release strategy \"${e}\" on a non-semver version (${t})`);let r=BA.default.inc(t,e);if(r===null)throw new st(`Cannot apply the release strategy \"${e}\" on the specified version (${t})`);return r}function j5(t,e,{report:r}){let o=new Map;for(let a of t.workspaces)for(let n of Ut.allDependencies)for(let u of a.manifest[n].values()){let A=t.tryWorkspaceByDescriptor(u);if(A===null||!e.has(A))continue;He.getArrayWithDefault(o,A).push([a,n,u.identHash])}for(let[a,n]of e){let u=a.manifest.version;a.manifest.version=n,BA.default.prerelease(n)===null?delete a.manifest.raw.stableVersion:a.manifest.raw.stableVersion||(a.manifest.raw.stableVersion=u);let A=a.manifest.name!==null?G.stringifyIdent(a.manifest.name):null;r.reportInfo(0,`${G.prettyLocator(t.configuration,a.anchoredLocator)}: Bumped to ${n}`),r.reportJson({cwd:ue.fromPortablePath(a.cwd),ident:A,oldVersion:u,newVersion:n});let p=o.get(a);if(!(typeof p>\"u\"))for(let[h,E,I]of p){let v=h.manifest[E].get(I);if(typeof v>\"u\")throw new Error(\"Assertion failed: The dependency should have existed\");let x=v.range,C=!1;if(x.startsWith(ei.protocol)&&(x=x.slice(ei.protocol.length),C=!0,x===a.relativeCwd))continue;let R=x.match(ZDt);if(!R){r.reportWarning(0,`Couldn't auto-upgrade range ${x} (in ${G.prettyLocator(t.configuration,h.anchoredLocator)})`);continue}let L=`${R[1]}${n}`;C&&(L=`${ei.protocol}${L}`);let U=G.makeDescriptor(v,L);h.manifest[E].set(I,U)}}}var ePt=new Map([[\"%n\",{extract:t=>t.length>=1?[t[0],t.slice(1)]:null,generate:(t=0)=>`${t+1}`}]]);function zBe(t,{current:e,prerelease:r}){let o=new BA.default.SemVer(e),a=o.prerelease.slice(),n=[];o.prerelease=[],o.format()!==t&&(a.length=0);let u=!0,A=r.split(/\\./g);for(let p of A){let h=ePt.get(p);if(typeof h>\"u\")n.push(p),a[0]===p?a.shift():u=!1;else{let E=u?h.extract(a):null;E!==null&&typeof E[0]==\"number\"?(n.push(h.generate(E[0])),a=E[1]):(n.push(h.generate()),u=!1)}}return o.prerelease&&(o.prerelease=[]),`${t}-${n.join(\".\")}`}var zC=class extends ut{constructor(){super(...arguments);this.all=ge.Boolean(\"--all\",!1,{description:\"Apply the deferred version changes on all workspaces\"});this.dryRun=ge.Boolean(\"--dry-run\",!1,{description:\"Print the versions without actually generating the package archive\"});this.prerelease=ge.String(\"--prerelease\",{description:\"Add a prerelease identifier to new versions\",tolerateBoolean:!0});this.recursive=ge.Boolean(\"-R,--recursive\",{description:\"Release the transitive workspaces as well\"});this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"})}static{this.paths=[[\"version\",\"apply\"]]}static{this.usage=it.Usage({category:\"Release-related commands\",description:\"apply all the deferred version bumps at once\",details:`\n      This command will apply the deferred version changes and remove their definitions from the repository.\n\n      Note that if \\`--prerelease\\` is set, the given prerelease identifier (by default \\`rc.%n\\`) will be used on all new versions and the version definitions will be kept as-is.\n\n      By default only the current workspace will be bumped, but you can configure this behavior by using one of:\n\n      - \\`--recursive\\` to also apply the version bump on its dependencies\n      - \\`--all\\` to apply the version bump on all packages in the repository\n\n      Note that this command will also update the \\`workspace:\\` references across all your local workspaces, thus ensuring that they keep referring to the same workspaces even after the version bump.\n    `,examples:[[\"Apply the version change to the local workspace\",\"yarn version apply\"],[\"Apply the version change to all the workspaces in the local workspace\",\"yarn version apply --all\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);if(!a)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState({restoreResolutions:!1});let u=await Rt.start({configuration:r,json:this.json,stdout:this.context.stdout},async A=>{let p=this.prerelease?typeof this.prerelease!=\"boolean\"?this.prerelease:\"rc.%n\":null,h=await Dv(o,{prerelease:p}),E=new Map;if(this.all)E=h;else{let I=this.recursive?a.getRecursiveWorkspaceDependencies():[a];for(let v of I){let x=h.get(v);typeof x<\"u\"&&E.set(v,x)}}if(E.size===0){let I=h.size>0?\" Did you want to add --all?\":\"\";A.reportWarning(0,`The current workspace doesn't seem to require a version bump.${I}`);return}j5(o,E,{report:A}),this.dryRun||(p||(this.all?await _5(o):await H5(o,[...E.keys()])),A.reportSeparator())});return this.dryRun||u.hasErrors()?u.exitCode():await o.installWithNewReport({json:this.json,stdout:this.context.stdout},{cache:n})}};Ge();Pt();qt();var ZQ=Ze(Jn());var JC=class extends ut{constructor(){super(...arguments);this.interactive=ge.Boolean(\"-i,--interactive\",{description:\"Open an interactive interface used to set version bumps\"})}static{this.paths=[[\"version\",\"check\"]]}static{this.usage=it.Usage({category:\"Release-related commands\",description:\"check that all the relevant packages have been bumped\",details:\"\\n      **Warning:** This command currently requires Git.\\n\\n      This command will check that all the packages covered by the files listed in argument have been properly bumped or declined to bump.\\n\\n      In the case of a bump, the check will also cover transitive packages - meaning that should `Foo` be bumped, a package `Bar` depending on `Foo` will require a decision as to whether `Bar` will need to be bumped. This check doesn't cross packages that have declined to bump.\\n\\n      In case no arguments are passed to the function, the list of modified files will be generated by comparing the HEAD against `master`.\\n    \",examples:[[\"Check whether the modified packages need a bump\",\"yarn version check\"]]})}async execute(){return this.interactive?await this.executeInteractive():await this.executeStandard()}async executeInteractive(){GE(this.context);let{Gem:r}=await Promise.resolve().then(()=>(Zk(),Eq)),{ScrollableItems:o}=await Promise.resolve().then(()=>(rQ(),tQ)),{FocusRequest:a}=await Promise.resolve().then(()=>(wq(),$we)),{useListInput:n}=await Promise.resolve().then(()=>(eQ(),eIe)),{renderForm:u}=await Promise.resolve().then(()=>(oQ(),sQ)),{Box:A,Text:p}=await Promise.resolve().then(()=>Ze(ic())),{default:h,useCallback:E,useState:I}=await Promise.resolve().then(()=>Ze(an())),v=await Ke.find(this.context.cwd,this.context.plugins),{project:x,workspace:C}=await kt.find(v,this.context.cwd);if(!C)throw new sr(x.cwd,this.context.cwd);await x.restoreInstallState();let R=await KC(x);if(R===null||R.releaseRoots.size===0)return 0;if(R.root===null)throw new st(\"This command can only be run on Git repositories\");let L=()=>h.createElement(A,{flexDirection:\"row\",paddingBottom:1},h.createElement(A,{flexDirection:\"column\",width:60},h.createElement(A,null,h.createElement(p,null,\"Press \",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<up>\"),\"/\",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<down>\"),\" to select workspaces.\")),h.createElement(A,null,h.createElement(p,null,\"Press \",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<left>\"),\"/\",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<right>\"),\" to select release strategies.\"))),h.createElement(A,{flexDirection:\"column\"},h.createElement(A,{marginLeft:1},h.createElement(p,null,\"Press \",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<enter>\"),\" to save.\")),h.createElement(A,{marginLeft:1},h.createElement(p,null,\"Press \",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<ctrl+c>\"),\" to abort.\")))),U=({workspace:Ce,active:de,decision:Be,setDecision:Ee})=>{let g=Ce.manifest.raw.stableVersion??Ce.manifest.version;if(g===null)throw new Error(`Assertion failed: The version should have been set (${G.prettyLocator(v,Ce.anchoredLocator)})`);if(ZQ.default.prerelease(g)!==null)throw new Error(`Assertion failed: Prerelease identifiers shouldn't be found (${g})`);let me=[\"undecided\",\"decline\",\"patch\",\"minor\",\"major\"];n(Be,me,{active:de,minus:\"left\",plus:\"right\",set:Ee});let we=Be===\"undecided\"?h.createElement(p,{color:\"yellow\"},g):Be===\"decline\"?h.createElement(p,{color:\"green\"},g):h.createElement(p,null,h.createElement(p,{color:\"magenta\"},g),\" \\u2192 \",h.createElement(p,{color:\"green\"},ZQ.default.valid(Be)?Be:ZQ.default.inc(g,Be)));return h.createElement(A,{flexDirection:\"column\"},h.createElement(A,null,h.createElement(p,null,G.prettyLocator(v,Ce.anchoredLocator),\" - \",we)),h.createElement(A,null,me.map(Ae=>h.createElement(A,{key:Ae,paddingLeft:2},h.createElement(p,null,h.createElement(r,{active:Ae===Be}),\" \",Ae)))))},z=Ce=>{let de=new Set(R.releaseRoots),Be=new Map([...Ce].filter(([Ee])=>de.has(Ee)));for(;;){let Ee=Pv({project:R.project,releases:Be}),g=!1;if(Ee.length>0){for(let[me]of Ee)if(!de.has(me)){de.add(me),g=!0;let we=Ce.get(me);typeof we<\"u\"&&Be.set(me,we)}}if(!g)break}return{relevantWorkspaces:de,relevantReleases:Be}},te=()=>{let[Ce,de]=I(()=>new Map(R.releases)),Be=E((Ee,g)=>{let me=new Map(Ce);g!==\"undecided\"?me.set(Ee,g):me.delete(Ee);let{relevantReleases:we}=z(me);de(we)},[Ce,de]);return[Ce,Be]},ae=({workspaces:Ce,releases:de})=>{let Be=[];Be.push(`${Ce.size} total`);let Ee=0,g=0;for(let me of Ce){let we=de.get(me);typeof we>\"u\"?g+=1:we!==\"decline\"&&(Ee+=1)}return Be.push(`${Ee} release${Ee===1?\"\":\"s\"}`),Be.push(`${g} remaining`),h.createElement(p,{color:\"yellow\"},Be.join(\", \"))},ce=await u(({useSubmit:Ce})=>{let[de,Be]=te();Ce(de);let{relevantWorkspaces:Ee}=z(de),g=new Set([...Ee].filter(ne=>!R.releaseRoots.has(ne))),[me,we]=I(0),Ae=E(ne=>{switch(ne){case a.BEFORE:we(me-1);break;case a.AFTER:we(me+1);break}},[me,we]);return h.createElement(A,{flexDirection:\"column\"},h.createElement(L,null),h.createElement(A,null,h.createElement(p,{wrap:\"wrap\"},\"The following files have been modified in your local checkout.\")),h.createElement(A,{flexDirection:\"column\",marginTop:1,paddingLeft:2},[...R.changedFiles].map(ne=>h.createElement(A,{key:ne},h.createElement(p,null,h.createElement(p,{color:\"grey\"},ue.fromPortablePath(R.root)),ue.sep,ue.relative(ue.fromPortablePath(R.root),ue.fromPortablePath(ne)))))),R.releaseRoots.size>0&&h.createElement(h.Fragment,null,h.createElement(A,{marginTop:1},h.createElement(p,{wrap:\"wrap\"},\"Because of those files having been modified, the following workspaces may need to be released again (note that private workspaces are also shown here, because even though they won't be published, releasing them will allow us to flag their dependents for potential re-release):\")),g.size>3?h.createElement(A,{marginTop:1},h.createElement(ae,{workspaces:R.releaseRoots,releases:de})):null,h.createElement(A,{marginTop:1,flexDirection:\"column\"},h.createElement(o,{active:me%2===0,radius:1,size:2,onFocusRequest:Ae},[...R.releaseRoots].map(ne=>h.createElement(U,{key:ne.cwd,workspace:ne,decision:de.get(ne)||\"undecided\",setDecision:Z=>Be(ne,Z)}))))),g.size>0?h.createElement(h.Fragment,null,h.createElement(A,{marginTop:1},h.createElement(p,{wrap:\"wrap\"},\"The following workspaces depend on other workspaces that have been marked for release, and thus may need to be released as well:\")),h.createElement(A,null,h.createElement(p,null,\"(Press \",h.createElement(p,{bold:!0,color:\"cyanBright\"},\"<tab>\"),\" to move the focus between the workspace groups.)\")),g.size>5?h.createElement(A,{marginTop:1},h.createElement(ae,{workspaces:g,releases:de})):null,h.createElement(A,{marginTop:1,flexDirection:\"column\"},h.createElement(o,{active:me%2===1,radius:2,size:2,onFocusRequest:Ae},[...g].map(ne=>h.createElement(U,{key:ne.cwd,workspace:ne,decision:de.get(ne)||\"undecided\",setDecision:Z=>Be(ne,Z)}))))):null)},{versionFile:R},{stdin:this.context.stdin,stdout:this.context.stdout,stderr:this.context.stderr});if(typeof ce>\"u\")return 1;R.releases.clear();for(let[Ce,de]of ce)R.releases.set(Ce,de);await R.saveAll()}async executeStandard(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!a)throw new sr(o.cwd,this.context.cwd);return await o.restoreInstallState(),(await Rt.start({configuration:r,stdout:this.context.stdout},async u=>{let A=await KC(o);if(A===null||A.releaseRoots.size===0)return;if(A.root===null)throw new st(\"This command can only be run on Git repositories\");if(u.reportInfo(0,`Your PR was started right after ${pe.pretty(r,A.baseHash.slice(0,7),\"yellow\")} ${pe.pretty(r,A.baseTitle,\"magenta\")}`),A.changedFiles.size>0){u.reportInfo(0,\"You have changed the following files since then:\"),u.reportSeparator();for(let v of A.changedFiles)u.reportInfo(null,`${pe.pretty(r,ue.fromPortablePath(A.root),\"gray\")}${ue.sep}${ue.relative(ue.fromPortablePath(A.root),ue.fromPortablePath(v))}`)}let p=!1,h=!1,E=JQ(A);if(E.size>0){p||u.reportSeparator();for(let v of E)u.reportError(0,`${G.prettyLocator(r,v.anchoredLocator)} has been modified but doesn't have a release strategy attached`);p=!0}let I=Pv(A);for(let[v,x]of I)h||u.reportSeparator(),u.reportError(0,`${G.prettyLocator(r,v.anchoredLocator)} doesn't have a release strategy attached, but depends on ${G.prettyWorkspace(r,x)} which is planned for release.`),h=!0;(p||h)&&(u.reportSeparator(),u.reportInfo(0,\"This command detected that at least some workspaces have received modifications without explicit instructions as to how they had to be released (if needed).\"),u.reportInfo(0,\"To correct these errors, run `yarn version check --interactive` then follow the instructions.\"))})).exitCode()}};Ge();qt();var $Q=Ze(Jn());var XC=class extends ut{constructor(){super(...arguments);this.deferred=ge.Boolean(\"-d,--deferred\",{description:\"Prepare the version to be bumped during the next release cycle\"});this.immediate=ge.Boolean(\"-i,--immediate\",{description:\"Bump the version immediately\"});this.strategy=ge.String()}static{this.paths=[[\"version\"]]}static{this.usage=it.Usage({category:\"Release-related commands\",description:\"apply a new version to the current package\",details:\"\\n      This command will bump the version number for the given package, following the specified strategy:\\n\\n      - If `major`, the first number from the semver range will be increased (`X.0.0`).\\n      - If `minor`, the second number from the semver range will be increased (`0.X.0`).\\n      - If `patch`, the third number from the semver range will be increased (`0.0.X`).\\n      - If prefixed by `pre` (`premajor`, ...), a `-0` suffix will be set (`0.0.0-0`).\\n      - If `prerelease`, the suffix will be increased (`0.0.0-X`); the third number from the semver range will also be increased if there was no suffix in the previous version.\\n      - If `decline`, the nonce will be increased for `yarn version check` to pass without version bump.\\n      - If a valid semver range, it will be used as new version.\\n      - If unspecified, Yarn will ask you for guidance.\\n\\n      For more information about the `--deferred` flag, consult our documentation (https://yarnpkg.com/features/release-workflow#deferred-versioning).\\n    \",examples:[[\"Immediately bump the version to the next major\",\"yarn version major\"],[\"Prepare the version to be bumped to the next major\",\"yarn version major --deferred\"]]})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!a)throw new sr(o.cwd,this.context.cwd);let n=r.get(\"preferDeferredVersions\");this.deferred&&(n=!0),this.immediate&&(n=!1);let u=$Q.default.valid(this.strategy),A=this.strategy===\"decline\",p;if(u)if(a.manifest.version!==null){let E=q5(a.manifest.version,this.strategy);E!==null?p=E:p=this.strategy}else p=this.strategy;else{let E=a.manifest.version;if(!A){if(E===null)throw new st(\"Can't bump the version if there wasn't a version to begin with - use 0.0.0 as initial version then run the command again.\");if(typeof E!=\"string\"||!$Q.default.valid(E))throw new st(`Can't bump the version (${E}) if it's not valid semver`)}p=YC(this.strategy)}if(!n){let I=(await Dv(o)).get(a);if(typeof I<\"u\"&&p!==\"decline\"){let v=XQ(a.manifest.version,p);if($Q.default.lt(v,I))throw new st(`Can't bump the version to one that would be lower than the current deferred one (${I})`)}}let h=await KC(o,{allowEmpty:!0});return h.releases.set(a,p),await h.saveAll(),n?0:await this.cli.run([\"version\",\"apply\"])}};var tPt={configuration:{deferredVersionFolder:{description:\"Folder where are stored the versioning files\",type:\"ABSOLUTE_PATH\",default:\"./.yarn/versions\"},preferDeferredVersions:{description:\"If true, running `yarn version` will assume the `--deferred` flag unless `--immediate` is set\",type:\"BOOLEAN\",default:!1}},commands:[zC,JC,XC]},rPt=tPt;var Y5={};Vt(Y5,{WorkspacesFocusCommand:()=>ZC,WorkspacesForeachCommand:()=>ew,default:()=>sPt});Ge();Ge();qt();var ZC=class extends ut{constructor(){super(...arguments);this.json=ge.Boolean(\"--json\",!1,{description:\"Format the output as an NDJSON stream\"});this.production=ge.Boolean(\"--production\",!1,{description:\"Only install regular dependencies by omitting dev dependencies\"});this.all=ge.Boolean(\"-A,--all\",!1,{description:\"Install the entire project\"});this.workspaces=ge.Rest()}static{this.paths=[[\"workspaces\",\"focus\"]]}static{this.usage=it.Usage({category:\"Workspace-related commands\",description:\"install a single workspace and its dependencies\",details:\"\\n      This command will run an install as if the specified workspaces (and all other workspaces they depend on) were the only ones in the project. If no workspaces are explicitly listed, the active one will be assumed.\\n\\n      Note that this command is only very moderately useful when using zero-installs, since the cache will contain all the packages anyway - meaning that the only difference between a full install and a focused install would just be a few extra lines in the `.pnp.cjs` file, at the cost of introducing an extra complexity.\\n\\n      If the `-A,--all` flag is set, the entire project will be installed. Combine with `--production` to replicate the old `yarn install --production`.\\n    \"})}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd),n=await Gr.find(r);await o.restoreInstallState({restoreResolutions:!1});let u;if(this.all)u=new Set(o.workspaces);else if(this.workspaces.length===0){if(!a)throw new sr(o.cwd,this.context.cwd);u=new Set([a])}else u=new Set(this.workspaces.map(A=>o.getWorkspaceByIdent(G.parseIdent(A))));for(let A of u)for(let p of this.production?[\"dependencies\"]:Ut.hardDependencies)for(let h of A.manifest.getForScope(p).values()){let E=o.tryWorkspaceByDescriptor(h);E!==null&&u.add(E)}for(let A of o.workspaces)u.has(A)?this.production&&A.manifest.devDependencies.clear():(A.manifest.installConfig=A.manifest.installConfig||{},A.manifest.installConfig.selfReferences=!1,A.manifest.dependencies.clear(),A.manifest.devDependencies.clear(),A.manifest.peerDependencies.clear(),A.manifest.scripts.clear());return await o.installWithNewReport({json:this.json,stdout:this.context.stdout},{cache:n,persistProject:!1})}};Ge();Ge();Ge();qt();var $C=Ze($o()),XBe=Ze(eg());el();var ew=class extends ut{constructor(){super(...arguments);this.from=ge.Array(\"--from\",{description:\"An array of glob pattern idents or paths from which to base any recursion\"});this.all=ge.Boolean(\"-A,--all\",{description:\"Run the command on all workspaces of a project\"});this.recursive=ge.Boolean(\"-R,--recursive\",{description:\"Run the command on the current workspace and all of its recursive dependencies\"});this.worktree=ge.Boolean(\"-W,--worktree\",{description:\"Run the command on all workspaces of the current worktree\"});this.verbose=ge.Counter(\"-v,--verbose\",{description:\"Increase level of logging verbosity up to 2 times\"});this.parallel=ge.Boolean(\"-p,--parallel\",!1,{description:\"Run the commands in parallel\"});this.interlaced=ge.Boolean(\"-i,--interlaced\",!1,{description:\"Print the output of commands in real-time instead of buffering it\"});this.jobs=ge.String(\"-j,--jobs\",{description:\"The maximum number of parallel tasks that the execution will be limited to; or `unlimited`\",validator:IT([Js([\"unlimited\"]),jw(wT(),[vT(),BT(1)])])});this.topological=ge.Boolean(\"-t,--topological\",!1,{description:\"Run the command after all workspaces it depends on (regular) have finished\"});this.topologicalDev=ge.Boolean(\"--topological-dev\",!1,{description:\"Run the command after all workspaces it depends on (regular + dev) have finished\"});this.include=ge.Array(\"--include\",[],{description:\"An array of glob pattern idents or paths; only matching workspaces will be traversed\"});this.exclude=ge.Array(\"--exclude\",[],{description:\"An array of glob pattern idents or paths; matching workspaces won't be traversed\"});this.publicOnly=ge.Boolean(\"--no-private\",{description:\"Avoid running the command on private workspaces\"});this.since=ge.String(\"--since\",{description:\"Only include workspaces that have been changed since the specified ref.\",tolerateBoolean:!0});this.dryRun=ge.Boolean(\"-n,--dry-run\",{description:\"Print the commands that would be run, without actually running them\"});this.commandName=ge.String();this.args=ge.Proxy()}static{this.paths=[[\"workspaces\",\"foreach\"]]}static{this.usage=it.Usage({category:\"Workspace-related commands\",description:\"run a command on all workspaces\",details:\"\\n      This command will run a given sub-command on current and all its descendant workspaces. Various flags can alter the exact behavior of the command:\\n\\n      - If `-p,--parallel` is set, the commands will be ran in parallel; they'll by default be limited to a number of parallel tasks roughly equal to half your core number, but that can be overridden via `-j,--jobs`, or disabled by setting `-j unlimited`.\\n\\n      - If `-p,--parallel` and `-i,--interlaced` are both set, Yarn will print the lines from the output as it receives them. If `-i,--interlaced` wasn't set, it would instead buffer the output from each process and print the resulting buffers only after their source processes have exited.\\n\\n      - If `-t,--topological` is set, Yarn will only run the command after all workspaces that it depends on through the `dependencies` field have successfully finished executing. If `--topological-dev` is set, both the `dependencies` and `devDependencies` fields will be considered when figuring out the wait points.\\n\\n      - If `-A,--all` is set, Yarn will run the command on all the workspaces of a project.\\n\\n      - If `-R,--recursive` is set, Yarn will find workspaces to run the command on by recursively evaluating `dependencies` and `devDependencies` fields, instead of looking at the `workspaces` fields.\\n\\n      - If `-W,--worktree` is set, Yarn will find workspaces to run the command on by looking at the current worktree.\\n\\n      - If `--from` is set, Yarn will use the packages matching the 'from' glob as the starting point for any recursive search.\\n\\n      - If `--since` is set, Yarn will only run the command on workspaces that have been modified since the specified ref. By default Yarn will use the refs specified by the `changesetBaseRefs` configuration option.\\n\\n      - If `--dry-run` is set, Yarn will explain what it would do without actually doing anything.\\n\\n      - The command may apply to only some workspaces through the use of `--include` which acts as a whitelist. The `--exclude` flag will do the opposite and will be a list of packages that mustn't execute the script. Both flags accept glob patterns (if valid Idents and supported by [micromatch](https://github.com/micromatch/micromatch)). Make sure to escape the patterns, to prevent your own shell from trying to expand them.\\n\\n      The `-v,--verbose` flag can be passed up to twice: once to prefix output lines with the originating workspace's name, and again to include start/finish/timing log lines. Maximum verbosity is enabled by default in terminal environments.\\n\\n      If the command is `run` and the script being run does not exist the child workspace will be skipped without error.\\n    \",examples:[[\"Publish all packages\",\"yarn workspaces foreach -A npm publish --tolerate-republish\"],[\"Run the build script on all descendant packages\",\"yarn workspaces foreach -A run build\"],[\"Run the build script on current and all descendant packages in parallel, building package dependencies first\",\"yarn workspaces foreach -Apt run build\"],[\"Run the build script on several packages and all their dependencies, building dependencies first\",\"yarn workspaces foreach -Rpt --from '{workspace-a,workspace-b}' run build\"]]})}static{this.schema=[Yw(\"all\",Yu.Forbids,[\"from\",\"recursive\",\"since\",\"worktree\"],{missingIf:\"undefined\"}),DT([\"all\",\"recursive\",\"since\",\"worktree\"],{missingIf:\"undefined\"})]}async execute(){let r=await Ke.find(this.context.cwd,this.context.plugins),{project:o,workspace:a}=await kt.find(r,this.context.cwd);if(!this.all&&!a)throw new sr(o.cwd,this.context.cwd);await o.restoreInstallState();let n=this.cli.process([this.commandName,...this.args]),u=n.path.length===1&&n.path[0]===\"run\"&&typeof n.scriptName<\"u\"?n.scriptName:null;if(n.path.length===0)throw new st(\"Invalid subcommand name for iteration - use the 'run' keyword if you wish to execute a script\");let A=Ee=>{this.dryRun&&this.context.stdout.write(`${Ee}\n`)},p=()=>{let Ee=this.from.map(g=>$C.default.matcher(g));return o.workspaces.filter(g=>{let me=G.stringifyIdent(g.anchoredLocator),we=g.relativeCwd;return Ee.some(Ae=>Ae(me)||Ae(we))})},h=[];if(this.since?(A(\"Option --since is set; selecting the changed workspaces as root for workspace selection\"),h=Array.from(await ia.fetchChangedWorkspaces({ref:this.since,project:o}))):this.from?(A(\"Option --from is set; selecting the specified workspaces\"),h=[...p()]):this.worktree?(A(\"Option --worktree is set; selecting the current workspace\"),h=[a]):this.recursive?(A(\"Option --recursive is set; selecting the current workspace\"),h=[a]):this.all&&(A(\"Option --all is set; selecting all workspaces\"),h=[...o.workspaces]),this.dryRun&&!this.all){for(let Ee of h)A(`\n- ${Ee.relativeCwd}\n  ${G.prettyLocator(r,Ee.anchoredLocator)}`);h.length>0&&A(\"\")}let E;if(this.recursive?this.since?(A(\"Option --recursive --since is set; recursively selecting all dependent workspaces\"),E=new Set(h.map(Ee=>[...Ee.getRecursiveWorkspaceDependents()]).flat())):(A(\"Option --recursive is set; recursively selecting all transitive dependencies\"),E=new Set(h.map(Ee=>[...Ee.getRecursiveWorkspaceDependencies()]).flat())):this.worktree?(A(\"Option --worktree is set; recursively selecting all nested workspaces\"),E=new Set(h.map(Ee=>[...Ee.getRecursiveWorkspaceChildren()]).flat())):E=null,E!==null&&(h=[...new Set([...h,...E])],this.dryRun))for(let Ee of E)A(`\n- ${Ee.relativeCwd}\n  ${G.prettyLocator(r,Ee.anchoredLocator)}`);let I=[],v=!1;if(u?.includes(\":\")){for(let Ee of o.workspaces)if(Ee.manifest.scripts.has(u)&&(v=!v,v===!1))break}for(let Ee of h){if(u&&!Ee.manifest.scripts.has(u)&&!v&&!(await An.getWorkspaceAccessibleBinaries(Ee)).has(u)){A(`Excluding ${Ee.relativeCwd} because it doesn't have a \"${u}\" script`);continue}if(!(u===r.env.npm_lifecycle_event&&Ee.cwd===a.cwd)){if(this.include.length>0&&!$C.default.isMatch(G.stringifyIdent(Ee.anchoredLocator),this.include)&&!$C.default.isMatch(Ee.relativeCwd,this.include)){A(`Excluding ${Ee.relativeCwd} because it doesn't match the --include filter`);continue}if(this.exclude.length>0&&($C.default.isMatch(G.stringifyIdent(Ee.anchoredLocator),this.exclude)||$C.default.isMatch(Ee.relativeCwd,this.exclude))){A(`Excluding ${Ee.relativeCwd} because it matches the --include filter`);continue}if(this.publicOnly&&Ee.manifest.private===!0){A(`Excluding ${Ee.relativeCwd} because it's a private workspace and --no-private was set`);continue}I.push(Ee)}}if(this.dryRun)return 0;let x=this.verbose??(this.context.stdout.isTTY?1/0:0),C=x>0,R=x>1,L=this.parallel?this.jobs===\"unlimited\"?1/0:Number(this.jobs)||Math.ceil(Xi.availableParallelism()/2):1,U=L===1?!1:this.parallel,z=U?this.interlaced:!0,te=(0,XBe.default)(L),ae=new Map,le=new Set,ce=0,Ce=null,de=!1,Be=await Rt.start({configuration:r,stdout:this.context.stdout,includePrefix:!1},async Ee=>{let g=async(me,{commandIndex:we})=>{if(de)return-1;!U&&R&&we>1&&Ee.reportSeparator();let Ae=nPt(me,{configuration:r,label:C,commandIndex:we}),[ne,Z]=JBe(Ee,{prefix:Ae,interlaced:z}),[xe,Ne]=JBe(Ee,{prefix:Ae,interlaced:z});try{R&&Ee.reportInfo(null,`${Ae?`${Ae} `:\"\"}Process started`);let ht=Date.now(),H=await this.cli.run([this.commandName,...this.args],{cwd:me.cwd,stdout:ne,stderr:xe})||0;ne.end(),xe.end(),await Z,await Ne;let rt=Date.now();if(R){let Te=r.get(\"enableTimers\")?`, completed in ${pe.pretty(r,rt-ht,pe.Type.DURATION)}`:\"\";Ee.reportInfo(null,`${Ae?`${Ae} `:\"\"}Process exited (exit code ${H})${Te}`)}return H===130&&(de=!0,Ce=H),H}catch(ht){throw ne.end(),xe.end(),await Z,await Ne,ht}};for(let me of I)ae.set(me.anchoredLocator.locatorHash,me);for(;ae.size>0&&!Ee.hasErrors();){let me=[];for(let[ne,Z]of ae){if(le.has(Z.anchoredDescriptor.descriptorHash))continue;let xe=!0;if(this.topological||this.topologicalDev){let Ne=this.topologicalDev?new Map([...Z.manifest.dependencies,...Z.manifest.devDependencies]):Z.manifest.dependencies;for(let ht of Ne.values()){let H=o.tryWorkspaceByDescriptor(ht);if(xe=H===null||!ae.has(H.anchoredLocator.locatorHash),!xe)break}}if(xe&&(le.add(Z.anchoredDescriptor.descriptorHash),me.push(te(async()=>{let Ne=await g(Z,{commandIndex:++ce});return ae.delete(ne),le.delete(Z.anchoredDescriptor.descriptorHash),Ne})),!U))break}if(me.length===0){let ne=Array.from(ae.values()).map(Z=>G.prettyLocator(r,Z.anchoredLocator)).join(\", \");Ee.reportError(3,`Dependency cycle detected (${ne})`);return}let Ae=(await Promise.all(me)).find(ne=>ne!==0);Ce===null&&(Ce=typeof Ae<\"u\"?1:Ce),(this.topological||this.topologicalDev)&&typeof Ae<\"u\"&&Ee.reportError(0,\"The command failed for workspaces that are depended upon by other workspaces; can't satisfy the dependency graph\")}});return Ce!==null?Ce:Be.exitCode()}};function JBe(t,{prefix:e,interlaced:r}){let o=t.createStreamReporter(e),a=new He.DefaultStream;a.pipe(o,{end:!1}),a.on(\"finish\",()=>{o.end()});let n=new Promise(A=>{o.on(\"finish\",()=>{A(a.active)})});if(r)return[a,n];let u=new He.BufferStream;return u.pipe(a,{end:!1}),u.on(\"finish\",()=>{a.end()}),[u,n]}function nPt(t,{configuration:e,commandIndex:r,label:o}){if(!o)return null;let n=`[${G.stringifyIdent(t.anchoredLocator)}]:`,u=[\"#2E86AB\",\"#A23B72\",\"#F18F01\",\"#C73E1D\",\"#CCE2A3\"],A=u[r%u.length];return pe.pretty(e,n,A)}var iPt={commands:[ZC,ew]},sPt=iPt;var Hy=()=>({modules:new Map([[\"@yarnpkg/cli\",W1],[\"@yarnpkg/core\",Y1],[\"@yarnpkg/fslib\",kw],[\"@yarnpkg/libzip\",p1],[\"@yarnpkg/parsers\",Ow],[\"@yarnpkg/shell\",E1],[\"clipanion\",Jw],[\"semver\",oPt],[\"typanion\",Vo],[\"@yarnpkg/plugin-essentials\",K8],[\"@yarnpkg/plugin-compat\",Z8],[\"@yarnpkg/plugin-constraints\",dH],[\"@yarnpkg/plugin-dlx\",mH],[\"@yarnpkg/plugin-exec\",CH],[\"@yarnpkg/plugin-file\",IH],[\"@yarnpkg/plugin-git\",W8],[\"@yarnpkg/plugin-github\",DH],[\"@yarnpkg/plugin-http\",PH],[\"@yarnpkg/plugin-init\",bH],[\"@yarnpkg/plugin-interactive-tools\",kq],[\"@yarnpkg/plugin-link\",Qq],[\"@yarnpkg/plugin-nm\",hj],[\"@yarnpkg/plugin-npm\",f5],[\"@yarnpkg/plugin-npm-cli\",w5],[\"@yarnpkg/plugin-pack\",a5],[\"@yarnpkg/plugin-patch\",S5],[\"@yarnpkg/plugin-pnp\",rj],[\"@yarnpkg/plugin-pnpm\",Q5],[\"@yarnpkg/plugin-stage\",O5],[\"@yarnpkg/plugin-typescript\",U5],[\"@yarnpkg/plugin-version\",G5],[\"@yarnpkg/plugin-workspace-tools\",Y5]]),plugins:new Set([\"@yarnpkg/plugin-essentials\",\"@yarnpkg/plugin-compat\",\"@yarnpkg/plugin-constraints\",\"@yarnpkg/plugin-dlx\",\"@yarnpkg/plugin-exec\",\"@yarnpkg/plugin-file\",\"@yarnpkg/plugin-git\",\"@yarnpkg/plugin-github\",\"@yarnpkg/plugin-http\",\"@yarnpkg/plugin-init\",\"@yarnpkg/plugin-interactive-tools\",\"@yarnpkg/plugin-link\",\"@yarnpkg/plugin-nm\",\"@yarnpkg/plugin-npm\",\"@yarnpkg/plugin-npm-cli\",\"@yarnpkg/plugin-pack\",\"@yarnpkg/plugin-patch\",\"@yarnpkg/plugin-pnp\",\"@yarnpkg/plugin-pnpm\",\"@yarnpkg/plugin-stage\",\"@yarnpkg/plugin-typescript\",\"@yarnpkg/plugin-version\",\"@yarnpkg/plugin-workspace-tools\"])});function eve({cwd:t,pluginConfiguration:e}){let r=new Jo({binaryLabel:\"Yarn Package Manager\",binaryName:\"yarn\",binaryVersion:nn??\"<unknown>\"});return Object.assign(r,{defaultContext:{...Jo.defaultContext,cwd:t,plugins:e,quiet:!1,stdin:process.stdin,stdout:process.stdout,stderr:process.stderr}})}function aPt(t){if(He.parseOptionalBoolean(process.env.YARN_IGNORE_NODE))return!0;let r=process.versions.node,o=\">=18.12.0\";if(Lr.satisfiesWithPrereleases(r,o))return!0;let a=new st(`This tool requires a Node version compatible with ${o} (got ${r}). Upgrade Node, or set \\`YARN_IGNORE_NODE=1\\` in your environment.`);return Jo.defaultContext.stdout.write(t.error(a)),!1}async function tve({selfPath:t,pluginConfiguration:e}){return await Ke.find(ue.toPortablePath(process.cwd()),e,{strict:!1,usePathCheck:t})}function lPt(t,e,{yarnPath:r}){if(!oe.existsSync(r))return t.error(new Error(`The \"yarn-path\" option has been set, but the specified location doesn't exist (${r}).`)),1;process.on(\"SIGINT\",()=>{});let o={stdio:\"inherit\",env:{...process.env,YARN_IGNORE_PATH:\"1\"}};try{(0,ZBe.execFileSync)(process.execPath,[ue.fromPortablePath(r),...e],o)}catch(a){return a.status??1}return 0}function cPt(t,e){let r=null,o=e;return e.length>=2&&e[0]===\"--cwd\"?(r=ue.toPortablePath(e[1]),o=e.slice(2)):e.length>=1&&e[0].startsWith(\"--cwd=\")?(r=ue.toPortablePath(e[0].slice(6)),o=e.slice(1)):e[0]===\"add\"&&e[e.length-2]===\"--cwd\"&&(r=ue.toPortablePath(e[e.length-1]),o=e.slice(0,e.length-2)),t.defaultContext.cwd=r!==null?V.resolve(r):V.cwd(),o}function uPt(t,{configuration:e}){if(!e.get(\"enableTelemetry\")||$Be.isCI||!process.stdout.isTTY)return;Ke.telemetry=new Oy(e,\"puba9cdc10ec5790a2cf4969dd413a47270\");let o=/^@yarnpkg\\/plugin-(.*)$/;for(let a of e.plugins.keys())Uy.has(a.match(o)?.[1]??\"\")&&Ke.telemetry?.reportPluginName(a);t.binaryVersion&&Ke.telemetry.reportVersion(t.binaryVersion)}function rve(t,{configuration:e}){for(let r of e.plugins.values())for(let o of r.commands||[])t.register(o)}async function APt(t,e,{selfPath:r,pluginConfiguration:o}){if(!aPt(t))return 1;let a=await tve({selfPath:r,pluginConfiguration:o}),n=a.get(\"yarnPath\"),u=a.get(\"ignorePath\");if(n&&!u)return lPt(t,e,{yarnPath:n});delete process.env.YARN_IGNORE_PATH;let A=cPt(t,e);uPt(t,{configuration:a}),rve(t,{configuration:a});let p=t.process(A,t.defaultContext);return p.help||Ke.telemetry?.reportCommandName(p.path.join(\" \")),await t.run(p,t.defaultContext)}async function ihe({cwd:t=V.cwd(),pluginConfiguration:e=Hy()}={}){let r=eve({cwd:t,pluginConfiguration:e}),o=await tve({pluginConfiguration:e,selfPath:null});return rve(r,{configuration:o}),r}async function Wx(t,{cwd:e=V.cwd(),selfPath:r,pluginConfiguration:o}){let a=eve({cwd:e,pluginConfiguration:o});function n(){Jo.defaultContext.stdout.write(`ERROR: Yarn is terminating due to an unexpected empty event loop.\nPlease report this issue at https://github.com/yarnpkg/berry/issues.`)}process.once(\"beforeExit\",n);try{process.exitCode=42,process.exitCode=await APt(a,t,{selfPath:r,pluginConfiguration:o})}catch(u){Jo.defaultContext.stdout.write(a.error(u)),process.exitCode=1}finally{process.off(\"beforeExit\",n),await oe.rmtempPromise()}}Wx(process.argv.slice(2),{cwd:V.cwd(),selfPath:ue.toPortablePath(ue.resolve(process.argv[1])),pluginConfiguration:Hy()});})();\n/**\n  @license\n  Copyright (c) 2015, Rebecca Turner\n\n  Permission to use, copy, modify, and/or distribute this software for any\n  purpose with or without fee is hereby granted, provided that the above\n  copyright notice and this permission notice appear in all copies.\n\n  THE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\n  REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND\n  FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\n  INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\n  LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\n  OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\n  PERFORMANCE OF THIS SOFTWARE.\n */\n/**\n  @license\n  Copyright Node.js contributors. All rights reserved.\n\n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files (the \"Software\"), to\n  deal in the Software without restriction, including without limitation the\n  rights to use, copy, modify, merge, publish, distribute, sublicense, and/or\n  sell copies of the Software, and to permit persons to whom the Software is\n  furnished to do so, subject to the following conditions:\n\n  The above copyright notice and this permission notice shall be included in\n  all copies or substantial portions of the Software.\n\n  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING\n  FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS\n  IN THE SOFTWARE.\n*/\n/**\n  @license\n  The MIT License (MIT)\n\n  Copyright (c) 2014 Blake Embrey (hello@blakeembrey.com)\n\n  Permission is hereby granted, free of charge, to any person obtaining a copy\n  of this software and associated documentation files (the \"Software\"), to deal\n  in the Software without restriction, including without limitation the rights\n  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n  copies of the Software, and to permit persons to whom the Software is\n  furnished to do so, subject to the following conditions:\n\n  The above copyright notice and this permission notice shall be included in\n  all copies or substantial portions of the Software.\n\n  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n  THE SOFTWARE.\n*/\n/**\n  @license\n  Copyright Joyent, Inc. and other Node contributors.\n\n  Permission is hereby granted, free of charge, to any person obtaining a\n  copy of this software and associated documentation files (the\n  \"Software\"), to deal in the Software without restriction, including\n  without limitation the rights to use, copy, modify, merge, publish,\n  distribute, sublicense, and/or sell copies of the Software, and to permit\n  persons to whom the Software is furnished to do so, subject to the\n  following conditions:\n\n  The above copyright notice and this permission notice shall be included\n  in all copies or substantial portions of the Software.\n\n  THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\n  OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\n  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\n  NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\n  DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\n  OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\n  USE OR OTHER DEALINGS IN THE SOFTWARE.\n*/\n/*! Bundled license information:\n\nis-number/index.js:\n  (*!\n   * is-number <https://github.com/jonschlinkert/is-number>\n   *\n   * Copyright (c) 2014-present, Jon Schlinkert.\n   * Released under the MIT License.\n   *)\n\nto-regex-range/index.js:\n  (*!\n   * to-regex-range <https://github.com/micromatch/to-regex-range>\n   *\n   * Copyright (c) 2015-present, Jon Schlinkert.\n   * Released under the MIT License.\n   *)\n\nfill-range/index.js:\n  (*!\n   * fill-range <https://github.com/jonschlinkert/fill-range>\n   *\n   * Copyright (c) 2014-present, Jon Schlinkert.\n   * Licensed under the MIT License.\n   *)\n\nis-extglob/index.js:\n  (*!\n   * is-extglob <https://github.com/jonschlinkert/is-extglob>\n   *\n   * Copyright (c) 2014-2016, Jon Schlinkert.\n   * Licensed under the MIT License.\n   *)\n\nis-glob/index.js:\n  (*!\n   * is-glob <https://github.com/jonschlinkert/is-glob>\n   *\n   * Copyright (c) 2014-2017, Jon Schlinkert.\n   * Released under the MIT License.\n   *)\n\nqueue-microtask/index.js:\n  (*! queue-microtask. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)\n\nrun-parallel/index.js:\n  (*! run-parallel. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> *)\n\ngit-url-parse/lib/index.js:\n  (*!\n   * buildToken\n   * Builds OAuth token prefix (helper function)\n   *\n   * @name buildToken\n   * @function\n   * @param {GitUrl} obj The parsed Git url object.\n   * @return {String} token prefix\n   *)\n\nobject-assign/index.js:\n  (*\n  object-assign\n  (c) Sindre Sorhus\n  @license MIT\n  *)\n\nreact/cjs/react.production.min.js:\n  (** @license React v16.13.1\n   * react.production.min.js\n   *\n   * Copyright (c) Facebook, Inc. and its affiliates.\n   *\n   * This source code is licensed under the MIT license found in the\n   * LICENSE file in the root directory of this source tree.\n   *)\n\nscheduler/cjs/scheduler.production.min.js:\n  (** @license React v0.18.0\n   * scheduler.production.min.js\n   *\n   * Copyright (c) Facebook, Inc. and its affiliates.\n   *\n   * This source code is licensed under the MIT license found in the\n   * LICENSE file in the root directory of this source tree.\n   *)\n\nreact-reconciler/cjs/react-reconciler.production.min.js:\n  (** @license React v0.24.0\n   * react-reconciler.production.min.js\n   *\n   * Copyright (c) Facebook, Inc. and its affiliates.\n   *\n   * This source code is licensed under the MIT license found in the\n   * LICENSE file in the root directory of this source tree.\n   *)\n\nis-windows/index.js:\n  (*!\n   * is-windows <https://github.com/jonschlinkert/is-windows>\n   *\n   * Copyright © 2015-2018, Jon Schlinkert.\n   * Released under the MIT License.\n   *)\n*/\n"
  },
  {
    "path": ".yarnrc.yml",
    "content": "compressionLevel: mixed\n\nenableGlobalCache: false\n\nenableTransparentWorkspaces: false\n\nnodeLinker: node-modules\n\nyarnPath: .yarn/releases/yarn-4.4.1.cjs\n"
  },
  {
    "path": "CNAME",
    "content": "redux-toolkit.js.org\n"
  },
  {
    "path": "CODE_OF_CONDUCT.md",
    "content": "# Contributor Code of Conduct\n\nAs contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.\n\nWe are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, age, or religion.\n\nExamples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.\n\nProject maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.\n\nInstances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.\n\nThis Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)\n"
  },
  {
    "path": "CONTRIBUTING.md",
    "content": "# Contributing\n\nWe are open to, and grateful for, any contributions made by the community. By contributing to Redux Toolkit, you agree to abide by the [code of conduct](https://github.com/reduxjs/redux-toolkit/blob/master/CODE_OF_CONDUCT.md).\n\n## Reporting Issues and Asking Questions\n\nBefore opening an issue, please search the [issue tracker](https://github.com/reduxjs/redux-toolkit/issues) to make sure your issue hasn't already been reported.\n\nPlease ask any general and implementation specific questions on [Stack Overflow with a Redux Toolkit tag](http://stackoverflow.com/questions/tagged/redux-toolkit?sort=votes&pageSize=50) for support.\n\nWe ask you to do this because StackOverflow has a much better job at keeping popular questions visible. Unfortunately good answers get lost and outdated on GitHub.\n\nIf your question gets closed or you don't get a reply after a few days, consider opening a [discussion](https://github.com/reduxjs/redux-toolkit/discussions) or joining the [Reactiflux](https://discord.gg/reactiflux) discord server and asking in the #redux channel.\n\n### Help Us Help You\n\nOn both websites, it is a good idea to structure your code and question in a way that is easy to read to help people to answer it. For example, we encourage you to use syntax highlighting, indentation, and split text in paragraphs.\n\nPlease keep in mind that people spend their free time trying to help you. You can make it easier for them if you provide versions of the relevant libraries and a runnable small project reproducing your issue. You can put your code on [JSBin](https://jsbin.com) or, for bigger projects, on GitHub. Make sure all the necessary dependencies are declared in `package.json` so anyone can run `npm install && npm start` and reproduce your issue.\n\n## Ways You Can Contribute\n\nThere are several ways you can contribute to the repository. Instead of developing a feature or fixing a bug, you can also contribute by updating or writing [documentation](https://github.com/reduxjs/redux-toolkit/tree/master/docs) for a specific feature or implementation if you know you are good with documentation. Alternatively, you can add [examples](https://github.com/reduxjs/redux-toolkit/tree/master/examples) of any 3rd party implementation like GraphQL or React (just an example) that would help users to understand and easily integrate Redux Toolkit with that specific framework and library.\n\n## Getting started\n\nVisit the [Issue tracker](https://github.com/reduxjs/redux-toolkit/issues) to find a list of open issues that need attention.\n\n### Bugs and Improvements\n\nWe use the [Issue tracker](https://github.com/reduxjs/redux-toolkit/issues) to keep track of bugs and improvements to Redux Toolkit itself, its examples, and the documentation. We encourage you to open issues to discuss improvements, architecture, theory, internal implementation, etc. If a topic has been discussed before, we will ask you to join the previous discussion.\n\n### New Features\n\nPlease open an [issue](https://github.com/reduxjs/redux-toolkit/issues) with a proposal for a new feature or refactoring before starting on the work. We don't want you to waste your efforts on a pull request that we won't want to accept.\n\n### Fork the repository\n\nPlease use the GitHub UI to [fork this repository](https://github.com/reduxjs/redux-toolkit) (_read more about [Forking a repository](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo)_). Redux Toolkit has forked builds enabled in the CI, so you will see the build status of your fork's branch.\n\n![Fork Button](https://docs.github.com/assets/cb-40742/mw-1440/images/help/repository/fork-button.webp)\n\nFork, then clone the repo:\n\n```sh\ngit clone https://github.com/your-username/redux-toolkit.git\n```\n\n### Install\n\n```bash\n$ cd redux-toolkit\n$ yarn\n```\n\n### Build\n\nYou can build the packages with the following command:\n\n```\nyarn build\n```\n\n### Tests\n\nYou can run tests for all packages with:\n\n```\nyarn test\n```\n\nTo continuously watch and run tests, run the following:\n\n```\nyarn test --watch\n```\n\n## Git workflow / Submitting Changes\n\n- Open a new issue in the [Issue tracker](https://github.com/reduxjs/redux-toolkit/issues).\n- Fork the repo.\n- Create a new feature branch based off the `master` branch.\n- Make sure all tests pass and there are no linting errors.\n- Submit a pull request, referencing any issues it addresses.\n- If you changed external-facing types, make sure to also build the project locally and include the updated API report file etc/redux-toolkit.api.md in your pull request.\n\nPlease try to keep your pull request focused in scope and avoid including unrelated commits.\n\nAfter you have submitted your pull request, we'll try to get back to you as soon as possible. We may suggest some changes or improvements.\n\nThank you for contributing!\n"
  },
  {
    "path": "LICENSE",
    "content": "MIT License\n\nCopyright (c) 2018 Mark Erikson\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": "_artifacts/domain_map.yaml",
    "content": "# domain_map.yaml\n# Generated by skill-domain-discovery\n# Library: Redux Toolkit\n# Version: workspace snapshot (toolkit 2.11.2)\n# Date: 2026-03-14\n# Status: reviewed\n\nlibrary:\n  name: '@reduxjs/toolkit'\n  version: 'workspace snapshot (toolkit 2.11.2)'\n  repository: 'https://github.com/reduxjs/redux-toolkit'\n  description: 'Monorepo for Redux Toolkit, RTK Query, and companion codegen and codemod packages.'\n  primary_framework: 'framework-agnostic'\n\nstatus: 'reviewed'\n\ndomains:\n  - name: 'Build Modern Redux Apps'\n    slug: 'build-modern-redux-apps'\n    description: 'Getting a React plus Redux Toolkit app wired correctly and understanding the action-to-state-to-UI loop.'\n  - name: 'Model Redux State'\n    slug: 'model-redux-state'\n    description: 'Deciding what belongs in Redux and shaping slice state so updates and selectors stay maintainable.'\n  - name: 'Orchestrate Side Effects'\n    slug: 'orchestrate-side-effects'\n    description: 'Choosing and implementing the right async or reactive mechanism outside reducers.'\n  - name: 'Manage Server Data'\n    slug: 'manage-server-data'\n    description: 'Fetching, caching, invalidating, and generating server-state integrations with RTK Query.'\n  - name: 'Evolve And Diagnose Redux Apps'\n    slug: 'evolve-and-diagnose-redux-apps'\n    description: 'Migrating legacy code forward and tracing bugs back to state flow, configuration, or cache behavior.'\n\nskills:\n  - name: 'Modern Redux'\n    slug: 'modern-redux'\n    domain: 'build-modern-redux-apps'\n    description: 'Set up the standard RTK plus React-Redux architecture for a new or newly-modernized app, including the right store lifetime for SPA and SSR-heavy environments.'\n    type: 'lifecycle'\n    packages:\n      - '@reduxjs/toolkit'\n    covers:\n      - 'configureStore'\n      - 'Provider'\n      - 'hooks-first React-Redux usage'\n      - 'useSelector and useDispatch'\n      - 'typed hooks'\n      - 'feature-folder structure'\n      - 'framework-specific store lifetime'\n      - 'Redux DevTools'\n    tasks:\n      - 'Create the store and root reducer setup for a React app'\n      - 'Wire Provider and typed hooks into the UI'\n      - 'Choose the correct store lifetime for an SPA singleton or an SSR-heavy app'\n      - 'Establish the default app and features folder structure'\n    failure_modes:\n      - mistake: 'Importing the store directly into React UI components'\n        mechanism: 'In React apps, direct store imports bypass the Provider and hook boundary, create hidden coupling, and make tests and refactors brittle. Some non-React integrations can read a store directly, but React components should normally go through hooks and context.'\n        wrong_pattern: |\n          import { store } from '@/app/store'\n\n          export function PostsList() {\n            const posts = store.getState().posts\n            return <div>{posts.length}</div>\n          }\n        correct_pattern: |\n          export function PostsList() {\n            const posts = useAppSelector((state) => state.posts)\n            return <div>{posts.length}</div>\n          }\n        source: 'docs/tutorials/essentials/part-3-data-flow.md; /home/weber/tmp/redux/docs/style-guide/style-guide.md; maintainer interview'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current React guidance; some non-React framework code may read a store directly, but agents should not default to that in React UI code.'\n      - mistake: 'Defaulting to connect() for new React code'\n        mechanism: 'Legacy connect wrappers still exist, but hooks are the modern default and are simpler to type, simpler to read, and the maintainer explicitly does not want agents generating connect-based code for new usage.'\n        wrong_pattern: |\n          const mapState = (state) => ({ posts: selectPosts(state) })\n          const mapDispatch = { postAdded }\n\n          function PostsList({ posts, postAdded }) {\n            return <button onClick={() => postAdded()}>Add</button>\n          }\n\n          export default connect(mapState, mapDispatch)(PostsList)\n        correct_pattern: |\n          export function PostsList() {\n            const posts = useAppSelector(selectPosts)\n            const dispatch = useAppDispatch()\n            return <button onClick={() => dispatch(postAdded())}>Add</button>\n          }\n        source: 'docs/usage/migrating-to-modern-redux.mdx; /home/weber/tmp/redux/docs/style-guide/style-guide.md; maintainer interview'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current maintainer guidance; connect may remain in legacy code, but agents should steer new React code toward hooks.'\n      - mistake: 'Recreating the store during render in SSR-heavy React frameworks'\n        mechanism: 'In SSR-heavy React frameworks, a module-level singleton can leak state across requests, but creating the store on every render loses client state. The store needs to be request-scoped and also stable across renders inside the client provider component.'\n        wrong_pattern: |\n          'use client'\n          export function StoreProvider({ children }) {\n            const store = makeStore()\n            return <Provider store={store}>{children}</Provider>\n          }\n        correct_pattern: |\n          'use client'\n          export function StoreProvider({ children }) {\n            const [store] = useState(makeStore)\n            return <Provider store={store}>{children}</Provider>\n          }\n        source: 'docs/usage/nextjs.mdx; maintainer interview'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance for SSR-heavy React frameworks; classic client-only SPAs can still use a module-level singleton store.'\n      - mistake: 'Keeping manual createStore boilerplate as the default'\n        mechanism: 'Legacy store setup works, but it silently drops RTK safety middleware and the modern default configuration unless each piece is rebuilt by hand.'\n        wrong_pattern: |\n          import { createStore, applyMiddleware, combineReducers } from 'redux'\n          import thunk from 'redux-thunk'\n\n          export const store = createStore(\n            combineReducers({ users: usersReducer }),\n            applyMiddleware(thunk),\n          )\n        correct_pattern: |\n          import { configureStore } from '@reduxjs/toolkit'\n\n          export const store = configureStore({\n            reducer: { users: usersReducer },\n          })\n        source: 'docs/usage/migrating-to-modern-redux.mdx; /home/weber/tmp/redux/docs/style-guide/style-guide.md'\n        priority: 'HIGH'\n        status: 'fixed-but-legacy-risk'\n        version_context: 'Still technically valid Redux, but it is no longer the recommended baseline and agents trained on pre-RTK material still generate it.'\n    compositions:\n      - library: 'react-redux'\n        skill: 'modern-redux'\n\n  - name: 'Redux Dataflow'\n    slug: 'redux-dataflow'\n    domain: 'build-modern-redux-apps'\n    description: 'Explain and apply the Redux action, reducer, selector, and render data flow so architectural choices and debugging stay predictable.'\n    type: 'core'\n    packages:\n      - '@reduxjs/toolkit'\n    covers:\n      - 'single store'\n      - 'actions'\n      - 'reducers'\n      - 'selectors'\n      - 'state machines'\n      - 'event-style actions'\n      - 'reducer-owned state transitions'\n    tasks:\n      - 'Explain how data moves from UI events to reducers and back to the UI'\n      - 'Choose whether new data should be derived or stored'\n      - 'Decide whether a transition belongs in a reducer or at an authoritative external source boundary'\n      - 'Model reducer transitions so invalid states are impossible'\n    failure_modes:\n      - mistake: 'Mutating selected state outside reducers'\n        mechanism: 'Changing objects read from the store breaks immutability assumptions and leads to stale UI or DevTools history that no longer matches reality.'\n        wrong_pattern: |\n          const post = useAppSelector((state) => state.posts.entities[id])\n          post.title = title\n          dispatch(postSaved(post))\n        correct_pattern: |\n          dispatch(postUpdated({ id, title }))\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md; docs/usage/immer-reducers.md'\n        priority: 'CRITICAL'\n        status: 'active'\n        version_context: 'Current invariant; this remains the most common Redux bug pattern.'\n      - mistake: 'Using setter-style actions instead of event-style actions'\n        mechanism: 'Setter actions like setPosts hide what actually happened in the UI and encourage callers to calculate the next state themselves. Redux actions should describe events, and reducers should translate those events into state changes.'\n        wrong_pattern: |\n          const nextPosts = [...posts, newPost]\n          dispatch(setPosts(nextPosts))\n        correct_pattern: |\n          dispatch(postAdded(newPost))\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md; maintainer interview'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance; event-style actions make Redux timelines and reducer logic easier to understand and debug.'\n      - mistake: 'Combining store state with new external data before dispatch'\n        mechanism: 'If the next state depends on both existing store data and new outside input, the reducer should own that combination logic. Full replacement is fine when the payload is an authoritative external snapshot, but mixed transitions belong in reducers.'\n        wrong_pattern: |\n          const currentPosts = selectPosts(store.getState())\n          const mergedPosts = mergeById(currentPosts, incomingPosts)\n          dispatch(postsReplaced(mergedPosts))\n        correct_pattern: |\n          dispatch(postsReceived(incomingPosts))\n\n          postsReceived(state, action) {\n            postsAdapter.upsertMany(state, action.payload)\n          }\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md; maintainer interview'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance; reducers should own transitions that mix old store state with new outside data.'\n        skills:\n          - 'redux-dataflow'\n          - 'build-slices-and-selectors'\n      - mistake: 'Ignoring current state when reducing async actions'\n        mechanism: 'Reducers that only inspect action.type allow impossible transitions like success after success or stale requests overwriting newer state.'\n        wrong_pattern: |\n          builder.addCase(fetchPosts.fulfilled, (state, action) => {\n            state.status = 'succeeded'\n            state.posts = action.payload\n          })\n        correct_pattern: |\n          builder.addCase(fetchPosts.fulfilled, (state, action) => {\n            if (state.status === 'pending') {\n              state.status = 'succeeded'\n              state.posts = action.payload\n            }\n          })\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md; /home/weber/tmp/redux/docs/tutorials/essentials/part-5-async-logic.md'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance; reducers should behave like state machines when request lifecycle matters.'\n      - mistake: 'Storing derived values instead of deriving them'\n        mechanism: 'Keeping filtered lists or counts in state creates duplicate sources of truth that drift out of sync as features change.'\n        wrong_pattern: |\n          const initialState = {\n            posts: [],\n            visiblePosts: [],\n          }\n        correct_pattern: |\n          export const selectVisiblePosts = createSelector(\n            [selectAllPosts, selectFilter],\n            (posts, filter) => posts.filter((post) => matches(post, filter)),\n          )\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md'\n        priority: 'MEDIUM'\n        status: 'active'\n        version_context: 'Current guidance; agents often materialize derived state because it looks explicit.'\n\n  - name: 'Design State Ownership'\n    slug: 'design-state-ownership'\n    domain: 'model-redux-state'\n    description: 'Decide what belongs in Redux, what should stay local, and how state shape should be organized around data, authority boundaries, and evolving slice size.'\n    type: 'core'\n    packages:\n      - '@reduxjs/toolkit'\n    covers:\n      - 'local versus global state heuristics'\n      - 'state slice naming'\n      - 'feature-folder structure'\n      - 'reducers owning state shape'\n      - 'authoritative external sources'\n      - 'slice sizing and granularity'\n      - 'moving state from local components into Redux'\n    tasks:\n      - 'Decide whether new state should live in a component or Redux'\n      - 'Design slice boundaries and root state keys'\n      - 'Re-evaluate slice boundaries as access patterns evolve'\n      - 'Refactor local state into a shared slice when requirements change'\n    failure_modes:\n      - mistake: 'Putting ordinary form editing state in Redux'\n        mechanism: 'Per-keystroke form dispatches add overhead and global complexity for data that is usually only needed inside one component tree.'\n        wrong_pattern: |\n          const title = useAppSelector(selectDraftTitle)\n          <input\n            value={title}\n            onChange={(e) => dispatch(titleChanged(e.target.value))}\n          />\n        correct_pattern: |\n          const [title, setTitle] = useState('')\n          <input value={title} onChange={(e) => setTitle(e.target.value)} />\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md'\n        priority: 'MEDIUM'\n        status: 'active'\n        version_context: 'Current style-guide rule; exceptions exist, but the default should be local component state.'\n      - mistake: 'Synchronizing router or URL state into Redux'\n        mechanism: 'When another system already owns the state, copying it into Redux creates duplicate sources of truth. URL and router state should usually stay with the router and be combined with Redux state at the component boundary or passed as selector input.'\n        wrong_pattern: |\n          useEffect(() => {\n            dispatch(filterChanged(searchParams.get('filter') ?? 'all'))\n          }, [searchParams, dispatch])\n        correct_pattern: |\n          const filter = searchParams.get('filter') ?? 'all'\n          const posts = useAppSelector((state) =>\n            selectVisiblePosts(state, filter),\n          )\n        source: 'maintainer interview'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance; state with another authoritative source should rarely be synchronized into Redux.'\n      - mistake: 'Naming state after components instead of data'\n        mechanism: 'UI-shaped state like loginScreen or postsList bakes a view tree into the store and makes reuse, routing, and selector design brittle.'\n        wrong_pattern: |\n          const rootReducer = combineReducers({\n            loginScreen: loginReducer,\n            postsList: postsReducer,\n          })\n        correct_pattern: |\n          const rootReducer = combineReducers({\n            auth: authReducer,\n            posts: postsReducer,\n          })\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance; this usually appears when Redux is introduced from the component layer downward.'\n      - mistake: 'Letting slice boundaries fossilize as the app evolves'\n        mechanism: 'Slices that are too broad force unrelated data together, while slices that are too fragmented require constant stitching outside the reducer layer. Good slice boundaries should be revisited as access patterns change.'\n        source: 'maintainer interview'\n        priority: 'MEDIUM'\n        status: 'active'\n        version_context: 'Current guidance; if data is constantly stitched together outside Redux, it may belong closer together, and independent data may deserve a split.'\n      - mistake: 'Blindly spreading payloads into state'\n        mechanism: 'Reducers that return action payloads or spread them wholesale give up ownership of state shape and silently accept malformed data.'\n        wrong_pattern: |\n          userLoggedIn(state, action) {\n            return { ...state, ...action.payload }\n          }\n        correct_pattern: |\n          userLoggedIn(state, action) {\n            state.id = action.payload.id\n            state.name = action.payload.name\n          }\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance; static typing can reduce risk but does not change the architectural tradeoff.'\n\n  - name: 'Build Slices And Selectors'\n    slug: 'build-slices-and-selectors'\n    domain: 'model-redux-state'\n    description: 'Author slices, selectors, lazy-injected reducers, and normalized entity state with RTK-first patterns and explicit Immer guidance.'\n    type: 'core'\n    packages:\n      - '@reduxjs/toolkit'\n    covers:\n      - 'createSlice'\n      - 'reducers creator callback'\n      - 'create.asyncThunk'\n      - 'Immer-backed reducer logic'\n      - 'extraReducers'\n      - 'selectors field and getSelectors'\n      - 'injectInto and withLazyLoadedSlices'\n      - 'prepare callbacks'\n      - 'createSelector'\n      - 'createEntityAdapter'\n    tasks:\n      - 'Create or refactor a feature slice with actions, selectors, and optional slice-local async thunks'\n      - 'Use Immer-backed reducers without mutating real state or falling back to hand-written reducers'\n      - 'Normalize entity collections and expose stable selectors'\n      - 'Prepare slices for lazy injection with injectInto and withLazyLoadedSlices'\n    reference_candidates:\n      - topic: 'slice reducer patterns and selector shapes'\n        reason: 'This topic spans createSlice reducer forms, selectors defined in the slice, create.asyncThunk, injectInto and withLazyLoadedSlices, entity adapters, and selector export patterns.'\n    failure_modes:\n      - mistake: 'Using mutating update logic outside Immer reducers'\n        mechanism: 'Mutating syntax is only safe inside createSlice or createReducer; the same code in helpers or components mutates real objects.'\n        wrong_pattern: |\n          export function addTodo(todos, todo) {\n            todos.push(todo)\n            return todos\n          }\n        correct_pattern: |\n          const todosSlice = createSlice({\n            name: 'todos',\n            initialState: [] as Todo[],\n            reducers: {\n              todoAdded(state, action) {\n                state.push(action.payload)\n              },\n            },\n          })\n        source: 'docs/usage/immer-reducers.md; docs/api/createSlice.mdx'\n        priority: 'CRITICAL'\n        status: 'active'\n        version_context: 'Current invariant; Immer makes the reducer case safe, not the syntax universally safe. Agents also often miss that mutation syntax is encouraged inside slice reducers.'\n      - mistake: 'Writing hand-written switch reducers as the default'\n        mechanism: 'Agents trained on legacy Redux still emit action constants plus switch reducers. That throws away co-located actions, selectors, and Immer-based updates even though modern RTK expects createSlice to be the normal baseline. Falling back to hand-written reducers should only happen after a measured Immer bottleneck.'\n        wrong_pattern: |\n          export default function todosReducer(state = initialState, action) {\n            switch (action.type) {\n              case 'todos/todoAdded':\n                return state.concat(action.payload)\n              default:\n                return state\n            }\n          }\n        correct_pattern: |\n          const todosSlice = createSlice({\n            name: 'todos',\n            initialState,\n            reducers: {\n              todoAdded(state, action) {\n                state.push(action.payload)\n              },\n            },\n          })\n        source: 'docs/usage/migrating-to-modern-redux.mdx; /home/weber/tmp/redux/docs/style-guide/style-guide.md; maintainer interview'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current maintainer guidance; hand-written reducers are an exceptional escape hatch, not the default code agents should write.'\n      - mistake: 'Writing RTK 1.x object syntax for extraReducers'\n        mechanism: 'RTK 2 removed the object form for createReducer and createSlice.extraReducers, so older examples now generate broken upgrades.'\n        wrong_pattern: |\n          extraReducers: {\n            [fetchPosts.fulfilled]: (state, action) => {\n              state.items = action.payload\n            },\n          }\n        correct_pattern: |\n          extraReducers: (builder) => {\n            builder.addCase(fetchPosts.fulfilled, (state, action) => {\n              state.items = action.payload\n            })\n          }\n        source: 'docs/usage/migrating-rtk-2.md; packages/toolkit/src/createSlice.ts'\n        priority: 'HIGH'\n        status: 'fixed-but-legacy-risk'\n        version_context: 'Removed in RTK 2.0; agents trained on RTK 1.x code still emit the object form.'\n      - mistake: 'Relying on entity.id when the real key is elsewhere'\n        mechanism: 'createEntityAdapter defaults to entity.id, so collections with bookId or slug keys silently create broken selectors and updates unless selectId is provided.'\n        wrong_pattern: |\n          interface Book { bookId: string; title: string }\n          const booksAdapter = createEntityAdapter<Book>()\n        correct_pattern: |\n          interface Book { bookId: string; title: string }\n          const booksAdapter = createEntityAdapter({\n            selectId: (book: Book) => book.bookId,\n          })\n        source: 'docs/api/createEntityAdapter.mdx'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current behavior; only id-based entities can omit selectId.'\n\n  - name: 'Handle Side Effects'\n    slug: 'handle-side-effects'\n    domain: 'orchestrate-side-effects'\n    description: 'Choose between RTK Query, thunks, and listener middleware, then implement side-effectful workflows without leaking logic into reducers or components.'\n    type: 'core'\n    packages:\n      - '@reduxjs/toolkit'\n    covers:\n      - 'decision boundary with RTK Query'\n      - 'createAsyncThunk'\n      - 'handwritten thunks'\n      - 'createListenerMiddleware'\n      - 'listener workflow helpers'\n      - 'middleware ordering'\n    tasks:\n      - 'Choose the right mechanism for server cache, imperative async logic, and reactive workflows'\n      - 'Write imperative async logic that needs dispatch and getState'\n      - 'Respond to actions or state changes with reactive workflows'\n      - 'Move non-UI logic out of components and reducers'\n    reference_candidates:\n      - topic: 'listener middleware workflow helpers'\n        reason: 'take, condition, pause, fork, cancel, and matcher options form a dense API surface that is easy to misuse without examples.'\n    failure_modes:\n      - mistake: 'Running side effects inside reducers'\n        mechanism: 'Reducers must stay pure; async calls, timestamps, random IDs, and other effects break time travel, replay, and predictability.'\n        wrong_pattern: |\n          todoSaved(state, action) {\n            fetch('/api/todos', { method: 'POST' })\n            state.items.push(action.payload)\n          }\n        correct_pattern: |\n          export const saveTodo = createAsyncThunk('todos/save', async (todo) => {\n            await client.post('/api/todos', todo)\n            return todo\n          })\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md; docs/api/createAsyncThunk.mdx'\n        priority: 'CRITICAL'\n        status: 'active'\n        version_context: 'Current invariant; reducers are pure even when using Immer.'\n      - mistake: 'Using thunks to watch future state changes'\n        mechanism: 'Polling or looping inside thunks to react to later actions fights the architecture; listeners are meant for reactive long-lived workflows.'\n        wrong_pattern: |\n          export const waitForSave = () => async (_dispatch, getState) => {\n            while (getState().docs.status !== 'saved') {\n              await delay(100)\n            }\n          }\n        correct_pattern: |\n          startAppListening({\n            predicate: (_action, currentState) => currentState.docs.status === 'saved',\n            effect: async () => {\n              await notifySaved()\n            },\n          })\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md; docs/api/createListenerMiddleware.mdx'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance; listeners are the preferred tool for reactive action/state driven workflows.'\n      - mistake: 'Appending listener middleware after the default checks'\n        mechanism: 'Listener add and remove actions may contain functions, so adding the middleware after serializability checks causes avoidable warnings or failures.'\n        wrong_pattern: |\n          middleware: (getDefaultMiddleware) =>\n            getDefaultMiddleware().concat(listenerMiddleware.middleware)\n        correct_pattern: |\n          middleware: (getDefaultMiddleware) =>\n            getDefaultMiddleware().prepend(listenerMiddleware.middleware)\n        source: 'docs/api/createListenerMiddleware.mdx'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance; ordering matters because listener actions can carry functions.'\n\n  - name: 'Adopt RTK Query'\n    slug: 'adopt-rtk-query'\n    domain: 'manage-server-data'\n    description: 'Introduce RTK Query as the default data-fetching and document-caching layer, from API slice setup through cache updates and React usage.'\n    type: 'lifecycle'\n    packages:\n      - '@reduxjs/toolkit'\n    covers:\n      - 'createApi'\n      - 'fetchBaseQuery'\n      - 'document cache tradeoffs'\n      - 'query and mutation endpoints'\n      - 'tags and invalidation'\n      - 'onQueryStarted'\n      - 'onCacheEntryAdded'\n      - 'injectEndpoints'\n      - 'selectFromResult'\n    tasks:\n      - 'Define an API slice and add it to the store'\n      - 'Recognize when server data should move to RTK Query and when normalized caching needs a different tool'\n      - 'Replace handwritten server-cache logic with RTK Query endpoints and hooks'\n      - 'Handle optimistic updates, streaming updates, and cache invalidation'\n    reference_candidates:\n      - topic: 'endpoint lifecycle and cache control options'\n        reason: 'RTK Query combines endpoint builders, cache timing, invalidation, rehydration, hook options, and lifecycle APIs in one dense configuration surface.'\n    failure_modes:\n      - mistake: 'Creating many API slices for one backend'\n        mechanism: 'Multiple createApi calls per base URL break automatic invalidation across endpoints and add middleware overhead, while shared reducerPath values can conflict at runtime.'\n        wrong_pattern: |\n          export const postsApi = createApi({ reducerPath: 'api', baseQuery, endpoints: () => ({}) })\n          export const usersApi = createApi({ reducerPath: 'api', baseQuery, endpoints: () => ({}) })\n        correct_pattern: |\n          export const api = createApi({\n            reducerPath: 'api',\n            baseQuery,\n            endpoints: () => ({}),\n          })\n\n          export const apiWithUsers = api.injectEndpoints({ endpoints: (build) => ({}) })\n        source: 'docs/rtk-query/api/createApi.mdx; packages/toolkit/src/query/core/buildMiddleware/devMiddleware.ts'\n        priority: 'CRITICAL'\n        status: 'active'\n        version_context: 'Current guidance; one API slice per base URL is the default architecture.'\n        skills:\n          - 'adopt-rtk-query'\n          - 'debug-redux-toolkit-apps'\n      - mistake: 'Forgetting to add api.reducer and api.middleware to the store'\n        mechanism: 'RTK Query hooks depend on both the reducer and middleware; omitting either leads to missing cache state or request orchestration that fails at runtime.'\n        wrong_pattern: |\n          export const store = configureStore({\n            reducer: { users: usersReducer },\n          })\n        correct_pattern: |\n          export const store = configureStore({\n            reducer: {\n              users: usersReducer,\n              [api.reducerPath]: api.reducer,\n            },\n            middleware: (getDefaultMiddleware) =>\n              getDefaultMiddleware().concat(api.middleware),\n          })\n        source: 'docs/tutorials/rtk-query.mdx; packages/toolkit/src/query/core/module.ts'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current requirement; missing store integration is one of the first RTK Query setup failures.'\n      - mistake: 'Persisting browser API cache as a default optimization'\n        mechanism: 'Persisted RTK Query cache can leave users with very stale data in browsers, so persistence is a special-case escape hatch rather than the default strategy.'\n        wrong_pattern: |\n          const persistConfig = {\n            key: 'root',\n            storage,\n          }\n        correct_pattern: |\n          // Prefer normal browser cache behavior for web apps.\n          // Only add RTK Query rehydration in environments that truly need it.\n          const api = createApi({\n            baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n            endpoints: () => ({}),\n          })\n        source: 'docs/rtk-query/usage/persistence-and-rehydration.mdx'\n        priority: 'MEDIUM'\n        status: 'active'\n        version_context: 'Current guidance; persistence is viable for native-style environments, not the default browser path.'\n      - mistake: 'Manually patching cache from arbitrary component code'\n        mechanism: 'Ad-hoc cache updates drift away from request lifecycles; RTK Query expects optimistic and pessimistic updates to be coordinated inside endpoint lifecycle handlers.'\n        wrong_pattern: |\n          useEffect(() => {\n            dispatch(api.util.updateQueryData('getPosts', undefined, patchPosts))\n          }, [dispatch])\n        correct_pattern: |\n          addReaction: build.mutation<Post, Args>({\n            query: ({ postId, reaction }) => ({ url: `posts/${postId}/reactions`, method: 'POST' }),\n            async onQueryStarted({ postId, reaction }, { dispatch, queryFulfilled }) {\n              const patch = dispatch(\n                api.util.updateQueryData('getPosts', undefined, (draft) => {\n                  const post = draft.find((item) => item.id === postId)\n                  if (post) post.reactions[reaction]++\n                }),\n              )\n              try {\n                await queryFulfilled\n              } catch {\n                patch.undo()\n              }\n            },\n          })\n        source: 'docs/rtk-query/usage/manual-cache-updates.mdx; /home/weber/tmp/redux/docs/tutorials/essentials/part-8-rtk-query-advanced.md'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance; lifecycle-bound cache changes scale better than component-scoped patches.'\n      - mistake: 'Expecting invalidation to refetch unsubscribed queries'\n        mechanism: 'Invalidation only refetches cache entries that are actively subscribed. Invalidated queries with no current subscribers are removed and will refetch when they are used again, instead of refetching data that may never be displayed.'\n        source: 'docs/rtk-query/usage/automated-refetching.mdx; maintainer interview'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current behavior; invalidation is not a global background refresh for every cached query.'\n    compositions:\n      - library: 'react-redux'\n        skill: 'modern-redux'\n      - library: 'redux-persist'\n        skill: 'adopt-rtk-query'\n\n  - name: 'Generate RTK Query From OpenAPI'\n    slug: 'generate-rtk-query-from-openapi'\n    domain: 'manage-server-data'\n    description: 'Generate RTK Query endpoints from an OpenAPI schema and integrate the output back into a single RTK Query architecture.'\n    type: 'composition'\n    packages:\n      - '@reduxjs/toolkit'\n      - '@rtk-query/codegen-openapi'\n    covers:\n      - '@rtk-query/codegen-openapi'\n      - 'empty API pattern'\n      - 'injectEndpoints'\n      - 'endpointOverrides'\n      - 'filterEndpoints'\n      - 'generated hooks'\n      - 'tag generation'\n    tasks:\n      - 'Create a codegen config for an OpenAPI schema'\n      - 'Generate RTK Query endpoints into an existing API service'\n      - 'Correct generated endpoint types, parameters, or tags when the schema is imperfect'\n    reference_candidates:\n      - topic: 'codegen config and endpoint override options'\n        reason: 'Schema file inputs, output layouts, tag generation, hooks, endpoint filtering, and override matchers all change the generated surface.'\n    failure_modes:\n      - mistake: 'Assuming auto-generated tags are granular enough'\n        mechanism: 'The tag option only generates string tags without ids, so invalidation can become overly broad unless endpoints are enhanced or overridden.'\n        wrong_pattern: |\n          const config = {\n            schemaFile: './openapi.json',\n            tag: true,\n          }\n        correct_pattern: |\n          const config = {\n            schemaFile: './openapi.json',\n            tag: true,\n            endpointOverrides: [\n              { pattern: 'getPetById', providesTags: ['SinglePet'] },\n            ],\n          }\n        source: 'docs/rtk-query/usage/code-generation.mdx'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current behavior; tag generation is intentionally coarse unless you refine it.'\n      - mistake: 'Generating a brand-new API slice instead of extending an empty one'\n        mechanism: 'Codegen works best when it injects endpoints into a shared API service; standalone generated APIs make later composition and code splitting harder.'\n        wrong_pattern: |\n          export const petApi = createApi({\n            baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n            endpoints: (build) => ({ /* generated endpoints */ }),\n          })\n        correct_pattern: |\n          export const emptySplitApi = createApi({\n            baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n            endpoints: () => ({}),\n          })\n        source: 'docs/rtk-query/usage/code-generation.mdx'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance; the documented flow starts from an empty shared API.'\n      - mistake: 'Trusting generated query and mutation shapes without overrides'\n        mechanism: 'Real schemas are messy; if an operation is classified incorrectly or exposes the wrong parameters, codegen needs endpointOverrides rather than hand edits after the fact.'\n        wrong_pattern: |\n          const config = {\n            schemaFile: './openapi.json',\n            outputFile: './petApi.ts',\n          }\n        correct_pattern: |\n          const config = {\n            schemaFile: './openapi.json',\n            outputFile: './petApi.ts',\n            endpointOverrides: [\n              { pattern: 'loginUser', type: 'mutation' },\n            ],\n          }\n        source: 'docs/rtk-query/usage/code-generation.mdx'\n        priority: 'MEDIUM'\n        status: 'active'\n        version_context: 'Current guidance; endpointOverrides exist because many schemas do not map cleanly to ideal endpoint shapes.'\n    compositions:\n      - library: 'OpenAPI'\n        skill: 'generate-rtk-query-from-openapi'\n\n  - name: 'Migrate To Modern Redux'\n    slug: 'migrate-to-modern-redux'\n    domain: 'evolve-and-diagnose-redux-apps'\n    description: 'Move legacy Redux and React-Redux code toward current RTK-first patterns without freezing delivery.'\n    type: 'lifecycle'\n    packages:\n      - '@reduxjs/toolkit'\n      - '@reduxjs/rtk-codemods'\n    covers:\n      - 'configureStore migration'\n      - 'createSlice migration'\n      - 'hooks migration'\n      - 'RTK 2 migration'\n      - 'codemods'\n    tasks:\n      - 'Replace a legacy createStore setup with configureStore'\n      - 'Convert one reducer or screen at a time to createSlice and hooks'\n      - 'Apply codemods and RTK 2 migration fixes safely'\n    failure_modes:\n      - mistake: 'Attempting a big-bang rewrite of the whole app'\n        mechanism: 'Modern Redux migration is designed to be incremental; rewriting every slice and component at once increases risk and removes a safe rollback path. Once the store is migrated, though, new work should stop introducing legacy patterns.'\n        wrong_pattern: |\n          // Replace every reducer, action creator, and connected component\n          // in one branch before shipping anything.\n        correct_pattern: |\n          // 1) Switch createStore to configureStore\n          // 2) When touching a legacy reducer, migrate it to createSlice\n          // 3) Convert connected components to hooks as you touch them\n          // 4) Repeat incrementally, but do not add new legacy Redux code\n        source: 'docs/usage/migrating-to-modern-redux.mdx; maintainer interview'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current migration guidance; legacy and modern Redux code are expected to coexist temporarily.'\n      - mistake: 'Carrying removed RTK 2 configuration forms forward'\n        mechanism: 'RTK 2 requires callback forms for middleware and enhancers, and removed object notation for extraReducers and createReducer.'\n        wrong_pattern: |\n          configureStore({\n            reducer,\n            middleware: [logger],\n          })\n        correct_pattern: |\n          configureStore({\n            reducer,\n            middleware: (getDefaultMiddleware) =>\n              getDefaultMiddleware().concat(logger),\n          })\n        source: 'docs/usage/migrating-rtk-2.md; packages/toolkit/src/configureStore.ts'\n        priority: 'CRITICAL'\n        status: 'fixed-but-legacy-risk'\n        version_context: 'Removed in RTK 2.0; agents trained on RTK 1.x setup code still emit array middleware and object reducers.'\n      - mistake: 'Preserving hand-written fetch lifecycle state by default'\n        mechanism: 'Migration often keeps old loading booleans, thunks, and reducers even when the feature is really server cache and RTK Query can replace the whole stack.'\n        wrong_pattern: |\n          const initialState = { items: [], status: 'idle', error: null }\n          export const fetchTodos = createAsyncThunk('todos/fetch', async () => client.get('/todos'))\n        correct_pattern: |\n          export const api = createApi({\n            baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n            endpoints: (build) => ({\n              getTodos: build.query<Todo[], void>({ query: () => '/todos' }),\n            }),\n          })\n        source: 'docs/usage/migrating-to-modern-redux.mdx; /home/weber/tmp/redux/docs/style-guide/style-guide.md; maintainer interview'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current guidance; RTK Query is the default for server-cache use cases, while createAsyncThunk remains valid for non-cache workflows.'\n        skills:\n          - 'migrate-to-modern-redux'\n          - 'adopt-rtk-query'\n          - 'handle-side-effects'\n    compositions:\n      - library: 'react-redux'\n        skill: 'modern-redux'\n\n  - name: 'Debug Redux Toolkit Apps'\n    slug: 'debug-redux-toolkit-apps'\n    domain: 'evolve-and-diagnose-redux-apps'\n    description: 'Trace incorrect state, duplicate requests, cache bugs, and render churn back to the underlying RTK or RTK Query mechanism.'\n    type: 'lifecycle'\n    packages:\n      - '@reduxjs/toolkit'\n    covers:\n      - 'Redux DevTools'\n      - 'serializability and immutability checks'\n      - 'React StrictMode request duplication'\n      - 'React-Redux subscription granularity'\n      - 'RTK Query reducerPath conflicts'\n      - 'selector and hook stability'\n    tasks:\n      - 'Investigate duplicate network requests or repeated cache writes'\n      - 'Interpret serializable and immutable-state warnings'\n      - 'Reduce unnecessary rerenders from selectors or query hooks'\n    failure_modes:\n      - mistake: 'Dispatching fetch thunks from effects without a thunk-level guard'\n        mechanism: 'React StrictMode can run mount effects twice in development, so component checks alone may still dispatch duplicate requests before render catches up.'\n        wrong_pattern: |\n          useEffect(() => {\n            if (postStatus === 'idle') {\n              dispatch(fetchPosts())\n            }\n          }, [postStatus, dispatch])\n        correct_pattern: |\n          export const fetchPosts = createAsyncThunk(\n            'posts/fetchPosts',\n            async () => client.get('/posts'),\n            {\n              condition(_arg, { getState }) {\n                return selectPostsStatus(getState()) === 'idle'\n              },\n            },\n          )\n        source: '/home/weber/tmp/redux/docs/tutorials/essentials/part-5-async-logic.md'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current React development behavior; the bug often disappears in production, which makes it harder to diagnose.'\n        skills:\n          - 'debug-redux-toolkit-apps'\n          - 'handle-side-effects'\n      - mistake: 'Ignoring serializable-state warnings as harmless noise'\n        mechanism: 'Non-serializable values can appear to work, but they break DevTools, persistence, replay, and equality assumptions in subtle ways.'\n        wrong_pattern: |\n          const initialState = {\n            lastSeen: new Date(),\n            pending: new Set(),\n          }\n        correct_pattern: |\n          const initialState = {\n            lastSeenIso: new Date().toISOString(),\n            pendingIds: [] as string[],\n          }\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md; docs/usage/usage-guide.md'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current invariant; exceptions only apply when middleware intercepts values before reducers.'\n      - mistake: 'Selecting broad slice state in parents and threading it through props'\n        mechanism: 'Selecting whole slices or pulling lots of state into a parent component widens the subscription surface and forces rerenders through prop chains. React-Redux works better when components select only the values they use, as close to usage as possible.'\n        wrong_pattern: |\n          function PostsPage() {\n            const postsState = useAppSelector((state) => state.posts)\n            return <PostsList items={postsState.items} status={postsState.status} />\n          }\n        correct_pattern: |\n          function PostsList() {\n            const items = useAppSelector(selectPosts)\n            const status = useAppSelector(selectPostsStatus)\n            return <PostsView items={items} status={status} />\n          }\n        source: '/home/weber/tmp/redux/docs/style-guide/style-guide.md; maintainer interview'\n        priority: 'HIGH'\n        status: 'active'\n        version_context: 'Current React-Redux guidance; subscribe narrowly and where data is actually used.'\n      - mistake: 'Returning unstable objects from query selection logic'\n        mechanism: 'RTK Query and useSelector rely on stable references; recreating arrays or objects in selectFromResult defeats memoization and forces rerenders.'\n        wrong_pattern: |\n          const result = api.useGetPostsQuery(undefined, {\n            selectFromResult: ({ data = [] }) => ({\n              posts: [...data],\n            }),\n          })\n        correct_pattern: |\n          const result = api.useGetPostsQuery(undefined, {\n            selectFromResult: ({ data = [] }) => ({\n              posts: data,\n            }),\n          })\n        source: '/home/weber/tmp/redux/docs/tutorials/essentials/part-8-rtk-query-advanced.md; /home/weber/tmp/redux/docs/style-guide/style-guide.md'\n        priority: 'MEDIUM'\n        status: 'active'\n        version_context: 'Current behavior; hook result selection stays efficient only when returned references remain stable.'\n\ntensions:\n  - name: 'Local simplicity vs global observability'\n    skills:\n      - 'modern-redux'\n      - 'design-state-ownership'\n    description: 'Moving state into Redux improves sharing, tooling, and event history, but over-globalizing UI-local state adds needless indirection and render churn.'\n    implication: 'Agents that optimize only for Redux consistency tend to pull transient UI state into slices when local state would be simpler and safer.'\n  - name: 'Normalized slice ownership vs document-cache convenience'\n    skills:\n      - 'build-slices-and-selectors'\n      - 'adopt-rtk-query'\n    description: 'Entity adapters encourage normalized client state, while RTK Query deliberately keeps document-style cache entries unless you transform them yourself.'\n    implication: 'Agents often duplicate server data into Redux slices or try to force RTK Query into a fully normalized cache model without a real need.'\n  - name: 'Imperative clarity vs reactive orchestration'\n    skills:\n      - 'handle-side-effects'\n      - 'redux-dataflow'\n    description: 'Thunks are straightforward for one-off workflows, but listeners fit better when logic must react to future actions or state transitions over time.'\n    implication: 'Agents that only know thunks end up writing polling loops or effect-heavy components instead of event-driven listener workflows.'\n  - name: 'Single API slice performance vs file-level modularity'\n    skills:\n      - 'adopt-rtk-query'\n      - 'generate-rtk-query-from-openapi'\n    description: 'RTK Query wants one API slice per base URL for invalidation and middleware performance, while large codebases want generated or split endpoint code in many files.'\n    implication: 'Agents often create multiple createApi roots for organization, then lose invalidation behavior and introduce reducerPath conflicts.'\n\ncross_references:\n  - from: 'modern-redux'\n    to: 'redux-dataflow'\n    reason: 'Store setup decisions make more sense when the action, reducer, selector, and render loop is explicit.'\n  - from: 'design-state-ownership'\n    to: 'build-slices-and-selectors'\n    reason: 'State shape decisions directly determine how slices, entity adapters, and selectors should be authored.'\n  - from: 'build-slices-and-selectors'\n    to: 'handle-side-effects'\n    reason: 'extraReducers, async thunk actions, and listener-triggered updates meet at slice boundaries.'\n  - from: 'adopt-rtk-query'\n    to: 'generate-rtk-query-from-openapi'\n    reason: 'Generated endpoints still need to live inside a coherent RTK Query architecture with the right invalidation and code-splitting patterns.'\n  - from: 'migrate-to-modern-redux'\n    to: 'modern-redux'\n    reason: 'Migration guidance is only actionable when the target modern architecture is clear.'\n  - from: 'debug-redux-toolkit-apps'\n    to: 'redux-dataflow'\n    reason: 'Most debugging sessions resolve faster when the intended Redux data flow is explicit.'\n\ngaps: []\n"
  },
  {
    "path": "_artifacts/skill_spec.md",
    "content": "# Redux Toolkit - Skill Spec\n\nRedux Toolkit is the current recommended way to write Redux logic, and this monorepo also contains RTK Query plus companion codegen and codemod packages. The skill surface is driven less by isolated APIs than by developer moments: setting up modern Redux, deciding what belongs in the store, handling side effects, adopting RTK Query, migrating legacy patterns, and debugging subtle state-flow issues.\n\n## Domains\n\n| Domain | Description | Skills |\n| ------ | ----------- | ------ |\n| Build Modern Redux Apps | Getting a React plus Redux Toolkit app wired correctly and understanding the action-to-state-to-UI loop. | modern-redux, redux-dataflow |\n| Model Redux State | Deciding what belongs in Redux and shaping slice state so updates and selectors stay maintainable. | design-state-ownership, build-slices-and-selectors |\n| Orchestrate Side Effects | Choosing and implementing the right async or reactive mechanism outside reducers. | handle-side-effects |\n| Manage Server Data | Fetching, caching, invalidating, and generating server-state integrations with RTK Query. | adopt-rtk-query, generate-rtk-query-from-openapi |\n| Evolve And Diagnose Redux Apps | Migrating legacy code forward and tracing bugs back to state flow, configuration, or cache behavior. | migrate-to-modern-redux, debug-redux-toolkit-apps |\n\n## Skill Inventory\n\n| Skill | Type | Domain | What it covers | Failure modes |\n| ----- | ---- | ------ | -------------- | ------------- |\n| modern-redux | lifecycle | build-modern-redux-apps | configureStore, Provider, hooks-first React-Redux usage, typed hooks, SPA vs SSR-heavy store lifetime | 4 |\n| redux-dataflow | core | build-modern-redux-apps | actions, reducers, selectors, state machines, event-style actions, reducer-owned transitions | 5 |\n| design-state-ownership | core | model-redux-state | local vs global state, authority boundaries, slice sizing, root keys, reducer ownership | 5 |\n| build-slices-and-selectors | core | model-redux-state | createSlice, slice selectors, create.asyncThunk, lazy injection APIs, Immer, createEntityAdapter | 4 |\n| handle-side-effects | core | orchestrate-side-effects | RTK Query vs thunk vs listener boundaries, createAsyncThunk, createListenerMiddleware | 3 |\n| adopt-rtk-query | lifecycle | manage-server-data | createApi, fetchBaseQuery, document cache tradeoffs, invalidation, hooks, persistence caveats | 5 |\n| generate-rtk-query-from-openapi | composition | manage-server-data | empty API pattern, codegen config, endpointOverrides, generated hooks, tags | 3 |\n| migrate-to-modern-redux | lifecycle | evolve-and-diagnose-redux-apps | configureStore migration, createSlice rewrites, hooks migration, RTK 2 changes, codemods | 3 |\n| debug-redux-toolkit-apps | lifecycle | evolve-and-diagnose-redux-apps | DevTools, strict-mode duplication, subscription granularity, selector stability, reducerPath conflicts | 4 |\n\n## Failure Mode Inventory\n\n### modern-redux (4 failure modes)\n\n| # | Mistake | Priority | Source | Cross-skill? |\n| - | ------- | -------- | ------ | ------------ |\n| 1 | Importing the store directly into React UI components | HIGH | tutorials/essentials part 3; style guide; maintainer interview | - |\n| 2 | Defaulting to `connect()` for new React code | HIGH | migrating-to-modern-redux; style guide; maintainer interview | - |\n| 3 | Recreating the store during render in SSR-heavy React frameworks | HIGH | nextjs guide; maintainer interview | - |\n| 4 | Keeping manual `createStore` boilerplate as the default | HIGH | migrating-to-modern-redux; style guide | - |\n\n### redux-dataflow (5 failure modes)\n\n| # | Mistake | Priority | Source | Cross-skill? |\n| - | ------- | -------- | ------ | ------------ |\n| 1 | Mutating selected state outside reducers | CRITICAL | style guide; immer docs | - |\n| 2 | Using setter-style actions instead of event-style actions | HIGH | style guide; maintainer interview | - |\n| 3 | Combining store state with new external data before dispatch | HIGH | style guide; maintainer interview | build-slices-and-selectors |\n| 4 | Ignoring current state when reducing async actions | HIGH | style guide; essentials part 5 | - |\n| 5 | Storing derived values instead of deriving them | MEDIUM | style guide | - |\n\n### design-state-ownership (5 failure modes)\n\n| # | Mistake | Priority | Source | Cross-skill? |\n| - | ------- | -------- | ------ | ------------ |\n| 1 | Putting ordinary form editing state in Redux | MEDIUM | style guide | - |\n| 2 | Synchronizing router or URL state into Redux | HIGH | maintainer interview | - |\n| 3 | Naming state after components instead of data | HIGH | style guide | - |\n| 4 | Letting slice boundaries fossilize as the app evolves | MEDIUM | maintainer interview | - |\n| 5 | Blindly spreading payloads into state | HIGH | style guide | - |\n\n### build-slices-and-selectors (4 failure modes)\n\n| # | Mistake | Priority | Source | Cross-skill? |\n| - | ------- | -------- | ------ | ------------ |\n| 1 | Using mutating update logic outside Immer reducers | CRITICAL | createSlice docs; immer docs | - |\n| 2 | Writing hand-written switch reducers as the default | HIGH | migrating-to-modern-redux; style guide; maintainer interview | - |\n| 3 | Writing RTK 1.x object syntax for `extraReducers` | HIGH | migrating-rtk-2; createSlice source | - |\n| 4 | Relying on `entity.id` when the real key is elsewhere | HIGH | createEntityAdapter docs | - |\n\n### handle-side-effects (3 failure modes)\n\n| # | Mistake | Priority | Source | Cross-skill? |\n| - | ------- | -------- | ------ | ------------ |\n| 1 | Running side effects inside reducers | CRITICAL | style guide; createAsyncThunk docs | - |\n| 2 | Using thunks to watch future state changes | HIGH | style guide; listener middleware docs | - |\n| 3 | Appending listener middleware after the default checks | HIGH | createListenerMiddleware docs | - |\n\n### adopt-rtk-query (5 failure modes)\n\n| # | Mistake | Priority | Source | Cross-skill? |\n| - | ------- | -------- | ------ | ------------ |\n| 1 | Creating many API slices for one backend | CRITICAL | createApi docs; dev middleware source | debug-redux-toolkit-apps |\n| 2 | Forgetting to add api.reducer and api.middleware to the store | HIGH | RTK Query quick start; core module source | - |\n| 3 | Persisting browser API cache as a default optimization | MEDIUM | persistence-and-rehydration docs | - |\n| 4 | Manually patching cache from arbitrary component code | HIGH | manual-cache-updates docs; essentials part 8 | - |\n| 5 | Expecting invalidation to refetch unsubscribed queries | HIGH | automated-refetching docs; maintainer interview | - |\n\n### generate-rtk-query-from-openapi (3 failure modes)\n\n| # | Mistake | Priority | Source | Cross-skill? |\n| - | ------- | -------- | ------ | ------------ |\n| 1 | Assuming auto-generated tags are granular enough | HIGH | code-generation docs | - |\n| 2 | Generating a brand-new API slice instead of extending an empty one | HIGH | code-generation docs | - |\n| 3 | Trusting generated query and mutation shapes without overrides | MEDIUM | code-generation docs | - |\n\n### migrate-to-modern-redux (3 failure modes)\n\n| # | Mistake | Priority | Source | Cross-skill? |\n| - | ------- | -------- | ------ | ------------ |\n| 1 | Attempting a big-bang rewrite of the whole app | HIGH | migrating-to-modern-redux docs | - |\n| 2 | Carrying removed RTK 2 configuration forms forward | CRITICAL | migrating-rtk-2 docs; configureStore source | - |\n| 3 | Preserving hand-written fetch lifecycle state by default | HIGH | migrating-to-modern-redux docs; style guide; maintainer interview | adopt-rtk-query, handle-side-effects |\n\n### debug-redux-toolkit-apps (4 failure modes)\n\n| # | Mistake | Priority | Source | Cross-skill? |\n| - | ------- | -------- | ------ | ------------ |\n| 1 | Dispatching fetch thunks from effects without a thunk-level guard | HIGH | essentials part 5 | handle-side-effects |\n| 2 | Ignoring serializable-state warnings as harmless noise | HIGH | style guide; usage guide | - |\n| 3 | Selecting broad slice state in parents and threading it through props | HIGH | style guide; maintainer interview | - |\n| 4 | Returning unstable objects from query selection logic | MEDIUM | essentials part 8; style guide | - |\n\n## Tensions\n\n| Tension | Skills | Agent implication |\n| ------- | ------ | ----------------- |\n| Local simplicity vs global observability | modern-redux ↔ design-state-ownership | Agents over-globalize transient UI state when they optimize only for Redux consistency. |\n| Normalized slice ownership vs document-cache convenience | build-slices-and-selectors ↔ adopt-rtk-query | Agents duplicate server data or force RTK Query into a normalized-cache mental model unnecessarily. |\n| Imperative clarity vs reactive orchestration | handle-side-effects ↔ redux-dataflow | Agents overuse thunks for workflows that should react to future actions or state changes. |\n| Single API slice performance vs file-level modularity | adopt-rtk-query ↔ generate-rtk-query-from-openapi | Agents create multiple createApi roots for organization and lose invalidation and reducerPath safety. |\n\n## Cross-References\n\n| From | To | Reason |\n| ---- | -- | ------ |\n| modern-redux | redux-dataflow | Store setup decisions make more sense when the action, reducer, selector, and render loop is explicit. |\n| design-state-ownership | build-slices-and-selectors | State shape decisions directly determine how slices, entity adapters, and selectors should be authored. |\n| build-slices-and-selectors | handle-side-effects | extraReducers, async thunk actions, and listener-triggered updates meet at slice boundaries. |\n| adopt-rtk-query | generate-rtk-query-from-openapi | Generated endpoints still need a coherent RTK Query architecture. |\n| migrate-to-modern-redux | modern-redux | Migration advice depends on a clear target architecture. |\n| debug-redux-toolkit-apps | redux-dataflow | Many bugs become obvious once the intended Redux data flow is explicit. |\n\n## Subsystems & Reference Candidates\n\n| Skill | Subsystems | Reference candidates |\n| ----- | ---------- | -------------------- |\n| modern-redux | - | store lifetime and framework-specific setup |\n| redux-dataflow | - | reducer-owned state transitions |\n| design-state-ownership | - | authority boundaries and slice sizing |\n| build-slices-and-selectors | - | slice reducer patterns, selectors, and lazy injection |\n| handle-side-effects | - | listener middleware workflow helpers |\n| adopt-rtk-query | - | endpoint lifecycle and cache control options |\n| generate-rtk-query-from-openapi | - | codegen config and endpoint override options |\n| migrate-to-modern-redux | - | - |\n| debug-redux-toolkit-apps | - | - |\n\n## Remaining Gaps\n\nNone after the Phase 4 maintainer interview and repo/issue follow-up.\n\n## Recommended Skill File Structure\n\n- Core skills: redux-dataflow, design-state-ownership, build-slices-and-selectors, handle-side-effects\n- Framework skills: none inside this repo; modern-redux composes with react-redux externally\n- Lifecycle skills: modern-redux, adopt-rtk-query, migrate-to-modern-redux, debug-redux-toolkit-apps\n- Composition skills: generate-rtk-query-from-openapi\n- Reference files: build-slices-and-selectors, handle-side-effects, adopt-rtk-query, generate-rtk-query-from-openapi\n\n## Composition Opportunities\n\n| Library | Integration points | Composition skill needed? |\n| ------- | ------------------ | ------------------------- |\n| react-redux | Provider, hooks, typed hooks, modern Redux app structure | yes - modern-redux |\n| redux-persist | serializability exceptions, RTK Query rehydration, browser staleness caveats | no - mention inside adopt-rtk-query |\n| OpenAPI | endpoint generation, tags, overrides, output structure | yes - generate-rtk-query-from-openapi |\n| @reduxjs/rtk-codemods | RTK 2 migration rewrites | no - mention inside migrate-to-modern-redux |\n"
  },
  {
    "path": "_artifacts/skill_tree.yaml",
    "content": "# skill_tree.yaml\nlibrary:\n  name: '@reduxjs/toolkit'\n  version: 'workspace snapshot (toolkit 2.11.2)'\n  repository: 'https://github.com/reduxjs/redux-toolkit'\n  description: 'Monorepo for Redux Toolkit, RTK Query, and companion codegen and codemod packages.'\ngenerated_from:\n  domain_map: '_artifacts/domain_map.yaml'\n  skill_spec: '_artifacts/skill_spec.md'\ngenerated_at: '2026-03-14T19:25:20+01:00'\n\nskills:\n  - name: 'Modern Redux'\n    slug: 'modern-redux'\n    type: 'lifecycle'\n    domain: 'build-modern-redux-apps'\n    path: 'packages/toolkit/skills/build-modern-redux-apps/modern-redux/SKILL.md'\n    package: 'packages/toolkit'\n    description: 'Set up modern Redux with Redux Toolkit and React-Redux, including the correct store lifetime for SPA and SSR-heavy React environments.'\n    requires:\n      - 'redux-dataflow'\n    sources:\n      - 'reduxjs/redux-toolkit:docs/tutorials/quick-start.mdx'\n      - 'reduxjs/redux-toolkit:docs/tutorials/typescript.md'\n      - 'reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx'\n      - 'reduxjs/redux-toolkit:docs/usage/nextjs.mdx'\n      - 'reduxjs/redux:docs/style-guide/style-guide.md'\n    references:\n      - 'references/store-lifetime.md'\n\n  - name: 'Redux Dataflow'\n    slug: 'redux-dataflow'\n    type: 'core'\n    domain: 'build-modern-redux-apps'\n    path: 'packages/toolkit/skills/build-modern-redux-apps/redux-dataflow/SKILL.md'\n    package: 'packages/toolkit'\n    description: 'Explain the Redux event-to-reducer-to-selector-to-render loop so agents can author and debug Redux Toolkit code without fighting the architecture.'\n    sources:\n      - 'reduxjs/redux:docs/tutorials/fundamentals/part-2-concepts-data-flow.md'\n      - 'reduxjs/redux:docs/tutorials/essentials/part-3-data-flow.md'\n      - 'reduxjs/redux:docs/style-guide/style-guide.md'\n\n  - name: 'Design State Ownership'\n    slug: 'design-state-ownership'\n    type: 'core'\n    domain: 'model-redux-state'\n    path: 'packages/toolkit/skills/model-redux-state/design-state-ownership/SKILL.md'\n    package: 'packages/toolkit'\n    description: 'Decide what belongs in Redux, what should stay local or external, and when slice boundaries should be resized as the app evolves.'\n    sources:\n      - 'reduxjs/redux:docs/style-guide/style-guide.md'\n      - 'reduxjs/redux:docs/tutorials/essentials/part-2-app-structure.md'\n      - 'reduxjs/redux:docs/tutorials/essentials/part-4-using-data.md'\n    references:\n      - 'references/state-ownership.md'\n\n  - name: 'Build Slices And Selectors'\n    slug: 'build-slices-and-selectors'\n    type: 'core'\n    domain: 'model-redux-state'\n    path: 'packages/toolkit/skills/model-redux-state/build-slices-and-selectors/SKILL.md'\n    package: 'packages/toolkit'\n    description: 'Author slices, selectors, entity adapters, and lazy-injected reducers with current RTK patterns such as slice selectors and create.asyncThunk.'\n    requires:\n      - 'design-state-ownership'\n    sources:\n      - 'reduxjs/redux-toolkit:docs/api/createSlice.mdx'\n      - 'reduxjs/redux-toolkit:docs/api/combineSlices.mdx'\n      - 'reduxjs/redux-toolkit:docs/api/createEntityAdapter.mdx'\n      - 'reduxjs/redux-toolkit:docs/usage/immer-reducers.md'\n      - 'reduxjs/redux-toolkit:docs/usage/migrating-rtk-2.md'\n      - 'reduxjs/redux:docs/style-guide/style-guide.md'\n    references:\n      - 'references/slice-patterns.md'\n\n  - name: 'Handle Side Effects'\n    slug: 'handle-side-effects'\n    type: 'core'\n    domain: 'orchestrate-side-effects'\n    path: 'packages/toolkit/skills/orchestrate-side-effects/handle-side-effects/SKILL.md'\n    package: 'packages/toolkit'\n    description: 'Choose correctly between RTK Query, thunks, and listener middleware, then implement imperative or reactive workflows without leaking logic into reducers.'\n    requires:\n      - 'redux-dataflow'\n    sources:\n      - 'reduxjs/redux-toolkit:docs/api/createAsyncThunk.mdx'\n      - 'reduxjs/redux-toolkit:docs/api/createListenerMiddleware.mdx'\n      - 'reduxjs/redux:docs/style-guide/style-guide.md'\n      - 'reduxjs/redux:docs/tutorials/essentials/part-5-async-logic.md'\n    references:\n      - 'references/listener-workflows.md'\n\n  - name: 'Adopt RTK Query'\n    slug: 'adopt-rtk-query'\n    type: 'lifecycle'\n    domain: 'manage-server-data'\n    path: 'packages/toolkit/skills/manage-server-data/adopt-rtk-query/SKILL.md'\n    package: 'packages/toolkit'\n    description: 'Introduce RTK Query as the default server-data layer, including API slice setup, invalidation behavior, cache lifecycles, and React usage.'\n    requires:\n      - 'modern-redux'\n    sources:\n      - 'reduxjs/redux-toolkit:docs/rtk-query/api/createApi.mdx'\n      - 'reduxjs/redux-toolkit:docs/rtk-query/usage/automated-refetching.mdx'\n      - 'reduxjs/redux-toolkit:docs/rtk-query/usage/manual-cache-updates.mdx'\n      - 'reduxjs/redux-toolkit:docs/rtk-query/usage/persistence-and-rehydration.mdx'\n      - 'reduxjs/redux-toolkit:docs/tutorials/rtk-query.mdx'\n      - 'reduxjs/redux:docs/style-guide/style-guide.md'\n    references:\n      - 'references/endpoint-lifecycle.md'\n\n  - name: 'Generate RTK Query From OpenAPI'\n    slug: 'generate-rtk-query-from-openapi'\n    type: 'composition'\n    domain: 'manage-server-data'\n    path: 'packages/rtk-query-codegen-openapi/skills/manage-server-data/generate-rtk-query-from-openapi/SKILL.md'\n    package: 'packages/rtk-query-codegen-openapi'\n    description: 'Generate RTK Query endpoints from OpenAPI schemas, then review endpoint overrides, tags, and output shape so the generated API still fits a single RTK Query architecture.'\n    requires:\n      - 'adopt-rtk-query'\n    sources:\n      - 'reduxjs/redux-toolkit:docs/rtk-query/usage/code-generation.mdx'\n      - 'reduxjs/redux-toolkit:packages/rtk-query-codegen-openapi/src/types.ts'\n      - 'reduxjs/redux-toolkit:packages/rtk-query-codegen-openapi/src/generate.ts'\n      - 'reduxjs/redux-toolkit:packages/rtk-query-codegen-openapi/README.md'\n    references:\n      - 'references/codegen-overrides.md'\n\n  - name: 'Migrate To Modern Redux'\n    slug: 'migrate-to-modern-redux'\n    type: 'lifecycle'\n    domain: 'evolve-and-diagnose-redux-apps'\n    path: 'packages/toolkit/skills/evolve-and-diagnose-redux-apps/migrate-to-modern-redux/SKILL.md'\n    package: 'packages/toolkit'\n    description: 'Incrementally replace legacy Redux patterns with configureStore, createSlice, hooks, RTK Query, and codemod-assisted upgrades without reintroducing legacy code.'\n    requires:\n      - 'modern-redux'\n    sources:\n      - 'reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx'\n      - 'reduxjs/redux-toolkit:docs/usage/migrating-rtk-2.md'\n      - 'reduxjs/redux-toolkit:packages/rtk-codemods/README.md'\n      - 'reduxjs/redux:docs/style-guide/style-guide.md'\n\n  - name: 'Debug Redux Toolkit Apps'\n    slug: 'debug-redux-toolkit-apps'\n    type: 'lifecycle'\n    domain: 'evolve-and-diagnose-redux-apps'\n    path: 'packages/toolkit/skills/evolve-and-diagnose-redux-apps/debug-redux-toolkit-apps/SKILL.md'\n    package: 'packages/toolkit'\n    description: 'Trace duplicate requests, stale cache behavior, broad subscriptions, selector churn, and serializability issues back to the underlying RTK or RTK Query mechanism.'\n    requires:\n      - 'redux-dataflow'\n    sources:\n      - 'reduxjs/redux:docs/style-guide/style-guide.md'\n      - 'reduxjs/redux:docs/tutorials/essentials/part-5-async-logic.md'\n      - 'reduxjs/redux:docs/tutorials/essentials/part-8-rtk-query-advanced.md'\n      - 'reduxjs/redux-toolkit:docs/usage/usage-guide.md'\n"
  },
  {
    "path": "docs/api/actionCreatorMiddleware.mdx",
    "content": "---\nid: actionCreatorMiddleware\ntitle: Action Creator Middleware\nsidebar_label: Action Creator Middleware\nhide_title: true\n---\n\n&nbsp;\n\n# Action Creator Middleware\n\nA custom middleware that detects if an action creator has been mistakenly dispatched, instead of being called before dispatching.\n\nA common mistake is to call `dispatch(actionCreator)` instead of `dispatch(actionCreator())`.\nThis tends to \"work\" as the action creator has the static `type` property, but can lead to unexpected behavior.\n\n## Options\n\n```ts no-transpile\nexport interface ActionCreatorInvariantMiddlewareOptions {\n  /**\n   * The function to identify whether a value is an action creator.\n   * The default checks for a function with a static type property and match method.\n   */\n  isActionCreator?: (action: unknown) => action is Function & { type?: unknown }\n}\n```\n\n## Exports\n\n### `createActionCreatorInvariantMiddleware`\n\nCreates an instance of the action creator check middleware, with the given options.\n\nYou will most likely not need to call this yourself, as `getDefaultMiddleware` already does so.\nExample:\n\n```ts\n// file: reducer.ts noEmit\n\nexport default function (state = {}, action: any) {\n  return state\n}\n\n// file: store.ts\n\nimport {\n  configureStore,\n  createActionCreatorInvariantMiddleware,\n  Tuple,\n} from '@reduxjs/toolkit'\nimport reducer from './reducer'\n\n// Augment middleware to consider all functions with a static type property to be action creators\nconst isActionCreator = (\n  action: unknown,\n): action is Function & { type: unknown } =>\n  typeof action === 'function' && 'type' in action\n\nconst actionCreatorMiddleware = createActionCreatorInvariantMiddleware({\n  isActionCreator,\n})\n\nconst store = configureStore({\n  reducer,\n  middleware: () => new Tuple(actionCreatorMiddleware),\n})\n```\n"
  },
  {
    "path": "docs/api/autoBatchEnhancer.mdx",
    "content": "---\nid: autoBatchEnhancer\ntitle: autoBatchEnhancer\nsidebar_label: autoBatchEnhancer\nhide_title: true\n---\n\n&nbsp;\n\n# `autoBatchEnhancer`\n\nA Redux store enhancer that looks for one or more \"low-priority\" dispatched actions in a row, and queues a callback to run subscriber notifications on a delay. It then notifies subscribers either when the queued callback runs, or when the next \"normal-priority\" action is dispatched, whichever is first.\n\n## Basic Usage\n\n```ts\nimport {\n  createSlice,\n  configureStore,\n  autoBatchEnhancer,\n  prepareAutoBatched,\n} from '@reduxjs/toolkit'\n\ninterface CounterState {\n  value: number\n}\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 } satisfies CounterState as CounterState,\n  reducers: {\n    incrementBatched: {\n      // Batched, low-priority\n      reducer(state) {\n        state.value += 1\n      },\n      // highlight-start\n      // Use the `prepareAutoBatched` utility to automatically\n      // add the `action.meta[SHOULD_AUTOBATCH]` field the enhancer needs\n      prepare: prepareAutoBatched<void>(),\n      // highlight-end\n    },\n    // Not batched, normal priority\n    decrementUnbatched(state) {\n      state.value -= 1\n    },\n  },\n})\nconst { incrementBatched, decrementUnbatched } = counterSlice.actions\n\n// includes batch enhancer by default, as of RTK 2.0\nconst store = configureStore({\n  reducer: counterSlice.reducer,\n})\n```\n\n## API\n\n### `autoBatchEnhancer`\n\n```ts title=\"autoBatchEnhancer signature\" no-transpile\nexport type SHOULD_AUTOBATCH = string\ntype AutoBatchOptions =\n  | { type: 'tick' }\n  | { type: 'timer'; timeout: number }\n  | { type: 'raf' }\n  | { type: 'callback'; queueNotification: (notify: () => void) => void }\n\nexport type autoBatchEnhancer = (options?: AutoBatchOptions) => StoreEnhancer\n```\n\n:::tip\nAs of RTK 2.0, the `autoBatchEnhancer` is included by default when calling `configureStore`.\n\nThis means to configure it, you should instead pass an callback that receives `getDefaultEnhancers` and calls it with your desired settings.\n\n```ts title=\"Configuring autoBatchEnhancer with getDefaultEnhancers\"\nimport { configureStore } from '@reduxjs/toolkit'\n\nconst store = configureStore({\n  reducer: () => 0,\n  enhancers: (getDefaultEnhancers) =>\n    getDefaultEnhancers({\n      autoBatch: { type: 'tick' },\n    }),\n})\n```\n\n:::\n\nCreates a new instance of the autobatch store enhancer.\n\nAny action that is tagged with `action.meta[SHOULD_AUTOBATCH] = true` will be treated as \"low-priority\", and a notification callback will be queued. The enhancer will delay notifying subscribers until either:\n\n- The queued callback runs and triggers the notifications\n- A \"normal-priority\" action (any action _without_ `action.meta[SHOULD_AUTOBATCH] = true`) is dispatched in the same tick\n\n`autoBatchEnhancer` accepts options to configure how the notification callback is queued:\n\n- `{type: 'raf'}`: queues using `requestAnimationFrame` (default)\n- `{type: 'tick'}`: queues using `queueMicrotask`\n- `{type: 'timer', timeout: number}`: queues using `setTimeout`\n- `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback, such as a debounced or throttled function\n\nThe default behavior is to queue the notifications using `requestAnimationFrame`.\n\nThe `SHOULD_AUTOBATCH` value is meant to be opaque - it's currently a string for simplicity, but could be a `Symbol` in the future.\n\n### `prepareAutoBatched`\n\n```ts title=\"prepareAutoBatched signature\" no-transpile\ntype prepareAutoBatched = <T>() => (payload: T) => { payload: T; meta: unknown }\n```\n\nCreates a function that accepts a `payload` value, and returns an object with `{payload, meta: {[SHOULD_AUTOBATCH]: true}}`. This is meant to be used with RTK's `createSlice` and its \"`prepare` callback\" syntax:\n\n```ts no-transpile\ncreateSlice({\n  name: 'todos',\n  initialState,\n  reducers: {\n    todoAdded: {\n      reducer(state, action: PayloadAction<Todo>) {\n        state.push(action.payload)\n      },\n      // highlight-start\n      prepare: prepareAutoBatched<Todo>(),\n      // highlight-end\n    },\n  },\n})\n```\n\n## Batching Approach and Background\n\nThe post [A Comparison of Redux Batching Techniques](https://blog.isquaredsoftware.com/2020/01/blogged-answers-redux-batching-techniques/) describes four different approaches for \"batching Redux actions/dispatches\"\n\n- a higher-order reducer that accepts multiple actions nested inside one real action, and iterates over them together\n- an enhancer that wraps `dispatch` and debounces the notification callback\n- an enhancer that wraps `dispatch` to accept an array of actions\n- React's `unstable_batchedUpdates()`, which just combines multiple queued renders into one but doesn't affect subscriber notifications\n\nThis enhancer is a variation of the \"debounce\" approach, but with a twist.\n\nInstead of _just_ debouncing _all_ subscriber notifications, it watches for any actions with a specific `action.meta[SHOULD_AUTOBATCH]: true` field attached.\n\nWhen it sees an action with that field, it queues a callback. The reducer is updated immediately, but the enhancer does _not_ notify subscribers right way. If other actions with the same field are dispatched in succession, the enhancer will continue to _not_ notify subscribers. Then, when the queued callback runs, it finally notifies all subscribers, similar to how React batches re-renders.\n\nThe additional twist is also inspired by React's separation of updates into \"low-priority\" and \"immediate\" behavior (such as a render queued by an AJAX request vs a render queued by a user input that should be handled synchronously).\n\nIf some low-pri actions have been dispatched and a notification microtask is queued, then a _normal_ priority action (without the field) is dispatched, the enhancer will go ahead and notify all subscribers synchronously as usual, and _not_ notify them at the end of the tick.\n\nThis allows Redux users to selectively tag certain actions for effective batching behavior, making this purely opt-in on a per-action basis, while retaining normal notification behavior for all other actions.\n\n### RTK Query and Batching\n\nRTK Query already marks several of its key internal action types as batchable. By adding the `autoBatchEnhancer` to the store setup, it improves the overall UI performance, especially when rendering large lists of components that use the RTKQ query hooks.\n"
  },
  {
    "path": "docs/api/codemods.mdx",
    "content": "---\nid: codemods\ntitle: Codemods\nsidebar_label: Codemods\nhide_title: true\n---\n\n&nbsp;\n\n# Codemods\n\nPer [the description in `1.9.0`](https://github.com/reduxjs/redux-toolkit/releases/tag/v1.9.0), we have removed the \"object\" argument from `createReducer` and `createSlice.extraReducers` in the RTK 2.0 major version. We've also added a new optional form of `createSlice.reducers` that uses a callback instead of an object.\n\nTo simplify upgrading codebases, we've published a set of codemods that will automatically transform the deprecated \"object\" syntax into the equivalent \"builder\" syntax.\n\nThe codemods package is available on NPM as [**`@reduxjs/rtk-codemods`**](https://www.npmjs.com/package/@reduxjs/rtk-codemods). It currently contains these codemods:\n\n- `createReducerBuilder`: migrates `createReducer` calls that use the removed object syntax to the builder callback syntax\n- `createSliceBuilder`: migrates `createSlice` calls that use the removed object syntax for `extraReducers` to the builder callback syntax\n- `createSliceReducerBuilder`: migrates `createSlice` calls that use the still-standard object syntax for `reducers` to the optional new builder callback syntax, including uses of prepared reducers\n\nTo run the codemods against your codebase, run `npx @reduxjs/rtk-codemods <TRANSFORM NAME> path/of/files/ or/some**/*glob.js`.\n\nExamples:\n\n```bash\nnpx @reduxjs/rtk-codemods createReducerBuilder ./src\n\nnpx @reduxjs/rtk-codemods createSliceBuilder ./packages/my-app/**/*.ts\n```\n\nWe also recommend re-running Prettier on the codebase before committing the changes.\n\n**These codemods _should_ work, but we would greatly appreciate testing and feedback on more real-world codebases!**\n\nBefore:\n\n```js\ncreateReducer(initialState, {\n  [todoAdded1a]: (state, action) => {\n    // stuff\n  },\n  [todoAdded1b]: (state, action) => action.payload,\n})\n\nconst slice1 = createSlice({\n  name: 'a',\n  initialState: {},\n  extraReducers: {\n    [todoAdded1a]: (state, action) => {\n      // stuff\n    },\n    [todoAdded1b]: (state, action) => action.payload,\n  },\n})\n```\n\nAfter:\n\n```js\ncreateReducer(initialState, (builder) => {\n  builder.addCase(todoAdded1a, (state, action) => {\n    // stuff\n  })\n\n  builder.addCase(todoAdded1b, (state, action) => action.payload)\n})\n\nconst slice1 = createSlice({\n  name: 'a',\n  initialState: {},\n\n  extraReducers: (builder) => {\n    builder.addCase(todoAdded1a, (state, action) => {\n      // stuff\n    })\n\n    builder.addCase(todoAdded1b, (state, action) => action.payload)\n  },\n})\n```\n"
  },
  {
    "path": "docs/api/combineSlices.mdx",
    "content": "---\nid: combineSlices\ntitle: combineSlices\nsidebar_label: combineSlices\nhide_title: true\n---\n\n&nbsp;\n\n# `combineSlices`\n\n## Overview\n\nA function that combines slices into a single reducer, and enables injection of more reducers after initialisation.\n\n```ts\n// file: slices/api.ts noEmit\nimport type { Api } from '@reduxjs/toolkit/query'\n\nexport declare const api: Api<() => any, {}, 'api', never>\n\n// file: slices/users.ts noEmit\nimport type { Slice } from '@reduxjs/toolkit'\n\nexport declare const userSlice: Slice<string, {}, 'user'>\n\n// file: slices/index.ts\nimport { combineSlices } from '@reduxjs/toolkit'\nimport { api } from './api'\nimport { userSlice } from './users'\n\nexport const rootReducer = combineSlices(api, userSlice)\n\n// file: store.ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport { rootReducer } from './slices'\n\nexport const store = configureStore({\n  reducer: rootReducer,\n})\n```\n\n:::note\n\nA \"slice\" for `combineSlices` is typically created with [`createSlice`](./createSlice.mdx),\nbut can be any \"slice-like\" object with `reducerPath` and `reducer` properties (meaning RTK Query [API instances](/rtk-query/api/created-api/overview.mdx) are also compatible).\n\n```ts no-transpile\nconst withUserReducer = rootReducer.inject({\n  reducerPath: 'user',\n  reducer: userReducer,\n})\n\nconst withApiReducer = rootReducer.inject(fooApi)\n```\n\nFor simplicity, this `{ reducerPath, reducer }` shape will be described in these docs as a \"slice\".\n\n:::\n\n## Parameters\n\n`combineSlices` accepts a set of slices and/or reducer map objects, and combines them into a single reducer.\n\nSlices will be mounted at their `reducerPath`, and items from reducer map objects will be mounted under their respective key.\n\n```ts no-transpile\nconst rootReducer = combineSlices(counterSlice, baseApi, {\n  user: userSlice.reducer,\n  auth: authSlice.reducer,\n})\n// is like\nconst rootReducer = combineReducers({\n  [counterSlice.reducerPath]: counterSlice.reducer,\n  [baseApi.reducerPath]: baseApi.reducer,\n  user: userSlice.reducer,\n  auth: authSlice.reducer,\n})\n```\n\n:::caution\n\nIf multiple slices/map objects have the same reducer path, the reducer provided later in the arguments will override the previous.\n\nHowever, typing will not be able to account for this. It's best to ensure that all of your reducers will aim for a unique location.\n\n:::\n\n## Return Value\n\n`combineSlices` returns a reducer function, with attached methods.\n\n```ts no-transpile\ninterface CombinedSliceReducer<InitialState, DeclaredState = InitialState>\n  extends Reducer<DeclaredState, AnyAction, Partial<DeclaredState>> {\n  withLazyLoadedSlices<LazyLoadedSlices>(): CombinedSliceReducer<\n    InitialState,\n    DeclaredState & Partial<LazyLoadedSlices>\n  >\n  inject<Slice extends SliceLike>(\n    slice: Slice,\n    config?: InjectConfig\n  ): CombinedSliceReducer<InitialState, DeclaredState & WithSlice<Slice>>\n  selector: {\n    (selectorFn: Selector, selectState?: SelectFromRootState) => WrappedSelector\n    original(state: DeclaredState) => InitialState & Partial<DeclaredState>\n  }\n}\n```\n\n### `withLazyLoadedSlices`\n\nIt's recommended to [infer your RootState type from your store](https://redux.js.org/usage/usage-with-typescript#define-root-state-and-dispatch-types), which is inferred from the reducer. However, this can present issues if slices are lazy loaded, and thus not able to be inferred from.\n\n`withLazyLoadedSlices` allows you to declare slices that will be added to state later, which will be included in the final state type.\n\nOne possible pattern of managing this would be with declaration merging:\n\n```ts no-transpile title=\"Using declaration merging to declare injected slices\"\n// file: slices/index.ts\nimport { combineSlices } from '@reduxjs/toolkit'\nimport { staticSlice } from './static'\n\nexport interface LazyLoadedSlices {}\n\nexport const rootReducer =\n  combineSlices(staticSlice).withLazyLoadedSlices<LazyLoadedSlices>()\n\n// keys in LazyLoadedSlices are marked as optional\nexport type RootState = ReturnType<typeof rootReducer>\n\n// file: slices/lazySlice.ts\nimport type { WithSlice } from '@reduxjs/toolkit'\nimport { rootReducer } from '.'\n\nconst lazySlice = createSlice({\n  /* ... */\n})\n\ndeclare module '.' {\n  export interface LazyLoadedSlices extends WithSlice<typeof lazySlice> {}\n}\n\nconst injectedReducer = rootReducer.inject(lazySlice)\n\n// and/or\n\nconst injectedSlice = lazySlice.injectInto(rootReducer)\n```\n\n:::tip\n\nThe above example uses the `WithSlice` utility type for a slice mounted under its `reducerPath`. If the slice is mounted under a different key, you can declare it as a regular key instead.\n\n```ts no-transpile title=\"Declaring a slice mounted outside its reducerPath\"\n// file: slices/lazySlice.ts\nimport { rootReducer } from '.'\n\nconst lazySlice = createSlice({\n  /* ... */\n})\n\ndeclare module '.' {\n  export interface LazyLoadedSlices {\n    customKey: LazyState\n  }\n}\n\nconst injectedReducer = rootReducer.inject({\n  reducerPath: 'customKey',\n  reducer: lazySlice.reducer,\n})\n\n// and/or\n\nconst injectedSlice = lazySlice.injectInto(rootReducer, {\n  reducerPath: 'customKey',\n})\n```\n\n:::\n\n### `inject`\n\n`inject` allows you to add a slice to your set of reducers after initialisation.\nIt expects to be passed a slice and an optional config, and returns an updated version of the reducer with the slice included.\n\nThis is mainly useful for lazy loading reducers.\n\n```ts no-transpile\nconst reducerWithUser = rootReducer.inject(userSlice)\n```\n\n:::note\n\n`inject` adds the slice to the map of reducers in your original reducer, but doesn't dispatch an action.\n\nThis means that the added reducer state will not show up in your store until the next action is dispatched.\n\n:::\n\n#### Reducer replacement\n\nBy default, replacing a reducer is not allowed.\nIn development mode, a warning will be logged to console if a new reducer instance is attempted to inject into a `reducerPath` that's already injected. (It won't warn if the same reducer instance is injected into the same place twice.)\n\nIf you wish to allow replacing a reducer with a new instance, you must explicitly pass `overrideExisting: true` as part of your configuration object.\n\n```ts no-transpile\nconst reducerWithUser = rootReducer.inject(userSlice, {\n  overrideExisting: true,\n})\n```\n\nThis may be useful for hot reload, or \"removing\" a reducer by replacing it with a function that always returns `null`.\nNote that for predictable behavior, your types should account for all of the possible reducers you intend to occupy a path.\n\n```ts no-transpile title=\"'Removing' a reducer, by replacing it with a no-op function\"\ndeclare module '.' {\n  export interface LazyLoadedSlices {\n    removable: RemovableState | null\n  }\n}\n\nconst withInjected = rootReducer.inject(\n  { reducerPath: 'removable', reducer: removableReducer },\n  { overrideExisting: true },\n)\n\nconst emptyReducer = () => null\n\nconst removeReducer = () =>\n  rootReducer.inject(\n    { reducerPath: 'removable', reducer: emptyReducer },\n    { overrideExisting: true },\n  )\n```\n\n### `selector`\n\nAs noted previously, an injected reducer can still be undefined in state if no action has been dispatched.\n\nDealing with this possibly-optional state can be inconvient when writing selectors, as you may end up with a lot of results being possibly undefined or relying on explicit defaults.\n\n`selector` allows you to get around this, by wrapping the reducer state in a `Proxy` that ensures that any currently injected reducers evaluate to their initial state if they're currently `undefined` in state.\n\n```ts no-transpile\ndeclare module '.' {\n  export interface LazyLoadedSlices extends WithSlice<typeof counterSlice> {}\n}\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 },\n  reducers: {\n    /* ... */\n  },\n})\n\nconst withCounter = rootReducer.inject(counterSlice)\n\nconst selectCounterValue = (rootState: RootState) => rootState.counter?.value // number | undefined\n\nconst wrappedSelectCounterValue = withCounter.selector(\n  (rootState) => rootState.counter.value, // number\n)\n\nconsole.log(\n  selectCounterValue({}), // undefined\n  selectCounterValue({ counter: { value: 2 } }), // 2\n  wrappedSelectCounterValue({}), // 0\n  wrappedSelectCounterValue({ counter: { value: 2 } }), // 2\n)\n```\n\n:::caution\n\nThe `Proxy` retrieves a reducer's initial state by calling it with a randomly generated action type - don't try to handle this as a special case inside your reducer.\n\n:::\n\n#### Nested combined reducer\n\nThe wrapped selector expects to use the state returned by the combined reducer as its first argument.\n\nIf the combined reducer is nested further inside the store state, pass a `selectState` callback as the second argument to `selector`:\n\n```ts no-transpile\ninterface RootState {\n  innerCombined: ReturnType<typeof combinedReducer>\n}\n\nconst selectCounterValue = withCounter.selector(\n  (combinedState) => combinedState.counter.value,\n  (rootState: RootState) => rootState.innerCombined,\n)\n\nconsole.log(\n  selectCounterValue({\n    innerCombined: {},\n  }), // 0\n  selectCounterValue({\n    innerCombined: {\n      counter: {\n        value: 2,\n      },\n    },\n  }), // 2\n)\n```\n\n#### `original`\n\nSimilar to [Immer usage](/usage/immer-reducers.md#debugging-and-inspecting-drafted-state), an `original` function is provided to retrieve the original state value provided to the `Proxy`.\n\nThis is mainly useful for debugging/inspecting, as `Proxy` instances tend to be displayed in a format that's hard to read.\n\nThe function is attached as a method on the `selector` function:\n\n```ts no-transpile\nconst wrappedSelectCounterValue = withCounter.selector((rootState) => {\n  console.log(withCounter.selector.original(rootState))\n  return rootState.counter.value\n})\n```\n\n## Slice integration\n\n### `injectInto`\n\nSlice instances returned by [`createSlice`](./createSlice) have an attached `injectInto` method, which receive an injectable reducer from `combineSlices` and returns an \"injected\" version of that slice.\n\n```ts no-transpile\nconst injectedCounterSlice = counterSlice.injectInto(rootReducer)\n```\n\nAn optional configuration object can be passed. This follows [`inject`](#inject)'s options with an additional `reducerPath` field, for injecting the slice under a path other than its current `reducerPath` property.\n\n```ts no-transpile\nconst aCounterSlice = counterSlice.injectInto(rootReducer, {\n  reducerPath: 'aCounter',\n})\n```\n\n### `selectors` / `getSelectors`\n\nSimilar to [`selector`](#selector), the selectors from an \"injected\" slice instance behave slightly differently.\n\nIf the slice state is undefined in the store state passed, the selector will instead be called with the slice's initial state.\n\n`selectors` will also reflect the change in `reducerPath` if one was made during injection.\n\n```ts no-transpile\nconsole.log(\n  injectedCounterSlice.selectors.selectValue({}), // 0\n  injectedCounterSlice.selectors.selectValue({ counter: { value: 2 } }), // 2\n  aCounterSlice.selectors.selectValue({ aCounter: { value: 2 } }), // 2\n)\n```\n"
  },
  {
    "path": "docs/api/configureStore.mdx",
    "content": "---\nid: configureStore\ntitle: configureStore\nsidebar_label: configureStore\nhide_title: true\n---\n\n&nbsp;\n\n# `configureStore`\n\nThe standard method for creating a Redux store. It uses the low-level Redux core `createStore` method internally, but wraps that to provide good defaults to the store setup for a better development experience.\n\n## Purpose and Behavior\n\nA standard Redux store setup typically requires multiple pieces of configuration:\n\n- Combining the slice reducers into the root reducer\n- Creating the middleware enhancer, usually with the thunk middleware or other side effects middleware, as well as middleware that might be used for development checks\n- Adding the Redux DevTools enhancer, and composing the enhancers together\n- Calling `createStore`\n\nLegacy Redux usage patterns typically required several dozen lines of copy-pasted boilerplate to achieve this.\n\nRedux Toolkit's `configureStore` simplifies that setup process, by doing all that work for you. One call to `configureStore` will:\n\n- Call `combineReducers` to combine your slices reducers into the root reducer function\n- Add the thunk middleware and called `applyMiddleware`\n- In development, automatically add more middleware to check for common mistakes like accidentally mutating the state\n- Automatically set up the Redux DevTools Extension connection\n- Call `createStore` to create a Redux store using that root reducer and those configuration options\n\n`configureStore` also offers an improved API and usage patterns compared to the original `createStore` by accepting named fields for `reducer`, `preloadedState`, `middleware`, `enhancers`, and `devtools`, as well as much better TS type inference.\n\n## Parameters\n\n`configureStore` accepts a single configuration object parameter, with the following options:\n\n```ts no-transpile\n\ninterface ConfigureStoreOptions<\n  S = any,\n  A extends Action = UnknownAction,\n  M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>\n  E extends Tuple<Enhancers> = Tuple<Enhancers>,\n  P = S\n> {\n  /**\n   * A single reducer function that will be used as the root reducer, or an\n   * object of slice reducers that will be passed to `combineReducers()`.\n   */\n  reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>\n\n  /**\n   * An array of Redux middleware to install. If not supplied, defaults to\n   * the set of middleware returned by `getDefaultMiddleware()`.\n   */\n  middleware?: ((getDefaultMiddleware: CurriedGetDefaultMiddleware<S>) => M) | M\n\n  /**\n   * Whether to enable Redux DevTools integration. Defaults to `true`.\n   *\n   * Additional configuration can be done by passing Redux DevTools options\n   */\n  devTools?: boolean | DevToolsOptions\n\n  /**\n   * Whether to check for duplicate middleware instances. Defaults to `true`.\n   */\n  duplicateMiddlewareCheck?: boolean\n\n  /**\n   * The initial state, same as Redux's createStore.\n   * You may optionally specify it to hydrate the state\n   * from the server in universal apps, or to restore a previously serialized\n   * user session. If you use `combineReducers()` to produce the root reducer\n   * function (either directly or indirectly by passing an object as `reducer`),\n   * this must be an object with the same shape as the reducer map keys.\n   */\n  preloadedState?: P\n\n  /**\n   * The store enhancers to apply. See Redux's `createStore()`.\n   * All enhancers will be included before the DevTools Extension enhancer.\n   * If you need to customize the order of enhancers, supply a callback\n   * function that will receive the getDefaultEnhancers,\n   * and should return a new array (such as `getDefaultEnhancers().concat(offline)`).\n   * If you only need to add middleware, you can use the `middleware` parameter instead.\n   */\n  enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E | E\n}\n\nfunction configureStore<\n  S = any,\n  A extends Action = UnknownAction,\n  M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>\n  E extends Tuple<Enhancers> = Tuple<Enhancers>,\n  P = S\n>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, M, E>\n```\n\n### `reducer`\n\nIf this is a single function, it will be directly used as the root reducer for the store.\n\nIf it is an object of slice reducers, like `{users : usersReducer, posts : postsReducer}`,\n`configureStore` will automatically create the root reducer by passing this object to the\n[Redux `combineReducers` utility](https://redux.js.org/api/combinereducers).\n\n### `middleware`\n\nA callback which will receive `getDefaultMiddleware` as its argument,\nand should return a middleware array.\n\nIf this option is provided, it should return all the middleware functions you\nwant added to the store. `configureStore` will automatically pass those to `applyMiddleware`.\n\nIf not provided, `configureStore` will call `getDefaultMiddleware` and use the\narray of middleware functions it returns.\n\nFor more details on how the `middleware` parameter works and the list of middleware that are added by default, see the\n[`getDefaultMiddleware` docs page](./getDefaultMiddleware.mdx).\n\n:::note Tuple\nTypeScript users are required to use a `Tuple` instance (if not using a `getDefaultMiddleware` result, which is already a `Tuple`), for better inference.\n\n```ts no-transpile\nimport { configureStore, Tuple } from '@reduxjs/toolkit'\n\nconfigureStore({\n  reducer: rootReducer,\n  middleware: () => new Tuple(additionalMiddleware, logger),\n})\n```\n\nJavascript-only users are free to use a plain array if preferred.\n\n:::\n\n### `devTools`\n\nIf this is a boolean, it will be used to indicate whether `configureStore` should automatically enable support for [the Redux DevTools browser extension](https://github.com/reduxjs/redux-devtools).\n\nIf it is an object, then the DevTools Extension will be enabled, and the options object will be passed to `composeWithDevtools()`. See\nthe DevTools Extension docs for [`EnhancerOptions`](https://github.com/reduxjs/redux-devtools/blob/main/extension/docs/API/Arguments.md) for\na list of the specific options that are available.\n\nDefaults to `true`.\n\n### `duplicateMiddlewareCheck`\n\nIf enabled, the store will check the final middleware array to see if there are any duplicate middleware references. This will catch issues like accidentally adding the same RTK Query API middleware twice (such as adding both the base API middleware and an injected API middleware, which are actually the exact same function reference).\n\nDefaults to `true`.\n\n#### `trace`\n\nThe Redux DevTools Extension recently added [support for showing action stack traces](https://github.com/reduxjs/redux-devtools/blob/main/extension/docs/Features/Trace.md) that show exactly where each action was dispatched.\nCapturing the traces can add a bit of overhead, so the DevTools Extension allows users to configure whether action stack traces are captured by [setting the 'trace' argument](https://github.com/reduxjs/redux-devtools/blob/main/extension/docs/API/Arguments.md#trace).\nIf the DevTools are enabled by passing `true` or an object, then `configureStore` will default to enabling capturing action stack traces in development mode only.\n\n### `preloadedState`\n\nAn optional initial state value to be passed to the Redux `createStore` function.\n\n### `enhancers`\n\nA callback function to customize the array of enhancers.\n\nEnhancers returned by this callback will be passed to [the Redux `compose` function](https://redux.js.org/api/compose), and the combined enhancer will be passed to `createStore`.\n\n:::tip Dev Tools\nThis should _not_ include the Redux DevTools Extension `composeWithDevTools`, as this is already handled by `configureStore`.\n\nExample: `enhancers: () => new Tuple(offline)` will result in a final setup of `[offline, devToolsExtension]`.\n:::\n\nIf not provided, `configureStore` will call `getDefaultEnhancers` and use the array of enhancers it returns (including `applyMiddleware` with specified middleware).\n\nWhere you wish to add onto or customize the default enhancers, you may pass a callback function that will receive `getDefaultEnhancers` as its argument, and should return an enhancer array.\n\nExample: `enhancers: (defaultEnhancers) => defaultEnhancers.prepend(offline)` will result in a final setup\nof `[offline, applyMiddleware, devToolsExtension]`.\n\nFor more details on how the `enhancers` parameter works and the list of enhancers that are added by default, see the [`getDefaultEnhancers` docs page](./getDefaultEnhancers).\n\n:::caution Middleware\n\nIf you don't use `getDefaultEnhancers` and instead return an array, the `applyMiddleware` enhancer will _not_ be used.\n\n`configureStore` will warn in console if any middleware are provided (or left as default) but not included in the final list of enhancers.\n\n```ts no-transpile\n// warns - middleware customised but not included in final enhancers\nconfigureStore({\n  reducer,\n  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),\n  enhancers: [offline(offlineConfig)],\n})\n\n// fine - default enhancers included\nconfigureStore({\n  reducer,\n  enhancers: (getDefaultEnhancers) => getDefaultEnhancers().concat(offline(offlineConfig)),\n})\n\n// also allowed\nconfigureStore({\n  reducer,\n  middleware: () => [],\n  enhancers: () => [offline(offlineConfig)],\n})\n```\n\nNote that if using TypeScript, the `middleware` option is required to be provided _before_ the enhancer option, as the type of `getDefaultEnhancers` depends on its result.\n\n:::\n\n:::note Tuple\nTypeScript users are required to use a `Tuple` instance (if not using a `getDefaultEnhancers` result, which is already a `Tuple`), for better inference.\n\n```ts no-transpile\nimport { configureStore, Tuple } from '@reduxjs/toolkit'\n\nconfigureStore({\n  reducer: rootReducer,\n  enhancers: () => new Tuple(offline),\n})\n```\n\nJavascript-only users are free to use a plain array if preferred.\n\n:::\n\n## Usage\n\n### Basic Example\n\n```ts\n// file: reducers.ts noEmit\nimport type { Reducer } from '@reduxjs/toolkit'\ndeclare const rootReducer: Reducer<{}>\nexport default rootReducer\n\n// file: store.ts\nimport { configureStore } from '@reduxjs/toolkit'\n\nimport rootReducer from './reducers'\n\nconst store = configureStore({ reducer: rootReducer })\n// The store now has redux-thunk added and the Redux DevTools Extension is turned on\n```\n\n### Full Example\n\n```ts no-transpile\n// file: todos/todosReducer.ts noEmit\nimport type { Reducer } from '@reduxjs/toolkit'\ndeclare const reducer: Reducer<{}>\nexport default reducer\n\n// file: visibility/visibilityReducer.ts noEmit\nimport type { Reducer } from '@reduxjs/toolkit'\ndeclare const reducer: Reducer<{}>\nexport default reducer\n\n// file: store.ts\nimport { configureStore } from '@reduxjs/toolkit'\n\n// We'll use redux-logger just as an example of adding another middleware\nimport logger from 'redux-logger'\n\n// And use redux-batched-subscribe as an example of adding enhancers\nimport { batchedSubscribe } from 'redux-batched-subscribe'\n\nimport todosReducer from './todos/todosReducer'\nimport visibilityReducer from './visibility/visibilityReducer'\n\nconst reducer = {\n  todos: todosReducer,\n  visibility: visibilityReducer,\n}\n\nconst preloadedState = {\n  todos: [\n    {\n      text: 'Eat food',\n      completed: true,\n    },\n    {\n      text: 'Exercise',\n      completed: false,\n    },\n  ],\n  visibilityFilter: 'SHOW_COMPLETED',\n}\n\nconst debounceNotify = _.debounce((notify) => notify())\n\nconst store = configureStore({\n  reducer,\n  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),\n  devTools: process.env.NODE_ENV !== 'production',\n  preloadedState,\n  enhancers: (getDefaultEnhancers) =>\n    getDefaultEnhancers({\n      autoBatch: false,\n    }).concat(batchedSubscribe(debounceNotify)),\n})\n\n// The store has been created with these options:\n// - The slice reducers were automatically passed to combineReducers()\n// - redux-thunk and redux-logger were added as middleware\n// - The Redux DevTools Extension is disabled for production\n// - The middleware, batched subscribe, and devtools enhancers were composed together\n```\n"
  },
  {
    "path": "docs/api/createAction.mdx",
    "content": "---\nid: createAction\ntitle: createAction\nsidebar_label: createAction\nhide_title: true\n---\n\n&nbsp;\n\n# `createAction`\n\nA helper function for defining a Redux [action](https://redux.js.org/basics/actions) type and creator.\n\n```js\nfunction createAction(type, prepareAction?)\n```\n\nThe usual way to define an action in Redux is to separately declare an _action type_ constant and an _action creator_ function for constructing actions of that type.\n\n```ts\nconst INCREMENT = 'counter/increment'\n\nfunction increment(amount: number) {\n  return {\n    type: INCREMENT,\n    payload: amount,\n  }\n}\n\nconst action = increment(3)\n// { type: 'counter/increment', payload: 3 }\n```\n\nThe `createAction` helper combines these two declarations into one. It takes an action type and returns an action creator for that type. The action creator can be called either without arguments or with a `payload` to be attached to the action.\n\n```ts\nimport { createAction } from '@reduxjs/toolkit'\n\nconst increment = createAction<number | undefined>('counter/increment')\n\nlet action = increment()\n// { type: 'counter/increment' }\n\naction = increment(3)\n// returns { type: 'counter/increment', payload: 3 }\n\nconsole.log(`The action type is: ${increment.type}`)\n// 'The action type is: counter/increment'\n```\n\n## Using Prepare Callbacks to Customize Action Contents\n\nBy default, the generated action creators accept a single argument, which becomes `action.payload`. This requires the caller to construct the entire payload correctly and pass it in.\n\nIn many cases, you may want to write additional logic to customize the creation of the `payload` value, such as accepting multiple parameters for the action creator, generating a random ID, or getting the current timestamp. To do this, `createAction` accepts an optional second argument: a \"prepare callback\" that will be used to construct the payload value.\n\n```ts\nimport { createAction, nanoid } from '@reduxjs/toolkit'\n\nconst addTodo = createAction('todos/add', function prepare(text: string) {\n  return {\n    payload: {\n      text,\n      id: nanoid(),\n      createdAt: new Date().toISOString(),\n    },\n  }\n})\n\nconsole.log(addTodo('Write more docs'))\n/**\n * {\n *   type: 'todos/add',\n *   payload: {\n *     text: 'Write more docs',\n *     id: '4AJvwMSWEHCchcWYga3dj',\n *     createdAt: '2019-10-03T07:53:36.581Z'\n *   }\n * }\n **/\n```\n\nIf provided, all arguments from the action creator will be passed to the prepare callback, and it should return an object with the `payload` field (otherwise the payload of created actions will be `undefined`). Additionally, the object can have a `meta` and/or an `error` field that will also be added to created actions. `meta` may contain extra information about the action, `error` may contain details about the action failure. These three fields (`payload`, `meta` and `error`) adhere to the specification of [Flux Standard Actions](https://github.com/redux-utilities/flux-standard-action#actions).\n\n**Note:** The type field will be added automatically.\n\n## Usage with createReducer()\n\nAction creators can be passed directly to `addCase` in a [createReducer()](createReducer.mdx) build callback.\n\n```ts\nimport { createAction, createReducer } from '@reduxjs/toolkit'\n\nconst increment = createAction<number>('counter/increment')\nconst decrement = createAction<number>('counter/decrement')\n\nconst counterReducer = createReducer(0, (builder) => {\n  builder.addCase(increment, (state, action) => state + action.payload)\n  builder.addCase(decrement, (state, action) => state - action.payload)\n})\n```\n\n:::warning Non-String Action Types\nAs of Redux 5.0, action types are _required_ to be strings. An error will be thrown by the store if a non-string action type reaches the original store dispatch.\n:::\n\n## actionCreator.match\n\nEvery generated actionCreator has a `.match(action)` method that can be used to determine if the passed action is of the same type as an action that would be created by the action creator.\n\nThis has different uses:\n\n### As a TypeScript Type Guard\n\nThis `match` method is a [TypeScript type guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates) and can be used to discriminate the `payload` type of an action.\n\nThis behavior can be particularly useful when used in custom middlewares, where manual casts might be necessary otherwise.\n\n```ts\nimport { createAction } from '@reduxjs/toolkit'\nimport type { Action } from '@reduxjs/toolkit'\n\nconst increment = createAction<number>('INCREMENT')\n\nfunction someFunction(action: Action) {\n  // accessing action.payload would result in an error here\n  if (increment.match(action)) {\n    // action.payload can be used as `number` here\n  }\n}\n```\n\n### With redux-observable\n\nThe `match` method can also be used as a filter method, which makes it powerful when used with redux-observable:\n\n```ts\nimport { createAction } from '@reduxjs/toolkit'\nimport type { Action } from '@reduxjs/toolkit'\nimport type { Observable } from 'rxjs'\nimport { map, filter } from 'rxjs/operators'\n\nconst increment = createAction<number>('INCREMENT')\n\nexport const epic = (actions$: Observable<Action>) =>\n  actions$.pipe(\n    filter(increment.match),\n    map((action) => {\n      // action.payload can be safely used as number here (and will also be correctly inferred by TypeScript)\n      // ...\n    }),\n  )\n```\n"
  },
  {
    "path": "docs/api/createAsyncThunk.mdx",
    "content": "---\nid: createAsyncThunk\ntitle: createAsyncThunk\nsidebar_label: createAsyncThunk\nhide_title: true\n---\n\n&nbsp;\n\n# `createAsyncThunk`\n\n## Overview\n\nA function that accepts a Redux action type string and a callback function that should return a promise. It generates promise lifecycle action types based on the action type prefix that you pass in, and returns a thunk action creator that will run the promise callback and dispatch the lifecycle actions based on the returned promise.\n\nThis abstracts the standard recommended approach for handling async request lifecycles.\n\nIt does not generate any reducer functions, since it does not know what data you're fetching, how you want to track loading state, or how the data you return needs to be processed. You should write your own reducer logic that handles these actions, with whatever loading state and processing logic is appropriate for your own app.\n\n:::tip\n\nRedux Toolkit's [**RTK Query data fetching API**](../rtk-query/overview.md) is a purpose built data fetching and caching solution for Redux apps, and can **eliminate the need to write _any_ thunks or reducers to manage data fetching**. We encourage you to try it out and see if it can help simplify the data fetching code in your own apps!\n\n:::\n\nSample usage:\n\n```ts no-transpile {5-11,22-25,30}\nimport { createAsyncThunk, createSlice } from '@reduxjs/toolkit'\nimport { userAPI } from './userAPI'\n\n// First, create the thunk\nconst fetchUserById = createAsyncThunk(\n  'users/fetchByIdStatus',\n  async (userId: number, thunkAPI) => {\n    const response = await userAPI.fetchById(userId)\n    return response.data\n  },\n)\n\ninterface UsersState {\n  entities: User[]\n  loading: 'idle' | 'pending' | 'succeeded' | 'failed'\n}\n\nconst initialState = {\n  entities: [],\n  loading: 'idle',\n} satisfies UserState as UsersState\n\n// Then, handle actions in your reducers:\nconst usersSlice = createSlice({\n  name: 'users',\n  initialState,\n  reducers: {\n    // standard reducer logic, with auto-generated action types per reducer\n  },\n  extraReducers: (builder) => {\n    // Add reducers for additional action types here, and handle loading state as needed\n    builder.addCase(fetchUserById.fulfilled, (state, action) => {\n      // Add user to the state array\n      state.entities.push(action.payload)\n    })\n  },\n})\n\n// Later, dispatch the thunk as needed in the app\ndispatch(fetchUserById(123))\n```\n\n## Parameters\n\n`createAsyncThunk` accepts three parameters: a string action `type` value, a `payloadCreator` callback, and an `options` object.\n\n### `type`\n\nA string that will be used to generate additional Redux action type constants, representing the lifecycle of an async request:\n\nFor example, a `type` argument of `'users/requestStatus'` will generate these action types:\n\n- `pending`: `'users/requestStatus/pending'`\n- `fulfilled`: `'users/requestStatus/fulfilled'`\n- `rejected`: `'users/requestStatus/rejected'`\n\n### `payloadCreator`\n\nA callback function that should return a promise containing the result of some asynchronous logic. It may also return a value synchronously. If there is an error, it should either return a rejected promise containing an `Error` instance or a plain value such as a descriptive error message or otherwise a resolved promise with a `RejectWithValue` argument as returned by the `thunkAPI.rejectWithValue` function.\n\nThe `payloadCreator` function can contain whatever logic you need to calculate an appropriate result. This could include a standard AJAX data fetch request, multiple AJAX calls with the results combined into a final value, interactions with React Native `AsyncStorage`, and so on.\n\nThe `payloadCreator` function will be called with two arguments:\n\n- `arg`: a single value, containing the first parameter that was passed to the thunk action creator when it was dispatched. This is useful for passing in values like item IDs that may be needed as part of the request. If you need to pass in multiple values, pass them together in an object when you dispatch the thunk, like `dispatch(fetchUsers({status: 'active', sortBy: 'name'}))`.\n- `thunkAPI`: an object containing all of the parameters that are normally passed to a Redux thunk function, as well as additional options:\n  - `dispatch`: the Redux store `dispatch` method\n  - `getState`: the Redux store `getState` method\n  - `extra`: the \"extra argument\" given to the thunk middleware on setup, if available\n  - `requestId`: a unique string ID value that was automatically generated to identify this request sequence\n  - `signal`: an [`AbortController.signal` object](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/signal) that may be used to see if another part of the app logic has marked this request as needing cancelation.\n  - `rejectWithValue(value, [meta])`: rejectWithValue is a utility function that you can `return` (or `throw`) in your action creator to return a rejected response with a defined payload and meta. It will pass whatever value you give it and return it in the payload of the rejected action. If you also pass in a `meta`, it will be merged with the existing `rejectedAction.meta`.\n  - `fulfillWithValue(value, meta)`: fulfillWithValue is a utility function that you can `return` in your action creator to `fulfill` with a value while having the ability of adding to `fulfilledAction.meta`.\n\nThe logic in the `payloadCreator` function may use any of these values as needed to calculate the result.\n\n### Options\n\nAn object with the following optional fields:\n\n- `condition(arg, { getState, extra } ): boolean | Promise<boolean>`: a callback that can be used to skip execution of the payload creator and all action dispatches, if desired. See [Canceling Before Execution](#canceling-before-execution) for a complete description.\n- `dispatchConditionRejection`: if `condition()` returns `false`, the default behavior is that no actions will be dispatched at all. If you still want a \"rejected\" action to be dispatched when the thunk was canceled, set this flag to `true`.\n- `idGenerator(arg): string`: a function to use when generating the `requestId` for the request sequence. Defaults to use [nanoid](./otherExports.mdx#nanoid), but you can implement your own ID generation logic.\n- `serializeError(error: unknown) => any` to replace the internal `miniSerializeError` method with your own serialization logic.\n- `getPendingMeta({ arg, requestId }, { getState, extra }): any`: a function to create an object that will be merged into the `pendingAction.meta` field.\n\n## Return Value\n\n`createAsyncThunk` returns a standard Redux thunk action creator. The thunk action creator function will have plain action creators for the `pending`, `fulfilled`, and `rejected` cases attached as nested fields.\n\nUsing the `fetchUserById` example above, `createAsyncThunk` will generate four functions:\n\n- `fetchUserById`, the thunk action creator that kicks off the async payload callback you wrote\n  - `fetchUserById.pending`, an action creator that dispatches an `'users/fetchByIdStatus/pending'` action\n  - `fetchUserById.fulfilled`, an action creator that dispatches an `'users/fetchByIdStatus/fulfilled'` action\n  - `fetchUserById.rejected`, an action creator that dispatches an `'users/fetchByIdStatus/rejected'` action\n\nWhen dispatched, the thunk will:\n\n- dispatch the `pending` action\n- call the `payloadCreator` callback and wait for the returned promise to settle\n- when the promise settles:\n  - if the promise resolved successfully, dispatch the `fulfilled` action with the promise value as `action.payload`\n  - if the promise resolved with a `rejectWithValue(value)` return value, dispatch the `rejected` action with the value passed into `action.payload` and 'Rejected' as `action.error.message`\n  - if the promise failed and was not handled with `rejectWithValue`, dispatch the `rejected` action with a serialized version of the error value as `action.error`\n- Return a fulfilled promise containing the final dispatched action (either the `fulfilled` or `rejected` action object)\n\n## Thunk Dispatch Options\n\nThe returned thunk action creator accepts an optional second argument with the following options:\n\n- `signal`: an optional [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) that will be tracked by the internal abort signal (see [Canceling While Running](#canceling-while-running))\n\n```ts no-transpile\nconst externalController = new AbortController()\ndispatch(fetchUserById(123, { signal: externalController.signal }))\nexternalController.abort()\n```\n\n## Promise Lifecycle Actions\n\n`createAsyncThunk` will generate three Redux action creators using [`createAction`](./createAction.mdx): `pending`, `fulfilled`, and `rejected`. Each lifecycle action creator will be attached to the returned thunk action creator so that your reducer logic can reference the action types and respond to the actions when dispatched. Each action object will contain the current unique `requestId` and `arg` values under `action.meta`.\n\nThe action creators will have these signatures:\n\n```ts no-transpile\ninterface SerializedError {\n  name?: string\n  message?: string\n  code?: string\n  stack?: string\n}\n\ninterface PendingAction<ThunkArg> {\n  type: string\n  payload: undefined\n  meta: {\n    requestId: string\n    arg: ThunkArg\n  }\n}\n\ninterface FulfilledAction<ThunkArg, PromiseResult> {\n  type: string\n  payload: PromiseResult\n  meta: {\n    requestId: string\n    arg: ThunkArg\n  }\n}\n\ninterface RejectedAction<ThunkArg> {\n  type: string\n  payload: undefined\n  error: SerializedError | any\n  meta: {\n    requestId: string\n    arg: ThunkArg\n    aborted: boolean\n    condition: boolean\n  }\n}\n\ninterface RejectedWithValueAction<ThunkArg, RejectedValue> {\n  type: string\n  payload: RejectedValue\n  error: { message: 'Rejected' }\n  meta: {\n    requestId: string\n    arg: ThunkArg\n    aborted: boolean\n  }\n}\n\ntype Pending = <ThunkArg>(\n  requestId: string,\n  arg: ThunkArg,\n) => PendingAction<ThunkArg>\n\ntype Fulfilled = <ThunkArg, PromiseResult>(\n  payload: PromiseResult,\n  requestId: string,\n  arg: ThunkArg,\n) => FulfilledAction<ThunkArg, PromiseResult>\n\ntype Rejected = <ThunkArg>(\n  requestId: string,\n  arg: ThunkArg,\n) => RejectedAction<ThunkArg>\n\ntype RejectedWithValue = <ThunkArg, RejectedValue>(\n  requestId: string,\n  arg: ThunkArg,\n) => RejectedWithValueAction<ThunkArg, RejectedValue>\n```\n\nTo handle these actions in your reducers, reference the action creators in `createReducer` or `createSlice` using the \"builder callback\" notation.\n\n```ts no-transpile {2,10}\nconst reducer1 = createReducer(initialState, (builder) => {\n  builder.addCase(fetchUserById.fulfilled, (state, action) => {})\n})\n\nconst reducer2 = createSlice({\n  name: 'users',\n  initialState,\n  reducers: {},\n  extraReducers: (builder) => {\n    builder.addCase(fetchUserById.fulfilled, (state, action) => {})\n  },\n})\n```\n\nAdditionally, a `settled` matcher is attached, for matching against both fulfilled and rejected actions. Conceptually this is similar to a `finally` block.\n\nMake sure you use `addMatcher` instead of `addCase`, since `settled` is a matcher rather than an action creator.\n\n```ts no-transpile {2,10}\nconst reducer1 = createReducer(initialState, (builder) => {\n  builder.addMatcher(fetchUserById.settled, (state, action) => {})\n})\n\nconst reducer2 = createSlice({\n  name: 'users',\n  initialState,\n  reducers: {},\n  extraReducers: (builder) => {\n    builder.addMatcher(fetchUserById.settled, (state, action) => {})\n  },\n})\n```\n\n## Handling Thunk Results\n\n### Unwrapping Result Actions\n\nThunks may return a value when dispatched. A common use case is to return a promise from the thunk, dispatch the thunk from a component, and then wait for the promise to resolve before doing additional work:\n\n```ts no-transpile\nconst onClick = () => {\n  dispatch(fetchUserById(userId)).then(() => {\n    // do additional work\n  })\n}\n```\n\nThe thunks generated by `createAsyncThunk` **will always return a resolved promise** with either the `fulfilled` action object or `rejected` action object inside, as appropriate.\n\nThe calling logic may wish to treat these actions as if they were the original promise contents. The promise returned by the dispatched thunk has an `unwrap` property which can be called to extract the `payload` of a `fulfilled` action or to throw either the `error` or, if available, `payload` created by `rejectWithValue` from a `rejected` action:\n\n```ts no-transpile\n// in the component\n\nconst onClick = () => {\n  dispatch(fetchUserById(userId))\n    .unwrap()\n    .then((originalPromiseResult) => {\n      // handle result here\n    })\n    .catch((rejectedValueOrSerializedError) => {\n      // handle error here\n    })\n}\n```\n\nOr with async/await syntax:\n\n```ts no-transpile\n// in the component\n\nconst onClick = async () => {\n  try {\n    const originalPromiseResult = await dispatch(fetchUserById(userId)).unwrap()\n    // handle result here\n  } catch (rejectedValueOrSerializedError) {\n    // handle error here\n  }\n}\n```\n\nUsing the attached `.unwrap()` property is preferred in most cases, however Redux Toolkit also exports an `unwrapResult` function that can be used for a similar purpose:\n\n```ts no-transpile\nimport { unwrapResult } from '@reduxjs/toolkit'\n\n// in the component\nconst onClick = () => {\n  dispatch(fetchUserById(userId))\n    .then(unwrapResult)\n    .then((originalPromiseResult) => {\n      // handle result here\n    })\n    .catch((rejectedValueOrSerializedError) => {\n      // handle result here\n    })\n}\n```\n\nOr with async/await syntax:\n\n```ts no-transpile\nimport { unwrapResult } from '@reduxjs/toolkit'\n\n// in the component\nconst onClick = async () => {\n  try {\n    const resultAction = await dispatch(fetchUserById(userId))\n    const originalPromiseResult = unwrapResult(resultAction)\n    // handle result here\n  } catch (rejectedValueOrSerializedError) {\n    // handle error here\n  }\n}\n```\n\n### Checking Errors After Dispatching\n\nNote that this means **a failed request or error in a thunk will _never_ return a _rejected_ promise**. We assume that any failure is more of a handled error than an unhandled exception at this point. This is due to the fact that we want to prevent uncaught promise rejections for those who do not use the result of `dispatch`.\n\nIf your component needs to know if the request failed, use `.unwrap` or `unwrapResult` and handle the re-thrown error accordingly.\n\n## Handling Thunk Errors\n\nWhen your `payloadCreator` returns a rejected promise (such as a thrown error in an `async` function), the thunk will dispatch a `rejected` action containing an automatically-serialized version of the error as `action.error`. However, to ensure serializability, everything that does not match the `SerializedError` interface will have been removed from it:\n\n```ts no-transpile\nexport interface SerializedError {\n  name?: string\n  message?: string\n  stack?: string\n  code?: string\n}\n```\n\nIf you need to customize the contents of the `rejected` action, you should catch any errors yourself, and then **return** a new value using the `thunkAPI.rejectWithValue` utility. Doing `return rejectWithValue(errorPayload)` will cause the `rejected` action to use that value as `action.payload`.\n\nThe `rejectWithValue` approach should also be used if your API response \"succeeds\", but contains some kind of additional error details that the reducer should know about. This is particularly common when expecting field-level validation errors from an API.\n\n```ts no-transpile\nconst updateUser = createAsyncThunk(\n  'users/update',\n  async (userData, { rejectWithValue }) => {\n    const { id, ...fields } = userData\n    try {\n      const response = await userAPI.updateById(id, fields)\n      return response.data.user\n    } catch (err) {\n      // Use `err.response.data` as `action.payload` for a `rejected` action,\n      // by explicitly returning it using the `rejectWithValue()` utility\n      return rejectWithValue(err.response.data)\n    }\n  },\n)\n```\n\n## Cancellation\n\n### Canceling Before Execution\n\nIf you need to cancel a thunk before the payload creator is called, you may provide a `condition` callback as an option after the payload creator. The callback will receive the thunk argument and an object with `{getState, extra}` as parameters, and use those to decide whether to continue or not. If the execution should be canceled, the `condition` callback should return a literal `false` value or a promise that should resolve to `false`. If a promise is returned, the thunk waits for it to get fulfilled before dispatching the `pending` action, otherwise it proceeds with dispatching synchronously.\n\n```ts no-transpile\nconst fetchUserById = createAsyncThunk(\n  'users/fetchByIdStatus',\n  async (userId: number, thunkAPI) => {\n    const response = await userAPI.fetchById(userId)\n    return response.data\n  },\n  {\n    condition: (userId, { getState, extra }) => {\n      const { users } = getState()\n      const fetchStatus = users.requests[userId]\n      if (fetchStatus === 'fulfilled' || fetchStatus === 'loading') {\n        // Already fetched or in progress, don't need to re-fetch\n        return false\n      }\n    },\n  },\n)\n```\n\nIf `condition()` returns `false`, the default behavior is that no actions will be dispatched at all. If you still want a \"rejected\" action to be dispatched when the thunk was canceled, pass in `{condition, dispatchConditionRejection: true}`.\n\n### Canceling While Running\n\nIf you want to cancel your running thunk before it has finished, you can use the `abort` method of the promise returned by `dispatch(fetchUserById(userId))`.\n\nA real-life example of that would look like this:\n\n```ts no-transpile\n// file: store.ts noEmit\nimport { configureStore } from '@reduxjs/toolkit'\nimport type { Reducer } from '@reduxjs/toolkit'\nimport { useDispatch } from 'react-redux'\n\ndeclare const reducer: Reducer<{}>\nconst store = configureStore({ reducer })\nexport const useAppDispatch = () => useDispatch<typeof store.dispatch>()\n\n// file: slice.ts noEmit\nimport { createAsyncThunk } from '@reduxjs/toolkit'\nexport const fetchUserById = createAsyncThunk(\n  'fetchUserById',\n  (userId: string) => {\n    /* ... */\n  },\n)\n\n// file: MyComponent.ts\nimport { fetchUserById } from './slice'\nimport { useAppDispatch } from './store'\nimport React from 'react'\n\nfunction MyComponent(props: { userId: string }) {\n  const dispatch = useAppDispatch()\n  React.useEffect(() => {\n    // Dispatching the thunk returns a promise\n    const promise = dispatch(fetchUserById(props.userId))\n    return () => {\n      // `createAsyncThunk` attaches an `abort()` method to the promise\n      promise.abort()\n    }\n  }, [props.userId])\n}\n```\n\nAfter a thunk has been cancelled this way, it will dispatch (and return) a `\"thunkName/rejected\"` action with an `AbortError` on the `error` property. The thunk will not dispatch any further actions.\n\nAdditionally, your `payloadCreator` can use the `AbortSignal` it is passed via `thunkAPI.signal` to actually cancel a costly asynchronous action.\n\nThe `fetch` api of modern browsers already comes with support for an `AbortSignal`:\n\n```ts no-transpile\nimport { createAsyncThunk } from '@reduxjs/toolkit'\n\nconst fetchUserById = createAsyncThunk(\n  'users/fetchById',\n  async (userId: string, thunkAPI) => {\n    const response = await fetch(`https://reqres.in/api/users/${userId}`, {\n      signal: thunkAPI.signal,\n    })\n    return await response.json()\n  },\n)\n```\n\n### Checking Cancellation Status\n\n### Reading the Signal Value\n\nYou can use the `signal.aborted` property to regularly check if the thunk has been aborted and in that case stop costly long-running work:\n\n```ts no-transpile\nimport { createAsyncThunk } from '@reduxjs/toolkit'\n\nconst readStream = createAsyncThunk(\n  'readStream',\n  async (stream: ReadableStream, { signal }) => {\n    const reader = stream.getReader()\n\n    let done = false\n    let result = ''\n\n    while (!done) {\n      if (signal.aborted) {\n        throw new Error('stop the work, this has been aborted!')\n      }\n      const read = await reader.read()\n      result += read.value\n      done = read.done\n    }\n    return result\n  },\n)\n```\n\n#### Listening for Abort Events\n\nYou can also call `signal.addEventListener('abort', callback)` to have logic inside the thunk be notified when `promise.abort()` was called.\nThis can for example be used in conjunction with an axios `CancelToken`:\n\n```ts no-transpile\nimport { createAsyncThunk } from '@reduxjs/toolkit'\nimport axios from 'axios'\n\nconst fetchUserById = createAsyncThunk(\n  'users/fetchById',\n  async (userId: string, { signal }) => {\n    const source = axios.CancelToken.source()\n    signal.addEventListener('abort', () => {\n      source.cancel()\n    })\n    const response = await axios.get(`https://reqres.in/api/users/${userId}`, {\n      cancelToken: source.token,\n    })\n    return response.data\n  },\n)\n```\n\n### Checking if a Promise Rejection was from an Error or Cancellation\n\nTo investigate behavior around thunk cancellation, you can inspect various properties on the `meta` object of the dispatched action.\nIf a thunk was cancelled, the result of the promise will be a `rejected` action (regardless of whether that action was actually dispatched to the store).\n\n- If it was cancelled before execution, `meta.condition` will be true.\n- If it was aborted while running, `meta.aborted` will be true.\n- If neither of those is true, the thunk was not cancelled, it was simply rejected, either by a Promise rejection or `rejectWithValue`.\n- If the thunk was not rejected, both `meta.aborted` and `meta.condition` will be `undefined`.\n\nSo if you wanted to test that a thunk was cancelled before executing, you can do the following:\n\n```ts no-transpile\nimport { createAsyncThunk } from '@reduxjs/toolkit'\n\ntest('this thunk should always be skipped', async () => {\n  const thunk = createAsyncThunk(\n    'users/fetchById',\n    async () => throw new Error('This promise should never be entered'),\n    {\n      condition: () => false,\n    }\n  )\n  const result = await thunk()(dispatch, getState, null)\n\n  expect(result.meta.condition).toBe(true)\n  expect(result.meta.aborted).toBe(false)\n})\n```\n\n## Examples\n\n- Requesting a user by ID, with loading state, and only one request at a time:\n\n```ts no-transpile\nimport { createAsyncThunk, createSlice } from '@reduxjs/toolkit'\nimport { userAPI, User } from './userAPI'\n\nconst fetchUserById = createAsyncThunk<\n  User,\n  string,\n  {\n    state: { users: { loading: string; currentRequestId: string } }\n  }\n>('users/fetchByIdStatus', async (userId: string, { getState, requestId }) => {\n  const { currentRequestId, loading } = getState().users\n  if (loading !== 'pending' || requestId !== currentRequestId) {\n    return\n  }\n  const response = await userAPI.fetchById(userId)\n  return response.data\n})\n\nconst usersSlice = createSlice({\n  name: 'users',\n  initialState: {\n    entities: [],\n    loading: 'idle',\n    currentRequestId: undefined,\n    error: null,\n  },\n  reducers: {},\n  extraReducers: (builder) => {\n    builder\n      .addCase(fetchUserById.pending, (state, action) => {\n        if (state.loading === 'idle') {\n          state.loading = 'pending'\n          state.currentRequestId = action.meta.requestId\n        }\n      })\n      .addCase(fetchUserById.fulfilled, (state, action) => {\n        const { requestId } = action.meta\n        if (\n          state.loading === 'pending' &&\n          state.currentRequestId === requestId\n        ) {\n          state.loading = 'idle'\n          state.entities.push(action.payload)\n          state.currentRequestId = undefined\n        }\n      })\n      .addCase(fetchUserById.rejected, (state, action) => {\n        const { requestId } = action.meta\n        if (\n          state.loading === 'pending' &&\n          state.currentRequestId === requestId\n        ) {\n          state.loading = 'idle'\n          state.error = action.error\n          state.currentRequestId = undefined\n        }\n      })\n  },\n})\n\nconst UsersComponent = () => {\n  const { entities, loading, error } = useSelector((state) => state.users)\n  const dispatch = useDispatch()\n\n  const fetchOneUser = async (userId) => {\n    try {\n      const user = await dispatch(fetchUserById(userId)).unwrap()\n      showToast('success', `Fetched ${user.name}`)\n    } catch (err) {\n      showToast('error', `Fetch failed: ${err.message}`)\n    }\n  }\n\n  // render UI here\n}\n```\n\n- Using rejectWithValue to access a custom rejected payload in a component\n\n  _Note: this is a contrived example assuming our userAPI only ever throws validation-specific errors_\n\n```ts no-transpile\n// file: store.ts noEmit\nimport { configureStore } from '@reduxjs/toolkit'\nimport type { Reducer } from '@reduxjs/toolkit'\nimport { useDispatch } from 'react-redux'\nimport usersReducer from './user/slice'\n\nconst store = configureStore({ reducer: { users: usersReducer } })\nexport const useAppDispatch = () => useDispatch<typeof store.dispatch>()\nexport type RootState = ReturnType<typeof store.getState>\n\n// file: user/userAPI.ts noEmit\n\nexport declare const userAPI: {\n  updateById<Response>(id: string, fields: {}): { data: Response }\n}\n\n// file: user/slice.ts\nimport { createAsyncThunk, createSlice } from '@reduxjs/toolkit'\nimport { userAPI } from './userAPI'\nimport type { AxiosError } from 'axios'\n\n// Sample types that will be used\nexport interface User {\n  id: string\n  first_name: string\n  last_name: string\n  email: string\n}\n\ninterface ValidationErrors {\n  errorMessage: string\n  field_errors: Record<string, string>\n}\n\ninterface UpdateUserResponse {\n  user: User\n  success: boolean\n}\n\nexport const updateUser = createAsyncThunk<\n  User,\n  { id: string } & Partial<User>,\n  {\n    rejectValue: ValidationErrors\n  }\n>('users/update', async (userData, { rejectWithValue }) => {\n  try {\n    const { id, ...fields } = userData\n    const response = await userAPI.updateById<UpdateUserResponse>(id, fields)\n    return response.data.user\n  } catch (err) {\n    let error: AxiosError<ValidationErrors> = err // cast the error for access\n    if (!error.response) {\n      throw err\n    }\n    // We got validation errors, let's return those so we can reference in our component and set form errors\n    return rejectWithValue(error.response.data)\n  }\n})\n\ninterface UsersState {\n  error: string | null | undefined\n  entities: Record<string, User>\n}\n\nconst initialState = {\n  entities: {},\n  error: null,\n} satisfies UsersState as UsersState\n\nconst usersSlice = createSlice({\n  name: 'users',\n  initialState,\n  reducers: {},\n  extraReducers: (builder) => {\n    // The `builder` callback form is used here because it provides correctly typed reducers from the action creators\n    builder.addCase(updateUser.fulfilled, (state, { payload }) => {\n      state.entities[payload.id] = payload\n    })\n    builder.addCase(updateUser.rejected, (state, action) => {\n      if (action.payload) {\n        // Being that we passed in ValidationErrors to rejectType in `createAsyncThunk`, the payload will be available here.\n        state.error = action.payload.errorMessage\n      } else {\n        state.error = action.error.message\n      }\n    })\n  },\n})\n\nexport default usersSlice.reducer\n\n// file: externalModules.d.ts noEmit\n\ndeclare module 'some-toast-library' {\n  export function showToast(type: string, message: string)\n}\n\n// file: user/UsersComponent.ts\n\nimport React from 'react'\nimport { useAppDispatch } from '../store'\nimport type { RootState } from '../store'\nimport { useSelector } from 'react-redux'\nimport { updateUser } from './slice'\nimport type { User } from './slice'\nimport type { FormikHelpers } from 'formik'\nimport { showToast } from 'some-toast-library'\n\ninterface FormValues extends Omit<User, 'id'> {}\n\nconst UsersComponent = (props: { id: string }) => {\n  const { entities, error } = useSelector((state: RootState) => state.users)\n  const dispatch = useAppDispatch()\n\n  // This is an example of an onSubmit handler using Formik meant to demonstrate accessing the payload of the rejected action\n  const handleUpdateUser = async (\n    values: FormValues,\n    formikHelpers: FormikHelpers<FormValues>,\n  ) => {\n    const resultAction = await dispatch(updateUser({ id: props.id, ...values }))\n    if (updateUser.fulfilled.match(resultAction)) {\n      // user will have a type signature of User as we passed that as the Returned parameter in createAsyncThunk\n      const user = resultAction.payload\n      showToast('success', `Updated ${user.first_name} ${user.last_name}`)\n    } else {\n      if (resultAction.payload) {\n        // Being that we passed in ValidationErrors to rejectType in `createAsyncThunk`, those types will be available here.\n        formikHelpers.setErrors(resultAction.payload.field_errors)\n      } else {\n        showToast('error', `Update failed: ${resultAction.error}`)\n      }\n    }\n  }\n\n  // render UI here\n}\n```\n"
  },
  {
    "path": "docs/api/createDynamicMiddleware.mdx",
    "content": "---\nid: createDynamicMiddleware\ntitle: createDynamicMiddleware\nsidebar_label: createDynamicMiddleware\nhide_title: true\n---\n\n&nbsp;\n\n# `createDynamicMiddleware`\n\n## Overview\n\nA \"meta-middleware\" that allows adding middleware to the dispatch chain after store initialisation.\n\n## Instance Creation\n\n```ts no-transpile\nimport { createDynamicMiddleware, configureStore } from '@reduxjs/toolkit'\n\nconst dynamicMiddleware = createDynamicMiddleware()\n\nconst store = configureStore({\n  reducer: {\n    todos: todosReducer,\n  },\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().prepend(dynamicMiddleware.middleware),\n})\n```\n\n:::tip\n\nIt's possible to pass two type parameters to `createDynamicMiddleware`, `State` and `Dispatch`.\n\nThese are used by methods that receive middleware to ensure that the provided middleware are compatible with the types provided.\n\n```ts no-transpile\nconst dynamicMiddleware = createDynamicMiddleware<State, Dispatch>()\n```\n\nHowever, if these values are derived from the store (as they should be), a circular type dependency is formed.\n\nAs a result, it's better to use the `withTypes` helper attached to `addMiddleware`, `withMiddleware` and `createDispatchWithMiddlewareHook`.\n\n```ts no-transpile\nimport { createDynamicMiddleware } from '@reduxjs/toolkit/react'\nimport type { RootState, AppDispatch } from './store'\n\nconst dynamicMiddleware = createDynamicMiddleware()\n\nconst {\n  middleware,\n  addMiddleware,\n  withMiddleware,\n  createDispatchWithMiddlewareHook,\n} = dynamicMiddleware\n\ninterface MiddlewareApiConfig {\n  state: RootState\n  dispatch: AppDispatch\n}\n\nexport const addAppMiddleware = addMiddleware.withTypes<MiddlewareApiConfig>()\n\nexport const withAppMiddleware = withMiddleware.withTypes<MiddlewareApiConfig>()\n\nexport const createAppDispatchWithMiddlewareHook =\n  createDispatchWithMiddlewareHook.withTypes<MiddlewareApiConfig>()\n\nexport default middleware\n```\n\n:::\n\n## Dynamic Middleware Instance\n\nThe \"dynamic middleware instance\" returned from `createDynamicMiddleware` is an object similar to the object generated by `createListenerMiddleware`. The instance object is _not_ the actual Redux middleware itself. Rather, it contains the middleware and some instance methods used to add middleware to the chain.\n\n```ts no-transpile\nexport type DynamicMiddlewareInstance<\n  State = unknown,\n  Dispatch extends ReduxDispatch<UnknownAction> = ReduxDispatch<UnknownAction>,\n> = {\n  middleware: DynamicMiddleware<State, Dispatch>\n  addMiddleware: AddMiddleware<State, Dispatch>\n  withMiddleware: WithMiddleware<State, Dispatch>\n}\n```\n\n### `middleware`\n\nThe wrapper middleware instance, to add to the Redux store.\n\nYou can place this anywhere in the middleware chain, but note that all the middleware you inject into this instance will be contained within this position.\n\n### `addMiddleware`\n\nInjects a set of middleware into the instance.\n\n```ts no-transpile\naddMiddleware(logger, listenerMiddleware.instance)\n```\n\n:::note\n\n- Middleware are compared by function reference, and each is only added to the chain once.\n\n- Middleware are stored in an ES6 map, and are thus called in insertion order during dispatch.\n\n:::\n\n### `withMiddleware`\n\nAccepts a set of middleware, and creates an action. When dispatched, it injects the middleware and returns a version of `dispatch` typed to be aware of any extensions added.\n\n```ts no-transpile\nconst listenerDispatch = store.dispatch(\n  withMiddleware(listenerMiddleware.middleware),\n)\n\nconst unsubscribe = listenerDispatch(addListener({ type, effect }))\n```\n\n## React Integration\n\nWhen imported from the React-specific entry point (`@reduxjs/toolkit/react`), the result of calling `createDynamicMiddleware` will have extra methods attached.\n\n_These depend on having `react-redux` installed._\n\n```ts no-transpile\ninterface ReactDynamicMiddlewareInstance<\n  State = any,\n  Dispatch extends ReduxDispatch<UnknownAction> = ReduxDispatch<UnknownAction>,\n> extends DynamicMiddlewareInstance<State, Dispatch> {\n  createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<\n    State,\n    Dispatch\n  >\n  createDispatchWithMiddlewareHookFactory: (\n    context?: Context<\n      ReactReduxContextValue<State, ActionFromDispatch<Dispatch>>\n    >,\n  ) => CreateDispatchWithMiddlewareHook<State, Dispatch>\n}\n```\n\n### `createDispatchWithMiddlewareHook`\n\nAccepts a set of middleware, and returns a [`useDispatch`](https://react-redux.js.org/api/hooks#usedispatch) hook returning a `dispatch` typed to include extensions from provided middleware.\n\n```ts no-transpile\nconst useListenerDispatch = createDispatchWithMiddlewareHook(\n  listenerInstance.middleware,\n)\n\nconst Component = () => {\n  const listenerDispatch = useListenerDispatch()\n  useEffect(() => {\n    const unsubscribe = listenerDispatch(addListener({ type, effect }))\n    return () => unsubscribe()\n  }, [dispatch])\n}\n```\n\n:::caution\n\nMiddleware is injected when `createDispatchWithMiddlewareHook` is called, not when the `useDispatch` hook is used.\n\n:::\n\n### `createDispatchWithMiddlewareHookFactory`\n\nAccepts a React context instance, and returns a `createDispatchWithMiddlewareHook` built to use that context.\n\n```ts no-transpile\nconst createDispatchWithMiddlewareHook =\n  createDispatchWithMiddlewareHookFactory(context)\n```\n\nUseful if you're using a [custom context](https://react-redux.js.org/using-react-redux/accessing-store#providing-custom-context) for React Redux.\n"
  },
  {
    "path": "docs/api/createEntityAdapter.mdx",
    "content": "---\nid: createEntityAdapter\ntitle: createEntityAdapter\nsidebar_label: createEntityAdapter\nhide_title: true\n---\n\n&nbsp;\n\n# `createEntityAdapter`\n\n## Overview\n\nA function that generates a set of prebuilt reducers and selectors for performing CRUD operations on a [normalized state structure](https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape) containing instances of a particular type of data object. These reducer functions may be passed as case reducers to `createReducer` and `createSlice`. They may also be used as \"mutating\" helper functions inside of `createReducer` and `createSlice`.\n\nThis API was ported from [the `@ngrx/entity` library](https://ngrx.io/guide/entity) created by the NgRx maintainers, but has been significantly modified for use with Redux Toolkit. We'd like to thank the NgRx team for originally creating this API and allowing us to port and adapt it for our needs.\n\n:::note\nThe term \"Entity\" is used to refer to a unique type of data object in an application. For example, in a blogging application, you might have `User`, `Post`, and `Comment` data objects, with many instances of each being stored in the client and persisted on the server. `User` is an \"entity\" - a unique type of data object that the application uses. Each unique instance of an entity is assumed to have a unique ID value in a specific field.\n\nAs with all Redux logic, [_only_ plain JS objects and arrays should be passed in to the store - **no class instances!**](https://redux.js.org/style-guide/style-guide#do-not-put-non-serializable-values-in-state-or-actions)\n\nFor purposes of this reference, we will use `Entity` to refer to the specific data type that is being managed by a copy of the reducer logic in a specific portion of the Redux state tree, and `entity` to refer to a single instance of that type. Example: in `state.users`, `Entity` would refer to the `User` type, and `state.users.entities[123]` would be a single `entity`.\n:::\n\nThe methods generated by `createEntityAdapter` will all manipulate an \"entity state\" structure that looks like:\n\n```js\n{\n  // The unique IDs of each item. Must be strings or numbers\n  ids: []\n  // A lookup table mapping entity IDs to the corresponding entity objects\n  entities: {\n  }\n}\n```\n\n`createEntityAdapter` may be called multiple times in an application. If you are using it with plain JavaScript, you may be able to reuse a single adapter definition with multiple entity types if they're similar enough (such as all having an `entity.id` field). For [TypeScript usage](../usage/usage-with-typescript.md#createentityadapter), you will need to call `createEntityAdapter` a separate time for each distinct `Entity` type, so that the type definitions are inferred correctly.\n\nSample usage:\n\n```ts\nimport {\n  createEntityAdapter,\n  createSlice,\n  configureStore,\n} from '@reduxjs/toolkit'\n\ntype Book = { bookId: string; title: string }\n\nconst booksAdapter = createEntityAdapter({\n  // Assume IDs are stored in a field other than `book.id`\n  selectId: (book: Book) => book.bookId,\n  // Keep the \"all IDs\" array sorted based on book titles\n  sortComparer: (a, b) => a.title.localeCompare(b.title),\n})\n\nconst booksSlice = createSlice({\n  name: 'books',\n  initialState: booksAdapter.getInitialState(),\n  reducers: {\n    // Can pass adapter functions directly as case reducers.  Because we're passing this\n    // as a value, `createSlice` will auto-generate the `bookAdded` action type / creator\n    bookAdded: booksAdapter.addOne,\n    booksReceived(state, action) {\n      // Or, call them as \"mutating\" helpers in a case reducer\n      booksAdapter.setAll(state, action.payload.books)\n    },\n  },\n})\n\nconst store = configureStore({\n  reducer: {\n    books: booksSlice.reducer,\n  },\n})\n\ntype RootState = ReturnType<typeof store.getState>\n\nconsole.log(store.getState().books)\n// { ids: [], entities: {} }\n\n// Can create a set of memoized selectors based on the location of this entity state\nconst booksSelectors = booksAdapter.getSelectors<RootState>(\n  (state) => state.books,\n)\n\n// And then use the selectors to retrieve values\nconst allBooks = booksSelectors.selectAll(store.getState())\n```\n\n## Parameters\n\n`createEntityAdapter` accepts a single options object parameter, with two optional fields inside.\n\n### `selectId`\n\nA function that accepts a single `Entity` instance, and returns the value of whatever unique ID field is inside. If not provided, the default implementation is `entity => entity.id`. If your `Entity` type keeps its unique ID values in a field other than `entity.id`, you **must** provide a `selectId` function.\n\n### `sortComparer`\n\nA callback function that accepts two `Entity` instances, and should return a standard `Array.sort()` numeric result (1, 0, -1) to indicate their relative order for sorting.\n\nIf provided, the `state.ids` array will be kept in sorted order based on comparisons of the entity objects, so that mapping over the IDs array to retrieve entities by ID should result in a sorted array of entities.\n\nIf not provided, the `state.ids` array will not be sorted, and no guarantees are made about the ordering. In other words, `state.ids` can be expected to behave like a standard Javascript array.\n\nNote that sorting only kicks in when state is changed via one of the CRUD functions below (for example, `addOne()`, `updateMany()`).\n\n## Return Value\n\nA \"entity adapter\" instance. An entity adapter is a plain JS object (not a class) containing the generated reducer functions, the original provided `selectId` and `sortComparer` callbacks, a method to generate an initial \"entity state\" value, and functions to generate a set of globalized and non-globalized memoized selector functions for this entity type.\n\nThe adapter instance will include the following methods (additional referenced TypeScript types included):\n\n```ts no-transpile\nexport type EntityId = number | string\n\nexport type Comparer<T> = (a: T, b: T) => number\n\nexport type IdSelector<T> = (model: T) => EntityId\n\nexport type Update<T> = { id: EntityId; changes: Partial<T> }\n\nexport interface EntityState<T> {\n  ids: EntityId[]\n  entities: Record<EntityId, T>\n}\n\nexport interface EntityDefinition<T> {\n  selectId: IdSelector<T>\n  sortComparer: false | Comparer<T>\n}\n\nexport interface EntityStateAdapter<T> {\n  addOne<S extends EntityState<T>>(state: S, entity: T): S\n  addOne<S extends EntityState<T>>(state: S, action: PayloadAction<T>): S\n\n  addMany<S extends EntityState<T>>(state: S, entities: T[]): S\n  addMany<S extends EntityState<T>>(state: S, entities: PayloadAction<T[]>): S\n\n  setOne<S extends EntityState<T>>(state: S, entity: T): S\n  setOne<S extends EntityState<T>>(state: S, action: PayloadAction<T>): S\n\n  setMany<S extends EntityState<T>>(state: S, entities: T[]): S\n  setMany<S extends EntityState<T>>(state: S, entities: PayloadAction<T[]>): S\n\n  setAll<S extends EntityState<T>>(state: S, entities: T[]): S\n  setAll<S extends EntityState<T>>(state: S, entities: PayloadAction<T[]>): S\n\n  removeOne<S extends EntityState<T>>(state: S, key: EntityId): S\n  removeOne<S extends EntityState<T>>(state: S, key: PayloadAction<EntityId>): S\n\n  removeMany<S extends EntityState<T>>(state: S, keys: EntityId[]): S\n  removeMany<S extends EntityState<T>>(\n    state: S,\n    keys: PayloadAction<EntityId[]>,\n  ): S\n\n  removeAll<S extends EntityState<T>>(state: S): S\n\n  updateOne<S extends EntityState<T>>(state: S, update: Update<T>): S\n  updateOne<S extends EntityState<T>>(\n    state: S,\n    update: PayloadAction<Update<T>>,\n  ): S\n\n  updateMany<S extends EntityState<T>>(state: S, updates: Update<T>[]): S\n  updateMany<S extends EntityState<T>>(\n    state: S,\n    updates: PayloadAction<Update<T>[]>,\n  ): S\n\n  upsertOne<S extends EntityState<T>>(state: S, entity: T): S\n  upsertOne<S extends EntityState<T>>(state: S, entity: PayloadAction<T>): S\n\n  upsertMany<S extends EntityState<T>>(state: S, entities: T[]): S\n  upsertMany<S extends EntityState<T>>(\n    state: S,\n    entities: PayloadAction<T[]>,\n  ): S\n}\n\nexport interface EntitySelectors<T, V> {\n  selectIds: (state: V) => EntityId[]\n  selectEntities: (state: V) => Record<EntityId, T>\n  selectAll: (state: V) => T[]\n  selectTotal: (state: V) => number\n  selectById: (state: V, id: EntityId) => T | undefined\n}\n\nexport interface EntityAdapter<T> extends EntityStateAdapter<T> {\n  selectId: IdSelector<T>\n  sortComparer: false | Comparer<T>\n  getInitialState(): EntityState<T>\n  getInitialState<S extends object>(state: S): EntityState<T> & S\n  getSelectors(): EntitySelectors<T, EntityState<T>>\n  getSelectors<V>(\n    selectState: (state: V) => EntityState<T>,\n  ): EntitySelectors<T, V>\n}\n```\n\n### CRUD Functions\n\nThe primary content of an entity adapter is a set of generated reducer functions for adding, updating, and removing entity instances from an entity state object:\n\n- `addOne`: accepts a single entity, and adds it if it's not already present.\n- `addMany`: accepts an array of entities or an object in the shape of `Record<EntityId, T>`, and adds them if not already present.\n- `setOne`: accepts a single entity and adds or replaces it\n- `setMany`: accepts an array of entities or an object in the shape of `Record<EntityId, T>`, and adds or replaces them.\n- `setAll`: accepts an array of entities or an object in the shape of `Record<EntityId, T>`, and replaces all existing entities with the values in the array.\n- `removeOne`: accepts a single entity ID value, and removes the entity with that ID if it exists.\n- `removeMany`: accepts an array of entity ID values, and removes each entity with those IDs if they exist.\n- `removeAll`: removes all entities from the entity state object.\n- `updateOne`: accepts an \"update object\" containing an entity ID and an object containing one or more new field values to update inside a `changes` field, and performs a shallow update on the corresponding entity.\n- `updateMany`: accepts an array of update objects, and performs shallow updates on all corresponding entities.\n- `upsertOne`: accepts a single entity. If an entity with that ID exists, it will perform a shallow update and the specified fields will be merged into the existing entity, with any matching fields overwriting the existing values. If the entity does not exist, it will be added.\n- `upsertMany`: accepts an array of entities or an object in the shape of `Record<EntityId, T>` that will be shallowly upserted.\n\n:::info Should I add, set or upsert my entity?\n\nAll three options will insert _new_ entities into the list. However they differ in how they handle entities that already exist. If an entity **already exists**:\n\n- `addOne` and `addMany` will do nothing with the new entity\n- `setOne` and `setMany` will completely replace the old entity with the new one. This will also get rid of any properties on the entity that are not present in the new version of said entity.\n- `upsertOne` and `upsertMany` will do a shallow copy to merge the old and new entities overwriting existing values, adding any that were not there and not touching properties not provided in the new entity.\n\n:::\n\nEach method has a signature that looks like:\n\n```ts no-transpile\n;(state: EntityState<T>, argument: TypeOrPayloadAction<Argument<T>>) =>\n  EntityState<T>\n```\n\nIn other words, they accept a state that looks like `{ids: [], entities: {}}`, and calculate and return a new state.\n\nThese CRUD methods may be used in multiple ways:\n\n- They may be passed as case reducers directly to `createReducer` and `createSlice`.\n- They may be used as \"mutating\" helper methods when called manually, such as a separate hand-written call to `addOne()` inside of an existing case reducer, if the `state` argument is actually an Immer `Draft` value.\n- They may be used as immutable update methods when called manually, if the `state` argument is actually a plain JS object or array.\n\n:::note\nThese methods do _not_ have corresponding Redux actions created - they are just standalone reducers / update logic. **It is entirely up to you to decide where and how to use these methods!** Most of the time, you will want to pass them to `createSlice` or use them inside another reducer.\n:::\n\nEach method will check to see if the `state` argument is an Immer `Draft` or not. If it is a draft, the method will assume that it's safe to continue mutating that draft further. If it is not a draft, the method will pass the plain JS value to Immer's `createNextState()`, and return the immutably updated result value.\n\nThe `argument` may be either a plain value (such as a single `Entity` object for `addOne()` or an `Entity[]` array for `addMany()`, or a `PayloadAction` action object with that same value as `action.payload`. This enables using them as both helper functions and reducers.\n\n> **Note on shallow updates:** `updateOne`, `updateMany`, `upsertOne`, and `upsertMany` only perform shallow updates in a mutable manner. This means that if your update/upsert consists of an object that includes nested properties, the value of the incoming change will overwrite the **entire** existing nested object. This may be unintended behavior for your application. As a general rule, these methods are best used with [normalized data](../usage/usage-guide.md#managing-normalized-data) that _do not_ have nested properties.\n\n### `getInitialState`\n\nReturns a new entity state object like `{ids: [], entities: {}}`.\n\nIt accepts an optional object as an argument. The fields in that object will be merged into the returned initial state value. For example, perhaps you want your slice to also track some loading state:\n\n```js\nconst booksSlice = createSlice({\n  name: 'books',\n  initialState: booksAdapter.getInitialState({\n    loading: 'idle',\n  }),\n  reducers: {\n    booksLoadingStarted(state, action) {\n      // Can update the additional state field\n      state.loading = 'pending'\n    },\n  },\n})\n```\n\nYou can also pass in an array of entities or a `Record<EntityId, T>` object to pre-populate the initial state with some entities:\n\n```js\nconst booksSlice = createSlice({\n  name: 'books',\n  initialState: booksAdapter.getInitialState(\n    {\n      loading: 'idle',\n    },\n    [\n      { id: 'a', title: 'First' },\n      { id: 'b', title: 'Second' },\n    ],\n  ),\n  reducers: {},\n})\n```\n\nThis is equivalent to calling:\n\n```js\nconst initialState = booksAdapter.getInitialState({\n  loading: 'idle',\n})\n\nconst prePopulatedState = booksAdapter.setAll(initialState, [\n  { id: 'a', title: 'First' },\n  { id: 'b', title: 'Second' },\n])\n```\n\nThe first parameter can be `undefined` if no additional properties are needed.\n\n### Selector Functions\n\nThe entity adapter will contain a `getSelectors()` function that returns a set of selectors that know how to read the contents of an entity state object:\n\n- `selectIds`: returns the `state.ids` array.\n- `selectEntities`: returns the `state.entities` lookup table.\n- `selectAll`: maps over the `state.ids` array, and returns an array of entities in the same order.\n- `selectTotal`: returns the total number of entities being stored in this state.\n- `selectById`: given the state and an entity ID, returns the entity with that ID or `undefined`.\n\nEach selector function will be created using the `createSelector` function from Reselect, to enable memoizing calculation of the results.\n\n:::tip\n\nThe `createSelector` instance used can be replaced, by passing it as part of the options object (second parameter):\n\n```js\nimport {\n  createDraftSafeSelectorCreator,\n  weakMapMemoize,\n} from '@reduxjs/toolkit'\n\nconst createWeakMapDraftSafeSelector =\n  createDraftSafeSelectorCreator(weakMapMemoize)\n\nconst simpleSelectors = booksAdapter.getSelectors(undefined, {\n  createSelector: createWeakMapDraftSafeSelector,\n})\n\nconst globalizedSelectors = booksAdapter.getSelectors((state) => state.books, {\n  createSelector: createWeakMapDraftSafeSelector,\n})\n```\n\nIf no instance is passed, it will default to [`createDraftSafeSelector`](./createSelector.mdx#createdraftsafeselector).\n\n:::\n\nBecause selector functions are dependent on knowing where in the state tree this specific entity state object is kept, `getSelectors()` can be called in two ways:\n\n- If called without any arguments (or with undefined as the first parameter), it returns an \"unglobalized\" set of selector functions that assume their `state` argument is the actual entity state object to read from.\n- It may also be called with a selector function that accepts the entire Redux state tree and returns the correct entity state object.\n\nFor example, the entity state for a `Book` type might be kept in the Redux state tree as `state.books`. You can use `getSelectors()` to read from that state in two ways:\n\n```js\nconst store = configureStore({\n  reducer: {\n    books: booksReducer,\n  },\n})\n\nconst simpleSelectors = booksAdapter.getSelectors()\nconst globalizedSelectors = booksAdapter.getSelectors((state) => state.books)\n\n// Need to manually pass the correct entity state object in to this selector\nconst bookIds = simpleSelectors.selectIds(store.getState().books)\n\n// This selector already knows how to find the books entity state\nconst allBooks = globalizedSelectors.selectAll(store.getState())\n```\n\n## Notes\n\n### Applying Multiple Updates\n\nIf `updateMany()` is called with multiple updates targeted to the same ID, they will be merged into a single update, with later updates overwriting the earlier ones.\n\nFor both `updateOne()` and `updateMany()`, changing the ID of one existing entity to match the ID of a second existing entity will cause the first to replace the second completely.\n\nAdditionally, if there is no item for that ID, the update will be silently ignored.\n\n## Examples\n\nExercising several of the CRUD methods and selectors:\n\n```js\nimport {\n  createEntityAdapter,\n  createSlice,\n  configureStore,\n} from '@reduxjs/toolkit'\n\n// Since we don't provide `selectId`, it defaults to assuming `entity.id` is the right field\nconst booksAdapter = createEntityAdapter({\n  // Keep the \"all IDs\" array sorted based on book titles\n  sortComparer: (a, b) => a.title.localeCompare(b.title),\n})\n\nconst booksSlice = createSlice({\n  name: 'books',\n  initialState: booksAdapter.getInitialState({\n    loading: 'idle',\n  }),\n  reducers: {\n    // Can pass adapter functions directly as case reducers.  Because we're passing this\n    // as a value, `createSlice` will auto-generate the `bookAdded` action type / creator\n    bookAdded: booksAdapter.addOne,\n    booksLoading(state, action) {\n      if (state.loading === 'idle') {\n        state.loading = 'pending'\n      }\n    },\n    booksReceived(state, action) {\n      if (state.loading === 'pending') {\n        // Or, call them as \"mutating\" helpers in a case reducer\n        booksAdapter.setAll(state, action.payload)\n        state.loading = 'idle'\n      }\n    },\n    bookUpdated: booksAdapter.updateOne,\n  },\n})\n\nconst { bookAdded, booksLoading, booksReceived, bookUpdated } =\n  booksSlice.actions\n\nconst store = configureStore({\n  reducer: {\n    books: booksSlice.reducer,\n  },\n})\n\n// Check the initial state:\nconsole.log(store.getState().books)\n// {ids: [], entities: {}, loading: 'idle' }\n\nconst booksSelectors = booksAdapter.getSelectors((state) => state.books)\n\nstore.dispatch(bookAdded({ id: 'a', title: 'First' }))\nconsole.log(store.getState().books)\n// {ids: [\"a\"], entities: {a: {id: \"a\", title: \"First\"}}, loading: 'idle' }\n\nstore.dispatch(bookUpdated({ id: 'a', changes: { title: 'First (altered)' } }))\nstore.dispatch(booksLoading())\nconsole.log(store.getState().books)\n// {ids: [\"a\"], entities: {a: {id: \"a\", title: \"First (altered)\"}}, loading: 'pending' }\n\nstore.dispatch(\n  booksReceived([\n    { id: 'b', title: 'Book 3' },\n    { id: 'c', title: 'Book 2' },\n  ]),\n)\n\nconsole.log(booksSelectors.selectIds(store.getState()))\n// \"a\" was removed due to the `setAll()` call\n// Since they're sorted by title, \"Book 2\" comes before \"Book 3\"\n// [\"c\", \"b\"]\n\nconsole.log(booksSelectors.selectAll(store.getState()))\n// All book entries in sorted order\n// [{id: \"c\", title: \"Book 2\"}, {id: \"b\", title: \"Book 3\"}]\n```\n"
  },
  {
    "path": "docs/api/createListenerMiddleware.mdx",
    "content": "---\nid: createListenerMiddleware\ntitle: createListenerMiddleware\nsidebar_label: createListenerMiddleware\nhide_title: true\n---\n\n&nbsp;\n\n# `createListenerMiddleware`\n\n## Overview\n\nA Redux middleware that lets you define \"listener\" entries that contain an \"effect\" callback with additional logic, and a way to specify when that callback should run based on dispatched actions or state changes.\n\nIt's intended to be a lightweight alternative to more widely used Redux async middleware like sagas and observables. While similar to thunks in level of complexity and concept, it can be used to replicate some common saga usage patterns.\n\nConceptually, you can think of this as being similar to React's `useEffect` hook, except that it runs logic in response to Redux store updates instead of component props/state updates.\n\nListener effect callbacks have access to `dispatch` and `getState`, similar to thunks. The listener also receives a set of async workflow functions like `take`, `condition`, `pause`, `fork`, and `unsubscribe`, which allow writing more complex async logic.\n\nListeners can be defined statically by calling `listenerMiddleware.startListening()` during setup, or added and removed dynamically at runtime with special `dispatch(addListener())` and `dispatch(removeListener())` actions.\n\n### Basic Usage\n\n```js\nimport { configureStore, createListenerMiddleware } from '@reduxjs/toolkit'\n\nimport todosReducer, {\n  todoAdded,\n  todoToggled,\n  todoDeleted,\n} from '../features/todos/todosSlice'\n\n// Create the middleware instance and methods\nconst listenerMiddleware = createListenerMiddleware()\n\n// Add one or more listener entries that look for specific actions.\n// They may contain any sync or async logic, similar to thunks.\nlistenerMiddleware.startListening({\n  actionCreator: todoAdded,\n  effect: async (action, listenerApi) => {\n    // Run whatever additional side-effect-y logic you want here\n    console.log('Todo added: ', action.payload.text)\n\n    // Can cancel other running instances\n    listenerApi.cancelActiveListeners()\n\n    // Run async logic\n    const data = await fetchData()\n\n    // Pause until action dispatched or state changed\n    if (await listenerApi.condition(matchSomeAction)) {\n      // Use the listener API methods to dispatch, get state,\n      // unsubscribe the listener, start child tasks, and more\n      listenerApi.dispatch(todoAdded('Buy pet food'))\n\n      // Spawn \"child tasks\" that can do more work and return results\n      const task = listenerApi.fork(async (forkApi) => {\n        // Can pause execution\n        await forkApi.delay(5)\n        // Complete the child by returning a value\n        return 42\n      })\n\n      const result = await task.result\n      // Unwrap the child result in the listener\n      if (result.status === 'ok') {\n        // Logs the `42` result value that was returned\n        console.log('Child succeeded: ', result.value)\n      }\n    }\n  },\n})\n\nconst store = configureStore({\n  reducer: {\n    todos: todosReducer,\n  },\n  // Add the listener middleware to the store.\n  // NOTE: Since this can receive actions with functions inside,\n  // it should go before the serializability check middleware\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().prepend(listenerMiddleware.middleware),\n})\n```\n\n## `createListenerMiddleware`\n\nCreates an instance of the middleware, which should then be added to the store via `configureStore`'s `middleware` parameter.\n\n```ts no-transpile\nconst createListenerMiddleware = (options?: CreateMiddlewareOptions) =>\n  ListenerMiddlewareInstance\n\ninterface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {\n  extra?: ExtraArgument\n  onError?: ListenerErrorHandler\n}\n\ntype ListenerErrorHandler = (\n  error: unknown,\n  errorInfo: ListenerErrorInfo,\n) => void\n\ninterface ListenerErrorInfo {\n  raisedBy: 'effect' | 'predicate'\n}\n```\n\n### Middleware Options\n\n- `extra`: an optional \"extra argument\" that will be injected into the `listenerApi` parameter of each listener. Equivalent to [the \"extra argument\" in the Redux Thunk middleware](https://redux.js.org/usage/writing-logic-thunks#injecting-config-values-into-thunks)\n- `onError`: an optional error handler that gets called with synchronous and async errors raised by `listener` and synchronous errors thrown by `predicate`.\n\n## Listener Middleware Instance\n\nThe \"listener middleware instance\" returned from `createListenerMiddleware` is an object similar to the \"slice\" objects generated by `createSlice`. The instance object is _not_ the actual Redux middleware itself. Rather, it contains the middleware and some instance methods used to add and remove listener entries within the middleware.\n\n```ts no-transpile\ninterface ListenerMiddlewareInstance<\n  State = unknown,\n  Dispatch extends ThunkDispatch<State, unknown, UnknownAction> = ThunkDispatch<\n    State,\n    unknown,\n    UnknownAction\n  >,\n  ExtraArgument = unknown,\n> {\n  middleware: ListenerMiddleware<State, Dispatch, ExtraArgument>\n  startListening: (options: AddListenerOptions) => Unsubscribe\n  stopListening: (\n    options: AddListenerOptions & UnsubscribeListenerOptions,\n  ) => boolean\n  clearListeners: () => void\n}\n```\n\n### `middleware`\n\nThe actual Redux middleware. Add this to the Redux store via [the `configureStore.middleware` option](./configureStore.mdx#middleware).\n\nSince the listener middleware can receive \"add\" and \"remove\" actions containing functions, this should normally be added as the first middleware in the chain so that it is before the serializability check middleware.\n\n```js\nconst store = configureStore({\n  reducer: {\n    todos: todosReducer,\n  },\n  // Add the listener middleware to the store.\n  // NOTE: Since this can receive actions with functions inside,\n  // it should go before the serializability check middleware\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().prepend(listenerMiddleware.middleware),\n})\n```\n\n### `startListening`\n\nAdds a new listener entry to the middleware. Typically used to \"statically\" add new listeners during application setup.\n\n```ts no-transpile\nconst startListening = (options: AddListenerOptions) => UnsubscribeListener\n\ninterface AddListenerOptions {\n  // Four options for deciding when the listener will run:\n\n  // 1) Exact action type string match\n  type?: string\n\n  // 2) Exact action type match based on the RTK action creator\n  actionCreator?: ActionCreator\n\n  // 3) Match one of many actions using an RTK matcher\n  matcher?: Matcher\n\n  // 4) Return true based on a combination of action + state\n  predicate?: ListenerPredicate\n\n  // The actual callback to run when the action is matched\n  effect: (action: Action, listenerApi: ListenerApi) => void | Promise<void>\n}\n\ntype ListenerPredicate<Action extends ReduxAction, State> = (\n  action: Action,\n  currentState?: State,\n  originalState?: State,\n) => boolean\n\ntype UnsubscribeListener = (\n  unsubscribeOptions?: UnsubscribeListenerOptions,\n) => void\n\ninterface UnsubscribeListenerOptions {\n  cancelActive?: true\n}\n```\n\n**You must provide exactly _one_ of the four options for deciding when the listener will run: `type`, `actionCreator`, `matcher`, or `predicate`**. Every time an action is dispatched, each listener will be checked to see if it should run based on the current action vs the comparison option provided.\n\nThese are all acceptable:\n\n```js\n// 1) Action type string\nlistenerMiddleware.startListening({ type: 'todos/todoAdded', effect })\n// 2) RTK action creator\nlistenerMiddleware.startListening({ actionCreator: todoAdded, effect })\n// 3) RTK matcher function\nlistenerMiddleware.startListening({\n  matcher: isAnyOf(todoAdded, todoToggled),\n  effect,\n})\n// 4) Listener predicate\nlistenerMiddleware.startListening({\n  predicate: (action, currentState, previousState) => {\n    // return true when the listener should run\n  },\n  effect,\n})\n```\n\nNote that the `predicate` option actually allows matching solely against state-related checks, such as \"did `state.x` change\" or \"the current value of `state.x` matches some criteria\", regardless of the actual action.\n\nThe [\"matcher\" utility functions included in RTK](./matching-utilities.mdx) are acceptable as either the `matcher` or `predicate` option.\n\nThe return value is an `unsubscribe()` callback that will remove this listener. By default, unsubscribing will _not_ cancel any active instances of the listener. However, you may also pass in `{cancelActive: true}` to cancel running instances.\n\nIf you try to add a listener entry but another entry with this exact function reference already exists, no new entry will be added, and the existing `unsubscribe` method will be returned.\n\nThe `effect` callback will receive the current action as its first argument, as well as a \"listener API\" object similar to the \"thunk API\" object in `createAsyncThunk`.\n\nAll listener predicates and callbacks are checked _after_ the root reducer has already processed the action and updated the state. The `listenerApi.getOriginalState()` method can be used to get the state value that existed before the action that triggered this listener was processed.\n\n### `stopListening`\n\nRemoves a given listener entry.\n\nIt accepts the same arguments as `startListening()`. It checks for an existing listener entry by comparing the function references of `listener` and the provided `actionCreator/matcher/predicate` function or `type` string.\n\nBy default, this does _not_ cancel any active running instances. However, you may also pass in `{cancelActive: true}` to cancel running instances.\n\n```ts no-transpile\nconst stopListening = (\n  options: AddListenerOptions & UnsubscribeListenerOptions,\n) => boolean\n\ninterface UnsubscribeListenerOptions {\n  cancelActive?: true\n}\n```\n\nReturns `true` if the listener entry has been removed, or `false` if no subscription matching the input provided has been found.\n\n```js\n// Examples:\n// 1) Action type string\nlistenerMiddleware.stopListening({\n  type: 'todos/todoAdded',\n  listener,\n  cancelActive: true,\n})\n// 2) RTK action creator\nlistenerMiddleware.stopListening({ actionCreator: todoAdded, effect })\n// 3) RTK matcher function\nlistenerMiddleware.stopListening({ matcher, effect, cancelActive: true })\n// 4) Listener predicate\nlistenerMiddleware.stopListening({ predicate, effect })\n```\n\n### `clearListeners`\n\nRemoves all current listener entries. It also cancels all active running instances of those listeners as well.\n\nThis is most likely useful for test scenarios where a single middleware or store instance might be used in multiple tests, as well as some app cleanup situations.\n\n```ts no-transpile\nconst clearListeners = () => void;\n```\n\n## Action Creators\n\nIn addition to adding and removing listeners by directly calling methods on the listener instance, you can dynamically add and remove listeners at runtime by dispatching special \"add\" and \"remove\" actions. These are exported from the main RTK package as standard RTK-generated action creators.\n\n### `addListener`\n\nA standard RTK action creator, imported from the package. Dispatching this action tells the middleware to dynamically add a new listener at runtime. It accepts exactly the same options as `startListening()`\n\nDispatching this action returns an `unsubscribe()` callback from `dispatch`.\n\n```js\n// Per above, provide `predicate` or any of the other comparison options\nconst unsubscribe = store.dispatch(addListener({ predicate, effect }))\n```\n\n### `removeListener`\n\nA standard RTK action creator, imported from the package. Dispatching this action tells the middleware to dynamically remove a listener at runtime. Accepts the same arguments as `stopListening()`.\n\nBy default, this does _not_ cancel any active running instances. However, you may also pass in `{cancelActive: true}` to cancel running instances.\n\nReturns `true` if the listener entry has been removed, `false` if no subscription matching the input provided has been found.\n\n```js\nconst wasRemoved = store.dispatch(\n  removeListener({ predicate, effect, cancelActive: true }),\n)\n```\n\n### `clearAllListeners`\n\nA standard RTK action creator, imported from the package. Dispatching this action tells the middleware to remove all current listener entries. It also cancels all active running instances of those listeners as well.\n\n```js\nstore.dispatch(clearAllListeners())\n```\n\n## Listener API\n\nThe `listenerApi` object is the second argument to each listener callback. It contains several utility functions that may be called anywhere inside the listener's logic.\n\n```ts no-transpile\nexport interface ListenerEffectAPI<\n  State,\n  Dispatch extends ReduxDispatch<UnknownAction>,\n  ExtraArgument = unknown,\n> extends MiddlewareAPI<Dispatch, State> {\n  // NOTE: MiddlewareAPI contains `dispatch` and `getState` already\n\n  /**\n   * Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.\n   * This function can **only** be invoked **synchronously**, it throws error otherwise.\n   */\n  getOriginalState: () => State\n  /**\n   * Removes the listener entry from the middleware and prevent future instances of the listener from running.\n   * It does **not** cancel any active instances.\n   */\n  unsubscribe(): void\n  /**\n   * It will subscribe a listener if it was previously removed, noop otherwise.\n   */\n  subscribe(): void\n  /**\n   * Returns a promise that resolves when the input predicate returns `true` or\n   * rejects if the listener has been cancelled or is completed.\n   *\n   * The return value is `true` if the predicate succeeds or `false` if a timeout is provided and expires first.\n   */\n  condition: ConditionFunction<State>\n  /**\n   * Returns a promise that resolves when the input predicate returns `true` or\n   * rejects if the listener has been cancelled or is completed.\n   *\n   * The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments.\n   *\n   * The promise resolves to null if a timeout is provided and expires first.\n   */\n  take: TakePattern<State>\n  /**\n   * Cancels all other running instances of this same listener except for the one that made this call.\n   */\n  cancelActiveListeners: () => void\n  /**\n   * Cancels the listener instance that made this call.\n   */\n  cancel: () => void\n  /**\n   * Throws a `TaskAbortError` if this listener has been cancelled\n   */\n  throwIfCancelled: () => void\n  /**\n   * An abort signal whose `aborted` property is set to `true`\n   * if the listener execution is either aborted or completed.\n   * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\n   */\n  signal: AbortSignal\n  /**\n   * Returns a promise that resolves after `timeoutMs` or\n   * rejects if the listener has been cancelled or is completed.\n   */\n  delay(timeoutMs: number): Promise<void>\n  /**\n   * Queues in the next microtask the execution of a task.\n   */\n  fork<T>(executor: ForkedTaskExecutor<T>): ForkedTask<T>\n  /**\n   * Returns a promise that resolves when `waitFor` resolves or\n   * rejects if the listener has been cancelled or is completed.\n   * @param promise\n   */\n  pause<M>(promise: Promise<M>): Promise<M>\n  extra: ExtraArgument\n}\n```\n\nThese can be divided into several categories.\n\n### Store Interaction Methods\n\n- `dispatch: Dispatch`: the standard `store.dispatch` method\n- `getState: () => State`: the standard `store.getState` method\n- `getOriginalState: () => State`: returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran. (**Note**: this method can only be called synchronously, during the initial dispatch call stack, to avoid memory leaks. Calling it asynchronously will throw an error.)\n- `extra: unknown`: the \"extra argument\" that was provided as part of the middleware setup, if any\n\n`dispatch` and `getState` are exactly the same as in a thunk. `getOriginalState` can be used to compare the original state before the listener was started.\n\n`extra` can be used to inject a value such as an API service layer into the middleware at creation time, and is accessible here.\n\n### Listener Subscription Management\n\n- `unsubscribe: () => void`: removes the listener entry from the middleware, and prevent future instances of the listener from running. (This does _not_ cancel any active instances.)\n- `subscribe: () => void`: will re-subscribe the listener entry if it was previously removed, or no-op if currently subscribed\n- `cancelActiveListeners: () => void`: cancels all other running instances of this same listener _except_ for the one that made this call. (The cancellation will only have a meaningful effect if the other instances are paused using one of the cancellation-aware APIs like `take/cancel/pause/delay` - see \"Cancelation and Task Management\" in the \"Usage\" section for more details)\n- `cancel: () => void`: cancels the instance of this listener that made this call.\n- `throwIfCancelled: () => void`: throws a `TaskAbortError` if the current listener instance was cancelled.\n- `signal: AbortSignal`: An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) whose `aborted` property will be set to `true` if the listener execution is aborted or completed.\n\nDynamically unsubscribing and re-subscribing this listener allows for more complex async workflows, such as avoiding duplicate running instances by calling `listenerApi.unsubscribe()` at the start of a listener, or calling `listenerApi.cancelActiveListeners()` to ensure that only the most recent instance is allowed to complete.\n\n### Conditional Workflow Execution\n\n- `take: (predicate: ListenerPredicate, timeout?: number) => Promise<[Action, State, State] | null>`: returns a promise that will resolve when the `predicate` returns `true`. The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments. If a `timeout` is provided and expires first, the promise resolves to `null`.\n- `condition: (predicate: ListenerPredicate, timeout?: number) => Promise<boolean>`: Similar to `take`, but resolves to `true` if the predicate succeeds, and `false` if a `timeout` is provided and expires first. This allows async logic to pause and wait for some condition to occur before continuing. See \"Writing Async Workflows\" below for details on usage.\n- `delay: (timeoutMs: number) => Promise<void>`: returns a cancellation-aware promise that resolves after the timeout, or rejects if cancelled before the expiration\n- `pause: (promise: Promise<T>) => Promise<T>`: accepts any promise, and returns a cancellation-aware promise that either resolves with the argument promise or rejects if cancelled before the resolution\n\nThese methods provide the ability to write conditional logic based on future dispatched actions and state changes. Both also accept an optional `timeout` in milliseconds.\n\n`take` resolves to a `[action, currentState, previousState]` tuple or `null` if it timed out, whereas `condition` resolves to `true` if it succeeded or `false` if timed out.\n\n`take` is meant for \"wait for an action and get its contents\", while `condition` is meant for checks like `if (await condition(predicate))`.\n\nBoth these methods are cancellation-aware, and will throw a `TaskAbortError` if the listener instance is cancelled while paused.\n\nNote that both `take` and `condition` will only resolve **after the next action** has been dispatched. They do not resolve immediately even if their predicate would return true for the current state.\n\n### Child Tasks\n\n- `fork: (executor: (forkApi: ForkApi) => T | Promise<T>) => ForkedTask<T>`: Launches a \"child task\" that may be used to accomplish additional work. Accepts any sync or async function as its argument, and returns a `{result, cancel}` object that can be used to check the final status and return value of the child task, or cancel it while in-progress.\n\nChild tasks can be launched, and waited on to collect their return values. The provided `executor` function will be called asynchronously with a `forkApi` object containing `{pause, delay, signal}`, allowing it to pause or check cancellation status. It can also make use of the `listenerApi` from the listener's scope.\n\nAn example of this might be a listener that forks a child task containing an infinite loop that listens for events from a server. The parent then uses `listenerApi.condition()` to wait for a \"stop\" action, and cancels the child task.\n\nThe task and result types are:\n\n```ts no-transpile\ninterface ForkedTaskAPI {\n  pause<W>(waitFor: Promise<W>): Promise<W>\n  delay(timeoutMs: number): Promise<void>\n  signal: AbortSignal\n}\n\nexport type TaskResolved<T> = {\n  readonly status: 'ok'\n  readonly value: T\n}\n\nexport type TaskRejected = {\n  readonly status: 'rejected'\n  readonly error: unknown\n}\n\nexport type TaskCancelled = {\n  readonly status: 'cancelled'\n  readonly error: TaskAbortError\n}\n\nexport type TaskResult<Value> =\n  | TaskResolved<Value>\n  | TaskRejected\n  | TaskCancelled\n\nexport interface ForkedTask<T> {\n  result: Promise<TaskResult<T>>\n  cancel(): void\n}\n```\n\n## TypeScript Usage\n\nThe middleware code is fully TS-typed. However, the `startListening` and `addListener` functions do not know what the store's `RootState` type looks like by default, so `getState()` will return `unknown`.\n\nTo fix this, the middleware provides types for defining \"pre-typed\" versions of those methods, similar to the pattern used for defing pre-typed React-Redux hooks. We specifically recommend creating the middleware instance in a separate file from the actual `configureStore()` call:\n\n```ts no-transpile\n// listenerMiddleware.ts\nimport { createListenerMiddleware, addListener } from '@reduxjs/toolkit'\nimport type { RootState, AppDispatch } from './store'\n\ndeclare type ExtraArgument = {foo: string};\n\nexport const listenerMiddleware = createListenerMiddleware()\n\nexport const startAppListening = listenerMiddleware.startListening.withTypes<\n  RootState,\n  AppDispatch,\n  ExtraArgument\n>()\n\nexport const addAppListener = addListener.withTypes<RootState, AppDispatch>()\n```\n\nThen import and use those pre-typed methods in your components.\n\n## Usage Guide\n\n### Overall Purpose\n\nThis middleware lets you run additional logic when some action is dispatched, as a lighter-weight alternative to middleware like sagas and observables that have both a heavy runtime bundle cost and a large conceptual overhead.\n\nThis middleware is not intended to handle all possible use cases. Like thunks, it provides you with a basic set of primitives (including access to `dispatch` and `getState`), and gives you freedom to write any sync or async logic you want. This is both a strength (you can do anything!) and a weakness (you can do anything, with no guard rails!).\n\nThe middleware includes several async workflow primitives that are sufficient to write equivalents to many Redux-Saga effects operators like `takeLatest`, `takeLeading`, and `debounce`, although none of those methods are directly included. (See [the listener middleware tests file for examples of how to write code equivalent to those effects](https://github.com/reduxjs/redux-toolkit/blob/03eafd5236f16574935cdf1c5958e32ee8cf3fbe/packages/toolkit/src/listenerMiddleware/tests/effectScenarios.test.ts#L74-L363).)\n\n### Standard Usage Patterns\n\nThe most common expected usage is \"run some logic after a given action was dispatched\". For example, you could set up a simple analytics tracker by looking for certain actions and sending extracted data to the server, including pulling user details from the store:\n\n```js\nlistenerMiddleware.startListening({\n  matcher: isAnyOf(action1, action2, action3),\n  effect: (action, listenerApi) => {\n    const user = selectUserDetails(listenerApi.getState())\n\n    const { specialData } = action.meta\n\n    analyticsApi.trackUsage(action.type, user, specialData)\n  },\n})\n```\n\nHowever, the `predicate` option also allows triggering logic when some state value has changed, or when the state matches a particular condition:\n\n```js\nlistenerMiddleware.startListening({\n  predicate: (action, currentState, previousState) => {\n    // Trigger logic whenever this field changes\n    return currentState.counter.value !== previousState.counter.value\n  },\n  effect,\n})\n\nlistenerMiddleware.startListening({\n  predicate: (action, currentState, previousState) => {\n    // Trigger logic after every action if this condition is true\n    return currentState.counter.value > 3\n  },\n  effect,\n})\n```\n\nYou could also implement a generic API fetching capability, where the UI dispatches a plain action describing the type of resource to be requested, and the middleware automatically fetches it and dispatches a result action:\n\n```js\nlistenerMiddleware.startListening({\n  actionCreator: resourceRequested,\n  effect: async (action, listenerApi) => {\n    const { name, args } = action.payload\n    listenerApi.dispatch(resourceLoading())\n\n    const res = await serverApi.fetch(`/api/${name}`, ...args)\n    listenerApi.dispatch(resourceLoaded(res.data))\n  },\n})\n```\n\n(That said, we would recommend use of RTK Query for any meaningful data fetching behavior - this is primarily an example of what you _could_ do in a listener.)\n\nThe `listenerApi.unsubscribe` method may be used at any time, and will remove the listener from handling any future actions. As an example, you could create a one-shot listener by unconditionally calling `unsubscribe()` in the body - the effect callback would run the first time the relevant action is seen, then immediately unsubscribe and never run again. (The middleware actually uses this technique internally for the `take/condition` methods)\n\n### Writing Async Workflows with Conditions\n\nOne of the great strengths of both sagas and observables is their support for complex async workflows, including stopping and starting behavior based on specific dispatched actions. However, the weakness is that both require mastering a complex API with many unique operators (effects methods like `call()` and `fork()` for sagas, RxJS operators for observables), and both add a significant amount to application bundle size.\n\nWhile the listener middleware is _not_ meant to fully replace sagas or observables, it does provide a carefully chosen set of APIs to implement long-running async workflows as well.\n\nListeners can use the `condition` and `take` methods in `listenerApi` to wait until some action is dispatched or state check is met. The `condition` method is directly inspired by [the `condition` function in Temporal.io's workflow API](https://docs.temporal.io/docs/typescript/workflows/#condition) (credit to [@swyx](https://twitter.com/swyx) for the suggestion!), and `take` is inspired by [the `take` effect from Redux-Saga](https://redux-saga.js.org/docs/api#takepattern).\n\nThe signatures are:\n\n```ts no-transpile\ntype ConditionFunction<Action extends ReduxAction, State> = (\n  predicate: ListenerPredicate<Action, State> | (() => boolean),\n  timeout?: number,\n) => Promise<boolean>\n\ntype TakeFunction<Action extends ReduxAction, State> = (\n  predicate: ListenerPredicate<Action, State> | (() => boolean),\n  timeout?: number,\n) => Promise<[Action, State, State] | null>\n```\n\nYou can use `await condition(somePredicate)` as a way to pause execution of your listener callback until some criteria is met.\n\nThe `predicate` will be called after every action is processed by the reducers, and should return `true` when the condition should resolve. (It is effectively a one-shot listener itself.) If a `timeout` number (in ms) is provided, the promise will resolve `true` if the `predicate` returns first, or `false` if the timeout expires. This allows you to write comparisons like `if (await condition(predicate, timeout))`.\n\nThis should enable writing longer-running workflows with more complex async logic, such as [the \"cancellable counter\" example from Redux-Saga](https://github.com/redux-saga/redux-saga/blob/1ecb1bed867eeafc69757df8acf1024b438a79e0/examples/cancellable-counter/src/sagas/index.js).\n\nAn example of `condition` usage, from the test suite:\n\n```ts no-transpile\ntest('condition method resolves promise when there is a timeout', async () => {\n  let finalCount = 0\n  let listenerStarted = false\n\n  listenerMiddleware.startListening({\n    predicate: (action, currentState: CounterState) => {\n      return increment.match(action) && currentState.value === 0\n    },\n    effect: async (action, listenerApi) => {\n      listenerStarted = true\n      // Wait for either the counter to hit 3, or 50ms to elapse\n      const result = await listenerApi.condition(\n        (action, currentState: CounterState) => {\n          return currentState.value === 3\n        },\n        50,\n      )\n\n      // In this test, we expect the timeout to happen first\n      expect(result).toBe(false)\n      // Save the state for comparison outside the listener\n      const latestState = listenerApi.getState()\n      finalCount = latestState.value\n    },\n  })\n\n  store.dispatch(increment())\n  // The listener should have started right away\n  expect(listenerStarted).toBe(true)\n\n  store.dispatch(increment())\n\n  // If we wait 150ms, the condition timeout will expire first\n  await delay(150)\n  // Update the state one more time to confirm the listener isn't checking it\n  store.dispatch(increment())\n\n  // Handled the state update before the delay, but not after\n  expect(finalCount).toBe(2)\n})\n```\n\n### Cancellation and Task Management\n\nThe listener middleware supports cancellation of running listener instances, `take/condition/pause/delay` functions, and \"child tasks\", with an implementation based on [`AbortController`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController).\n\nThe `listenerApi.pause/delay()` functions provide a cancellation-aware way to have the current listener sleep. `pause()` accepts a promise, while `delay` accepts a timeout value. If the listener is cancelled while waiting, a `TaskAbortError` will be thrown. In addition, both `take` and `condition` support cancellation interruption as well.\n\n`listenerApi.cancelActiveListeners()` will cancel _other_ existing instances that are running, while `listenerApi.cancel()` can be used to cancel the _current_ instance (which may be useful from a fork, which could be deeply nested and not able to directly throw a promise to break out of the effect execution). `listenerAPi.throwIfCancelled()` can also be useful to bail out of workflows in case cancellation happened while the effect was doing other work.\n\n`listenerApi.fork()` can used to launch \"child tasks\" that can do additional work. These can be waited on to collect their results. An example of this might look like:\n\n```ts no-transpile\nlistenerMiddleware.startListening({\n  actionCreator: increment,\n  effect: async (action, listenerApi) => {\n    // Spawn a child task and start it immediately\n    const task = listenerApi.fork(async (forkApi) => {\n      // Artificially wait a bit inside the child\n      await forkApi.delay(5)\n      // Complete the child by returning a value\n      return 42\n    })\n\n    const result = await task.result\n    // Unwrap the child result in the listener\n    if (result.status === 'ok') {\n      // Logs the `42` result value that was returned\n      console.log('Child succeeded: ', result.value)\n    }\n  },\n})\n```\n\n### Complex Async Workflows\n\nThe provided async workflow primitives (`cancelActiveListeners`, `cancel`, `unsubscribe`, `subscribe`, `take`, `condition`, `pause`, `delay`) can be used to implement behavior that is equivalent to many of the more complex async workflow capabilities found in the Redux-Saga library. This includes effects such as `throttle`, `debounce`, `takeLatest`, `takeLeading`, and `fork/join`. Some examples from the test suite:\n\n```js\ntest('debounce / takeLatest', async () => {\n  // Repeated calls cancel previous ones, no work performed\n  // until the specified delay elapses without another call\n  // NOTE: This is also basically identical to `takeLatest`.\n  // Ref: https://redux-saga.js.org/docs/api#debouncems-pattern-saga-args\n  // Ref: https://redux-saga.js.org/docs/api#takelatestpattern-saga-args\n\n  listenerMiddleware.startListening({\n    actionCreator: increment,\n    effect: async (action, listenerApi) => {\n      // Cancel any in-progress instances of this listener\n      listenerApi.cancelActiveListeners()\n\n      // Delay before starting actual work\n      await listenerApi.delay(15)\n\n      // do work here\n    },\n  })\n}\n\ntest('takeLeading', async () => {\n  // Starts listener on first action, ignores others until task completes\n  // Ref: https://redux-saga.js.org/docs/api#takeleadingpattern-saga-args\n\n  listenerMiddleware.startListening({\n    actionCreator: increment,\n    effect: async (action, listenerApi) => {\n      listenerCalls++\n\n      // Stop listening for this action\n      listenerApi.unsubscribe()\n\n      // Pretend we're doing expensive work\n\n      // Re-enable the listener\n      listenerApi.subscribe()\n    },\n  })\n})\n\ntest('cancelled', async () => {\n  // cancelled allows checking if the current task was cancelled\n  // Ref: https://redux-saga.js.org/docs/api#cancelled\n\n  let canceledAndCaught = false\n  let canceledCheck = false\n\n  // Example of canceling prior instances conditionally and checking cancellation\n  listenerMiddleware.startListening({\n    matcher: isAnyOf(increment, decrement, incrementByAmount),\n    effect: async (action, listenerApi) => {\n      if (increment.match(action)) {\n        // Have this branch wait around to be cancelled by the other\n        try {\n          await listenerApi.delay(10)\n        } catch (err) {\n          // Can check cancellation based on the exception and its reason\n          if (err instanceof TaskAbortError) {\n            canceledAndCaught = true\n          }\n        }\n      } else if (incrementByAmount.match(action)) {\n        // do a non-cancellation-aware wait\n        await delay(15)\n        if (listenerApi.signal.aborted) {\n          canceledCheck = true\n        }\n      } else if (decrement.match(action)) {\n        listenerApi.cancelActiveListeners()\n      }\n    },\n  })\n})\n```\n\nAs a more practical example: [this saga-based \"long polling\" loop](https://gist.github.com/markerikson/5203e71a69fa9dff203c9e27c3d84154) repeatedly asks the server for a message and then processes each response. The child loop is started on demand when a \"start polling\" action is dispatched, and the loop is cancelled when a \"stop polling\" action is dispatched.\n\nThat approach can be implemented via the listener middleware:\n\n```ts no-transpile\n// Track how many times each message was processed by the loop\nconst receivedMessages = {\n  a: 0,\n  b: 0,\n  c: 0,\n}\n\nconst eventPollingStarted = createAction('serverPolling/started')\nconst eventPollingStopped = createAction('serverPolling/stopped')\n\nlistenerMiddleware.startListening({\n  actionCreator: eventPollingStarted,\n  effect: async (action, listenerApi) => {\n    // Only allow one instance of this listener to run at a time\n    listenerApi.unsubscribe()\n\n    // Start a child job that will infinitely loop receiving messages\n    const pollingTask = listenerApi.fork(async (forkApi) => {\n      try {\n        while (true) {\n          // Cancellation-aware pause for a new server message\n          const serverEvent = await forkApi.pause(pollForEvent())\n          // Process the message. In this case, just count the times we've seen this message.\n          if (serverEvent.type in receivedMessages) {\n            receivedMessages[\n              serverEvent.type as keyof typeof receivedMessages\n            ]++\n          }\n        }\n      } catch (err) {\n        if (err instanceof TaskAbortError) {\n          // could do something here to track that the task was cancelled\n        }\n      }\n    })\n\n    // Wait for the \"stop polling\" action\n    await listenerApi.condition(eventPollingStopped.match)\n    pollingTask.cancel()\n  },\n})\n```\n\n### Adding Listeners Inside Components\n\nListeners can be added at runtime via `dispatch(addListener())`. This means that you can add listeners anywhere you have access to `dispatch`, and that includes React components.\n\nSince dispatching `addListener` returns an `unsubscribe` callback, this naturally maps to the behavior of React `useEffect` hooks, which let you return a cleanup function. You can add a listener in an effect, and remove the listener when the hook is cleaned up.\n\nThe basic pattern might look like:\n\n```js\nuseEffect(() => {\n  // Could also just `return dispatch(addListener())` directly, but showing this\n  // as a separate variable to be clear on what's happening\n  const unsubscribe = dispatch(\n    addListener({\n      actionCreator: todoAdded,\n      effect: (action, listenerApi) => {\n        // do some useful logic here\n      },\n    }),\n  )\n  return unsubscribe\n}, [])\n```\n\nWhile this pattern is _possible_, **we do not necessarily _recommend_ doing this!** The React and Redux communities have always tried to emphasize basing behavior on _state_ as much as possible. Having React components directly tie into the Redux action dispatch pipeline could potentialy lead to codebases that are more difficult to maintain.\n\nAt the same time, this _is_ a valid technique, both in terms of API behavior and potential use cases. It's been common to lazy-load sagas as part of a code-split app, and that has often required some complex additional setup work to \"inject\" sagas. In contrast, `dispatch(addListener())` fits naturally into a React component's lifecycle.\n\nSo, while we're not specifically encouraging use of this pattern, it's worth documenting here so that users are aware of it as a possibility.\n\n### Organizing Listeners in Files\n\nAs a starting point, **it's best to create the listener middleware in a separate file, such as `app/listenerMiddleware.ts`, rather than in the same file as the store**. This avoids any potential circular import problems from other files trying to import `middleware.addListener`.\n\nFrom there, so far we've come up with three different ways to organize listener functions and setup.\n\nFirst, you can import effect callbacks from slice files into the middleware file, and add the listeners:\n\n```ts no-transpile title=\"app/listenerMiddleware.ts\"\nimport { action1, listener1 } from '../features/feature1/feature1Slice'\nimport { action2, listener2 } from '../features/feature2/feature2Slice'\n\nlistenerMiddleware.startListening({ actionCreator: action1, effect: listener1 })\nlistenerMiddleware.startListening({ actionCreator: action2, effect: listener2 })\n```\n\nThis is probably the simplest option, and mirrors how the store setup pulls together all the slice reducers to create the app.\n\nThe second option is the opposite: have the slice files import the middleware and directly add their listeners:\n\n```ts no-transpile  title=\"features/feature1/feature1Slice.ts\"\nimport { listenerMiddleware } from '../../app/listenerMiddleware'\n\nconst feature1Slice = createSlice(/* */)\nconst { action1 } = feature1Slice.actions\n\nexport default feature1Slice.reducer\n\nlistenerMiddleware.startListening({\n  actionCreator: action1,\n  effect: () => {},\n})\n```\n\nThis keeps all the logic in the slice, although it does lock the setup into a single middleware instance.\n\nThe third option is to create a setup function in the slice, but let the listener file call that on startup:\n\n```ts no-transpile  title=\"features/feature1/feature1Slice.ts\"\nimport type { AppStartListening } from '../../app/listenerMiddleware'\n\nconst feature1Slice = createSlice(/* */)\nconst { action1 } = feature1Slice.actions\n\nexport default feature1Slice.reducer\n\nexport const addFeature1Listeners = (startListening: AppStartListening) => {\n  startListening({\n    actionCreator: action1,\n    effect: () => {},\n  })\n}\n```\n\n```ts no-transpile title=\"app/listenerMiddleware.ts\"\nimport { addFeature1Listeners } from '../features/feature1/feature1Slice'\n\naddFeature1Listeners(listenerMiddleware.startListening)\n```\n\nFeel free to use whichever of these approaches works best in your app.\n"
  },
  {
    "path": "docs/api/createReducer.mdx",
    "content": "---\nid: createReducer\ntitle: createReducer\nsidebar_label: createReducer\nhide_title: true\n---\n\n&nbsp;\n\n# `createReducer()`\n\n## Overview\n\nA utility that simplifies creating Redux reducer functions. It uses Immer internally to drastically simplify immutable update logic\nby writing \"mutative\" code in your reducers, and supports directly mapping specific action types to case reducer functions\nthat will update the state when that action is dispatched.\n\nRedux [reducers](https://redux.js.org/basics/reducers) are often implemented using a `switch` statement, with one `case` for every handled action type.\n\n```js\nconst initialState = { value: 0 }\n\nfunction counterReducer(state = initialState, action) {\n  switch (action.type) {\n    case 'increment':\n      return { ...state, value: state.value + 1 }\n    case 'decrement':\n      return { ...state, value: state.value - 1 }\n    case 'incrementByAmount':\n      return { ...state, value: state.value + action.payload }\n    default:\n      return state\n  }\n}\n```\n\nThis approach works well, but is a bit boilerplate-y and error-prone. For instance, it is easy to forget the `default` case or\nsetting the initial state.\n\nThe `createReducer` helper streamlines the implementation of such reducers. It uses a \"builder callback\" notation to define handlers for specific action types, matching against a range of actions, or handling a default case. This is conceptually similar to a switch statement, but with better TS support.\n\nWith `createReducer`, your reducers instead look like:\n\n```ts\nimport { createAction, createReducer } from '@reduxjs/toolkit'\n\ninterface CounterState {\n  value: number\n}\n\nconst increment = createAction('counter/increment')\nconst decrement = createAction('counter/decrement')\nconst incrementByAmount = createAction<number>('counter/incrementByAmount')\n\nconst initialState = { value: 0 } satisfies CounterState as CounterState\n\nconst counterReducer = createReducer(initialState, (builder) => {\n  builder\n    .addCase(increment, (state, action) => {\n      state.value++\n    })\n    .addCase(decrement, (state, action) => {\n      state.value--\n    })\n    .addCase(incrementByAmount, (state, action) => {\n      state.value += action.payload\n    })\n})\n```\n\n## Usage with the \"Builder Callback\" Notation\n\n[overloadSummary](docblock://createReducer.ts?token=createReducer)\n\n### Parameters\n\n[params](docblock://createReducer.ts?token=createReducer)\n\n### Example Usage\n\n[examples](docblock://createReducer.ts?token=createReducer)\n\n### Builder Methods\n\n### `builder.addCase`\n\n[summary,remarks](docblock://mapBuilders.ts?token=ActionReducerMapBuilder.addCase)\n\n#### Parameters\n\n[params,examples](docblock://mapBuilders.ts?token=ActionReducerMapBuilder.addCase)\n\n### `builder.addAsyncThunk`\n\n[summary,remarks](docblock://mapBuilders.ts?token=ActionReducerMapBuilder.addAsyncThunk)\n\n#### Parameters\n\n[params,examples](docblock://mapBuilders.ts?token=ActionReducerMapBuilder.addAsyncThunk)\n\n### `builder.addMatcher`\n\n[summary,remarks](docblock://mapBuilders.ts?token=ActionReducerMapBuilder.addMatcher)\n\n#### Parameters\n\n[params,examples](docblock://mapBuilders.ts?token=ActionReducerMapBuilder.addMatcher)\n\n### `builder.addDefaultCase`\n\n[summary,remarks](docblock://mapBuilders.ts?token=ActionReducerMapBuilder.addDefaultCase)\n\n#### Parameters\n\n[params,examples](docblock://mapBuilders.ts?token=ActionReducerMapBuilder.addDefaultCase)\n\n### Returns\n\nThe generated reducer function.\n\nThe reducer will have a `getInitialState` function attached that will return the initial state when called. This may be useful for tests or usage with React's `useReducer` hook:\n\n```js\nconst counterReducer = createReducer(0, (builder) => {\n  builder\n    .addCase('increment', (state, action) => state + action.payload)\n    .addCase('decrement', (state, action) => state - action.payload)\n})\n\nconsole.log(counterReducer.getInitialState()) // 0\n```\n\n### Example Usage\n\n[examples](docblock://createReducer.ts?token=createReducer)\n\n## Direct State Mutation\n\nRedux requires reducer functions to be pure and treat state values as immutable. While this is essential for making state updates predictable and observable, it can sometimes make the implementation of such updates awkward. Consider the following example:\n\n```ts\nimport { createAction, createReducer } from '@reduxjs/toolkit'\n\ninterface Todo {\n  text: string\n  completed: boolean\n}\n\nconst addTodo = createAction<Todo>('todos/add')\nconst toggleTodo = createAction<number>('todos/toggle')\n\nconst todosReducer = createReducer([] as Todo[], (builder) => {\n  builder\n    .addCase(addTodo, (state, action) => {\n      const todo = action.payload\n      return [...state, todo]\n    })\n    .addCase(toggleTodo, (state, action) => {\n      const index = action.payload\n      const todo = state[index]\n      return [\n        ...state.slice(0, index),\n        { ...todo, completed: !todo.completed },\n        ...state.slice(index + 1),\n      ]\n    })\n})\n```\n\nThe `addTodo` reducer is straightforward if you know the [ES6 spread syntax](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax). However, the code for `toggleTodo` is much less straightforward, especially considering that it only sets a single flag.\n\nTo make things easier, `createReducer` uses [immer](https://github.com/mweststrate/immer) to let you write reducers as if they were mutating the state directly. In reality, the reducer receives a proxy state that translates all mutations into equivalent copy operations.\n\n```ts\nimport { createAction, createReducer } from '@reduxjs/toolkit'\n\ninterface Todo {\n  text: string\n  completed: boolean\n}\n\nconst addTodo = createAction<Todo>('todos/add')\nconst toggleTodo = createAction<number>('todos/toggle')\n\nconst todosReducer = createReducer([] as Todo[], (builder) => {\n  builder\n    .addCase(addTodo, (state, action) => {\n      // This push() operation gets translated into the same\n      // extended-array creation as in the previous example.\n      const todo = action.payload\n      state.push(todo)\n    })\n    .addCase(toggleTodo, (state, action) => {\n      // The \"mutating\" version of this case reducer is much\n      //  more direct than the explicitly pure one.\n      const index = action.payload\n      const todo = state[index]\n      todo.completed = !todo.completed\n    })\n})\n```\n\nWriting \"mutating\" reducers simplifies the code. It's shorter, there's less indirection, and it eliminates common mistakes made while spreading nested state. However, the use of Immer does add some \"magic\", and Immer has its own nuances in behavior. You should read through [pitfalls mentioned in the immer docs](https://immerjs.github.io/immer/pitfalls) . Most importantly, **you need to ensure that you either mutate the `state` argument or return a new state, _but not both_**. For example, the following reducer would throw an exception if a `toggleTodo` action is passed:\n\n```ts\nimport { createAction, createReducer } from '@reduxjs/toolkit'\n\ninterface Todo {\n  text: string\n  completed: boolean\n}\n\nconst toggleTodo = createAction<number>('todos/toggle')\n\nconst todosReducer = createReducer([] as Todo[], (builder) => {\n  builder.addCase(toggleTodo, (state, action) => {\n    const index = action.payload\n    const todo = state[index]\n\n    // This case reducer both mutates the passed-in state...\n    todo.completed = !todo.completed\n\n    // ... and returns a new value. This will throw an\n    // exception. In this example, the easiest fix is\n    // to remove the `return` statement.\n    return [...state.slice(0, index), todo, ...state.slice(index + 1)]\n  })\n})\n```\n\n## Multiple Case Reducer Execution\n\nOriginally, `createReducer` always matched a given action type to a single case reducer, and only that one case reducer would execute for a given action.\n\nUsing action matchers changes that behavior, as multiple matchers may handle a single action.\n\nFor any dispatched action, the behavior is:\n\n- If there is an exact match for the action type, the corresponding case reducer will execute first\n- Any matchers that return `true` will execute in the order they were defined\n- If a default case reducer is provided, and _no_ case or matcher reducers ran, the default case reducer will execute\n- If no case or matcher reducers ran, the original existing state value will be returned unchanged\n\nThe executing reducers form a pipeline, and each of them will receive the output of the previous reducer:\n\n```ts\nimport { createReducer } from '@reduxjs/toolkit'\n\nconst reducer = createReducer(0, (builder) => {\n  builder\n    .addCase('increment', (state) => state + 1)\n    .addMatcher(\n      (action) => action.type.startsWith('i'),\n      (state) => state * 5,\n    )\n    .addMatcher(\n      (action) => action.type.endsWith('t'),\n      (state) => state + 2,\n    )\n})\n\nconsole.log(reducer(0, { type: 'increment' }))\n// Returns 7, as the 'increment' case and both matchers all ran in sequence:\n// - case 'increment\": 0 => 1\n// - matcher starts with 'i': 1 => 5\n// - matcher ends with 't': 5 => 7\n```\n\n## Logging Draft State Values\n\nIt's very common for a developer to call `console.log(state)` during the development process. However, browsers display Proxies in a format that is hard to read, which can make console logging of Immer-based state difficult.\n\nWhen using either `createSlice` or `createReducer`, you may use the [`current`](./otherExports.mdx#current) utility that we re-export from the [`immer` library](https://immerjs.github.io/immer/current). This utility creates a separate plain copy of the current Immer `Draft` state value, which can then be logged for viewing as normal.\n\n```ts\nimport { createSlice, current } from '@reduxjs/toolkit'\n\nconst slice = createSlice({\n  name: 'todos',\n  initialState: [{ id: 1, title: 'Example todo' }],\n  reducers: {\n    addTodo: (state, action) => {\n      console.log('before', current(state))\n      state.push(action.payload)\n      console.log('after', current(state))\n    },\n  },\n})\n```\n"
  },
  {
    "path": "docs/api/createSelector.mdx",
    "content": "---\nid: createSelector\ntitle: createSelector\nsidebar_label: createSelector\nhide_title: true\n---\n\n&nbsp;\n\n# `createSelector`\n\n## Overview\n\nThe `createSelector` utility from the [Reselect library](https://github.com/reduxjs/reselect), re-exported for ease of use.\n\nFor more details on using `createSelector`, see:\n\n- The [Reselect API documentation](https://github.com/reduxjs/reselect)\n- [React-Redux docs: Hooks API - Using memoizing selectors](https://react-redux.js.org/next/api/hooks#using-memoizing-selectors)\n- [Idiomatic Redux: Using Reselect Selectors for Encapsulation and Performance](https://blog.isquaredsoftware.com/2017/12/idiomatic-redux-using-reselect-selectors/)\n- [React/Redux Links: Reducers and Selectors](https://github.com/markerikson/react-redux-links/blob/master/redux-reducers-selectors.md)\n\n:::note\nPrior to v0.7, RTK re-exported `createSelector` from [`selectorator`](https://github.com/planttheidea/selectorator), which\nallowed using string keypaths as input selectors. This was removed, as it ultimately did not provide enough benefits, and\nthe string keypaths made static typing for selectors difficult.\n:::\n\n## `createDraftSafeSelector`\n\nIn general, we recommend against using selectors inside of reducers:\n\n- Selectors typically expect the entire Redux state object as an argument, while slice reducers only have access to a specific subset of the entire Redux state\n- Reselect's `createSelector` relies on reference comparisons to determine if inputs have changed, and if an Immer Proxy-wrapped draft value is passed in to a selector, the selector may see the same reference and think nothing has changed.\n\nHowever, some users have requested the ability to create selectors that will work correctly inside of Immer-powered reducers. One use case for this might be collecting an ordered set of items when using `createEntityAdapter`, such as `const orderedTodos = todosSelectors.selectAll(todosState)`, and then using `orderedTodos` in the rest of the reducer logic.\n\nBesides re-exporting `createSelector`, RTK also exports a wrapped version of `createSelector` named `createDraftSafeSelector` that allows you to create selectors that can safely be used inside of `createReducer` and `createSlice` reducers with Immer-powered mutable logic. When used with plain state values, the selector will still memoize normally based on the inputs. But, when used with Immer draft values, the selector will err on the side of recalculating the results, just to be safe.\n\nAll selectors created by `entityAdapter.getSelectors` are \"draft safe\" selectors by default.\n\nExample:\n\n```ts no-transpile\nconst selectSelf = (state: State) => state\nconst unsafeSelector = createSelector(selectSelf, (state) => state.value)\nconst draftSafeSelector = createDraftSafeSelector(\n  selectSelf,\n  (state) => state.value,\n)\n\n// in your reducer:\n\nstate.value = 1\n\nconst unsafe1 = unsafeSelector(state)\nconst safe1 = draftSafeSelector(state)\n\nstate.value = 2\n\nconst unsafe2 = unsafeSelector(state)\nconst safe2 = draftSafeSelector(state)\n```\n\nAfter executing that, `unsafe1` and `unsafe2` will be of the same value, because the memoized selector was\nexecuted on the same object - but `safe2` will actually be different from `safe1` (with the updated value of `2`),\nbecause the safe selector detected that it was executed on a Immer draft object and recalculated using the current\nvalue instead of returning a cached value.\n\n:::tip `createDraftSafeSelectorCreator`\n\nRTK also exports a `createDraftSafeSelectorCreator` function, the \"draft safe\" equivalent of [`createSelectorCreator`](https://github.com/reduxjs/reselect#createselectorcreatormemoize-memoizeoptions).\n\n```ts no-transpile\nimport {\n  createDraftSafeSelectorCreator,\n  weakMapMemoize,\n} from '@reduxjs/toolkit'\n\nconst createWeakMapDraftSafeSelector =\n  createDraftSafeSelectorCreator(weakMapMemoize)\n\nconst selectSelf = (state: State) => state\nconst draftSafeSelector = createWeakMapDraftSafeSelector(\n  selectSelf,\n  (state) => state.value,\n)\n```\n\n:::\n\n### Defining a Pre-Typed `createDraftSelector`\n\nAs of RTK 2.1, you can define a \"pre-typed\" version of `createDraftSafeSelector` that can have the type for `state` built in. This lets you set up those types once, so you don't have to repeat them each time you call `createDraftSafeSelector`.\n\n```ts no-transpile\nconst createTypedDraftSafeSelector =\n  createDraftSafeSelector.withTypes<RootState>()\n```\n\nImport and use the pre-typed `createTypedDraftSafeSelector` function, and it will automatically know that the `state` argument is of type `RootState`.\n\n:::warning Known Limitations\nCurrently this approach only works if input selectors are provided as a single array.\n\nIf you pass the input selectors as separate inline arguments, the parameter types of the result function will not be inferred. As a workaround you can either\n\n1. Wrap your input selectors in a single array\n2. You can annotate the parameter types of the result function:\n\n```ts no-transpile\nimport { createSelector } from 'reselect'\n\ninterface Todo {\n  id: number\n  completed: boolean\n}\n\ninterface Alert {\n  id: number\n  read: boolean\n}\n\nexport interface RootState {\n  todos: Todo[]\n  alerts: Alert[]\n}\n\nexport const createTypedDraftSafeSelector =\n  createDraftSafeSelector.withTypes<RootState>()\n\nconst selectTodoIds = createTypedDraftSafeSelector(\n  // Type of `state` is set to `RootState`, no need to manually set the type\n  (state) => state.todos,\n  // ❌ Known limitation: Parameter types are not inferred in this scenario\n  // so you will have to manually annotate them.\n  (todos: Todo[]) => todos.map(({ id }) => id),\n)\n```\n"
  },
  {
    "path": "docs/api/createSlice.mdx",
    "content": "---\nid: createSlice\ntitle: createSlice\nsidebar_label: createSlice\nhide_title: true\n---\n\n&nbsp;\n\n# `createSlice`\n\nA function that accepts an initial state, an object of reducer functions, and a \"slice name\",\nand automatically generates action creators and action types that correspond to the reducers and state.\n\nThis API is the standard approach for writing Redux logic.\n\nInternally, it uses [`createAction`](./createAction.mdx) and [`createReducer`](./createReducer.mdx), so\nyou may also use [Immer](../usage/immer-reducers.md) to write \"mutating\" immutable updates:\n\n```ts\nimport { createSlice } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\n\ninterface CounterState {\n  value: number\n}\n\nconst initialState = { value: 0 } satisfies CounterState as CounterState\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState,\n  reducers: {\n    increment(state) {\n      state.value++\n    },\n    decrement(state) {\n      state.value--\n    },\n    incrementByAmount(state, action: PayloadAction<number>) {\n      state.value += action.payload\n    },\n  },\n})\n\nexport const { increment, decrement, incrementByAmount } = counterSlice.actions\nexport default counterSlice.reducer\n```\n\n## Parameters\n\n`createSlice` accepts a single configuration object parameter, with the following options:\n\n```ts no-transpile\nfunction createSlice({\n    // A name, used in action types\n    name: string,\n    // The initial state for the reducer\n    initialState: State,\n    // An object of \"case reducers\". Key names will be used to generate actions.\n    reducers: Record<string, ReducerFunction | ReducerAndPrepareObject>,\n    // A \"builder callback\" function used to add more reducers\n    extraReducers?: (builder: ActionReducerMapBuilder<State>) => void,\n    // A preference for the slice reducer's location, used by `combineSlices` and `slice.selectors`. Defaults to `name`.\n    reducerPath?: string,\n    // An object of selectors, which receive the slice's state as their first parameter.\n    selectors?: Record<string, (sliceState: State, ...args: any[]) => any>,\n})\n```\n\n### `initialState`\n\nThe initial state value for this slice of state.\n\nThis may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n\n### `name`\n\nA string name for this slice of state. Generated action type constants will use this as a prefix.\n\n### `reducers`\n\nAn object containing Redux \"case reducer\" functions (functions intended to handle a specific action type, equivalent\nto a single case statement in a switch).\n\nThe keys in the object will be used to generate string action type constants, and these will show up in the Redux\nDevTools Extension when they are dispatched. Also, if any other part of the application happens to dispatch an action\nwith the exact same type string, the corresponding reducer will be run. Therefore, you should give the functions\ndescriptive names.\n\nThis object will be passed to [`createReducer`](./createReducer.mdx), so the reducers may safely \"mutate\" the\nstate they are given.\n\n```ts\nimport { createSlice } from '@reduxjs/toolkit'\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: 0,\n  reducers: {\n    increment: (state) => state + 1,\n  },\n})\n// Will handle the action type `'counter/increment'`\n```\n\n#### Customizing Generated Action Creators\n\nIf you need to customize the creation of the payload value of an action creator by means of a [`prepare callback`](./createAction.mdx#using-prepare-callbacks-to-customize-action-contents), the value of the appropriate field of the `reducers` argument object should be an object instead of a function. This object must contain two properties: `reducer` and `prepare`. The value of the `reducer` field should be the case reducer function while the value of the `prepare` field should be the prepare callback function:\n\n```ts\nimport { createSlice, nanoid } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\n\ninterface Item {\n  id: string\n  text: string\n}\n\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [] as Item[],\n  reducers: {\n    addTodo: {\n      reducer: (state, action: PayloadAction<Item>) => {\n        state.push(action.payload)\n      },\n      prepare: (text: string) => {\n        const id = nanoid()\n        return { payload: { id, text } }\n      },\n    },\n  },\n})\n```\n\n### The `reducers` \"creator callback\" notation\n\nAlternatively, the `reducers` field can be a callback which receives a \"create\" object.\n\nThe main benefit of this is that you can create [async thunks](./createAsyncThunk) as part of your slice (though for bundle size reasons, you [need a bit of setup for this](#createasyncthunk)). Types are also slightly simplified for prepared reducers.\n\n```ts title=\"Creator callback for reducers\"\nimport { createSlice, nanoid } from '@reduxjs/toolkit'\n\ninterface Item {\n  id: string\n  text: string\n}\n\ninterface TodoState {\n  loading: boolean\n  todos: Item[]\n}\n\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: {\n    loading: false,\n    todos: [],\n  } satisfies TodoState as TodoState,\n  reducers: (create) => ({\n    deleteTodo: create.reducer<number>((state, action) => {\n      state.todos.splice(action.payload, 1)\n    }),\n    addTodo: create.preparedReducer(\n      (text: string) => {\n        const id = nanoid()\n        return { payload: { id, text } }\n      },\n      // action type is inferred from prepare callback\n      (state, action) => {\n        state.todos.push(action.payload)\n      },\n    ),\n    fetchTodo: create.asyncThunk(\n      async (id: string, thunkApi) => {\n        const res = await fetch(`myApi/todos?id=${id}`)\n        return (await res.json()) as Item\n      },\n      {\n        pending: (state) => {\n          state.loading = true\n        },\n        rejected: (state, action) => {\n          state.loading = false\n        },\n        fulfilled: (state, action) => {\n          state.loading = false\n          state.todos.push(action.payload)\n        },\n      },\n    ),\n  }),\n})\n\nexport const { addTodo, deleteTodo, fetchTodo } = todosSlice.actions\n```\n\n#### Create Methods\n\n#### `create.reducer`\n\nA standard slice case reducer.\n\n**Parameters**\n\n- **reducer** The slice case reducer to use.\n\n```ts no-transpile\ncreate.reducer<Todo>((state, action) => {\n  state.todos.push(action.payload)\n})\n```\n\n#### `create.preparedReducer`\n\nA [prepared](#customizing-generated-action-creators) reducer, to customize the action creator.\n\n**Parameters**\n\n- **prepareAction** The [`prepare callback`](./createAction#using-prepare-callbacks-to-customize-action-contents).\n- **reducer** The slice case reducer to use.\n\nThe action passed to the case reducer will be inferred from the prepare callback's return.\n\n```ts no-transpile\ncreate.preparedReducer(\n  (text: string) => {\n    const id = nanoid()\n    return { payload: { id, text } }\n  },\n  (state, action) => {\n    state.todos.push(action.payload)\n  },\n)\n```\n\n#### `create.asyncThunk`\n\nCreates an async thunk instead of an action creator.\n\n:::caution Setup\n\nTo avoid pulling `createAsyncThunk` into the bundle size of `createSlice` by default, some extra setup is required to use `create.asyncThunk`.\n\nThe version of `createSlice` exported from RTK will throw an error if `create.asyncThunk` is called.\n\nInstead, import `buildCreateSlice` and `asyncThunkCreator`, and create your own version of `createSlice`:\n\n```ts\nimport { buildCreateSlice, asyncThunkCreator } from '@reduxjs/toolkit'\n\nexport const createAppSlice = buildCreateSlice({\n  creators: { asyncThunk: asyncThunkCreator },\n})\n```\n\nThen import this `createAppSlice` as needed instead of the exported version from RTK.\n\n:::\n\n**Parameters**\n\n- **payloadCreator** The thunk [payload creator](./createAsyncThunk#payloadcreator).\n- **config** The configuration object. (optional)\n\nThe configuration object can contain case reducers for each of the [lifecycle actions](./createAsyncThunk#promise-lifecycle-actions) (`pending`, `fulfilled`, and `rejected`), as well as a `settled` reducer that will run for both fulfilled and rejected actions (note that this will run _after_ any provided `fulfilled`/`rejected` reducers. Conceptually it can be thought of like a `finally` block.).\n\nEach case reducer will be attached to the slice's `caseReducers` object, e.g. `slice.caseReducers.fetchTodo.fulfilled`.\n\nThe configuration object can also contain [`options`](./createAsyncThunk#options).\n\n```ts no-transpile\ncreate.asyncThunk(\n  async (id: string, thunkApi) => {\n    const res = await fetch(`myApi/todos?id=${id}`)\n    return (await res.json()) as Item\n  },\n  {\n    pending: (state) => {\n      state.loading = true\n    },\n    rejected: (state, action) => {\n      state.error = action.payload ?? action.error\n    },\n    fulfilled: (state, action) => {\n      state.todos.push(action.payload)\n    },\n    settled: (state, action) => {\n      state.loading = false\n    }\n    options: {\n      idGenerator: uuid,\n    },\n  }\n)\n```\n\n:::note\n\nTyping for the `create.asyncThunk` works in the same way as [`createAsyncThunk`](../usage/usage-with-typescript#createasyncthunk), with one key difference.\n\nA type for `state` and/or `dispatch` _cannot_ be provided as part of the `ThunkApiConfig`, as this would cause circular types.\n\nInstead, it is necessary to assert the type when needed - `getState() as RootState`. You may also include an explicit return type for the payload function as well, in order to break the circular type inference cycle.\n\n```ts no-transpile\ncreate.asyncThunk<Todo, string, { rejectValue: { error: string } }>(\n  // highlight-start\n  // may need to include an explicit return type\n  async (id: string, thunkApi): Promise<Todo> => {\n    // Cast types for `getState` and `dispatch` manually\n    const state = thunkApi.getState() as RootState\n    const dispatch = thunkApi.dispatch as AppDispatch\n    // highlight-end\n    try {\n      const todo = await fetchTodo()\n      return todo\n    } catch (e) {\n      throw thunkApi.rejectWithValue({\n        error: 'Oh no!',\n      })\n    }\n  },\n)\n```\n\nFor common thunk API configuration options, a [`withTypes` helper](../usage/usage-with-typescript#defining-a-pre-typed-createasyncthunk) is provided:\n\n```ts no-transpile\nreducers: (create) => {\n  const createAThunk = create.asyncThunk.withTypes<{\n    rejectValue: { error: string }\n  }>()\n\n  return {\n    fetchTodo: createAThunk<Todo, string>(async (id, thunkApi) => {\n      throw thunkApi.rejectWithValue({\n        error: 'Oh no!',\n      })\n    }),\n    fetchTodos: createAThunk<Todo[], string>(async (id, thunkApi) => {\n      throw thunkApi.rejectWithValue({\n        error: 'Oh no, not again!',\n      })\n    }),\n  }\n}\n```\n\n:::\n\n### `extraReducers`\n\nConceptually, each slice reducer \"owns\" its slice of state. There's also a natural correspondence between the update logic defined inside `reducers`, and the action types that are generated based on those.\n\nHowever, there are many times that a Redux slice may also need to update its own state in response to action types that were defined elsewhere in the application (such as clearing many different kinds of data when a \"user logged out\" action is dispatched). This can include action types defined by another `createSlice` call, actions generated by a `createAsyncThunk`, RTK Query endpoint matchers, or any other action. In addition, one of the key concepts of Redux is that many slice reducers can independently respond to the same action type.\n\n**`extraReducers` allows `createSlice` to respond and update its own state in response to other action types besides the types it has generated.**\n\nAs with the `reducers` field, each case reducer in `extraReducers` is [wrapped in Immer and may use \"mutating\" syntax to safely update the state inside](../usage/immer-reducers.md).\n\nHowever, unlike the `reducers` field, each individual case reducer inside of `extraReducers` will _not_ generate a new action type or action creator.\n\nIf two fields from `reducers` and `extraReducers` happen to end up with the same action type string, the function from `reducers` will be used to handle that action type.\n\n#### The `extraReducers` \"builder callback\" notation\n\nSimilar to `createReducer`, the `extraReducers` field uses a \"builder callback\" notation to define handlers for specific action types, matching against a range of actions, or handling a default case. This is conceptually similar to a switch statement, but with better TS support as it can infer the action type from the provided action creator. It's particularly useful for working with actions produced by `createAction` and `createAsyncThunk`.\n\n[examples](docblock://createSlice.ts?token=CreateSliceOptions.extraReducers)\n\nSee [the \"Builder Callback Notation\" section of the `createReducer` reference](./createReducer.mdx#usage-with-the-builder-callback-notation) for details on how to use `builder.addCase`, `builder.addMatcher`, and `builder.addDefaultCase`\n\n### `reducerPath`\n\nIndicates a preference of where the slice should be located. Defaults to [`name`](#name).\n\nThis is used by `combineSlices` and the default generated `slice.selectors`.\n\n### `selectors`\n\nA set of selectors that receive the slice state as their first parameter, and any other parameters.\n\nEach selector will have a corresponding key in the resulting [`selectors`](#selectors-1) object.\n\n:::caution Circular types\n\nIt's fairly common to have selectors that use other selectors. This is still possible with slice selectors, but defining a selector without a return type can cause a circular type inference problem:\n\n```ts no-transpile\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 },\n  reducers: {},\n  selectors: {\n    selectValue: (state) => state.value,\n    // highlight-start\n    // this creates a cycle, because it's inferring a type from the object we're creating here\n    selectTimes: (state, times = 1) =>\n      counterSlice.getSelectors().selectValue(state) * times,\n    // highlight-end\n  },\n})\n```\n\nThis cycle can be fixed by providing an explicit return type for the selector:\n\n```ts no-transpile\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 },\n  reducers: {},\n  selectors: {\n    selectValue: (state) => state.value,\n    // highlight-start\n    // explicit return type means cycle is broken\n    selectTimes: (state, times = 1): number =>\n      counterSlice.getSelectors().selectValue(state) * times,\n    // highlight-end\n  },\n})\n```\n\nThis limitation may be also encountered when using a slice's `asyncThunk` creator.\nIn the same way, the issue is resolved by explicitly providing a type somewhere in the chain and breaking the cycle.\n\n```ts no-transpile\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 },\n  reducers: (create) => ({\n    getCountData: create.asyncThunk(async (_arg, { getState }) => {\n      const currentCount = counterSlice.selectors.selectValue(\n        getState() as RootState,\n      )\n      // highlight-start\n      // this would cause a circular type, but the type annotation breaks the circle\n      const result: Response = await fetch('api/' + currentCount)\n      // highlight-end\n      return result.json()\n    }),\n  }),\n  selectors: {\n    selectValue: (state) => state.value,\n  },\n})\n```\n\n:::\n\n## Return Value\n\n`createSlice` will return an object that looks like:\n\n```ts no-transpile\n{\n    name: string,\n    reducer: ReducerFunction,\n    actions: Record<string, ActionCreator>,\n    caseReducers: Record<string, CaseReducer>.\n    getInitialState: () => State,\n    reducerPath: string,\n    selectSlice: Selector;\n    selectors: Record<string, Selector>,\n    getSelectors: (selectState: (rootState: RootState) => State) => Record<string, Selector>\n    injectInto: (injectable: Injectable, config?: InjectConfig & { reducerPath?: string }) => InjectedSlice\n}\n```\n\nEach function defined in the `reducers` argument will have a corresponding action creator generated using [`createAction`](./createAction.mdx)\nand included in the result's `actions` field using the same function name.\n\nThe generated `reducer` function is suitable for passing to the Redux `combineReducers` function as a \"slice reducer\".\n\nYou may want to consider destructuring the action creators and exporting them individually, for ease of searching\nfor references in a larger codebase.\n\nThe functions passed to the `reducers` parameter can be accessed through the `caseReducers` return field. This can be particularly useful for testing or direct access to reducers created inline.\n\nResult's function `getInitialState` provides access to the initial state value given to the slice. If a lazy state initializer was provided, it will be called and a fresh value returned.\n\n`injectInto` creates an instance of the slice that is aware it's been injected - see [`combineSlices`](./combineSlices#slice-integration).\n\n:::note\nThe result object is conceptually similar to a\n[\"Redux duck\" code structure](https://redux.js.org/faq/code-structure#what-should-my-file-structure-look-like-how-should-i-group-my-action-creators-and-reducers-in-my-project-where-should-my-selectors-go).\nThe actual code structure you use is up to you, but it's worth keeping in mind that actions are not exclusively limited to a single slice.\nAny part of the reducer logic can (and should!) respond to any dispatched action.\n:::\n\n### Selectors\n\nSlice selectors are written to expect the slice's state as their first parameter, but the slice may be located anywhere inside the store's root state.\n\nAs a result, there are two ways of getting final selectors:\n\n#### `selectors`\n\nMost commonly, the slice is reliably mounted under its [`reducerPath`](#reducerpath).\n\nFollowing this, the slice has a `selectSlice` selector attached, which assumes that the slice is located under `rootState[slice.reducerPath]`.\n\n`slice.selectors` then uses this selector to wrap each of the selectors provided.\n\n```ts\nimport { createSlice } from '@reduxjs/toolkit'\n\ninterface CounterState {\n  value: number\n}\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 } satisfies CounterState as CounterState,\n  reducers: {\n    // omitted\n  },\n  selectors: {\n    selectValue: (sliceState) => sliceState.value,\n  },\n})\n\nconsole.log(counterSlice.selectSlice({ counter: { value: 2 } })) // { value: 2 }\n\nconst { selectValue } = counterSlice.selectors\n\nconsole.log(selectValue({ counter: { value: 2 } })) // 2\n```\n\n:::note\n\nThe original selector passed is attached to the wrapped selector as `.unwrapped`. For example:\n\n```ts\nimport { createSlice, createSelector } from '@reduxjs/toolkit'\n\ninterface CounterState {\n  value: number\n}\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 } satisfies CounterState as CounterState,\n  reducers: {\n    // omitted\n  },\n  selectors: {\n    selectDouble: createSelector(\n      (sliceState: CounterState) => sliceState.value,\n      (value) => value * 2,\n    ),\n  },\n})\n\nconst { selectDouble } = counterSlice.selectors\n\nconsole.log(selectDouble({ counter: { value: 2 } })) // 4\nconsole.log(selectDouble({ counter: { value: 3 } })) // 6\nconsole.log(selectDouble.unwrapped.recomputations) // 2\n```\n\n:::\n\n#### `getSelectors`\n\n`slice.getSelectors` is called with a single parameter, a `selectState` callback. This function should receive the store root state (or whatever you expect to call the resulting selectors with) and return the slice state.\n\n```ts no-transpile\nconst { selectValue } = counterSlice.getSelectors(\n  (rootState: RootState) => rootState.aCounter,\n)\n\nconsole.log(selectValue({ aCounter: { value: 2 } })) // 2\n```\n\nIf no `selectState` callback is passed, selectors will be returned as is - expecting the slice state as their first parameter (the same as calling `slice.getSelectors(state => state)`).\n\n```ts no-transpile\nconst { selectValue } = counterSlice.getSelectors()\n\nconsole.log(selectValue({ value: 2 })) // 2\n```\n\n:::note\nThe [`slice.selectors`](#selectors-2) object is the equivalent of calling\n\n```ts no-transpile\nconst { selectValue } = counterSlice.getSelectors(counterSlice.selectSlice)\n// or\nconst { selectValue } = counterSlice.getSelectors(\n  (state: RootState) => state[counterSlice.reducerPath],\n)\n```\n\n:::\n\n## Examples\n\n```ts\nimport { createSlice, createAction, configureStore } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\nimport { combineReducers } from 'redux'\n\nconst incrementBy = createAction<number>('incrementBy')\nconst decrementBy = createAction<number>('decrementBy')\n\nconst counter = createSlice({\n  name: 'counter',\n  initialState: 0 satisfies number as number,\n  reducers: {\n    increment: (state) => state + 1,\n    decrement: (state) => state - 1,\n    multiply: {\n      reducer: (state, action: PayloadAction<number>) => state * action.payload,\n      prepare: (value?: number) => ({ payload: value || 2 }), // fallback if the payload is a falsy value\n    },\n  },\n  extraReducers: (builder) => {\n    builder.addCase(incrementBy, (state, action) => {\n      return state + action.payload\n    })\n    builder.addCase(decrementBy, (state, action) => {\n      return state - action.payload\n    })\n  },\n})\n\nconst user = createSlice({\n  name: 'user',\n  initialState: { name: '', age: 20 },\n  reducers: {\n    setUserName: (state, action) => {\n      state.name = action.payload // mutate the state all you want with immer\n    },\n  },\n  extraReducers: (builder) => {\n    builder.addCase(counter.actions.increment, (state, action) => {\n      state.age += 1\n    })\n  },\n})\n\nconst store = configureStore({\n  reducer: {\n    counter: counter.reducer,\n    user: user.reducer,\n  },\n})\n\nstore.dispatch(counter.actions.increment())\n// -> { counter: 1, user: {name : '', age: 21} }\nstore.dispatch(counter.actions.increment())\n// -> { counter: 2, user: {name: '', age: 22} }\nstore.dispatch(counter.actions.multiply(3))\n// -> { counter: 6, user: {name: '', age: 22} }\nstore.dispatch(counter.actions.multiply())\n// -> { counter: 12, user: {name: '', age: 22} }\nconsole.log(counter.actions.decrement.type)\n// -> \"counter/decrement\"\nstore.dispatch(user.actions.setUserName('eric'))\n// -> { counter: 12, user: { name: 'eric', age: 22} }\n```\n"
  },
  {
    "path": "docs/api/getDefaultEnhancers.mdx",
    "content": "---\nid: getDefaultEnhancers\ntitle: getDefaultEnhancers\nsidebar_label: getDefaultEnhancers\nhide_title: true\n---\n\n&nbsp;\n\n# `getDefaultEnhancers`\n\nReturns an array containing the default list of enhancers.\n\n## Intended Usage\n\nBy default, [`configureStore`](./configureStore.mdx) adds some enhancers to the Redux store setup automatically.\n\n```js\nconst store = configureStore({\n  reducer: rootReducer,\n})\n\n// Store has enhancers added, because the enhancer list was not customized\n```\n\nIf you want to customise the list of enhancers, you can supply an array of enhancer functions to `configureStore`:\n\n```js\nconst store = configureStore({\n  reducer: rootReducer,\n  enhancers: () => new Tuple(offline(offlineConfig)),\n})\n\n// store specifically has the offline enhancer applied\n```\n\nHowever, when you supply the `enhancer` option, you are responsible for defining _all_ the enhancers you want added\nto the store (with the exception of the [devtools](./configureStore#devtools)). `configureStore` will not add any extra enhancers beyond what you listed, **including the middleware enhancer**.\n\n`getDefaultEnhancers` is useful if you want to add some custom enhancers, but also still want to have the default\nenhancers added as well:\n\n```ts no-transpile\nimport { configureStore } from '@reduxjs/toolkit'\nimport { offline } from '@redux-offline/redux-offline'\nimport offlineConfig from '@redux-offline/redux-offline/lib/defaults'\n\nimport rootReducer from './reducer'\n\nconst store = configureStore({\n  reducer: rootReducer,\n  enhancers: (getDefaultEnhancers) =>\n    getDefaultEnhancers().concat(offline(offlineConfig)),\n})\n\n// Store has all of the default middleware + enhancers added, _plus_ the offline enhancer\n```\n\n## Included Default Enhancers\n\nThe resulting array will always contain the `applyMiddleware` enhancer created based on the `configureStore`'s `middleware` field.\n\nAdditionally, the [`autoBatchEnhancer`](./autoBatchEnhancer.mdx) is included, to allow for \"batching\" of low priority action updates. This is used by [RTK Query](/rtk-query/overview.md) and should improve performance when using it.\n\nCurrently, the return value is\n\n```js\nconst enhancers = [applyMiddleware, autoBatchEnhancer]\n```\n\n## Customising the Included Enhancers\n\n`getDefaultEnhancers` accepts an options object that allows customizing each enhancer (excluding the middleware enhancer) in two ways:\n\n- Each enhancer can be excluded from the result array by passing `false` for its corresponding field\n- Each enhancer can have its options customized by passing the matching options object for its corresponding field\n\nThis example shows customising the autoBatch enhancer:\n\n```ts\n// file: reducer.ts noEmit\n\nexport default function rootReducer(state = {}, action: any) {\n  return state\n}\n\n// file: store.ts\nimport rootReducer from './reducer'\nimport { configureStore } from '@reduxjs/toolkit'\n\nconst store = configureStore({\n  reducer: rootReducer,\n  enhancers: (getDefaultEnhancers) =>\n    getDefaultEnhancers({\n      autoBatch: { type: 'tick' },\n    }),\n})\n```\n\n## API Reference\n\n```ts no-transpile\ninterface AutoBatchOptions {\n  // see \"autoBatchEnhancer\" page for options\n}\n\ninterface GetDefaultEnhancersOptions {\n  autoBatch?: boolean | AutoBatchOptions\n}\n\nfunction getDefaultEnhancers<M extends Middlewares<any>>(\n  options: GetDefaultEnhancersOptions = {},\n): EnhancerArray<[StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>]>\n```\n"
  },
  {
    "path": "docs/api/getDefaultMiddleware.mdx",
    "content": "---\nid: getDefaultMiddleware\ntitle: getDefaultMiddleware\nsidebar_label: getDefaultMiddleware\nhide_title: true\n---\n\n&nbsp;\n\n# `getDefaultMiddleware`\n\nReturns an array containing the default list of middleware.\n\n## Intended Usage\n\nBy default, [`configureStore`](./configureStore.mdx) adds some middleware to the Redux store setup automatically.\n\n```js\nconst store = configureStore({\n  reducer: rootReducer,\n})\n\n// Store has middleware added, because the middleware list was not customized\n```\n\nIf you want to customize the list of middleware, you can supply an array of middleware functions to `configureStore`:\n\n```js\nconst store = configureStore({\n  reducer: rootReducer,\n  middleware: () => new Tuple(thunk, logger),\n})\n\n// Store specifically has the thunk and logger middleware applied\n```\n\nHowever, when you supply the `middleware` option, you are responsible for defining _all_ the middleware you want added\nto the store. `configureStore` will not add any extra middleware beyond what you listed.\n\n`getDefaultMiddleware` is useful if you want to add some custom middleware, but also still want to have the default\nmiddleware added as well:\n\n```ts no-transpile\nimport { configureStore } from '@reduxjs/toolkit'\n\nimport logger from 'redux-logger'\n\nimport rootReducer from './reducer'\n\nconst store = configureStore({\n  reducer: rootReducer,\n  middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(logger),\n})\n\n// Store has all of the default middleware added, _plus_ the logger middleware\n```\n\nIt is preferable to use the chainable `.concat(...)` and `.prepend(...)` methods of the returned `Tuple` instead of the array spread operator, as the latter can lose valuable TS type information under some circumstances.\n\n## Included Default Middleware\n\n### Development\n\nOne of the goals of Redux Toolkit is to provide opinionated defaults and prevent common mistakes. As part of that,\n`getDefaultMiddleware` includes some middleware that are added **in development builds of your app only** to\nprovide runtime checks for three common issues:\n\n- [Immutability check middleware](./immutabilityMiddleware.mdx): deeply compares\n  state values for mutations. It can detect mutations in reducers during a dispatch, and also mutations that occur between\n  dispatches (such as in a component or a selector). When a mutation is detected, it will throw an error and indicate the key\n  path for where the mutated value was detected in the state tree. (Forked from [`redux-immutable-state-invariant`](https://github.com/leoasis/redux-immutable-state-invariant).)\n\n- [Serializability check middleware](./serializabilityMiddleware.mdx): a custom middleware created specifically for use in Redux Toolkit. Similar in\n  concept to `immutable-state-invariant`, but deeply checks your state tree and your actions for non-serializable values\n  such as functions, Promises, Symbols, and other non-plain-JS-data values. When a non-serializable value is detected, a\n  console error will be printed with the key path for where the non-serializable value was detected.\n\n- [Action creator check middleware](./actionCreatorMiddleware.mdx): another custom middleware created specifically for use in Redux Toolkit.\n  Identifies when an action creator was mistakenly dispatched without being called, and warns to console with the action type.\n\nIn addition to these development tool middleware, it also adds [`redux-thunk`](https://github.com/reduxjs/redux-thunk)\nby default, since thunks are the basic recommended side effects middleware for Redux.\n\nCurrently, the return value is:\n\n```js\nconst middleware = [\n  actionCreatorInvariant,\n  immutableStateInvariant,\n  thunk,\n  serializableStateInvariant,\n]\n```\n\n### Production\n\nCurrently, the return value is:\n\n```js\nconst middleware = [thunk]\n```\n\n## Customizing the Included Middleware\n\n`getDefaultMiddleware` accepts an options object that allows customizing each middleware in two ways:\n\n- Each middleware can be excluded from the result array by passing `false` for its corresponding field\n- Each middleware can have its options customized by passing the matching options object for its corresponding field\n\nThis example shows excluding the serializable state check middleware, and passing a specific value for the thunk\nmiddleware's \"extra argument\":\n\n```ts\n// file: reducer.ts noEmit\n\nexport default function rootReducer(state = {}, action: any) {\n  return state\n}\n\n// file: api.ts noEmit\n\nexport declare const myCustomApiService: any\n\n// file: store.ts\n\nimport { configureStore } from '@reduxjs/toolkit'\nimport rootReducer from './reducer'\nimport { myCustomApiService } from './api'\n\nconst store = configureStore({\n  reducer: rootReducer,\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware({\n      thunk: {\n        extraArgument: myCustomApiService,\n      },\n      serializableCheck: false,\n    }),\n})\n```\n\n## API Reference\n\n```ts no-transpile\ninterface ThunkOptions<E = any> {\n  extraArgument: E\n}\n\ninterface ImmutableStateInvariantMiddlewareOptions {\n  // See \"Immutability Middleware\" page for definition\n}\n\ninterface SerializableStateInvariantMiddlewareOptions {\n  // See \"Serializability Middleware\" page for definition\n}\n\ninterface ActionCreatorInvariantMiddlewareOptions {\n  // See \"Action Creator Middleware\" page for definition\n}\n\ninterface GetDefaultMiddlewareOptions {\n  thunk?: boolean | ThunkOptions\n  immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions\n  serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions\n  actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions\n}\n\nfunction getDefaultMiddleware<S = any>(\n  options: GetDefaultMiddlewareOptions = {},\n): Middleware<{}, S>[]\n```\n"
  },
  {
    "path": "docs/api/immutabilityMiddleware.mdx",
    "content": "---\nid: immutabilityMiddleware\ntitle: Immutability Middleware\nsidebar_label: Immutability Middleware\nhide_title: true\n---\n\n&nbsp;\n\n# Immutability Middleware\n\nA port of the [`redux-immutable-state-invariant`](https://github.com/leoasis/redux-immutable-state-invariant) middleware, customized for use with Redux Toolkit. Any detected mutations will be thrown as errors.\n\nThis middleware is added to the store by default by [`configureStore`](./configureStore.mdx) and [`getDefaultMiddleware`](./getDefaultMiddleware.mdx).\n\nYou can customize the behavior of this middleware by passing any of the supported options as the `immutableCheck` value for `getDefaultMiddleware`.\n\n## Options\n\n```ts no-transpile\ntype IsImmutableFunc = (value: any) => boolean\n\ninterface ImmutableStateInvariantMiddlewareOptions {\n  /**\n    Callback function to check if a value is considered to be immutable.\n    This function is applied recursively to every value contained in the state.\n    The default implementation will return true for primitive types \n    (like numbers, strings, booleans, null and undefined).\n   */\n  isImmutable?: IsImmutableFunc\n  /** \n    An array of dot-separated path strings or RegExps that match named nodes from \n    the root state to ignore when checking for immutability.\n    Defaults to undefined\n   */\n  ignoredPaths?: (string | RegExp)[]\n  /** Print a warning if checks take longer than N ms. Default: 32ms */\n  warnAfter?: number\n}\n```\n\n## Exports\n\n### `createImmutableStateInvariantMiddleware`\n\nCreates an instance of the immutability check middleware, with the given options.\n\nYou will most likely not need to call this yourself, as `getDefaultMiddleware` already does so.\n\nExample:\n\n```ts\n// file: exampleSlice.ts\n\nimport { createSlice } from '@reduxjs/toolkit'\n\nexport const exampleSlice = createSlice({\n  name: 'example',\n  initialState: {\n    user: 'will track changes',\n    ignoredPath: 'single level',\n    ignoredNested: {\n      one: 'one',\n      two: 'two',\n    },\n  },\n  reducers: {},\n})\n\nexport default exampleSlice.reducer\n\n// file: store.ts\n\nimport {\n  configureStore,\n  createImmutableStateInvariantMiddleware,\n  Tuple,\n} from '@reduxjs/toolkit'\n\nimport exampleSliceReducer from './exampleSlice'\n\nconst immutableInvariantMiddleware = createImmutableStateInvariantMiddleware({\n  ignoredPaths: ['ignoredPath', 'ignoredNested.one', 'ignoredNested.two'],\n})\n\nconst store = configureStore({\n  reducer: exampleSliceReducer,\n  // Note that this will replace all default middleware\n  middleware: () => new Tuple(immutableInvariantMiddleware),\n})\n```\n\ndoing the same without removing all other middlewares, using [getDetfaultMiddleware](./getDefaultMiddleware):\n\n```ts\n// file: exampleSlice.ts noEmit\n\nimport { createSlice } from '@reduxjs/toolkit'\n\nexport const exampleSlice = createSlice({\n  name: 'example',\n  initialState: {\n    user: 'will track changes',\n    ignoredPath: 'single level',\n    ignoredNested: {\n      one: 'one',\n      two: 'two',\n    },\n  },\n  reducers: {},\n})\n\nexport default exampleSlice.reducer\n\n// file: store.ts\nimport { configureStore } from '@reduxjs/toolkit'\n\nimport exampleSliceReducer from './exampleSlice'\n\nconst store = configureStore({\n  reducer: exampleSliceReducer,\n  // This replaces the original default middleware with the customized versions\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware({\n      immutableCheck: {\n        ignoredPaths: ['ignoredPath', 'ignoredNested.one', 'ignoredNested.two'],\n      },\n    }),\n})\n```\n\n### `isImmutableDefault`\n\nDefault implementation of the \"is this value immutable?\" check. Currently implemented as:\n\n```js\nreturn (\n  typeof value !== 'object' || value === null || typeof value === 'undefined'\n)\n```\n\nThis will return true for primitive types (like numbers, strings, booleans, null and undefined)\n"
  },
  {
    "path": "docs/api/matching-utilities.mdx",
    "content": "---\nid: matching-utilities\ntitle: Matching Utilities\nsidebar_label: Matching Utilities\nhide_title: true\n---\n\n&nbsp;\n\n# Matching Utilities\n\nRedux Toolkit exports several type-safe action matching utilities that you can leverage when checking for specific kinds of actions. These are primarily useful for the `builder.addMatcher()` cases in `createSlice` and `createReducer`, as well as when writing custom middleware.\n\n### General Purpose\n\n- [`isAllOf`](#isallof) - returns true when **all** conditions are met\n- [`isAnyOf`](#isanyof) - returns true when **at least one of** the conditions are met\n\n### `createAsyncThunk`-specific matchers\n\nAll these matchers can either be called with one or more thunks as arguments, in which case they will return a matcher function for that condition and thunks, or with one actions, in which case they will match for any thunk action with said condition.\n\n- [`isAsyncThunkAction`](#isasyncthunkaction) - accepts one or more action creators and returns true when all match\n- [`isPending`](#ispending) - accepts one or more action creators and returns true when all match\n- [`isFulfilled`](#isfulfilled) - accepts one or more action creators and returns true when all match\n- [`isRejected`](#isrejected) - accepts one or more action creators and returns true when all match\n- [`isRejectedWithValue`](#isrejectedwithvalue) - accepts one or more action creators and returns true when all match\n\n## `isAllOf`\n\nA higher-order function that accepts one or more of:\n\n- `redux-toolkit` action creator functions such as the ones produced by:\n  - [`createAction`](./createAction.mdx)\n  - [`createSlice`](./createSlice.mdx#return-value)\n  - [`createAsyncThunk`](./createAsyncThunk.mdx#promise-lifecycle-actions)\n- type guard functions\n- custom action creator functions that have a `.match` property that is a type guard\n\nIt will return a type guard function that returns `true` if _all_ of the provided functions match.\n\n## `isAnyOf`\n\nAccepts the same inputs as `isAllOf` and will return a type guard function that returns `true` if at least one of the provided functions match.\n\n## `isAsyncThunkAction`\n\nA higher-order function that returns a type guard function that may be used to check whether an action was created by [`createAsyncThunk`](./createAsyncThunk.mdx).\n\n```ts title=\"isAsyncThunkAction usage\"\nimport { isAsyncThunkAction } from '@reduxjs/toolkit'\nimport type { UnknownAction } from '@reduxjs/toolkit'\nimport { requestThunk1, requestThunk2 } from '@virtual/matchers'\n\nconst isARequestAction = isAsyncThunkAction(requestThunk1, requestThunk2)\n\nfunction handleRequestAction(action: UnknownAction) {\n  if (isARequestAction(action)) {\n    // action is an action dispatched by either `requestThunk1` or `requestThunk2`\n  }\n}\n```\n\n## `isPending`\n\nA higher-order function that returns a type guard function that may be used to check whether an action is a 'pending' action creator from the `createAsyncThunk` promise lifecycle.\n\n```ts title=\"isPending usage\"\nimport { isPending } from '@reduxjs/toolkit'\nimport type { UnknownAction } from '@reduxjs/toolkit'\nimport { requestThunk1, requestThunk2 } from '@virtual/matchers'\n\nconst isAPendingAction = isPending(requestThunk1, requestThunk2)\n\nfunction handlePendingAction(action: UnknownAction) {\n  if (isAPendingAction(action)) {\n    // action is a pending action dispatched by either `requestThunk1` or `requestThunk2`\n  }\n}\n```\n\n## `isFulfilled`\n\nA higher-order function that returns a type guard function that may be used to check whether an action is a 'fulfilled'' action creator from the `createAsyncThunk` promise lifecycle.\n\n```ts title=\"isFulfilled usage\"\nimport { isFulfilled } from '@reduxjs/toolkit'\nimport type { UnknownAction } from '@reduxjs/toolkit'\nimport { requestThunk1, requestThunk2 } from '@virtual/matchers'\n\nconst isAFulfilledAction = isFulfilled(requestThunk1, requestThunk2)\n\nfunction handleFulfilledAction(action: UnknownAction) {\n  if (isAFulfilledAction(action)) {\n    // action is a fulfilled action dispatched by either `requestThunk1` or `requestThunk2`\n  }\n}\n```\n\n## `isRejected`\n\nA higher-order function that returns a type guard function that may be used to check whether an action is a 'rejected' action creator from the `createAsyncThunk` promise lifecycle.\n\n```ts title=\"isRejected usage\"\nimport { isRejected } from '@reduxjs/toolkit'\nimport type { UnknownAction } from '@reduxjs/toolkit'\nimport { requestThunk1, requestThunk2 } from '@virtual/matchers'\n\nconst isARejectedAction = isRejected(requestThunk1, requestThunk2)\n\nfunction handleRejectedAction(action: UnknownAction) {\n  if (isARejectedAction(action)) {\n    // action is a rejected action dispatched by either `requestThunk1` or `requestThunk2`\n  }\n}\n```\n\n## `isRejectedWithValue`\n\nA higher-order function that returns a type guard function that may be used to check whether an action is a 'rejected' action creator from the `createAsyncThunk` promise lifecycle that was created by [`rejectWithValue`](./createAsyncThunk.mdx#handling-thunk-errors).\n\n```ts title=\"isRejectedWithValue usage\"\nimport { isRejectedWithValue } from '@reduxjs/toolkit'\nimport type { UnknownAction } from '@reduxjs/toolkit'\nimport { requestThunk1, requestThunk2 } from '@virtual/matchers'\n\nconst isARejectedWithValueAction = isRejectedWithValue(\n  requestThunk1,\n  requestThunk2,\n)\n\nfunction handleRejectedWithValueAction(action: UnknownAction) {\n  if (isARejectedWithValueAction(action)) {\n    // action is a rejected action dispatched by either `requestThunk1` or `requestThunk2`\n    // where rejectWithValue was used\n  }\n}\n```\n\n## Using matchers to reduce code complexity, duplication and boilerplate\n\nWhen using the `builder` pattern to construct a reducer, we add cases or matchers one at a time. However, by using `isAnyOf` or `isAllOf`,\nwe're able to easily use the same matcher for several cases in a type-safe manner.\n\nFirst, let's examine an unnecessarily complex example:\n\n```ts title=\"Example without using a matcher utility\"\nimport { createAsyncThunk, createReducer } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\n\ninterface Data {\n  isInteresting: boolean\n  isSpecial: boolean\n}\n\ninterface Special extends Data {\n  isSpecial: true\n}\n\ninterface Interesting extends Data {\n  isInteresting: true\n}\n\nfunction isSpecial(\n  action: PayloadAction<Data>,\n): action is PayloadAction<Special> {\n  return action.payload.isSpecial\n}\n\nfunction isInteresting(\n  action: PayloadAction<Data>,\n): action is PayloadAction<Interesting> {\n  return action.payload.isInteresting\n}\n\ninterface ExampleState {\n  isSpecial: boolean\n  isInteresting: boolean\n}\n\nconst initialState = {\n  isSpecial: false,\n  isInteresting: false,\n} satisfies ExampleState as ExampleState\n\nexport const isSpecialAndInterestingThunk = createAsyncThunk(\n  'isSpecialAndInterestingThunk',\n  () => {\n    return {\n      isSpecial: true,\n      isInteresting: true,\n    }\n  },\n)\n\n// This has unnecessary complexity\nconst loadingReducer = createReducer(initialState, (builder) => {\n  builder.addCase(isSpecialAndInterestingThunk.fulfilled, (state, action) => {\n    if (isSpecial(action)) {\n      state.isSpecial = true\n    }\n    if (isInteresting(action)) {\n      state.isInteresting = true\n    }\n  })\n})\n```\n\nIn this scenario, we can use `isAllOf` to simplify our code and reduce some of the boilerplate.\n\n```ts title=\"Refactoring with isAllOf\"\nimport { createReducer, isAllOf } from '@reduxjs/toolkit'\nimport {\n  isSpecialAndInterestingThunk,\n  initialState,\n  isSpecial,\n  isInteresting,\n} from '@virtual/matchers' // This is a fake pkg that provides the types shown above\nimport type { Data } from '@virtual/matchers' // This is a fake pkg that provides the types shown above\n\nconst loadingReducer = createReducer(initialState, (builder) => {\n  builder\n    .addMatcher(\n      isAllOf(isSpecialAndInterestingThunk.fulfilled, isSpecial),\n      (state, action) => {\n        state.isSpecial = true\n      },\n    )\n    .addMatcher(\n      isAllOf(isSpecialAndInterestingThunk.fulfilled, isInteresting),\n      (state, action) => {\n        state.isInteresting = true\n      },\n    )\n})\n```\n\n## Using matchers as a TypeScript Type Guard\n\nThe function returned by `isAllOf` and `isAnyOf` can also be used as a TypeScript type guard in other contexts.\n\n```ts title=\"Using isAllOf as a type guard\"\nimport { isAllOf } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\nimport { isSpecial, isInteresting } from '@virtual/matchers' // This is a fake pkg that provides the types shown above\nimport type { Data } from '@virtual/matchers' // This is a fake pkg that provides the types shown above\n\nconst isSpecialAndInteresting = isAllOf(isSpecial, isInteresting)\n\nfunction someFunction(action: PayloadAction<Data>) {\n  if (isSpecialAndInteresting(action)) {\n    // \"action\" will be correctly typed as:\n    // `PayloadAction<Special> & PayloadAction<Interesting>`\n  }\n}\n```\n\n```ts title=\"Using isAnyOf as a type guard\"\nimport { isAnyOf } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\nimport { Data, isSpecial, isInteresting } from '@virtual/matchers' // this is a fake pkg that provides the types shown above\n\nconst isSpecialOrInteresting = isAnyOf(isSpecial, isInteresting)\n\nfunction someFunction(action: PayloadAction<Data>) {\n  if (isSpecialOrInteresting(action)) {\n    // \"action\" will be correctly typed as:\n    // `PayloadAction<Special> | PayloadAction<Interesting>`\n  }\n}\n```\n\n## Example\n\n<iframe\n  src=\"https://codesandbox.io/embed/redux-toolkit-matchers-example-e765q?fontsize=14&hidenavigation=1&module=%2Fsrc%2Ffeatures%2Fcounter%2FcounterSlice.ts&theme=dark&runonclick=1\"\n  style={{\n    width: '100%',\n    height: '500px',\n    border: 0,\n    borderRadius: 4,\n    overflow: 'hidden',\n  }}\n  title=\"redux-toolkit-matchers-example\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>\n"
  },
  {
    "path": "docs/api/otherExports.mdx",
    "content": "---\nid: other-exports\ntitle: Other Exports\nsidebar_label: Other Exports\nhide_title: true\n---\n\n&nbsp;\n\n# Other Exports\n\nRedux Toolkit exports some of its internal utilities, and re-exports additional functions from other dependencies as well.\n\n### `nanoid`\n\nAn inlined copy of [`nanoid/nonsecure`](https://github.com/ai/nanoid). Generates a non-cryptographically-secure random ID string. `createAsyncThunk` uses this by default for request IDs. May also be useful for other cases as well.\n\n```ts\nimport { nanoid } from '@reduxjs/toolkit'\n\nconsole.log(nanoid())\n// 'dgPXxUz_6fWIQBD8XmiSy'\n```\n\n### `miniSerializeError`\n\nThe default error serialization function used by `createAsyncThunk`, based on https://github.com/sindresorhus/serialize-error. If its argument is an object (such as an `Error` instance), it returns a plain JS `SerializedError` object that copies over any of the listed fields. Otherwise, it returns a stringified form of the value: `{ message: String(value) }`.\n\n```ts no-transpile\nexport interface SerializedError {\n  name?: string\n  message?: string\n  stack?: string\n  code?: string\n}\n\nexport function miniSerializeError(value: any): SerializedError {}\n```\n\n### `copyWithStructuralSharing`\n\nA utility that will recursively merge two similar objects together, preserving existing references if the values appear to be the same. This is used internally to help ensure that re-fetched data keeps using the same references unless the new data has actually changed, to avoid unnecessary re-renders. Otherwise, every re-fetch would likely cause the entire dataset to be replaced and all consuming components to always re-render.\n\nIf either of the inputs are not plain JS objects or arrays, the new value is returned.\n\n```ts no-transpile\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T\nexport function copyWithStructuralSharing(oldObj: any, newObj: any): any {}\n```\n\n## Exports from Other Libraries\n\n### `createNextState`\n\nThe default immutable update function from the [`immer` library](https://immerjs.github.io/immer/), re-exported here as `createNextState` (also commonly referred to as [`produce`](https://immerjs.github.io/immer/produce))\n\n### `current`\n\n[The `current` function](https://immerjs.github.io/immer/current) from the [`immer` library](https://immerjs.github.io/immer/), which takes a snapshot of the current state of a draft and finalizes it (but without freezing). Current is a great utility to print the current state during debugging, and the output of `current` can also be safely leaked outside the producer.\n\n```ts\nimport { createReducer, createAction, current } from '@reduxjs/toolkit'\n\ninterface Todo {\n  //...\n}\nconst addTodo = createAction<Todo>('addTodo')\n\nconst initialState = [] satisfies Todo[] as Todo[]\n\nconst todosReducer = createReducer(initialState, (builder) => {\n  builder.addCase(addTodo, (state, action) => {\n    state.push(action.payload)\n    console.log(current(state))\n  })\n})\n```\n\n### `original`\n\n[The `original` function](https://immerjs.github.io/immer/original) from the [`immer` library](https://immerjs.github.io/immer/), which returns the original object. This is particularly useful for referential equality check in reducers.\n\n### `isDraft`\n\n[The `isDraft` function](https://immerjs.github.io/immer/original) from the [`immer` library](https://immerjs.github.io/immer/), which checks to see if a given value is a Proxy-wrapped \"draft\" state.\n\n### `freeze`\n\n[The `freeze` function](https://immerjs.github.io/immer/api) from the [`immer` library](https://immerjs.github.io/immer/), which [freezes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) draftable objects.\n\n### `combineReducers`\n\nRedux's [`combineReducers`](https://redux.js.org/api/combinereducers), re-exported for convenience. While `configureStore` calls this internally, you may wish to call it yourself to compose multiple levels of slice reducers.\n\n### `compose`\n\nRedux's [`compose`](https://redux.js.org/api/compose). It composes functions from right to left.\nThis is a functional programming utility. You might want to use it to apply several store custom enhancers/ functions in a row.\n\n### `bindActionCreators`\n\nRedux's [`bindActionCreators`](https://redux.js.org/api/bindactioncreators). It wraps action creators with `dispatch()` so that they dispatch immediately when called.\n\n### `createStore`\n\nRedux's [`createStore`](https://redux.js.org/api/createstore). You should not need to use this directly.\n\n### `applyMiddleware`\n\nRedux's [`applyMiddleware`](https://redux.js.org/api/applymiddleware). You should not need to use this directly.\n"
  },
  {
    "path": "docs/api/serializabilityMiddleware.mdx",
    "content": "---\nid: serializabilityMiddleware\ntitle: Serializability Middleware\nsidebar_label: Serializability Middleware\nhide_title: true\n---\n\n&nbsp;\n\n# Serializability Middleware\n\nA custom middleware that detects if any non-serializable values have been included in state or dispatched actions, modeled after `redux-immutable-state-invariant`. Any detected non-serializable values will be logged to the console.\n\nThis middleware is added to the store by default by [`configureStore`](./configureStore.mdx) and [`getDefaultMiddleware`](./getDefaultMiddleware.mdx).\n\nYou can customize the behavior of this middleware by passing any of the supported options as the `serializableCheck` value for `getDefaultMiddleware`.\n\n## Options\n\n```ts no-transpile\ninterface SerializableStateInvariantMiddlewareOptions {\n  /**\n   * The function to check if a value is considered serializable. This\n   * function is applied recursively to every value contained in the\n   * state. Defaults to `isPlain()`.\n   */\n  isSerializable?: (value: any) => boolean\n  /**\n   * The function that will be used to retrieve entries from each\n   * value.  If unspecified, `Object.entries` will be used. Defaults\n   * to `undefined`.\n   */\n  getEntries?: (value: any) => [string, any][]\n\n  /**\n   * An array of action types to ignore when checking for serializability.\n   * Defaults to []\n   */\n  ignoredActions?: string[]\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to\n   * ['meta.arg', 'meta.baseQueryMeta']\n   */\n  ignoredActionPaths?: (string | RegExp)[]\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to []\n   */\n  ignoredPaths?: (string | RegExp)[]\n  /**\n   * Execution time warning threshold. If the middleware takes longer\n   * than `warnAfter` ms, a warning will be displayed in the console.\n   * Defaults to 32ms.\n   */\n  warnAfter?: number\n\n  /**\n   * Opt out of checking state. When set to `true`, other state-related params will be ignored.\n   */\n  ignoreState?: boolean\n\n  /**\n   * Opt out of checking actions. When set to `true`, other action-related params will be ignored.\n   */\n  ignoreActions?: boolean\n}\n```\n\n## Exports\n\n### `createSerializableStateInvariantMiddleware`\n\nCreates an instance of the serializability check middleware, with the given options.\n\nYou will most likely not need to call this yourself, as `getDefaultMiddleware` already does so.\n\nExample:\n\n```ts\n// file: reducer.ts noEmit\n\nexport default function (state = {}, action: any) {\n  return state\n}\n\n// file: store.ts\n\nimport { Iterable } from 'immutable'\nimport {\n  configureStore,\n  createSerializableStateInvariantMiddleware,\n  isPlain,\n  Tuple,\n} from '@reduxjs/toolkit'\nimport reducer from './reducer'\n\n// Augment middleware to consider Immutable.JS iterables serializable\nconst isSerializable = (value: any) =>\n  Iterable.isIterable(value) || isPlain(value)\n\nconst getEntries = (value: any) =>\n  Iterable.isIterable(value) ? value.entries() : Object.entries(value)\n\nconst serializableMiddleware = createSerializableStateInvariantMiddleware({\n  isSerializable,\n  getEntries,\n})\n\nconst store = configureStore({\n  reducer,\n  middleware: () => new Tuple(serializableMiddleware),\n})\n```\n\n### `isPlain`\n\nChecks whether the given value is considered a \"plain value\" or not.\n\nCurrently implemented as:\n\n```ts\n// file: src/isPlainObject.ts noEmit\n\ndeclare function isPlainObject(value: unknown): value is object\nexport default isPlainObject\n\n// file: src/serializableStateInvariantMiddleware.ts\nimport isPlainObject from './isPlainObject'\n\nexport function isPlain(val: any) {\n  return (\n    typeof val === 'undefined' ||\n    val === null ||\n    typeof val === 'string' ||\n    typeof val === 'boolean' ||\n    typeof val === 'number' ||\n    Array.isArray(val) ||\n    isPlainObject(val)\n  )\n}\n```\n\nThis will accept all standard JS objects, arrays, and primitives, but return false for `Date`s, `Map`s, and other similar class instances.\n"
  },
  {
    "path": "docs/components/DetailedExplanation.jsx",
    "content": "import React from 'react'\n\nexport const DetailedExplanation = ({\n  children,\n  title = 'Detailed Explanation',\n}) => {\n  return (\n    <details className=\"detailed-explanation\">\n      <summary>\n        <h4>{title}</h4>\n      </summary>\n      {children}\n    </details>\n  )\n}\n"
  },
  {
    "path": "docs/introduction/getting-started.md",
    "content": "---\nid: getting-started\ntitle: Getting Started\nsidebar_label: Getting Started\nhide_title: true\n---\n\nimport LiteYouTubeEmbed from 'react-lite-youtube-embed';\nimport 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css'\nimport Tabs from '@theme/Tabs';\nimport TabItem from '@theme/TabItem';\n\n&nbsp;\n\n# Getting Started with Redux Toolkit\n\n## Purpose\n\nThe **Redux Toolkit** package is intended to be the standard way to write [Redux](https://redux.js.org) logic. It was originally created to help address three common concerns about Redux:\n\n- \"Configuring a Redux store is too complicated\"\n- \"I have to add a lot of packages to get Redux to do anything useful\"\n- \"Redux requires too much boilerplate code\"\n\nWe can't solve every use case, but in the spirit of [`create-react-app`](https://github.com/facebook/create-react-app), we can try to provide some tools that abstract over the setup process and handle the most common use cases, as well as include some useful utilities that will let the user simplify their application code.\n\nRedux Toolkit also includes a powerful data fetching and caching capability that we've dubbed [\"RTK Query\"](#rtk-query). It's included in the package as a separate set of entry points. It's optional, but can eliminate the need to hand-write data fetching logic yourself.\n\n**These tools should be beneficial to all Redux users**. Whether you're a brand new Redux user setting up your\nfirst project, or an experienced user who wants to simplify an existing application, **Redux Toolkit** can help\nyou make your Redux code better.\n\n## Installation\n\n### Create a React Redux App\n\nThe recommended way to start new apps with React and Redux Toolkit is by using [our official Redux Toolkit + TS template for Vite](https://github.com/reduxjs/redux-templates), or by creating a new Next.js project using [Next's `with-redux` template](https://github.com/vercel/next.js/tree/canary/examples/with-redux).\n\nBoth of these already have Redux Toolkit and React-Redux configured appropriately for that build tool, and come with a small example app that demonstrates how to use several of Redux Toolkit's features.\n\n```bash\n# Vite with our Redux+TS template\n# (using the `degit` tool to clone and extract the template)\nnpx degit reduxjs/redux-templates/packages/vite-template-redux my-app\n\n# Next.js using the `with-redux` template\nnpx create-next-app --example with-redux my-app\n```\n\nWe do not currently have official React Native templates, but recommend these templates for standard React Native and for Expo:\n\n- https://github.com/rahsheen/react-native-template-redux-typescript\n- https://github.com/rahsheen/expo-template-redux-typescript\n\n### An Existing App\n\nRedux Toolkit is available as a package on NPM for use with a module bundler or in a Node application:\n\n<Tabs>\n  <TabItem value=\"npm\" label=\"npm\" default>\n\n```bash\nnpm install @reduxjs/toolkit\n```\n\nIf you need React bindings:\n\n```bash\nnpm install react-redux\n```\n\n  </TabItem>\n  <TabItem value=\"yarn\" label=\"yarn\" default>\n\n```bash\nyarn add @reduxjs/toolkit\n```\n\nIf you need React bindings:\n\n```bash\nyarn add react-redux\n```\n\n  </TabItem>\n</Tabs>\n\nThe package includes a precompiled ESM build that can be used as a [`<script type=\"module\">` tag](https://unpkg.com/@reduxjs/toolkit/dist/redux-toolkit.browser.mjs) directly in the browser.\n\n## Requirements\n\n### TypeScript\n\nRedux Toolkit follows [DefinitelyTyped's policy](https://github.com/DefinitelyTyped/DefinitelyTyped#support-window) of supporting TypeScript versions released within the past two years. As of RTK 2.11, this means we support:\n\n| RTK Version | Minimum TypeScript |\n| ----------- | ------------------ |\n| 2.x         | 5.4+               |\n| 1.9.x       | 4.7+               |\n\n<details>\n<summary>Using an older TypeScript version?</summary>\n\nIf you're unable to upgrade TypeScript, RTK may still work with older versions, but you may encounter type errors or missing type inference. We strongly recommend upgrading to take advantage of improved type safety and developer experience.\n\n</details>\n\n## What's Included\n\nRedux Toolkit includes these APIs:\n\n- [`configureStore()`](../api/configureStore.mdx): wraps `createStore` to provide simplified configuration options and good defaults. It can automatically combine your slice reducers, adds whatever Redux middleware you supply, includes `redux-thunk` by default, and enables use of the Redux DevTools Extension.\n- [`createReducer()`](../api/createReducer.mdx): that lets you supply a lookup table of action types to case reducer functions, rather than writing switch statements. In addition, it automatically uses the [`immer` library](https://github.com/immerjs/immer) to let you write simpler immutable updates with normal mutative code, like `state.todos[3].completed = true`.\n- [`createAction()`](../api/createAction.mdx): generates an action creator function for the given action type string.\n- [`createSlice()`](../api/createSlice.mdx): accepts an object of reducer functions, a slice name, and an initial state value, and automatically generates a slice reducer with corresponding action creators and action types.\n- [`combineSlices()`](../api/combineSlices.mdx): combines multiple slices into a single reducer, and allows \"lazy loading\" of slices after initialisation.\n- [`createAsyncThunk`](../api/createAsyncThunk.mdx): accepts an action type string and a function that returns a promise, and generates a thunk that dispatches `pending/fulfilled/rejected` action types based on that promise\n- [`createEntityAdapter`](../api/createEntityAdapter.mdx): generates a set of reusable reducers and selectors to manage normalized data in the store\n- The [`createSelector` utility](../api/createSelector.mdx) from the [Reselect](https://github.com/reduxjs/reselect) library, re-exported for ease of use.\n\n## RTK Query\n\n[**RTK Query**](../rtk-query/overview.md) is provided as an optional addon within the `@reduxjs/toolkit` package. It is purpose-built to solve the use case of data fetching and caching, supplying a compact, but powerful toolset to define an API interface layer for your app. It is intended to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.\n\nRTK Query is built on top of the Redux Toolkit core for its implementation, using [Redux](https://redux.js.org/) internally for its architecture. Although knowledge of Redux and RTK are not required to use RTK Query, you should explore all of the additional global store management capabilities they provide, as well as installing the [Redux DevTools browser extension](https://github.com/reduxjs/redux-devtools), which works flawlessly with RTK Query to traverse and replay a timeline of your request & cache behavior.\n\nRTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:\n\n```ts no-transpile\nimport { createApi } from '@reduxjs/toolkit/query'\n\n/* React-specific entry point that automatically generates\n   hooks corresponding to the defined endpoints */\nimport { createApi } from '@reduxjs/toolkit/query/react'\n```\n\n### What's included\n\nRTK Query includes these APIs:\n\n- [`createApi()`](../rtk-query/api/createApi.mdx): The core of RTK Query's functionality. It allows you to define a set of endpoints and describe how to retrieve data from a series of endpoints, including configuration of how to fetch and transform that data. In most cases, you should use this once per app, with \"one API slice per base URL\" as a rule of thumb.\n- [`fetchBaseQuery()`](../rtk-query/api/fetchBaseQuery.mdx): A small wrapper around [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) that aims to simplify requests. Intended as the recommended `baseQuery` to be used in `createApi` for the majority of users.\n- [`<ApiProvider />`](../rtk-query/api/ApiProvider.mdx): Can be used as a `Provider` if you **do not already have a Redux store**.\n- [`setupListeners()`](../rtk-query/api/setupListeners.mdx): A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\n\nSee the [**RTK Query Overview**](../rtk-query/overview.md) page for more details on what RTK Query is, what problems it solves, and how to use it.\n\n## Learn Redux\n\nWe have a variety of resources available to help you learn Redux.\n\n### Redux Essentials Tutorial\n\nThe [**Redux Essentials tutorial**](https://redux.js.org/tutorials/essentials/part-1-overview-concepts) is a \"top-down\" tutorial that teaches \"how to use Redux the right way\", using our latest recommended APIs and best practices. We recommend starting there.\n\n### Redux Fundamentals Tutorial\n\nThe [**Redux Fundamentals tutorial**](https://redux.js.org/tutorials/fundamentals/part-1-overview) is a \"bottom-up\" tutorial that teaches \"how Redux works\" from first principles and without any abstractions, and why standard Redux usage patterns exist.\n\n### Learn Modern Redux Livestream\n\nRedux maintainer Mark Erikson appeared on the \"Learn with Jason\" show to explain how we recommend using Redux today. The show includes a live-coded example app that shows how to use Redux Toolkit and React-Redux hooks with TypeScript, as well as the new RTK Query data fetching APIs.\n\nSee [the \"Learn Modern Redux\" show notes page](https://www.learnwithjason.dev/let-s-learn-modern-redux) for a transcript and links to the example app source.\n\n<LiteYouTubeEmbed \n    id=\"9zySeP5vH9c\"\n    title=\"Learn Modern Redux - Redux Toolkit, React-Redux Hooks, and RTK Query\"\n/>\n\n## Help and Discussion\n\nThe **[#redux channel](https://discord.gg/0ZcbPKXt5bZ6au5t)** of the **[Reactiflux Discord community](https://www.reactiflux.com)** is our official resource for all questions related to learning and using Redux. Reactiflux is a great place to hang out, ask questions, and learn - come join us!\n\nYou can also ask questions on [Stack Overflow](https://stackoverflow.com) using the **[#redux tag](https://stackoverflow.com/questions/tagged/redux)**.\n"
  },
  {
    "path": "docs/introduction/why-rtk-is-redux-today.md",
    "content": "---\nid: why-rtk-is-redux-today\ntitle: Why Redux Toolkit is How To Use Redux Today\n# Yes, we are serious with the title. It's okay as it is. Please don't open more Pull Requests to change it.\ndescription: 'Introduction > Why RTK is Redux Today: details on how RTK replaces the Redux core'\n---\n\n## What is Redux Toolkit?\n\n[**Redux Toolkit**](https://redux-toolkit.js.org) (also known as **\"RTK\"** for short) is our official recommended approach for writing Redux logic. The `@reduxjs/toolkit` package wraps around the core `redux` package, and contains API methods and common dependencies that we think are essential for building a Redux app. Redux Toolkit builds in our suggested best practices, simplifies most Redux tasks, prevents common mistakes, and makes it easier to write Redux applications.\n\n**If you are writing _any_ Redux logic today, you _should_ be using Redux Toolkit to write that code!**\n\nRTK includes utilities that help simplify many common use cases, including [store setup](https://redux-toolkit.js.org/api/configureStore),\n[creating reducers and writing immutable update logic](https://redux-toolkit.js.org/api/createreducer),\nand even [creating entire \"slices\" of state at once](https://redux-toolkit.js.org/api/createslice).\n\nWhether you're a brand new Redux user setting up your first project, or an experienced user who wants to\nsimplify an existing application, **[Redux Toolkit](https://redux-toolkit.js.org/)** can help you\nmake your Redux code better.\n\n:::tip\n\nSee these pages to learn how to use \"modern Redux\" with Redux Toolkit:\n\n- [**The \"Redux Essentials\" tutorial**](https://redux.js.org/tutorials/essentials/part-1-overview-concepts), which teaches \"how to use Redux, the right way\" with Redux Toolkit for real-world apps,\n- [**Redux Fundamentals, Part 8: Modern Redux with Redux Toolkit**](https://redux.js.org/tutorials/fundamentals/part-8-modern-redux), which shows how to convert the low-level examples from earlier sections of the tutorial into modern Redux Toolkit equivalents\n- [**Using Redux: Migrating to Modern Redux**](../usage/migrating-to-modern-redux.mdx), which covers how to migrate different kinds of legacy Redux logic into modern Redux equivalents\n\n:::\n\n## How Redux Toolkit Is Different From the Redux Core\n\n### What Is \"Redux\"?\n\nThe first thing to ask is, \"what is Redux?\"\n\nRedux is really:\n\n- A single store containing \"global\" state\n- Dispatching plain object actions to the store when something happens in the app\n- Pure reducer functions looking at those actions and returning immutably updated state\n\nWhile it's not required, [your Redux code also normally includes](https://redux.js.org/tutorials/fundamentals/part-7-standard-patterns):\n\n- Action creators that generate those action objects\n- Middleware to enable side effects\n- Thunk functions that contain sync or async logic with side effects\n- Normalized state to enable looking up items by ID\n- Memoized selector functions with the Reselect library for optimizing derived data\n- The Redux DevTools Extension to view your action history and state changes\n- TypeScript types for actions, state, and other functions\n\nAdditionally, Redux is normally used with the React-Redux library to let your React components talk to a Redux store.\n\n### What Does the Redux Core Do?\n\nThe Redux core is a very small and deliberately unopinionated library. It provides a few small API primitives:\n\n- `createStore` to actually create a Redux store\n- `combineReducers` to combine multiple slice reducers into a single larger reducer\n- `applyMiddleware` to combine multiple middleware into a store enhancer\n- `compose` to combine multiple store enhancers into a single store enhancer\n\nOther than that, all the other Redux-related logic in your app has to be written entirely by you.\n\nThe good news is that this means Redux _can_ be used in many different ways. The bad news is that there are no helpers to make any of your code easier to write.\n\nFor example, a reducer function is _just_ a function. Prior to Redux Toolkit, you'd typically write that reducer with a `switch` statement and manual updates. You'd also probably have hand-written action creators and action type constants along with it:\n\n```js title=\"Legacy hand-written Redux usage\"\nconst ADD_TODO = 'ADD_TODO'\nconst TODO_TOGGLED = 'TODO_TOGGLED'\n\nexport const addTodo = (text) => ({\n  type: ADD_TODO,\n  payload: { text, id: nanoid() },\n})\n\nexport const todoToggled = (id) => ({\n  type: TODO_TOGGLED,\n  payload: { id },\n})\n\nexport const todosReducer = (state = [], action) => {\n  switch (action.type) {\n    case ADD_TODO:\n      return state.concat({\n        id: action.payload.id,\n        text: action.payload.text,\n        completed: false,\n      })\n    case TODO_TOGGLED:\n      return state.map((todo) => {\n        if (todo.id !== action.payload.id) return todo\n\n        return {\n          ...todo,\n          completed: !todo.completed,\n        }\n      })\n    default:\n      return state\n  }\n}\n```\n\nNone of this code specifically depends on any API from the `redux` core library. But, this is a lot of code to write. Immutable updates required a lot of hand-written object spreads and array operations, and it was very easy to make mistakes and accidentally mutate state in the process (always the #1 cause of Redux bugs!). It was also common, though not strictly required, to spread the code for one feature across multiple files like `actions/todos.js`, `constants/todos.js`, and `reducers/todos.js`.\n\nAdditionally, store setup usually required a series of steps to add commonly used middleware like thunks and enable Redux DevTools Extension support, even though these are standard tools used in almost every Redux app.\n\n### What Does Redux Toolkit Do?\n\nWhile these _were_ the patterns originally shown in the Redux docs, they unfortunately require a lot of very verbose and repetitive code. Most of this boilerplate isn't _necessary_ to use Redux. On top of that, the boilerplate-y code lead to more opportunities to make mistakes.\n\n**We specifically created Redux Toolkit to eliminate the \"boilerplate\" from hand-written Redux logic, prevent common mistakes, and provide APIs that simplify standard Redux tasks**.\n\nRedux Toolkit starts with two key APIs that simplify the most common things you do in every Redux app:\n\n- `configureStore` sets up a well-configured Redux store with a single function call, including combining reducers, adding the thunk middleware, and setting up the Redux DevTools integration. It also is easier to configure than `createStore`, because it takes named options parameters.\n- `createSlice` lets you write reducers that use [the Immer library](https://immerjs.github.io/immer/) to enable writing immutable updates using \"mutating\" JS syntax like `state.value = 123`, with no spreads needed. It also automatically generates action creator functions for each reducer, and generates action type strings internally based on your reducer's names. Finally, it works great with TypeScript.\n\nThat means that the code _you_ write can be drastically simpler. For example, that same todos reducer could just be:\n\n```js title=\"features/todos/todosSlice.js\"\nimport { createSlice } from '@reduxjs/toolkit'\n\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [],\n  reducers: {\n    todoAdded(state, action) {\n      state.push({\n        id: action.payload.id,\n        text: action.payload.text,\n        completed: false,\n      })\n    },\n    todoToggled(state, action) {\n      const todo = state.find((todo) => todo.id === action.payload)\n      todo.completed = !todo.completed\n    },\n  },\n})\n\nexport const { todoAdded, todoToggled } = todosSlice.actions\nexport default todosSlice.reducer\n```\n\nAll of the action creators and action types are generated automatically, and the reducer code is shorter and easier to understand. It's also much more clear what's actually being updated in each case.\n\nWith `configureStore`, the store setup can be simplified down to:\n\n```js title=\"app/store.js\"\nimport { configureStore } from '@reduxjs/toolkit'\nimport todosReducer from '../features/todos/todosSlice'\nimport filtersReducer from '../features/filters/filtersSlice'\n\nexport const store = configureStore({\n  reducer: {\n    todos: todosReducer,\n    filters: filtersReducer,\n  },\n})\n```\n\nNote that **this one `configureStore` call automatically does all the usual setup work you'd have done manually**:\n\n- The slice reducers were automatically passed to `combineReducers()`\n- The `redux-thunk` middleware was automatically added\n- Dev-mode middleware was added to catch accidental mutations\n- The Redux DevTools Extension was automatically set up\n- The middleware and DevTools enhancers were composed together and added to the store\n\nAt the same time, **`configureStore` provides the options to let users modify any of those default behaviors** (like turning off thunks and adding sagas, or disabling the DevTools in production),\n\nFrom there, Redux Toolkit includes other APIs for common Redux tasks:\n\n- `createAsyncThunk`: abstracts the standard \"dispatch actions before/after an async request\" pattern\n- `createEntityAdapter`: prebuilt reducers and selectors for CRUD operations on normalized state\n- `createSelector`: a re-export of the standard Reselect API for memoized selectors\n- `createListenerMiddleware`: a side effects middleware for running logic in response to dispatched actions\n\nFinally, the RTK package also includes \"RTK Query\", a full data fetching and caching solution for Redux apps, as a separate optional `@reduxjs/toolkit/query` entry point. It lets you define endpoints (REST, GraphQL, or any async function), and generates a reducer and middleware that fully manage fetching data, updating loading state, and caching results. It also automatically generates React hooks that can be used in components to fetch data, like `const { data, isFetching} = useGetPokemonQuery('pikachu')`\n\nEach of these APIs is completely optional and designed for specific use cases, and **you can pick and choose which APIs you actually use in your app**. But, all of them are highly recommended to help with those tasks.\n\nNote that **Redux Toolkit is still \"Redux\"!** There's still a single store, with dispatched action objects for updates, and reducers that immutably update state, plus the ability to write thunks for async logic, manage normalized state, type your code with TypeScript, and use the DevTools. **There's just way less code _you_ have to write for the same results!**\n\n## Why We Want You To Use Redux Toolkit\n\nAs Redux maintainers, our opinion is:\n\n:::tip\n\n**We want _all_ Redux users to write their Redux code with Redux Toolkit, because it simplifies your code _and_ eliminates many common Redux mistakes and bugs!**\n\n:::\n\nThe \"boilerplate\" and complexity of the early Redux patterns was never a _necessary_ part of Redux. Those patterns only existed because:\n\n- The original \"Flux Architecture\" used some of those same approaches\n- The early Redux docs showed things like action type constants to enable separating code into different files by type\n- JavaScript is a mutable language by default, and writing immutable updates required manual object spreads and array updates\n- Redux was originally built in just a few weeks and intentionally designed to be just a few API primitives\n\nAdditionally, the Redux community has adopted some specific approaches that add additional boilerplate:\n\n- Emphasizing use of the `redux-saga` middleware as a common approach for writing side effects\n- Insisting on hand-writing TS types for Redux action objects and creating union types to limit what actions can be dispatched at the type level\n\nOver the years, we've seen how people actually used Redux in practice. We've seen how the community wrote hundreds of add-on libraries for tasks like generating action types and creators, async logic and side effects, and data fetching. We've also seen the problems that have consistently caused pain for our users, like accidentally mutating state, writing dozens of lines of code just to make one simple state update, and having trouble tracing how a codebase fits together. We've helped thousands of users who were trying to learn and use Redux and struggling to understand how all the pieces fit together, and were confused by the number of concepts and amount of extra code they had to write. We _know_ what problems our users are facing.\n\n**We specifically designed Redux Toolkit to solve those problems!**\n\n- Redux Toolkit simplifies store setup down to a single clear function call, while retaining the ability to fully configure the store's options if you need to\n- Redux Toolkit eliminates accidental mutations, which have always been the #1 cause of Redux bugs\n- Redux Toolkit eliminates the need to write any action creators or action types by hand\n- Redux Toolkit eliminates the need to write manual and error-prone immutable update logic\n- Redux Toolkit makes it easy to write a Redux feature's code in one file, instead of spreading it across multiple separate files\n- Redux Toolkit offers excellent TS support, with APIs that are designed to give you excellent type safety and minimize the number of types you have to define in your code\n- RTK Query can eliminate the need to write _any_ thunks, reducers, action creators, or effect hooks to manage fetching data and tracking loading state\n\nBecause of this:\n\n:::tip\n\n**We specifically recommend that our users _should_ use Redux Toolkit (the `@reduxjs/toolkit` package), and should _not_ use the legacy `redux` core package for any new Redux code today!**\n\n:::\n\nEven for existing applications, we recommend at least switching out `createStore` for `configureStore` as the dev-mode middleware will also help you catch accidental mutation and serializability errors in existing code bases. We also want to encourage you to switch the reducers you are using most (and any ones you write in the future) over to `createSlice` - the code will be shorter and easier to understand, and the safety improvements will save you time and effort going forward.\n\n**The `redux` core package still works, but today we consider it to be obsolete**. All of its APIs are also re-exported from `@reduxjs/toolkit`, and `configureStore` does everything `createStore` does but with better default behavior and configurability.\n\nIt _is_ useful to understand the lower-level concepts, so that you have a better understanding of what Redux Toolkit is doing for you. That's why [the \"Redux Fundamentals\" tutorial shows how Redux works, with no abstractions](https://redux.js.org/tutorials/fundamentals/part-1-overview). _But_, it shows those examples solely as a learning tool, and finishes by showing you how Redux Toolkit simplifies the older hand-written Redux code.\n\nIf you are using the `redux` core package by itself, your code will continue to work. **But, we strongly encourage you to switch over to `@reduxjs/toolkit`, and update your code to use the Redux Toolkit APIs instead!**\n\n## Further Information\n\nSee these docs pages and blog posts for more details\n\n- [Redux Essentials: Redux Toolkit App Structure](https://redux.js.org/tutorials/essentials/part-2-app-structure)\n- [Redux Fundamentals: Modern Redux with Redux Toolkit](https://redux.js.org/tutorials/fundamentals/part-8-modern-redux)\n- [Redux Style Guide: Best Practices and Recommendations](https://redux.js.org/style-guide/)\n- [Presentation: Modern Redux with Redux Toolkit](https://blog.isquaredsoftware.com/2022/06/presentations-modern-redux-rtk/)\n- [Mark Erikson: Redux Toolkit 1.0 Announcement and development history](https://blog.isquaredsoftware.com/2019/10/redux-toolkit-1.0/)\n"
  },
  {
    "path": "docs/package.json",
    "content": "{\n  \"name\": \"docs\",\n  \"devDependencies\": {\n    \"@manaflair/redux-batch\": \"^1.0.0\",\n    \"@types/nanoid\": \"^2.1.0\",\n    \"@types/react\": \"^19.0.1\",\n    \"async-mutex\": \"^0.3.2\",\n    \"axios\": \"^0.20.0\",\n    \"formik\": \"^2.1.5\",\n    \"graphql-request\": \"^3.4.0\",\n    \"immutable\": \"^3.8.2\",\n    \"nanoid\": \"^3.1.23\",\n    \"next-redux-wrapper\": \"^7.0.5\",\n    \"redux-persist\": \"^6.0.0\",\n    \"rxjs\": \"^6.6.2\"\n  }\n}\n"
  },
  {
    "path": "docs/rtk-query/api/ApiProvider.mdx",
    "content": "---\nid: ApiProvider\ntitle: ApiProvider\nsidebar_label: ApiProvider\nhide_title: true\ndescription: 'RTK Query > API: ApiProvider reference'\n---\n\n&nbsp;\n\n# `ApiProvider`\n\n[summary](docblock://query/react/ApiProvider.tsx?token=ApiProvider)\n\n[examples](docblock://query/react/ApiProvider.tsx?token=ApiProvider)\n\n:::danger\nUsing this together with an existing Redux store will cause them to conflict with each other. If you are already using Redux, please follow the instructions as shown in the [Getting Started guide](../../introduction/getting-started).\n:::\n\n### Example\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/with-apiprovider?fontsize=12&runonclick=1&hidenavigation=1&module=%2Fsrc%2FApp.tsx&theme=dark\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query ApiProvider\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n"
  },
  {
    "path": "docs/rtk-query/api/createApi.mdx",
    "content": "---\nid: createApi\ntitle: createApi\nsidebar_label: createApi\nhide_title: true\ndescription: 'RTK Query > API: createApi reference'\n---\n\n&nbsp;\n\n# `createApi`\n\n`createApi` is the core of RTK Query's functionality. It allows you to define a set of \"endpoints\" that describe how to retrieve data from backend APIs and other async sources, including the configuration of how to fetch and transform that data. It generates [an \"API slice\" structure](./created-api/overview.mdx) that contains Redux logic (and optionally React hooks) that encapsulate the data fetching and caching process for you.\n\n:::tip\n\nTypically, you should only have one API slice per base URL that your application needs to communicate with. For example, if your site fetches data from both `/api/posts` and `/api/users`, you would have a single API slice with `/api/` as the base URL, and separate endpoint definitions for `posts` and `users`. This allows you to effectively take advantage of [automated re-fetching](../usage/automated-refetching.mdx) by defining [tag](../usage/automated-refetching.mdx#tags) relationships across endpoints.\n\nThis is because:\n\n- Automatic tag invalidation only works within a single API slice. If you have multiple API slices, the automatic invalidation won't work across them.\n- Every `createApi` call generates its own middleware, and each middleware added to the store will run checks against every dispatched action. That has a perf cost that adds up. So, if you called `createApi` 10 times and added 10 separate API middleware to the store, that will be noticeably slower perf-wise.\n\nFor maintainability purposes, you may wish to split up endpoint definitions across multiple files, while still maintaining a single API slice which includes all of these endpoints. See [code splitting](../usage/code-splitting.mdx) for how you can use the `injectEndpoints` property to inject API endpoints from other files into a single API slice definition.\n\n:::\n\n```ts title=\"Example: src/services/pokemon.ts\"\n// file: src/services/types.ts noEmit\nexport type Pokemon = {}\n\n// file: src/services/pokemon.ts\n// Need to use the React-specific entry point to allow generating React hooks\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Pokemon } from './types'\n\n// highlight-start\n// Define a service using a base URL and expected endpoints\nexport const pokemonApi = createApi({\n  reducerPath: 'pokemonApi',\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (build) => ({\n    getPokemonByName: build.query<Pokemon, string>({\n      query: (name) => `pokemon/${name}`,\n    }),\n  }),\n})\n//highlight-end\n\n// highlight-start\n// Export hooks for usage in function components, which are\n// auto-generated based on the defined endpoints\nexport const { useGetPokemonByNameQuery } = pokemonApi\n// highlight-end\n```\n\n## `createApi` Parameters\n\n`createApi` accepts a single configuration object parameter with the following options:\n\n```ts no-transpile\n  baseQuery(args: InternalQueryArgs, api: BaseQueryApi, extraOptions?: DefinitionExtraOptions): any;\n  endpoints(build: EndpointBuilder<InternalQueryArgs, TagTypes>): Definitions;\n  extractRehydrationInfo?: (\n    action: UnknownAction,\n    {\n      reducerPath,\n    }: {\n      reducerPath: ReducerPath\n    }\n  ) =>\n    | undefined\n    | CombinedState<Definitions, TagTypes, ReducerPath>\n  tagTypes?: readonly TagTypes[];\n  reducerPath?: ReducerPath;\n  serializeQueryArgs?: SerializeQueryArgs<InternalQueryArgs>;\n  keepUnusedDataFor?: number; // value is in seconds\n  refetchOnMountOrArgChange?: boolean | number; // value is in seconds\n  refetchOnFocus?: boolean;\n  refetchOnReconnect?: boolean;\n```\n\n### `baseQuery`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.baseQuery)\n\n#### baseQuery function arguments\n\n- `args` - The return value of the `query` function for a given endpoint\n- `api` - The `BaseQueryApi` object contains:\n  - `signal` - An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) object that may be used to abort DOM requests and/or read whether the request is aborted.\n  - `abort` - The [`abort()`](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/abort) method of the AbortController attached to `signal`.\n  - `dispatch` - The `store.dispatch` method for the corresponding Redux store\n  - `getState` - A function that may be called to access the current store state\n  - `extra` - Provided as thunk.extraArgument to the configureStore getDefaultMiddleware option.\n  - `endpoint` - The name of the endpoint.\n  - `type` - Type of request (`query` or `mutation`).\n  - `forced` - Indicates if a query has been forced.\n  - `queryCacheKey`- The computed query cache key.\n- `extraOptions` - The value of the optional `extraOptions` property provided for a given endpoint\n\n#### baseQuery function signature\n\n```ts title=\"Base Query signature\" no-transpile\nexport type BaseQueryFn<\n  Args = any,\n  Result = unknown,\n  Error = unknown,\n  DefinitionExtraOptions = {},\n  Meta = {},\n> = (\n  args: Args,\n  api: BaseQueryApi,\n  extraOptions: DefinitionExtraOptions,\n) => MaybePromise<QueryReturnValue<Result, Error, Meta>>\n\nexport interface BaseQueryApi {\n  signal: AbortSignal\n  abort: (reason?: string) => void\n  dispatch: ThunkDispatch<any, any, any>\n  getState: () => unknown\n  extra: unknown\n  endpoint: string\n  type: 'query' | 'mutation'\n  forced?: boolean\n}\n\nexport type QueryReturnValue<T = unknown, E = unknown, M = unknown> =\n  | {\n      error: E\n      data?: undefined\n      meta?: M\n    }\n  | {\n      error?: undefined\n      data: T\n      meta?: M\n    }\n```\n\n[examples](docblock://query/createApi.ts?token=CreateApiOptions.baseQuery)\n\n### `endpoints`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.endpoints)\n\nSee [Endpoint Definition Parameters](#endpoint-definition-parameters) for details on individual properties.\n\n#### Query endpoint definition\n\nQuery endpoints (defined with `build.query()`) are used to cache data fetched from the server.\n\nYou must specify either a `query` field (which will use the API's `baseQuery` to make a request), or a `queryFn` function with your own async logic. All other fields are optional.\n\n```ts title=\"Query endpoint definition\" no-transpile\nexport type FullTagDescription<TagType> = {\n  type: TagType\n  id?: number | string\n}\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>\n\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<\n  TagDescription<TagTypes> | undefined | null\n>\n\nexport type ResultDescription<\n  TagTypes extends string,\n  ResultType,\n  QueryArg,\n  ErrorType,\n  MetaType,\n> =\n  | TagDescriptionArray<TagTypes>\n  | (\n  result: ResultType | undefined,\n  error: ErrorType | undefined,\n  arg: QueryArg,\n  meta: MetaType,\n) => TagDescriptionArray<TagTypes>\n\n\nexport type QueryDefinition<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  TagTypes extends string,\n  ResultType,\n  ReducerPath extends string = string,\n> = {\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>\n\n  /* either `query` or `queryFn` can be present, but not both simultaneously */\n  queryFn(\n    arg: QueryArg,\n    api: BaseQueryApi,\n    extraOptions: BaseQueryExtraOptions<BaseQuery>,\n    baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>,\n  ): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>>>\n\n  /* transformResponse only available with `query`, not `queryFn` */\n  transformResponse?(\n    baseQueryReturnValue: BaseQueryResult<BaseQuery>,\n    meta: BaseQueryMeta<BaseQuery>,\n    arg: QueryArg,\n  ): ResultType | Promise<ResultType>\n\n  /* transformErrorResponse only available with `query`, not `queryFn` */\n  transformErrorResponse?(\n    baseQueryReturnValue: BaseQueryError<BaseQuery>,\n    meta: BaseQueryMeta<BaseQuery>,\n    arg: QueryArg,\n  ): unknown\n\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>\n\n  providesTags?: ResultDescription<\n    TagTypes,\n    ResultType,\n    QueryArg,\n    BaseQueryError<BaseQuery>\n  >\n\n  keepUnusedDataFor?: number\n\n  onQueryStarted?(\n    arg: QueryArg,\n    {\n      dispatch,\n      getState,\n      extra,\n      requestId,\n      queryFulfilled,\n      getCacheEntry,\n      updateCachedData, // available for query endpoints only\n    }: QueryLifecycleApi,\n  ): Promise<void>\n\n  onCacheEntryAdded?(\n    arg: QueryArg,\n    {\n      dispatch,\n      getState,\n      extra,\n      requestId,\n      cacheEntryRemoved,\n      cacheDataLoaded,\n      getCacheEntry,\n      updateCachedData, // available for query endpoints only\n    }: QueryCacheLifecycleApi,\n  ): Promise<void>\n\n  argSchema?: StandardSchemaV1<QueryArg>\n\n  /* only available with `query`, not `queryFn` */\n  rawResponseSchema?: StandardSchemaV1<BaseQueryResult<BaseQuery>>\n\n  responseSchema?: StandardSchemaV1<ResultType>\n\n  /* only available with `query`, not `queryFn` */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>\n\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>\n\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>\n}\n```\n\n#### Infinite Query endpoint definition\n\nInfinite query endpoints (defined with `build.infiniteQuery()`) are used to cache multi-page data sets from the server. They have all the same callbacks and options as standard query endpoints, but also require an additional [`infiniteQueryOptions`](#infinitequeryoptions) field to specify how to calculate the unique parameters to fetch each page.\n\nFor infinite query endpoints, there is a separation between the \"query arg\" used for the cache key, and the \"page param\" used to fetch a specific page. For example, a Pokemon API endpoint might have a string query arg like `\"fire\"` , but use a page number as the param to determine which page to fetch out of the results. The `query` and `queryFn` methods will receive a combined `{queryArg, pageParam}` object as the argument, rather than just the `queryArg` by itself.\n\n```ts title=\"Infinite Query endpoint definition\" no-transpile\nexport type PageParamFunction<DataType, PageParam, QueryArg> = (\n  firstPage: DataType,\n  allPages: Array<DataType>,\n  firstPageParam: PageParam,\n  allPageParams: Array<PageParam>,\n  queryArg: QueryArg,\n) => PageParam | undefined | null\n\ntype InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg\n  pageParam: PageParam\n}\n\nexport type InfiniteQueryDefinition<\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n  TagTypes extends string,\n  ResultType,\n  ReducerPath extends string = string,\n> =\n  // Infinite queries have all the same options as query endpoints,\n  // but store the `{pages, pageParams}` structure, and receive an object\n  // with both `{queryArg, pageParam}` as the arg for `query` and `queryFn`.\n  QueryDefinition<\n    InfiniteQueryCombinedArg<QueryArg, PageParam>,\n    BaseQuery,\n    TagTypes,\n    InfiniteData<ResultType>\n  > & {\n    /**\n     * Required options to configure the infinite query behavior.\n     * `initialPageParam` and `getNextPageParam` are required, to\n     * ensure the infinite query can properly fetch the next page of data.\n     * `initialPageparam` may be specified when using the\n     * endpoint, to override the default value.\n     */\n    infiniteQueryOptions: {\n      /**\n       * The initial page parameter to use for the first page fetch.\n       */\n      initialPageParam: PageParam\n      /**\n       * This function is required to automatically get the next cursor for infinite queries.\n       * The result will also be used to determine the value of `hasNextPage`.\n       */\n      getNextPageParam: PageParamFunction<DataType, PageParam, QueryArg>\n      /**\n       * This function can be set to automatically get the previous cursor for infinite queries.\n       * The result will also be used to determine the value of `hasPreviousPage`.\n       */\n      getPreviousPageParam?: PageParamFunction<DataType, PageParam, QueryArg>\n      /**\n       * If specified, only keep this many pages in cache at once.\n       * If additional pages are fetched, older pages in the other\n       * direction will be dropped from the cache.\n       */\n      maxPages?: number\n      /**\n       * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n       * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n       * RTK Query will try to sequentially refetch all pages currently in the cache.\n       * When `false` only the first page will be refetched.\n       */\n      refetchCachedPages?: boolean\n    }\n  }\n```\n\n#### Mutation endpoint definition\n\nMutation endpoints (defined with `build.mutation()`) are used to send updates to the server, and force invalidation and refetching of query endpoints.\n\nAs with queries, you must specify either the `query` option or the `queryFn` async method.\n\n```ts title=\"Mutation endpoint definition\" no-transpile\nexport type MutationDefinition<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  TagTypes extends string,\n  ResultType,\n  ReducerPath extends string = string,\n  Context = Record<string, any>,\n> = {\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>\n\n  /* either `query` or `queryFn` can be present, but not both simultaneously */\n  queryFn(\n    arg: QueryArg,\n    api: BaseQueryApi,\n    extraOptions: BaseQueryExtraOptions<BaseQuery>,\n    baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>,\n  ): MaybePromise<QueryReturnValue<ResultType, BaseQueryError<BaseQuery>>>\n\n  /* transformResponse only available with `query`, not `queryFn` */\n  transformResponse?(\n    baseQueryReturnValue: BaseQueryResult<BaseQuery>,\n    meta: BaseQueryMeta<BaseQuery>,\n    arg: QueryArg,\n  ): ResultType | Promise<ResultType>\n\n  /* transformErrorResponse only available with `query`, not `queryFn` */\n  transformErrorResponse?(\n    baseQueryReturnValue: BaseQueryError<BaseQuery>,\n    meta: BaseQueryMeta<BaseQuery>,\n    arg: QueryArg,\n  ): unknown\n\n  extraOptions?: BaseQueryExtraOptions<BaseQuery>\n\n  invalidatesTags?: ResultDescription<TagTypes, ResultType, QueryArg>\n\n  onQueryStarted?(\n    arg: QueryArg,\n    {\n      dispatch,\n      getState,\n      extra,\n      requestId,\n      queryFulfilled,\n      getCacheEntry,\n    }: MutationLifecycleApi,\n  ): Promise<void>\n\n  onCacheEntryAdded?(\n    arg: QueryArg,\n    {\n      dispatch,\n      getState,\n      extra,\n      requestId,\n      cacheEntryRemoved,\n      cacheDataLoaded,\n      getCacheEntry,\n    }: MutationCacheLifecycleApi,\n  ): Promise<void>\n}\n```\n\n#### How endpoints get used\n\nWhen defining a key like `getPosts` as shown below, it's important to know that this name will become exportable from `api` and be able to referenced under `api.endpoints.getPosts.useQuery()`, `api.endpoints.getPosts.initiate()` and `api.endpoints.getPosts.select()`. The same thing applies to `mutation`s but they reference `useMutation` instead of `useQuery`.\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\ninterface Post {\n  id: number\n  name: string\n}\ntype PostsResponse = Post[]\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  tagTypes: ['Posts'],\n  endpoints: (build) => ({\n    getPosts: build.query<PostsResponse, void>({\n      query: () => 'posts',\n      providesTags: (result) =>\n        result ? result.map(({ id }) => ({ type: 'Posts', id })) : [],\n    }),\n    addPost: build.mutation<Post, Partial<Post>>({\n      query: (body) => ({\n        url: `posts`,\n        method: 'POST',\n        body,\n      }),\n      invalidatesTags: ['Posts'],\n    }),\n  }),\n})\n\n// Auto-generated hooks\nexport const { useGetPostsQuery, useAddPostMutation } = api\n\n// Possible exports\nexport const { endpoints, reducerPath, reducer, middleware } = api\n// reducerPath, reducer, middleware are only used in store configuration\n// endpoints will have:\n// endpoints.getPosts.initiate(), endpoints.getPosts.select(), endpoints.getPosts.useQuery()\n// endpoints.addPost.initiate(), endpoints.addPost.select(), endpoints.addPost.useMutation()\n// see `createApi` overview for _all exports_\n```\n\n### `extractRehydrationInfo`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.extractRehydrationInfo)\n\n[examples](docblock://query/createApi.ts?token=CreateApiOptions.extractRehydrationInfo)\n\nSee also [Server Side Rendering](../usage/server-side-rendering.mdx) and\n[Persistence and Rehydration](../usage/persistence-and-rehydration.mdx).\n\n### `tagTypes`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.tagTypes)\n\n[examples](docblock://query/createApi.ts?token=CreateApiOptions.tagTypes)\n\n### `reducerPath`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.reducerPath)\n\n[examples](docblock://query/createApi.ts?token=CreateApiOptions.reducerPath)\n\n### `serializeQueryArgs`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.serializeQueryArgs)\n\nBy default, this function will take the query arguments, sort object keys where applicable, stringify the result, and concatenate it with the endpoint name. This creates a cache key based on the combination of arguments + endpoint name (ignoring object key order), such that calling any given endpoint with the same arguments will result in the same cache key.\n\n### `invalidationBehavior`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.invalidationBehavior)\n\n### `keepUnusedDataFor`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.keepUnusedDataFor)\n\n[examples](docblock://query/createApi.ts?token=CreateApiOptions.keepUnusedDataFor)\n\n### `refetchOnMountOrArgChange`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.refetchOnMountOrArgChange)\n\n:::note\nYou can set this globally in `createApi`, but you can also override the default value and have more granular control by passing `refetchOnMountOrArgChange` to each individual hook call or similarly by passing `forceRefetch: true` when dispatching the [`initiate`](./created-api/endpoints.mdx#initiate) action.\n:::\n\n### `refetchOnFocus`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.refetchOnFocus)\n\n:::note\nYou can set this globally in `createApi`, but you can also override the default value and have more granular control by passing `refetchOnFocus` to each individual hook call or when dispatching the [`initiate`](./created-api/endpoints.mdx#initiate) action.\n\nIf you specify `track: false` when manually dispatching queries, RTK Query will not be able to automatically refetch for you.\n:::\n\n### `refetchOnReconnect`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.refetchOnReconnect)\n\n:::note\nYou can set this globally in `createApi`, but you can also override the default value and have more granular control by passing `refetchOnReconnect` to each individual hook call or when dispatching the [`initiate`](./created-api/endpoints.mdx#initiate) action.\n\nIf you specify `track: false` when manually dispatching queries, RTK Query will not be able to automatically refetch for you.\n:::\n\n### `onSchemaFailure`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.onSchemaFailure)\n\n[examples](docblock://query/createApi.ts?token=CreateApiOptions.onSchemaFailure)\n\n:::note\nYou can set this globally in `createApi`, but you can also override the default value and have more granular control by passing `onSchemaFailure` to each individual endpoint definition.\n:::\n\n### `catchSchemaFailure`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.catchSchemaFailure)\n\n[examples](docblock://query/createApi.ts?token=CreateApiOptions.catchSchemaFailure)\n\n:::note\nYou can set this globally in `createApi`, but you can also override the default value and have more granular control by passing `catchSchemaFailure` to each individual endpoint definition.\n:::\n\n### `skipSchemaValidation`\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.skipSchemaValidation)\n\n[examples](docblock://query/createApi.ts?token=CreateApiOptions.skipSchemaValidation)\n\n:::note\nYou can set this globally in `createApi`, but you can also override the default value and have more granular control by passing `skipSchemaValidation` to each individual endpoint definition.\n:::\n\n## Endpoint Definition Parameters\n\n### `query`\n\n_(required if no `queryFn` provided)_\n\n```ts title=\"query signature\" no-transpile\nexport type query = <QueryArg>(\n  arg: QueryArg,\n) => string | Record<string, unknown>\n\n// with `fetchBaseQuery`\nexport type query = <QueryArg>(arg: QueryArg) => string | FetchArgs\n```\n\n[summary](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.query)\n\n[examples](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.query)\n\n### `queryFn`\n\n_(required if no `query` provided)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQueryFn.queryFn)\n\nCalled with the same arguments as `baseQuery`, as well as the provided `baseQuery` function itself. It is expected to return an object with either a `data` or `error` property, or a promise that resolves to return such an object.\n\nSee also [Customizing queries with queryFn](../usage/customizing-queries.mdx#customizing-queries-with-queryfn).\n\n```ts title=\"queryFn signature\" no-transpile\nqueryFn(\n  arg: QueryArg,\n  api: BaseQueryApi,\n  extraOptions: BaseQueryExtraOptions<BaseQuery>,\n  baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>\n): MaybePromise<\n| {\n    error: BaseQueryError<BaseQuery>\n    data?: undefined\n  }\n| {\n    error?: undefined\n    data: ResultType\n  }\n>\n\nexport interface BaseQueryApi {\n  signal: AbortSignal\n  dispatch: ThunkDispatch<any, any, any>\n  getState: () => unknown\n}\n```\n\n#### `queryFn` function arguments\n\n- `args` - The argument provided when the query itself is called\n- `api` - The `BaseQueryApi` object, containing `signal`, `dispatch` and `getState` properties\n  - `signal` - An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) object that may be used to abort DOM requests and/or read whether the request is aborted.\n  - `dispatch` - The `store.dispatch` method for the corresponding Redux store\n  - `getState` - A function that may be called to access the current store state\n- `extraOptions` - The value of the optional `extraOptions` property provided for the endpoint\n- `baseQuery` - The `baseQuery` function provided to the api itself\n\n[examples](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQueryFn.queryFn)\n\n### `infiniteQueryOptions`\n\n_(only for `infiniteQuery` endpoints)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=InfiniteQueryExtraOptions.infiniteQueryOptions)\n\nThe `infiniteQueryOptions` field includes:\n\n- `initialPageParam`: the default page param value used for the first request, if this was not specified at the usage site\n- `getNextPageParam`: a required callback you must provide to calculate the next page param, given the existing cached pages and page params\n- `getPreviousPageParam`: an optional callback that will be used to calculate the previous page param, if you try to fetch backwards.\n- `maxPages`: an optional limit to how many fetched pages will be kept in the cache entry at a time\n\n[examples](docblock://query/endpointDefinitions.ts?token=InfiniteQueryExtraOptions.infiniteQueryOptions)\n\n### `transformResponse`\n\n_(optional, not applicable with `queryFn`)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.transformResponse)\n\nIn some cases, you may want to manipulate the data returned from a query before you put it in the cache. In this instance, you can take advantage of `transformResponse`.\n\nSee also [Customizing query responses with `transformResponse`](../usage/customizing-queries.mdx#customizing-query-responses-with-transformresponse)\n\n```ts title=\"Unpack a deeply nested collection\" no-transpile\ntransformResponse: (response, meta, arg) =>\n  response.some.deeply.nested.collection\n```\n\n### `transformErrorResponse`\n\n_(optional, not applicable with `queryFn`)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.transformErrorResponse)\n\nIn some cases, you may want to manipulate the error returned from a query before you put it in the cache. In this instance, you can take advantage of `transformErrorResponse`.\n\nSee also [Customizing query responses with `transformErrorResponse`](../usage/customizing-queries.mdx#customizing-query-responses-with-transformerrorresponse)\n\n```ts title=\"Unpack a deeply nested error object\" no-transpile\ntransformErrorResponse: (response, meta, arg) =>\n  response.data.some.deeply.nested.errorObject\n```\n\n### `extraOptions`\n\n_(optional)_\n\nPassed as the third argument to the supplied `baseQuery` function\n\n### `providesTags`\n\n_(optional, only for query endpoints)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.providesTags)\n\nSee also [Providing cache data](../usage/automated-refetching.mdx#providing-cache-data).\n\n[examples](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.providesTags)\n\n### `invalidatesTags`\n\n_(optional, only for mutation endpoints)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=MutationExtraOptions.invalidatesTags)\n\nSee also [Invalidating cache data](../usage/automated-refetching.mdx#invalidating-cache-data).\n\n[examples](docblock://query/endpointDefinitions.ts?token=MutationExtraOptions.invalidatesTags)\n\n### `keepUnusedDataFor`\n\n_(optional, only for query endpoints)_\n\nOverrides the api-wide definition of `keepUnusedDataFor` for this endpoint only.\n\n[summary](docblock://query/createApi.ts?token=CreateApiOptions.keepUnusedDataFor)\n\n[examples](docblock://query/core/buildMiddleware/cacheCollection.ts?token=CacheCollectionQueryExtraOptions)\n\n### `serializeQueryArgs`\n\n_(optional, only for query endpoints)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.serializeQueryArgs)\n\n[examples](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.serializeQueryArgs)\n\n### `merge`\n\n_(optional, only for query endpoints)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.merge)\n\n[examples](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.merge)\n\n### `forceRefetch`\n\n_(optional, only for query endpoints)_\n\n```ts title=\"forceRefetch signature\" no-transpile\ntype forceRefetch = (params: {\n  currentArg: QueryArg | undefined\n  previousArg: QueryArg | undefined\n  state: RootState<any, any, string>\n  endpointState?: QuerySubState<any>\n}) => boolean\n```\n\n[summary](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.forceRefetch)\n\n[examples](docblock://query/endpointDefinitions.ts?token=QueryExtraOptions.forceRefetch)\n\n### `onQueryStarted`\n\n_(optional)_\n\nAvailable to both [queries](../usage/queries.mdx) and [mutations](../usage/mutations.mdx).\n\nA function that is called when you start each individual query or mutation. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n\nCan be used in `mutations` for [optimistic updates](../usage/manual-cache-updates.mdx#optimistic-updates).\n\n#### Lifecycle API properties\n\n- `dispatch` - The dispatch method for the store.\n- `getState` - A method to get the current state for the store.\n- `extra` - `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\n- `requestId` - A unique ID generated for the query/mutation.\n- `queryFulfilled` - A Promise that will resolve with a `data` property (the transformed query result),\n  and a `meta` property (`meta` returned by the `baseQuery`).\n  If the query fails, this Promise will reject with the error. This allows you to `await` for the query to finish.\n- `getCacheEntry` - A function that gets the current value of the cache entry.\n- `updateCachedData` _(query endpoints only)_ - A function that accepts a 'recipe' callback specifying how to update the data for the corresponding cache at the time it is called. This uses `immer` internally, and updates can be written 'mutably' while safely producing the next immutable state.\n\n```ts title=\"Mutation onQueryStarted signature\" no-transpile\nasync function onQueryStarted(\n  arg: QueryArg,\n  {\n    dispatch,\n    getState,\n    extra,\n    requestId,\n    queryFulfilled,\n    getCacheEntry,\n  }: MutationLifecycleApi,\n): Promise<void>\n```\n\n```ts title=\"Query onQueryStarted signature\" no-transpile\nasync function onQueryStarted(\n  arg: QueryArg,\n  {\n    dispatch,\n    getState,\n    extra,\n    requestId,\n    queryFulfilled,\n    getCacheEntry,\n    updateCachedData, // available for query endpoints only\n  }: QueryLifecycleApi,\n): Promise<void>\n```\n\n```ts title=\"onQueryStarted query lifecycle example\"\n// file: notificationsSlice.ts noEmit\nexport const messageCreated = (msg: string) => ({\n  type: 'notifications/messageCreated',\n  payload: msg,\n})\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport { messageCreated } from './notificationsSlice'\n\nexport interface Post {\n  id: number\n  name: string\n}\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n  }),\n  endpoints: (build) => ({\n    getPost: build.query<Post, number>({\n      query: (id) => `post/${id}`,\n      async onQueryStarted(id, { dispatch, queryFulfilled }) {\n        // `onStart` side-effect\n        dispatch(messageCreated('Fetching post...'))\n        try {\n          const { data } = await queryFulfilled\n          // `onSuccess` side-effect\n          dispatch(messageCreated('Post received!'))\n        } catch (err) {\n          // `onError` side-effect\n          dispatch(messageCreated('Error fetching post!'))\n        }\n      },\n    }),\n  }),\n})\n```\n\n### `onCacheEntryAdded`\n\n_(optional)_\n\nAvailable to both [queries](../usage/queries.mdx) and [mutations](../usage/mutations.mdx).\n\nA function that is called when a new cache entry is added, i.e. when a new subscription for the endpoint + query parameters combination is created. The function is called with a lifecycle api object containing properties such as `cacheDataLoaded` & `cacheDataRemoved`, allowing code to be run when a cache entry is added, when cache data is loaded, and when the cache entry is removed (i.e. throughout the lifecycle of a cache entry).\n\nCan be used for [streaming updates](../usage/streaming-updates.mdx).\n\n#### Cache Lifecycle API properties\n\n- `dispatch` - The dispatch method for the store.\n- `getState` - A method to get the current state for the store.\n- `extra` - `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\n- `requestId` - A unique ID generated for the cache entry.\n- `cacheEntryRemoved` - A Promise that allows you to wait for the point in time when the cache entry has been removed from the cache, by not being used/subscribed to any more in the application for too long or by dispatching `api.util.resetApiState`.\n- `cacheDataLoaded` - A Promise that will resolve with the first value for this cache key. This allows you to `await` until an actual value is in the cache.  \n  Note: If the cache entry is removed from the cache before any value has ever been resolved, this Promise will reject with `new Error('Promise never resolved before cacheEntryRemoved.')` to prevent memory leaks. You can just re-throw that error (or not handle it at all) - it will be caught outside of `cacheEntryAdded`.\n- `getCacheEntry` - A function that gets the current value of the cache entry.\n- `updateCachedData` _(query endpoints only)_ - A function that accepts a 'recipe' callback specifying how to update the data at the time it is called. This uses `immer` internally, and updates can be written 'mutably' while safely producing the next immutable state.\n\n```ts title=\"Mutation onCacheEntryAdded signature\" no-transpile\nasync function onCacheEntryAdded(\n  arg: QueryArg,\n  {\n    dispatch,\n    getState,\n    extra,\n    requestId,\n    cacheEntryRemoved,\n    cacheDataLoaded,\n    getCacheEntry,\n  }: MutationCacheLifecycleApi,\n): Promise<void>\n```\n\n```ts title=\"Query onCacheEntryAdded signature\" no-transpile\nasync function onCacheEntryAdded(\n  arg: QueryArg,\n  {\n    dispatch,\n    getState,\n    extra,\n    requestId,\n    cacheEntryRemoved,\n    cacheDataLoaded,\n    getCacheEntry,\n    updateCachedData, // available for query endpoints only\n  }: QueryCacheLifecycleApi,\n): Promise<void>\n```\n\n### Schema Validation\n\nEndpoints can have schemas for runtime validation of query args, responses, and errors. Any [Standard Schema](https://standardschema.dev/) compliant library can be used.\n\nWhen used with TypeScript, schemas can also be used to [infer the type of that value instead of having to declare it](../usage-with-typescript.mdx#schema-validation).\n\n:::warning\n\nBy default, schema failures are treated as _fatal_, meaning that normal error handling such as tag invalidation will not be executed.\n\nIn order for schema failures to be treated as non-fatal, you must provide a [`catchSchemaFailure`](#catchschemafailure) function, to convert the schema failure into an error shape matching the base query errors.\n\n```ts title=\"catchSchemaFailure example\" no-transpile\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  catchSchemaFailure: (error, info) => ({\n    status: 'CUSTOM_ERROR',\n    error: error.schemaName + ' failed validation',\n    data: error,\n  }),\n  endpoints: (build) => ({\n    // ...\n  }),\n})\n```\n\n:::\n\n#### `argSchema`\n\n_(optional)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=CommonEndpointDefinition.argSchema)\n\n[examples](docblock://query/endpointDefinitions.ts?token=CommonEndpointDefinition.argSchema)\n\n#### `responseSchema`\n\n_(optional)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=CommonEndpointDefinition.responseSchema)\n\n[examples](docblock://query/endpointDefinitions.ts?token=CommonEndpointDefinition.responseSchema)\n\n#### `rawResponseSchema`\n\n_(optional, not applicable with `queryFn`)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.rawResponseSchema)\n\n[examples](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.rawResponseSchema)\n\n#### `errorResponseSchema`\n\n_(optional)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=CommonEndpointDefinition.errorResponseSchema)\n\n[examples](docblock://query/endpointDefinitions.ts?token=CommonEndpointDefinition.errorResponseSchema)\n\n#### `rawErrorResponseSchema`\n\n_(optional, not applicable with `queryFn`)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.rawErrorResponseSchema)\n\n[examples](docblock://query/endpointDefinitions.ts?token=EndpointDefinitionWithQuery.rawErrorResponseSchema)\n\n#### `metaSchema`\n\n_(optional)_\n\n[summary](docblock://query/endpointDefinitions.ts?token=CommonEndpointDefinition.metaSchema)\n\n[examples](docblock://query/endpointDefinitions.ts?token=CommonEndpointDefinition.metaSchema)\n\n## Return value\n\nSee [the \"created Api\" API reference](./created-api/overview)\n"
  },
  {
    "path": "docs/rtk-query/api/created-api/api-slice-utils.mdx",
    "content": "---\nid: api-slice-utils\ntitle: 'API Slices: Utilities'\nsidebar_label: API Slice Utilities\nhide_title: true\n---\n\n&nbsp;\n\n# API Slices: Utilities\n\nThe API slice object includes various utilities that can be used for cache management,\nsuch as implementing [optimistic updates](../../usage/manual-cache-updates.mdx#optimistic-updates),\nas well implementing [server side rendering](../../usage/server-side-rendering.mdx).\n\nThese are included as `api.util` inside the API object.\n\n:::info\n\nSome of the TS types on this page are pseudocode to illustrate intent, as the actual internal types are fairly complex.\n\n:::\n\n### `updateQueryData`\n\nA Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.\n\n#### Signature\n\n```ts no-transpile\nconst updateQueryData = (\n  endpointName: string,\n  arg: any,\n  updateRecipe: (draft: Draft<CachedState>) => void,\n  updateProvided?: boolean,\n) => ThunkAction<PatchCollection, PartialState, any, AnyAction>\n\ninterface PatchCollection {\n  patches: Patch[]\n  inversePatches: Patch[]\n  undo: () => void\n}\n```\n\n#### Parameters\n\n- `endpointName`: a string matching an existing endpoint name\n- `arg`: an argument matching that used for a previous query call, used to determine which cached dataset needs to be updated\n- `updateRecipe`: an Immer `produce` callback that can apply changes to the cached state\n- `updateProvided`: a boolean indicating whether the endpoint's provided tags should be re-calculated based on the updated cache. Defaults to `false`.\n\n#### Description\n\nThe thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), any relevant query arguments, and a callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.\n\nThe thunk returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).\n\nThis is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.\n\nNote that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.\n\n#### Example 1\n\n```ts no-transpile\nconst patchCollection = dispatch(\n  api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n    draftPosts.push({ id: 1, name: 'Teddy' })\n  }),\n)\n```\n\nIn the example above, `'getPosts'` is provided for the `endpointName`, and `undefined` is provided\nfor `arg`. This will match a query cache key of `'getPosts(undefined)'`.\n\ni.e. it will match a cache entry that may have been created via any of the following calls:\n\n```ts no-transpile\napi.endpoints.getPosts.useQuery()\n\nuseGetPostsQuery()\n\nuseGetPostsQuery(undefined, { ...options })\n\ndispatch(api.endpoints.getPosts.initiate())\n\ndispatch(api.endpoints.getPosts.initiate(undefined, { ...options }))\n```\n\n#### Example 2\n\n```ts no-transpile\nconst patchCollection = dispatch(\n  api.util.updateQueryData('getPostById', 1, (draftPost) => {\n    draftPost.name = 'Lilly'\n  }),\n)\n```\n\nIn the example above, `'getPostById'` is provided for the `endpointName`, and `1` is provided\nfor `arg`. This will match a query cache key of `'getPostById(1)'`.\n\ni.e. it will match a cache entry that may have been created via any of the following calls:\n\n```ts no-transpile\napi.endpoints.getPostById.useQuery(1)\n\nuseGetPostByIdQuery(1)\n\nuseGetPostByIdQuery(1, { ...options })\n\ndispatch(api.endpoints.getPostById.initiate(1))\n\ndispatch(api.endpoints.getPostById.initiate(1, { ...options }))\n```\n\n### `upsertQueryData`\n\nA Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.\n\n#### Signature\n\n```ts no-transpile\nconst upsertQueryData = <T>(endpointName: string, arg: any, newEntryData: T) =>\n  ThunkAction<Promise<CacheEntry<T>>, PartialState, any, UnknownAction>\n```\n\n#### Parameters\n\n- `endpointName`: a string matching an existing endpoint name\n- `arg`: an argument matching that used for a previous query call, used to determine which cached dataset needs to be updated\n- `newEntryValue`: the value to be written into the corresponding cache entry's `data` field\n\n#### Description\n\nThe thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.\n\nIf no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.\n\nThe thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated. This includes executing the `transformResponse` callback if defined for that endpoint.\n\nIf dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a \"last result wins\" update behavior.\n\n#### Example\n\n```ts no-transpile\nawait dispatch(\n  api.util.upsertQueryData('getPost', { id: 1 }, { id: 1, text: 'Hello!' }),\n)\n```\n\n### `patchQueryData`\n\nA Redux thunk action creator that, when dispatched, applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.\n\n#### Signature\n\n```ts no-transpile\nconst patchQueryData = (\n  endpointName: string,\n  arg: any\n  patches: Patch[],\n  updateProvided?: boolean\n) => ThunkAction<void, PartialState, any, UnknownAction>;\n```\n\n#### Parameters\n\n- `endpointName`: a string matching an existing endpoint name\n- `arg`: a cache key, used to determine which cached dataset needs to be updated\n- `patches`: an array of patches (or inverse patches) to apply to cached state. These would typically be obtained from the result of dispatching [`updateQueryData`](#updatequerydata)\n- `updateProvided`: a boolean indicating whether the endpoint's provided tags should be re-calculated based on the updated cache. Defaults to `false`.\n\n#### Description\n\nThe thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.\n\nThis is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.\n\nIn cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.\n\n#### Example\n\n```ts no-transpile\nconst patchCollection = dispatch(\n  api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n    draftPosts.push({ id: 1, name: 'Teddy' })\n  }),\n)\n\n// later\ndispatch(\n  api.util.patchQueryData(\n    'getPosts',\n    undefined,\n    patchCollection.inversePatches,\n  ),\n)\n\n// or\npatchCollection.undo()\n```\n\n### `upsertQueryEntries`\n\nA standard Redux action creator that accepts an array of individual cache entry descriptions, and immediately upserts them into the store. This is designed to efficiently bulk-insert many entries at once.\n\n#### Signature\n\n```ts no-transpile\n/**\n * A typesafe single entry to be upserted into the cache\n */\nexport type NormalizedQueryUpsertEntry<\n  Definitions extends EndpointDefinitions,\n  EndpointName extends QueryKeys<Definitions>,\n> = {\n  endpointName: EndpointName\n  arg: QueryArgFrom<Definitions[EndpointName]>\n  value: ResultTypeFrom<Definitions[EndpointName]>\n}\n\nconst upsertQueryEntries = (entries: NormalizedQueryUpsertEntry[]) =>\n  PayloadAction<NormalizedQueryUpsertEntry[]>\n```\n\n#### Parameters\n\n- `entries`: an array of objects that contain the data needed to upsert individual cache entries:\n  - `endpointName`: the name of the endpoint, such as `\"getPokemon\"`\n  - `arg`: the full query key argument needed to identify this cache entry, such as `\"pikachu\"` (same as you would pass to a `useQuery` hook or `api.endpoints.someEndpoint.select()`)\n  - `value`: the data to be upserted into this cache entry, exactly as formatted.\n\n#### Description\n\nThis method is designed as a more efficient approach to bulk-inserting many entries at once than many individual calls to `upsertQueryData`. As a comparison:\n\n- `upsertQueryData`:\n  - upserts one cache entry at a time\n  - Is async\n  - Dispatches 2 separate actions, `pending` and `fulfilled`\n  - Runs the `transformResponse` callback if defined for that endpoint, as well as the `merge` callback if defined\n- `upsertQueryEntries`:\n  - upserts many cache entries at once, and they may be for any combination of endpoints defined in the API\n  - Is a single synchronous action\n  - Does _not_ run `transformResponse`, so the provided `value` fields must already be in the final format expected for that endpoint. However, it will still run the `merge` callback if defined\n\nCurrently, this method has two main use cases. The first is prefilling the cache with data retrieved from storage on app startup. The second is to act as a \"pseudo-normalization\" tool. [RTK Query is _not_ a \"normalized\" cache](../../usage/cache-behavior.mdx#no-normalized-or-de-duplicated-cache). However, there are times when you may want to prefill other cache entries with the contents of another endpoint, such as taking the results of a `getPosts` list endpoint response and prefilling the individual `getPost(id)` endpoint cache entries.\n\nIf no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.\n\nIf dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a \"last result wins\" update behavior.\n\n#### Example\n\n```ts no-transpile\nconst api = createApi({\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => '/posts',\n      async onQueryStarted(_, { dispatch, queryFulfilled }) {\n        const res = await queryFulfilled\n        const posts = res.data\n\n        // Pre-fill the individual post entries with the results\n        // from the list endpoint query\n        dispatch(\n          api.util.upsertQueryEntries(\n            posts.map((post) => ({\n              endpointName: 'getPost',\n              arg: { id: post.id },\n              value: post,\n            })),\n          ),\n        )\n      },\n    }),\n    getPost: build.query<Post, Pick<Post, 'id'>>({\n      query: (post) => `post/${post.id}`,\n    }),\n  }),\n})\n```\n\n### `prefetch`\n\nA Redux thunk action creator that can be used to manually trigger pre-fetching of data.\n\n#### Signature\n\n```ts no-transpile\ntype PrefetchOptions = { ifOlderThan?: false | number } | { force?: boolean }\n\nconst prefetch = (endpointName: string, arg: any, options: PrefetchOptions) =>\n  ThunkAction<void, any, any, UnknownAction>\n```\n\n#### Parameters\n\n- `endpointName`: a string matching an existing endpoint name\n- `args`: a cache key, used to determine which cached dataset needs to be updated\n- `options`: options to determine whether the request should be sent for a given situation:\n  - `ifOlderThan`: if specified, only runs the query if the difference between `new Date()` and the last`fulfilledTimeStamp` is greater than the given value (in seconds)\n  - `force`: if `true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.\n\n#### Description\n\nThe thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), any relevant query arguments, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.\n\nReact Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch the thunk action creator result internally as needed when you call the prefetching function supplied by the hook.\n\n#### Example\n\n```ts no-transpile\ndispatch(api.util.prefetch('getPosts', undefined, { force: true }))\n```\n\n### `selectInvalidatedBy`\n\nA selector function that can select query parameters to be invalidated.\n\n#### Signature\n\n```ts no-transpile\nfunction selectInvalidatedBy(\n  state: RootState,\n  tags: ReadonlyArray<TagDescription<string>>,\n): Array<{\n  endpointName: string\n  originalArgs: any\n  queryCacheKey: QueryCacheKey\n}>\n```\n\n#### Parameters\n\n- `state`: the root state\n- `tags`: a readonly array of invalidated tags, where the provided `TagDescription` is one of the strings provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api. e.g.\n  - `[TagType]`\n  - `[{ type: TagType }]`\n  - `[{ type: TagType, id: number | string }]`\n\n#### Description\n\nThe function accepts two arguments\n\n- the root state and\n- the cache tags to be invalidated.\n\nIt returns an array that contains\n\n- the endpoint name,\n- the original args and\n- the queryCacheKey.\n\n#### Example\n\n```ts no-transpile\nconst entries = api.util.selectInvalidatedBy(state, ['Post'])\nconst entries = api.util.selectInvalidatedBy(state, [{ type: 'Post', id: 1 }])\nconst entries = api.util.selectInvalidatedBy(state, [\n  { type: 'Post', id: 1 },\n  { type: 'Post', id: 4 },\n])\n```\n\n### `invalidateTags`\n\nA Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).\n\n#### Signature\n\n```ts no-transpile\nconst invalidateTags = (\n  tags: Array<TagTypes | FullTagDescription<TagTypes>>,\n) => ({\n  type: string,\n  payload: tags,\n})\n```\n\n#### Parameters\n\n- `tags`: an array of tags to be invalidated, where the provided `TagType` is one of the strings provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api. e.g.\n  - `[TagType]`\n  - `[{ type: TagType }]`\n  - `[{ type: TagType, id: number | string }]`\n\n#### Description\n\nThe action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.\n\nDispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.\n\n#### Example\n\n```ts no-transpile\ndispatch(api.util.invalidateTags(['Post']))\ndispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))\ndispatch(\n  api.util.invalidateTags([\n    { type: 'Post', id: 1 },\n    { type: 'Post', id: 'LIST' },\n  ]),\n)\n```\n\n### `selectCachedArgsForQuery`\n\nA selector function that can select arguments for currently cached queries.\n\n#### Signature\n\n```ts no-transpile\nfunction selectCachedArgsForQuery(\n  state: RootState,\n  queryName: QueryName,\n): Array<QueryArg>\n```\n\n#### Parameters\n\n- `state`: the root state\n- `queryName`: a string matching an existing query endpoint name\n\n#### Description\n\nThe function accepts two arguments\n\n- the root state and\n\n- the name of the query\n\nIt returns an array that contains arguments used for each entry.\n\n#### Example\n\n```ts no-transpile\nconst args = api.util.selectCachedArgsForQuery(state, 'getPosts')\n```\n\n### `resetApiState`\n\n#### Signature\n\n```ts no-transpile\nconst resetApiState = () => ({\n  type: string,\n  payload: undefined,\n})\n```\n\n#### Description\n\nA Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.\n\nNote that [hooks](./hooks.mdx) also track state in local component state and might not fully be reset by `resetApiState`.\n\n#### Example\n\n```ts no-transpile\ndispatch(api.util.resetApiState())\n```\n\n## `getRunningQueriesThunk` and `getRunningMutationsThunk`\n\n#### Signature\n\n```ts no-transpile\ngetRunningQueriesThunk(): ThunkWithReturnValue<Array<QueryActionCreatorResult<any>>>\ngetRunningMutationsThunk(): ThunkWithReturnValue<Array<MutationActionCreatorResult<any>>>\n```\n\n#### Description\n\nThunks that (if dispatched) return either all running queries or mutations.\nThese returned values can be awaited like promises.\n\nThis is useful for SSR scenarios to await all queries (or mutations) triggered in any way, including via hook calls\nor manually dispatching `initiate` actions.\n\n```ts no-transpile title=\"Awaiting all currently running queries example\"\nawait Promise.all(dispatch(api.util.getRunningQueriesThunk()))\n```\n\n## `getRunningQueryThunk` and `getRunningMutationThunk`\n\n#### Signature\n\n```ts no-transpile\ngetRunningQueryThunk<EndpointName extends QueryKeys<Definitions>>(\n  endpointName: EndpointName,\n  args: QueryArgFrom<Definitions[EndpointName]>\n): ThunkWithReturnValue<\n  | QueryActionCreatorResult<\n      Definitions[EndpointName] & { type: 'query' }\n    >\n  | undefined\n>\n\ngetRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(\n  endpointName: EndpointName,\n  fixedCacheKeyOrRequestId: string\n): ThunkWithReturnValue<\n  | MutationActionCreatorResult<\n      Definitions[EndpointName] & { type: 'mutation' }\n    >\n  | undefined\n>\n```\n\n#### Description\n\nThunks that (if dispatched) return a single running query (or mutation) for a given\nendpoint name + argument (or requestId/fixedCacheKey) combination, if it is currently running.\nIf it is not currently running, the function returns `undefined`.\n\nThese thunks are primarily added to add experimental support for suspense in the future.\nThey enable writing custom hooks that look up if RTK Query has already got a running query/mutation\nfor a certain endpoint/argument combination, and retrieving that to `throw` it as a promise.\n"
  },
  {
    "path": "docs/rtk-query/api/created-api/code-splitting.mdx",
    "content": "---\nid: code-splitting\ntitle: 'API Slices: Code Splitting and Generation'\nsidebar_label: Code Splitting\nhide_title: true\n---\n\n&nbsp;\n\n# API Slices: Code Splitting and Generation\n\nEach API slice allows [additional endpoint definitions to be injected at runtime](../../usage/code-splitting.mdx) after the initial API slice has been defined. This can be beneficial for apps that may have _many_ endpoints.\n\nThe individual API slice endpoint definitions can also be split across multiple files. This is primarily useful for working with API slices that were [code-generated from an API schema file](../../usage/code-generation.mdx), allowing you to add additional custom behavior and configuration to a set of automatically-generated endpoint definitions.\n\nEach API slice object has `injectEndpoints` and `enhanceEndpoints` functions to support these use cases.\n\n## `injectEndpoints`\n\n#### Signature\n\n```ts no-transpile\nconst injectEndpoints = (endpointOptions: InjectedEndpointOptions) =>\n  EnhancedApiSlice\n\ninterface InjectedEndpointOptions {\n  endpoints: (build: EndpointBuilder) => NewEndpointDefinitions\n  /**\n   * Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.\n   *\n   * If set to `true`, will override existing endpoints with the new definition.\n   * If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.\n   * If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.\n   */\n  overrideExisting?: boolean | 'throw'\n}\n```\n\n#### Description\n\nAccepts an options object containing the same `endpoints` builder callback you would pass to [`createApi.endpoints`](../createApi.mdx#endpoints). Any endpoint definitions defined using that builder will be merged into the existing endpoint definitions for this API slice using a shallow merge, so any new endpoint definitions will override existing endpoints with the same name.\n\nReturns an updated and enhanced version of the API slice object, containing the combined endpoint definitions.\n\nEndpoints will not be overridden unless `overrideExisting` is set to `true`. If not, a development mode warning will be shown to notify you if there is a name clash between endpoint definitions.\n\nThis method is primarily useful for code splitting and hot reloading.\n\n## `enhanceEndpoints`\n\n#### Signature\n\n```ts no-transpile\nconst enhanceEndpoints = (endpointOptions: EnhanceEndpointsOptions) =>\n  EnhancedApiSlice\n\ninterface EnhanceEndpointsOptions {\n  addTagTypes?: readonly string[]\n  endpoints?: Record<string, Partial<EndpointDefinition>>\n}\n```\n\n#### Description\n\nAny provided tag types or endpoint definitions will be merged into the existing endpoint definitions for this API slice. Unlike `injectEndpoints`, the partial endpoint definitions will not _replace_ existing definitions, but are rather merged together on a per-definition basis (ie, `Object.assign(existingEndpoint, newPartialEndpoint)`).\n\nReturns an updated and enhanced version of the API slice object, containing the combined endpoint definitions.\n\nThis is primarily useful for taking an API slice object that was code-generated from an API schema file like OpenAPI, and adding additional specific hand-written configuration for cache invalidation management on top of the generated endpoint definitions.\n\nFor example, `enhanceEndpoints` can be used to modify caching behavior by changing the values of `providesTags`, `invalidatesTags`, and `keepUnusedDataFor`:\n\n```ts\n// file: api.ts noEmit\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    getUserByUserId: build.query({\n      query() {\n        return ''\n      },\n    }),\n    patchUserByUserId: build.mutation({\n      query() {\n        return ''\n      },\n    }),\n    getUsers: build.query({\n      query() {\n        return ''\n      },\n    }),\n  }),\n})\n\n// file: enhanceEndpoints.ts\nimport { api } from './api'\n\nconst enhancedApi = api.enhanceEndpoints({\n  addTagTypes: ['User'],\n  endpoints: {\n    getUserByUserId: {\n      providesTags: ['User'],\n    },\n    patchUserByUserId: {\n      invalidatesTags: ['User'],\n    },\n    // alternatively, define a function which is called with the endpoint definition as an argument\n    getUsers(endpoint) {\n      endpoint.providesTags = ['User']\n      endpoint.keepUnusedDataFor = 120\n    },\n  },\n})\n```\n"
  },
  {
    "path": "docs/rtk-query/api/created-api/endpoints.mdx",
    "content": "---\nid: endpoints\ntitle: 'API Slices: Endpoints'\nsidebar_label: Endpoints\nhide_title: true\n---\n\n&nbsp;\n\n# API Slices: Endpoints\n\nThe API slice object will have an `endpoints` field inside. This section maps the endpoint names you provided to `createApi` to the core Redux logic (thunks and selectors) used to trigger data fetches and read cached data for that endpoint. If you're using the React-specific version of `createApi`, each endpoint definition will also contain the auto-generated React hooks for that endpoint.\n\nEach endpoint structure contains the following fields:\n\n```ts no-transpile\ntype EndpointLogic = {\n  initiate: InitiateRequestThunk\n  select: CreateCacheSelectorFactory\n  matchPending: Matcher<PendingAction>\n  matchFulfilled: Matcher<FulfilledAction>\n  matchRejected: Matcher<RejectedAction>\n}\n```\n\n## `initiate`\n\n#### Signature\n\n```ts no-transpile\ntype InitiateRequestThunk = StartQueryActionCreator | StartMutationActionCreator;\n\ntype StartQueryActionCreator = (\n  arg:any,\n  options?: StartQueryActionCreatorOptions\n) => ThunkAction<QueryActionCreatorResult, any, any, UnknownAction>;\n\ntype StartMutationActionCreator<D extends MutationDefinition<any, any, any, any>> = (\n  arg: any\n  options?: StartMutationActionCreatorOptions\n) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>;\n\ntype SubscriptionOptions = {\n  /**\n   * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).\n   */\n  pollingInterval?: number;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires `setupListeners` to have been called.\n   */\n  refetchOnReconnect?: boolean;\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires `setupListeners` to have been called.\n   */\n  refetchOnFocus?: boolean;\n};\n\ninterface StartQueryActionCreatorOptions {\n  subscribe?: boolean;\n  forceRefetch?: boolean | number;\n  subscriptionOptions?: SubscriptionOptions;\n}\n\ninterface StartMutationActionCreatorOptions {\n  /**\n   * If this mutation should be tracked in the store.\n   * If you just want to manually trigger this mutation using `dispatch` and don't care about the\n   * result, state & potential errors being held in store, you can set this to false.\n   * (defaults to `true`)\n   */\n  track?: boolean;\n}\n```\n\n#### Description\n\nA Redux thunk action creator that you can dispatch to trigger data fetch queries or mutations.\n\nReact Hooks users will most likely never need to use these directly, as the hooks automatically dispatch these actions as needed.\n\n:::note Usage of actions outside of React Hooks\nWhen dispatching an action creator, you're responsible for storing a reference to the promise it returns in the event that you want to update that specific subscription. Also, you have to manually unsubscribe once your component unmounts. To get an idea of what that entails, see the [Svelte Example](../../usage/examples.mdx#svelte) or the [React Class Components Example](../../usage/examples.mdx#react-class-components)\n:::\n\n#### Example\n\n```tsx no-transpile title=\"initiate query example\"\nimport { useState } from 'react'\nimport { useAppDispatch } from './store/hooks'\nimport { api } from './services/api'\n\nfunction App() {\n  const dispatch = useAppDispatch()\n  const [postId, setPostId] = useState<number>(1)\n\n  useEffect(() => {\n    // highlight-start\n    // Add a subscription\n    const result = dispatch(api.endpoints.getPost.initiate(postId))\n\n    // Return the `unsubscribe` callback to be called in the `useEffect` cleanup step\n    return result.unsubscribe\n    // highlight-end\n  }, [dispatch, postId])\n\n  return (\n    <div>\n      <div>Initiate query example</div>\n    </div>\n  )\n}\n```\n\n```tsx no-transpile title=\"initiate mutation example\"\nimport { useState } from 'react'\nimport { useAppDispatch } from './store/hooks'\nimport { api, Post } from './services/api'\n\nfunction App() {\n  const dispatch = useAppDispatch()\n  const [newPost, setNewPost] = useState<Omit<Post, 'id'>>({ name: 'Ash' })\n\n  function handleClick() {\n    // highlight-start\n    // Trigger a mutation\n    // The `track` property can be set `false` in situations where we aren't\n    // interested in the result of the mutation\n    dispatch(api.endpoints.addPost.initiate(newPost), { track: false })\n    // highlight-end\n  }\n\n  return (\n    <div>\n      <div>Initiate mutation example</div>\n      <button onClick={handleClick}>Add post</button>\n    </div>\n  )\n}\n```\n\n## `select`\n\n#### Signature\n\n```ts no-transpile\ntype CreateCacheSelectorFactory =\n  | QueryResultSelectorFactory\n  | MutationResultSelectorFactory\n\ntype QueryResultSelectorFactory = (\n  queryArg: QueryArg | SkipToken,\n) => (state: RootState) => QueryResultSelectorResult<Definition>\n\ntype MutationResultSelectorFactory<\n  Definition extends MutationDefinition<any, any, any, any>,\n  RootState,\n> = (\n  requestId: string | SkipToken,\n) => (state: RootState) => MutationSubState<Definition> & RequestStatusFlags\n\ntype SkipToken = typeof Symbol\n```\n\n#### Description\n\nA function that accepts a cache key argument, and generates a new memoized selector for reading cached data for this endpoint using the given cache key. The generated selector is memoized using [Reselect's `createSelector`](https://redux-toolkit.js.org/api/createSelector).\n\nWhen selecting mutation results rather than queries, the function accepts a request ID instead.\n\nRTKQ defines a `Symbol` named `skipToken` internally. If `skipToken` is passed as the query argument to these selectors, the selector will return a default uninitialized state. This can be used to avoid returning a value if a given query is supposed to be disabled.\n\nReact Hooks users will most likely never need to use these directly, as the hooks automatically use these selectors as needed.\n\n:::caution\n\nEach call to `.select(someCacheKey)` returns a _new_ selector function instance. In order for memoization to work correctly, you should create a given selector function once per cache key and reuse that selector function instance, rather than creating a new selector instance each time.\n\n:::\n\n#### Example\n\n```tsx no-transpile title=\"select query example\"\nimport { useState, useMemo } from 'react'\nimport { useAppDispatch, useAppSelector } from './store/hooks'\nimport { api } from './services/api'\n\nfunction App() {\n  const dispatch = useAppDispatch()\n  const [postId, setPostId] = useState(1)\n  // highlight-start\n  // useMemo is used to only call `.select()` when required.\n  // Each call will create a new selector function instance\n  const selectPost = useMemo(\n    () => api.endpoints.getPost.select(postId),\n    [postId],\n  )\n  const { data, isLoading } = useAppSelector(selectPost)\n  // highlight-end\n\n  useEffect(() => {\n    // Add a subscription\n    const result = dispatch(api.endpoints.getPost.initiate(postId))\n\n    // Return the `unsubscribe` callback to be called in the cleanup step\n    return result.unsubscribe\n  }, [dispatch, postId])\n\n  if (isLoading) return <div>Loading post...</div>\n\n  return (\n    <div>\n      <div>Initiate query example</div>\n      <div>Post name: {data.name}</div>\n    </div>\n  )\n}\n```\n\n```tsx no-transpile title=\"select mutation example\"\nimport { useState, useMemo } from 'react'\nimport { skipToken } from '@reduxjs/toolkit/query'\nimport { useAppDispatch, useAppSelector } from './store/hooks'\nimport { api } from './services/api'\n\nfunction App() {\n  const dispatch = useAppDispatch()\n  const [newPost, setNewPost] = useState({ name: 'Ash' })\n  const [requestId, setRequestId] = useState<typeof skipToken | string>(\n    skipToken,\n  )\n  // highlight-start\n  // useMemo is used to only call `.select(..)` when required.\n  // Each call will create a new selector function instance\n  const selectMutationResult = useMemo(\n    () => api.endpoints.addPost.select(requestId),\n    [requestId],\n  )\n  const { isLoading } = useAppSelector(selectMutationResult)\n  // highlight-end\n\n  function handleClick() {\n    // Trigger a mutation\n    const result = dispatch(api.endpoints.addPost.initiate(newPost))\n    // store the requestId to select the mutation result elsewhere\n    setRequestId(result.requestId)\n  }\n\n  if (isLoading) return <div>Adding post...</div>\n\n  return (\n    <div>\n      <div>Select mutation example</div>\n      <button onClick={handleClick}>Add post</button>\n    </div>\n  )\n}\n```\n\n## Matchers\n\nA set of [Redux Toolkit action matching utilities](https://redux-toolkit.js.org/api/matching-utilities) that match the `pending`, `fulfilled`, and `rejected` actions that will be dispatched by this thunk. These allow you to match on Redux actions for that endpoint, such as in `createSlice.extraReducers` or a custom middleware. Those are implemented as follows:\n\n```ts no-transpile\n matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpoint)),\n matchFulfilled: isAllOf(isFulfilled(thunk), matchesEndpoint(endpoint)),\n matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpoint)),\n```\n"
  },
  {
    "path": "docs/rtk-query/api/created-api/hooks.mdx",
    "content": "---\nid: hooks\ntitle: 'API Slices: React Hooks'\nsidebar_label: React Hooks\nhide_title: true\n---\n\n&nbsp;\n\n# API Slices: React Hooks\n\n## Hooks Overview\n\nThe core RTK Query `createApi` method is UI-agnostic, in the same way that the Redux core library and Redux Toolkit are UI-agnostic. They are all plain JS logic that can be used anywhere. So, if you import `createApi` from `'@reduxjs/toolkit/query'`, it does not have any specific UI integrations included.\n\nHowever, RTK Query also provides the ability to auto-generate React hooks for each of your endpoints. Since this specifically depends on React itself, RTK Query provides an additional entry point that exposes a customized version of `createApi` that includes that functionality:\n\n```ts no-transpile\nimport { createApi } from '@reduxjs/toolkit/query/react'\n```\n\nIf you have used the React-specific version of `createApi`, the generated `api` slice structure will also contain a set of React hooks. The primary endpoint hooks are available as `api.endpoints[endpointName].useQuery`, `api.endpoints[endpointName].useMutation`, and `api.endpoints[endpointName].useInfiniteQuery`, matching how you defined that endpoint.\n\n### Generated Hook Names\n\nThe same hooks are also added to the `api` object itself, and given auto-generated names based on the endpoint name and query/mutation type.\n\nFor example, if you had endpoints for `getPosts` and `updatePost`, these options would be available:\n\n```ts title=\"Generated React Hook names\" no-transpile\n// Hooks attached to the endpoint definition\nconst { data } = api.endpoints.getPosts.useQuery()\nconst [updatePost, { data }] = api.endpoints.updatePost.useMutation()\n\n// Same hooks, but given unique names and attached to the API slice object\nconst { data } = api.useGetPostsQuery()\nconst [updatePost, { data }] = api.useUpdatePostMutation()\n```\n\nThe general format is `use(Endpointname)(Query|Mutation|InfiniteQuery)` - `use` is prefixed, the first letter of your endpoint name is capitalized, then `Query` or `Mutation` or `InfiniteQuery` is appended depending on the type.\n\n### Available Hooks\n\nRTK Query provides additional hooks for more advanced use-cases, although not all are generated directly on the `api` object as well.\n\nMost of the hooks are generated on a per-endpoint basis.\n\nThe full list of hooks generated in the React-specific version of `createApi` is:\n\n- Endpoint-specific, generated the `api` object with a unique name and on the endpoint object with a generic name:\n  - [`useQuery`](#usequery) (all standard queries)\n  - [`useMutation`](#usemutation) (all mutations)\n  - [`useInfiniteQuery`](#useinfinitequery) (only infinite queries)\n  - [`useLazyQuery`](#uselazyquery) (all standard queries)\n- Endpoint-specific, only generated on the endpoint object with a generic name:\n  - [`useQueryState`](#usequerystate)\n  - [`useQuerySubscription`](#usequerysubscription)\n  - [`useLazyQuerySubscription`](#uselazyquerysubscription)\n  - [`useInfiniteQueryState`](#useinfinitequerystate)\n  - [`useInfiniteQuerySubscription`](#useinfinitequerysubscription)\n- Endpoint-agnostic, generated on the `api` object:\n  - [`usePrefetch`](#useprefetch)\n\nFor the example above, the full set of generated hooks for the api would be like so:\n\n```ts title=\"Generated React Hooks\" no-transpile\n/* Hooks attached to the `getPosts` query endpoint definition */\napi.endpoints.getPosts.useQuery(arg, options)\napi.endpoints.getPosts.useQueryState(arg, options)\napi.endpoints.getPosts.useQuerySubscription(arg, options)\napi.endpoints.getPosts.useLazyQuery(options)\napi.endpoints.getPosts.useLazyQuerySubscription(options)\n\n/* hooks attached to the `getManyPosts` infinite query endpoint definition */\napi.endpoints.getManyPosts.useInfiniteQuery(arg, options)\napi.endpoints.getManyPosts.useInfiniteQueryState(arg, options)\napi.endpoints.getManyPosts.useInfiniteQuerySubscription(arg, options)\n\n/* Hooks attached to the `updatePost` mutation endpoint definition */\napi.endpoints.updatePost.useMutation(options)\n\n/* Hooks attached to the `api` object */\n// same as api.endpoints.getPosts.useQuery\napi.useGetPostsQuery(arg, options)\n// same as api.endpoints.getPosts.useLazyQuery\napi.useLazyGetPostsQuery(arg, options)\n// same as api.endpoints.updatePost.useMutation\napi.useUpdatePostMutation(arg, options)\n// same as api.endpoints.getManyPosts.useInfiniteQuery\napi.useGetManyPostsInfiniteQuery(arg, options)\n// Generic, used for any endpoint\napi.usePrefetch(endpointName, options)\n```\n\n### Feature Comparison\n\nThe provided hooks have a degree of feature overlap in order to provide options optimized for a given situation. The table below provides a comparison of the core features for each hook.\n\n<table style={{ 'overflow-y': 'hidden' }}>\n  <thead>\n    <tr style={{ height: '250px', border: 'none' }}>\n      <th style={{ width: '300px' }}>Feature</th>\n      <th style={{ 'white-space': 'nowrap', border: 'none' }}>\n        <div\n          style={{\n            transform: 'translate(0px, 51px) rotate(315deg)',\n            width: '20px',\n          }}\n        >\n          <a href=\"#usequery\">useQuery</a>\n        </div>\n      </th>\n      <th style={{ 'white-space': 'nowrap', border: 'none' }}>\n        <div\n          style={{\n            transform: 'translate(0px, 51px) rotate(315deg)',\n            width: '20px',\n          }}\n        >\n          <a href=\"#usemutation\">useMutation</a>\n        </div>\n      </th>\n      <th style={{ 'white-space': 'nowrap', border: 'none' }}>\n        <div\n          style={{\n            transform: 'translate(0px, 51px) rotate(315deg)',\n            width: '20px',\n          }}\n        >\n          <a href=\"#usequerystate\">useQueryState</a>\n        </div>\n      </th>\n      <th style={{ 'white-space': 'nowrap', border: 'none' }}>\n        <div\n          style={{\n            transform: 'translate(0px, 51px) rotate(315deg)',\n            width: '20px',\n          }}\n        >\n          <a href=\"#usequerysubscription\">useQuerySubscription</a>\n        </div>\n      </th>\n      <th style={{ 'white-space': 'nowrap', border: 'none' }}>\n        <div\n          style={{\n            transform: 'translate(0px, 51px) rotate(315deg)',\n            width: '20px',\n          }}\n        >\n          <a href=\"#uselazyquery\">useLazyQuery</a>\n        </div>\n      </th>\n      <th style={{ 'white-space': 'nowrap', border: 'none' }}>\n        <div\n          style={{\n            transform: 'translate(0px, 51px) rotate(315deg)',\n            width: '20px',\n          }}\n        >\n          <a href=\"#uselazyquerysubscription\">useLazyQuerySubscription</a>\n        </div>\n      </th>\n      <th style={{ 'white-space': 'nowrap', border: 'none' }}>\n        <div\n          style={{\n            transform: 'translate(0px, 51px) rotate(315deg)',\n            width: '20px',\n          }}\n        >\n          <a href=\"#useprefetch\">usePrefetch</a>\n        </div>\n      </th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td style={{ width: '330px' }}>Automatically triggers query requests</td>\n      <td>✔️</td>\n      <td></td>\n      <td></td>\n      <td>✔️</td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <td style={{ width: '330px' }}>\n        Allows manually triggering query requests\n      </td>\n      <td>✔️</td>\n      <td></td>\n      <td></td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td>✔️</td>\n    </tr>\n    <tr>\n      <td style={{ width: '330px' }}>\n        Allows manually triggering mutation requests\n      </td>\n      <td></td>\n      <td>✔️</td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <td style={{ width: '330px' }}>\n        Subscribes a component to keep cached data in the store\n      </td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td></td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td></td>\n    </tr>\n    <tr>\n      <td style={{ width: '330px' }}>\n        Returns request status and cached data from the store\n      </td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td></td>\n      <td>✔️</td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <td style={{ width: '330px' }}>\n        Re-renders as request status and data become available\n      </td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td></td>\n      <td>✔️</td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <td style={{ width: '330px' }}>\n        Accepts polling/re-fetching options to trigger automatic re-fetches\n      </td>\n      <td>✔️</td>\n      <td></td>\n      <td></td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td></td>\n    </tr>\n  </tbody>\n</table>\n\n## Primary Hooks\n\nThese hooks are the main methods you will use to interact with RTK Query in your React components. They encapsulate all of logic and options needed for most data fetching and update use cases.\n\n### `useQuery`\n\n```ts title=\"Accessing a useQuery hook\" no-transpile\nconst useQueryResult = api.endpoints.getPosts.useQuery(arg, options)\n// or\nconst useQueryResult = api.useGetPostsQuery(arg, options)\n```\n\n[summary](docblock://query/react/buildHooks.ts?token=UseQuery)\n\n#### `useQuery` Signature\n\n```ts no-transpile\ntype UseQuery = (\n  arg: any | SkipToken,\n  options?: UseQueryOptions,\n) => UseQueryResult\n\ntype UseQueryOptions = {\n  pollingInterval?: number\n  skipPollingIfUnfocused?: boolean\n  refetchOnReconnect?: boolean\n  refetchOnFocus?: boolean\n  skip?: boolean\n  refetchOnMountOrArgChange?: boolean | number\n  selectFromResult?: (result: UseQueryStateDefaultResult) => any\n}\n\ntype UseQueryResult<T> = {\n  // Base query state\n\n  // Arguments passed to the query\n  originalArgs?: unknown\n  // The latest returned result regardless of hook arg, if present\n  data?: T\n  // The latest returned result for the current hook arg, if present\n  currentData?: T\n  // Error result if present\n  error?: unknown\n  // A string generated by RTK Query\n  requestId?: string\n  // The name of the given endpoint for the query\n  endpointName?: string\n  // Timestamp for when the query was initiated\n  startedTimeStamp?: number\n  // Timestamp for when the query was completed\n  fulfilledTimeStamp?: number\n\n  // Derived request status booleans\n\n  // Query has not started yet.\n  isUninitialized: boolean\n  // Query is currently loading for the first time. No data yet.\n  isLoading: boolean\n  // Query is currently fetching, but might have data from an earlier request.\n  isFetching: boolean\n  // Query has data from a successful load.\n  isSuccess: boolean\n  // Query is currently in an \"error\" state.\n  isError: boolean\n\n  // A function to force refetch the query - returns a Promise with additional methods\n  refetch: () => QueryActionCreatorResult\n}\n```\n\n- **Parameters**\n  - `arg`: The query argument to be used in constructing the query itself, and as a cache key for the query.\n    You can also pass in `skipToken` here as an alternative way of skipping the query, see [skipToken](#skiptoken)\n  - `options`: A set of options that control the fetching behavior of the hook\n- **Returns**\n  - A query result object containing the current loading state, the actual data or error returned from the API call, metadata about the request, and a function to `refetch` the data. Can be customized with `selectFromResult`\n\n#### `skipToken`\n\n[summary](docblock://query/core/buildSelectors.ts?token=skipToken)\n\nSee also [Skipping queries with TypeScript using `skipToken`](../../usage-with-typescript.mdx#skipping-queries-with-typescript-using-skiptoken)\n\n### `useMutation`\n\n```ts title=\"Accessing a useMutation hook\" no-transpile\nconst useMutationResult = api.endpoints.updatePost.useMutation(options)\n// or\nconst useMutationResult = api.useUpdatePostMutation(options)\n```\n\n[summary](docblock://query/react/buildHooks.ts?token=UseMutation)\n\n#### `useMutation` Signature\n\n```ts no-transpile\ntype UseMutation = (\n  options?: UseMutationStateOptions,\n) => [UseMutationTrigger, UseMutationResult | SelectedUseMutationResult]\n\ntype UseMutationStateOptions = {\n  // A method to determine the contents of `UseMutationResult`\n  selectFromResult?: (result: UseMutationStateDefaultResult) => any\n  // A string used to enable shared results across hook instances which have the same key\n  fixedCacheKey?: string\n}\n\ntype UseMutationTrigger<T> = (arg: any) => Promise<\n  { data: T } | { error: BaseQueryError | SerializedError }\n> & {\n  requestId: string // A string generated by RTK Query\n  abort: () => void // A method to cancel the mutation promise\n  unwrap: () => Promise<T> // A method to unwrap the mutation call and provide the raw response/error\n  reset: () => void // A method to manually unsubscribe from the mutation call and reset the result to the uninitialized state\n}\n\ntype UseMutationResult<T> = {\n  // Base query state\n\n  // Arguments passed to the latest mutation call. Not available if using the `fixedCacheKey` option\n  originalArgs?: unknown\n  // Returned result if present\n  data?: T\n  // Error result if present\n  error?: unknown\n  // The name of the given endpoint for the mutation\n  endpointName?: string\n  // Timestamp for when the mutation was completed\n  fulfilledTimeStamp?: number\n\n  // Derived request status booleans\n\n  // Mutation has not been fired yet\n  isUninitialized: boolean\n  // Mutation has been fired and is awaiting a response\n  isLoading: boolean\n  // Mutation has data from a successful call\n  isSuccess: boolean\n  // Mutation is currently in an \"error\" state\n  isError: boolean\n  // Timestamp for when the latest mutation was initiated\n  startedTimeStamp?: number\n\n  // A method to manually unsubscribe from the mutation call and reset the result to the uninitialized state\n  reset: () => void\n}\n```\n\n:::tip\n\nThe generated `UseMutation` hook will cause a component to re-render by default after the trigger callback is fired, as it affects the properties of the result. If you want to call the trigger but don't care about subscribing to the result with the hook, you can use the `selectFromResult` option to limit the properties that the hook cares about.\n\nReturning a completely empty object will mean that any individual mutation call will cause only one re-render at most, e.g.\n\n```ts no-transpile\nselectFromResult: () => ({})\n```\n\n:::\n\n- **Parameters**\n\n  - `options`: A set of options that control the subscription behavior of the hook:\n    - `selectFromResult`: A callback that can be used to customize the mutation result returned as the second item in the tuple\n    - `fixedCacheKey`: An optional string used to enable shared results across hook instances\n\n- **Returns**: A tuple containing:\n  - `trigger`: A function that triggers an update to the data based on the provided argument. The trigger function returns a promise with the properties shown above that may be used to handle the behavior of the promise\n  - `mutationState`: A query status object containing the current loading state and metadata about the request, or the values returned by the `selectFromResult` option where applicable.\n    Additionally, this object will contain\n    - a `reset` method to reset the hook back to its original state and remove the current result from the cache\n    - an `originalArgs` property that contains the argument passed to the last call of the `trigger` function.\n\n### `useInfiniteQuery`\n\n```ts title=\"Accessing a useQuery hook\" no-transpile\nconst useQueryResult = api.endpoints.getManyPosts.useInfiniteQuery(arg, options)\n// or\nconst useQueryResult = api.useGetManyPostsInfiniteQuery(arg, options)\n```\n\n[summary](docblock://query/react/buildHooks.ts?token=UseInfiniteQuery)\n\n#### `useInfiniteQuery` Signature\n\n```ts no-transpile\ntype UseInfiniteQuery = (\n  arg: any | SkipToken,\n  options?: UseQueryOptions,\n) => UseInfiniteQueryResult\n\ntype InfiniteData<Data, PageParam> = {\n  pages: Array<Data>\n  pageParams: Array<PageParam>\n}\n\ntype UseInfiniteQueryOptions = {\n  pollingInterval?: number\n  skipPollingIfUnfocused?: boolean\n  refetchOnReconnect?: boolean\n  refetchOnFocus?: boolean\n  skip?: boolean\n  refetchOnMountOrArgChange?: boolean | number\n  selectFromResult?: (result: UseQueryStateDefaultResult) => any\n  initialPageParam?: PageParam\n  refetchCachedPages?: boolean\n}\n\ntype UseInfiniteQueryResult<Data, PageParam> = {\n  // Base query state\n\n  // Arguments passed to the query\n  originalArgs?: unknown\n  // The latest returned result regardless of hook arg, if present\n  data?: InfiniteData<Data, PageParam>\n  // The latest returned result for the current hook arg, if present\n  currentData?: InfiniteData<Data, PageParam>\n  // Error result if present\n  error?: unknown\n  // A string generated by RTK Query\n  requestId?: string\n  // The name of the given endpoint for the query\n  endpointName?: string\n  // Timestamp for when the query was initiated\n  startedTimeStamp?: number\n  // Timestamp for when the query was completed\n  fulfilledTimeStamp?: number\n\n  // Derived request status booleans\n\n  // Query has not started yet.\n  isUninitialized: boolean\n  // Query is currently loading for the first time. No data yet.\n  isLoading: boolean\n  // Query is currently fetching, but might have data from an earlier request.\n  isFetching: boolean\n  // Query has data from a successful load.\n  isSuccess: boolean\n  // Query is currently in an \"error\" state.\n  isError: boolean\n\n  // Derived request status booleans for infinite query pages\n\n  // There is another page available querying forwards\n  hasNextPage: boolean\n  // There is another page available querying backwards\n  hasPreviousPage: boolean\n  // The current in-progress fetch is for the next page\n  isFetchingNextPage: boolean\n  // The current in-progress fetch is for the previous page\n  isFetchingPreviousPage: boolean\n  // The current error occurred fetching the next page\n  isFetchNextPageError: boolean\n  // The current error occurred fetching the previous page\n  isFetchPreviousPageError: boolean\n\n  // A function to force refetch the query - returns a Promise with additional methods\n  refetch: (options?: {\n    refetchCachedPages?: boolean\n  }) => InfiniteQueryActionCreatorResult\n\n  // Triggers a fetch for the next page, based on the current cache\n  fetchNextPage: () => InfiniteQueryActionCreatorResult\n  // Triggers a fetch for the previous page, based on the current cache\n  fetchPreviousPage: () => InfiniteQueryActionCreatorResult\n}\n```\n\n- **Parameters**\n  - `arg`: The query argument to be used in constructing the query itself, and as a cache key for the query.\n    You can also pass in `skipToken` here as an alternative way of skipping the query, see [skipToken](#skiptoken)\n  - `options`: A set of options that control the fetching behavior of the hook\n- **Returns**\n  - A query result object containing the current loading state, the actual data or error returned from the API call, metadata about the request, and a function to `refetch` the data. Can be customized with `selectFromResult`\n\n## Secondary Hooks\n\nThese hooks are useful for specific additional use cases in your application, but will probably not be used that frequently.\n\n### `useLazyQuery`\n\n```ts title=\"Accessing a useLazyQuery hook\" no-transpile\nconst [trigger, result, lastPromiseInfo] =\n  api.endpoints.getPosts.useLazyQuery(options)\n// or\nconst [trigger, result, lastPromiseInfo] = api.useLazyGetPostsQuery(options)\n```\n\n[summary](docblock://query/react/buildHooks.ts?token=UseLazyQuery)\n\n#### `useLazyQuery` Signature\n\n```ts no-transpile\ntype UseLazyQuery = (\n  options?: UseLazyQueryOptions\n) => [UseLazyQueryTrigger, UseLazyQueryStateResult, UseLazyQueryLastPromiseInfo]\n\ntype UseLazyQueryOptions = {\n  pollingInterval?: number\n  skipPollingIfUnfocused?: boolean\n  refetchOnReconnect?: boolean\n  refetchOnFocus?: boolean\n  selectFromResult?: (result: UseQueryStateDefaultResult) => any\n}\n\ntype UseLazyQueryTrigger<T> = (arg: any, preferCacheValue?: boolean) => Promise<\n  QueryResultSelectorResult\n> & {\n  // Whatever argument was provided to the query\n  arg: unknown\n  // A string generated by RTK Query\n  requestId: string\n  // The values used for the query subscription\n  subscriptionOptions: SubscriptionOptions\n\n   // A method to cancel the query promise\n  abort: () => void\n  // A method to unwrap the query call and provide the raw response/error\n  unwrap: () => Promise<T>\n  // A method used to manually unsubscribe from the query results\n  unsubscribe: () => void\n  // A method used to re-run the query. In most cases when using a lazy query, you will never use this and should prefer to call the trigger again.\n  refetch: () => void\n  // A method used to update the subscription options (eg. pollingInterval)\n  updateSubscriptionOptions: (options: SubscriptionOptions) () => void\n}\n\ntype UseLazyQueryStateResult<T> = {\n  // Base query state\n\n  // Arguments passed to the query\n  originalArgs?: unknown\n  // The latest returned result regardless of hook arg, if present\n  data?: T\n  // The latest returned result for the current hook arg, if present\n  currentData?: T\n  // Error result if present\n  error?: unknown\n  // A string generated by RTK Query\n  requestId?: string\n  // The name of the given endpoint for the query\n  endpointName?: string\n  // Timestamp for when the query was initiated\n  startedTimeStamp?: number\n  // Timestamp for when the query was completed\n  fulfilledTimeStamp?: number\n\n  // Derived request status booleans\n\n  // Query has not started yet.\n  isUninitialized: boolean\n  // Query is currently loading for the first time. No data yet.\n  isLoading: boolean\n  // Query is currently fetching, but might have data from an earlier request.\n  isFetching: boolean\n  // Query has data from a successful load.\n  isSuccess: boolean\n  // Query is currently in an \"error\" state.\n  isError: boolean\n}\n\ntype UseLazyQueryLastPromiseInfo = {\n  lastArg: any\n}\n```\n\n- **Parameters**\n\n  - `options`: A set of options that control the fetching behavior and returned result value of the hook. Options affecting fetching behavior will only have an effect after the lazy query has been triggered at least once.\n\n- **Returns**: A tuple containing:\n  - `trigger`: A function that fetches the corresponding data for the endpoint when called\n  - `result`: A query result object containing the current loading state, the actual data or error returned from the API call and metadata about the request. Can be customized with `selectFromResult`\n  - `lastPromiseInfo`: An object containing the last argument used to call the trigger function\n\n### `usePrefetch`\n\n```ts title=\"Accessing a usePrefetch hook\" no-transpile\nconst prefetchCallback = api.usePrefetch(endpointName, options)\n```\n\nA React hook which can be used to initiate fetching data ahead of time.\n\n##### Features\n\n- Manual control over firing a request to retrieve data\n\n##### Signature\n\n```ts no-transpile\ntype UsePrefetch = (\n  endpointName: string,\n  options?: UsePrefetchOptions,\n) => PrefetchCallback\n\ntype UsePrefetchOptions =\n  | {\n      // If specified, only runs the query if the difference between `new Date()` and the last\n      // `fulfilledTimeStamp` is greater than the given value (in seconds)\n      ifOlderThan?: false | number\n    }\n  | {\n      // If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query\n      // will be run even if it exists in the cache.\n      force?: boolean\n    }\n\ntype PrefetchCallback = (arg: any, options?: UsePrefetchOptions) => void\n```\n\n- **Parameters**\n\n  - `endpointName`: The name of the endpoint to prefetch data for\n  - `options`: A set of options that control whether the prefetch request should occur\n\n- **Returns**\n  - A `prefetch` callback that when called, will initiate fetching the data for the provided endpoint\n\n## Implementation Hooks\n\nThis hooks exist as implementation details of the primary hooks. They may be useful in rare cases, but you should generally use the primary hooks in your apps.\n\n### `useQueryState`\n\n```ts title=\"Accessing a useQuery hook\" no-transpile\nconst useQueryStateResult = api.endpoints.getPosts.useQueryState(arg, options)\n```\n\n[summary](docblock://query/react/buildHooks.ts?token=UseQueryState)\n\n##### `useQueryState` Signature\n\n```ts no-transpile\ntype UseQueryState = (\n  arg: any | SkipToken,\n  options?: UseQueryStateOptions,\n) => UseQueryStateResult | SelectedQueryStateResult\n\ntype UseQueryStateOptions = {\n  skip?: boolean\n  selectFromResult?: (result: UseQueryStateDefaultResult) => any\n}\n\ntype UseQueryStateResult<T> = {\n  // Base query state\n\n  // Arguments passed to the query\n  originalArgs?: unknown\n  // The latest returned result regardless of hook arg, if present\n  data?: T\n  // The latest returned result for the current hook arg, if present\n  currentData?: T\n  // Error result if present\n  error?: unknown\n  // A string generated by RTK Query\n  requestId?: string\n  // The name of the given endpoint for the query\n  endpointName?: string\n  // Timestamp for when the query was initiated\n  startedTimeStamp?: number\n  // Timestamp for when the query was completed\n  fulfilledTimeStamp?: number\n\n  // Derived request status booleans\n\n  // Query has not started yet.\n  isUninitialized: boolean\n  // Query is currently loading for the first time. No data yet.\n  isLoading: boolean\n  // Query is currently fetching, but might have data from an earlier request.\n  isFetching: boolean\n  // Query has data from a successful load.\n  isSuccess: boolean\n  // Query is currently in an \"error\" state.\n  isError: boolean\n}\n```\n\n- **Parameters**\n\n  - `arg`: The argument passed to the query defined in the endpoint.\n    You can also pass in `skipToken` here as an alternative way of skipping the selection, see [skipToken](#skiptoken)\n  - `options`: A set of options that control the return value for the hook\n\n- **Returns**\n  - A query result object containing the current loading state, the actual data or error returned from the API call and metadata about the request. Can be customized with `selectFromResult`\n\n### `useQuerySubscription`\n\n```ts title=\"Accessing a useQuerySubscription hook\" no-transpile\nconst { refetch } = api.endpoints.getPosts.useQuerySubscription(arg, options)\n```\n\n[summary](docblock://query/react/buildHooks.ts?token=UseQuerySubscription)\n\n##### `useQuerySubscription` Signature\n\n```ts no-transpile\ntype UseQuerySubscription = (\n  arg: any | SkipToken,\n  options?: UseQuerySubscriptionOptions,\n) => UseQuerySubscriptionResult\n\ntype UseQuerySubscriptionOptions = {\n  skip?: boolean\n  refetchOnMountOrArgChange?: boolean | number\n  pollingInterval?: number\n  skipPollingIfUnfocused?: boolean\n  refetchOnReconnect?: boolean\n  refetchOnFocus?: boolean\n}\n\ntype UseQuerySubscriptionResult = {\n  refetch: () => void // A function to force refetch the query\n}\n```\n\n- **Parameters**\n\n  - `arg`: The argument passed to the query defined in the endpoint.\n    You can also pass in `skipToken` here as an alternative way of skipping the query, see [skipToken](#skiptoken)\n  - `options`: A set of options that control the fetching behavior of the hook\n\n- **Returns**\n  - An object containing a function to `refetch` the data\n\n### `useInfiniteQueryState`\n\n```ts title=\"Accessing a useInfiniteQueryState hook\" no-transpile\nconst useInfiniteQueryStateResult =\n  api.endpoints.getManyPosts.useInfiniteQueryState(arg, options)\n```\n\n[summary](docblock://query/react/buildHooks.ts?token=UseInfiniteQueryState)\n\n### `useInfiniteQuerySubscription`\n\n```ts title=\"Accessing a useInfiniteQuerySubscription hook\" no-transpile\nconst useInfiniteQuerySubscriptionResult =\n  api.endpoints.getManyPosts.useInfiniteQuerySubscription(arg, options)\n```\n\n[summary](docblock://query/react/buildHooks.ts?token=UseInfiniteQuerySubscription)\n\n### `useLazyQuerySubscription`\n\n```ts title=\"Accessing a useLazyQuerySubscription hook\" no-transpile\nconst [trigger, lastArg] =\n  api.endpoints.getPosts.useLazyQuerySubscription(options)\n```\n\n[summary](docblock://query/react/buildHooks.ts?token=UseLazyQuerySubscription)\n\n##### `useLazyQuerySubscription` Signature\n\n```ts no-transpile\ntype UseLazyQuerySubscription = (\n  options?: UseLazyQuerySubscriptionOptions,\n) => [UseLazyQuerySubscriptionTrigger, LastArg]\n\ntype UseLazyQuerySubscriptionOptions = {\n  pollingInterval?: number\n  skipPollingIfUnfocused?: boolean\n  refetchOnReconnect?: boolean\n  refetchOnFocus?: boolean\n}\n\ntype UseLazyQuerySubscriptionTrigger = (\n  arg: any,\n  preferCacheValue?: boolean,\n) => void\n```\n\n- **Parameters**\n\n  - `options`: A set of options that control the fetching behavior of the hook. The options will only have an effect after the lazy query has been triggered at least once.\n\n- **Returns**: A tuple containing:\n  - `trigger`: A function that fetches the corresponding data for the endpoint when called\n  - `lastArg`: The last argument used to call the trigger function\n"
  },
  {
    "path": "docs/rtk-query/api/created-api/overview.mdx",
    "content": "---\nid: overview\ntitle: Overview\nsidebar_label: API Slice Overview\nhide_title: true\n---\n\n&nbsp;\n\n# Generated API Slices\n\n## API Slice Overview\n\nWhen you call [`createApi`](../createApi.mdx), it automatically generates and returns an API service \"slice\" object structure containing Redux logic you can use to interact with the endpoints you defined. This slice object includes a reducer to manage cached data, a middleware to manage cache lifetimes and subscriptions, and selectors and thunks for each endpoint. If you imported `createApi` from the React-specific entry point, it also includes auto-generated React hooks for use in your components.\n\nThis section documents the contents of that API structure, with the different fields grouped by category. The API types and descriptions are listed on separate pages for each category.\n\n:::tip\n\nTypically, you should only have one API slice per base URL that your application needs to communicate with. For example, if your site fetches data from both `/api/posts` and `/api/users`, you would have a single API slice with `/api/` as the base URL, and separate endpoint definitions for `posts` and `users`. This allows you to effectively take advantage of [automated re-fetching](../../usage/automated-refetching.mdx) by defining [tag](../../usage/automated-refetching.mdx#tags) relationships across endpoints.\n\nThis is because:\n\n- Automatic tag invalidation only works within a single API slice. If you have multiple API slices, the automatic invalidation won't work across them.\n- Every `createApi` call generates its own middleware, and each middleware added to the store will run checks against every dispatched action. That has a perf cost that adds up. So, if you called `createApi` 10 times and added 10 separate API middleware to the store, that will be noticeably slower perf-wise.\n\nFor maintainability purposes, you may wish to split up endpoint definitions across multiple files, while still maintaining a single API slice which includes all of these endpoints. See [code splitting](../../usage/code-splitting.mdx) for how you can use the `injectEndpoints` property to inject API endpoints from other files into a single API slice definition.\n\n:::\n\n```ts title=\"API Slice Contents\" no-transpile\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    // ...\n  }),\n})\n\ntype Api = {\n  // Redux integration\n  reducerPath: string\n  reducer: Reducer\n  middleware: Middleware\n\n  // Endpoint interactions\n  endpoints: Record<string, EndpointDefinition>\n\n  // Code splitting and generation\n  injectEndpoints: (options: InjectEndpointsOptions) => UpdatedApi\n  enhanceEndpoints: (options: EnhanceEndpointsOptions) => UpdatedApi\n\n  // Utilities\n  utils: {\n    updateQueryData: UpdateQueryDataThunk\n    patchQueryData: PatchQueryDataThunk\n    prefetch: PrefetchThunk\n    invalidateTags: ActionCreatorWithPayload<\n      Array<TagTypes | FullTagDescription<TagTypes>>,\n      string\n    >\n    selectInvalidatedBy: (\n      state: FullState,\n      tags: Array<TagTypes | FullTagDescription<TagTypes>>,\n    ) => Array<{\n      endpointName: string\n      originalArgs: any\n      queryCacheKey: string\n    }>\n    selectCachedArgsForQuery: (\n      state: FullState,\n      endpointName: EndpointName,\n    ) => Array<QueryArg>\n    resetApiState: ActionCreator<ResetAction>\n    getRunningQueryThunk(\n      endpointName: EndpointName,\n      args: QueryArg,\n    ): ThunkWithReturnValue<QueryActionCreatorResult | undefined>\n    getRunningMutationThunk(\n      endpointName: EndpointName,\n      fixedCacheKeyOrRequestId: string,\n    ): ThunkWithReturnValue<MutationActionCreatorResult | undefined>\n    getRunningQueriesThunk(): ThunkWithReturnValue<\n      Array<QueryActionCreatorResult<any>>\n    >\n    getRunningMutationsThunk(): ThunkWithReturnValue<\n      Array<MutationActionCreatorResult<any>>\n    >\n  }\n\n  // Internal actions\n  internalActions: InternalActions\n\n  // React hooks (if applicable)\n  [key in GeneratedReactHooks]: GeneratedReactHooks[key]\n}\n```\n\n## Redux Integration\n\nInternally, `createApi` will call [the Redux Toolkit `createSlice` API](https://redux-toolkit.js.org/api/createSlice) to generate a slice reducer and corresponding action creators with the appropriate logic for caching fetched data. It also automatically generates a custom Redux middleware that manages subscription counts and cache lifetimes.\n\nThe generated slice reducer and the middleware both need to be adding to your Redux store setup in `configureStore` in order to work correctly.\n\n:::info API Reference\n\n- [API Slices: Redux Integration](./redux-integration.mdx)\n\n:::\n\n## Endpoints\n\nThe API slice object will have an `endpoints` field inside. This section maps the endpoint names you provided to `createApi` to the core Redux logic (thunks and selectors) used to trigger data fetches and read cached data for that endpoint. If you're using the React-specific version of `createApi`, each endpoint definition will also contain the auto-generated React hooks for that endpoint.\n\n:::info API Reference\n\n- [API Slices: Endpoints](./endpoints.mdx)\n\n:::\n\n## Code Splitting and Generation\n\nEach API slice allows [additional endpoint definitions to be injected at runtime](../../usage/code-splitting.mdx) after the initial API slice has been defined. This can be beneficial for apps that may have _many_ endpoints.\n\nThe individual API slice endpoint definitions can also be split across multiple files. This is primarily useful for working with API slices that were [code-generated from an API schema file](../../usage/code-generation.mdx), allowing you to add additional custom behavior and configuration to a set of automatically-generated endpoint definitions.\n\nEach API slice object has `injectEndpoints` and `enhanceEndpoints` functions to support these use cases.\n\n:::info API Reference\n\n- [API Slices: Code Splitting and Generation](./code-splitting.mdx)\n\n:::\n\n## API Slice Utilities\n\nThe `util` field includes various utility functions that can be used to manage the cache, including\nmanually updating query cache data, triggering pre-fetching of data, manually invalidating tags,\nand manually resetting the api state, as well as other utility functions that can be used in\nvarious scenarios, including SSR.\n\n:::info API Reference\n\n- [API Slices: Utilities](./api-slice-utils.mdx)\n\n:::\n\n## Internal Actions\n\nThe `internalActions` field contains a set of additional thunks that are used for internal behavior, such as managing updates based on focus.\n\n## React Hooks\n\nThe core RTK Query `createApi` method is UI-agnostic, in the same way that the Redux core library and Redux Toolkit are UI-agnostic. They are all plain JS logic that can be used anywhere.\n\nHowever, RTK Query also provides the ability to auto-generate React hooks for each of your endpoints. Since this specifically depends on React itself, RTK Query provides an alternate entry point that exposes a customized version of `createApi` that includes that functionality:\n\n```js\nimport { createApi } from '@reduxjs/toolkit/query/react'\n```\n\nIf you have used the React-specific version of `createApi`, the generated `Api` slice structure will also contain a set of React hooks. These endpoint hooks are available as `api.endpoints[endpointName].useQuery` or `api.endpoints[endpointName].useMutation`, matching how you defined that endpoint.\n\nThe same hooks are also added to the `Api` object itself, and given auto-generated names based on the endpoint name and query/mutation type.\n\nFor example, if you had endpoints for `getPosts` and `updatePost`, these options would be available:\n\n```ts title=\"Generated React Hook names\" no-transpile\n// Hooks attached to the endpoint definition\nconst { data } = api.endpoints.getPosts.useQuery()\nconst { data } = api.endpoints.updatePost.useMutation()\n\n// Same hooks, but given unique names and attached to the API slice object\nconst { data } = api.useGetPostsQuery()\nconst [updatePost] = api.useUpdatePostMutation()\n```\n\nThe React-specific version of `createApi` also generates a `usePrefetch` hook, attached to the `Api` object, which can be used to initiate fetching data ahead of time.\n\n:::info API Reference\n\n- [API Slices: React Hooks](./hooks.mdx)\n\n:::\n"
  },
  {
    "path": "docs/rtk-query/api/created-api/redux-integration.mdx",
    "content": "---\nid: redux-integration\ntitle: 'API Slices: Redux Integration'\nsidebar_label: Redux Integration\nhide_title: true\n---\n\n&nbsp;\n\n# API Slices: Redux Integration\n\nInternally, `createApi` will call [the Redux Toolkit `createSlice` API](https://redux-toolkit.js.org/api/createSlice) to generate a slice reducer and corresponding action creators with the appropriate logic for caching fetched data. It also automatically generates a custom Redux middleware that manages subscription counts and cache lifetimes.\n\nThe generated slice reducer and the middleware both need to be added to your Redux store setup in `configureStore` in order to work correctly:\n\n```ts title=\"src/store.ts\"\n// file: src/services/pokemon.ts noEmit\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\nexport const pokemonApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: () => ({}),\n})\n\n// file: src/store.ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport { setupListeners } from '@reduxjs/toolkit/query'\nimport { pokemonApi } from './services/pokemon'\n\nexport const store = configureStore({\n  reducer: {\n    // Add the generated reducer as a specific top-level slice\n    [pokemonApi.reducerPath]: pokemonApi.reducer,\n  },\n  // Adding the api middleware enables caching, invalidation, polling,\n  // and other useful features of `rtk-query`.\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(pokemonApi.middleware),\n})\n\n// configure listeners using the provided defaults\nsetupListeners(store.dispatch)\n```\n\n## `reducerPath`\n\n```ts no-transpile\nreducerPath: string\n```\n\nContains the `reducerPath` option provided to `createApi`. Use this as the root state key when adding the `reducer` function to the store so that the rest of the generated API logic can find the state correctly.\n\n## `reducer`\n\n```ts no-transpile\nreducer: Reducer\n```\n\nA standard Redux slice reducer function containing the logic for updating the cached data. Add this to the Redux store using the `reducerPath` you provided as the root state key.\n\n## `middleware`\n\n```ts no-transpile\nmiddleware: Middleware\n```\n\nA custom Redux middleware that contains logic for managing caching, invalidation, subscriptions, polling, and more. Add this to the store setup after other middleware.\n"
  },
  {
    "path": "docs/rtk-query/api/fetchBaseQuery.mdx",
    "content": "---\nid: fetchBaseQuery\ntitle: fetchBaseQuery\nsidebar_label: fetchBaseQuery\nhide_title: true\nhide_table_of_contents: false\ndescription: 'RTK Query > API: fetchBaseQuery reference'\n---\n\n&nbsp;\n\n# `fetchBaseQuery`\n\nThis is a very small wrapper around [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) that aims to simplify HTTP requests. It is not a full-blown replacement for `axios`, `superagent`, or any other more heavyweight library, but it will cover the vast majority of your HTTP request needs.\n\n`fetchBaseQuery` is a factory function that generates a data fetching method compatible with RTK Query's `baseQuery` configuration option. It takes all standard options from fetch's [`RequestInit`](https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/fetch) interface, as well as `baseUrl`, a `prepareHeaders` function, an optional `fetch` function, a `paramsSerializer` function, and a `timeout`.\n\n## Basic Usage\n\nTo use it, import it when you are [creating an API service definition](../../tutorials/rtk-query#create-an-api-service), call it as `fetchBaseQuery(options)`, and pass the result as the `baseQuery` field in `createApi`:\n\n```ts title=\"src/services/pokemon.ts\"\n// Or from '@reduxjs/toolkit/query/react'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\nexport const pokemonApi = createApi({\n  // Set the baseUrl for every endpoint below\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (build) => ({\n    getPokemonByName: build.query({\n      // Will make a request like https://pokeapi.co/api/v2/pokemon/bulbasaur\n      query: (name: string) => `pokemon/${name}`,\n    }),\n    updatePokemon: build.mutation({\n      query: ({ name, patch }) => ({\n        url: `pokemon/${name}`,\n        // When performing a mutation, you typically use a method of\n        // PATCH/PUT/POST/DELETE for REST endpoints\n        method: 'PATCH',\n        // fetchBaseQuery automatically adds `content-type: application/json` to\n        // the Headers and calls `JSON.stringify(patch)`\n        body: patch,\n      }),\n    }),\n  }),\n})\n```\n\n## Signature\n\n```ts title=\"fetchBaseQuery signature\" no-transpile\ntype FetchBaseQuery = (\n  args: FetchBaseQueryArgs,\n) => (\n  args: string | FetchArgs,\n  api: BaseQueryApi,\n  extraOptions: ExtraOptions,\n) => FetchBaseQueryResult\n\ntype FetchBaseQueryArgs = {\n  baseUrl?: string\n  prepareHeaders?: (\n    headers: Headers,\n    api: Pick<\n      BaseQueryApi,\n      'getState' | 'extra' | 'endpoint' | 'type' | 'forced'\n    > & { arg: string | FetchArgs },\n  ) => MaybePromise<Headers | void>\n  fetchFn?: (\n    input: RequestInfo,\n    init?: RequestInit | undefined,\n  ) => Promise<Response>\n  paramsSerializer?: (params: Record<string, any>) => string\n  isJsonContentType?: (headers: Headers) => boolean\n  jsonContentType?: string\n  timeout?: number\n} & RequestInit\n\ntype FetchBaseQueryResult = Promise<\n  | {\n      data: any\n      error?: undefined\n      meta?: { request: Request; response: Response }\n    }\n  | {\n      error: FetchBaseQueryError\n      data?: undefined\n      meta?: { request: Request; response: Response }\n    }\n>\n\ntype FetchBaseQueryError =\n  | {\n      /**\n       * * `number`:\n       *   HTTP status code\n       */\n      status: number\n      data: unknown\n    }\n  | {\n      /**\n       * * `\"FETCH_ERROR\"`:\n       *   An error that occurred during execution of `fetch` or the `fetchFn` callback option\n       **/\n      status: 'FETCH_ERROR'\n      data?: undefined\n      error: string\n    }\n  | {\n      /**\n       * * `\"PARSING_ERROR\"`:\n       *   An error happened during parsing.\n       *   Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\n       *   or an error occurred while executing a custom `responseHandler`.\n       **/\n      status: 'PARSING_ERROR'\n      originalStatus: number\n      data: string\n      error: string\n    }\n  | {\n      /**\n       * * `\"TIMEOUT_ERROR\"`:\n       *   Request timed out\n       **/\n      status: 'TIMEOUT_ERROR'\n      data?: undefined\n      error: string\n    }\n  | {\n      /**\n       * * `\"CUSTOM_ERROR\"`:\n       *   A custom error type that you can return from your `queryFn` where another error might not make sense.\n       **/\n      status: 'CUSTOM_ERROR'\n      data?: unknown\n      error: string\n    }\n```\n\n## Parameters\n\n### `baseUrl`\n\n_(required)_\n\nTypically a string like `https://api.your-really-great-app.com/v1/`. If you don't provide a `baseUrl`, it defaults to a relative path from where the request is being made. **You should most likely _always_ specify this**.\n\n### `prepareHeaders`\n\n_(optional)_\n\nAllows you to inject headers on every request. You can specify headers at the endpoint level, but you'll typically want to set common headers like `authorization` here. As a convenience mechanism, the second argument allows you to use `getState` to access your redux store in the event you store information you'll need there such as an auth token. Additionally, it provides access to `arg`, `extra`, `endpoint`, `type`, and `forced` to unlock more granular conditional behaviors.\n\nYou can mutate the `headers` argument directly, and returning it is optional.\n\n```ts title=\"prepareHeaders signature\" no-transpile\ntype prepareHeaders = (\n  headers: Headers,\n  api: {\n    getState: () => unknown\n    arg: string | FetchArgs\n    extra: unknown\n    endpoint: string\n    type: 'query' | 'mutation'\n    forced: boolean | undefined\n  },\n) => Headers | void\n```\n\n### `paramsSerializer`\n\n_(optional)_\n\nA function that can be used to apply custom transformations to the data passed into [`params`](#setting-the-query-string). If you don't provide this, `params` will be stripped of keys with `undefined` values, and then passed to `new URLSearchParams()`. With some API integrations, you may need to leverage this to use something like the [`query-string`](https://github.com/sindresorhus/query-string) library to support different array types.\n\n### `fetchFn`\n\n_(optional)_\n\nA fetch function that overrides the default on the window. Can be useful in SSR environments where you may need to leverage `isomorphic-fetch` or `cross-fetch`.\n\n### `timeout`\n\n_(optional)_\n\nA number in milliseconds that represents the maximum time a request can take before timing out.\n\n### `isJsonContentType`\n\n_(optional)_\n\nA callback that receives a `Headers` object and determines the `body` field of the `FetchArgs` argument should be stringified via `JSON.stringify()`.\n\nThe default implementation inspects the `content-type` header, and will match values like `\"application/json\"` and `\"application/vnd.api+json\"`.\n\n### `jsonContentType`\n\n_(optional)_\n\nUsed when automatically setting the `content-type` header for a request with a jsonifiable body that does not have an explicit `content-type` header. Defaults to `\"application/json\"`.\n\n## Common Usage Patterns\n\n### Setting default headers on requests\n\nThe most common use case for `prepareHeaders` would be to automatically include `authorization` headers for your API requests.\n\n```ts title=\"Setting a token from a redux store value\n// file: store.ts noEmit\nexport type RootState = { auth: { token: string } }\n\n// file: baseQuery.ts\nimport { fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { RootState } from './store'\n\nconst baseQuery = fetchBaseQuery({\n  baseUrl: '/',\n  prepareHeaders: (headers, { getState }) => {\n    const token = (getState() as RootState).auth.token\n\n    // If we have a token set in state, let's assume that we should be passing it.\n    if (token) {\n      headers.set('authorization', `Bearer ${token}`)\n    }\n\n    return headers\n  },\n})\n```\n\n## Individual query options\n\nThere is more behavior that you can define on a per-request basis. The `query` field may return an object containing any of the default `fetch` options available to the `RequestInit` interface, as well as these additional options:\n\n```ts title=\"endpoint request options\"\ninterface FetchArgs extends RequestInit {\n  url: string\n  params?: Record<string, any>\n  body?: any\n  responseHandler?:\n    | 'json'\n    | 'text'\n    | `content-type`\n    | ((response: Response) => Promise<any>)\n  validateStatus?: (response: Response, body: any) => boolean\n  timeout?: number\n}\n\nconst defaultValidateStatus = (response: Response) =>\n  response.status >= 200 && response.status <= 299\n```\n\n### Setting the body\n\nBy default, `fetchBaseQuery` assumes that every request you make will be `json`, so in those cases all you have to do is set the `url` and pass a `body` object when appropriate. For other implementations, you can manually set the `Headers` to specify the content type.\n\n#### json\n\n```ts no-transpile\n // omitted\n  endpoints: (build) => ({\n    updateUser: build.query({\n      query: (user: Record<string, string>) => ({\n        url: `users`,\n        method: 'PUT',\n        body: user // Body is automatically converted to json with the correct headers\n      }),\n    }),\n```\n\n#### text\n\n```ts no-transpile\n // omitted\n  endpoints: (build) => ({\n    updateUser: build.query({\n      query: (user: Record<string, string>) => ({\n        url: `users`,\n        method: 'PUT',\n        headers: {\n            'content-type': 'text/plain',\n        },\n        body: user\n      }),\n    }),\n```\n\n### Setting the query string\n\n`fetchBaseQuery` provides a simple mechanism that converts an `object` to a serialized query string by passing the object to `new URLSearchParms()`. If this doesn't suit your needs, you have two options:\n\n1. Pass the `paramsSerializer` option to `fetchBaseQuery` to apply custom transformations\n2. Build your own querystring and set it in the `url`\n\n```ts no-transpile\n // omitted\n  endpoints: (build) => ({\n    updateUser: build.query({\n      query: (user: Record<string, string>) => ({\n        url: `users`,\n        // Assuming no `paramsSerializer` is specified, the user object is automatically converted\n        // and produces a url like /api/users?first_name=test&last_name=example\n        params: user\n      }),\n    }),\n```\n\n### Parsing a Response\n\nBy default, `fetchBaseQuery` assumes that every `Response` you get will be parsed as `json`. In the event that you don't want that to happen, you can customize the behavior by specifying an alternative response handler like `text`, or take complete control and use a custom function that accepts the raw `Response` object &mdash; allowing you to use any [`Response` method](https://developer.mozilla.org/en-US/docs/Web/API/Response).\n\nThe `responseHandler` field can be either:\n\n```ts\ntype ResponseHandler =\n  | 'content-type'\n  | 'json'\n  | 'text'\n  | ((response: Response) => Promise<any>)\n```\n\nThe `\"json\"` and `\"text\"` values instruct `fetchBaseQuery` to the corresponding fetch response methods for reading the body. `content-type` will check the header field to first determine if this appears to be JSON, and then use one of those two methods. The callback allows you to process the body yourself.\n\n```ts title=\"Parse a Response as text\"\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\nexport const customApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  endpoints: (build) => ({\n    getUsers: build.query({\n      query: () => ({\n        url: `users`,\n        // This is the same as passing 'text'\n        responseHandler: (response) => response.text(),\n      }),\n    }),\n  }),\n})\n```\n\n:::note Note about responses that return an undefined body\nIf you make a `json` request to an API that only returns a `200` with an undefined body, `fetchBaseQuery` will pass that through as `undefined` and will not try to parse it as `json`. This can be common with some APIs, especially on `delete` requests.\n:::\n\n#### Default response handler\n\nThe default response handler is `\"json\"`, which is equivalent to the following function:\n\n```ts title=\"Default responseHandler\"\nconst defaultResponseHandler = async (res: Response) => {\n  const text = await res.text()\n  return text.length ? JSON.parse(text) : null\n}\n```\n\n### Handling non-standard Response status codes\n\nBy default, `fetchBaseQuery` will `reject` any `Response` that does not have a status code of `2xx` and set it to `error`. This is the same behavior you've most likely experienced with `axios` and other popular libraries. In the event that you have a non-standard API you're dealing with, you can use the `validateStatus` option to customize this behavior.\n\n```ts title=\"Using a custom validateStatus\"\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\nexport const customApi = createApi({\n  // Set the baseUrl for every endpoint below\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  endpoints: (build) => ({\n    getUsers: build.query({\n      query: () => ({\n        url: `users`,\n        // Example: we have a backend API always returns a 200,\n        // but sets an `isError` property when there is an error.\n        validateStatus: (response, result) =>\n          response.status === 200 && !result.isError,\n      }),\n    }),\n  }),\n})\n```\n\n### Adding a custom timeout to requests\n\nBy default, `fetchBaseQuery` has no default timeout value set, meaning your requests will stay pending until your api resolves the request(s) or it reaches the browser's default timeout (normally 5 minutes). Most of the time, this isn't what you'll want. When using `fetchBaseQuery`, you have the ability to set a `timeout` on the `baseQuery` or on individual endpoints. When specifying both options, the endpoint value will take priority.\n\n```ts title=\"Setting a timeout value\"\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\nexport const api = createApi({\n  // Set a default timeout of 10 seconds\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/', timeout: 10000 }),\n  endpoints: (build) => ({\n    getUsers: build.query({\n      query: () => ({\n        url: `users`,\n        // Example: we know the users endpoint is _really fast_ because it's always cached.\n        // We can assume if it's over > 1000ms, something is wrong and we should abort the request.\n        timeout: 1000,\n      }),\n    }),\n  }),\n})\n```\n"
  },
  {
    "path": "docs/rtk-query/api/setupListeners.mdx",
    "content": "---\nid: setupListeners\ntitle: setupListeners\nsidebar_label: setupListeners\nhide_title: true\nhide_table_of_contents: false\ndescription: 'RTK Query > API: setupListeners reference'\n---\n\n&nbsp;\n\n# `setupListeners`\n\nA utility used to enable `refetchOnFocus` and `refetchOnReconnect` behaviors. It requires the `dispatch` method from your store. Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults, but you have the option of providing a callback for more granular control.\n\n```ts title=\"setupListeners default configuration\" no-transpile\nlet initialized = false\nexport function setupListeners(\n  dispatch: ThunkDispatch<any, any, any>,\n  customHandler?: (\n    dispatch: ThunkDispatch<any, any, any>,\n    actions: {\n      onFocus: typeof onFocus\n      onFocusLost: typeof onFocusLost\n      onOnline: typeof onOnline\n      onOffline: typeof onOffline\n    },\n  ) => () => void,\n) {\n  function defaultHandler() {\n    const handleFocus = () => dispatch(onFocus())\n    const handleFocusLost = () => dispatch(onFocusLost())\n    const handleOnline = () => dispatch(onOnline())\n    const handleOffline = () => dispatch(onOffline())\n    const handleVisibilityChange = () => {\n      if (window.document.visibilityState === 'visible') {\n        handleFocus()\n      } else {\n        handleFocusLost()\n      }\n    }\n\n    if (!initialized) {\n      if (typeof window !== 'undefined' && window.addEventListener) {\n        // Handle focus events\n        window.addEventListener(\n          'visibilitychange',\n          handleVisibilityChange,\n          false,\n        )\n        window.addEventListener('focus', handleFocus, false)\n\n        // Handle connection events\n        window.addEventListener('online', handleOnline, false)\n        window.addEventListener('offline', handleOffline, false)\n        initialized = true\n      }\n    }\n    const unsubscribe = () => {\n      window.removeEventListener('focus', handleFocus)\n      window.removeEventListener('visibilitychange', handleVisibilityChange)\n      window.removeEventListener('online', handleOnline)\n      window.removeEventListener('offline', handleOffline)\n      initialized = false\n    }\n    return unsubscribe\n  }\n\n  return customHandler\n    ? customHandler(dispatch, { onFocus, onFocusLost, onOffline, onOnline })\n    : defaultHandler()\n}\n```\n\nIf you notice, `onFocus`, `onFocusLost`, `onOffline`, `onOnline` are all actions that are provided to the callback. Additionally, these actions are made available to `api.internalActions` and are able to be used by dispatching them like this:\n\n```ts title=\"Manual onFocus event\" no-transpile\ndispatch(api.internalActions.onFocus())\n```\n"
  },
  {
    "path": "docs/rtk-query/comparison.md",
    "content": "---\nid: comparison\ntitle: Comparison with Other Tools\nsidebar_label: Comparison with Other Tools\nhide_title: true\ndescription: 'RTK Query > Comparison: Compares features and tradeoffs vs other similar tools'\n---\n\n&nbsp;\n\n# Comparison with Other Tools\n\n**RTK Query takes inspiration from many other data fetching libraries in the ecosystem**. Much like [the Redux core library was inspired by tools like Flux and Elm](https://redux.js.org/understanding/history-and-design/prior-art), RTK Query builds on API design patterns and feature concepts popularized by libraries like [React Query](https://react-query.tanstack.com/), [SWR](https://swr.vercel.app/), [Apollo](https://www.apollographql.com/), and [Urql](https://formidable.com/open-source/urql/). RTK Query has been written from scratch, but tries to use the best concepts from those libraries and other data fetching tools, with an eye towards leveraging the unique strengths and capabilities of Redux.\n\nWe think that all of those tools are great! If you're using one of them, you're happy with it, and it solves the problems you are facing in your app, keep using that tool. The information on this page is meant to help show **where there are differences in features, implementation approaches, and API design**. The goal is to help you **make informed decisions and understand tradeoffs**, rather than argue that tool X is better than tool Y.\n\n## When Should You Use RTK Query?\n\nIn general, the main reasons to use RTK Query are:\n\n- You already have a Redux app and you want to simplify your existing data fetching logic\n- You want to be able to use the Redux DevTools to see the history of changes to your state over time\n- You want to be able to integrate the RTK Query behavior with the rest of the Redux ecosystem\n- Your app logic needs to work outside of React\n\n### Unique Capabilities\n\nRTK Query has some unique API design aspects and capabilities that are worth considering.\n\n- With React Query and SWR, you usually define your hooks yourself, and you can do that all over the place and on the fly. With RTK Query, you do so in one central place by defining an \"API slice\" with multiple endpoints ahead of time. This allows for a more tightly integrated model of mutations automatically invalidating/refetching queries on trigger.\n- Because RTK Query dispatches normal Redux actions as requests are processed, all actions are visible in the Redux DevTools. Additionally, every request is automatically visible to your Redux reducers and can easily update the global application state if necessary ([see example](https://github.com/reduxjs/redux-toolkit/issues/958#issuecomment-809570419)). You can use the endpoint [matcher functionality](./api/created-api/endpoints#matchers) to do additional processing of cache-related actions in your own reducers.\n- Like Redux itself, the main RTK Query functionality is UI-agnostic and can be used with any UI layer\n- You can easily invalidate entities or patch existing query data (via `util.updateQueryData`) from middleware.\n- RTK Query enables [streaming cache updates](./usage/streaming-updates.mdx), such as updating the initial fetched data as messages are received over a websocket, and has built in support for [optimistic updates](./usage/manual-cache-updates.mdx#optimistic-updates) as well.\n- RTK Query ships a very tiny and flexible fetch wrapper: [`fetchBaseQuery`](./api/fetchBaseQuery.mdx). It's also very easy to [swap our client with your own](./usage/customizing-queries.mdx), such as using `axios`, `redaxios`, or something custom.\n- RTK Query has [a (currently experimental) code-gen tool](https://github.com/reduxjs/redux-toolkit/tree/master/packages/rtk-query-codegen-openapi) that will take an OpenAPI spec or GraphQL schema and give you a typed API client, as well as provide methods for enhancing the generated client after the fact.\n\n## Tradeoffs\n\n### No Normalized or Deduplicated Cache\n\nRTK Query deliberately **does _not_ implement a cache that would deduplicate identical items across multiple requests**. There are several reasons for this:\n\n- A fully normalized shared-across-queries cache is a _hard_ problem to solve\n- We don't have the time, resources, or interest in trying to solve that right now\n- In many cases, simply refetching data when it's invalidated works well and is easier to understand\n- At a minimum, RTKQ can help solve the general use case of \"fetch some data\", which is a big pain point for a lot of people\n\n### Bundle Size\n\nRTK Query adds a fixed one-time amount to your app's bundle size. Since RTK Query builds on top of Redux Toolkit and React-Redux, the added size varies depending on whether you are already using those in your app. The estimated min+gzip bundle sizes are:\n\n- If you are using RTK already: ~9kb for RTK Query and ~2kb for the hooks.\n- If you are not using RTK already:\n  - Without React: 17 kB for RTK+dependencies+RTK Query\n  - With React: 19kB + React-Redux, which is a peer dependency\n\nAdding additional endpoint definitions should only increase size based on the actual code inside the `endpoints` definitions, which will typically be just a few bytes.\n\nThe functionality included in RTK Query quickly pays for the added bundle size, and the elimination of hand-written data fetching logic should be a net improvement in size for most meaningful applications.\n\n## Comparing Feature Sets\n\nIt's worth comparing the feature sets of all these tools to get a sense of their similarities and differences.\n\n:::info\n\nThis comparison table strives to be as accurate and as unbiased as possible. If you use any of these libraries and feel the information could be improved, feel free to suggest changes (with notes or evidence of claims) by [opening an issue](https://github.com/reduxjs/redux-toolkit/issues/new).\n\n:::\n\n| Feature                                | rtk-query                               | [react-query]            | [apollo]                                                                            | [urql]                                                                                                      |\n| -------------------------------------- | --------------------------------------- | ------------------------ | ----------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------- |\n| **Supported Protocols**                | any, REST included                      | any, none included       | GraphQL                                                                             | GraphQL                                                                                                     |\n| **API Definition**                     | declarative                             | on use, declarative      | GraphQL schema                                                                      | GraphQL schema                                                                                              |\n| **Cache by**                           | endpoint + serialized arguments         | user-defined query-key   | type/id                                                                             | type/id?                                                                                                    |\n| **Invalidation Strategy + Refetching** | declarative, by type and/or type/id     | manual by cache key      | automatic cache updates on per-entity level, manual query invalidation by cache key | declarative, by type OR automatic cache updates on per-entity level, manual query invalidation by cache key |\n| **Polling**                           | yes                                     | yes                      | yes                                                                                 | yes                                                                                                         |\n| **Parallel queries**                  | yes                                     | yes                      | yes                                                                                 | yes                                                                                                         |\n| **Dependent queries**                  | yes                                     | yes                      | yes                                                                                 | yes                                                                                                         |\n| **Skip queries**                       | yes                                     | yes                      | yes                                                                                 | yes                                                                                                         |\n| **Lagged queries**                     | yes                                     | yes                      | no                                                                                  | ?                                                                                                           |\n| **Auto garbage collection**            | yes                                     | yes                      | no                                                                                  | ?                                                                                                           |\n| **Normalized caching**                 | no                                      | no                       | yes                                                                                 | yes                                                                                                         |\n| **Infinite scrolling**                 | yes                                     | yes                      | requires manual code                                                                | ?                                                                                                           |\n| **Prefetching**                        | yes                                     | yes                      | yes                                                                                 | yes?                                                                                                        |\n| **Retrying**                           | yes                                     | yes                      | requires manual code                                                                | ?                                                                                                           |\n| **Optimistic updates**                 | can update cache by hand                | can update cache by hand | `optimisticResponse`                                                                | ?                                                                                                           |\n| **Manual cache manipulation**          | yes                                     | yes                      | yes                                                                                 | yes                                                                                                         |\n| **Platforms**                          | hooks for React, everywhere Redux works | hooks for React          | various                                                                             | various                                                                                                     |\n\n[react-query]: https://react-query.tanstack.com/\n[apollo]: https://www.apollographql.com/\n[urql]: https://formidable.com/open-source/urql/\n\n## Further Information\n\n- The [React Query \"Comparison\" page](https://tanstack.com/query/latest/docs/react/comparison) has an additional detailed feature set comparison table and discussion of capabilities\n- Urql maintainer Phil Pluckthun wrote [an excellent explanation of what a \"normalized cache\" is and how Urql's cache works](https://kitten.sh/graphql-normalized-caching)\n- The [RTK Query \"Cache Behavior\" page](./usage/cache-behavior.mdx#tradeoffs) has further details on why RTK Query does not implement a normalized cache\n"
  },
  {
    "path": "docs/rtk-query/internal/buildMiddleware/invalidationByTags.mdx",
    "content": "# invalidationByTags\n\n## Overview\n\n`InvalidationByTagsHandler` is a handler instantiated during the (BuildMiddleware) step of the build. The handler acts as a (Middleware) and executes each step in response to matching of internal asyncThunk actions.\n\nThe matchers used for a \"invalidation sequence\" are these two cases:\n\n```ts no-transpile\nconst isThunkActionWithTags = isAnyOf(\n  isFulfilled(mutationThunk),\n  isRejectedWithValue(mutationThunk),\n)\n\nconst isQueryEnd = isAnyOf(\n  isFulfilled(mutationThunk, queryThunk),\n  isRejected(mutationThunk, queryThunk),\n)\n```\n\n## Triggers\n\nThe handler has 3 core conditionals that trigger a sequence:\n\n_Conditional 1 AND 3 are identical in process except the tags are calculated from the payload rather than from the action and endpointDefinition_\n\n1. Mutation trigger\n2. Query trigger\n3. Manual invalidation via `api.util.invalidateTags` trigger\n\n```ts no-transpile\nconst handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n  if (isThunkActionWithTags(action)) {\n    invalidateTags(\n      calculateProvidedByThunk(\n        action,\n        'invalidatesTags',\n        endpointDefinitions,\n        assertTagType,\n      ),\n      mwApi,\n    )\n  } else if (isQueryEnd(action)) {\n    invalidateTags([], mwApi)\n  } else if (api.util.invalidateTags.match(action)) {\n    invalidateTags(\n      calculateProvidedBy(\n        action.payload,\n        undefined,\n        undefined,\n        undefined,\n        undefined,\n        assertTagType,\n      ),\n      mwApi,\n    )\n  }\n}\n```\n\n## Core Sequence\n\n1. `invalidateTags()` initiates:\n   1. invalidateTags function is called with a list of tags generated from the action metadata\n   2. in the case of a [queryThunk] resolution an empty set of tags is always provided\n2. The tags calculated are added to the list of pending tags to invalidate (see [delayed](#delayed))\n3. (optional: 'Delayed') the invalidateTags function is ended if the `apiSlice.invalidationBehavior` is set to \"delayed\" and there are any pending thunks/queries running in that `apiSlice`\n4. Pending tags are reset to an empty list, if there are no tags the function ends here\n5. Selects all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.\n6. Iterates through queryCacheKeys selected and performs one of two actions if the query exists\\*\n   1. removes cached query result - via the `removeQueryResult` action - if no subscription is active\n   2. if the query is \"uninitialized\" it initiates a `refetchQuery` action\n\n```js no-transpile\nconst toInvalidate = api.util.selectInvalidatedBy(rootState, tags)\ncontext.batch(() => {\n  const valuesArray = Array.from(toInvalidate.values())\n  for (const { queryCacheKey } of valuesArray) {\n    const querySubState = state.queries[queryCacheKey]\n    const subscriptionSubState =\n      internalState.currentSubscriptions[queryCacheKey] ?? {}\n    if (querySubState) {\n      if (countObjectKeys(subscriptionSubState) === 0) {\n        mwApi.dispatch(\n          removeQueryResult({\n            queryCacheKey,\n          }),\n        )\n      } else if (querySubState.status !== 'uninitialized' /* uninitialized */) {\n        mwApi.dispatch(refetchQuery(querySubState, queryCacheKey))\n      }\n    }\n  }\n})\n```\n\n:::note\nStep 6 is performed within a `context.batch()` call.\n:::\n\n### Delayed\n\nRTKQ now has internal logic to delay tag invalidation briefly, to allow multiple invalidations to get handled together. This is controlled by a new `invalidationBehavior: 'immediate' | 'delayed'` flag on `createApi`. The new default behavior is `'delayed'`. Set it to `'immediate'` to revert to the behavior in RTK 1.9.\n\nThe `'delayed'` behavior enables a check inside `invalidationByTags` that will cause any invalidation that is triggered while a query/mutation is still pending to batch the invalidation until no query/mutation is running.\n\n```ts no-transpile\nfunction invalidateTags(\n  newTags: readonly FullTagDescription<string>[],\n  mwApi: SubMiddlewareApi,\n) {\n  const rootState = mwApi.getState()\n  const state = rootState[reducerPath]\n\n  pendingTagInvalidations.push(...newTags)\n\n  if (\n    state.config.invalidationBehavior === 'delayed' &&\n    hasPendingRequests(state)\n  ) {\n    return\n  }\n```\n"
  },
  {
    "path": "docs/rtk-query/internal/buildSlice.mdx",
    "content": "# BuildSlice\n\n## Slices\n\n### querySlice\n\n#### reducers\n\n- `removeQueryResult` - delete a specific cacheKey's stored result\n- `queryResultPatched` - patch a specific cacheKey's result\n\n#### extraReducers - matching queryThunk cases\n\n- `queryThunk.pending`\n  - Initially sets QueryStatus to uninitialized\n  - updates QueryStatus to pending\n  - Generates requestId\n  - stores originalArgs\n  - stores startedTimeStamp\n- `queryThunk.fulfilled`\n  - handles merge functionality first\n  - otherwise updates the cache data, creates a fulfilledTimeStamp and deletes the substates error\n\n```ts no-transpile\nif (merge) {\n  if (substate.data !== undefined) {\n    const { fulfilledTimeStamp, arg, baseQueryMeta, requestId } = meta\n    // There's existing cache data. Let the user merge it in themselves.\n    // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`\n    // themselves inside of `merge()`. But, they might also want to return a new value.\n    // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.\n    let newData = createNextState(substate.data, (draftSubstateData) => {\n      // As usual with Immer, you can mutate _or_ return inside here, but not both\n      return merge(draftSubstateData, payload, {\n        arg: arg.originalArgs,\n        baseQueryMeta,\n        fulfilledTimeStamp,\n        requestId,\n      })\n    })\n    substate.data = newData\n  } else {\n    // Presumably a fresh request. Just cache the response data.\n    substate.data = payload\n  }\n}\n```\n\n- `queryThunk.rejected`\n  - utilises `condition()` from `queryThunk` and does nothing if the rejection is a result of `condition()` (indicates a thunk is already running here)\n  - else substate.error is set and the status is changed to rejected\n- `hasRehydrationInfo`\n  - iterates through and resets entries for all fulfilled or rejected status\n\n### mutationSlice\n\n#### reducers\n\n- `removeMutationResult`\n  - calls `getMutationCacheKey` from payload\n  - if cacheKey is in draft it deletes `draft[cacheKey`(?)\n\n#### extraReducers - matching mutationThunk cases\n\n- `mutationThunk.pending`\n  - exits if track is set to false\n  - otherwise updates appropriate cacheKey with requestId, pending status and startedTimeStamp\n- `mutationThunk.fulfilled`\n  - exits if track is set to false\n  - otherwise sets data off payload and fulfilledTimeStamp\n- `mutationThunk.rejected`\n  - exits if track is set to false\n  - otherwise sets error and status to rejected\n- `hasRehydrationInfo`\n  - iterates through and resets entries for all fulfilled or rejected status\n\n### invalidationSlice\n\n#### reducers\n\n- updateProvidedBy\n  - takes queryCacheKey and providedTags from payload\n  - appends to a list of idSubscriptions the queryCacheKey that are currently subscribed to for each tag\n\n#### extraReducers\n\n- `querySlice.actions.removeQueryResult`,\n  - deletes relevant queryCacheKey entry from list of subscription ids\n- `hasRehydrationInfo`\n  - TODO\n- `queryThunk.fulfilled` or `queryThunk.rejected`\n  - gets list of tags from action and endpoint definition\n  - gets queryCacheKey\n  - calls updateProvidedBy action\n\n### subscriptionSlice / internalSubscriptionSlice\n\n#### reducers\n\n- updateSubscriptionOptions\n- unsubscribeQueryResult\n- internal_getRTKQSubscriptions\n- subscriptionsUpdated\n  - applyPatches() to the state from the payload\n\n### configSlice\n\n#### reducers\n\n- middlewareRegistered\n  - toggles whether the middleware is registered or if there is a conflict\n\n#### extraReducers\n\n- `onOnline`\n  - manages state.online in response to listenerMiddleware\n- `onOffline`\n  - manages state.online in response to listenerMiddleware\n- `onFocus`\n  - manages state.focused in response to listenerMiddleware\n- `onFocusLost`\n  - manages state.focused in response to listenerMiddleware\n- `hasRehydrationInfo`\n  - lists a comment that says: \"update the state to be a new object to be picked up as a \"state change\" by redux-persist's `autoMergeLevel2`\"\n\n## Functions\n\n### `updateQuerySubstateIfExists`\n\nUtility function that takes the api/endpoint state, queryCacheKey and Update function.\nThe \"SubState\" is determined by accessing the `queryCacheKey` value inside the state. If the substate exists, the update function is executed on the substate.\n\n```js no-transpile\nfunction updateQuerySubstateIfExists(state, queryCacheKey, update) {\n  const substate = state[queryCacheKey]\n  if (substate) {\n    update(substate)\n  }\n}\n```\n\n### `getMutationCacheKey`\n\nconditionally determines the cachekey to be used for the mutation, prioritising the argument provided, followed by the provided cacheKey, and the generated requestId otherwise\n\n```ts no-transpile\nexport function getMutationCacheKey(\n  id:\n    | { fixedCacheKey?: string; requestId?: string }\n    | MutationSubstateIdentifier\n    | { requestId: string; arg: { fixedCacheKey?: string | undefined } },\n): string | undefined {\n  return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId\n}\n```\n\n### `getMutationSubstateIfExists`\n\nsame as query version except it uses the id instead of the queryCacheKey, and uses the `getMutationCacheKey` to determine the cachekey\n\n```js no-transpile\nfunction updateMutationSubstateIfExists(state, id, update) {\n  const substate = state[getMutationCacheKey(id)]\n  if (substate) {\n    update(substate)\n  }\n}\n```\n"
  },
  {
    "path": "docs/rtk-query/internal/overview.mdx",
    "content": "# RTKQ internal\n\n## Overview\n\n> RTK Query is a powerful data fetching and caching tool built on top of Redux Toolkit. It is designed to simplify the process of fetching, caching, and updating server state in your application. It is built on top of Redux Toolkit and uses Redux internally.\n\nThis documentation is intended to provide a high-level overview of the internal architecture of RTK-Query. It is not intended to be a comprehensive guide to the library, but rather a guide to the internal architecture and how it works.\n\n## createApi - The Entry Point\n\nWhen `createApi()` is called it takes the options provided and calls internally the `buildCreateApi()` function passing into it two modules:\n\n_Modules are RTK-Query's method of customizing how the `createApi` method handles endpoints._\n\n- `coreModule()` - responsible for the majority of the internal handling using core redux logic i.e. slices, reducers, asyncThunks.\n- `reactHooksModule()` - a module that generates react hooks from endpoints using react-redux\n\n## Core Module\n\nThe core module takes the `api` and the options passed to `createApi()`. In turn an internal set of \"build\" methods are called. Each of these build methods create a set of functions which are assigned to either `api.util` or `api.internalActions` and/or passed to a future \"build\" step.\n\n### buildThunks\n\nRTK-Query's internal functionality operates using the same `asyncThunk` exposed from RTK. In the first \"build\" method, a number of thunks are generated for the core module to use:\n\n- `queryThunk`\n- `mutationThunk`\n- `patchedQueryData`\n- `updateQueryData`\n- `upsertQueryData`\n- `prefetch`\n- `buildMatchThunkActions`\n\n### buildSlice\n\nRTK-Query uses a very familiar redux-centric architecture. Where the `api` is a slice of your store, the `api` has its own slices created within it. These slices are where the majority of the RTKQ magic happens.\n\nThe slices built inside this \"build\" are:\n_Some of which have their own actions_\n\n- `querySlice`\n- `mutationSlice`\n- `invalidationSlice`\n- `subscriptionSlice` (used as a dummy slice to generate actions internally)\n- `internalSubscriptionsSlice`\n- `configSlice` (internal tracking of focus state, online state, hydration etc)\n\nbuildSlice also exposes the core action `resetApiState` which is subsequently added to the `api.util`\n\n### buildMiddleware\n\nRTK-Query has a series of custom middlewares established within its store to handle additional responses in addition to the core logic established within the slices from buildSlice.\n\nEach middleware built during this step is referred to internally as a \"Handler\" and are as follows:\n\n- `buildDevCheckHandler`\n- `buildCacheCollectionHandler`\n- `buildInvalidationByTagsHandler`\n- `buildPollingHandler`\n- `buildCacheLifecycleHandler`\n- `buildQueryLifecycleHandler`\n\n### buildSelectors\n\nbuild selectors is a crucial step that exposes to the `api` and utils:\n\n- `buildQuerySelector`\n- `buildMutationSelector`\n- `selectInvalidatedBy`\n- `selectCachedArgsForQuery`\n\n### return\n\nFinally each endpoint passed into the `createApi()` is iterated over and assigned either the query or the mutation selectors, initiators and match cases.\n"
  },
  {
    "path": "docs/rtk-query/internal/queryThunk.mdx",
    "content": "# queryThunk\n\n## Overview\n\nA core action instantiated during (buildThunks). `queryThunk` leverages `createAsyncThunk` to initiate the query process and is used extensively throughout the codebase both as a match case and to initiate queries. The payload for the query is built using [executeEndpoint]\n\n## Functions\n\nBefore executing the payload creator function in [executeEndpoint], `queryThunk` executes two functions:\n\n### `getPendingMeta()`\n\n1. `getPendingMeta()` - adds additional metadata to the action to be used in reducers or middleware.\n   1. `startedTimeStamp`\n   2. `SHOULD_AUTOBATCH`\n\n### `condition()`\n\nPerforms conditional checks based on the provided args to decide whether the query should continue or not. (also attaches the field `dispatchConditionRejected: true` as confirmation that the condition was checked)\n\n```ts no-transpile\nif (isUpsertQuery(queryThunkArgs)) { return true }\nif (requestState?.status === \"pending\") { return false }\nif (isForcedQuery(queryThunkArgs, state)) { return true }\nif (isQueryDefinition(endpointDefinition) && endpointDefinition?.forceRefetch?.({ return true }\nif (fulfilledVal) { return false }\nelse return true\n```\n\n## Middleware Uses\n\n### buildSlice\n\nThe query endpoint is built almost entirely off of the `extraReducers` matching a `queryThunk` pending/fulfilled/rejected actions and updates the `querySubstate` plus meta data accordingly. The query slice utilises the condition and attached metadata created by a `queryThunk`.\n\n`buildSlice` additionally matches resolved (rejected OR fulfilled) `queryThunks` to update providedTags.\n\n### invalidationByTags\n\nmatches against all rejected/fulfilled cases for `queryThunk`\n\n### Polling\n\nmatches against multiple queryThunk cases\n\n```js no-transpile\nif (\n  queryThunk.pending.match(action) ||\n  (queryThunk.rejected.match(action) && action.meta.condition)\n) {\n  updatePollingInterval(action.meta.arg, mwApi)\n}\nif (\n  queryThunk.fulfilled.match(action) ||\n  (queryThunk.rejected.match(action) && !action.meta.condition)\n) {\n  startNextPoll(action.meta.arg, mwApi)\n}\n```\n\n### cacheLifecycle\n\nuses `queryThunk` matching to differentiate between mutation cache and query cache handling\n\n### queryLifecycle\n\nleverages the createAsyncThunk pending/fulfilled/rejected to extend the lifecycle with query specific traits, also uses it to handle onQueryStarted\n\n### batchedActions\n\n### buildMiddleware\n\n`refetchQuery` refires queryThunk with arguments for the `queryThunk` to determine if the query should be sent or not\n"
  },
  {
    "path": "docs/rtk-query/overview.md",
    "content": "---\nid: overview\ntitle: RTK Query Overview\nsidebar_label: RTK Query Overview\nhide_title: true\ndescription: 'RTK Query > Overview: a summary of the RTK Query data caching API for Redux Toolkit'\n---\n\n&nbsp;\n\n# RTK Query Overview\n\n:::tip What You'll Learn\n\n- What RTK Query is and what problems it solves\n- What APIs are included in RTK Query\n- Basic RTK Query usage\n\n:::\n\n**RTK Query** is a powerful data fetching and caching tool. It is designed to simplify common cases for loading data in a web application, **eliminating the need to hand-write data fetching & caching logic yourself**.\n\nRTK Query is **an optional addon included in the Redux Toolkit package**, and its functionality is built on top of the other APIs in Redux Toolkit.\n\n:::info\n\nTo learn how to use RTK Query, see the full [\"Redux Essentials\" tutorial](https://redux.js.org/tutorials/essentials/part-7-rtk-query-basics) on the Redux core docs site.\n\nIf you prefer a video course, you can [watch this RTK Query video course by Lenz Weber-Tronic, the creator of RTK Query, for free at Egghead](https://egghead.io/courses/rtk-query-basics-query-endpoints-data-flow-and-typescript-57ea3c43?af=7pnhj6) or take a look at the first lesson right here:\n\n<div style={{position:\"relative\",paddingTop:\"56.25%\"}}>\n  <iframe \n    src=\"https://app.egghead.io/lessons/redux-course-introduction-and-application-walk-through-for-rtk-query-basics/embed?af=7pnhj6\" \n    title=\"RTK Query Video course at Egghead: Course Introduction and Application Walk through for RTK Query Basics\"\n    frameborder=\"0\" \n    allowfullscreen\n    style={{position:\"absolute\",top:0,left:0,width:\"100%\",height:\"100%\"}}\n  ></iframe>\n</div>\n\n:::\n\n## Motivation\n\nWeb applications normally need to fetch data from a server in order to display it. They also usually need to make updates to that data, send those updates to the server, and keep the cached data on the client in sync with the data on the server. This is made more complicated by the need to implement other behaviors used in today's applications:\n\n- Tracking loading state in order to show UI spinners\n- Avoiding duplicate requests for the same data\n- Optimistic updates to make the UI feel faster\n- Managing cache lifetimes as the user interacts with the UI\n\nThe Redux core has always been very minimal - it's up to developers to write all the actual logic. That means that Redux has never included anything built in to help solve these use cases. The Redux docs have taught [some common patterns for dispatching actions around the request lifecycle to track loading state and request results](https://redux.js.org/tutorials/fundamentals/part-7-standard-patterns#async-request-status), and [Redux Toolkit's `createAsyncThunk` API](../api/createAsyncThunk.mdx) was designed to abstract that typical pattern. However, users still have to write significant amounts of reducer logic to manage the loading state and the cached data.\n\nOver the last couple years, the React community has come to realize that **\"data fetching and caching\" is really a different set of concerns than \"state management\"**. While you can use a state management library like Redux to cache data, the use cases are different enough that it's worth using tools that are purpose-built for the data fetching use case.\n\nRTK Query takes inspiration from other tools that have pioneered solutions for data fetching, like Apollo Client, React Query, Urql, and SWR, but adds a unique approach to its API design:\n\n- The data fetching and caching logic is built on top of Redux Toolkit's `createSlice` and `createAsyncThunk` APIs\n- Because Redux Toolkit is UI-agnostic, RTK Query's functionality can be used with any UI layer\n- API endpoints are defined ahead of time, including how to generate query parameters from arguments and transform responses for caching\n- RTK Query can also generate React hooks that encapsulate the entire data fetching process, provide `data` and `isLoading` fields to components, and manage the lifetime of cached data as components mount and unmount\n- RTK Query provides \"cache entry lifecycle\" options that enable use cases like streaming cache updates via websocket messages after fetching the initial data\n- We have early working examples of code generation of API slices from OpenAPI and GraphQL schemas\n- Finally, RTK Query is completely written in TypeScript, and is designed to provide an excellent TS usage experience\n\n## What's included\n\n### APIs\n\nRTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:\n\n```ts no-transpile\nimport { createApi } from '@reduxjs/toolkit/query'\n\n/* React-specific entry point that automatically generates\n   hooks corresponding to the defined endpoints */\nimport { createApi } from '@reduxjs/toolkit/query/react'\n```\n\nRTK Query includes these APIs:\n\n- [`createApi()`](./api/createApi.mdx): The core of RTK Query's functionality. It allows you to define a set of \"endpoints\" that describe how to retrieve data from backend APIs and other async sources, including the configuration of how to fetch and transform that data. In most cases, you should use this once per app, with \"one API slice per base URL\" as a rule of thumb.\n- [`fetchBaseQuery()`](./api/fetchBaseQuery.mdx): A small wrapper around [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) that aims to simplify requests. Intended as the recommended `baseQuery` to be used in `createApi` for the majority of users.\n- [`<ApiProvider />`](./api/ApiProvider.mdx): Can be used as a `Provider` if you **do not already have a Redux store**.\n- [`setupListeners()`](./api/setupListeners.mdx): A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\n\n### Bundle Size\n\nRTK Query adds a fixed one-time amount to your app's bundle size. Since RTK Query builds on top of Redux Toolkit and React-Redux, the added size varies depending on whether you are already using those in your app. The estimated min+gzip bundle sizes are:\n\n- If you are using RTK already: ~9kb for RTK Query and ~2kb for the hooks.\n- If you are not using RTK already:\n  - Without React: 17 kB for RTK+dependencies+RTK Query\n  - With React: 19kB + React-Redux, which is a peer dependency\n\nAdding additional endpoint definitions should only increase size based on the actual code inside the `endpoints` definitions, which will typically be just a few bytes.\n\nThe functionality included in RTK Query quickly pays for the added bundle size, and the elimination of hand-written data fetching logic should be a net improvement in size for most meaningful applications.\n\n## Basic Usage\n\n### Create an API Slice\n\nRTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:\n\n```ts\nimport { createApi } from '@reduxjs/toolkit/query'\n\n/* React-specific entry point that automatically generates\n   hooks corresponding to the defined endpoints */\nimport { createApi } from '@reduxjs/toolkit/query/react'\n```\n\nFor typical usage with React, start by importing `createApi` and defining an \"API slice\" that lists the server's base URL and which endpoints we want to interact with:\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Pokemon } from './types'\n\n// Define a service using a base URL and expected endpoints\nexport const pokemonApi = createApi({\n  reducerPath: 'pokemonApi',\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (build) => ({\n    getPokemonByName: build.query<Pokemon, string>({\n      query: (name) => `pokemon/${name}`,\n    }),\n  }),\n})\n\n// Export hooks for usage in functional components, which are\n// auto-generated based on the defined endpoints\nexport const { useGetPokemonByNameQuery } = pokemonApi\n```\n\n### Configure the Store\n\nThe \"API slice\" also contains an auto-generated Redux slice reducer and a custom middleware that manages subscription lifetimes. Both of those need to be added to the Redux store:\n\n```ts\nimport { configureStore } from '@reduxjs/toolkit'\n// Or from '@reduxjs/toolkit/query/react'\nimport { setupListeners } from '@reduxjs/toolkit/query'\nimport { pokemonApi } from './services/pokemon'\n\nexport const store = configureStore({\n  reducer: {\n    // Add the generated reducer as a specific top-level slice\n    [pokemonApi.reducerPath]: pokemonApi.reducer,\n  },\n  // Adding the api middleware enables caching, invalidation, polling,\n  // and other useful features of `rtk-query`.\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(pokemonApi.middleware),\n})\n\n// optional, but required for refetchOnFocus/refetchOnReconnect behaviors\n// see `setupListeners` docs - takes an optional callback as the 2nd arg for customization\nsetupListeners(store.dispatch)\n```\n\n### Use Hooks in Components\n\nFinally, import the auto-generated React hooks from the API slice into your component file, and call the hooks in your component with any needed parameters. RTK Query will automatically fetch data on mount, re-fetch when parameters change, provide `{data, isFetching}` values in the result, and re-render the component as those values change:\n\n```ts\nimport * as React from 'react'\nimport { useGetPokemonByNameQuery } from './services/pokemon'\n\nexport default function App() {\n  // Using a query hook automatically fetches data and returns query values\n  const { data, error, isLoading } = useGetPokemonByNameQuery('bulbasaur')\n  // Individual hooks are also accessible under the generated endpoints:\n  // const { data, error, isLoading } = pokemonApi.endpoints.getPokemonByName.useQuery('bulbasaur')\n\n  // render UI based on data and loading state\n}\n```\n\n## Further Information\n\nSee the [**RTK Query Quick Start tutorial**](../tutorials/rtk-query.mdx) for examples of how to add RTK Query to a project that uses Redux Toolkit, set up an \"API slice\" with endpoint definitions, and how to use the auto-generated React hooks in your components.\n\nThe [**RTK Query usage guide section**](./usage/queries.mdx) has information on topics like [querying data](./usage/queries.mdx), [using mutations to send updates to the server](./usage/mutations.mdx), [streaming cache updates](./usage/streaming-updates.mdx), and much more.\n\nThe [**Examples page**](./usage/examples.mdx) has runnable CodeSandboxes that demonstrate topics like [making queries with GraphQL](./usage/examples.mdx#react-with-graphql), [authentication](./usage/examples.mdx#authentication), and even [using RTK Query with other UI libraries like Svelte](./usage/examples.mdx#svelte).\n"
  },
  {
    "path": "docs/rtk-query/usage/automated-refetching.mdx",
    "content": "---\nid: automated-refetching\ntitle: Automated Re-fetching\nsidebar_label: Automated Re-fetching\nhide_title: true\ndescription: 'RTK Query > Usage > Automated Refetching: cache invalidation management'\n---\n\n&nbsp;\n\n# Automated Re-fetching\n\nAs seen under [Default Cache Behavior](./cache-behavior.mdx#default-cache-behavior), when a subscription is added for a query endpoint, a request will be sent only if the cache data does not already exist. If it exists, the existing data will be served instead.\n\nRTK Query uses a \"cache tag\" system to automate re-fetching for query endpoints that have data affected by mutation endpoints. This enables designing your API such that firing a specific mutation will cause a certain query endpoint to consider its cached data _invalid_, and re-fetch the data if there is an active subscription.\n\nEach endpoint + parameter combination contributes its own `queryCacheKey`. The cache tag system enables the ability to inform RTK Query that a particular query cache has _provided_ specific tags. If a mutation is fired which is said to `invalidate` tags that a query cache has _provided_, the cached data will be considered _invalidated_, and re-fetch if there is an active subscription to the cached data.\n\nFor triggering re-fetching through other means, see [Manipulating Cache Behavior](./cache-behavior.mdx#manipulating-cache-behavior).\n\n## Definitions\n\n### Tags\n\n_see also: [tagTypes API reference](../api/createApi.mdx#tagtypes)_\n\nFor RTK Query, _tags_ are just a name that you can give to a specific collection of data to control caching and invalidation behavior for re-fetching purposes. It can be considered as a 'label' attached to cached data that is read after a mutation, to decide whether the data should be affected by the mutation.\n\nTags are defined in the `tagTypes` argument when defining an api. For example, in an application that has both `Posts` and `Users`, you might define `tagTypes: ['Post', 'User']` when calling `createApi`.\n\nAn individual `tag` has a `type`, represented as a `string` name, and an optional `id`, represented as a `string` or `number`. It can be represented as a plain string (such as `'Post'`), or an object in the shape `{type: string, id?: string|number}` (such as `[{type: 'Post', id: 1}]`).\n\n### Providing tags\n\n_see also: [providesTags API reference](../api/createApi.mdx#providestags)_\n\nA _query_ can have its cached data _provide_ tags. Doing so determines which 'tag' is attached to the cached data returned by the query.\n\nThe `providesTags` argument can either be an array of `string` (such as `['Post']`), `{type: string, id?: string|number}` (such as `[{type: 'Post', id: 1}]`), or a callback that returns such an array. That function will be passed the result as the first argument, the response error as the second argument, and the argument originally passed into the `query` method as the third argument. Note that either the result or error arguments may be undefined based on whether the query was successful or not.\n\n### Invalidating tags\n\n_see also: [invalidatesTags API reference](../api/createApi.mdx#invalidatestags)_\n\nA _mutation_ can _invalidate_ specific cached data based on the tags. Doing so determines which cached data will be either refetched or removed from the cache.\n\nThe `invalidatesTags` argument can either be an array of `string` (such as `['Post']`), `{type: string, id?: string|number}` (such as `[{type: 'Post', id: 1}]`), or a callback that returns such an array. That function will be passed the result as the first argument, the response error as the second argument, and the argument originally passed into the `query` method as the third argument. Note that either the result or error arguments may be undefined based on whether the mutation was successful or not.\n\n## Cache tags\n\nRTK Query uses the concept of 'tags' to determine whether a mutation for one endpoint intends to _invalidate_ some data that was _provided_ by a query from another endpoint.\n\nIf cache data is being invalidated, it will either refetch the providing query (if components are still using that data) or remove the data from the cache.\n\nWhen defining an API slice, `createApi` accepts an array of tag type names for the `tagTypes` property, which is a list of possible tag name options that the queries for the API slice could provide.\n\nThe example below declares that endpoints can possibly provide 'Posts' and/or 'Users' to the cache:\n\n```ts title=\"Example of declaring cache tags\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\nexport interface User {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post, User } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n  }),\n  // highlight-start\n  tagTypes: ['Post', 'User'],\n  // highlight-end\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => '/posts',\n    }),\n    getUsers: build.query<User[], void>({\n      query: () => '/users',\n    }),\n    addPost: build.mutation<Post, Omit<Post, 'id'>>({\n      query: (body) => ({\n        url: 'post',\n        method: 'POST',\n        body,\n      }),\n    }),\n    editPost: build.mutation<Post, Partial<Post> & Pick<Post, 'id'>>({\n      query: (body) => ({\n        url: `post/${body.id}`,\n        method: 'POST',\n        body,\n      }),\n    }),\n  }),\n})\n```\n\nBy declaring these tags as what can possibly be provided to the cache, it enables control for individual mutation endpoints to claim whether they affect specific portions of the cache or not, in conjunction with `providesTags` and `invalidatesTags` on individual endpoints.\n\n### Providing cache data\n\nEach individual `query` endpoint can have its cached data _provide_ particular tags. Doing so enables a relationship between cached data from one or more query endpoints and the behavior of one or more mutation endpoints.\n\nThe `providesTags` property on a `query` endpoint is used for this purpose.\n\n:::info\n\nProvided tags have no inherent relationship across separate `query` endpoints. Provided tags are used to determine whether cached data returned by an endpoint should be `invalidated` and either be refetched or removed from the cache. If two separate endpoints provide the same tags, they will still contribute their own distinct cached data, which could later both be invalidated by a single tag declared from a mutation.\n\n:::\n\nThe example below declares that the `getPosts` `query` endpoint `provides` the `'Post'` tag to the cache, using the `providesTags` property for a `query` endpoint.\n\n```ts title=\"Example of providing tags to the cache\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\nexport interface User {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post, User } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n  }),\n  tagTypes: ['Post', 'User'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => '/posts',\n      // highlight-start\n      providesTags: ['Post'],\n      // highlight-end\n    }),\n    getUsers: build.query<User[], void>({\n      query: () => '/users',\n      // highlight-start\n      providesTags: ['User'],\n      // highlight-end\n    }),\n    addPost: build.mutation<Post, Omit<Post, 'id'>>({\n      query: (body) => ({\n        url: 'posts',\n        method: 'POST',\n        body,\n      }),\n    }),\n    editPost: build.mutation<Post, Partial<Post> & Pick<Post, 'id'>>({\n      query: (body) => ({\n        url: `post/${body.id}`,\n        method: 'POST',\n        body,\n      }),\n    }),\n  }),\n})\n```\n\nFor more granular control over the provided data, provided `tags` can have an associated `id`. This enables a distinction between 'any of a particular tag type', and 'a specific instance of a particular tag type'.\n\nThe example below declares that the provided posts are associated with particular IDs as determined by the result returned by the endpoint:\n\n```ts title=\"Example of providing tags with IDs to the cache\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\nexport interface User {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post, User } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n  }),\n  tagTypes: ['Post', 'User'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => '/posts',\n      // highlight-start\n      providesTags: (result, error, arg) =>\n        result\n          ? [...result.map(({ id }) => ({ type: 'Post' as const, id })), 'Post']\n          : ['Post'],\n      // highlight-end\n    }),\n    getUsers: build.query<User[], void>({\n      query: () => '/users',\n      providesTags: ['User'],\n    }),\n    addPost: build.mutation<Post, Omit<Post, 'id'>>({\n      query: (body) => ({\n        url: 'post',\n        method: 'POST',\n        body,\n      }),\n    }),\n    editPost: build.mutation<Post, Partial<Post> & Pick<Post, 'id'>>({\n      query: (body) => ({\n        url: `post/${body.id}`,\n        method: 'POST',\n        body,\n      }),\n    }),\n  }),\n})\n```\n\nNote that for the example above, the `id` is used where possible on a successful result. In the case of an error, no result is supplied, and we still consider that it has provided the general `'Post'` tag type rather than any specific instance of that tag.\n\n:::tip Advanced List Invalidation\nIn order to provide stronger control over invalidating the appropriate data, you can use an arbitrary ID such as `'LIST'` for a given tag. See [Advanced Invalidation with abstract tag IDs](#advanced-invalidation-with-abstract-tag-ids) for additional details.\n:::\n\n### Invalidating cache data\n\nEach individual mutation endpoint can `invalidate` particular tags for existing cached data. Doing so enables a relationship between cached data from one or more query endpoints and the behavior of one or more mutation endpoints.\n\nThe `invalidatesTags` property on a mutation endpoint is used for this purpose.\n\nThe example below declares that the `addPost` and `editPost` mutation endpoints `invalidate` any cached data with the `'Post'` tag, using the `invalidatesTags` property for a mutation endpoint:\n\n```ts title=\"Example of invalidating tags in the cache\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\nexport interface User {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post, User } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n  }),\n  tagTypes: ['Post', 'User'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => '/posts',\n      providesTags: (result, error, arg) =>\n        result\n          ? [...result.map(({ id }) => ({ type: 'Post' as const, id })), 'Post']\n          : ['Post'],\n    }),\n    getUsers: build.query<User[], void>({\n      query: () => '/users',\n      providesTags: ['User'],\n    }),\n    addPost: build.mutation<Post, Omit<Post, 'id'>>({\n      query: (body) => ({\n        url: 'post',\n        method: 'POST',\n        body,\n      }),\n      // highlight-start\n      invalidatesTags: ['Post'],\n      // highlight-end\n    }),\n    editPost: build.mutation<Post, Partial<Post> & Pick<Post, 'id'>>({\n      query: (body) => ({\n        url: `post/${body.id}`,\n        method: 'POST',\n        body,\n      }),\n      // highlight-start\n      invalidatesTags: ['Post'],\n      // highlight-end\n    }),\n  }),\n})\n```\n\nFor the example above, this tells RTK Query that after the `addPost` and/or `editPost` mutations are called and completed, any cache data supplied with the `'Post'` tag is no longer valid. If a component is currently subscribed to the cached data for a `'Post'` tag after the above mutations are called and complete, it will automatically re-fetch in order to retrieve up to date data from the server.\n\nAn example scenario would be like so:\n\n1. A component is rendered which is using the `useGetPostsQuery()` hook to subscribe to that endpoint's cached data\n2. The `/posts` request is fired off, and server responds with posts with IDs 1, 2 & 3\n3. The `getPosts` endpoint stores the received data in the cache, and internally registers that the following tags have been provided:\n   <!-- prettier-ignore -->\n   ```js\n   [\n     { type: 'Post', id: 1 },\n     { type: 'Post', id: 2 },\n     { type: 'Post', id: 3 },\n   ]\n   ```\n4. The `editPost` mutation is fired off to alter a particular post\n5. Upon completion, RTK Query internally registers that the `'Post'` tag is now invalidated, and removes the previously provided `'Post'` tags from the cache\n6. Since the `getPosts` endpoint has provided tags of type `'Post'` which now has invalid cache data, and the component is still subscribed to the data, the `/posts` request is automatically fired off again, fetching new data and registering new tags for the updated cached data\n\nFor more granular control over the invalidated data, invalidated `tags` can have an associated `id` in the same manner as `providesTags`. This enables a distinction between 'any of a particular tag type' and 'a specific instance of a particular tag type'.\n\nThe example below declares that the `editPost` mutation invalidates a specific instance of a `Post` tag, using the ID passed in when calling the mutation function:\n\n```ts title=\"Example of invalidating tags with IDs to the cache\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\nexport interface User {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post, User } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n  }),\n  tagTypes: ['Post', 'User'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => '/posts',\n      providesTags: (result, error, arg) =>\n        result\n          ? [...result.map(({ id }) => ({ type: 'Post' as const, id })), 'Post']\n          : ['Post'],\n    }),\n    getUsers: build.query<User[], void>({\n      query: () => '/users',\n      providesTags: ['User'],\n    }),\n    addPost: build.mutation<Post, Omit<Post, 'id'>>({\n      query: (body) => ({\n        url: 'post',\n        method: 'POST',\n        body,\n      }),\n      invalidatesTags: ['Post'],\n    }),\n    editPost: build.mutation<Post, Partial<Post> & Pick<Post, 'id'>>({\n      query: (body) => ({\n        url: `post/${body.id}`,\n        method: 'POST',\n        body,\n      }),\n      // highlight-start\n      invalidatesTags: (result, error, arg) => [{ type: 'Post', id: arg.id }],\n      // highlight-end\n    }),\n  }),\n})\n```\n\nFor the example above, rather than invalidating any tag with the type `'Post'`, calling the `editPost` mutation function will now only invalidate a tag for the provided `id`. I.e. if cached data from an endpoint does not provide a `'Post'` for that same `id`, it will remain considered as 'valid', and will not be triggered to automatically re-fetch.\n\n:::tip Using abstract tag IDs\nIn order to provide stronger control over invalidating the appropriate data, you can use an arbitrary ID such as `'LIST'` for a given tag. See [Advanced Invalidation with abstract tag IDs](#advanced-invalidation-with-abstract-tag-ids) for additional details.\n:::\n\n## Tag Invalidation Behavior\n\nThe matrix below shows examples of which invalidated tags will affect and invalidate which provided tags:\n\n<table className=\"checkbox-table\">\n  <thead>\n    <tr>\n      <th className=\"diagonal-cell\">\n        <div className=\"diagonal-cell--content\">\n          <div className=\"diagonal-cell--topRight\">Provided</div>\n          <div className=\"diagonal-cell--bottomLeft\">Invalidated</div>\n        </div>\n      </th>\n      <th>\n        <div>General tag A</div>\n        <div style={{ fontWeight: 'normal', fontSize: '0.9rem' }}>\n          {\"['Post']\"}\n          <br />\n          {'/'}\n          <br />\n          {\"[{ type: 'Post' }]\"}\n        </div>\n      </th>\n      <th>\n        <div>General tag B</div>\n        <div style={{ fontWeight: 'normal', fontSize: '0.9rem' }}>\n          {\"['User']\"}\n          <br />\n          {'/'}\n          <br />\n          {\"[{ type: 'User' }]\"}\n        </div>\n      </th>\n      <th>\n        <div>Specific tag A1</div>\n        <div style={{ fontWeight: 'normal', fontSize: '0.9rem' }}>\n          {\"[{ type: 'Post',\"}\n          <br />\n          {' id: 1 }]'}\n        </div>\n      </th>\n      <th>\n        <div>Specific tag A2</div>\n        <div style={{ fontWeight: 'normal', fontSize: '0.9rem' }}>\n          {\"[{ type: 'Post', id: 'LIST' }]\"}\n        </div>\n      </th>\n      <th>\n        <div>Specific tag B1</div>\n        <div style={{ fontWeight: 'normal', fontSize: '0.9rem' }}>\n          {\"[{ type: 'User',\"}\n          <br />\n          {' id: 1 }]'}\n        </div>\n      </th>\n      <th>\n        <div>Specific tag B2</div>\n        <div style={{ fontWeight: 'normal', fontSize: '0.9rem' }}>\n          {\"[{ type: 'User',\"}\n          <br />\n          {' id: 2 }]'}\n        </div>\n      </th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>\n        <div style={{ fontWeight: 'bold' }}>General tag A</div>\n        <div style={{ fontSize: '0.9rem' }}>\n          {\"['Post'] / [{ type: 'Post' }]\"}\n        </div>\n      </td>\n      <td>✔️</td>\n      <td></td>\n      <td>✔️</td>\n      <td>✔️</td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <td>\n        <div style={{ fontWeight: 'bold' }}>General tag B</div>\n        <div style={{ fontSize: '0.9rem' }}>\n          {\"['User'] /\"}\n          <br />\n          {\"[{ type: 'User' }]\"}\n        </div>\n      </td>\n      <td></td>\n      <td>✔️</td>\n      <td></td>\n      <td></td>\n      <td>✔️</td>\n      <td>✔️</td>\n    </tr>\n    <tr>\n      <td>\n        <div style={{ fontWeight: 'bold' }}>Specific tag A1</div>\n        <div style={{ fontSize: '0.9rem' }}>{\"[{ type: 'Post', id: 1 }]\"}</div>\n      </td>\n      <td></td>\n      <td></td>\n      <td>✔️</td>\n      <td></td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <td>\n        <div style={{ fontWeight: 'bold' }}>Specific tag A2</div>\n        <div style={{ fontSize: '0.9rem' }}>\n          {\"[{ type: 'Post', id: 'LIST' }]\"}\n        </div>\n      </td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>✔️</td>\n      <td></td>\n      <td></td>\n    </tr>\n    <tr>\n      <td>\n        <div style={{ fontWeight: 'bold' }}>Specific tag B1</div>\n        <div style={{ fontSize: '0.9rem' }}>{\"[{ type: 'User', id: 1 }]\"}</div>\n      </td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>✔️</td>\n      <td></td>\n    </tr>\n    <tr>\n      <td>\n        <div style={{ fontWeight: 'bold' }}>Specific tag B2</div>\n        <div style={{ fontSize: '0.9rem' }}>{\"[{ type: 'User', id: 2 }]\"}</div>\n      </td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td></td>\n      <td>✔️</td>\n    </tr>\n  </tbody>\n</table>\n\nThe invalidation behavior is summarized based on tag specificity in the sections below.\n\n### General tag\n\ne.g. `['Post'] / [{ type: 'Post' }]`\n\nWill `invalidate` any `provided` tag with the matching type, including general and specific tags.\n\nExample:  \nIf a general tag of `Post` was invalidated, endpoints whose data `provided` the following tags would all have their data invalidated:\n\n- `['Post']`\n- `[{ type: 'Post' }]`\n- `[{ type: 'Post' }, { type: 'Post', id: 1 }]`\n- `[{ type: 'Post', id: 1 }]`\n- `[{ type: 'Post', id: 1 }, { type: 'User' }]`\n- `[{ type: 'Post', id: 'LIST' }]`\n- `[{ type: 'Post', id: 1 }, { type: 'Post', id: 'LIST' }]`\n\nEndpoints whose data `provided` the following tags would _not_ have their data invalidated:\n\n- `['User']`\n- `[{ type: 'User' }]`\n- `[{ type: 'User', id: 1 }]`\n- `[{ type: 'User', id: 'LIST' }]`\n- `[{ type: 'User', id: 1 }, { type: 'User', id: 'LIST' }]`\n\n### Specific tag\n\ne.g. `[{ type: 'Post', id: 1 }]`\n\nWill `invalidate` any `provided` tag with both the matching type, _and_ matching id. Will not cause a `general` tag to be invalidated directly, but _might_ invalidate data for an endpoint that provides a `general` tag _if_ it also provides a matching `specific` tag.\n\nExample 1:\nIf a specific tag of `{ type: 'Post', id: 1 }` was invalidated, endpoints whose data `provided` the following tags would all have their data invalidated:\n\n- `[{ type: 'Post' }, { type: 'Post', id: 1 }]`\n- `[{ type: 'Post', id: 1 }]`\n- `[{ type: 'Post', id: 1 }, { type: 'User' }]`\n- `[{ type: 'Post', id: 1 }, { type: 'Post', id: 'LIST' }]`\n\nEndpoints whose data `provided` the following tags would _not_ have their data invalidated:\n\n- `['Post']`\n- `[{ type: 'Post' }]`\n- `[{ type: 'Post', id: 'LIST' }]`\n- `['User']`\n- `[{ type: 'User' }]`\n- `[{ type: 'User', id: 1 }]`\n- `[{ type: 'User', id: 'LIST' }]`\n- `[{ type: 'User', id: 1 }, { type: 'User', id: 'LIST' }]`\n\nExample 2:\nIf a specific tag of `{ type: 'Post', id: 'LIST' }` was invalidated, endpoints whose data `provided` the following tags would all have their data invalidated:\n\n- `[{ type: 'Post', id: 'LIST' }]`\n- `[{ type: 'Post', id: 1 }, { type: 'Post', id: 'LIST' }]`\n\nEndpoints whose data `provided` the following tags would _not_ have their data invalidated:\n\n- `['Post']`\n- `[{ type: 'Post' }]`\n- `[{ type: 'Post' }, { type: 'Post', id: 1 }]`\n- `[{ type: 'Post', id: 1 }]`\n- `[{ type: 'Post', id: 1 }, { type: 'User' }]`\n- `['User']`\n- `[{ type: 'User' }]`\n- `[{ type: 'User', id: 1 }]`\n- `[{ type: 'User', id: 'LIST' }]`\n- `[{ type: 'User', id: 1 }, { type: 'User', id: 'LIST' }]`\n\n## Recipes\n\n### Advanced Invalidation with abstract tag IDs\n\nWhile using an 'entity ID' for a tag `id` is a common use case, the `id` property is not intended to be limited to database IDs alone. The `id` is simply a way to label a subset of a particular collection of data for a particular `tag type`.\n\nA powerful use-case is to use an ID like `'LIST'` as a label for data provided by a bulk query, _as well as_ using entity IDs for the individual items. Doing so allows future `mutations` to declare whether they invalidate the data only if it contains a particular item (e.g. `{ type: 'Post', id: 5 }`), or invalidate the data if it is a `'LIST'` (e.g. `{ type: 'Post', id: 'LIST' }`).\n\n:::info 'LIST' Tag and IDs\n\n1. `LIST` is an arbitrary string - technically speaking, you could use anything you want here, such as `ALL` or `*`. The important thing when choosing a custom id is to make sure there is no possibility of it colliding with an id that is returned by a query result. If you have unknown ids in your query results and don't want to risk it, you can go with point 3 below.\n2. You can add _many_ tag types for even more control\n   - `[{ type: 'Posts', id: 'LIST' }, { type: 'Posts', id: 'SVELTE_POSTS' }, { type: 'Posts', id: 'REACT_POSTS' }]`\n3. If the concept of using an `id` like 'LIST' seems strange to you, you can always add another `tagType` and invalidate its root, but we recommend using the `id` approach as shown.\n\n:::\n\nWe can compare the scenarios below to see how using a `'LIST'` id can be leveraged to optimize behavior.\n\n#### Invalidating everything of a type\n\n```ts title=\"API Definition\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\nexport interface User {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Post, User } from './types'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  tagTypes: ['Posts'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => 'posts',\n      providesTags: (result) =>\n        result ? result.map(({ id }) => ({ type: 'Posts', id })) : ['Posts'],\n    }),\n    addPost: build.mutation<Post, Partial<Post>>({\n      query: (body) => ({\n        url: `post`,\n        method: 'POST',\n        body,\n      }),\n      invalidatesTags: ['Posts'],\n    }),\n    getPost: build.query<Post, number>({\n      query: (id) => `post/${id}`,\n      providesTags: (result, error, id) => [{ type: 'Posts', id }],\n    }),\n  }),\n})\n\nexport const { useGetPostsQuery, useGetPostQuery, useAddPostMutation } = api\n```\n\n```tsx no-transpile title=\"App.tsx\"\nfunction App() {\n  const { data: posts } = useGetPostsQuery()\n  const [addPost] = useAddPostMutation()\n\n  return (\n    <div>\n      <AddPost onAdd={addPost} />\n      <PostsList />\n      {/* Assume each PostDetail is subscribed via `const {data} = useGetPostQuery(id)` */}\n      <PostDetail id={1} />\n      <PostDetail id={2} />\n      <PostDetail id={3} />\n    </div>\n  )\n}\n```\n\n**What to expect**\n\nWhen `addPost` is triggered, it would cause each `PostDetail` component to go back into a `isFetching` state because `addPost` invalidates the root tag, which causes _every query_ that provides 'Posts' to be re-run. In most cases, this may not be what you want to do. Imagine if you had 100 posts on the screen that all subscribed to a `getPost` query – in this case, you'd create 100 requests and send a ton of unnecessary traffic to your server, which we're trying to avoid in the first place! Even though the user would still see the last good cached result and potentially not notice anything other than their browser hiccuping, you still want to avoid this.\n\n#### Selectively invalidating lists\n\n```ts title=\"API Definition\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\nexport interface User {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Post, User } from './types'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  tagTypes: ['Posts'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => 'posts',\n      providesTags: (result) =>\n        result\n          ? [\n              ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n              { type: 'Posts', id: 'LIST' },\n            ]\n          : [{ type: 'Posts', id: 'LIST' }],\n    }),\n    addPost: build.mutation<Post, Partial<Post>>({\n      query(body) {\n        return {\n          url: `post`,\n          method: 'POST',\n          body,\n        }\n      },\n      invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n    }),\n    getPost: build.query<Post, number>({\n      query: (id) => `post/${id}`,\n      providesTags: (result, error, id) => [{ type: 'Posts', id }],\n    }),\n  }),\n})\n\nexport const { useGetPostsQuery, useAddPostMutation, useGetPostQuery } = api\n```\n\n```tsx no-transpile title=\"App.tsx\"\nfunction App() {\n  const { data: posts } = useGetPostsQuery()\n  const [addPost] = useAddPostMutation()\n\n  return (\n    <div>\n      <AddPost onAdd={addPost} />\n      <PostsList />\n      {/* Assume each PostDetail is subscribed via `const {data} = useGetPostQuery(id)` */}\n      <PostDetail id={1} />\n      <PostDetail id={2} />\n      <PostDetail id={3} />\n    </div>\n  )\n}\n```\n\n**What to expect**\n\nWhen `addPost` is fired, it will only cause the `PostsList` to go into an `isFetching` state because `addPost` only invalidates the `'LIST'` id, which causes `getPosts` to rerun (because it provides that specific id). So in your network tab, you would only see 1 new request fire for `GET /posts`. As the singular `getPost` queries have not been invalidated, they will not re-run as a result of `addPost`.\n\n:::info\n\nIf you intend for the `addPost` mutation to refresh all posts including individual `PostDetail` components while still only making 1 new `GET /posts` request, this can be done by selecting a part of the data using [`selectFromResult`](./queries.mdx#selecting-data-from-a-query-result).\n\n:::\n\n### Providing errors to the cache\n\nThe information provided to the cache is not limited to successful data fetches. The concept can be used to inform RTK Query that when a particular failure has been encountered, to `provide` a specific `tag` for that failed cache data. A separate endpoint can then `invalidate` the data for that `tag`, telling RTK Query to re-attempt the previously failed endpoints if a component is still subscribed to the failed data.\n\nThe example below demonstrates an example with the following behavior:\n\n- Provides an `UNAUTHORIZED` cache tag if a query fails with an error code of `401 UNAUTHORIZED`\n- Provides an `UNKNOWN_ERROR` cache tag if a query fails with a different error\n- Enables a 'login' mutation, which when _successful_, will `invalidate` the data with the `UNAUTHORIZED` tag.  \n  This will trigger the `postById` endpoint to re-fire if:\n  1. The last call for `postById` had encountered an unauthorized error, and\n  2. A component is still subscribed to the cached data\n- Enables a 'refetchErroredQueries' mutation which when _called_, will `invalidate` the data with the `UNKNOWN_ERROR` tag.  \n  This will trigger the `postById` endpoint to re-fire if:\n  1. The last call for `postById` had encountered an unknown error, and\n  2. A component is still subscribed to the cached data\n\n```ts\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\nexport interface LoginResponse {}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport { Post, LoginResponse } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n  tagTypes: ['Post', 'UNAUTHORIZED', 'UNKNOWN_ERROR'],\n  endpoints: (build) => ({\n    postById: build.query<Post, number>({\n      query: (id) => `post/${id}`,\n      providesTags: (result, error, id) =>\n        result\n          ? [{ type: 'Post', id }]\n          : error?.status === 401\n            ? ['UNAUTHORIZED']\n            : ['UNKNOWN_ERROR'],\n    }),\n    login: build.mutation<LoginResponse, void>({\n      query: () => '/login',\n      // on successful login, will refetch all currently\n      // 'UNAUTHORIZED' queries\n      invalidatesTags: (result) => (result ? ['UNAUTHORIZED'] : []),\n    }),\n    refetchErroredQueries: build.mutation<null, void>({\n      queryFn: () => ({ data: null }),\n      invalidatesTags: ['UNKNOWN_ERROR'],\n    }),\n  }),\n})\n```\n\n### Abstracting common provides/invalidates usage\n\nThe code written to `provide` & `invalidate` tags for a given API slice will be dependent on multiple factors, including:\n\n- The shape of the data returned by your backend\n- Which tags you expect a given query endpoint to provide\n- Which tags you expect a given mutation endpoint to invalidate\n- The extent that you wish to use the invalidation feature for\n\nWhen declaring your API slice, you may feel as though you're duplicating your code. For instance, for two separate endpoints that both provide a list of a particular entity, the `providesTags` declaration may only differ in the `tagType` provided.\n\ne.g.\n\n```ts\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\nexport interface User {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post, User } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n  tagTypes: ['Post', 'User'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => `posts`,\n      // highlight-start\n      providesTags: (result) =>\n        result\n          ? [\n              { type: 'Post', id: 'LIST' },\n              ...result.map(({ id }) => ({ type: 'Post' as const, id })),\n            ]\n          : [{ type: 'Post', id: 'LIST' }],\n      // highlight-end\n    }),\n    getUsers: build.query<User[], void>({\n      query: () => `users`,\n      // highlight-start\n      providesTags: (result) =>\n        result\n          ? [\n              { type: 'User', id: 'LIST' },\n              ...result.map(({ id }) => ({ type: 'User' as const, id })),\n            ]\n          : [{ type: 'User', id: 'LIST' }],\n      // highlight-end\n    }),\n  }),\n})\n```\n\nYou may find it beneficial to define helper functions designed for your particular api to reduce this boilerplate across endpoint definitions, e.g.\n\n```ts\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\nexport interface User {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post, User } from './types'\n\n// highlight-start\nfunction providesList<R extends { id: string | number }[], T extends string>(\n  resultsWithIds: R | undefined,\n  tagType: T,\n) {\n  return resultsWithIds\n    ? [\n        { type: tagType, id: 'LIST' },\n        ...resultsWithIds.map(({ id }) => ({ type: tagType, id })),\n      ]\n    : [{ type: tagType, id: 'LIST' }]\n}\n// highlight-end\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n  tagTypes: ['Post', 'User'],\n  endpoints: (build) => ({\n    getPosts: build.query({\n      query: () => `posts`,\n      // highlight-start\n      providesTags: (result) => providesList(result, 'Post'),\n      // highlight-end\n    }),\n    getUsers: build.query({\n      query: () => `users`,\n      // highlight-start\n      providesTags: (result) => providesList(result, 'User'),\n      // highlight-end\n    }),\n  }),\n})\n```\n\nAn example of various abstractions for tag providing/invalidating designed for common rest data formats can be seen in the following gist, including typescript support, and factoring both ['LIST' style advanced tag invalidation](#advanced-invalidation-with-abstract-tag-ids) and ['error' style tag invalidation](#providing-errors-to-the-cache): **[RTK Query cache utils](https://gist.github.com/Shrugsy/6b6af02aef1f783df9d636526c1e05fa)**.\n"
  },
  {
    "path": "docs/rtk-query/usage/cache-behavior.mdx",
    "content": "---\nid: cache-behavior\ntitle: Cache Behavior\nsidebar_label: Cache Behavior\nhide_title: true\ndescription: 'RTK Query > Usage > Cache Behavior: defaults, cache lifetimes, and tradeoffs'\n---\n\n&nbsp;\n\n# Cache Behavior\n\nA key feature of RTK Query is its management of cached data. When data is fetched from the server, RTK Query will store the data in the Redux store as a 'cache'. When an additional request is performed for the same data, RTK Query will provide the existing cached data rather than sending an additional request to the server.\n\nRTK Query provides a number of concepts and tools to manipulate the cache behavior and adjust it to your needs.\n\n## Default Cache Behavior\n\nWith RTK Query, caching is based on:\n\n- API endpoint definitions\n- The serialized query parameters used when components subscribe to data from an endpoint\n- Active subscription reference counts\n\nWhen a subscription is started, the parameters used with the endpoint are serialized and stored internally as a `queryCacheKey` for the request. Any future request that produces the same `queryCacheKey` (i.e. called with the same parameters, factoring serialization) will be de-duped against the original, and will share the same data and updates. i.e. two separate components performing the same request will use the same cached data.\n\nWhen a request is attempted, if the data already exists in the cache, then that data is served and no new request is sent to the server. Otherwise, if the data does not exist in the cache, then a new request is sent, and the returned response is stored in the cache.\n\nSubscriptions are reference-counted. Additional subscriptions that ask for the same endpoint+params increment the reference count. As long as there is an active 'subscription' to the data (e.g. if a component is mounted that calls a `useQuery` hook for the endpoint), then the data will remain in the cache. Once the subscription is removed (e.g. when last component subscribed to the data unmounts), after an amount of time (default 60 seconds), the data will be removed from the cache. The expiration time can be configured with the `keepUnusedDataFor` property for the [API definition as a whole](../api/createApi.mdx#keepunuseddatafor), as well as on a [per-endpoint](../api/createApi.mdx#keepunuseddatafor-1) basis.\n\n### Cache lifetime & subscription example\n\nImagine an endpoint that expects an `id` as the query param, and 4 components mounted which are requesting data from this same endpoint:\n\n```ts no-transpile\nimport { useGetUserQuery } from './api.ts'\n\nfunction ComponentOne() {\n  // component subscribes to the data\n  const { data } = useGetUserQuery(1)\n\n  return <div>...</div>\n}\n\nfunction ComponentTwo() {\n  // component subscribes to the data\n  const { data } = useGetUserQuery(2)\n\n  return <div>...</div>\n}\n\nfunction ComponentThree() {\n  // component subscribes to the data\n  const { data } = useGetUserQuery(3)\n\n  return <div>...</div>\n}\n\nfunction ComponentFour() {\n  // component subscribes to the *same* data as ComponentThree,\n  // as it has the same query parameters\n  const { data } = useGetUserQuery(3)\n\n  return <div>...</div>\n}\n```\n\nWhile four components are subscribed to the endpoint, there are only three distinct combinations of endpoint + query parameters. Query parameters `1` and `2` will each have a single subscriber, while query parameter `3` has two subscribers. RTK Query will make three distinct fetches; one for each unique set of query parameters per endpoint.\n\nData is kept in the cache as long as at least one active subscriber is interested in that endpoint + parameter combination. When the subscriber reference count reaches zero, a timer is set, and if there are no new subscriptions to that data by the time the timer expires, the cached data will be removed. The default expiration is 60 seconds, which can be configured both for the [API definition as a whole](../api/createApi.mdx#keepunuseddatafor), as well as on a [per-endpoint](../api/createApi.mdx#keepunuseddatafor-1) basis.\n\nIf 'ComponentThree' is unmounted in the example above, regardless of how much time passes, the data will remain in the cache due to 'ComponentFour' still being subscribed to the same data, and the subscribe reference count will be `1`. However, once 'ComponentFour' unmounts, the subscriber reference count will be `0`. The data will remain in the cache for the remainder of the expiration time. If no new subscription has been created before the timer expires, the cached data will finally be removed.\n\n## Manipulating Cache Behavior\n\nOn top of the default behavior, RTK Query provides a number of methods to re-fetch data earlier in scenarios where it should be considered invalid, or is otherwise deemed suitable to be 'refreshed'.\n\n### Reducing subscription time with `keepUnusedDataFor`\n\nAs mentioned above under [Default Cache Behavior](#default-cache-behavior) and [Cache lifetime & subscription example](#cache-lifetime--subscription-example), by default, data will remain in the cache for 60 seconds after the subscriber reference count hits zero.\n\nThis value can be configured using the `keepUnusedDataFor` option for both the API definition, as well as per-endpoint. Note that the per-endpoint version, if provided, will overrule a setting on the API definition.\n\nProviding a value to `keepUnusedDataFor` as a number in seconds specifies how long the data should be kept in the cache after the subscriber reference count reaches zero.\n\n```ts title=\"keepUnusedDataFor configuration\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Post } from './types'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  // highlight-start\n  // global configuration for the api\n  keepUnusedDataFor: 30,\n  // highlight-end\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], number>({\n      query: () => `posts`,\n      // highlight-start\n      // configuration for an individual endpoint, overriding the api setting\n      keepUnusedDataFor: 5,\n      // highlight-end\n    }),\n  }),\n})\n```\n\n### Re-fetching on demand with `refetch`/`initiate`\n\nIn order to achieve complete granular control over re-fetching data, you can use the `refetch` function returned as a result property from a [`useQuery`](../api/created-api/hooks.mdx#usequery) or [`useQuerySubscription`](../api/created-api/hooks.mdx#usequerysubscription) hook.\n\nCalling the `refetch` function will force refetch the associated query.\n\nAlternatively, you can dispatch the `initiate` thunk action for an endpoint, passing the option `forceRefetch: true` to the thunk action creator for the same effect.\n\n```tsx no-transpile title=\"Force refetch example\"\nimport { useDispatch } from 'react-redux'\nimport { api, useGetPostsQuery } from './api'\n\nconst Component = () => {\n  const dispatch = useDispatch()\n  const { data, refetch } = useGetPostsQuery({ count: 5 })\n\n  function handleRefetchOne() {\n    // force re-fetches the data\n    refetch()\n  }\n\n  function handleRefetchTwo() {\n    // has the same effect as `refetch` for the associated query\n    dispatch(\n      api.endpoints.getPosts.initiate(\n        { count: 5 },\n        { subscribe: false, forceRefetch: true },\n      ),\n    )\n  }\n\n  return (\n    <div>\n      <button onClick={handleRefetchOne}>Force re-fetch 1</button>\n      <button onClick={handleRefetchTwo}>Force re-fetch 2</button>\n    </div>\n  )\n}\n```\n\n### Encouraging re-fetching with `refetchOnMountOrArgChange`\n\nQueries can be encouraged to re-fetch more frequently than usual via the [`refetchOnMountOrArgChange`](../api/createApi.mdx#refetchonmountorargchange) property. This can be passed to the endpoint as a whole, to individual hook calls, or when dispatching the [`initiate`](../api/created-api/endpoints.mdx#initiate) action (the name of the action creator's option is `forceRefetch`).\n\n`refetchOnMountOrArgChange` is used to encourage re-fetching in additional situations where the default behavior would instead serve cached data.\n\n`refetchOnMountOrArgChange` accepts either a boolean value, or a number as time in seconds.\n\nPassing `false` (the default value) for this property will use the default behavior [described above](#default-cache-behavior).\n\nPassing `true` for this property will cause the endpoint to always refetch when a new subscriber to the query is added. If passed to an individual hook call and not the api definition itself, then this applies only to that hook call. I.e., when the component calling the hook mounts, or the argument changes, it will always refetch, regardless of whether cached data for the endpoint + arg combination already exists.\n\nPassing a `number` as a value in seconds will use the following behavior:\n\n- At the time a query subscription is created:\n  - if there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp for that query,\n  - It will refetch if the provided amount of time in seconds has elapsed.\n- If there is no query, it will fetch the data.\n- If there is an existing query, but the amount of time specified since the last query has not elapsed, it will serve the existing cached data.\n\n```ts title=\"Configuring re-fetching on subscription if data exceeds a given time\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Post } from './types'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  // highlight-start\n  // global configuration for the api\n  refetchOnMountOrArgChange: 30,\n  // highlight-end\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], number>({\n      query: () => `posts`,\n    }),\n  }),\n})\n```\n\n```tsx no-transpile title=\"Forcing refetch on component mount\"\nimport { useGetPostsQuery } from './api'\n\nconst Component = () => {\n  const { data } = useGetPostsQuery(\n    { count: 5 },\n    // highlight-start\n    // this overrules the api definition setting,\n    // forcing the query to always fetch when this component is mounted\n    { refetchOnMountOrArgChange: true },\n    // highlight-end\n  )\n\n  return <div>...</div>\n}\n```\n\n### Re-fetching on window focus with `refetchOnFocus`\n\nThe [`refetchOnFocus`](../api/createApi.mdx#refetchonfocus) option allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n\nIf you specify this option alongside `skip: true`, this will not be evaluated until skip is false.\n\nNote that this requires [`setupListeners`](../api/setupListeners.mdx) to have been called.\n\nThis option is available on both the api definition with [`createApi`](../api/createApi.mdx), as well as on the [`useQuery`](../api/created-api/hooks.mdx#usequery), [`useQuerySubscription`](../api/created-api/hooks.mdx#usequerysubscription), [`useLazyQuery`](../api/created-api/hooks.mdx#uselazyquery), and [`useLazyQuerySubscription`](../api/created-api/hooks.mdx#uselazyquerysubscription) hooks.\n\n```ts title=\"src/services/api.ts\"\n// file: src/services/types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: src/services/api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Post } from './types'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  // highlight-start\n  // global configuration for the api\n  refetchOnFocus: true,\n  // highlight-end\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], number>({\n      query: () => `posts`,\n    }),\n  }),\n})\n```\n\n```ts title=\"src/store.ts\"\n// file: src/services/types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: src/services/api.ts noEmit\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Post } from './types'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  // highlight-start\n  // global configuration for the api\n  refetchOnFocus: true,\n  // highlight-end\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], number>({\n      query: () => `posts`,\n    }),\n  }),\n})\n\n// file: src/store.ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport { setupListeners } from '@reduxjs/toolkit/query'\nimport { api } from './services/api'\n\nexport const store = configureStore({\n  reducer: {\n    [api.reducerPath]: api.reducer,\n  },\n  middleware: (gDM) => gDM().concat(api.middleware),\n})\n\n// highlight-start\n// enable listener behavior for the store\nsetupListeners(store.dispatch)\n// highlight-end\n\nexport type RootState = ReturnType<typeof store.getState>\n```\n\n### Re-fetching on network reconnection with `refetchOnReconnect`\n\nThe [`refetchOnReconnect`](../api/createApi.mdx#refetchonreconnect) option on [`createApi`](../api/createApi.mdx) allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n\nIf you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n\nNote that this requires [`setupListeners`](../api/setupListeners.mdx) to have been called.\n\nThis option is available on both the api definition with [`createApi`](../api/createApi.mdx), as well as on the [`useQuery`](../api/created-api/hooks.mdx#usequery), [`useQuerySubscription`](../api/created-api/hooks.mdx#usequerysubscription), [`useLazyQuery`](../api/created-api/hooks.mdx#uselazyquery), and [`useLazyQuerySubscription`](../api/created-api/hooks.mdx#uselazyquerysubscription) hooks.\n\n```ts title=\"src/services/api.ts\"\n// file: src/services/types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: src/services/api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Post } from './types'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  // highlight-start\n  // global configuration for the api\n  refetchOnReconnect: true,\n  // highlight-end\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], number>({\n      query: () => `posts`,\n    }),\n  }),\n})\n```\n\n```ts title=\"src/store.ts\"\n// file: src/services/types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: src/services/api.ts noEmit\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Post } from './types'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  // highlight-start\n  // global configuration for the api\n  refetchOnReconnect: true,\n  // highlight-end\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], number>({\n      query: () => `posts`,\n    }),\n  }),\n})\n\n// file: src/store.ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport { setupListeners } from '@reduxjs/toolkit/query'\nimport { api } from './services/api'\n\nexport const store = configureStore({\n  reducer: {\n    [api.reducerPath]: api.reducer,\n  },\n  middleware: (gDM) => gDM().concat(api.middleware),\n})\n\n// highlight-start\n// enable listener behavior for the store\nsetupListeners(store.dispatch)\n// highlight-end\n\nexport type RootState = ReturnType<typeof store.getState>\n```\n\n### Re-fetching after mutations by invalidating cache tags\n\nRTK Query uses an optional [cache tag](./automated-refetching.mdx#cache-tags) system to automate re-fetching for query endpoints that have data affected by mutation endpoints.\n\nSee [Automated Re-fetching](./automated-refetching.mdx) for full details on this concept.\n\n## Tradeoffs\n\n### No Normalized or De-duplicated Cache\n\nRTK Query deliberately **does _not_ implement a cache that would deduplicate identical items across multiple requests**. There are several reasons for this:\n\n- A fully normalized shared-across-queries cache is a _hard_ problem to solve\n- We don't have the time, resources, or interest in trying to solve that right now\n- In many cases, simply re-fetching data when it's invalidated works well and is easier to understand\n- At a minimum, RTKQ can help solve the general use case of \"fetch some data\", which is a big pain point for a lot of people\n\nAs an example, say that we have an API slice with `getTodos` and `getTodo` endpoints, and our components make the following queries:\n\n- `getTodos()`\n- `getTodos({filter: 'odd'})`\n- `getTodo({id: 1})`\n\nEach of these query results would include a Todo object that looks like `{id: 1}`.\n\nIn a fully normalized de-duplicating cache, only a single copy of this Todo object would be stored. However, RTK Query saves each query result independently in the cache. So, this would result in three separate copies of this Todo being cached in the Redux store. However, if all the endpoints are consistently providing the same tags (such as `{type: 'Todo', id: 1}`), then invalidating that tag will force all the matching endpoints to refetch their data for consistency.\n\nThe Redux docs have always recommended [keeping data in a normalized lookup table](https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape) to enable easily finding items by ID and updating them in the store, and [RTK's `createEntityAdapter`](../../api/createEntityAdapter.mdx) was designed to help manage normalized state. Those concepts are still valuable and don't go away. However, if you're using RTK Query to manage caching data, there's less need to manipulate the data that way yourself.\n\nThere are a couple additional points that can help here:\n\n- The generated query hooks have [a `selectFromResult` option](../api/created-api/hooks.mdx#usequery) that allow components to read individual pieces of data from a query result. As an example, a `<TodoList>` component might call `useTodosQuery()`, and each individual `<TodoListItem>` could use the same query hook but select from the result to get the right todo object.\n- You can use the [`transformResponse` endpoint option](../api/createApi.mdx#transformresponse) to modify the fetched data so that it's [stored in a different shape](./customizing-queries.mdx#customizing-query-responses-with-transformresponse), such as using `createEntityAdapter` to normalize the data _for this one response_ before it's inserted into the cache.\n\n### Further information\n\n- [Reddit: discussion of why RTKQ doesn't have a normalized cache, and tradeoffs](https://www.reddit.com/r/reactjs/comments/my9vrq/redux_toolkit_v16_alpha1_rtk_query_apis/gvxi5t7/)\n\n## Examples\n\n### Cache Subscription Lifetime Demo\n\nThis example is a live demo of how the subscriber reference count and the value of `keepUnusedDataFor` interact with each other. The `Subscriptions` and `Queries` (including the cached data) are shown in the demo for you to visualize (note that this can also be viewed in the [Redux Devtools Extension](https://github.com/reduxjs/redux-devtools)).\n\nTwo components are mounted, each with the same endpoints query (`useGetUsersQuery(2)`). You will be able to observe that when toggling off the components, the subscriber reference count will be reduced. After toggling off both components such that the subscriber reference count reaches zero, you will observe the cached data under the `Queries` section will persist for 5 seconds (the value of `keepUnusedDataFor` provided for the endpoint in this demo). If the subscriber reference count remains at 0 for the full duration, the cached data will then be removed from the store.\n\n<iframe\n  src=\"https://codesandbox.io/embed/rtk-query-cache-subscription-lifetime-example-77tn4?fontsize=12&runonclick=1&hidenavigation=1&theme=dark&module=%2Fsrc%2Fservice%2Findex.ts\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"rtk-query-cache-subscription-lifetime-example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n"
  },
  {
    "path": "docs/rtk-query/usage/code-generation.mdx",
    "content": "---\nid: code-generation\ntitle: Code Generation\nsidebar_label: Code Generation\nhide_title: true\ndescription: 'RTK Query > Usage > Code Generation: automated creation of API code'\n---\n\n&nbsp;\n\n# Code Generation\n\nRTK Query's API and architecture is oriented around declaring API endpoints up front. This lends itself well to automatically generating API slice definitions from external API schema definitions, such as OpenAPI and GraphQL.\n\nWe have early previews of code generation capabilities available as separate tools.\n\n## GraphQL\n\nWe provide a [Plugin for GraphQL Codegen](https://www.graphql-code-generator.com/docs/plugins/typescript-rtk-query). You can find the documentation to that on the graphql-codegen homepage.\n\nFor a full example on how to use it, you can see [this example project](https://github.com/reduxjs/redux-toolkit/tree/master/examples/query/react/graphql-codegen).\n\n## OpenAPI\n\nWe provide a package for RTK Query code generation from OpenAPI schemas. It is published as `@rtk-query/codegen-openapi` and you can find the source code at [`packages/rtk-query-codegen-openapi`](https://github.com/reduxjs/redux-toolkit/tree/master/packages/rtk-query-codegen-openapi).\n\n### Usage\n\nCreate an empty api using `createApi` like\n\n```ts no-transpile title=\"src/store/emptyApi.ts\"\n// Or from '@reduxjs/toolkit/query' if not using the auto-generated hooks\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\n// initialize an empty api service that we'll inject endpoints into later as needed\nexport const emptySplitApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: () => ({}),\n})\n```\n\nGenerate a config file (json, js or ts) with contents like\n\n```ts no-transpile title=\"openapi-config.ts\"\nimport type { ConfigFile } from '@rtk-query/codegen-openapi'\n\nconst config: ConfigFile = {\n  schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  apiImport: 'emptySplitApi',\n  outputFile: './src/store/petApi.ts',\n  exportName: 'petApi',\n  hooks: true,\n}\n\nexport default config\n```\n\nand then call the code generator:\n\n```bash\nnpx @rtk-query/codegen-openapi openapi-config.ts\n```\n\n#### Generating tags\n\nIf your OpenAPI specification uses [tags](https://swagger.io/docs/specification/grouping-operations-with-tags/), you can specify the `tag` option to the codegen.\nThat will result in all generated endpoints having `providesTags`/`invalidatesTags` declarations for the `tags` of their respective operation definition.\n\nNote that this will only result in string tags with no ids, so it might lead to scenarios where too much is invalidated and unnecessary requests are made on mutation.\n\nIn that case you have two options:\n\n1. Use [`endpointOverrides`](#overriding-tags) to customize tags for specific endpoints during code generation\n2. Use [`enhanceEndpoints`](../api/created-api/code-splitting.mdx) after generation to manually add more specific `providesTags`/`invalidatesTags` with IDs\n\n### Programmatic usage\n\n```ts no-transpile title=\"src/store/petApi.ts\"\nimport { generateEndpoints } from '@rtk-query/codegen-openapi'\n\nconst api = await generateEndpoints({\n  apiFile: './fixtures/emptyApi.ts',\n  schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n  filterEndpoints: ['getPetById', 'addPet'],\n  hooks: true,\n})\n```\n\n#### With Node.js Child process\n\n```ts no-transpile title=\"bin/openapi-codegen.ts\"\nimport { exec } from 'node:child_process'\n\nconst cliPath = require.resolve('@rtk-query/codegen-openapi/cli')\n\n// you can also use esbuild-runner (esr) or ts-node instead of tsx\nexec(`tsx ${cliPath} config.ts`)\n```\n\n### Config file options\n\n#### Simple usage\n\n```ts no-transpile\ninterface SimpleUsage {\n  apiFile: string\n  schemaFile: string\n  apiImport?: string\n  exportName?: string\n  argSuffix?: string\n  operationNameSuffix?: string\n  responseSuffix?: string\n  hooks?:\n    | boolean\n    | { queries: boolean; lazyQueries: boolean; mutations: boolean }\n  tag?: boolean\n  outputFile: string\n  filterEndpoints?:\n    | string\n    | RegExp\n    | EndpointMatcherFunction\n    | Array<string | RegExp | EndpointMatcherFunction>\n  endpointOverrides?: EndpointOverrides[]\n  flattenArg?: boolean\n}\n\nexport type EndpointOverrides = {\n  pattern: EndpointMatcher\n} & AtLeastOneOf<{\n  type: 'mutation' | 'query'\n  parameterFilter: ParameterMatcher\n  providesTags: string[]\n  invalidatesTags: string[]\n}>\n  useEnumType?: boolean\n  outputRegexConstants?: boolean\n  httpResolverOptions?: SwaggerParser.HTTPResolverOptions\n}\n\nexport type EndpointMatcherFunction = (\n  operationName: string,\n  operationDefinition: OperationDefinition,\n) => boolean\n```\n\n#### Filtering endpoints\n\nIf you only want to include a few endpoints, you can use the `filterEndpoints` config option to filter your endpoints.\nNote that endpoints are transformed to camel case. For example, `login_user` will become `loginUser`.\n`filterEndpoints` will be checked against this camel case version of the endpoint.\n\n```ts no-transpile title=\"openapi-config.ts\"\nconst filteredConfig: ConfigFile = {\n  // ...\n  // should only have endpoints loginUser, placeOrder, getOrderById, deleteOrder\n  filterEndpoints: ['loginUser', /Order/],\n}\n```\n\n#### Endpoint overrides\n\nIf an endpoint is generated as a mutation instead of a query or the other way round, you can override that:\n\n```ts no-transpile title=\"openapi-config.ts\"\nconst withOverride: ConfigFile = {\n  // ...\n  endpointOverrides: [\n    {\n      pattern: 'loginUser',\n      type: 'mutation',\n    },\n  ],\n}\n```\n\nYou can also filter the parameters that are included for an endpoint, as long as they aren't a path parameter. This filter is of type `ParameterMatcher`. For example, to only include parameters that begin with \"x-\" for the 'loginUser' endpoint, see the below example.\n\n```ts no-transpile title=\"openapi-config.ts\"\nconst withOverride: ConfigFile = {\n  // ...\n  endpointOverrides: [\n    {\n      pattern: 'loginUser',\n      parameterFilter: /^x-/,\n    },\n  ],\n}\n```\n\nFor more complex requirements, consider the other possible matchers, such as a `ParameterMatcherFunction`. The below example filters out any parameters that are in the header of the request.\n\n```ts no-transpile title=\"openapi-config.ts\"\nconst withOverride: ConfigFile = {\n  // ...\n  endpointOverrides: [\n    {\n      pattern: /.*/,\n      parameterFilter: (_name, parameter) => parameter.in !== 'header',\n    },\n  ],\n}\n```\n\n#### Overriding tags\n\nYou can override the `providesTags` and `invalidatesTags` generated for any endpoint, regardless of whether the global `tag` option is enabled:\n\n```ts no-transpile title=\"openapi-config.ts\"\nconst withTagOverrides: ConfigFile = {\n  // ...\n  tag: true, // or false - overrides work either way\n  endpointOverrides: [\n    {\n      // Override the tags for a specific query\n      pattern: 'getPetById',\n      providesTags: ['SinglePet', 'PetDetails'],\n    },\n    {\n      // Remove auto-generated tags by providing an empty array\n      pattern: 'deletePet',\n      invalidatesTags: [],\n    },\n    {\n      // Add both providesTags AND invalidatesTags to any endpoint\n      pattern: 'updatePet',\n      providesTags: ['LastUpdatedPet'],\n      invalidatesTags: ['Pet', 'PetList'],\n    },\n  ],\n}\n```\n\n**Key behaviors:**\n\n- Tag overrides take precedence over auto-generated tags from the OpenAPI `tags` field\n- You can use an empty array (`[]`) to explicitly remove tags from an endpoint\n- Both `providesTags` and `invalidatesTags` can be set on any endpoint type (query or mutation)\n- Overrides work regardless of whether the global `tag: true` option is set\n\nThis is useful when:\n\n- The OpenAPI tags don't match your caching strategy\n- You need more specific cache invalidation than the default tag generation provides\n- A mutation should also provide tags (e.g., login returning user data)\n- A query should also invalidate tags (e.g., polling that triggers cache updates)\n\n:::note\nWhen using tag overrides with `tag: false`, the overridden tags will be emitted in the generated code, but they won't be automatically added to `addTagTypes`. You may need to manually add your custom tags to the base API's `tagTypes` array.\n:::\n\n#### Generating hooks\n\nSetting `hooks: true` will generate `useQuery` and `useMutation` hook exports. If you also want `useLazyQuery` hooks generated or more granular control, you can also pass an object in the shape of: `{ queries: boolean; lazyQueries: boolean; mutations: boolean }`.\n\n#### Generating regex constants for schema patterns\n\nIf your OpenAPI schema uses the [`pattern` keyword](https://swagger.io/docs/specification/data-models/data-types/#pattern) to specify regex validation on string properties, you can export these patterns as JavaScript regex constants by setting `outputRegexConstants: true`.\n\n```ts no-transpile title=\"openapi-config.ts\"\nconst config: ConfigFile = {\n  schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  outputFile: './src/store/petApi.ts',\n  outputRegexConstants: true,\n}\n```\n\nFor a schema with pattern-validated properties like:\n\n```yaml\nUser:\n  type: object\n  properties:\n    email:\n      type: string\n      pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'\n    phone:\n      type: string\n      pattern: '^\\+?[1-9]\\d{1,14}$'\n```\n\nThe codegen will generate:\n\n```ts no-transpile title=\"Generated output\"\nexport const userEmailPattern =\n  /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/\nexport const userPhonePattern = /^\\+?[1-9]\\d{1,14}$/\n```\n\nThese constants can be used for client-side validation to ensure consistency with API expectations.\n\n:::note\nOnly string-type properties with non-empty `pattern` values will generate constants. The constant name follows the format `{typeName}{propertyName}Pattern` in camelCase.\n:::\n\n#### Multiple output files\n\n```ts no-transpile title=\"openapi-config.ts\"\nconst config: ConfigFile = {\n  schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  outputFiles: {\n    './src/store/user.ts': {\n      filterEndpoints: [/user/i],\n    },\n    './src/store/order.ts': {\n      filterEndpoints: [/order/i],\n    },\n    './src/store/pet.ts': {\n      filterEndpoints: [/pet/i],\n    },\n  },\n}\n```\n\n#### Custom HTTP resolver options\n\nIf you need to customize the HTTP request issued to your server, you user the `httpResolverOptions` option. This object is passed directly to the `SwaggerParser` instance that fetches the OpenAPI schema.\n\nFor example, you can pass custom headers or set a custom request timeout.\n\n```ts no-transpile title=\"openapi-config.ts\"\nconst config: ConfigFile = {\n  schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  outputFile: './src/store/petApi.ts',\n  httpResolverOptions: {\n    timeout: 30_000,\n    headers: {\n      Accept: 'application/json',\n      Authorization: 'Basic cmVkdXgtdG9vbGtpdDppcy1ncmVhdA==',\n    },\n  },\n}\n```\n"
  },
  {
    "path": "docs/rtk-query/usage/code-splitting.mdx",
    "content": "---\nid: code-splitting\ntitle: Code Splitting\nsidebar_label: Code Splitting\nhide_title: true\ndescription: 'RTK Query > Usage > Code Splitting: dynamic injection of endpoints'\n---\n\n&nbsp;\n\n# Code Splitting\n\n## Overview\n\nBy default, an RTK Query API definition normally has all of the endpoint definitions in a single file. However, in larger applications this can result in very large files that may be harder to maintain. It also means that all of the relevant code is being imported right away.\n\nRTK Query allows dynamically injecting endpoint definitions into an existing API service object. This enables splitting up endpoints into multiple files for maintainability, as well as lazy-loading endpoint definitions and associated code to trim down initial bundle sizes. This can be very beneficial for larger applications that may have _many_ endpoints.\n\n## Injecting Endpoints\n\n`api.injectEndpoints` accepts a collection of endpoint definitions (same as `createApi`), as well as an optional `overrideExisting` parameter.\n\nCalling `api.injectEndpoints` will inject the endpoints into the original API service object, modifying it immediately. It returns **the _same_ API service object reference**. If you're using TypeScript, the return value has the TS types for the new endpoints included. (Unfortunately, it cannot modify the types for the original API reference.)\n\nA typical approach would be to have one empty central API slice definition:\n\n```ts title=\"Basic setup\"\n// Or from '@reduxjs/toolkit/query' if not using the auto-generated hooks\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\n// initialize an empty api service that we'll inject endpoints into later as needed\nexport const emptySplitApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: () => ({}),\n})\n```\n\nand then inject the api endpoints in other files and export them from there - that way you will be sure to always import the endpoints in a way that they are definitely injected.\n\n```ts title=\"Injecting & exporting additional endpoints\"\n// file: emptySplitApi.ts noEmit\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const emptySplitApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: () => ({}),\n})\n\n// file: extendedApi.ts\nimport { emptySplitApi } from './emptySplitApi'\n\n// NOTE: these are the _SAME_ API reference!\nconst extendedApi = emptySplitApi.injectEndpoints({\n  endpoints: (build) => ({\n    example: build.query({\n      query: () => 'test',\n    }),\n  }),\n  overrideExisting: false,\n})\n\nexport const { useExampleQuery } = extendedApi\n```\n\n:::tip\nIf you inject an endpoint that already exists and don't explicitly specify `overrideExisting: true`, the endpoint\nwill not be overridden. In development mode, you will get a warning about this if `overrideExisting` is set to `false`,\nand an error will be throw if set to `'throw'`.\n:::\n\n## Enhancing Endpoints\n\nSometimes you may also need to modify an existing API definition, such as adding additional tag types, or providing additional configuration options to a given endpoint.\n\n`api.enhanceEndpoints` returns an updated and enhanced version of the API slice object, containing the combined endpoint definitions.\n\nThis is primarily useful for taking an API slice object that was code-generated from an API schema file like OpenAPI, and adding additional specific hand-written configuration for cache invalidation management on top of the generated endpoint definitions.\n\nFor example, `enhanceEndpoints` can be used to modify caching behavior by changing the values of `providesTags`, `invalidatesTags`, and `keepUnusedDataFor`:\n\n```ts\n// file: api.ts noEmit\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    getUserByUserId: build.query({\n      query() {\n        return ''\n      },\n    }),\n    patchUserByUserId: build.mutation({\n      query() {\n        return ''\n      },\n    }),\n    getUsers: build.query({\n      query() {\n        return ''\n      },\n    }),\n  }),\n})\n\n// file: enhanceEndpoints.ts\nimport { api } from './api'\n\nconst enhancedApi = api.enhanceEndpoints({\n  addTagTypes: ['User'],\n  endpoints: {\n    getUserByUserId: {\n      providesTags: ['User'],\n    },\n    patchUserByUserId: {\n      invalidatesTags: ['User'],\n    },\n    // alternatively, define a function which is called with the endpoint definition as an argument\n    getUsers(endpoint) {\n      endpoint.providesTags = ['User']\n      endpoint.keepUnusedDataFor = 120\n    },\n  },\n})\n```\n"
  },
  {
    "path": "docs/rtk-query/usage/conditional-fetching.mdx",
    "content": "---\nid: conditional-fetching\ntitle: Conditional Fetching\nsidebar_label: Conditional Fetching\nhide_title: true\ndescription: 'RTK Query > Usage > Conditional Fetching: skipping fetching if needed'\n---\n\n&nbsp;\n\n# Conditional Fetching\n\n## Overview\n\nQuery hooks automatically begin fetching data as soon as the component is mounted. But, there are use cases where you may want to delay fetching data until some condition becomes true. RTK Query supports conditional fetching to enable that behavior.\n\nIf you want to prevent a query from automatically running, you can use the `skip` parameter in a hook.\n\n[examples](docblock://query/react/buildHooks.ts?token=UseQuerySubscriptionOptions.skip)\n\n[remarks](docblock://query/react/buildHooks.ts?token=UseQuerySubscriptionOptions.skip)\n\n:::tip\nTypeScript users may wish to use [`skipToken`](../api/created-api/hooks.mdx#skiptoken) as an alternative to the `skip` option in order to skip running a query, while still keeping types for the endpoint accurate.\n:::\n\n## Conditional Fetching Example\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/conditional-fetching?fontsize=12&runonclick=1&hidenavigation=1&module=%2Fsrc%2FPokemon.tsx&moduleview=1&theme=dark\"\n  style={{\n    width: '100%',\n    height: '600px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"Conditional Fetching Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n"
  },
  {
    "path": "docs/rtk-query/usage/customizing-create-api.mdx",
    "content": "---\nid: customizing-create-api\ntitle: Customizing createApi\nsidebar_label: Customizing createApi\nhide_title: true\ndescription: 'RTK Query > Usage > Customizing createApi: adding customized variations'\n---\n\n&nbsp;\n\n# Customizing `createApi`\n\nCurrently, RTK Query includes two variants of `createApi`:\n\n- `createBaseApi`, which contains only the UI-agnostic Redux logic (the core module)\n- `createApi`, which contains both the core and React hooks modules\n\nYou can create your own versions of `createApi` by either specifying non-default options for the modules or by adding your own modules.\n\n## Customizing the React-Redux Hooks\n\nIf you want the hooks to use different versions of `useSelector`, `useDispatch` and `useStore`, such as if you are using a custom context, you can pass these in at module creation:\n\n```ts\nimport * as React from 'react'\nimport {\n  createDispatchHook,\n  createSelectorHook,\n  createStoreHook,\n  ReactReduxContextValue,\n} from 'react-redux'\nimport {\n  buildCreateApi,\n  coreModule,\n  reactHooksModule,\n} from '@reduxjs/toolkit/query/react'\n\nconst MyContext = React.createContext<ReactReduxContextValue | null>(null)\nconst customCreateApi = buildCreateApi(\n  coreModule(),\n  reactHooksModule({\n    hooks: {\n      useDispatch: createDispatchHook(MyContext),\n      useSelector: createSelectorHook(MyContext),\n      useStore: createStoreHook(MyContext),\n    },\n  }),\n)\n```\n\n## Customizing `createSelector` for RTKQ\n\nBoth `coreModule` and `reactHooksModule` accept a `createSelector` option which should be a selector creator instance from Reselect or with an equivalent signature.\n\n```ts\nimport * as React from 'react'\nimport { createSelectorCreator, lruMemoize } from '@reduxjs/toolkit'\nimport {\n  buildCreateApi,\n  coreModule,\n  reactHooksModule,\n} from '@reduxjs/toolkit/query/react'\n\nconst createLruSelector = createSelectorCreator(lruMemoize)\n\nconst customCreateApi = buildCreateApi(\n  coreModule({ createSelector: createLruSelector }),\n  reactHooksModule({ createSelector: createLruSelector }),\n)\n```\n\n## Creating your own module\n\nIf you want to create your own module, you should review [the react-hooks module](https://github.com/reduxjs/redux-toolkit/blob/b74a52935a5840bebca5acdc8e2265e3b6497afa/src/query/react/module.ts) to see what an implementation would look like.\n\nHere is a very stripped down version:\n\n```ts no-transpile\nimport {\n  BaseQueryFn,\n  CoreModule,\n  EndpointDefinitions,\n  Api,\n  Module,\n  buildCreateApi,\n  coreModule,\n} from '@reduxjs/toolkit/query'\n\nexport const customModuleName = Symbol()\nexport type CustomModule = typeof customModuleName\n\ndeclare module '@reduxjs/toolkit/query' {\n  export interface ApiModules<\n    BaseQuery extends BaseQueryFn,\n    Definitions extends EndpointDefinitions,\n    ReducerPath extends string,\n    TagTypes extends string,\n  > {\n    [customModuleName]: {\n      endpoints: {\n        [K in keyof Definitions]: {\n          myEndpointProperty: string\n        }\n      }\n    }\n  }\n}\n\nexport const myModule = (): Module<CustomModule> => ({\n  name: customModuleName,\n  init(api, options, context) {\n    // initialize stuff here if you need to\n\n    return {\n      injectEndpoint(endpoint, definition) {\n        const anyApi = api as any as Api<\n          any,\n          Record<string, any>,\n          string,\n          string,\n          CustomModule | CoreModule\n        >\n        anyApi.endpoints[endpoint].myEndpointProperty = 'test'\n      },\n    }\n  },\n})\n\nexport const myCreateApi = buildCreateApi(coreModule(), myModule())\n```\n"
  },
  {
    "path": "docs/rtk-query/usage/customizing-queries.mdx",
    "content": "---\nid: customizing-queries\ntitle: Customizing Queries\nsidebar_label: Customizing Queries\nhide_title: true\ndescription: 'RTK Query > Usage > Customizing Queries: overriding default query behavior'\n---\n\n&nbsp;\n\n# Customizing queries\n\nRTK Query is agnostic as to how your requests resolve. You can use any library you like to handle requests, or no library at all. RTK Query provides reasonable defaults expected to cover the majority of use cases, while also allowing room for customization to alter query handling to fit specific needs.\n\n## Customizing queries with `baseQuery`\n\nThe default method to handle queries is via the [`baseQuery`](../api/createApi#basequery) option on [`createApi`](../api/createApi), in combination with the [`query`](../api/createApi.mdx#query) option on an endpoint definition.\n\nTo process queries, endpoints are defined with a [`query`](../api/createApi.mdx#query) option, which passes its return value to a common [`baseQuery`](../api/createApi#basequery) function used for the API.\n\nBy default, RTK Query ships with [`fetchBaseQuery`](../api/fetchBaseQuery), which is a lightweight [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) wrapper that automatically handles request headers and response parsing in a manner similar to common libraries like `axios`. If `fetchBaseQuery` alone does not meet your needs, you can customize its behavior with a wrapper function, or create your own [`baseQuery`](../api/createApi.mdx#basequery) function from scratch for [`createApi`](../api/createApi) to use.\n\nSee also [`baseQuery API Reference`](../api/createApi.mdx#basequery).\n\n### Implementing a custom `baseQuery`\n\nRTK Query expects a `baseQuery` function to be called with three arguments: `args`, `api`, and `extraOptions`. It is expected to return an object with either a `data` or `error` property, or a promise that resolves to return such an object.\n\n:::tip\n\nBase query and query functions must _always_ catch errors themselves, and return it in an object!\n\n```ts no-transpile\nfunction brokenCustomBaseQuery() {\n  // ❌ Don't let this throw by itself\n  const data = await fetchSomeData()\n  return { data }\n}\n\nfunction correctCustomBaseQuery() {\n  // ✅ Catch errors and _return_ them so the RTKQ logic can track it\n  try {\n    const data = await fetchSomeData()\n    return { data }\n  } catch (error) {\n    return { error }\n  }\n}\n```\n\n:::\n\n#### baseQuery function arguments\n\n```ts title=\"baseQuery example arguments\" no-transpile\nconst customBaseQuery = (\n  // highlight-start\n  args,\n  { signal, dispatch, getState },\n  extraOptions,\n  // highlight-end\n) => {\n  // omitted\n}\n```\n\n#### baseQuery function return value\n\n1.  ```ts title=\"Expected success result format\" no-transpile\n    return { data: YourData }\n    ```\n2.  ```ts title=\"Expected error result format\" no-transpile\n    return { error: YourError }\n    ```\n\n```ts title=\"baseQuery example return value\" no-transpile\nconst customBaseQuery = (\n  args,\n  { signal, dispatch, getState },\n  extraOptions,\n) => {\n  // highlight-start\n  if (Math.random() > 0.5) return { error: 'Too high!' }\n  return { data: 'All good!' }\n  // highlight-end\n}\n```\n\n:::note\nThis format is required so that RTK Query can infer the return types for your responses.\n:::\n\nAt its core, a `baseQuery` function only needs to have the minimum return value to be valid; an object with a `data` or `error` property. It is up to the user to determine how they wish to use the provided arguments, and how requests are handled within the function itself.\n\n#### fetchBaseQuery defaults\n\nFor [`fetchBaseQuery`](../api/fetchBaseQuery) specifically, the return type is as follows:\n\n```ts title=\"Return types of fetchBaseQuery\" no-transpile\nPromise<\n  | {\n      data: any\n      error?: undefined\n      meta?: { request: Request; response: Response }\n    }\n  | {\n      error: {\n        status: number\n        data: any\n      }\n      data?: undefined\n      meta?: { request: Request; response: Response }\n    }\n>\n```\n\n1.  ```ts title=\"Expected success result format with fetchBaseQuery\" no-transpile\n    return { data: YourData }\n    ```\n2.  ```ts title=\"Expected error result format with fetchBaseQuery\" no-transpile\n    return { error: { status: number, data: YourErrorData } }\n    ```\n\n## Customizing query responses with `transformResponse`\n\nIndividual endpoints on [`createApi`](../api/createApi.mdx) accept a [`transformResponse`](../api/createApi.mdx) property which allows manipulation of the data returned by a query or mutation before it hits the cache.\n\n`transformResponse` is called with the data that a successful `baseQuery` returns for the corresponding endpoint, and the return value of `transformResponse` is used as the cached data associated with that endpoint call.\n\nBy default, the payload from the server is returned directly.\n\n```ts\nfunction defaultTransformResponse(\n  baseQueryReturnValue: unknown,\n  meta: unknown,\n  arg: unknown,\n) {\n  return baseQueryReturnValue\n}\n```\n\nTo change it, provide a function that looks like:\n\n```ts title=\"Unpack a deeply nested collection\" no-transpile\ntransformResponse: (response, meta, arg) =>\n  response.some.deeply.nested.collection\n```\n\n`transformResponse` is called with the `meta` property returned from the `baseQuery` as its second\nargument, which can be used while determining the transformed response. The value for `meta` is\ndependent on the `baseQuery` used.\n\n```ts title=\"transformResponse meta example\" no-transpile\ntransformResponse: (response: { sideA: Tracks; sideB: Tracks }, meta, arg) => {\n  if (meta?.coinFlip === 'heads') {\n    return response.sideA\n  }\n  return response.sideB\n}\n```\n\n`transformResponse` is called with the `arg` property provided to the endpoint as its third\nargument, which can be used while determining the transformed response. The value for `arg` is\ndependent on the `endpoint` used, as well as the argument used when calling the query/mutation.\n\n```ts title=\"transformResponse arg example\" no-transpile\ntransformResponse: (response: Posts, meta, arg) => {\n  return {\n    originalArg: arg,\n    data: response,\n  }\n}\n```\n\nWhile there is less need to store the response in a [normalized lookup table](https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape) with RTK Query managing caching data, `transformResponse` can be leveraged to do so if desired.\n\n```ts title=\"Normalize the response data\" no-transpile\ntransformResponse: (response) =>\n  response.reduce((acc, curr) => {\n    acc[curr.id] = curr\n    return acc\n  }, {})\n\n/*\n  will convert:\n  [\n    {id: 1, name: 'Harry'},\n    {id: 2, name: 'Ron'},\n    {id: 3, name: 'Hermione'},\n  ]\n\n  to:\n  {\n    1: { id: 1, name: \"Harry\" },\n    2: { id: 2, name: \"Ron\" },\n    3: { id: 3, name: \"Hermione\" },\n  }\n*/\n```\n\n[`createEntityAdapter`](../../api/createEntityAdapter.mdx) can also be used with `transformResponse` to normalize data, while also taking advantage of other features provided by `createEntityAdapter`, including providing an `ids` array, using [`sortComparer`](../../api/createEntityAdapter.mdx#sortcomparer) to maintain a consistently sorted list, as well as maintaining strong TypeScript support.\n\nSee also [Websocket Chat API with a transformed response shape](./streaming-updates.mdx#websocket-chat-api-with-a-transformed-response-shape) for an example of `transformResponse` normalizing response data in combination with `createEntityAdapter`, while also updating further data using [`streaming updates`](./streaming-updates.mdx).\n\n## Customizing query responses with `transformErrorResponse`\n\nIndividual endpoints on [`createApi`](../api/createApi.mdx) accept a [`transformErrorResponse`](../api/createApi.mdx) property which allows manipulation of the error returned by a query or mutation before it hits the cache.\n\n`transformErrorResponse` is called with the error that a failed `baseQuery` returns for the corresponding endpoint, and the return value of `transformErrorResponse` is used as the cached error associated with that endpoint call.\n\nBy default, the payload from the server is returned directly.\n\n```ts\nfunction defaultTransformResponse(\n  baseQueryReturnValue: unknown,\n  meta: unknown,\n  arg: unknown,\n) {\n  return baseQueryReturnValue\n}\n```\n\nTo change it, provide a function that looks like:\n\n```ts title=\"Unpack a deeply nested error object\" no-transpile\ntransformErrorResponse: (response, meta, arg) =>\n  response.data.some.deeply.nested.errorObject\n```\n\n`transformErrorResponse` is called with the `meta` property returned from the `baseQuery` as its second\nargument, which can be used while determining the transformed response. The value for `meta` is\ndependent on the `baseQuery` used.\n\n```ts title=\"transformErrorResponse meta example\" no-transpile\ntransformErrorResponse: (\n  response: { data: { sideA: Tracks; sideB: Tracks } },\n  meta,\n  arg,\n) => {\n  if (meta?.coinFlip === 'heads') {\n    return response.data.sideA\n  }\n  return response.data.sideB\n}\n```\n\n`transformErrorResponse` is called with the `arg` property provided to the endpoint as its third\nargument, which can be used while determining the transformed response. The value for `arg` is\ndependent on the `endpoint` used, as well as the argument used when calling the query/mutation.\n\n```ts title=\"transformErrorResponse arg example\" no-transpile\ntransformErrorResponse: (response: Posts, meta, arg) => {\n  return {\n    originalArg: arg,\n    error: response,\n  }\n}\n```\n\n## Customizing queries with `queryFn`\n\nRTK Query comes with `fetchBaseQuery` out of the box, which makes it straightforward to define endpoints that talk to HTTP URLs (such as a typical REST API). We also have integrations with GraphQL as well. However, at its core, RTK Query is really about tracking loading state and cached values for _any_ async request/response sequence, not just HTTP requests.\n\nRTK Query supports defining endpoints that run arbitrary async logic and return a result. Individual endpoints on [`createApi`](../api/createApi.mdx) accept a [`queryFn`](../api/createApi.mdx#queryfn) property, which let you write your own async function with whatever logic you want inside.\n\nThis can be useful for scenarios where you want to have particularly different behavior for a single endpoint, or where the query itself is not relevant, including:\n\n- One-off queries that use a different base URL\n- One-off queries that use different request handling, such as automatic re-tries\n- One-off queries that use different error handling behavior\n- Queries that make requests using a third-party library SDK, such as Firebase or Supabase\n- Queries that perform async tasks that are not a typical request/response\n- Performing multiple requests with a single query ([example](#performing-multiple-requests-with-a-single-query))\n- Leveraging invalidation behavior with no relevant query ([example](#using-a-no-op-queryfn))\n- Using [Streaming Updates](./streaming-updates) with no relevant initial request ([example](#streaming-data-with-no-initial-request))\n\nSee also [`queryFn API Reference`](../api/createApi.mdx#queryfn) for the type signature and available options.\n\n### Implementing a `queryFn`\n\nA `queryFn` can be thought of as an inline `baseQuery`. It will be called with the same arguments as `baseQuery`, as well as the provided `baseQuery` function itself (`arg`, `api`, `extraOptions`, and `baseQuery`). Similarly to `baseQuery`, it is expected to return an object with either a `data` or `error` property, or a promise that resolves to return such an object.\n\n#### Basic `queryFn` Example\n\n```ts title=\"Basic queryFn example\" no-transpile\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport { userAPI, User } from './userAPI'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ url: '/' }),\n  endpoints: (build) => ({\n    // normal HTTP endpoint using fetchBaseQuery\n    getPosts: build.query<PostsResponse, void>({\n      query: () => ({ url: 'posts' }),\n    }),\n    // highlight-start\n    // endpoint with a custom `queryFn` and separate async logic\n    getUser: build.query<User, string>({\n      queryFn: async (userId: string) => {\n        try {\n          const user = await userApi.getUserById(userId)\n          // Return the result in an object with a `data` field\n          return { data: user }\n        } catch (error) {\n          // Catch any errors and return them as an object with an `error` field\n          return { error }\n        }\n      },\n    }),\n    // highlight-end\n  }),\n})\n```\n\n#### queryFn function arguments\n\n```ts title=\"queryFn example arguments\" no-transpile\nconst queryFn = (\n  // highlight-start\n  args,\n  { signal, dispatch, getState },\n  extraOptions,\n  baseQuery,\n  // highlight-end\n) => {\n  // omitted\n}\n```\n\n#### queryFn function return value\n\n1.  ```ts title=\"Expected success result format\" no-transpile\n    return { data: YourData }\n    ```\n2.  ```ts title=\"Expected error result format\" no-transpile\n    return { error: YourError }\n    ```\n\n```ts title=\"queryFn example return value\" no-transpile\nconst queryFn = (\n  args,\n  { signal, dispatch, getState },\n  extraOptions,\n  baseQuery,\n) => {\n  // highlight-start\n  if (Math.random() > 0.5) return { error: 'Too high!' }\n  return { data: 'All good!' }\n  // highlight-end\n}\n```\n\n## Examples - `baseQuery`\n\n### Axios baseQuery\n\nThis example implements a very basic axios-based `baseQuery` utility.\n\n```ts title=\"Basic axios baseQuery\"\nimport { createApi } from '@reduxjs/toolkit/query'\nimport type { BaseQueryFn } from '@reduxjs/toolkit/query'\nimport axios from 'axios'\nimport type { AxiosRequestConfig, AxiosError } from 'axios'\n\n// highlight-start\nconst axiosBaseQuery =\n  (\n    { baseUrl }: { baseUrl: string } = { baseUrl: '' },\n  ): BaseQueryFn<\n    {\n      url: string\n      method?: AxiosRequestConfig['method']\n      data?: AxiosRequestConfig['data']\n      params?: AxiosRequestConfig['params']\n      headers?: AxiosRequestConfig['headers']\n    },\n    unknown,\n    unknown\n  > =>\n  async ({ url, method, data, params, headers }) => {\n    try {\n      const result = await axios({\n        url: baseUrl + url,\n        method,\n        data,\n        params,\n        headers,\n      })\n      return { data: result.data }\n    } catch (axiosError) {\n      const err = axiosError as AxiosError\n      return {\n        error: {\n          status: err.response?.status,\n          data: err.response?.data || err.message,\n        },\n      }\n    }\n  }\n// highlight-end\n\nconst api = createApi({\n  // highlight-start\n  baseQuery: axiosBaseQuery({\n    baseUrl: 'https://example.com',\n  }),\n  // highlight-end\n  endpoints(build) {\n    return {\n      query: build.query({ query: () => ({ url: '/query', method: 'get' }) }),\n      mutation: build.mutation({\n        query: () => ({ url: '/mutation', method: 'post' }),\n      }),\n    }\n  },\n})\n```\n\n### GraphQL baseQuery\n\nThis example implements a very basic GraphQL-based `baseQuery`.\n\n```ts title=\"Basic GraphQL baseQuery\"\nimport { createApi } from '@reduxjs/toolkit/query'\nimport { request, gql, ClientError } from 'graphql-request'\n\n// highlight-start\nconst graphqlBaseQuery =\n  ({ baseUrl }: { baseUrl: string }) =>\n  async ({ body }: { body: string }) => {\n    try {\n      const result = await request(baseUrl, body)\n      return { data: result }\n    } catch (error) {\n      if (error instanceof ClientError) {\n        return { error: { status: error.response.status, data: error } }\n      }\n      return { error: { status: 500, data: error } }\n    }\n  }\n// highlight-end\n\nexport const api = createApi({\n  // highlight-start\n  baseQuery: graphqlBaseQuery({\n    baseUrl: 'https://graphqlzero.almansi.me/api',\n  }),\n  // highlight-end\n  endpoints: (build) => ({\n    getPosts: build.query({\n      query: () => ({\n        body: gql`\n          query {\n            posts {\n              data {\n                id\n                title\n              }\n            }\n          }\n        `,\n      }),\n      transformResponse: (response) => response.posts.data,\n    }),\n    getPost: build.query({\n      query: (id) => ({\n        body: gql`\n        query {\n          post(id: ${id}) {\n            id\n            title\n            body\n          }\n        }\n        `,\n      }),\n      transformResponse: (response) => response.post,\n    }),\n  }),\n})\n```\n\n### Automatic re-authorization by extending fetchBaseQuery\n\nThis example wraps [`fetchBaseQuery`](../api/fetchBaseQuery) such that when encountering a [`401 Unauthorized`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401) error, an additional request is sent to attempt to refresh an authorization token, and re-try to initial query after re-authorizing.\n\n```ts title=\"Simulating axios-like interceptors with a custom base query\"\n// file: authSlice.ts noEmit\ndeclare function tokenReceived(args?: any): void\ndeclare function loggedOut(): void\nexport { tokenReceived, loggedOut }\n// file: baseQueryWithReauth.ts\nimport { fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type {\n  BaseQueryFn,\n  FetchArgs,\n  FetchBaseQueryError,\n} from '@reduxjs/toolkit/query'\nimport { tokenReceived, loggedOut } from './authSlice'\n\nconst baseQuery = fetchBaseQuery({ baseUrl: '/' })\nconst baseQueryWithReauth: BaseQueryFn<\n  string | FetchArgs,\n  unknown,\n  FetchBaseQueryError\n> = async (args, api, extraOptions) => {\n  let result = await baseQuery(args, api, extraOptions)\n  if (result.error && result.error.status === 401) {\n    // try to get a new token\n    const refreshResult = await baseQuery('/refreshToken', api, extraOptions)\n    if (refreshResult.data) {\n      // store the new token\n      api.dispatch(tokenReceived(refreshResult.data))\n      // retry the initial query\n      result = await baseQuery(args, api, extraOptions)\n    } else {\n      api.dispatch(loggedOut())\n    }\n  }\n  return result\n}\n```\n\n#### Preventing multiple unauthorized errors\n\nUsing [`async-mutex`](https://github.com/DirtyHairy/async-mutex) to prevent multiple calls to '/refreshToken' when multiple calls fail with [`401 Unauthorized`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401) errors.\n\n```ts title=\"Preventing multiple calls to '/refreshToken'\"\n// file: authSlice.ts noEmit\ndeclare function tokenReceived(args?: any): void\ndeclare function loggedOut(): void\nexport { tokenReceived, loggedOut }\n// file: baseQueryWithReauth.ts\n\nimport { fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type {\n  BaseQueryFn,\n  FetchArgs,\n  FetchBaseQueryError,\n} from '@reduxjs/toolkit/query'\nimport { tokenReceived, loggedOut } from './authSlice'\n// highlight-start\nimport { Mutex } from 'async-mutex'\n// highlight-end\n\n// create a new mutex\n// highlight-start\nconst mutex = new Mutex()\n// highlight-end\nconst baseQuery = fetchBaseQuery({ baseUrl: '/' })\nconst baseQueryWithReauth: BaseQueryFn<\n  string | FetchArgs,\n  unknown,\n  FetchBaseQueryError\n> = async (args, api, extraOptions) => {\n  // wait until the mutex is available without locking it\n  // highlight-start\n  await mutex.waitForUnlock()\n  // highlight-end\n  let result = await baseQuery(args, api, extraOptions)\n  if (result.error && result.error.status === 401) {\n    // checking whether the mutex is locked\n    // highlight-start\n    if (!mutex.isLocked()) {\n      const release = await mutex.acquire()\n      // highlight-end\n      try {\n        const refreshResult = await baseQuery(\n          '/refreshToken',\n          api,\n          extraOptions,\n        )\n        if (refreshResult.data) {\n          api.dispatch(tokenReceived(refreshResult.data))\n          // retry the initial query\n          result = await baseQuery(args, api, extraOptions)\n        } else {\n          api.dispatch(loggedOut())\n        }\n      } finally {\n        // release must be called once the mutex should be released again.\n        // highlight-start\n        release()\n        // highlight-end\n      }\n    } else {\n      // wait until the mutex is available without locking it\n      // highlight-start\n      await mutex.waitForUnlock()\n      // highlight-end\n      result = await baseQuery(args, api, extraOptions)\n    }\n  }\n  return result\n}\n```\n\n### Automatic retries\n\nRTK Query exports a utility called `retry` that you can wrap the `baseQuery` in your API definition with. It defaults to 5 attempts with a basic exponential backoff.\n\nThe default behavior would retry at these intervals:\n\n[remarks](docblock://query/retry.ts?token=defaultBackoff)\n\n[examples](docblock://query/retry.ts?token=retry)\n\nIn the event that you didn't want to retry on a specific endpoint, you can just set `maxRetries: 0`.\n\n:::info\nIt is possible for a hook to return `data` and `error` at the same time. By default, RTK Query will keep whatever the last 'good' result was in `data` until it can be updated or garbage collected.\n:::\n\n#### Bailing out of error re-tries\n\nThe `retry` utility has a `fail` method property attached which can be used to bail out of retries immediately. This can be used for situations where it is known that additional re-tries would be guaranteed to all fail and would be redundant.\n\n```ts title=\"Bailing out of error re-tries\"\nimport { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\nimport type { FetchArgs } from '@reduxjs/toolkit/query'\ninterface Post {\n  id: number\n  name: string\n}\ntype PostsResponse = Post[]\n\n// highlight-start\nconst staggeredBaseQueryWithBailOut = retry(\n  async (args: string | FetchArgs, api, extraOptions) => {\n    const result = await fetchBaseQuery({ baseUrl: '/api/' })(\n      args,\n      api,\n      extraOptions,\n    )\n\n    // bail out of re-tries immediately if unauthorized,\n    // because we know successive re-retries would be redundant\n    if (result.error?.status === 401) {\n      retry.fail(result.error, result.meta)\n    }\n\n    return result\n  },\n  {\n    maxRetries: 5,\n  },\n)\n// highlight-end\n\nexport const api = createApi({\n  // highlight-start\n  baseQuery: staggeredBaseQueryWithBailOut,\n  // highlight-end\n  endpoints: (build) => ({\n    getPosts: build.query<PostsResponse, void>({\n      query: () => ({ url: 'posts' }),\n    }),\n    getPost: build.query<Post, string>({\n      query: (id) => ({ url: `post/${id}` }),\n      extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint\n    }),\n  }),\n})\nexport const { useGetPostsQuery, useGetPostQuery } = api\n```\n\n### Adding Meta information to queries\n\nA `baseQuery` can also include a `meta` property in its return value. This can be beneficial in cases where you may wish to include additional information associated with the request such as a request ID or timestamp.\n\nIn such a scenario, the return value would look like so:\n\n1.  ```ts title=\"Expected success result format with meta\" no-transpile\n    return { data: YourData, meta: YourMeta }\n    ```\n2.  ```ts title=\"Expected error result format with meta\" no-transpile\n    return { error: YourError, meta: YourMeta }\n    ```\n\n<!-- TODO: re-write below with a more realistic example -->\n\n```ts title=\"baseQuery example with meta information\"\n// file: idGenerator.ts noEmit\nexport declare const uuid: () => string\n\n// file: metaBaseQuery.ts\nimport { fetchBaseQuery, createApi } from '@reduxjs/toolkit/query'\nimport type {\n  BaseQueryFn,\n  FetchArgs,\n  FetchBaseQueryError,\n} from '@reduxjs/toolkit/query'\nimport type { FetchBaseQueryMeta } from '@reduxjs/toolkit/query'\nimport { uuid } from './idGenerator'\n\n// highlight-start\ntype Meta = {\n  requestId: string\n  timestamp: number\n}\n// highlight-end\n\n// highlight-start\nconst metaBaseQuery: BaseQueryFn<\n  string | FetchArgs,\n  unknown,\n  FetchBaseQueryError,\n  {},\n  Meta & FetchBaseQueryMeta\n> = async (args, api, extraOptions) => {\n  const requestId = uuid()\n  const timestamp = Date.now()\n\n  const baseResult = await fetchBaseQuery({ baseUrl: '/' })(\n    args,\n    api,\n    extraOptions,\n  )\n\n  return {\n    ...baseResult,\n    meta: baseResult.meta && { ...baseResult.meta, requestId, timestamp },\n  }\n}\n// highlight-end\n\nconst DAY_MS = 24 * 60 * 60 * 1000\n\ninterface Post {\n  id: number\n  name: string\n  timestamp: number\n}\ntype PostsResponse = Post[]\n\nconst api = createApi({\n  // highlight-start\n  baseQuery: metaBaseQuery,\n  // highlight-end\n  endpoints: (build) => ({\n    // a theoretical endpoint where we only want to return data\n    // if request was performed past a certain date\n    getRecentPosts: build.query<PostsResponse, void>({\n      query: () => 'posts',\n      // highlight-start\n      transformResponse: (returnValue: PostsResponse, meta) => {\n        // `meta` here contains our added `requestId` & `timestamp`, as well as\n        // `request` & `response` from fetchBaseQuery's meta object.\n        // These properties can be used to transform the response as desired.\n        if (!meta) return []\n        return returnValue.filter(\n          (post) => post.timestamp >= meta.timestamp - DAY_MS,\n        )\n      },\n      // highlight-end\n    }),\n  }),\n})\n```\n\n### Constructing a Dynamic Base URL using Redux state\n\nIn some cases, you may wish to have a dynamically altered base url determined from a property in your Redux state. A `baseQuery` has access to a [`getState`](../api/createApi.mdx#basequery-function-arguments) method that provides the current store state at the time it is called. This can be used to construct the desired url using a partial url string, and the appropriate data from your store state.\n\n```ts title=\"Dynamically generated Base URL example\"\n// file: src/store.ts noEmit\nexport type RootState = {\n  auth: {\n    projectId: number | null\n  }\n}\n\n// file: src/services/projectSlice.ts noEmit\nimport type { RootState } from '../store'\nexport const selectProjectId = (state: RootState) => state.auth.projectId\n\n// file: src/services/types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: src/services/api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type {\n  BaseQueryFn,\n  FetchArgs,\n  FetchBaseQueryError,\n} from '@reduxjs/toolkit/query/react'\nimport type { Post } from './types'\nimport { selectProjectId } from './projectSlice'\nimport type { RootState } from '../store'\n\nconst rawBaseQuery = fetchBaseQuery({\n  baseUrl: 'www.my-cool-site.com/',\n})\n\nconst dynamicBaseQuery: BaseQueryFn<\n  string | FetchArgs,\n  unknown,\n  FetchBaseQueryError\n> = async (args, api, extraOptions) => {\n  const projectId = selectProjectId(api.getState() as RootState)\n  // gracefully handle scenarios where data to generate the URL is missing\n  if (!projectId) {\n    return {\n      error: {\n        status: 400,\n        statusText: 'Bad Request',\n        data: 'No project ID received',\n      },\n    }\n  }\n\n  const urlEnd = typeof args === 'string' ? args : args.url\n  // construct a dynamically generated portion of the url\n  const adjustedUrl = `project/${projectId}/${urlEnd}`\n  const adjustedArgs =\n    typeof args === 'string' ? adjustedUrl : { ...args, url: adjustedUrl }\n  // provide the amended url and other params to the raw base query\n  return rawBaseQuery(adjustedArgs, api, extraOptions)\n}\n\nexport const api = createApi({\n  baseQuery: dynamicBaseQuery,\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => 'posts',\n    }),\n  }),\n})\n\nexport const { useGetPostsQuery } = api\n\n/*\n  Using `useGetPostsQuery()` where a `projectId` of 500 is in the redux state will result in\n  a request being sent to www.my-cool-site.com/project/500/posts\n*/\n```\n\n## Examples - `transformResponse`\n\n### Unpacking deeply nested GraphQL data\n\n```ts title=\"GraphQL transformation example\"\n// file: graphqlBaseQuery.ts noEmit\nimport { BaseQueryFn } from '@reduxjs/toolkit/query'\ndeclare const graphqlBaseQuery: (args: { baseUrl: string }) => BaseQueryFn\ndeclare const gql: (literals: TemplateStringsArray) => void\nexport { graphqlBaseQuery, gql }\n\n// file: graphqlApi.ts\nimport { createApi } from '@reduxjs/toolkit/query'\nimport { graphqlBaseQuery, gql } from './graphqlBaseQuery'\n\ninterface Post {\n  id: number\n  title: string\n}\n\nexport const api = createApi({\n  baseQuery: graphqlBaseQuery({\n    baseUrl: '/graphql',\n  }),\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => ({\n        body: gql`\n          query {\n            posts {\n              data {\n                id\n                title\n              }\n            }\n          }\n        `,\n      }),\n      // highlight-start\n      transformResponse: (response: { posts: { data: Post[] } }) =>\n        response.posts.data,\n      // highlight-end\n    }),\n  }),\n})\n```\n\n### Normalizing data with `createEntityAdapter`\n\nIn the example below, `transformResponse` is used in conjunction with [`createEntityAdapter`](../../api/createEntityAdapter.mdx) to normalize the data before storing it in the cache.\n\nFor a response such as:\n\n<!-- prettier-ignore -->\n```ts no-transpile\n[\n  { id: 1, name: 'Harry' },\n  { id: 2, name: 'Ron' },\n  { id: 3, name: 'Hermione' },\n]\n```\n\nThe normalized cache data will be stored as:\n\n```ts no-transpile\n{\n  ids: [1, 3, 2],\n  entities: {\n    1: { id: 1, name: \"Harry\" },\n    2: { id: 2, name: \"Ron\" },\n    3: { id: 3, name: \"Hermione\" },\n  }\n}\n```\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { createEntityAdapter } from '@reduxjs/toolkit'\nimport type { EntityState } from '@reduxjs/toolkit'\n\nexport interface Post {\n  id: number\n  name: string\n}\n\n// highlight-start\nconst postsAdapter = createEntityAdapter<Post>({\n  sortComparer: (a, b) => a.name.localeCompare(b.name),\n})\n// highlight-end\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    getPosts: build.query<EntityState<Post, number>, void>({\n      query: () => `posts`,\n      // highlight-start\n      transformResponse(response: Post[]) {\n        return postsAdapter.addMany(postsAdapter.getInitialState(), response)\n      },\n      // highlight-end\n    }),\n  }),\n})\n\nexport const { useGetPostsQuery } = api\n```\n\n## Examples - `queryFn`\n\n### Using a Third-Party SDK\n\nMany services like Firebase and Supabase provide their own SDK to make requests. You can use those SDK methods in a `queryFn`:\n\n```ts title=\"Basic Third-Party SDK\" no-transpile\nimport { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { supabase } from './supabaseApi'\n\nexport const supabaseApi = createApi({\n  reducerPath: 'supabaseApi',\n  baseQuery: fakeBaseQuery(),\n  endpoints: (build) => ({\n    getBlogs: build.query({\n      queryFn: async () => {\n        // Supabase conveniently already has `data` and `error` fields\n        const { data, error } = await supabase.from('blogs').select()\n        if (error) {\n          return { error }\n        }\n        return { data }\n      },\n    }),\n  }),\n})\n```\n\nYou could also try creating a custom base query that uses the SDK, and define endpoints that pass method names or args into that base query.\n\n### Using a no-op queryFn\n\nIn certain scenarios, you may wish to have a `query` or `mutation` where sending a request or returning data is not relevant for the situation. Such a scenario would be to leverage the `invalidatesTags` property to force re-fetch specific `tags` that have been provided to the cache.\n\nSee also [\"providing errors to the cache\"](./automated-refetching.mdx#providing-errors-to-the-cache) to see additional detail and an example for such a scenario to 'refetch errored queries'.\n\n```ts title=\"Using a no-op queryFn\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\nexport interface User {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post, User } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  tagTypes: ['Post', 'User'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => 'posts',\n      providesTags: ['Post'],\n    }),\n\n    getUsers: build.query<User[], void>({\n      query: () => 'users',\n      providesTags: ['User'],\n    }),\n\n    // highlight-start\n    refetchPostsAndUsers: build.mutation<null, void>({\n      // The query is not relevant here, so a `null` returning `queryFn` is used\n      queryFn: () => ({ data: null }),\n      // This mutation takes advantage of tag invalidation behavior to trigger\n      // any queries that provide the 'Post' or 'User' tags to re-fetch if the queries\n      // are currently subscribed to the cached data\n      invalidatesTags: ['Post', 'User'],\n    }),\n    // highlight-end\n  }),\n})\n```\n\n### Streaming data with no initial request\n\nRTK Query provides the ability for an endpoint to send an initial request for data, followed up with recurring [streaming updates](./streaming-updates.mdx) that perform further updates to the cached data as the updates occur. However, the initial request is optional, and you may wish to use streaming updates without any initial request fired off.\n\nIn the example below, a `queryFn` is used to populate the cache data with an empty array, with no initial request sent. The array is later populated using streaming updates via the [`onCacheEntryAdded`](../api/createApi.mdx#oncacheentryadded) endpoint option, updating the cached data as it is received.\n\n```ts title=\"Streaming data with no initial request\"\n// file: types.ts noEmit\nexport interface Message {\n  id: number\n  channel: 'general' | 'redux'\n  userName: string\n  text: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Message } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  tagTypes: ['Message'],\n  endpoints: (build) => ({\n    // highlight-start\n    streamMessages: build.query<Message[], void>({\n      // The query is not relevant here as the data will be provided via streaming updates.\n      // A queryFn returning an empty array is used, with contents being populated via\n      // streaming updates below as they are received.\n      queryFn: () => ({ data: [] }),\n      async onCacheEntryAdded(arg, { updateCachedData, cacheEntryRemoved }) {\n        const ws = new WebSocket('ws://localhost:8080')\n        // populate the array with messages as they are received from the websocket\n        ws.addEventListener('message', (event) => {\n          updateCachedData((draft) => {\n            draft.push(JSON.parse(event.data))\n          })\n        })\n        await cacheEntryRemoved\n        ws.close()\n      },\n    }),\n    // highlight-end\n  }),\n})\n```\n\n### Performing multiple requests with a single query\n\nIn the example below, a query is written to fetch all posts for a random user. This is done using a first request for a random user, followed by getting all posts for that user. Using `queryFn` allows the two requests to be included within a single query, avoiding having to chain that logic within component code.\n\n```ts title=\"Performing multiple requests with a single query\"\n// file: types.ts noEmit\nexport interface Post {}\nexport interface User {\n  id: number\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { FetchBaseQueryError } from '@reduxjs/toolkit/query'\nimport type { Post, User } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/ ' }),\n  endpoints: (build) => ({\n    getRandomUserPosts: build.query<Post, void>({\n      async queryFn(_arg, _queryApi, _extraOptions, fetchWithBQ) {\n        // get a random user\n        const randomResult = await fetchWithBQ('users/random')\n        if (randomResult.error)\n          return { error: randomResult.error as FetchBaseQueryError }\n        const user = randomResult.data as User\n        const result = await fetchWithBQ(`user/${user.id}/posts`)\n        return result.data\n          ? { data: result.data as Post }\n          : { error: result.error as FetchBaseQueryError }\n      },\n    }),\n  }),\n})\n```\n"
  },
  {
    "path": "docs/rtk-query/usage/error-handling.mdx",
    "content": "---\nid: error-handling\ntitle: Error Handling\nsidebar_label: Error Handling\nhide_title: true\ndescription: 'RTK Query > Usage > Error Handling: dealing with API errors'\n---\n\n&nbsp;\n\n# Error Handling\n\n## Overview\n\nIf your query or mutation happens to throw an error when using [fetchBaseQuery](../api/fetchBaseQuery), it will be returned in the `error` property of the respective hook. The component will re-render when that occurs, and you can show appropriate UI based on the error data if desired.\n\n### Error Display Examples\n\n```tsx no-transpile title=\"Query Error\"\nfunction PostsList() {\n  const { data, error } = useGetPostsQuery()\n\n  return (\n    <div>\n      {error.status} {JSON.stringify(error.data)}\n    </div>\n  )\n}\n```\n\n```tsx no-transpile title=\"Mutation Error\"\nfunction AddPost() {\n  const [addPost, { error }] = useAddPostMutation()\n\n  return (\n    <div>\n      {error.status} {JSON.stringify(error.data)}\n    </div>\n  )\n}\n```\n\n:::tip\nIf you need to access the error or success payload immediately after a mutation, you can chain `.unwrap()`.\n\n```ts title=\"Using .unwrap\" no-transpile\naddPost({ id: 1, name: 'Example' })\n  .unwrap()\n  .then((payload) => console.log('fulfilled', payload))\n  .catch((error) => console.error('rejected', error))\n```\n\n:::\n\n```tsx no-transpile title=\"Manually selecting an error\"\nfunction PostsList() {\n  const { error } = useSelector(api.endpoints.getPosts.select())\n\n  return (\n    <div>\n      {error.status} {JSON.stringify(error.data)}\n    </div>\n  )\n}\n```\n\n## Errors with a custom `baseQuery`\n\nWhether a response is returned as `data` or `error` is dictated by the `baseQuery` provided.\n\nUltimately, you can choose whatever library you prefer to use with your `baseQuery`, but it's important that you return the correct response format. If you haven't tried [`fetchBaseQuery`](../api/fetchBaseQuery) yet, give it a chance! Otherwise, see [Customizing Queries](./customizing-queries) for information on how to alter the returned errors.\n\n## Handling errors at a macro level\n\nThere are quite a few ways that you can manage your errors, and in some cases, you may want to show a generic toast notification for any async error. Being that RTK Query is built on top of Redux and Redux-Toolkit, you can easily add a middleware to your store for this purpose.\n\n:::tip\n\nRedux Toolkit has [action matching utilities](../../api/matching-utilities.mdx) that we can leverage for additional custom behaviors.\n\n:::\n\n```ts no-transpile title=\"Error catching middleware example\"\nimport { isRejectedWithValue } from '@reduxjs/toolkit'\nimport type { MiddlewareAPI, Middleware } from '@reduxjs/toolkit'\nimport { toast } from 'your-cool-library'\n\n/**\n * Log a warning and show a toast!\n */\nexport const rtkQueryErrorLogger: Middleware =\n  (api: MiddlewareAPI) => (next) => (action) => {\n    // RTK Query uses `createAsyncThunk` from redux-toolkit under the hood, so we're able to utilize these matchers!\n    if (isRejectedWithValue(action)) {\n      console.warn('We got a rejected action!')\n      toast.warn({\n        title: 'Async error!',\n        message:\n          'data' in action.error\n            ? (action.error.data as { message: string }).message\n            : action.error.message,\n      })\n    }\n\n    return next(action)\n  }\n```\n"
  },
  {
    "path": "docs/rtk-query/usage/examples.mdx",
    "content": "---\nid: examples\ntitle: RTK Query Examples\nsidebar_label: Examples\nhide_title: true\ndescription: 'RTK Query > Usage > Examples: sandboxes with runnable apps'\n---\n\n&nbsp;\n\n# RTK Query Examples\n\n## Examples Overview\n\nWe have a variety of examples that demonstrate various aspects of using RTK Query.\n\nThese examples are not meant to be what you base your application on, but exist to show _very specific_ behaviors that you may not actually want or need in your application. For most users, the basic examples in the [Queries](./queries) and [Mutations](./mutations) sections will cover the majority of your needs.\n\n:::tip\n\nPlease note that when playing with the examples in CodeSandbox that you can experience quirky behavior, especially if you fork them and start editing files. Hot reloading, CSB service workers and [`msw`](https://mswjs.io/) sometimes have trouble getting on the right page -- when that happens, just refresh in the CSB browser pane.\n\n:::\n\n## Kitchen Sink\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/kitchen-sink?fontsize=12&hidenavigation=1&theme=dark&runonclick=1\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query Kitchen Sink Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\n## React Optimistic Updates\n\nIn the example below you'll notice a few things. There are two `Posts` list on the sidebar. The top one will only update _after_ a successful mutation and resync with the server. The _subscribed_ one will update immediately due to the optimistic update. In the event of an error, you'll see this get rolled back.\n\n:::info\nThe example has some intentionally wonky behavior... when editing the name of a post, there is a decent chance you'll get a random error.\n:::\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/optimistic-update?fontsize=12&hidenavigation=1&module=%2Fsrc%2Fapp%2Fservices%2Fposts.ts&theme=dark&runonclick=1\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query Optimistic Update Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\n## React with GraphQL\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/graphql?fontsize=12&hidenavigation=1&theme=dark&module=%2Fsrc%2Fapi.js&runonclick=1\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query GraphQL Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\n## Authentication\n\nThere are several ways to handle authentication with RTK Query. This is a very basic example of taking a JWT from a login mutation, then setting that in our store. We then use `prepareHeaders` to inject the authentication headers into every subsequent request.\n\n### Dispatching an action to set the user state\n\nThis example dispatches a `setCredentials` action to store the user and token information.\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/authentication?fontsize=12&hidenavigation=1&module=%2Fsrc%2Ffeatures%2Fauth%2FauthSlice.tsx&theme=dark&runonclick=1\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query Authentication Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\n### Using `extraReducers`\n\nThis example uses a matcher from the endpoint and `extraReducers` in the `authSlice`.\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/authentication-with-extrareducers?fontsize=12&hidenavigation=1&module=%2Fsrc%2Ffeatures%2Fauth%2FauthSlice.tsx&theme=dark&runonclick=1\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query Authentication Example - extraReducers\"\n  allow=\"accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking\"\n  sandbox=\"allow-forms allow-modals allow-popups allow-presentation allow-same-origin allow-scripts\"\n></iframe>\n\n## React Class Components\n\nCheck out the `PostDetail` component for an example of Class Component usage.\n\n<iframe\n  src=\"https://codesandbox.io/embed/react-class-component-example-48hyq?fontsize=12&hidenavigation=1&theme=dark&runonclick=1\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query React Class Components Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\n## Svelte\n\n<iframe\n  src=\"https://codesandbox.io/embed/svelte-app-rtk-simplequery-demo-f1ueb?fontsize=12&hidenavigation=1&theme=dark&runonclick=1\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query Svelte Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n"
  },
  {
    "path": "docs/rtk-query/usage/infinite-queries.mdx",
    "content": "---\nid: infinite-queries\ntitle: Infinite Queries\nsidebar_label: Infinite Queries\nhide_title: true\ndescription: 'RTK Query > Usage > Infinite Queries: fetching many data pages from a server'\n---\n\n&nbsp;\n\n# Infinite Queries\n\n## Overview\n\nRendering lists that can additively \"load more\" data onto an existing set of data or \"infinite scroll\" is a common UI pattern.\n\nRTK Query supports this use case via \"infinite query\" endpoints. Infinite Query endpoints are similar to standard query endpoints, in that they fetch data and cache the results. However, infinite query endpoints have the ability to fetch \"next\" and \"previous\" pages, and contain all related fetched pages in a single cache entry.\n\n## Infinite Query Concepts\n\nRTK Query's support for infinite queries is modeled after [React Query's infinite query API design](https://tanstack.com/query/latest/docs/framework/react/guides/infinite-queries).\n\n### Query Args, Page Params, and Cache Structure\n\nWith standard query endpoints:\n\n- You specify the \"query arg\" value, which is passed to the `query` or `queryFn` function that will calculate the desired URL or do the actual fetching\n- The query arg is also serialized to generate the unique internal key for this specific cache entry\n- The single response value is directly stored as the `data` field in the cache entry\n\nInfinite queries work similarly, but have a couple additional layers:\n\n- You still specify a \"query arg\", which is still used to generate the unique cache key for this specific cache entry\n- However, there is a separation between the \"query arg\" used for the cache key, and the \"page param\" used to fetch a specific page. Since both are useful for determining what to fetch, **your `query` and `queryFn` methods will receive a combined object with `{queryArg, pageParam}` as the first argument, instead of just the `queryArg` by itself**.\n- The `data` field in the cache entry stores a `{pages: DataType[], pageParams: PageParam[]}` structure that contains _all_ of the fetched page results and their corresponding page params used to fetch them.\n\nFor example, a Pokemon API endpoint might have a string query arg like `\"fire\"`, but use a page number as the param to determine which page to fetch out of the results. For a query like `useGetPokemonInfiniteQuery('fire')`, the resulting cache data might look like this:\n\n```ts no-transpile\n{\n  queries: {\n    \"getPokemon('fire')\": {\n      data: {\n        pages: [\n          [\"Charmander\", \"Charmeleon\"],\n          [\"Charizard\", \"Vulpix\"],\n          [\"Magmar\", \"Flareon\"]\n        ],\n        pageParams: [\n          1,\n          2,\n          3\n        ]\n      }\n    }\n  }\n}\n```\n\nThis structure allows flexibility in how your UI chooses to render the data (showing individual pages, flattening into a single list), enables limiting how many pages are kept in cache, and makes it possible to dynamically determine the next or previous page to fetch based on either the data or the page params.\n\n## Defining Infinite Query Endpoints\n\nInfinite query endpoints are defined by returning an object inside the `endpoints` section of `createApi`, and defining the fields using the `build.infiniteQuery()` method. They are an extension of standard query endpoints - you can specify [the same options as standard queries](./queries.mdx#defining-query-endpoints) (providing either `query` or `queryFn`, customizing with `transformResponse`, lifecycles with `onCacheEntryAdded` and `onQueryStarted`, defining tags, etc). However, they also require an additional `infiniteQueryOptions` field to specify the infinite query behavior.\n\nWith TypeScript, you must supply 3 generic arguments: `build.infiniteQuery<ResultType, QueryArg, PageParam>`, where `ResultType` is the contents of a single page, `QueryArg` is the type passed in as the cache key, and `PageParam` is the value used to request a specific page. If there is no argument, use `void` for the arg type instead.\n\n### `infiniteQueryOptions`\n\nThe `infiniteQueryOptions` field includes:\n\n- `initialPageParam`: the default page param value used for the first request, if this was not specified at the usage site\n- `maxPages`: an optional limit to how many fetched pages will be kept in the cache entry at a time\n- `getNextPageParam`: a required callback you must provide to calculate the next page param, given the existing cached pages and page params\n- `getPreviousPageParam`: an optional callback that will be used to calculate the previous page param, if you try to fetch backwards.\n\nBoth `initialPageParam` and `getNextPageParam` are required, to\nensure the infinite query can properly fetch the next page of data. Also, `initialPageParam` may be specified when using the endpoint, to override the default value for a first fetch. `maxPages` and `getPreviousPageParam` are both optional.\n\n### Page Param Functions\n\n`getNextPageParam` and `getPreviousPageParam` are user-defined, giving you flexibility to determine how those values are calculated:\n\n```ts\nexport type PageParamFunction<DataType, PageParam, QueryArg> = (\n  currentPage: DataType,\n  allPages: DataType[],\n  currentPageParam: PageParam,\n  allPageParams: PageParam[],\n  queryArg: QueryArg,\n) => PageParam | undefined | null\n```\n\nA page param can be any value at all: numbers, strings, objects, arrays, etc. Since the existing page param values are stored in Redux state, you should still treat those immutably. For example, if you had a param structure like `{page: Number, filters: Filters}`, incrementing the page would look like `return {...currentPageParam, page: currentPageParam.page + 1}`.\n\nSince both actual page contents and page params are passed in, you can calculate new page params based on any of those. This enables a number of possible infinite query use cases, including cursor-based and limit+offset-based queries.\n\nThe \"current\" arguments will be either the last page for `getNextPageParam`, or the first page for `getPreviousPageParam`.\n\nThe list of arguments is the same as with React Query, but with the addition of `queryArg` at the end. (This is because React Query always has access to the query arg when you pass the options to its `useQuery` hook, but with RTK Query the endpoints are defined separately, so this makes the query arg accessible if you need it to calculate the page params.)\n\nIf there is no possible page to fetch in that direction, the callback should return `undefined`.\n\n### Infinite Query Definition Example\n\nA complete example of this for a fictional Pokemon API service might look like:\n\n```ts no-transpile title=\"Infinite Query definition example\"\ntype Pokemon = {\n  id: string\n  name: string\n}\n\nconst pokemonApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/pokemon' }),\n  endpoints: (build) => ({\n    // 3 TS generics: page contents, query arg, page param\n    getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n      infiniteQueryOptions: {\n        // Must provide a default initial page param value\n        initialPageParam: 1,\n        // Optionally limit the number of cached pages\n        maxPages: 3,\n        // Must provide a `getNextPageParam` function\n        getNextPageParam: (\n          lastPage,\n          allPages,\n          lastPageParam,\n          allPageParams,\n          queryArg,\n        ) => lastPageParam + 1,\n        // Optionally provide a `getPreviousPageParam` function\n        getPreviousPageParam: (\n          firstPage,\n          allPages,\n          firstPageParam,\n          allPageParams,\n          queryArg,\n        ) => {\n          return firstPageParam > 0 ? firstPageParam - 1 : undefined\n        },\n      },\n      // The `query` function receives `{queryArg, pageParam}` as its argument\n      query({ queryArg, pageParam }) {\n        return `/type/${queryArg}?page=${pageParam}`\n      },\n    }),\n  }),\n})\n```\n\n## Performing Infinite Queries with React Hooks\n\n[Similar to query endpoints](./queries.mdx#performing-queries-with-react-hooks), RTK Query will automatically generate React hooks for infinite query endpoints based on the name of the endpoint. An endpoint field with `getPokemon: build.infiniteQuery()` will generate a hook named `useGetPokemonInfiniteQuery`, as well as a generically-named hook attached to the endpoint, like `api.endpoints.getPokemon.useInfiniteQuery`.\n\n### Hook Types\n\nThere are 3 infinite query-related hooks:\n\n1. [`useInfiniteQuery`](../api/created-api/hooks.mdx#useinfinitequery)\n   - Composes `useInfiniteQuerySubscription` and `useInfiniteQueryState`, and is the primary hook. Automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store.\n2. [`useInfiniteQuerySubscription`](../api/created-api/hooks.mdx#useinfinitequerysubscription)\n   - Returns a `refetch` function and `fetchNext/PreviousPage` functions, and accepts all hooks options. Automatically triggers refetches of data from an endpoint, and 'subscribes' the component to the cached data.\n3. [`useInfiniteQueryState`](../api/created-api/hooks.mdx#useinfinitequerystate)\n   - Returns the query state and accepts `skip` and `selectFromResult`. Reads the request status and cached data from the Redux store.\n\nIn practice, the standard `useInfiniteQuery`-based hooks such as `useGetPokemonInfiniteQuery` will be the primary hooks used in your application, but the other hooks are available for specific use cases.\n\n### Query Hook Options\n\nThe query hooks expect two parameters: `(queryArg?, queryOptions?)`.\n\nThe `queryOptions` object accepts [all the same parameters as `useQuery`](./queries.mdx#query-hook-options), including `skip`, `selectFromResult`, and refetching/polling options.\n\nUnlike normal query hooks, your `query` or `queryFn` callbacks will receive a \"page param\" value to generate the URL or make the request, instead of the \"query arg\" that was passed to the hook. By default, the `initialPageParam` value specified in the endpoint will be used to make the first request, and then your `getNext/PreviousPageParam` callbacks will be used to calculate further page params as you fetch forwards or backwards.\n\nIf you want to start from a different page param, you may override the `initialPageParam` by passing it as part of the hook options:\n\n```ts no-transpile\nconst { data } = useGetPokemonInfiniteQuery('fire', {\n  initialPageParam: 3,\n})\n```\n\nThe next and previous page params will still be calculated as needed.\n\n### Frequently Used Query Hook Return Values\n\nInfinite query hooks return [the same result object as normal query hooks](./queries.mdx#frequently-used-query-hook-return-values), but with [a few additional fields specific to infinite queries](../api/created-api/hooks.mdx#useinfinitequery-signature) and a different structure for `data` and `currentData`.\n\n- `data` / `currentData`: These contain the same \"latest successful\" and \"latest for current arg\" results as normal queries, but the value is the `{pages, pageParams}` infinite query object with all fetched pages instead of a single response value.\n- `hasNextPage` / `hasPreviousPage`: When true, indicates that there _should_ be another page available to fetch in that direction. This is calculated by calling `getNext/PreviousPageParam` with the latest fetched pages.\n- `isFetchingNext/PreviousPage`: When true, indicates that the current `isFetching` flag represents a fetch in that direction.\n- `isFetchNext/PreviousPageError`: When true, indicates that the current `isError` flag represents an error for a failed fetch in that direction\n- `fetchNext/PreviousPage`: methods that will trigger a fetch for another page in that direction.\n\nIn most cases, you will probably read `data` and either `isLoading` or `isFetching` in order to render your UI. You will also want to use the `fetchNext/PreviousPage` methods to trigger fetching additional pages.\n\n### Displaying Infinite Query Data\n\nFor infinite query hooks, the `data` field returned by the hook will be the `{pages, pageParams}` structure containing all fetched pages, instead of just a single response value.\n\nThis gives you control over how the data is used for display. You can flatten all the page contents into a single array for infinite scrolling, use the individual page results for pagination, sort or reverse the entries, or any other logic you need for rendering the UI with this data.\n\nAs with any other Redux data, you should avoid mutating these arrays (including calling `array.sort/reverse()` directly on the existing references).\n\n### Infinite Query Hook Usage Example\n\nHere is an example of a typical infinite query endpoint definition, and hook usage in a component:\n\n```tsx no-transpile\ntype Pokemon = {\n  id: string\n  name: string\n}\n\nconst pokemonApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/pokemon' }),\n  endpoints: (build) => ({\n    getPokemon: build.infiniteQuery<Pokemon[], string, number>({\n      infiniteQueryOptions: {\n        initialPageParam: 1,\n        getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n          lastPageParam + 1,\n      },\n      query({ queryArg, pageParam }) {\n        return `/type/${queryArg}?page=${pageParam}`\n      },\n    }),\n  }),\n})\n\nfunction PokemonList({ pokemonType }: { pokemonType: string }) {\n  const { data, isFetching, fetchNextPage, fetchPreviousPage, refetch } =\n    pokemonApi.useGetPokemonInfiniteQuery(pokemonType)\n\n  const handleNextPage = async () => {\n    await fetchNextPage()\n  }\n\n  const handleRefetch = async () => {\n    await refetch()\n  }\n\n  const allResults = data?.pages.flat() ?? []\n\n  return (\n    <div>\n      <div>Type: {pokemonType}</div>\n      <div>\n        {allResults.map((pokemon, i: number | null | undefined) => (\n          <div key={i}>{pokemon.name}</div>\n        ))}\n      </div>\n      <button onClick={() => handleNextPage()}>Fetch More</button>\n      <button onClick={() => handleRefetch()}>Refetch</button>\n    </div>\n  )\n}\n```\n\nIn this example, the server returns an array of Pokemon as the response for each individual page. This component shows the results as a single list. Since the `data` field itself has a `pages` array of all responses, the component needs to flatten the pages into a single array to render that list. Alternately, it could map over the pages and show them in a paginated format.\n\nSimilarly, this example relies on manual user clicks on a \"Fetch More\" button to trigger fetching the next page, but could automatically call `fetchNextPage` based on things like an `IntersectionObserver`, a list component triggering some kind of \"end of the list\" event, or other similar indicators.\n\nThe endpoint itself only defines `getNextPageParam`, so this example doesn't support fetching backwards, but that can be provided in cases where backwards fetching makes sense. The page param here is a simple incremented number, but the page param\n\n## Infinite Query Behaviors\n\n### Overlapping Page Fetches\n\nSince all pages are stored in a single cache entry, there can only be one request in progress at a time. RTK Query already has logic built in to bail out of running a new request if there is already a request in flight for that cache entry.\n\nThat means that if you call `fetchNextPage()` again while an existing request is in progress, the second call won't actually execute a request. Be sure to either await the previous `fetchNextPage()` promise result first or check the `isFetching` flag if you have concerns about a potential request already in progress.\n\nThe promise returned from `fetchNextPage()` does have [a `promise.abort()` method attached](../../api/createAsyncThunk.mdx#canceling-while-running) that will force the earlier request to reject and not save the results. Note that this will mark the cache entry as errored, but the data will still exist. Since `promise.abort()` is synchronous, you would also need to await the previous promise to ensure the rejection is handled, and then trigger the new page fetch.\n\n### Refetching\n\nWhen an infinite query endpoint is refetched (due to tag invalidation, polling, arg change configuration, or manual refetching), RTK Query's default behavior is **sequentially refetching _all_ pages currently in the cache**. This ensures that the client is always working with the latest data, and avoids stale cursors or duplicate records.\n\nIf the cache entry is ever removed and then re-added, it will start with only fetching the initial page.\n\nThere may be cases when you want a refetch to _only_ refetch the first page, and not any of the other pages in cache (ie, the refetch shrinks the cache from N pages to 1 page). This can be done via the `refetchCachedPages` option, which can be passed in several different places:\n\n- Defined on the endpoint as part of `infiniteQueryOptions`: applies to all attempted refetches\n- Passed as an option to a `useInfiniteQuery` hook: applies to all attempted refetches\n- Passed as an option to `endpoint.initiate()`, or the `refetch` method available on the `initiate` or hook result objects: applies only to the manually triggered refetch\n\nOverall, the refetch logic defaults to refetching all pages, but will override that with the option provided to the endpoint or a manual refetch.\n\n### Limiting Cache Entry Size\n\nAll fetched pages for a given query arg are stored in the `pages` array in that cache entry. By default, there is no limit to the number of stored pages - if you call `fetchNextPage()` 1000 times, `data.pages` will have 1000 pages stored.\n\nIf you need to limit the number of stored pages (for reasons like memory usage), you can supply a `maxPages` option as part of the endpoint. If provided, fetching a page when already at the max will automatically drop the last page in the opposite direction. For example, with `maxPages: 3` and a cached page params of `[1, 2, 3]`, calling `fetchNextPage()` would result in page `1` being dropped and the new cached pages being `[2, 3, 4]`. From there, calling `fetchNextPage()` would result in `[3, 4, 5]`, or calling `fetchPreviousPage()` would go back to `[1, 2, 3]`.\n\n## Common Infinite Query Patterns\n\nThe `getNext/PreviousPageParam` callbacks offer flexibility in how you interact with the backend API.\n\nHere are some examples of common infinite query patterns to show how you might approach different use cases.\n\nFor additional examples, and to see some of these patterns in action, see [the RTK Query \"infinite queries\" example app in the repo](https://github.com/reduxjs/redux-toolkit/tree/master/examples/query/react/infinite-queries).\n\n### Basic Pagination\n\nFor a simple API that just needs page numbers, you can calculate the previous and next page numbers based on the existing page params:\n\n```ts no-transpile\nconst pokemonApi = createApi({\n  baseQuery,\n  endpoints: (build) => ({\n    getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({\n      infiniteQueryOptions: {\n        initialPageParam: 0,\n        getNextPageParam: (lastPage, allPages, lastPageParam) =>\n          lastPageParam + 1,\n        getPreviousPageParam: (firstPage, allPages, firstPageParam) => {\n          return firstPageParam > 0 ? firstPageParam - 1 : undefined\n        },\n      },\n      query({ pageParam }) {\n        return `https://example.com/listItems?page=${pageParam}`\n      },\n    }),\n  }),\n})\n```\n\n### Pagination with Sizes\n\nFor an API that accepts values like page number and page size and includes total pages in the response, you can calculate whether there are more pages remaining:\n\n```ts no-transpile\ntype ProjectsResponse = {\n  projects: Project[]\n  serverTime: string\n  totalPages: number\n}\n\ntype ProjectsInitialPageParam = {\n  page: number\n  size: number\n}\n\nconst projectsApi = createApi({\n  baseQuery,\n  endpoints: (build) => ({\n    projectsPaginated: build.infiniteQuery<\n      ProjectsResponse,\n      void,\n      ProjectsInitialPageParam\n    >({\n      infiniteQueryOptions: {\n        initialPageParam: {\n          page: 0,\n          size: 20,\n        },\n        getNextPageParam: (\n          lastPage,\n          allPages,\n          lastPageParam,\n          allPageParams,\n        ) => {\n          const nextPage = lastPageParam.page + 1\n          const remainingPages = lastPage?.totalPages - nextPage\n\n          if (remainingPages <= 0) {\n            return undefined\n          }\n\n          return {\n            ...lastPageParam,\n            page: nextPage,\n          }\n        },\n        getPreviousPageParam: (\n          firstPage,\n          allPages,\n          firstPageParam,\n          allPageParams,\n        ) => {\n          const prevPage = firstPageParam.page - 1\n          if (prevPage < 0) return undefined\n\n          return {\n            ...firstPageParam,\n            page: prevPage,\n          }\n        },\n      },\n      query: ({ pageParam: { page, size } }) => {\n        return `https://example.com/api/projectsPaginated?page=${page}&size=${size}`\n      },\n    }),\n  }),\n})\n```\n\n### Bidirectional Cursors\n\nIf the server sends back cursor values in the response, you can use those as the page params for the next and previous requests:\n\n```ts no-transpile\ntype ProjectsCursorPaginated = {\n  projects: Project[]\n  serverTime: string\n  pageInfo: {\n    startCursor: number\n    endCursor: number\n    hasNextPage: boolean\n    hasPreviousPage: boolean\n  }\n}\n\ntype ProjectsInitialPageParam = {\n  before?: number\n  around?: number\n  after?: number\n  limit: number\n}\ntype QueryParamLimit = number\n\nconst projectsApi = createApi({\n  baseQuery,\n  endpoints: (build) => ({\n    getProjectsBidirectionalCursor: build.infiniteQuery<\n      ProjectsCursorPaginated,\n      QueryParamLimit,\n      ProjectsInitialPageParam\n    >({\n      infiniteQueryOptions: {\n        initialPageParam: { limit: 10 },\n        getPreviousPageParam: (\n          firstPage,\n          allPages,\n          firstPageParam,\n          allPageParams,\n        ) => {\n          if (!firstPage.pageInfo.hasPreviousPage) {\n            return undefined\n          }\n          return {\n            before: firstPage.pageInfo.startCursor,\n            limit: firstPageParam.limit,\n          }\n        },\n        getNextPageParam: (\n          lastPage,\n          allPages,\n          lastPageParam,\n          allPageParams,\n        ) => {\n          if (!lastPage.pageInfo.hasNextPage) {\n            return undefined\n          }\n          return {\n            after: lastPage.pageInfo.endCursor,\n            limit: lastPageParam.limit,\n          }\n        },\n      },\n      query: ({ pageParam: { before, after, around, limit } }) => {\n        const params = new URLSearchParams()\n        params.append('limit', String(limit))\n        if (after != null) {\n          params.append('after', String(after))\n        } else if (before != null) {\n          params.append('before', String(before))\n        } else if (around != null) {\n          params.append('around', String(around))\n        }\n\n        return `https://example.com/api/projectsBidirectionalCursor?${params.toString()}`,\n      },\n    }),\n  }),\n})\n```\n\n### Limit and Offset\n\nIf the API expects a combination of limit and offset values, those can also be calculated based on the responses and page params.\n\n```ts no-transpile\nexport type ProjectsResponse = {\n  projects: Project[]\n  numFound: number\n  serverTime: string\n}\n\ntype ProjectsInitialPageParam = {\n  offset: number\n  limit: number\n}\n\nconst projectsApi = createApi({\n  baseQuery,\n  endpoints: (build) => ({\n    projectsLimitOffset: build.infiniteQuery<\n      ProjectsResponse,\n      void,\n      ProjectsInitialPageParam\n    >({\n      infiniteQueryOptions: {\n        initialPageParam: {\n          offset: 0,\n          limit: 20,\n        },\n        getNextPageParam: (\n          lastPage,\n          allPages,\n          lastPageParam,\n          allPageParams,\n        ) => {\n          const nextOffset = lastPageParam.offset + lastPageParam.limit\n          const remainingItems = lastPage?.numFound - nextOffset\n\n          if (remainingItems <= 0) {\n            return undefined\n          }\n\n          return {\n            ...lastPageParam,\n            offset: nextOffset,\n          }\n        },\n        getPreviousPageParam: (\n          firstPage,\n          allPages,\n          firstPageParam,\n          allPageParams,\n        ) => {\n          const prevOffset = firstPageParam.offset - firstPageParam.limit\n          if (prevOffset < 0) return undefined\n\n          return {\n            ...firstPageParam,\n            offset: firstPageParam.offset - firstPageParam.limit,\n          }\n        },\n      },\n      query: ({ pageParam: { offset, limit } }) => {\n        return `https://example.com/api/projectsLimitOffset?offset=${offset}&limit=${limit}`\n      },\n    }),\n  }),\n})\n```\n\n## Runtime Validation using Schemas\n\nEndpoints can use any [Standard Schema](https://standardschema.dev/) compliant library for runtime validation of query args, responses, and errors. See [API reference](../api/createApi.mdx#schema-validation) for full list of available schemas.\n\nWhen used with TypeScript, schemas can also be used to [infer the type of that value instead of having to declare it](../usage-with-typescript.mdx#schema-validation).\n\nMost commonly, you'll want to use `responseSchema` to validate the response from the server (or `rawResponseSchema` when using `transformResponse`).\n\n```ts title=\"Using responseSchema\" no-transpile\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport * as v from 'valibot'\n\nconst pokemonSchema = v.object({\n  id: v.number(),\n  name: v.string(),\n})\ntype Pokemon = v.InferOutput<typeof pokemonSchema>\nconst transformedPokemonSchema = v.object({\n  ...pokemonSchema.entries,\n  id: v.string(),\n})\ntype TransformedPokemon = v.InferOutput<typeof transformedPokemonSchema>\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/pokemon' }),\n  endpoints: (build) => ({\n    getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({\n      query: ({ queryArg, pageParam }) => `type/${queryArg}?page=${pageParam}`,\n      // argSchema for infinite queries must have both queryArg and pageParam\n      argSchema: v.object({\n        queryArg: v.string(),\n        pageParam: v.number(),\n      }),\n      responseSchema: v.array(pokemonSchema),\n    }),\n    getTransformedPokemon: build.infiniteQuery<\n      TransformedPokemon[],\n      string,\n      number\n    >({\n      query: ({ queryArg, pageParam }) => `type/${queryArg}?page=${pageParam}`,\n      argSchema: v.object({\n        queryArg: v.string(),\n        pageParam: v.number(),\n      }),\n      rawResponseSchema: v.array(pokemonSchema),\n      transformResponse: (response) =>\n        response.map((pokemon) => ({\n          ...pokemon,\n          id: String(pokemon.id),\n        })),\n      // responseSchema can still be provided, to validate the transformed response\n      responseSchema: v.array(transformedPokemonSchema),\n    }),\n  }),\n})\n```\n"
  },
  {
    "path": "docs/rtk-query/usage/manual-cache-updates.mdx",
    "content": "---\nid: manual-cache-updates\ntitle: Manual Cache Updates\nsidebar_label: Manual Cache Updates\nhide_title: true\ndescription: 'RTK Query > Usage > Manual Cache Updates: Updating and creating cached data manually'\n---\n\n&nbsp;\n\n# Manual Cache Updates\n\n## Overview\n\nFor most cases, in order to receive up to date data after a triggering a change in the backend, you can take advantage of cache tag invalidation to perform [automated re-fetching](./automated-refetching). This will cause a query to re-fetch its data when it has been told that a mutation has occurred which would cause its data to become out of date.\n\nWe recommend using automated re-fetching as a preference over manual cache updates in most situations.\n\nHowever, there _are_ use cases when manual cache updates are necessary, such as \"optimistic\" or \"pessimistic\" updates, or modifying data as part of cache entry lifecycles.\n\nRTK Query exports thunks for these use cases, attached to `api.utils`:\n\n- [`updateQueryData`](../api/created-api/api-slice-utils.mdx#updatequerydata): updates an already existing cache entry\n- [`upsertQueryData`](../api/created-api/api-slice-utils.mdx#upsertquerydata): creates or replaces cache entries\n\nSince these are thunks, you can dispatch them anywhere you have access to `dispatch`.\n\n### Updating existing cache entries\n\nFor updates of existing cache entries, use [`updateQueryData`](../api/created-api/api-slice-utils.mdx#updatequerydata).\n\n`updateQueryData` is strictly intended to perform _updates_ to existing cache entries, not create new entries. If an `updateQueryData` thunk action is dispatched and the `endpointName` + `args` combination that does not match any existing cache entry, the provided `recipe` callback will not be called, and no `patches` or `inversePatches` will be returned.\n\nUse cases for manual update of cache entries:\n\n- Providing immediate feedback to the user when a mutation is attempted\n- After a mutation, updating a single item in a large list of items that is already cached, rather than re-fetching the whole list\n- Debouncing a large number of mutations with immediate feedback as though they are being applied, followed by a single request sent to the server to update the debounced attempts\n\n### Creating new cache entries or replacing existing ones\n\nTo create or replace existing cache entries, use [`upsertQueryData`](../api/created-api/api-slice-utils.mdx#upsertquerydata).\n\n`upsertQueryData` is intended to perform _replacements_ to existing cache entries or _creation_ of new ones. Since `upsertQueryData` does not have access to the previous state of the cache entry, the update may be performed only as a replacement. In comparison, `updateQueryData` allows patching of the existing cache entry, but cannot create a new one.\n\nOne example use case is [pessimistic updates](../usage/manual-cache-updates.mdx#pessimistic-updates). If the client makes an API call to create a `Post`, the backend could return its complete data including the `id`. Then we can use `upsertQueryData` to create a new cache entry for the `getPostById(id)` query, preventing an extra fetch to retrieve the item later.\n\n## Recipes\n\n### Optimistic Updates\n\nWhen you wish to perform an update to cache data immediately after a [`mutation`](./mutations) is\ntriggered, you can apply an `optimistic update`. This can be a useful pattern for when you want to\ngive the user the impression that their changes are immediate, even while the mutation request is\nstill in flight.\n\nThe core concepts for an optimistic update are:\n\n- when you start a query or mutation, `onQueryStarted` will be executed\n- you manually update the cached data by dispatching `api.util.updateQueryData` within `onQueryStarted`\n- then, in the case that `queryFulfilled` rejects:\n  - you roll it back via the `.undo` property of the object you got back from the earlier dispatch,\n    OR\n  - you invalidate the cache data via `api.util.invalidateTags` to trigger a full re-fetch of the data\n\n:::tip\nWhere many mutations are potentially triggered in short succession causing overlapping requests,\nyou may encounter race conditions if attempting to roll back patches using the `.undo` property\non failures. For these scenarios, it is often simplest and safest to invalidate the tags on error\ninstead, and re-fetch truly up-to-date data from the server.\n:::\n\n```ts title=\"Optimistic update mutation example (async await)\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n  }),\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    getPost: build.query<Post, number>({\n      query: (id) => `post/${id}`,\n      providesTags: ['Post'],\n    }),\n    updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n      query: ({ id, ...patch }) => ({\n        url: `post/${id}`,\n        method: 'PATCH',\n        body: patch,\n      }),\n      // highlight-start\n      async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n        const patchResult = dispatch(\n          api.util.updateQueryData('getPost', id, (draft) => {\n            Object.assign(draft, patch)\n          }),\n        )\n        try {\n          await queryFulfilled\n        } catch {\n          patchResult.undo()\n\n          /**\n           * Alternatively, on failure you can invalidate the corresponding cache tags\n           * to trigger a re-fetch:\n           * dispatch(api.util.invalidateTags(['Post']))\n           */\n        }\n      },\n      // highlight-end\n    }),\n  }),\n})\n```\n\nor, if you prefer the slightly shorter version with `.catch`\n\n```diff\n-      async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n+      onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n        const patchResult = dispatch(\n          api.util.updateQueryData('getPost', id, (draft) => {\n            Object.assign(draft, patch)\n          })\n        )\n-       try {\n-         await queryFulfilled\n-       } catch {\n-         patchResult.undo()\n-       }\n+       queryFulfilled.catch(patchResult.undo)\n      }\n```\n\n#### Example\n\n[React Optimistic Updates](./examples#react-optimistic-updates)\n\n### Pessimistic Updates\n\nWhen you wish to perform an update to cache data based on the response received from the server\nafter a [`mutation`](./mutations) is triggered, you can apply a `pessimistic update`.\nThe distinction between a `pessimistic update` and an `optimistic update` is that the\n`pessimistic update` will instead wait for the response from the server prior to updating\nthe cached data.\n\nThe core concepts for a pessimistic update are:\n\n- when you start a query or mutation, `onQueryStarted` will be executed\n- you await `queryFulfilled` to resolve to an object containing the transformed response from the\n  server in the `data` property\n- you manually update the cached data by dispatching `api.util.updateQueryData` within\n  `onQueryStarted`, using the data in the response from the server for your draft updates\n- you manually create a new cache entry by dispatching `api.util.upsertQueryData` within `onQueryStarted`,\n  using the complete Post object returned by backend.\n\n```ts title=\"Pessimistic update mutation example (async await)\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n  }),\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    getPost: build.query<Post, number>({\n      query: (id) => `post/${id}`,\n      providesTags: ['Post'],\n    }),\n    updatePost: build.mutation<Post, Pick<Post, 'id'> & Partial<Post>>({\n      query: ({ id, ...patch }) => ({\n        url: `post/${id}`,\n        method: 'PATCH',\n        body: patch,\n      }),\n      // highlight-start\n      async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n        try {\n          const { data: updatedPost } = await queryFulfilled\n          const patchResult = dispatch(\n            api.util.updateQueryData('getPost', id, (draft) => {\n              Object.assign(draft, updatedPost)\n            }),\n          )\n        } catch {}\n      },\n      // highlight-end\n    }),\n    createPost: build.mutation<Post, Pick<Post, 'id'> & Partial<Post>>({\n      query: ({ id, ...body }) => ({\n        url: `post/${id}`,\n        method: 'POST',\n        body,\n      }),\n      // highlight-start\n      async onQueryStarted({ id }, { dispatch, queryFulfilled }) {\n        try {\n          const { data: createdPost } = await queryFulfilled\n          const patchResult = dispatch(\n            api.util.upsertQueryData('getPost', id, createdPost),\n          )\n        } catch {}\n      },\n      // highlight-end\n    }),\n  }),\n})\n```\n\n### General Updates\n\nIf you find yourself wanting to update cache data elsewhere in your application, you can do so\nanywhere you have access to the `store.dispatch` method, including within React components via\nthe [useDispatch](https://react-redux.js.org/api/hooks#usedispatch) hook (or a typed version such\nas [useAppDispatch](https://react-redux.js.org/using-react-redux/usage-with-typescript#define-typed-hooks)\nfor typescript users).\n\n:::info\nYou should generally avoid manually updating the cache outside of the `onQueryStarted`\ncallback for a mutation without a good reason, as RTK Query is intended to be used by considering\nyour cached data as a reflection of the server-side state.\n:::\n\n```tsx no-transpile title=\"General manual cache update example\"\nimport { api } from './api'\nimport { useAppDispatch } from './store/hooks'\n\nfunction App() {\n  const dispatch = useAppDispatch()\n\n  function handleClick() {\n    /**\n     * This will update the cache data for the query corresponding to the `getPosts` endpoint,\n     * when that endpoint is used with no argument (undefined).\n     */\n    const patchCollection = dispatch(\n      api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n        draftPosts.push({ id: 1, name: 'Teddy' })\n      }),\n    )\n  }\n\n  return <button onClick={handleClick}>Add post to cache</button>\n}\n```\n"
  },
  {
    "path": "docs/rtk-query/usage/migrating-to-rtk-query.mdx",
    "content": "---\nid: migrating-to-rtk-query\ntitle: Migrating to RTK Query\nsidebar_label: Migrating to RTK Query\nhide_title: true\ndescription: 'RTK Query > Usage > Migrating to RTKQ: how to convert logic to RTKQ'\n---\n\n&nbsp;\n\n# Migrating to RTK Query\n\n:::tip What You'll Learn\n\n- How to convert conventional data-fetching logic implemented with Redux Toolkit + `createAsyncThunk` to use Redux Toolkit Query\n\n:::\n\n## Overview\n\nThe most common use case for side effects in Redux apps is fetching data. Redux apps typically use a tool like thunks, sagas, or observables to make an AJAX request, and [dispatch actions based on the results of the request](https://redux.js.org/tutorials/fundamentals/part-7-standard-patterns#async-request-status). Reducers then listen for those actions to manage loading state and cache the fetched data.\n\nRTK Query is purpose-built to solve the use case of data fetching. While it can't replace all of the situations where you'd use thunks or other side effects approaches, **using RTK Query should eliminate the need for most of that hand-written side effects logic**.\n\nRTK Query is expected to cover a lot of overlapping behavior that users may have previously used `createAsyncThunk` for, including caching purposes, and request lifecycle management (e.g. `isUninitialized`, `isLoading`, `isError` states).\n\nIn order to migrate data-fetching features from existing Redux tools to RTK Query, the appropriate endpoints should be added to an RTK Query API slice, and the previous feature code deleted. This generally will not include much common code kept between the two, as the tools work differently and one will replace the other.\n\nIf you're looking to get started with RTK Query from scratch, you may also wish to see [`RTK Query Quick Start`](../../tutorials/rtk-query.mdx).\n\n## Example - Migrating data-fetching logic from Redux Toolkit to RTK Query\n\nA common method used to implement simple, cached, data-fetching logic with Redux is to set up a slice using `createSlice`, with state containing the associated `data` and `status` for a query, using `createAsyncThunk` to handle the asynchronous request lifecycles. Below we will explore an example of such an implementation, and how we can later go about migrating that code to use RTK Query instead.\n\n:::note\nRTK Query also provides many more features than what is created with the thunk example shown below. The example is only intended to demonstrate how the particular implementation could be replaced with RTK Query.\n:::\n\n### Design specifications\n\nFor our example, the design specifications required for the tool are as follows:\n\n- Provide a hook to fetch data for a `pokemon` using the api: https://pokeapi.co/api/v2/pokemon/bulbasaur, where bulbasaur can be any pokemon name\n- A request for any given name should only be sent if it hasn't already done so for the session\n- The hook should provide us with the current status of the request for the supplied pokemon name; whether it is in an 'uninitialized', 'pending', 'fulfilled', or 'rejected' state\n- The hook should provide us with the current data for the supplied pokemon name\n\nWith the above specifications in mind, lets first look at an overview of how this could be implemented traditionally using `createAsyncThunk` combined with `createSlice`.\n\n## Implementation using `createSlice` & `createAsyncThunk`\n\n### Slice file\n\nThe three snippets below make up our slice file. This file is concerned with managing our asynchronous request lifecycles, as well as storing our data & request statuses for a given pokemon name.\n\n#### Thunk action creator\n\nBelow we create a thunk action creator using [`createAsyncThunk`](../../api/createAsyncThunk.mdx) in order to manage asynchronous request lifecycles. This will be accessible within components & hooks to be dispatched, in order to fire off a request for some pokemon data. `createAsyncThunk` itself will handle dispatching lifecycle methods for our request: `pending`, `fulfilled`, and `rejected`, which we will handle within our slice.\n\n```ts title=\"src/services/pokemonSlice.ts - Thunk Action Creator\" no-transpile\nimport { createAsyncThunk, createSlice } from '@reduxjs/toolkit'\nimport type { Pokemon } from './types'\nimport type { RootState } from '../store'\n\n// highlight-start\nexport const fetchPokemonByName = createAsyncThunk<Pokemon, string>(\n  'pokemon/fetchByName',\n  async (name, { rejectWithValue }) => {\n    const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${name}`)\n    const data = await response.json()\n    if (response.status < 200 || response.status >= 300) {\n      return rejectWithValue(data)\n    }\n    return data\n  },\n)\n// highlight-end\n\n// slice & selectors omitted\n```\n\n#### Slice\n\nBelow we have our `slice` created with [`createSlice`](../../api/createSlice.mdx). We have our reducers containing our request handling logic defined here, storing the appropriate 'status' and 'data' in our state based on the name we search with.\n\n```ts title=\"src/services/pokemonSlice.ts - slice logic\" no-transpile\n// imports & thunk action creator omitted\n\n// highlight-start\ntype RequestState = 'pending' | 'fulfilled' | 'rejected'\n// highlight-end\n\nexport const pokemonSlice = createSlice({\n  name: 'pokemon',\n  initialState: {\n    // highlight-start\n    dataByName: {} as Record<string, Pokemon | undefined>,\n    statusByName: {} as Record<string, RequestState | undefined>,\n    // highlight-end\n  },\n  reducers: {},\n  extraReducers: (builder) => {\n    // highlight-start\n    // When our request is pending:\n    // - store the 'pending' state as the status for the corresponding pokemon name\n    builder.addCase(fetchPokemonByName.pending, (state, action) => {\n      state.statusByName[action.meta.arg] = 'pending'\n    })\n    // When our request is fulfilled:\n    // - store the 'fulfilled' state as the status for the corresponding pokemon name\n    // - and store the received payload as the data for the corresponding pokemon name\n    builder.addCase(fetchPokemonByName.fulfilled, (state, action) => {\n      state.statusByName[action.meta.arg] = 'fulfilled'\n      state.dataByName[action.meta.arg] = action.payload\n    })\n    // When our request is rejected:\n    // - store the 'rejected' state as the status for the corresponding pokemon name\n    builder.addCase(fetchPokemonByName.rejected, (state, action) => {\n      state.statusByName[action.meta.arg] = 'rejected'\n    })\n    // highlight-end\n  },\n})\n\n// selectors omitted\n```\n\n#### Selectors\n\nBelow we have our selectors defined, allowing us to later access the appropriate status & data for any given pokemon name.\n\n```ts title=\"src/services/pokemonSlice.ts - selectors\" no-transpile\n// imports, thunk action creator & slice omitted\n\n// highlight-start\nexport const selectStatusByName = (state: RootState, name: string) =>\n  state.pokemon.statusByName[name]\nexport const selectDataByName = (state: RootState, name: string) =>\n  state.pokemon.dataByName[name]\n// highlight-end\n```\n\n### Store\n\nIn our `store` for our app, we include the corresponding reducer from our slice under the `pokemon` branch in our state tree. This lets our store handle the appropriate actions for our requests we will dispatch when running the app, using the logic defined previously.\n\n```ts title=\"src/services/store.ts\"\n// file: src/services/pokemonSlice.ts noEmit\nimport type { Reducer } from '@reduxjs/toolkit'\ndeclare const reducer: Reducer<{}>\nexport const pokemonSlice = {\n  reducer,\n}\n\n// file: src/store.ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport { pokemonSlice } from './services/pokemonSlice'\n\nexport const store = configureStore({\n  reducer: {\n    // highlight-start\n    pokemon: pokemonSlice.reducer,\n    // highlight-end\n  },\n})\n\nexport type RootState = ReturnType<typeof store.getState>\n```\n\nIn order to have the store accessible within our app, we will wrap our `App` component with a [`Provider`](https://react-redux.js.org/api/provider) component from `react-redux`.\n\n```tsx no-transpile title=\"src/index.ts\"\nimport { render } from 'react-dom'\n// highlight-start\nimport { Provider } from 'react-redux'\n// highlight-end\n\nimport App from './App'\n// highlight-start\nimport { store } from './store'\n// highlight-end\n\nconst rootElement = document.getElementById('root')\nrender(\n  // highlight-start\n  <Provider store={store}>\n    <App />\n  </Provider>,\n  // highlight-end\n  rootElement,\n)\n```\n\n### Custom hook\n\nBelow we create a hook to manage sending our request at the appropriate time, as well as obtaining the appropriate data & status from the store. [`useDispatch`](https://react-redux.js.org/api/hooks#usedispatch) and [`useSelector`](https://react-redux.js.org/api/hooks#useselector) are used from [`react-redux`](https://react-redux.js.org/introduction/getting-started) in order to communicate with the Redux store. At the end of our hook, we return the information in a neat, packaged object to be accessed in components.\n\n```ts title=\"src/hooks.ts\"\n// file: src/services/pokemonSlice.ts noEmit\nimport { AsyncThunkAction } from '@reduxjs/toolkit'\nimport { RootState } from '../store'\ninterface Pokemon {}\nexport declare const fetchPokemonByName: (\n  arg: string,\n) => AsyncThunkAction<Pokemon, string, {}>\n\nexport const selectStatusByName = (state: RootState, name: string) =>\n  state.pokemon.statusByName[name]\nexport const selectDataByName = (state: RootState, name: string) =>\n  state.pokemon.dataByName[name]\n\n// file: src/store.ts noEmit\nimport { useDispatch } from 'react-redux'\nimport { EnhancedStore } from '@reduxjs/toolkit'\ninterface Pokemon {}\ntype RequestState = 'pending' | 'fulfilled' | 'rejected'\n\nconst initialPokemonSlice = {\n  dataByName: {} as Record<string, Pokemon | undefined>,\n  statusByName: {} as Record<string, RequestState | undefined>,\n}\nexport type RootState = {\n  pokemon: typeof initialPokemonSlice\n}\n\nexport declare const store: EnhancedStore<RootState>\nexport type AppDispatch = typeof store.dispatch\nexport declare const useAppDispatch: () => (...args: any[]) => any\n\n// file: src/hooks.ts\nimport { useEffect } from 'react'\nimport { useSelector } from 'react-redux'\nimport { useAppDispatch } from './store'\nimport type { RootState } from './store'\nimport {\n  fetchPokemonByName,\n  selectStatusByName,\n  selectDataByName,\n} from './services/pokemonSlice'\n\n// highlight-start\nexport function useGetPokemonByNameQuery(name: string) {\n  const dispatch = useAppDispatch()\n  // select the current status from the store state for the provided name\n  const status = useSelector((state: RootState) =>\n    selectStatusByName(state, name),\n  )\n  // select the current data from the store state for the provided name\n  const data = useSelector((state: RootState) => selectDataByName(state, name))\n  useEffect(() => {\n    // upon mount or name change, if status is uninitialized, send a request\n    // for the pokemon name\n    if (status === undefined) {\n      dispatch(fetchPokemonByName(name))\n    }\n  }, [status, name, dispatch])\n\n  // derive status booleans for ease of use\n  const isUninitialized = status === undefined\n  const isLoading = status === 'pending' || status === undefined\n  const isError = status === 'rejected'\n  const isSuccess = status === 'fulfilled'\n\n  // return the import data for the caller of the hook to use\n  return { data, isUninitialized, isLoading, isError, isSuccess }\n}\n// highlight-end\n```\n\n### Using the custom hook\n\nOur code above meets all of the design specifications, so let's use it! Below we can see how the hook can be called in a component, and return the relevant data & status booleans.\n\nOur implementation below provides the following behavior in the component:\n\n- When our component is mounted, if a request for the provided pokemon name has not already been sent for the session, send the request off\n- The hook always provides the latest received `data` when available, as well as the request status booleans `isUninitialized`, `isPending`, `isFulfilled` & `isRejected` in order to determine the current UI at any given moment as a function of our state.\n\n```tsx no-transpile title=\"src/App.tsx\"\nimport * as React from 'react'\n// highlight-start\nimport { useGetPokemonByNameQuery } from './hooks'\n// highlight-end\n\nexport default function App() {\n  // highlight-start\n  const { data, isError, isLoading } = useGetPokemonByNameQuery('bulbasaur')\n  // highlight-end\n\n  return (\n    <div className=\"App\">\n      {isError ? (\n        <>Oh no, there was an error</>\n      ) : isLoading ? (\n        <>Loading...</>\n      ) : data ? (\n        <>\n          <h3>{data.species.name}</h3>\n          <img src={data.sprites.front_shiny} alt={data.species.name} />\n        </>\n      ) : null}\n    </div>\n  )\n}\n```\n\nA runnable example of the above code can be seen below:\n\n<iframe\n  src=\"https://codesandbox.io/s/data-fetchingcaching-example-rtk-with-thunks-5kf80?fontsize=12&runonclick=1&hidenavigation=1&module=%2Fsrc%2Fservices/pokemonSlice.ts&theme=dark&view=preview\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"Data Fetching Example - RTK with Thunks\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\n## Converting to RTK Query\n\nOur implementation above _does_ work perfectly fine for the requirements specified, however, extending the code to include further endpoints could involve a lot of repetition. It also has some certain limitations that may not be immediately obvious. For example, multiple components rendering simultaneously calling our hook would each send off a request for bulbasaur at the same time!\n\nBelow we will walk through how a lot of the boilerplate can be avoided by migrating the above code to use RTK Query instead. RTK Query will also handle many other situations for us, including de-duping requests on a more granular level to prevent sending unnecessary duplicate requests like that brought up above.\n\n### API Slice File\n\nOur code below is for our API slice definition. This acts as our network API interface layer, and is created using [`createApi`](../api/createApi.mdx). This file will contain our endpoint definition, and `createApi` will provide us with an auto-generated hook which manages firing our request only when necessary, as well as providing us with request status lifecycle booleans.\n\nThis will completely cover our logic implemented above for the entire slice file, including the thunk, slice definition, selectors, _and_ our custom hook!\n\n```ts title=\"src/services/api.ts\"\n// file: types.ts noEmit\nexport interface Pokemon {}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Pokemon } from './types'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  reducerPath: 'pokemonApi',\n  endpoints: (build) => ({\n    // highlight-start\n    getPokemonByName: build.query<Pokemon, string>({\n      query: (name) => `pokemon/${name}`,\n    }),\n    // highlight-end\n  }),\n})\n\n// highlight-start\nexport const { useGetPokemonByNameQuery } = api\n// highlight-end\n```\n\n### Connecting the API slice to the store\n\nNow that we have our API definition created, we need to hook it up to our store. In order to do that, we will need to use the [`reducerPath`](../api/created-api/redux-integration.mdx#reducerpath) and [`middleware`](../api/created-api/redux-integration.mdx#middleware) properties from our created `api`. This will allow the store to process the internal actions that the generated hook uses, allows the generated API logic to find the state correctly, and adds the logic for managing caching, invalidation, subscriptions, polling, and more.\n\n```ts title=\"src/store.ts\"\n// file: src/services/pokemonSlice.ts noEmit\nimport type { Reducer } from '@reduxjs/toolkit'\ndeclare const reducer: Reducer<{}>\nexport const pokemonSlice = {\n  reducer,\n}\n\n// file: src/services/api.ts noEmit\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\ninterface Pokemon {}\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (build) => ({\n    getPokemonByName: build.query<Pokemon, string>({\n      query: (name) => `pokemon/${name}`,\n    }),\n  }),\n})\n\n// file: src/store.ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport { pokemonSlice } from './services/pokemonSlice'\n// highlight-start\nimport { api } from './services/api'\n// highlight-end\n\nexport const store = configureStore({\n  reducer: {\n    pokemon: pokemonSlice.reducer,\n    // highlight-start\n    [api.reducerPath]: api.reducer,\n    // highlight-end\n  },\n  // highlight-start\n  middleware: (gDM) => gDM().concat(api.middleware),\n  // highlight-end\n})\n\nexport type RootState = ReturnType<typeof store.getState>\n```\n\n### Using our auto-generated hook\n\nAt this basic level, the usage of the auto-generated hook is identical to our custom hook! All we need to do is change our import path and we're good to go!\n\n```diff title=\"src/App.tsx\"\n  import * as React from 'react'\n- import { useGetPokemonByNameQuery } from './hooks'\n+ import { useGetPokemonByNameQuery } from './services/api'\n\n  export default function App() {\n    const { data, isError, isLoading } = useGetPokemonByNameQuery('bulbasaur')\n\n\n    return (\n      <div className=\"App\">\n        {isError ? (\n          <>Oh no, there was an error</>\n        ) : isLoading ? (\n          <>Loading...</>\n        ) : data ? (\n          <>\n            <h3>{data.species.name}</h3>\n            <img src={data.sprites.front_shiny} alt={data.species.name} />\n          </>\n        ) : null}\n      </div>\n    )\n  }\n```\n\n### Cleaning up unused code\n\nAs mentioned previously, our `api` definition has replaced all of the logic that we implemented previously using `createAsyncThunk`, `createSlice`, and our custom hook definition.\n\nGiven that we're no longer using that slice any longer, we can remove the import and reducer from our store:\n\n```diff title=\"src/store.ts\"\n  import { configureStore } from '@reduxjs/toolkit'\n- import { pokemonSlice } from './services/pokemonSlice'\n  import { api } from './services/api'\n\n\n  export const store = configureStore({\n    reducer: {\n-     pokemon: pokemonSlice.reducer,\n      [api.reducerPath]: api.reducer,\n    },\n    middleware: (gDM) => gDM().concat(api.middleware),\n  })\n\n  export type RootState = ReturnType<typeof store.getState>\n```\n\nWe can also remove the _entire slice and hook files_ completely!\n\n```diff\n- src/services/pokemonSlice.ts (-51 lines)\n- src/hooks.ts (-34 lines)\n```\n\nWe've now re-implemented the full set of design specifications (and more!) in less than 20 lines of code, with room to easily expand by adding additional endpoints onto our api definition.\n\nA runnable example of our re-factored implementation using RTK Query can be seen below:\n\n<iframe\n  src=\"https://codesandbox.io/s/data-fetchingcaching-example-rtk-query-ndmwo?fontsize=12&runonclick=1&hidenavigation=1&module=%2Fsrc%2Fservices/api.ts&theme=dark&view=preview\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"Data Fetching Example - RTK with Thunks\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n"
  },
  {
    "path": "docs/rtk-query/usage/mutations.mdx",
    "content": "---\nid: mutations\ntitle: Mutations\nsidebar_label: Mutations\nhide_title: true\ndescription: 'RTK Query > Usage > Mutations: sending updates to the server'\n---\n\n&nbsp;\n\n# Mutations\n\n## Overview\n\nMutations are used to send data updates to the server and apply the changes to the local cache. Mutations can also invalidate cached data and force re-fetches.\n\n## Defining Mutation Endpoints\n\nMutation endpoints are defined by returning an object inside the `endpoints` section of `createApi`, and defining the fields using the `build.mutation()` method.\n\nMutation endpoints should define either a `query` callback that constructs the URL (including any URL query params), or [a `queryFn` callback](./customizing-queries.mdx#customizing-queries-with-queryfn) that may do arbitrary async logic and return a result. The `query` callback may also return an object containing the URL, the HTTP method to use and a request body.\n\nIf the `query` callback needs additional data to generate the URL, it should be written to take a single argument. If you need to pass in multiple parameters, pass them formatted as a single \"options object\".\n\nMutation endpoints may also modify the response contents before the result is cached, define \"tags\" to identify cache invalidation, and provide cache entry lifecycle callbacks to run additional logic as cache entries are added and removed.\n\nWhen used with TypeScript, you should supply generics for the return type and the expected query argument: `build.mutation<ReturnType, ArgType>`. If there is no argument, use `void` for the arg type instead.\n\n```ts title=\"Example of all mutation endpoint options\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n  }),\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    // The mutation accepts a `Partial<Post>` arg, and returns a `Post`\n    updatePost: build.mutation<Post, Partial<Post> & Pick<Post, 'id'>>({\n      // highlight-start\n      // note: an optional `queryFn` may be used in place of `query`\n      query: ({ id, ...patch }) => ({\n        url: `post/${id}`,\n        method: 'PATCH',\n        body: patch,\n      }),\n      // Pick out data and prevent nested properties in a hook or selector\n      transformResponse: (response: { data: Post }, meta, arg) => response.data,\n      // Pick out errors and prevent nested properties in a hook or selector\n      transformErrorResponse: (\n        response: { status: string | number },\n        meta,\n        arg,\n      ) => response.status,\n      invalidatesTags: ['Post'],\n      // onQueryStarted is useful for optimistic updates\n      // The 2nd parameter is the destructured `MutationLifecycleApi`\n      async onQueryStarted(\n        arg,\n        { dispatch, getState, queryFulfilled, requestId, extra, getCacheEntry },\n      ) {},\n      // The 2nd parameter is the destructured `MutationCacheLifecycleApi`\n      async onCacheEntryAdded(\n        arg,\n        {\n          dispatch,\n          getState,\n          extra,\n          requestId,\n          cacheEntryRemoved,\n          cacheDataLoaded,\n          getCacheEntry,\n        },\n      ) {},\n      // highlight-end\n    }),\n  }),\n})\n```\n\n:::info\n\nThe `onQueryStarted` method can be used for [optimistic updates](./manual-cache-updates.mdx#optimistic-updates)\n\n:::\n\n## Performing Mutations with React Hooks\n\n### Mutation Hook Behavior\n\nUnlike `useQuery`, `useMutation` returns a tuple. The first item in the tuple is the \"trigger\" function and the second element contains an object with `status`, `error`, and `data`.\n\nUnlike the `useQuery` hook, the `useMutation` hook doesn't execute automatically. To run a mutation you have to call the trigger function returned as the first tuple value from the hook.\n\nSee [`useMutation`](../api/created-api/hooks.mdx#usemutation) for the hook signature and additional details.\n\n### Frequently Used Mutation Hook Return Values\n\nThe `useMutation` hook returns a tuple containing a \"mutation trigger\" function, as well as an object containing properties about the \"mutation result\".\n\nThe \"mutation trigger\" is a function that when called, will fire off the mutation request for that endpoint. Calling the \"mutation trigger\" returns a promise with an `unwrap` property, which can be called to unwrap the mutation call and provide the raw response/error. This can be useful if you wish to determine whether the mutation succeeds/fails inline at the call-site.\n\nThe \"mutation result\" is an object containing properties such as the latest `data` for the mutation request, as well as status booleans for the current request lifecycle state.\n\nBelow are some of the most frequently used properties on the \"mutation result\" object. Refer to [`useMutation`](../api/created-api/hooks.mdx#usemutation) for an extensive list of all returned properties.\n\n- `data` - The data returned from the latest trigger response, if present. If subsequent triggers from the same hook instance are called, this will return undefined until the new data is received. Consider component level caching if the previous response data is required for a smooth transition to new data.\n- `error` - The error result if present.\n- `isUninitialized` - When true, indicates that the mutation has not been fired yet.\n- `isLoading` - When true, indicates that the mutation has been fired and is awaiting a response.\n- `isSuccess` - When true, indicates that the last mutation fired has data from a successful request.\n- `isError` - When true, indicates that the last mutation fired resulted in an error state.\n- `reset` - A method to reset the hook back to its original state and remove the current result from the cache\n\n:::note\n\nWith RTK Query, a mutation does not contain a semantic distinction between 'loading' and 'fetching' in the way that a [query does](./queries.mdx#frequently-used-query-hook-return-values). For a mutation, subsequent calls are not assumed to be necessarily related, so a mutation is either 'loading' or 'not loading', with no concept of 're-fetching'.\n\n:::\n\n### Shared Mutation Results\n\nBy default, separate instances of a `useMutation` hook are not inherently related to each other.\nTriggering one instance will not affect the result for a separate instance. This applies regardless\nof whether the hooks are called within the same component, or different components.\n\n```tsx no-transpile\nexport const ComponentOne = () => {\n  // Triggering `updatePostOne` will affect the result in this component,\n  // but not the result in `ComponentTwo`, and vice-versa\n  const [updatePost, result] = useUpdatePostMutation()\n\n  return <div>...</div>\n}\n\nexport const ComponentTwo = () => {\n  const [updatePost, result] = useUpdatePostMutation()\n\n  return <div>...</div>\n}\n```\n\nRTK Query provides an option to share results across mutation hook instances using the\n`fixedCacheKey` option.\nAny `useMutation` hooks with the same `fixedCacheKey` string will share results between each other\nwhen any of the trigger functions are called. This should be a unique string shared between each\nmutation hook instance you wish to share results.\n\n```tsx no-transpile\nexport const ComponentOne = () => {\n  // Triggering `updatePostOne` will affect the result in both this component,\n  // but as well as the result in `ComponentTwo`, and vice-versa\n  const [updatePost, result] = useUpdatePostMutation({\n    fixedCacheKey: 'shared-update-post',\n  })\n\n  return <div>...</div>\n}\n\nexport const ComponentTwo = () => {\n  const [updatePost, result] = useUpdatePostMutation({\n    fixedCacheKey: 'shared-update-post',\n  })\n\n  return <div>...</div>\n}\n```\n\n:::note\n\nWhen using `fixedCacheKey`, the `originalArgs` property is not able to be shared and will always be `undefined`.\n\n:::\n\n### Standard Mutation Example\n\nThis is a modified version of the complete example you can see at the bottom of the page to highlight the `updatePost` mutation. In this scenario, a post is fetched with `useQuery`, and then an `EditablePostName` component is rendered that allows us to edit the name of the post.\n\n```tsx no-transpile title=\"src/features/posts/PostDetail.tsx\"\nexport const PostDetail = () => {\n  const { id } = useParams<{ id: any }>()\n\n  const { data: post } = useGetPostQuery(id)\n\n  // highlight-start\n  const [\n    updatePost, // This is the mutation trigger\n    { isLoading: isUpdating }, // This is the destructured mutation result\n  ] = useUpdatePostMutation()\n  // highlight-end\n\n  return (\n    <Box p={4}>\n      <EditablePostName\n        name={post.name}\n        onUpdate={(name) => {\n          // If you want to immediately access the result of a mutation, you need to chain `.unwrap()`\n          // if you actually want the payload or to catch the error.\n          // Example: `updatePost().unwrap().then(fulfilled => console.log(fulfilled)).catch(rejected => console.error(rejected))\n\n          return (\n            // highlight-start\n            // Execute the trigger with the `id` and updated `name`\n            updatePost({ id, name })\n            // highlight-end\n          )\n        }}\n        // highlight-start\n        isLoading={isUpdating}\n        // highlight-end\n      />\n    </Box>\n  )\n}\n```\n\n## Advanced Mutations with Revalidation\n\nIn the real world, it's very common that a developer would want to resync their local data cache with the server after performing a mutation (aka \"revalidation\"). RTK Query takes a more centralized approach to this and requires you to configure the invalidation behavior in your API service definition. See [Advanced Invalidation with abstract tag IDs](./automated-refetching#advanced-invalidation-with-abstract-tag-ids) for details on advanced invalidation handling with RTK Query.\n\n### Revalidation Example\n\nThis is an example of a [CRUD service](https://en.wikipedia.org/wiki/Create,_read,_update_and_delete) for Posts. This implements the [Selectively invalidating lists](./automated-refetching#selectively-invalidating-lists) strategy and will most likely serve as a good foundation for real applications.\n\n```ts title=\"src/app/services/posts.ts\"\n// Or from '@reduxjs/toolkit/query' if not using the auto-generated hooks\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport interface Post {\n  id: number\n  name: string\n}\n\ntype PostsResponse = Post[]\n\nexport const postApi = createApi({\n  reducerPath: 'postsApi',\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  tagTypes: ['Posts'],\n  endpoints: (build) => ({\n    getPosts: build.query<PostsResponse, void>({\n      query: () => 'posts',\n      // Provides a list of `Posts` by `id`.\n      // If any mutation is executed that `invalidate`s any of these tags, this query will re-run to be always up-to-date.\n      // The `LIST` id is a \"virtual id\" we just made up to be able to invalidate this query specifically if a new `Posts` element was added.\n      providesTags: (result) =>\n        // is result available?\n        result\n          ? // successful query\n            [\n              ...result.map(({ id }) => ({ type: 'Posts', id }) as const),\n              { type: 'Posts', id: 'LIST' },\n            ]\n          : // an error occurred, but we still want to refetch this query when `{ type: 'Posts', id: 'LIST' }` is invalidated\n            [{ type: 'Posts', id: 'LIST' }],\n    }),\n    addPost: build.mutation<Post, Partial<Post>>({\n      query(body) {\n        return {\n          url: `post`,\n          method: 'POST',\n          body,\n        }\n      },\n      // Invalidates all Post-type queries providing the `LIST` id - after all, depending of the sort order,\n      // that newly created post could show up in any lists.\n      invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n    }),\n    getPost: build.query<Post, number>({\n      query: (id) => `post/${id}`,\n      providesTags: (result, error, id) => [{ type: 'Posts', id }],\n    }),\n    updatePost: build.mutation<Post, Partial<Post>>({\n      query(data) {\n        const { id, ...body } = data\n        return {\n          url: `post/${id}`,\n          method: 'PUT',\n          body,\n        }\n      },\n      // Invalidates all queries that subscribe to this Post `id` only.\n      // In this case, `getPost` will be re-run. `getPosts` *might*  rerun, if this id was under its results.\n      invalidatesTags: (result, error, { id }) => [{ type: 'Posts', id }],\n    }),\n    deletePost: build.mutation<{ success: boolean; id: number }, number>({\n      query(id) {\n        return {\n          url: `post/${id}`,\n          method: 'DELETE',\n        }\n      },\n      // Invalidates all queries that subscribe to this Post `id` only.\n      invalidatesTags: (result, error, id) => [{ type: 'Posts', id }],\n    }),\n  }),\n})\n\nexport const {\n  useGetPostsQuery,\n  useAddPostMutation,\n  useGetPostQuery,\n  useUpdatePostMutation,\n  useDeletePostMutation,\n} = postApi\n```\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/mutations?fontsize=14&runonclick=1&hidenavigation=1&module=%2Fsrc%2Fapp%2Fservices%2Fposts.ts&theme=dark\"\n  style={{\n    width: '100%',\n    height: '600px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query - Mutations Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\n## Runtime Validation using Schemas\n\nEndpoints can use any [Standard Schema](https://standardschema.dev/) compliant library for runtime validation of query args, responses, and errors. See [API reference](../api/createApi.mdx#schema-validation) for full list of available schemas.\n\nWhen used with TypeScript, schemas can also be used to [infer the type of that value instead of having to declare it](../usage-with-typescript.mdx#schema-validation).\n\nMost commonly, you'll want to use `responseSchema` to validate the response from the server (or `rawResponseSchema` when using `transformResponse`).\n\n```ts title=\"Using responseSchema\" no-transpile\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport * as v from 'valibot'\n\nconst postSchema = v.object({\n  id: v.number(),\n  name: v.string(),\n  published_at: v.string(),\n})\ntype Post = v.InferOutput<typeof postSchema>\nconst transformedPost = v.object({\n  ...postSchema.entries,\n  published_at: v.date(),\n})\ntype TransformedPost = v.InferOutput<typeof transformedPost>\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    updatePost: build.mutation<Post, Partial<Post>>({\n      query(data) {\n        const { id, ...body } = data\n        return {\n          url: `post/${id}`,\n          method: 'PUT',\n          body,\n        }\n      },\n      responseSchema: postSchema,\n    }),\n    updatePostWithTransform: build.mutation<TransformedPost, Partial<Post>>({\n      query(data) {\n        const { id, ...body } = data\n        return {\n          url: `post/${id}`,\n          method: 'PUT',\n          body,\n        }\n      },\n      rawResponseSchema: postSchema,\n      transformResponse: (response) => ({\n        ...response,\n        published_at: new Date(response.published_at),\n      }),\n      // responseSchema can still be provided, to validate the transformed response\n      responseSchema: transformedPost,\n    }),\n  }),\n})\n```\n"
  },
  {
    "path": "docs/rtk-query/usage/pagination.mdx",
    "content": "---\nid: pagination\ntitle: Pagination\nsidebar_label: Pagination\nhide_title: true\ndescription: 'RTK Query > Usage > Pagination: suggestions for handling paginated data'\n---\n\n&nbsp;\n\n# Pagination\n\nRTK Query does not include any built-in pagination behavior. However, RTK Query does make it straightforward to integrate with a standard index-based pagination API. This is the most common form of pagination that you'll need to implement.\n\n## Pagination Recipes\n\n### Setup an endpoint to accept a page `arg`\n\n```ts title=\"src/app/services/posts.ts\"\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\ninterface Post {\n  id: number\n  name: string\n}\ninterface ListResponse<T> {\n  page: number\n  per_page: number\n  total: number\n  total_pages: number\n  data: T[]\n}\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    listPosts: build.query<ListResponse<Post>, number | void>({\n      query: (page = 1) => `posts?page=${page}`,\n    }),\n  }),\n})\n\nexport const { useListPostsQuery } = api\n```\n\n### Trigger the next page by incrementing the `page` state variable\n\n```tsx no-transpile title=\"src/features/posts/PostsManager.tsx\"\nconst PostList = () => {\n  const [page, setPage] = useState(1)\n  const { data: posts, isLoading, isFetching } = useListPostsQuery(page)\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts?.data) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <div>\n      {posts.data.map(({ id, title, status }) => (\n        <div key={id}>\n          {title} - {status}\n        </div>\n      ))}\n      <button onClick={() => setPage(page - 1)} isLoading={isFetching}>\n        Previous\n      </button>\n      <button onClick={() => setPage(page + 1)} isLoading={isFetching}>\n        Next\n      </button>\n    </div>\n  )\n}\n```\n\n### Automated Re-fetching of Paginated Queries\n\nIt is a common use-case to utilize tag invalidation to perform\n[automated re-fetching](./automated-refetching.mdx) with RTK Query.\n\nA potential pitfall when combining this with pagination is that your paginated query may only\nprovide a _partial_ list at any given time, and hence not `provide` tags for entity IDs that\nfall on pages which aren't currently shown. If a specific entity is deleted that falls on an\nearlier page, the paginated query will not be providing a tag for that specific ID, and will\nnot be invalidated to trigger re-fetching data. As a result, items on the current page that\nshould shift one item up will not have done so, and the total count of items and/or pages\nmay be incorrect.\n\nA strategy to overcome this is to ensure that the `delete` mutation always `invalidates` the\npaginated query, even if the deleted item is not _currently_ provided on that page. We can\nleverage the concept of\n[advanced invalidation with abstract tag ids](./automated-refetching.mdx#advanced-invalidation-with-abstract-tag-ids)\nto do this by `providing` a `'Posts'` tag with the `'PARTIAL-LIST'` ID in our paginated query,\nand `invalidating` that corresponding tag for any mutation that should affect it.\n\n```ts title=\"Example of invalidating cache for paginated queries\"\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\ninterface Post {\n  id: number\n  name: string\n}\ninterface ListResponse<T> {\n  page: number\n  per_page: number\n  total: number\n  total_pages: number\n  data: T[]\n}\n\nexport const postApi = createApi({\n  reducerPath: 'postsApi',\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  tagTypes: ['Posts'],\n  endpoints: (build) => ({\n    listPosts: build.query<ListResponse<Post>, number | void>({\n      query: (page = 1) => `posts?page=${page}`,\n      // highlight-start\n      providesTags: (result, error, page) =>\n        result\n          ? [\n              // Provides a tag for each post in the current page,\n              // as well as the 'PARTIAL-LIST' tag.\n              ...result.data.map(({ id }) => ({ type: 'Posts' as const, id })),\n              { type: 'Posts', id: 'PARTIAL-LIST' },\n            ]\n          : [{ type: 'Posts', id: 'PARTIAL-LIST' }],\n      // highlight-end\n    }),\n    deletePost: build.mutation<{ success: boolean; id: number }, number>({\n      query(id) {\n        return {\n          url: `post/${id}`,\n          method: 'DELETE',\n        }\n      },\n      // Invalidates the tag for this Post `id`, as well as the `PARTIAL-LIST` tag,\n      // causing the `listPosts` query to re-fetch if a component is subscribed to the query.\n      // highlight-start\n      invalidatesTags: (result, error, id) => [\n        { type: 'Posts', id },\n        { type: 'Posts', id: 'PARTIAL-LIST' },\n      ],\n      // highlight-end\n    }),\n  }),\n})\n```\n\n## General Pagination Example\n\nIn the following example, you'll see `Loading` on the initial query, but then as you move forward we'll use the next/previous buttons as a _fetching_ indicator while any non-cached query is performed. When you go back, the cached data will be served instantaneously.\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/pagination?fontsize=12&runonclick=1&hidenavigation=1&theme=dark\"\n  style={{\n    width: '100%',\n    height: '600px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query Pagination Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n"
  },
  {
    "path": "docs/rtk-query/usage/persistence-and-rehydration.mdx",
    "content": "---\nid: persistence-and-rehydration\ntitle: Persistence and Rehydration\nsidebar_label: Persistence and Rehydration\nhide_title: true\ndescription: 'RTK Query > Usage > Persistence and Rehydration'\n---\n\n&nbsp;\n\n# Persistence and Rehydration\n\nRTK Query supports rehydration via the [`extractRehydrationInfo`](../api/createApi.mdx#extractrehydrationinfo)\noption on [`createApi`](../api/createApi.mdx). This function is passed every dispatched action,\nand where it returns a value other than `undefined`, that value is used to rehydrate the API state\nfor fulfilled & errored queries.\n\nSee also [Server Side Rendering](./server-side-rendering.mdx).\n\n:::info\n\nGenerally, persisting API slices is not recommended and instead, mechanisms like\n[`Cache-Control` Headers](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control)\nshould be used in browsers to define cache behavior.\nPersisting and rehydrating an api slice might always leave the user with very stale data if the user\nhas not visited the page for some time.\nNonetheless, in environments like Native Apps, where there is no browser cache to take care of this,\npersistence might still be a viable option.\n\n:::\n\n## Redux Persist\n\nAPI state rehydration can be used in conjunction with [Redux Persist](https://github.com/rt2zz/redux-persist)\nby leveraging the `REHYDRATE` action type imported from `redux-persist`. This can be used out of the\nbox with the `autoMergeLevel1` or `autoMergeLevel2` [state reconcilers](https://github.com/rt2zz/redux-persist#state-reconciler)\nwhen persisting the root reducer, or with the `autoMergeLevel1` reconciler when persisting just the api reducer.\n\n```ts title=\"redux-persist rehydration example\"\nimport type { Action } from '@reduxjs/toolkit'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { REHYDRATE } from 'redux-persist'\n\ntype RootState = any // normally inferred from state\n\nfunction isHydrateAction(action: Action): action is Action<typeof REHYDRATE> & {\n  key: string\n  payload: RootState\n  err: unknown\n} {\n  return action.type === REHYDRATE\n}\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  // highlight-start\n  // to prevent circular type issues, the return type needs to be annotated as any\n  extractRehydrationInfo(action, { reducerPath }): any {\n    if (isHydrateAction(action)) {\n      // when persisting the api reducer\n      if (action.key === 'key used with redux-persist') {\n        return action.payload\n      }\n\n      // When persisting the root reducer\n      return action.payload[api.reducerPath]\n    }\n  },\n  // highlight-end\n  endpoints: (build) => ({\n    // omitted\n  }),\n})\n```\n"
  },
  {
    "path": "docs/rtk-query/usage/polling.mdx",
    "content": "---\nid: polling\ntitle: Polling\nsidebar_label: Polling\nhide_title: true\ndescription: 'RTK Query > Usage > Polling: re-fetching data on a timer'\n---\n\n&nbsp;\n\n# Polling\n\n## Polling Overview\n\nPolling gives you the ability to have a 'real-time' effect by causing a query to run at a specified interval. To enable polling for a query, pass a `pollingInterval` to the `useQuery` hook or action creator with an interval in milliseconds:\n\n:::tip\nPolling additionally has the ability to skip sending requests while the window is out of focus. To enable this behavior, pass `skipPollingIfUnfocused: true` to the `useQuery` hook or action creator.\n\n_Note: `skipPollingIfUnfocused` requires [`setupListeners`](../api/setupListeners.mdx) to have been called._\n:::\n\n```tsx no-transpile title=\"src/Pokemon.tsx\" no-transpile\nimport * as React from 'react'\nimport { useGetPokemonByNameQuery } from './services/pokemon'\n\nexport const Pokemon = ({ name }: { name: string }) => {\n  // Automatically refetch every 3s unless the window is out of focus\n  const { data, status, error, refetch } = useGetPokemonByNameQuery(name, {\n    pollingInterval: 3000,\n    skipPollingIfUnfocused: true,\n  })\n\n  return <div>{data}</div>\n}\n```\n\nIn an action creator without React Hooks:\n\n```ts no-transpile\nconst { data, status, error, refetch } = store.dispatch(\n  endpoints.getCountById.initiate(id, {\n    subscriptionOptions: { pollingInterval: 3000 },\n  }),\n)\n```\n\n## Polling Without React Hooks\n\nIf you use polling without the convenience of React Hooks, you will need to manually call `updateSubscriptionOptions` on the promise ref to update the interval. This approach varies by framework but is possible everywhere. See the [Svelte Example](./examples#svelte) for one possibility, and the [Usage Without React Hooks](./usage-without-react-hooks.mdx) page for more details on working with subscriptions manually.\n\n```ts no-transpile\nqueryRef.updateSubscriptionOptions({ pollingInterval: 0 })\n```\n\n## Polling Example\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/polling?fontsize=12&runonclick=1&hidenavigation=1&theme=dark\"\n  style={{\n    width: '100%',\n    height: '600px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"rtk-query-react-hooks-example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n"
  },
  {
    "path": "docs/rtk-query/usage/prefetching.mdx",
    "content": "---\nid: prefetching\ntitle: Prefetching\nsidebar_label: Prefetching\nhide_title: true\ndescription: 'RTK Query > Usage > Prefetching: fetching before user interaction'\n---\n\n&nbsp;\n\n# Prefetching\n\nThe goal of prefetching is to make data fetch _before_ the user navigates to a page or attempts to load some known content.\n\nThere are a handful of situations that you may want to do this, but some very common use cases are:\n\n1. User hovers over a navigation element\n2. User hovers over a list element that is a link\n3. User hovers over a next pagination button\n4. User navigates to a page and you know that some components down the tree will require said data. This way, you can prevent fetching waterfalls.\n\n## Prefetching vs Subscriptions\n\nPrefetching is designed as a \"fire and forget\" operation that loads data into the cache without creating an ongoing subscription. This means:\n\n- **No automatic refetching**: Prefetched data will not automatically refetch when tags are invalidated\n- **No subscription management**: You don't need to (and can't) manually unsubscribe from prefetched data\n- **Cache cleanup**: Prefetched data without active subscriptions may be removed during normal cache cleanup\n- **Returns void**: The prefetch trigger function doesn't return a promise or subscription handle\n\nIf you need data that automatically refetches on invalidation or stays in the cache as long as a component is mounted, use a query hook like `useQuery` or `useQuerySubscription` instead. Prefetch is ideal for warming the cache before a user action, while query hooks are for ongoing data needs.\n\n:::tip When to use prefetch vs query hooks\n\n- **Use prefetch** when you want to load data ahead of time (e.g., on hover) but don't need it to stay fresh\n- **Use query hooks** when you need data that automatically refetches on invalidation and stays in cache while the component is mounted\n- **Use both together**: Prefetch on hover, then let the query hook create a subscription when the user navigates\n\n:::\n\n## Prefetching with React Hooks\n\nSimilar to the [`useMutation`](./mutations) hook, the `usePrefetch` hook will not run automatically — it returns a \"trigger function\" that can be used to initiate the behavior.\n\nIt accepts two arguments: the first is the key of a query action that you [defined in your API service](../api/createApi#endpoints), and the second is an object of two optional parameters:\n\n```ts title=\"usePrefetch Signature\" no-transpile\nexport type PrefetchOptions =\n  | { force?: boolean }\n  | {\n      ifOlderThan?: false | number;\n    };\n\nusePrefetch<EndpointName extends QueryKeys<Definitions>>(\n    endpointName: EndpointName,\n    options?: PrefetchOptions\n  ): (arg: QueryArgFrom<Definitions[EndpointName]>, options?: PrefetchOptions) => void;\n```\n\n### Customizing the Hook Behavior\n\nYou can specify these prefetch options when declaring the hook or at the call site. The call site will take priority over the defaults.\n\n1. [summary](docblock://query/core/module.ts?token=PrefetchOptions)\n2. [overloadSummary](docblock://query/core/module.ts?token=PrefetchOptions)\n\n### Trigger Function Behavior\n\n1. The trigger function _always_ returns `void`.\n2. If `force: true` is set during the declaration or at the call site, the query will be run no matter what. The one exception to that is if the same query is already in-flight.\n3. If no options are specified and the query exists in the cache, the query will not be performed.\n4. If no options are specified and the query _does not exist_ in the cache, the query will be performed.\n   - **Assuming** you have a `useQuery` hook in the tree that is subscribed to the same query that you are prefetching:\n     - `useQuery` will return `{isLoading: true, isFetching: true, ...rest`}\n5. If `ifOlderThan` is specified but evaluates to false and the query is in the cache, the query will not be performed.\n6. If `ifOlderThan` is specified and evaluates to true, the query will be performed even if there is an existing cache entry.\n   - **Assuming** you have a `useQuery` hook in the tree that is subscribed to the same query that you are prefetching:\n     - `useQuery` will return `{isLoading: false, isFetching: true, ...rest`}\n\n```tsx no-transpile title=\"usePrefetch Example\"\nfunction User() {\n  const prefetchUser = usePrefetch('getUser')\n\n  // Low priority hover will not fire unless the last request happened more than 35s ago\n  // High priority hover will _always_ fire\n  return (\n    <div>\n      <button onMouseEnter={() => prefetchUser(4, { ifOlderThan: 35 })}>\n        Low priority\n      </button>\n      <button onMouseEnter={() => prefetchUser(4, { force: true })}>\n        High priority\n      </button>\n    </div>\n  )\n}\n```\n\n### Recipe: Prefetch Immediately\n\nIn some cases, you may want to prefetch a resource immediately. You can implement this in just a few lines of code:\n\n```ts title=\"hooks/usePrefetchImmediately.ts\" no-transpile\ntype EndpointNames = keyof typeof api.endpoints\n\nexport function usePrefetchImmediately<T extends EndpointNames>(\n  endpoint: T,\n  arg: Parameters<(typeof api.endpoints)[T]['initiate']>[0],\n  options: PrefetchOptions = {},\n) {\n  const dispatch = useAppDispatch()\n  useEffect(() => {\n    dispatch(api.util.prefetch(endpoint, arg as any, options))\n  }, [])\n}\n\n// In a component\nusePrefetchImmediately('getUser', 5)\n```\n\n## Prefetching Without Hooks\n\nIf you're not using the `usePrefetch` hook, you can recreate the same behavior on your own in any framework.\n\nWhen dispatching the `prefetch` thunk as shown below you will see the same exact behavior as [described here](#trigger-function-behavior).\n\n```ts title=\"Non-hook prefetching example\" no-transpile\nstore.dispatch(\n  api.util.prefetch(endpointName, arg, { force: false, ifOlderThan: 10 }),\n)\n```\n\n### Prefetch vs `initiate()`\n\nWhile you can also use `initiate()` directly, there are important differences:\n\n```ts title=\"Using initiate() directly\" no-transpile\n// This creates a subscription that must be manually cleaned up\nconst promise = dispatch(\n  api.endpoints[endpointName].initiate(arg, {\n    subscribe: true, // Creates a subscription (default)\n    forceRefetch: true,\n  }),\n)\n\n// You must manually unsubscribe to prevent memory leaks\npromise.unsubscribe()\n```\n\n**Key differences:**\n\n- **`api.util.prefetch()`**: Automatically uses `subscribe: false`, no cleanup needed\n- **`endpoint.initiate()`**: Defaults to `subscribe: true`, requires manual `unsubscribe()` call\n\nUse `prefetch()` for simple \"load and forget\" scenarios. Use `initiate()` directly only when you need fine-grained control over subscriptions and are prepared to manage the subscription lifecycle yourself.\n\n## Prefetching Examples\n\n### Basic Prefetching\n\nThis is a very basic example that shows how you can prefetch when a user hovers over the next arrow. This is probably not the optimal solution, because if they hover, click, then change pages without moving their mouse, we wouldn't know to prefetch the next page because we wouldn't see the next `onMouseEnter` event. In this case, you would need to handle this on your own. You could also consider automatically prefetching the next page...\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/prefetching?fontsize=12&runonclick=1&hidenavigation=1&theme=dark\"\n  style={{\n    width: '100%',\n    height: '600px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query - Prefetching Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\n### Automatic Prefetching\n\nPicking up on our last example, we automatically `prefetch` the next page, giving the appearance of no network delay.\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/prefetching-automatic?fontsize=12&runonclick=1&hidenavigation=1&theme=dark\"\n  style={{\n    width: '100%',\n    height: '600px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query - Automatic Prefetching Example (on hover)\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\n### Prefetching All Known Pages\n\nAfter the first query initialized by `useQuery` runs, we automatically fetch all remaining pages.\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/prefetching-automatic-waterfall?fontsize=12&runonclick=1&hidenavigation=1&theme=dark&module=%2Fsrc%2Ffeatures%2Fposts%2FPostsManager.tsx\"\n  style={{\n    width: '100%',\n    height: '600px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query - Automatic Prefetching Waterfall Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n"
  },
  {
    "path": "docs/rtk-query/usage/queries.mdx",
    "content": "---\nid: queries\ntitle: Queries\nsidebar_label: Queries\nhide_title: true\ndescription: 'RTK Query > Usage > Queries: fetching data from a server'\n---\n\n&nbsp;\n\n# Queries\n\n## Overview\n\nQueries are operations that fetch data from the server and cache it within the client. This is the most common use case for RTK Query. A query operation can be performed with any data fetching library of your choice, but the general recommendation is that you only use queries for requests that retrieve data. For anything that alters data on the server or will possibly invalidate the cache, you should use a [Mutation](./mutations).\n\nA query can cache the status and result of any async/promise method. Since the most common type of query is an HTTP request, RTK Query ships with [`fetchBaseQuery`](../api/fetchBaseQuery), which is a lightweight [`fetch`](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) wrapper that automatically handles request headers and response parsing in a manner similar to common libraries like `axios`. See [Customizing Queries](./customizing-queries) if `fetchBaseQuery` does not handle your requirements.\n\n:::info\n\nDepending on your environment, you may need to polyfill `fetch` with `node-fetch` or `cross-fetch` if you choose to use `fetchBaseQuery` or `fetch` on its own.\n\n:::\n\nSee [`useQuery`](../api/created-api/hooks.mdx#usequery) for the hook signature and additional details.\n\n## Defining Query Endpoints\n\nQuery endpoints are defined by returning an object inside the `endpoints` section of `createApi`, and defining the fields using the `build.query()` method.\n\nQuery endpoints should define either a `query` callback that constructs the URL (including any URL query params), or [a `queryFn` callback](./customizing-queries.mdx#customizing-queries-with-queryfn) that may do arbitrary async logic and return a result.\n\nIf the `query` callback needs additional data to generate the URL, it should be written to take a single argument. If you need to pass in multiple parameters, pass them formatted as a single \"options object\".\n\nQuery endpoints may also modify the response contents before the result is cached, define \"tags\" to identify cache invalidation, and provide cache entry lifecycle callbacks to run additional logic as cache entries are added and removed.\n\nWhen used with TypeScript, you should supply generics for the return type and the expected query argument: `build.query<ReturnType, ArgType>`. If there is no argument, use `void` for the arg type instead.\n\n```ts title=\"Example of all query endpoint options\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: api.ts\n// Or from '@reduxjs/toolkit/query/react'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport type { Post } from './types'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n  }),\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    // highlight-start\n    // The query accepts a number and returns a Post\n    getPost: build.query<Post, number>({\n      // note: an optional `queryFn` may be used in place of `query`\n      query: (id) => ({ url: `post/${id}` }),\n      // Pick out data and prevent nested properties in a hook or selector\n      transformResponse: (response: { data: Post }, meta, arg) => response.data,\n      // Pick out errors and prevent nested properties in a hook or selector\n      transformErrorResponse: (\n        response: { status: string | number },\n        meta,\n        arg,\n      ) => response.status,\n      providesTags: (result, error, id) => [{ type: 'Post', id }],\n      // The 2nd parameter is the destructured `QueryLifecycleApi`\n      async onQueryStarted(\n        arg,\n        {\n          dispatch,\n          getState,\n          extra,\n          requestId,\n          queryFulfilled,\n          getCacheEntry,\n          updateCachedData,\n        },\n      ) {},\n      // The 2nd parameter is the destructured `QueryCacheLifecycleApi`\n      async onCacheEntryAdded(\n        arg,\n        {\n          dispatch,\n          getState,\n          extra,\n          requestId,\n          cacheEntryRemoved,\n          cacheDataLoaded,\n          getCacheEntry,\n          updateCachedData,\n        },\n      ) {},\n      // highlight-end\n    }),\n  }),\n})\n```\n\n## Performing Queries with React Hooks\n\nIf you're using React Hooks, RTK Query does a few additional things for you. The primary benefit is that you get a render-optimized hook that allows you to have 'background fetching' as well as [derived booleans](#frequently-used-query-hook-return-values) for convenience.\n\nHooks are automatically generated based on the name of the `endpoint` in the service definition. An endpoint field with `getPost: build.query()` will generate a hook named `useGetPostQuery`, as well as a generically-named hook attached to the endpoint, like `api.endpoints.getPost.useQuery`.\n\n### Hook types\n\nThere are 5 query-related hooks:\n\n1. [`useQuery`](../api/created-api/hooks.mdx#usequery)\n   - Composes `useQuerySubscription` and `useQueryState` and is the primary hook. Automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store.\n2. [`useQuerySubscription`](../api/created-api/hooks.mdx#usequerysubscription)\n   - Returns a `refetch` function and accepts all hook options. Automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.\n3. [`useQueryState`](../api/created-api/hooks.mdx#usequerystate)\n   - Returns the query state and accepts `skip` and `selectFromResult`. Reads the request status and cached data from the Redux store.\n4. [`useLazyQuery`](../api/created-api/hooks.mdx#uselazyquery)\n   - Returns a tuple with a `trigger` function, the query result, and last promise info. Similar to `useQuery`, but with manual control over when the data fetching occurs. **Note: the `trigger` function takes a second argument of `preferCacheValue?: boolean` in the event you want to skip making a request if cached data already exists.**\n5. [`useLazyQuerySubscription`](../api/created-api/hooks.mdx#uselazyquerysubscription)\n   - Returns a tuple with a `trigger` function, and last promise info. Similar to `useQuerySubscription`, but with manual control over when the data fetching occurs. **Note: the `trigger` function takes a second argument of `preferCacheValue?: boolean` in the event you want to skip making a request if cached data already exists.**\n\nIn practice, the standard `useQuery`-based hooks such as `useGetPostQuery` will be the primary hooks used in your application, but the other hooks are available for specific use cases.\n\n### Query Hook Options\n\nThe query hooks expect two parameters: `(queryArg?, queryOptions?)`.\n\nThe `queryArg` param will be passed through to the underlying `query` callback to generate the URL.\n\nThe `queryOptions` object accepts several additional parameters that can be used to control the behavior of the data fetching:\n\n- [skip](./conditional-fetching) - Allows a query to 'skip' running for that render. Defaults to `false`\n- [pollingInterval](./polling) - Allows a query to automatically refetch on a provided interval, specified in milliseconds. Defaults to `0` _(off)_\n- [selectFromResult](#selecting-data-from-a-query-result) - Allows altering the returned value of the hook to obtain a subset of the result, render-optimized for the returned subset.\n- [refetchOnMountOrArgChange](../api/createApi#refetchonmountorargchange) - Allows forcing the query to always refetch on mount (when `true` is provided). Allows forcing the query to refetch if enough time (in seconds) has passed since the last query for the same cache (when a `number` is provided). Defaults to `false`\n- [refetchOnFocus](../api/createApi#refetchonfocus) - Allows forcing the query to refetch when the browser window regains focus. Defaults to `false`\n- [refetchOnReconnect](../api/createApi#refetchonreconnect) - Allows forcing the query to refetch when regaining a network connection. Defaults to `false`\n\n:::info\n\nAll `refetch`-related options will override the defaults you may have set in [createApi](../api/createApi)\n\n:::\n\n### Frequently Used Query Hook Return Values\n\nThe query hook returns an object containing properties such as the latest `data` for the query request, as well as status booleans for the current request lifecycle state. Below are some of the most frequently used properties. Refer to [`useQuery`](../api/created-api/hooks.mdx#usequery) for an extensive list of all returned properties.\n\n- `data` - The latest returned result regardless of hook arg, if present.\n- `currentData` - The latest returned result for the current hook arg, if present.\n- `error` - The error result if present.\n- `isUninitialized` - When true, indicates that the query has not started yet.\n- `isLoading` - When true, indicates that the query is currently loading for the first time, and has no data yet. This will be `true` for the first request fired off, but _not_ for subsequent requests.\n- `isFetching` - When true, indicates that the query is currently fetching, but might have data from an earlier request. This will be `true` for both the first request fired off, as well as subsequent requests.\n- `isSuccess` - When true, indicates that the query has data from a successful request.\n- `isError` - When true, indicates that the query is in an `error` state.\n- `refetch` - A function to force refetch the query\n\nIn most cases, you will probably read `data` and either `isLoading` or `isFetching` in order to render your UI.\n\n### Query Hook Usage Example\n\nHere is an example of a `PostDetail` component:\n\n```tsx no-transpile title=\"Example\"\nexport const PostDetail = ({ id }: { id: string }) => {\n  const {\n    data: post,\n    isFetching,\n    isLoading,\n  } = useGetPostQuery(id, {\n    pollingInterval: 3000,\n    refetchOnMountOrArgChange: true,\n    skip: false,\n  })\n\n  if (isLoading) return <div>Loading...</div>\n  if (!post) return <div>Missing post!</div>\n\n  return (\n    <div>\n      {post.name} {isFetching ? '...refetching' : ''}\n    </div>\n  )\n}\n```\n\nThe way that this component is setup would have some nice traits:\n\n1. It only shows 'Loading...' on the **initial load**\n   - **Initial load** is defined as a query that is pending and does not have data in the cache\n2. When the request is re-triggered by the polling interval, it will add '...refetching' to the post name\n3. If a user closed this `PostDetail`, but then re-opened it within [the allowed time](../api/createApi#keepunuseddatafor), they would immediately be served a cached result and polling would resume with the previous behavior.\n\n### Query Loading State\n\nThe auto-generated React hooks created by the React-specific version of `createApi` provide [derived booleans](#frequently-used-query-hook-return-values) that reflect the current state of a given query. Derived booleans are preferred for the generated React hooks as opposed to a `status` flag, as the derived booleans are able to provide a greater amount of detail which would not be possible with a single `status` flag, as multiple statuses may be true at a given time (such as `isFetching` and `isSuccess`).\n\nFor query endpoints, RTK Query maintains a semantic distinction between `isLoading` and `isFetching` in order to provide more flexibility with the derived information provided.\n\n- `isLoading` refers to a query being in flight for the _first time_ for the given hook. No data will be available at this time.\n- `isFetching` refers to a query being in flight for the given endpoint + query param combination, but not necessarily for the first time. Data may be available from an earlier request done by this hook, maybe with the previous query param.\n\nThis distinction allows for greater control when handling UI behavior. For example, `isLoading` can be used to display a skeleton while loading for the first time, while `isFetching` can be used to grey out old data when changing from page 1 to page 2 or when data is invalidated and re-fetched.\n\n```tsx no-transpile title=\"Managing UI behavior with Query Loading States\"\nimport { Skeleton } from './Skeleton'\nimport { useGetPostsQuery } from './api'\n\nfunction App() {\n  const { data = [], isLoading, isFetching, isError } = useGetPostsQuery()\n\n  if (isError) return <div>An error has occurred!</div>\n\n  if (isLoading) return <Skeleton />\n\n  return (\n    <div className={isFetching ? 'posts--disabled' : ''}>\n      {data.map((post) => (\n        <Post\n          key={post.id}\n          id={post.id}\n          name={post.name}\n          disabled={isFetching}\n        />\n      ))}\n    </div>\n  )\n}\n```\n\nWhile `data` is expected to be used in the majority of situations, `currentData` is also provided,\nwhich allows for a further level of granularity. For example, if you wanted to show data in the UI\nas translucent to represent a re-fetching state, you can use `data` in combination with `isFetching`\nto achieve this. However, if you also wish to _only_ show data corresponding to the current arg,\nyou can instead use `currentData` to achieve this.\n\nIn the example below, if posts are being fetched for the first time, a loading skeleton will be\nshown. If posts for the current user have previously been fetched, and are re-fetching (e.g. as a\nresult of a mutation), the UI will show the previous data, but will grey out the data. If the user\nchanges, it will instead show the skeleton again as opposed to greying out data for the previous user.\n\n```tsx no-transpile title=\"Managing UI behavior with currentData\"\nimport { Skeleton } from './Skeleton'\nimport { useGetPostsByUserQuery } from './api'\n\nfunction PostsList({ userName }: { userName: string }) {\n  const { currentData, isFetching, isError } = useGetPostsByUserQuery(userName)\n\n  if (isError) return <div>An error has occurred!</div>\n\n  if (isFetching && !currentData) return <Skeleton />\n\n  return (\n    <div className={isFetching ? 'posts--disabled' : ''}>\n      {currentData\n        ? currentData.map((post) => (\n            <Post\n              key={post.id}\n              id={post.id}\n              name={post.name}\n              disabled={isFetching}\n            />\n          ))\n        : 'No data available'}\n    </div>\n  )\n}\n```\n\n### Query Cache Keys\n\nWhen you perform a query, RTK Query automatically serializes the request parameters and creates an internal `queryCacheKey` for the request. Any future request that produces the same `queryCacheKey` will be de-duped against the original, and will share updates if a `refetch` is triggered on the query from any subscribed component.\n\n### Selecting data from a query result\n\nSometimes you may have a parent component that is subscribed to a query, and then in a child component you want to pick an item from that query. In most cases you don't want to perform an additional request for a `getItemById`-type query when you know that you already have the result.\n\n`selectFromResult` allows you to get a specific segment from a query result in a performant manner. When using this feature, the component will not rerender unless the underlying data of the selected item has changed. If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n\n```tsx no-transpile title=\"Using selectFromResult to extract a single result\"\nfunction PostsList() {\n  const { data: posts } = api.useGetPostsQuery()\n\n  return (\n    <ul>\n      {posts?.data?.map((post) => <PostById key={post.id} id={post.id} />)}\n    </ul>\n  )\n}\n\nfunction PostById({ id }: { id: number }) {\n  // Will select the post with the given id, and will only rerender if the given post's data changes\n  const { post } = api.useGetPostsQuery(undefined, {\n    selectFromResult: ({ data }) => ({\n      post: data?.find((post) => post.id === id),\n    }),\n  })\n\n  return <li>{post?.name}</li>\n}\n```\n\nNote that a shallow equality check is performed on the overall return value of `selectFromResult` to determine whether to force a rerender. i.e. it will trigger a rerender if any of the returned object values change reference. If a new array/object is created and used as a return value within the callback, it will hinder the performance benefits due to being identified as a new item each time the callback is run. When intentionally providing an empty array/object, in order to avoid re-creating it each time the callback runs, you can declare an empty array/object outside of the component in order to maintain a stable reference.\n\n```tsx no-transpile title=\"Using selectFromResult with a stable empty array\"\n// An array declared here will maintain a stable reference rather than be re-created again\nconst emptyArray: Post[] = []\n\nfunction PostsList() {\n  // This call will result in an initial render returning an empty array for `posts`,\n  // and a second render when the data is received.\n  // It will trigger additional rerenders only if the `posts` data changes\n  const { posts } = api.useGetPostsQuery(undefined, {\n    selectFromResult: ({ data }) => ({\n      posts: data ?? emptyArray,\n    }),\n  })\n\n  return (\n    <ul>\n      {posts.map((post) => (\n        <PostById key={post.id} id={post.id} />\n      ))}\n    </ul>\n  )\n}\n```\n\nTo summarize the above behavior - the returned values must be correctly memoized. See also [Deriving Data with Selectors](https://redux.js.org/usage/deriving-data-selectors) and [Redux Essentials - RTK Query Advanced Patterns](https://redux.js.org/tutorials/essentials/part-8-rtk-query-advanced#selecting-values-from-results) for additional information.\n\n### Avoiding unnecessary requests\n\nBy default, if you add a component that makes the same query as an existing one, no request will be performed.\n\nIn some cases, you may want to skip this behavior and force a refetch - in that case, you can call `refetch` that is returned by the hook.\n\n:::info\n\nIf you're not using React Hooks, you can access `refetch` like this:\n\n```ts no-transpile\nconst { status, data, error, refetch } = dispatch(\n  pokemonApi.endpoints.getPokemon.initiate('bulbasaur'),\n)\n```\n\n:::\n\n## Runtime Validation using Schemas\n\nEndpoints can use any [Standard Schema](https://standardschema.dev/) compliant library for runtime validation of query args, responses, and errors. See [API reference](../api/createApi.mdx#schema-validation) for full list of available schemas.\n\nWhen used with TypeScript, schemas can also be used to [infer the type of that value instead of having to declare it](../usage-with-typescript.mdx#schema-validation).\n\nMost commonly, you'll want to use `responseSchema` to validate the response from the server (or `rawResponseSchema` when using `transformResponse`).\n\n```ts title=\"Using responseSchema\" no-transpile\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport * as v from 'valibot'\n\nconst postSchema = v.object({\n  id: v.number(),\n  name: v.string(),\n})\ntype Post = v.InferOutput<typeof postSchema>\nconst transformedPost = v.object({\n  ...postSchema.entries,\n  published_at: v.date(),\n})\ntype TransformedPost = v.InferOutput<typeof transformedPost>\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    getPost: build.query<Post, { id: number }>({\n      query: ({ id }) => `/post/${id}`,\n      responseSchema: postSchema,\n    }),\n    getTransformedPost: build.query<TransformedPost, { id: number }>({\n      query: ({ id }) => `/post/${id}`,\n      rawResponseSchema: postSchema,\n      transformResponse: (response) => ({\n        ...response,\n        published_at: new Date(response.published_at),\n      }),\n      // responseSchema can still be provided, to validate the transformed response\n      responseSchema: transformedPost,\n    }),\n  }),\n})\n```\n\n## Example: Observing caching behavior\n\nThis example demonstrates request deduplication and caching behavior:\n\n1. The first `Pokemon` component mounts and immediately fetches 'bulbasaur'\n2. A second later, another `Pokemon` component is rendered with 'bulbasaur'\n   - Notice that this one doesn't ever show 'Loading...' and no new network request happens? It's using the cache here.\n3. A moment after that, a `Pokemon` component for 'pikachu' is added, and a new request happens.\n4. When you click 'Refetch' for a specific `Pokemon`, it'll update all instances of that `Pokemon` with one request.\n\n:::note Try it out\nClick the 'Add bulbasaur' button. You'll observe the same behavior described above until you click the 'Refetch' button on one of the components.\n:::\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/deduping-queries?fontsize=12&runonclick=1&hidenavigation=1&theme=dark\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query - Basic query deduplication example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n"
  },
  {
    "path": "docs/rtk-query/usage/server-side-rendering.mdx",
    "content": "---\nid: server-side-rendering\ntitle: Server Side Rendering\nsidebar_label: Server Side Rendering\nhide_title: true\ndescription: 'RTK Query > Usage > Server Side Rendering'\n---\n\n&nbsp;\n\n# Server Side Rendering\n\n## Server Side Rendering with Next.js\n\nRTK Query supports Server Side Rendering (SSR) with [Next.js](https://nextjs.org/) via\n[rehydration](./persistence-and-rehydration.mdx) in combination with\n[next-redux-wrapper](https://github.com/kirill-konshin/next-redux-wrapper).\n\nThe workflow is as follows:\n\n- Set up `next-redux-wrapper`\n- In `getStaticProps` or `getServerSideProps`:\n  - Pre-fetch all queries via the `initiate` actions, e.g. `store.dispatch(api.endpoints.getPokemonByName.initiate(name))`\n  - Wait for each query to finish using `await Promise.all(dispatch(api.util.getRunningQueriesThunk()))`\n- In your `createApi` call, configure rehydration using the `extractRehydrationInfo` option:\n\n  [examples](docblock://query/createApi.ts?token=CreateApiOptions.extractRehydrationInfo)\n\nAn example repo using `next.js` is available [here](https://github.com/phryneas/ssr-experiments/tree/main/nextjs-blog).\n\n:::tip\nWhile memory leaks are not anticipated, once a render is sent to the client and the store is being\nremoved from memory, you may wish to also call `store.dispatch(api.util.resetApiState())` to\nensure that no rogue timers are left running.\n:::\n\n:::tip\nIn order to avoid providing stale data with Static Site Generation (SSG), you may wish to set\n[`refetchOnMountOrArgChange`](../api/createApi.mdx#refetchonmountorargchange) to a reasonable value\nsuch as 900 (seconds) in order to allow data to be re-fetched when accessed if it has been that\nlong since the page was generated.\n:::\n\n## Server Side Rendering elsewhere\n\nIf you are not using `next.js`, and the example above cannot be adapted to your SSR framework,\nan `unstable__` marked approach is available to support SSR scenarios where you need to execute\nasync code during render and not safely in an effect.\nThis is a similar approach to using [`getDataFromTree`](https://www.apollographql.com/docs/react/performance/server-side-rendering/#executing-queries-with-getdatafromtree)\nwith [Apollo](https://www.apollographql.com/docs/).\n\nThe workflow is as follows:\n\n- Create a version of `createApi` that performs asynchronous work during render:\n\n  [examples](docblock://query/react/module.ts?token=ReactHooksModuleOptions.unstable__sideEffectsInRender)\n\n- Use your custom `createApi` when calling `const api = createApi({...})`\n- Wait for all queries to finish using `await Promise.all(dispatch(api.util.getRunningQueriesThunk()))` before performing the next render cycle\n"
  },
  {
    "path": "docs/rtk-query/usage/streaming-updates.mdx",
    "content": "---\nid: streaming-updates\ntitle: Streaming Updates\nsidebar_label: Streaming Updates\nhide_title: true\ndescription: 'RTK Query > Usage > Streaming Updates: updating cache from pushed messages'\n---\n\n&nbsp;\n\n# Streaming Updates\n\n## Overview\n\nRTK Query gives you the ability to receive **streaming updates** for persistent queries. This enables a query to establish an ongoing connection to the server (typically using WebSockets), and apply updates to the cached data as additional information is received from the server.\n\nStreaming updates can be used to enable the API to receive real-time updates to the back-end data, such as new entries being created, or important properties being updated.\n\nTo enable streaming updates for a query, pass the asynchronous `onCacheEntryAdded` function to the query, including the logic for how to update the query when streamed data is received. See [`onCacheEntryAdded` API reference](../api/createApi#oncacheentryadded) for more details.\n\n## When to use streaming updates\n\nPrimarily updates to query data should be done via [`polling`](./polling) intermittently on an interval, using [`cache invalidation`](./automated-refetching#advanced-invalidation-with-abstract-tag-ids) to invalidate data based on tags associated with queries & mutations, or with [`refetchOnMountOrArgChange`](../api/createApi#refetchonmountorargchange) to fetch fresh data when a component using the data mounts.\n\nHowever, streaming updates is particularly useful for scenarios involving:\n\n- _Small, frequent changes to large objects_. Rather than repeatedly polling for a large object, the object can be fetched with an initial query, and streaming updates can update individual properties as updates are received.\n- _External event-driven updates_. Where data may be changed by the server or otherwise external users and where real-time updates are expected to be shown to an active user, polling alone would result in periods of stale data in between queries, causing state to easily get out of sync. Streaming updates can update all active clients as the updates occur rather than waiting for the next interval to elapse.\n\nExample use cases that benefit from streaming updates are:\n\n- GraphQL subscriptions\n- Real-time chat applications\n- Real-time multiplayer games\n- Collaborative document editing with multiple concurrent users\n\n## Using the `onCacheEntryAdded` Lifecycle\n\nThe `onCacheEntryAdded` lifecycle callback lets you write arbitrary async logic that will be executed after a new cache entry is added to the RTK Query cache (ie, after a component has created a new subscription to a given endpoint+params combination).\n\n`onCacheEntryAdded` will be called with two arguments: the `arg` that was passed to the subscription, and an options object containing \"lifecycle promises\" and utility functions. You can use these to write sequenced logic that waits for data to be added, initiates server connections, applies partial updates, and cleans up the connection when the query subscription is removed.\n\nTypically, you will `await cacheDataLoaded` to determine when the first data has been fetched, then use the `updateCacheData` utility to apply streaming updates as messages are received. `updateCacheData` is an Immer-powered callback that receives a `draft` of the current cache value. You may \"mutate\" the draft value to update it as needed based on the received values. RTK Query will then dispatch an action that applies a diffed patch based on those changes.\n\nFinally, you can `await cacheEntryRemoved` to know when to clean up any server connections.\n\n## Streaming Update Examples\n\n### Websocket Chat API\n\n```ts\n// file: schemaValidators.ts noEmit\nimport type { Message } from './api'\n\nexport function isMessage(message: unknown): message is Message {\n  // in real code this would check `message` to ensure it is a `Message`\n  return true\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { isMessage } from './schemaValidators'\n\nexport type Channel = 'redux' | 'general'\n\nexport interface Message {\n  id: number\n  channel: Channel\n  userName: string\n  text: string\n}\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    getMessages: build.query<Message[], Channel>({\n      query: (channel) => `messages/${channel}`,\n      // highlight-start\n      async onCacheEntryAdded(\n        arg,\n        { updateCachedData, cacheDataLoaded, cacheEntryRemoved },\n      ) {\n        // create a websocket connection when the cache subscription starts\n        const ws = new WebSocket('ws://localhost:8080')\n        try {\n          // wait for the initial query to resolve before proceeding\n          await cacheDataLoaded\n\n          // when data is received from the socket connection to the server,\n          // if it is a message and for the appropriate channel,\n          // update our query result with the received message\n          const listener = (event: MessageEvent) => {\n            const data = JSON.parse(event.data)\n            if (!isMessage(data) || data.channel !== arg) return\n\n            updateCachedData((draft) => {\n              draft.push(data)\n            })\n          }\n\n          ws.addEventListener('message', listener)\n        } catch {\n          // no-op in case `cacheEntryRemoved` resolves before `cacheDataLoaded`,\n          // in which case `cacheDataLoaded` will throw\n        }\n        // cacheEntryRemoved will resolve when the cache subscription is no longer active\n        await cacheEntryRemoved\n        // perform cleanup steps once the `cacheEntryRemoved` promise resolves\n        ws.close()\n      },\n      // highlight-end\n    }),\n  }),\n})\n\nexport const { useGetMessagesQuery } = api\n```\n\n#### What to expect\n\nWhen the `getMessages` query is triggered (e.g. via a component mounting with the `useGetMessagesQuery()` hook), a `cache entry` will be added based on the serialized arguments for the endpoint. The associated query will be fired off based on the `query` property to fetch the initial data for the cache. Meanwhile, the asynchronous `onCacheEntryAdded` callback will begin, and create a new WebSocket connection. Once the response for the initial query is received, the cache will be populated with the response data, and the `cacheDataLoaded` promise will resolve. After awaiting the `cacheDataLoaded` promise, the `message` event listener will be added to the WebSocket connection, which updates the cache data when an associated message is received.\n\nWhen there are no more active subscriptions to the data (e.g. when the subscribed components remain unmounted for a sufficient amount of time), the `cacheEntryRemoved` promise will resolve, allowing the remaining code to run and close the websocket connection. RTK Query will also remove the associated data from the cache.\n\nIf a query for the corresponding cache entry runs later, it will overwrite the whole cache entry, and the streaming update listeners will continue to work on the updated data.\n\n### Websocket Chat API with a transformed response shape\n\n```ts\n// file: schemaValidators.ts noEmit\nimport type { Message } from './api'\n\nexport function isMessage(message: unknown): message is Message {\n  // in real code this would check `message` to ensure it is a `Message`\n\n  return true\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { createEntityAdapter } from '@reduxjs/toolkit'\nimport type { EntityState } from '@reduxjs/toolkit'\nimport { isMessage } from './schemaValidators'\n\nexport type Channel = 'redux' | 'general'\n\nexport interface Message {\n  id: number\n  channel: Channel\n  userName: string\n  text: string\n}\n\n// highlight-start\nconst messagesAdapter = createEntityAdapter<Message>()\n// highlight-end\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    // highlight-start\n    getMessages: build.query<EntityState<Message, number>, Channel>({\n      // highlight-end\n      query: (channel) => `messages/${channel}`,\n      // highlight-start\n      transformResponse(response: Message[]) {\n        return messagesAdapter.addMany(\n          messagesAdapter.getInitialState(),\n          response,\n        )\n      },\n      // highlight-end\n      async onCacheEntryAdded(\n        arg,\n        { updateCachedData, cacheDataLoaded, cacheEntryRemoved },\n      ) {\n        const ws = new WebSocket('ws://localhost:8080')\n        try {\n          await cacheDataLoaded\n\n          const listener = (event: MessageEvent) => {\n            const data = JSON.parse(event.data)\n            if (!isMessage(data) || data.channel !== arg) return\n\n            updateCachedData((draft) => {\n              // highlight-start\n              messagesAdapter.upsertOne(draft, data)\n              // highlight-end\n            })\n          }\n\n          ws.addEventListener('message', listener)\n        } catch {}\n        await cacheEntryRemoved\n        ws.close()\n      },\n    }),\n  }),\n})\n\nexport const { useGetMessagesQuery } = api\n```\n\nThis example demonstrates how the [previous example](#websocket-chat-api) can be altered to allow for transforming the response shape when adding data to the cache.\n\nFor example, the data is transformed from this shape:\n\n```ts no-transpile\n[\n  {\n    id: 0\n    channel: 'redux'\n    userName: 'Mark'\n    text: 'Welcome to #redux!'\n  },\n  {\n    id: 1\n    channel: 'redux'\n    userName: 'Lenz'\n    text: 'Glad to be here!'\n  },\n]\n```\n\nTo this:\n\n```ts no-transpile\n{\n  // The unique IDs of each item. Must be strings or numbers\n  ids: [0, 1],\n  // A lookup table mapping entity IDs to the corresponding entity objects\n  entities: {\n    0: {\n      id: 0,\n      channel: \"redux\",\n      userName: \"Mark\",\n      text: \"Welcome to #redux!\",\n    },\n    1: {\n      id: 1,\n      channel: \"redux\",\n      userName: \"Lenz\",\n      text: \"Glad to be here!\",\n    },\n  },\n};\n```\n\nA key point to keep in mind is that updates to the cached data within the `onCacheEntryAdded` callback must respect the transformed data shape which will be present for the cached data. The example shows how [`createEntityAdapter`](../../api/createEntityAdapter) can be used for the initial `transformResponse`, and again when streamed updates are received to upsert received items into the cached data, while maintaining the normalized state structure.\n"
  },
  {
    "path": "docs/rtk-query/usage/usage-without-react-hooks.mdx",
    "content": "---\nid: usage-without-react-hooks\ntitle: Usage Without React Hooks\nsidebar_label: Usage Without React Hooks\nhide_title: true\ndescription: 'RTK Query > Usage > Usage Without React Hooks: Using RTKQ with other UI frameworks'\n---\n\n&nbsp;\n\n# Usage Without React Hooks\n\nLike the Redux core and Redux Toolkit, RTK Query's primary functionality is UI-agnostic and can be used with any UI layer. RTK Query also includes a version of [`createApi`](../api/createApi.mdx) designed specifically for use with React, which [automatically generates React hooks](../api/created-api/hooks.mdx).\n\nWhile React hooks are the primary way that the majority of users are expected to be using RTK Query, the library itself uses plain JS logic and can be used both with React Class components, and independent of React itself.\n\nThis page documents how to interact with RTK Query when used without React Hooks, in order to make proper use of RTK Query [`cache behavior`](./cache-behavior).\n\n## Adding a subscription\n\nCache subscriptions are used to tell RTK Query that it needs to fetch data for an endpoint. A subscription for an endpoint can be added by dispatching the result of the [`initiate`](../api/created-api/endpoints.mdx#initiate) thunk action creator attached to a query endpoint.\n\nWith React hooks, this behavior is instead handled within [`useQuery`](../api/created-api/hooks.mdx#usequery), [`useQuerySubscription`](../api/created-api/hooks.mdx#usequerysubscription), [`useLazyQuery`](../api/created-api/hooks.mdx#uselazyquery), and [`useLazyQuerySubscription`](../api/created-api/hooks.mdx#uselazyquerysubscription).\n\n```ts title=\"Subscribing to cached data\" no-transpile\nconst promise = dispatch(api.endpoints.getPosts.initiate())\nconst { refetch } = promise\n// interact with the cache in the same way as you would with a useFetch...() hook\nconst { data, isLoading, isSuccess /*...*/ } = await promise\n```\n\n## Removing a subscription\n\nRemoving a cache subscription is necessary for RTK Query to identify that cached data is no longer required. This allows RTK Query to clean up and remove old cache data.\n\nThe result of dispatching the [`initiate`](../api/created-api/endpoints.mdx#initiate) thunk action creator of a query endpoint is a Promise with an `unsubscribe` property. This property is a function that when called, will remove the corresponding cache subscription.\n\nWith React hooks, this behavior is instead handled within [`useQuery`](../api/created-api/hooks.mdx#usequery), [`useQuerySubscription`](../api/created-api/hooks.mdx#usequerysubscription), [`useLazyQuery`](../api/created-api/hooks.mdx#uselazyquery), and [`useLazyQuerySubscription`](../api/created-api/hooks.mdx#uselazyquerysubscription).\n\n```ts title=\"Unsubscribing from cached data\" no-transpile\n// Adding a cache subscription\nconst promise = dispatch(api.endpoints.getPosts.initiate())\n\n// Removing the corresponding cache subscription\npromise.unsubscribe()\n```\n\n## Accessing cached data & request status\n\nAccessing cache data and request status information can be performed using the `select` function property of a query endpoint to create a selector and call that with the Redux state. This provides a snapshot of the cache data and request status information at the time it is called.\n\n:::caution\n\nThe `endpoint.select(arg)` function creates a _new_ selector instance - it isn't the actual selector function itself!\n\n:::\n\nWith React hooks, this behavior is instead handled within [`useQuery`](../api/created-api/hooks.mdx#usequery), [`useQueryState`](../api/created-api/hooks.mdx#usequerystate), and [`useLazyQuery`](../api/created-api/hooks.mdx#uselazyquery).\n\n```ts title=\"Accessing cached data & request status\" no-transpile\nconst result = api.endpoints.getPosts.select()(state)\nconst { data, isSuccess, isError, error } = result\n```\n\nNote that unlike with the auto-generated hooks, there is no `isFetching` flag, and the `isLoading` flag will be true if the status is pending, regardless of if there is already data.\n\n### Memoization\n\nBecause the `endpoint.select(arg)` function returns a new selector each time it's called, and because this instance itself is memoized, it can be desirable to memoize the creation of a selector (for example, to then use that memoized instance in another selector). This can be done with `createSelector`:\n\n```ts title=\"Creating a memoized selector creator\" no-transpile\nconst createGetPostSelector = createSelector(\n  (id: string) => id,\n  (id) => api.endpoints.getPost.select(id),\n)\n\nconst selectGetPostError = createSelector(\n  (state: RootState) => state,\n  (state: RootState, id: string) => createGetPostSelector(id),\n  (state, selectGetPost) => selectGetPost(state).error,\n)\n```\n\n## Performing mutations\n\n[Mutations](./mutations.mdx) are used in order to update data on the server. Mutations can be performed by dispatching the result of the [`initiate`](../api/created-api/endpoints.mdx#initiate) thunk action creator attached to a mutation endpoint.\n\nWith React hooks, this behavior is instead handled within [`useMutation`](../api/created-api/hooks.mdx#usemutation).\n\n```ts title=\"Triggering a mutation endpoint\" no-transpile\ndispatch(api.endpoints.addPost.initiate({ name: 'foo' }))\n```\n\n## Examples\n\nExamples of usage without React hooks can be found under the following:\n\n- The `PostDetail` component in the [`React Class Components` example](./examples.mdx#react-class-components)\n- The [`Svelte` example](./examples.mdx#svelte)\n- The below `Cache Lifetime Subscription Class Component` example:\n\n<iframe\n  src=\"https://codesandbox.io/embed/rtk-query-cache-lifetime-subscription-class-component-example-38mgd?fontsize=12&runonclick=1&hidenavigation=1&module=%2Fsrc%2Fcomponents%2FUsersList.tsx&theme=dark&runonclick=1\"\n  style={{\n    width: '100%',\n    height: '800px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"RTK Query Cache Lietime Subscription Class Component Example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\n## Further Information\n\n- NgRx maintainer Brandon Roberts has written a post called [Cousins playing nicely: Experimenting with NgRx Store and RTK Query](https://dev.to/brandontroberts/cousins-playing-nicely-experimenting-with-ngrx-store-and-rtk-query-25f4), which demonstrates some approaches for integrating RTK Query into NgRx\n- [`saulmoro/ngrx-rtk-query`](https://github.com/SaulMoro/ngrx-rtk-query) implements an NgRx equivalent of the subscription lifecycle managed in RTKQ's own React hooks\n"
  },
  {
    "path": "docs/rtk-query/usage-with-typescript.mdx",
    "content": "---\nid: usage-with-typescript\ntitle: Usage With TypeScript\nsidebar_label: Usage With TypeScript\nhide_title: true\ndescription: 'RTK Query > TypeScript: Instructions on how to use RTK Query with TypeScript'\n---\n\n&nbsp;\n\n# Usage With TypeScript\n\n:::tip What You'll Learn\n\n- Details on how to use various RTK Query APIs with TypeScript\n\n:::\n\n## Introduction\n\nAs with the rest of the Redux Toolkit package, RTK Query is written in TypeScript, and its API is designed for seamless use in TypeScript applications.\n\nThis page provides details for using APIs included in RTK Query with TypeScript and how to type them correctly.\n\n:::info\n\nRTK Query [supports TS versions released within the last 2 years](../usage/usage-with-typescript.md).\n\nIf you encounter any problems with the types that are not described on this page, please [open an issue](https://github.com/reduxjs/redux-toolkit/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc) for discussion.\n\n:::\n\n## `createApi`\n\n### Using auto-generated React Hooks\n\nThe React-specific entry point for RTK Query exports a version of [`createApi`](./api/createApi.mdx) which automatically generates React hooks for each of the defined query & mutation [`endpoints`](./api/createApi.mdx#endpoints).\n\nTo use the auto-generated React Hooks as a TypeScript user, **you'll need to use TS4.1+**.\n\n```ts\n// file: src/services/types.ts noEmit\nexport type Pokemon = {}\n\n// file: src/services/pokemon.ts\n// Need to use the React-specific entry point to allow generating React hooks\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Pokemon } from './types'\n\n// Define a service using a base URL and expected endpoints\nexport const pokemonApi = createApi({\n  reducerPath: 'pokemonApi',\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (build) => ({\n    getPokemonByName: build.query<Pokemon, string>({\n      query: (name) => `pokemon/${name}`,\n    }),\n  }),\n})\n\n// highlight-start\n// Export hooks for usage in function components, which are\n// auto-generated based on the defined endpoints\nexport const { useGetPokemonByNameQuery } = pokemonApi\n// highlight-end\n```\n\nFor older versions of TS, you can use `api.endpoints.[endpointName].useQuery/useMutation` to access the same hooks.\n\n```ts title=\"Accessing api hooks directly\"\n// file: src/services/types.ts noEmit\nexport type Pokemon = {}\n\n// file: src/services/pokemon.ts noEmit\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Pokemon } from './types'\n\nexport const pokemonApi = createApi({\n  reducerPath: 'pokemonApi',\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (build) => ({\n    getPokemonByName: build.query<Pokemon, string>({\n      query: (name) => `pokemon/${name}`,\n    }),\n  }),\n})\n\nexport const { useGetPokemonByNameQuery } = pokemonApi\n\n// file: src/services/manual-query.ts\nimport { pokemonApi } from './pokemon'\n\nconst useGetPokemonByNameQuery = pokemonApi.endpoints.getPokemonByName.useQuery\n```\n\n### Typing a `baseQuery`\n\nTyping a custom [`baseQuery`](./api/createApi.mdx#basequery) can be done using the `BaseQueryFn` type exported by RTK Query.\n\n```ts title=\"Base Query signature\" no-transpile\nexport type BaseQueryFn<\n  Args = any,\n  Result = unknown,\n  Error = unknown,\n  DefinitionExtraOptions = {},\n  Meta = {},\n> = (\n  args: Args,\n  api: BaseQueryApi,\n  extraOptions: DefinitionExtraOptions,\n) => MaybePromise<QueryReturnValue<Result, Error, Meta>>\n\nexport interface BaseQueryApi {\n  signal: AbortSignal\n  dispatch: ThunkDispatch<any, any, any>\n  getState: () => unknown\n}\n\nexport type QueryReturnValue<T = unknown, E = unknown, M = unknown> =\n  | {\n      error: E\n      data?: undefined\n      meta?: M\n    }\n  | {\n      error?: undefined\n      data: T\n      meta?: M\n    }\n```\n\nThe `BaseQueryFn` type accepts the following generics:\n\n- `Args` - The type for the first parameter of the function. The result returned by a [`query`](./api/createApi.mdx#query) property on an endpoint will be passed here.\n- `Result` - The type to be returned in the `data` property for the success case. Unless you expect all queries and mutations to return the same type, it is recommended to keep this typed as `unknown`, and specify the types individually as shown [below](#typing-query-and-mutation-endpoints).\n- `Error` - The type to be returned for the `error` property in the error case. This type also applies to all [`queryFn`](#typing-a-queryfn) functions used in endpoints throughout the API definition.\n- `DefinitionExtraOptions` - The type for the third parameter of the function. The value provided to the [`extraOptions`](./api/createApi.mdx#extraoptions) property on an endpoint will be passed here.\n- `Meta` - the type of the `meta` property that may be returned from calling the `baseQuery`. The `meta` property is accessible as the second argument to [`transformResponse`](./api/createApi.mdx#transformresponse) and [`transformErrorResponse`](./api/createApi.mdx#transformerrorresponse).\n\n:::note\n\nThe `meta` property returned from a `baseQuery` will always be considered as potentially undefined, as a `throw` in the error case may result in it not being provided. When accessing values from the `meta` property, this should be accounted for, e.g. using [optional chaining](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining)\n\n:::\n\n```ts title=\"Simple baseQuery TypeScript example\"\nimport { createApi } from '@reduxjs/toolkit/query'\nimport type { BaseQueryFn } from '@reduxjs/toolkit/query'\n\nconst simpleBaseQuery: BaseQueryFn<\n  string, // Args\n  unknown, // Result\n  { reason: string }, // Error\n  { shout?: boolean }, // DefinitionExtraOptions\n  { timestamp: number } // Meta\n> = (arg, api, extraOptions) => {\n  // `arg` has the type `string`\n  // `api` has the type `BaseQueryApi` (not configurable)\n  // `extraOptions` has the type `{ shout?: boolean }\n\n  const meta = { timestamp: Date.now() }\n\n  if (arg === 'forceFail') {\n    return {\n      error: {\n        reason: 'Intentionally requested to fail!',\n        meta,\n      },\n    }\n  }\n\n  if (extraOptions.shout) {\n    return { data: 'CONGRATULATIONS', meta }\n  }\n\n  return { data: 'congratulations', meta }\n}\n\nconst api = createApi({\n  baseQuery: simpleBaseQuery,\n  endpoints: (build) => ({\n    getSupport: build.query({\n      query: () => 'support me',\n      extraOptions: {\n        shout: true,\n      },\n    }),\n  }),\n})\n```\n\n### Typing query and mutation `endpoints`\n\n`endpoints` for an api are defined as an object using the builder syntax. Both `query` and `mutation` endpoints can be typed by providing types to the generics in `<ResultType, QueryArg>` format.\n\n- `ResultType` - The type of the final data returned by the query, factoring an optional [`transformResponse`](./api/createApi.mdx#transformresponse).\n  - If `transformResponse` is not provided, then it is treated as though a successful query will return this type instead.\n  - If `transformResponse` _is_ provided, the input type for `transformResponse` must also be specified, to indicate the type that the initial query returns. The return type for `transformResponse` must match `ResultType`.\n  - If `queryFn` is used rather than `query`, then it must return the following shape for the success case:\n    ```ts no-transpile\n    {\n      data: ResultType\n    }\n    ```\n- `QueryArg` - The type of the input that will be passed as the only parameter to the `query` property of the endpoint, or the first parameter of a `queryFn` property if used instead.\n  - If `query` doesn't have a parameter, then `void` type has to be provided explicitly.\n  - If `query` has an optional parameter, then a union type with the type of parameter, and `void` has to be provided, e.g. `number | void`.\n\n```ts title=\"Defining endpoints with TypeScript\"\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\ninterface Post {\n  id: number\n  name: string\n}\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    // highlight-start\n    //              ResultType  QueryArg\n    //                    v       v\n    getPost: build.query<Post, number>({\n      // inferred as `number` from the `QueryArg` type\n      //       v\n      query: (id) => `post/${id}`,\n      // An explicit type must be provided to the raw result that the query returns\n      // when using `transformResponse`\n      //                             v\n      transformResponse: (rawResult: { result: { post: Post } }, meta) => {\n        //                                                        ^\n        // The optional `meta` property is available based on the type for the `baseQuery` used\n\n        // The return value for `transformResponse` must match `ResultType`\n        return rawResult.result.post\n      },\n    }),\n    // highlight-end\n  }),\n})\n```\n\n:::note\n\n`queries` and `mutations` can also have their return type defined by a [`baseQuery`](#typing-a-basequery) rather than the method shown above, however, unless you expect all of your queries and mutations to return the same type, it is recommended to leave the return type of the `baseQuery` as `unknown`.\n\n:::\n\n### Typing a `queryFn`\n\nAs mentioned in [Typing query and mutation endpoints](#typing-query-and-mutation-endpoints), a `queryFn` will receive its result & arg types from the generics provided to the corresponding built endpoint.\n\n```ts\n// file: randomData.ts noEmit\nexport declare const getRandomName: () => string\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { getRandomName } from './randomData'\n\ninterface Post {\n  id: number\n  name: string\n}\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    // highlight-start\n    //              ResultType  QueryArg\n    //                    v       v\n    getPost: build.query<Post, number>({\n      // inferred as `number` from the `QueryArg` type\n      //         v\n      queryFn: (arg, queryApi, extraOptions, baseQuery) => {\n        const post: Post = {\n          id: arg,\n          name: getRandomName(),\n        }\n        // For the success case, the return type for the `data` property\n        // must match `ResultType`\n        //              v\n        return { data: post }\n      },\n    }),\n    // highlight-end\n  }),\n})\n```\n\nThe error type that a `queryFn` must return is determined by the [`baseQuery`](#typing-a-basequery) provided to `createApi`.\n\nWith [`fetchBaseQuery`](./api/fetchBaseQuery.mdx), the error type is like so:\n\n```ts title=\"fetchBaseQuery error shape\" no-transpile\n{\n  status: number\n  data: any\n}\n```\n\nAn error case for the example above using `queryFn` and the error type from `fetchBaseQuery` could look like:\n\n```ts title=\"queryFn error example with error type from fetchBaseQuery\"\n// file: randomData.ts noEmit\nexport declare const getRandomName: () => string\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { getRandomName } from './randomData'\n\ninterface Post {\n  id: number\n  name: string\n}\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    // highlight-start\n    getPost: build.query<Post, number>({\n      queryFn: (arg, queryApi, extraOptions, baseQuery) => {\n        // highlight-start\n        if (arg <= 0) {\n          return {\n            error: {\n              status: 500,\n              statusText: 'Internal Server Error',\n              data: 'Invalid ID provided.',\n            },\n          }\n        }\n        // highlight-end\n        const post: Post = {\n          id: arg,\n          name: getRandomName(),\n        }\n        return { data: post }\n      },\n    }),\n  }),\n})\n```\n\nFor users who wish to _only_ use `queryFn` for each endpoint and not include a `baseQuery` at all, RTK Query provides a `fakeBaseQuery` function that can be used to easily specify the error type each `queryFn` should return.\n\n```ts title=\"Excluding baseQuery for all endpoints\"\nimport { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query'\n\n// highlight-start\ntype CustomErrorType = { reason: 'too cold' | 'too hot' }\n// highlight-end\n\nconst api = createApi({\n  // highlight-start\n  // This type will be used as the error type for all `queryFn` functions provided\n  //                              v\n  baseQuery: fakeBaseQuery<CustomErrorType>(),\n  // highlight-end\n  endpoints: (build) => ({\n    eatPorridge: build.query<'just right', 1 | 2 | 3>({\n      // highlight-start\n      queryFn(seat) {\n        if (seat === 1) {\n          return { error: { reason: 'too cold' } }\n        }\n\n        if (seat === 2) {\n          return { error: { reason: 'too hot' } }\n        }\n\n        return { data: 'just right' }\n      },\n      // highlight-end\n    }),\n    microwaveHotPocket: build.query<'delicious!', number>({\n      // highlight-start\n      queryFn(duration) {\n        if (duration < 110) {\n          return { error: { reason: 'too cold' } }\n        }\n        if (duration > 140) {\n          return { error: { reason: 'too hot' } }\n        }\n\n        return { data: 'delicious!' }\n      },\n      // highlight-end\n    }),\n  }),\n})\n```\n\n### Typing `dispatch` and `getState`\n\n`createApi` exposes the standard Redux `dispatch` and `getState` methods in several places, such as the `lifecycleApi` argument in lifecycle methods, or the `baseQueryApi` argument passed to `queryFn` methods and base query functions.\n\nNormally, [your application infers `RootState` and `AppDispatch` types from the store setup](../tutorials/typescript.md#define-root-state-and-dispatch-types). Since `createApi` has to be called prior to creating the Redux store and is used as part of the store setup sequence, it can't directly know or use those types - it would cause a circular type inference error.\n\nBy default, `dispatch` usages inside of `createApi` will be typed as `ThunkDispatch`, and `getState` usages are typed as `() => unknown`. You will need to assert the type when needed - `getState() as RootState`. You may also include an explicit return type for the function as well, in order to break the circular type inference cycle:\n\n```ts no-transpile\nconst api = createApi({\n  baseQuery,\n  endpoints: (build) => ({\n    getTodos: build.query<Todo[], void>({\n      async queryFn() {\n        // highlight-start\n        // Cast state as `RootState`\n        const state = getState() as RootState\n        // highlight-end\n        const text = state.todoTexts[queryFnCalls]\n        return { data: [{ id: `${queryFnCalls++}`, text }] }\n      },\n    }),\n  }),\n})\n```\n\n### Typing `providesTags`/`invalidatesTags`\n\nRTK Query utilizes a cache tag invalidation system in order to provide [automated re-fetching](./usage/automated-refetching.mdx) of stale data.\n\nWhen using the function notation, both the `providesTags` and `invalidatesTags` properties on endpoints are called with the following arguments:\n\n- result: `ResultType` | `undefined` - The result returned by a successful query. The type corresponds with `ResultType` as [supplied to the built endpoint](#typing-query-and-mutation-endpoints). In the error case for a query, this will be `undefined`.\n- error: `ErrorType` | `undefined` - The error returned by an errored query. The type corresponds with `Error` as [supplied to the `baseQuery` for the api](#typing-a-basequery). In the success case for a query, this will be `undefined`.\n- arg: `QueryArg` - The argument supplied to the `query` property when the query itself is called. The type corresponds with `QueryArg` as [supplied to the built endpoint](#typing-query-and-mutation-endpoints).\n\nA recommended use-case with `providesTags` when a query returns a list of items is to provide a tag for each item in the list using the entity ID, as well as a 'LIST' ID tag (see [Advanced Invalidation with abstract tag IDs](./usage/automated-refetching.mdx#advanced-invalidation-with-abstract-tag-ids)).\n\nThis is often written by spreading the result of mapping the received data into an array, as well as an additional item in the array for the `'LIST'` ID tag. When spreading the mapped array, by default, TypeScript will broaden the `type` property to `string`. As the tag `type` must correspond to one of the string literals provided to the [`tagTypes`](./api/createApi.mdx#tagtypes) property of the api, the broad `string` type will not satisfy TypeScript. In order to alleviate this, the tag `type` can be cast `as const` to prevent the type being broadened to `string`.\n\n```ts title=\"providesTags TypeScript example\"\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\ninterface Post {\n  id: number\n  name: string\n}\ntype PostsResponse = Post[]\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  tagTypes: ['Posts'],\n  endpoints: (build) => ({\n    getPosts: build.query<PostsResponse, void>({\n      query: () => 'posts',\n      providesTags: (result) =>\n        result\n          ? [\n              // highlight-start\n              ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n              { type: 'Posts', id: 'LIST' },\n              // highlight-end\n            ]\n          : [{ type: 'Posts', id: 'LIST' }],\n    }),\n  }),\n})\n```\n\n<!-- when mapping, needs the tag `type` cast `as const` to prevent being broadened to `string` -->\n\n## Skipping queries with TypeScript using `skipToken`\n\n<!-- good for scenarios where you never want to send the query for a nullish value (skipping the query), but want the param itself to be typed correctly. Passing `skipToken` as the param will prevents the query from firing, with the same effect as `{ skip: true }`  -->\n\nRTK Query provides the ability to conditionally skip queries from automatically running using the `skip` parameter as part of query hook options (see [Conditional Fetching](./usage/conditional-fetching.mdx)).\n\nTypeScript users may find that they encounter invalid type scenarios when a query argument is typed to not be `undefined`, and they attempt to `skip` the query when an argument would not be valid.\n\n```ts title=\"API definition\"\n// file: types.ts noEmit\nexport interface Post {\n  id: number\n  name: string\n}\n\n// file: api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Post } from './types'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    // Query argument is required to be `number`, and can't be `undefined`\n    //                            V\n    getPost: build.query<Post, number>({\n      query: (id) => `post/${id}`,\n    }),\n  }),\n})\n\nexport const { useGetPostQuery } = api\n```\n\n```tsx no-transpile title=\"Using skip in a component\"\nimport { useGetPostQuery } from './api'\n\nfunction MaybePost({ id }: { id?: number }) {\n  // This will produce a typescript error:\n  // Argument of type 'number | undefined' is not assignable to parameter of type 'number | unique symbol'.\n  // Type 'undefined' is not assignable to type 'number | unique symbol'.\n\n  // @ts-expect-error id passed must be a number, but we don't call it when it isn't a number\n  const { data } = useGetPostQuery(id, { skip: !id })\n\n  return <div>...</div>\n}\n```\n\nWhile you might be able to convince yourself that the query won't be called unless the `id` arg is a `number` at the time, TypeScript won't be convinced so easily.\n\nRTK Query provides a `skipToken` export which can be used as an alternative to the `skip` option in order to skip queries, while remaining type-safe. When `skipToken` is passed as the query argument to `useQuery`, `useQueryState` or `useQuerySubscription`, it provides the same effect as setting `skip: true` in the query options, while also being a valid argument in scenarios where the `arg` might be undefined otherwise.\n\n```tsx no-transpile title=\"Using skipToken in a component\"\nimport { skipToken } from '@reduxjs/toolkit/query/react'\nimport { useGetPostQuery } from './api'\n\nfunction MaybePost({ id }: { id?: number }) {\n  // When `id` is nullish, we will still skip the query.\n  // TypeScript is also happy that the query will only ever be called with a `number` now\n  const { data } = useGetPostQuery(id ?? skipToken)\n\n  return <div>...</div>\n}\n```\n\n## Type safe error handling\n\nWhen an error is gracefully provided from a [`base query`](./api/createApi.mdx#basequery), RTK query will provide the error\ndirectly. If an unexpected error is thrown by user code rather than a handled error,\nthat error will be transformed into a `SerializedError` shape. Users should make sure that they are checking which kind of error they are dealing with before attempting to access its properties. This can be done in a type safe manner either\nby using a type guard, e.g. by checking for [discriminated properties](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#the-in-operator-narrowing),\nor using a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates).\n\nWhen using [`fetchBaseQuery`](./api/fetchBaseQuery.mdx), as your base query,\nerrors will be of type `FetchBaseQueryError | SerializedError`. The specific shapes of those types can be seen below.\n\n```ts title=\"FetchBaseQueryError type\"\nexport type FetchBaseQueryError =\n  | {\n      /**\n       * * `number`:\n       *   HTTP status code\n       */\n      status: number\n      data: unknown\n    }\n  | {\n      /**\n       * * `\"FETCH_ERROR\"`:\n       *   An error that occurred during execution of `fetch` or the `fetchFn` callback option\n       **/\n      status: 'FETCH_ERROR'\n      data?: undefined\n      error: string\n    }\n  | {\n      /**\n       * * `\"PARSING_ERROR\"`:\n       *   An error happened during parsing.\n       *   Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\n       *   or an error occurred while executing a custom `responseHandler`.\n       **/\n      status: 'PARSING_ERROR'\n      originalStatus: number\n      data: string\n      error: string\n    }\n  | {\n      /**\n       * * `\"CUSTOM_ERROR\"`:\n       *   A custom error type that you can return from your `queryFn` where another error might not make sense.\n       **/\n      status: 'CUSTOM_ERROR'\n      data?: unknown\n      error: string\n    }\n```\n\n```ts title=\"SerializedError type\"\nexport interface SerializedError {\n  name?: string\n  message?: string\n  stack?: string\n  code?: string\n}\n```\n\n### Error result example\n\nWhen using `fetchBaseQuery`, the `error` property returned from a hook will have the type `FetchBaseQueryError | SerializedError | undefined`.\nIf an error is present, you can access error properties after narrowing the type to either `FetchBaseQueryError` or `SerializedError`.\n\n```tsx no-transpile\nimport { usePostsQuery } from './services/api'\n\nfunction PostDetail() {\n  const { data, error, isLoading } = usePostsQuery()\n\n  if (isLoading) {\n    return <div>Loading...</div>\n  }\n\n  if (error) {\n    if ('status' in error) {\n      // you can access all properties of `FetchBaseQueryError` here\n      const errMsg = 'error' in error ? error.error : JSON.stringify(error.data)\n\n      return (\n        <div>\n          <div>An error has occurred:</div>\n          <div>{errMsg}</div>\n        </div>\n      )\n    }\n    // you can access all properties of `SerializedError` here\n    return <div>{error.message}</div>\n  }\n\n  if (data) {\n    return (\n      <div>\n        {data.map((post) => (\n          <div key={post.id}>Name: {post.name}</div>\n        ))}\n      </div>\n    )\n  }\n\n  return null\n}\n```\n\n### Inline error handling example\n\nWhen handling errors inline after [`unwrapping`](../api/createAsyncThunk.mdx#unwrapping-result-actions) a mutation call,\na thrown error will have a type of `any` for typescript versions below 4.4,\nor [`unknown` for versions 4.4+](https://devblogs.microsoft.com/typescript/announcing-typescript-4-4/#use-unknown-catch-variables).\nIn order to safely access properties of the error, you must first narrow the type to a known type.\nThis can be done using a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\nas shown below.\n\n```tsx no-transpile title=\"services/helpers.ts\"\nimport { FetchBaseQueryError } from '@reduxjs/toolkit/query'\n\n/**\n * Type predicate to narrow an unknown error to `FetchBaseQueryError`\n */\nexport function isFetchBaseQueryError(\n  error: unknown,\n): error is FetchBaseQueryError {\n  return typeof error === 'object' && error != null && 'status' in error\n}\n\n/**\n * Type predicate to narrow an unknown error to an object with a string 'message' property\n */\nexport function isErrorWithMessage(\n  error: unknown,\n): error is { message: string } {\n  return (\n    typeof error === 'object' &&\n    error != null &&\n    'message' in error &&\n    typeof (error as any).message === 'string'\n  )\n}\n```\n\n```tsx no-transpile title=\"addPost.tsx\"\nimport { useState } from 'react'\nimport { useSnackbar } from 'notistack'\nimport { api } from './services/api'\nimport { isFetchBaseQueryError, isErrorWithMessage } from './services/helpers'\n\nfunction AddPost() {\n  const { enqueueSnackbar, closeSnackbar } = useSnackbar()\n  const [name, setName] = useState('')\n  const [addPost] = useAddPostMutation()\n\n  async function handleAddPost() {\n    try {\n      await addPost(name).unwrap()\n      setName('')\n    } catch (err) {\n      if (isFetchBaseQueryError(err)) {\n        // you can access all properties of `FetchBaseQueryError` here\n        const errMsg = 'error' in err ? err.error : JSON.stringify(err.data)\n        enqueueSnackbar(errMsg, { variant: 'error' })\n      } else if (isErrorWithMessage(err)) {\n        // you can access a string 'message' property here\n        enqueueSnackbar(err.message, { variant: 'error' })\n      }\n    }\n  }\n\n  return (\n    <div>\n      <input value={name} onChange={(e) => setName(e.target.value)} />\n      <button>Add post</button>\n    </div>\n  )\n}\n```\n\n## Schema Validation\n\nEndpoints can have schemas for runtime validation of query args, responses, and errors. Any [Standard Schema](https://standardschema.dev/) compliant library can be used. See [API reference](./api/createApi.mdx#schema-validation) for full list of available schemas.\n\nWhen following the default approach of explicitly specifying type parameters for queries and mutations, the schemas will be required to match the types provided.\n\n```ts title=\"Explicitly typed endpoint\" no-transpile\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport * as v from 'valibot'\n\nconst postSchema = v.object({\n  id: v.number(),\n  name: v.string(),\n})\ntype Post = v.InferOutput<typeof postSchema>\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    getPost: build.query<Post, { id: number }>({\n      query: ({ id }) => `/post/${id}`,\n      responseSchema: postSchema, // errors if type mismatch\n    }),\n  }),\n})\n```\n\nSchemas can also be used as a source of inference, meaning that the type parameters can be omitted.\n\n```ts title=\"Implicitly typed endpoint\" no-transpile\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport * as v from 'valibot'\n\nconst postSchema = v.object({\n  id: v.number(),\n  name: v.string(),\n})\ntype Post = v.InferOutput<typeof postSchema>\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    getPost: build.query({\n      // infer arg from here\n      query: ({ id }: { id: number }) => `/post/${id}`,\n      // infer result from here\n      responseSchema: postSchema,\n    }),\n    getTransformedPost: build.query({\n      // infer arg from here\n      query: ({ id }: { id: number }) => `/post/${id}`,\n      // infer untransformed result from here\n      rawResponseSchema: postSchema,\n      // infer transformed result from here\n      transformResponse: (response) => ({\n        ...response,\n        published_at: new Date(response.published_at),\n      }),\n    }),\n  }),\n})\n```\n\n:::warning\n\nSchemas should _not_ perform any transformation that would change the type of the value.\n\n```ts title=\"Incorrect usage\" no-transpile\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport * as v from 'valibot'\nimport { titleCase } from 'lodash'\n\nconst postSchema = v.object({\n  id: v.number(),\n  name: v.pipe(\n    v.string(),\n    v.transform(titleCase), // fine - string -> string\n  ),\n  published_at: v.pipe(\n    v.string(),\n    // highlight-next-line\n    v.transform((s) => new Date(s)), // not allowed!\n    v.date(),\n  ),\n})\ntype Post = v.InferOutput<typeof postSchema>\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    getPost: build.query<Post, { id: number }>({\n      query: ({ id }) => `/post/${id}`,\n      responseSchema: postSchema,\n    }),\n  }),\n})\n```\n\nInstead, transformation should be done with `transformResponse` and `transformErrorResponse` (when using `query`) or inside `queryFn` (when using `queryFn`).\n\n```ts title=\"Correct usage\" no-transpile\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport * as v from 'valibot'\n\nconst postSchema = v.object({\n  id: v.number(),\n  name: v.string(),\n  published_at: v.string(),\n})\ntype RawPost = v.InferOutput<typeof postSchema>\ntype Post = Omit<RawPost, 'published_at'> & { published_at: Date }\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    getPost: build.query<Post, { id: number }>({\n      query: ({ id }) => `/post/${id}`,\n      // use rawResponseSchema to validate *before* transformation\n      rawResponseSchema: postSchema,\n      // highlight-start\n      transformResponse: (response) => ({\n        ...response,\n        published_at: new Date(response.published_at),\n      }),\n      // highlight-end\n    }),\n  }),\n})\n```\n\n:::\n"
  },
  {
    "path": "docs/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"allowSyntheticDefaultImports\": true,\n    \"esModuleInterop\": true,\n    \"moduleResolution\": \"node\",\n    \"noUnusedLocals\": false,\n    \"noUnusedParameters\": false,\n    \"allowUnusedLabels\": true,\n    \"skipLibCheck\": true,\n    \"noEmitOnError\": false,\n    \"strict\": true,\n    \"removeComments\": false,\n    \"module\": \"ES2020\",\n    \"target\": \"ES2020\",\n    \"allowJs\": true,\n    \"checkJs\": true,\n    \"alwaysStrict\": false,\n    \"baseUrl\": \"..\",\n    \"jsx\": \"preserve\",\n    \"traceResolution\": false,\n    \"explainFiles\": false,\n    \"paths\": {\n      \"react\": [\"docs/node_modules/@types/react\"],\n      \"react-dom\": [\"docs/node_modules/@types/react-dom\"],\n      \"@reduxjs/toolkit\": [\"packages/toolkit/dist/index.d.ts\"],\n      \"@reduxjs/toolkit/query\": [\"packages/toolkit/dist/query/index.d.ts\"],\n      \"@reduxjs/toolkit/query/react\": [\n        \"packages/toolkit/dist/query/react/index.d.ts\"\n      ],\n      \"@virtual/*\": [\"docs/virtual/*\"],\n      \"your-cool-library\": [\"docs/virtual/your-cool-library/index.ts\"],\n      \"redux-logger\": [\"docs/virtual/redux-logger/index.ts\"],\n      \"petstore-api.generated\": [\"docs/virtual/petstore-api.generated/index.ts\"]\n    }\n  }\n}\n"
  },
  {
    "path": "docs/tutorials/overview.md",
    "content": "---\nid: tutorials-overview\nslug: overview\ntitle: Tutorials Overview\nsidebar_label: Tutorials Overview\nhide_title: true\n---\n\nimport LiteYouTubeEmbed from 'react-lite-youtube-embed';\nimport 'react-lite-youtube-embed/dist/LiteYouTubeEmbed.css'\n\n&nbsp;\n\n# Tutorials Overview\n\n**The Redux core docs site at https://redux.js.org contains the primary tutorials for learning Redux**, including how to use Redux Toolkit and React-Redux together.\n\n:::tip\n\nTo avoid duplicating explanations between the Redux core and Redux Toolkit documentation, we've focused on making the Redux core docs tutorials comprehensive, and point to them instead of having extended tutorials here in the Redux Toolkit docs.\n\n:::\n\nSee these linked tutorials to learn how to use Redux Toolkit effectively.\n\n## Redux Toolkit Quick Starts\n\nThe [**Redux Toolkit Quick Start tutorial**](./quick-start.mdx) briefly shows how to add and use Redux Toolkit in a React application.\n\n**If you just want the fastest way to get a basic example running, read the Quick Start tutorial.**\n\nWe also have a [**TypeScript Quick Start tutorial**](./typescript.md) that briefly shows how to set up and use TypeScript with Redux Toolkit and React-Redux.\n\nIf you are using Next.js we have a tutorial specific to using Redux Toolkit with Next.js [**Next.js tutorial**](../usage/nextjs.mdx).\n\n## Redux Essentials: A Real-World Example\n\nThe [**Redux Essentials tutorial**](https://redux.js.org/tutorials/essentials/part-1-overview-concepts) teaches you \"how to use Redux the right way\", using Redux Toolkit as the standard approach for writing Redux logic.\n\nIt shows how to build a \"real-world\" style example application, and teaches Redux concepts along the way.\n\n**If you've never used Redux before, and just want to know \"how do I use this to build something useful?\", start with the Redux Essentials tutorial.**\n\n## Redux Fundamentals: Redux from the Ground Up\n\nThe [**Redux Fundamentals tutorial**](https://redux.js.org/tutorials/fundamentals/part-1-overview) teaches \"how Redux works, from the bottom up\", by showing how to write Redux code by hand and why standard usage patterns exist. It then shows how Redux Toolkit simplifies those Redux usage patterns.\n\nSince Redux Toolkit is an abstraction layer that wraps around the Redux core, it's helpful to know what RTK's APIs are actually doing for you under the hood. **If you want to understand how Redux really works and why RTK is the recommended approach, read the Redux Fundamentals tutorial.**\n\n## Learn Modern Redux Livestream\n\nRedux maintainer Mark Erikson appeared on the \"Learn with Jason\" show to explain how we recommend using Redux today. The show includes a live-coded example app that shows how to use Redux Toolkit and React-Redux hooks with TypeScript, as well as the new RTK Query data fetching APIs.\n\nSee [the \"Learn Modern Redux\" show notes page](https://www.learnwithjason.dev/let-s-learn-modern-redux) for a transcript and links to the example app source.\n\n<LiteYouTubeEmbed \n    id=\"9zySeP5vH9c\"\n    title=\"Learn Modern Redux - Redux Toolkit, React-Redux Hooks, and RTK Query\"\n/>\n\n## Using Redux Toolkit\n\nThe RTK [**Usage Guide** docs page](../usage/usage-guide.md) explains the standard usage patterns for each of RTK's APIs. The [API Reference](../api/configureStore.mdx) section describes each API function and has additional usage examples.\n\nThe [Redux Essentials tutorial](https://redux.js.org/tutorials/essentials/part-1-overview-concepts) also shows how to use each of the APIs while building an application.\n\n## RTK Query Video Course\n\nIf you prefer a video course, you can [watch this RTK Query video course by Lenz Weber-Tronic, the creator of RTK Query, for free at Egghead](https://egghead.io/courses/rtk-query-basics-query-endpoints-data-flow-and-typescript-57ea3c43?af=7pnhj6) or take a look at the first lesson right here:\n\n<div style={{position:\"relative\",paddingTop:\"56.25%\"}}>\n  <iframe \n    src=\"https://app.egghead.io/lessons/redux-course-introduction-and-application-walk-through-for-rtk-query-basics/embed?af=7pnhj6\" \n    title=\"RTK Query Video course at Egghead: Course Introduction and Application Walk through for RTK Query Basics\"\n    frameborder=\"0\" \n    allowfullscreen\n    style={{position:\"absolute\",top:0,left:0,width:\"100%\",height:\"100%\"}}\n  ></iframe>\n</div>\n\n## Migrating Vanilla Redux to Redux Toolkit\n\nIf you already know Redux and just want to know how to migrate an existing application to use Redux Toolkit, the [**\"Modern Redux with Redux Toolkit\" page in the Redux Fundamentals tutorial**](https://redux.js.org/tutorials/fundamentals/part-8-modern-redux) shows how RTK's APIs simplify Redux usage patterns and how to handle that migration.\n\n## Using Redux Toolkit with TypeScript\n\nThe RTK docs page on [**Usage with TypeScript**](../usage/usage-with-typescript.md) shows the basic pattern for setting up Redux Toolkit with TypeScript and React, and documents specific TS patterns for each of the RTK APIs.\n\nIn addition, the [Redux + TS template for Create-React-App](https://github.com/reduxjs/cra-template-redux-typescript) comes with RTK already configured to use those TS patterns, and serves as a good example of how this should work.\n\n## Legacy Redux Toolkit Tutorials\n\nWe previously had a set of \"Basic/Intermediate/Advanced\" tutorials directly in the Redux Toolkit docs. They were helpful, but we've removed them in favor of pointing to the \"Essentials\" and \"Fundamentals\" tutorials in the Redux core docs.\n\nIf you'd like to browse the old tutorials, you can see the content files in our repo's history:\n\n[Redux Toolkit repo: legacy \"Basic/Intermediate/Advanced\" tutorial files](https://github.com/reduxjs/redux-toolkit/tree/e85eb17b39/docs/tutorials)\n"
  },
  {
    "path": "docs/tutorials/quick-start.mdx",
    "content": "---\nid: quick-start\ntitle: Quick Start\nsidebar_label: Quick Start\nhide_title: true\n---\n\n&nbsp;\n\n# Redux Toolkit Quick Start\n\n:::tip What You'll Learn\n\n- How to set up and use Redux Toolkit with React-Redux\n\n:::\n\n:::info Prerequisites\n\n- Familiarity with [ES6 syntax and features](https://www.taniarascia.com/es6-syntax-and-feature-overview/)\n- Knowledge of React terminology: [JSX](https://reactjs.org/docs/introducing-jsx.html), [State](https://reactjs.org/docs/state-and-lifecycle.html), [Function Components, Props](https://reactjs.org/docs/components-and-props.html), and [Hooks](https://reactjs.org/docs/hooks-intro.html)\n- Understanding of [Redux terms and concepts](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow)\n\n:::\n\n## Introduction\n\nWelcome to the Redux Toolkit Quick Start tutorial! **This tutorial will briefly introduce you to Redux Toolkit and teach you how to start using it correctly**.\n\n### How to Read This Tutorial\n\nThis page will focus on just how to set up a Redux application with Redux Toolkit and the main APIs you'll use. For explanations of what Redux is, how it works, and full examples of how to use Redux Toolkit, [see the tutorials linked in the \"Tutorials Overview\" page](./overview.md).\n\nFor this tutorial, we assume that you're using Redux Toolkit with React, but you can also use it with other UI layers as well. The examples are based on [a typical Create-React-App folder structure](https://create-react-app.dev/docs/folder-structure) where all the application code is in a `src`, but the patterns can be adapted to whatever project or folder setup you're using.\n\nThe [Redux+JS template for Create-React-App](https://github.com/reduxjs/redux-templates/tree/master/packages/cra-template-redux) comes with this same project setup already configured.\n\n## Usage Summary\n\n### Install Redux Toolkit and React-Redux\n\nAdd the Redux Toolkit and React-Redux packages to your project:\n\n```sh\nnpm install @reduxjs/toolkit react-redux\n```\n\n### Create a Redux Store\n\nCreate a file named `src/app/store.js`. Import the `configureStore` API from Redux Toolkit. We'll start by creating an empty Redux store, and exporting it:\n\n```ts title=\"app/store.ts\"\nimport { configureStore } from '@reduxjs/toolkit'\n\nexport const store = configureStore({\n  reducer: {},\n})\n\n// Infer the `RootState` and `AppDispatch` types from the store itself\nexport type RootState = ReturnType<typeof store.getState>\n// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}\nexport type AppDispatch = typeof store.dispatch\n```\n\nThis creates a Redux store, and also automatically configure the Redux DevTools extension so that you can inspect the store while developing.\n\n### Provide the Redux Store to React\n\nOnce the store is created, we can make it available to our React components by putting a React-Redux `<Provider>` around our application in `src/index.js`. Import the Redux store we just created, put a `<Provider>` around your `<App>`, and pass the store as a prop:\n\n```ts title=\"index.ts\"\n// file: App.tsx noEmit\nimport React from 'react'\nexport default function App() {\n  return <div>...</div>\n}\n\n// file: app/store.ts noEmit\nimport { configureStore } from '@reduxjs/toolkit'\n\nexport const store = configureStore({\n  reducer: {},\n})\n\n// file: index.tsx\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport './index.css'\nimport App from './App'\n// highlight-start\nimport { store } from './app/store'\nimport { Provider } from 'react-redux'\n// highlight-end\n\nconst container = document.getElementById('root')\n\nif (container) {\n  const root = createRoot(container)\n\n  root.render(\n    // highlight-next-line\n    <Provider store={store}>\n      <App />\n    </Provider>,\n  )\n} else {\n  throw new Error(\n    \"Root element with ID 'root' was not found in the document. Ensure there is a corresponding HTML element with the ID 'root' in your HTML file.\",\n  )\n}\n```\n\n### Create a Redux State Slice\n\nAdd a new file named `src/features/counter/counterSlice.js`. In that file, import the `createSlice` API from Redux Toolkit.\n\nCreating a slice requires a string name to identify the slice, an initial state value, and one or more reducer functions to define how the state can be updated. Once a slice is created, we can export the generated Redux action creators and the reducer function for the whole slice.\n\nRedux requires that [we write all state updates immutably, by making copies of data and updating the copies](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow#immutability). However, Redux Toolkit's `createSlice` and `createReducer` APIs use [Immer](https://immerjs.github.io/immer/) inside to allow us to [write \"mutating\" update logic that becomes correct immutable updates](https://redux.js.org/tutorials/fundamentals/part-8-modern-redux#immutable-updates-with-immer).\n\n```ts title=\"features/counter/counterSlice.ts\"\nimport { createSlice } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\n\nexport interface CounterState {\n  value: number\n}\n\nconst initialState: CounterState = {\n  value: 0,\n}\n\nexport const counterSlice = createSlice({\n  name: 'counter',\n  initialState,\n  reducers: {\n    increment: (state) => {\n      // Redux Toolkit allows us to write \"mutating\" logic in reducers. It\n      // doesn't actually mutate the state because it uses the Immer library,\n      // which detects changes to a \"draft state\" and produces a brand new\n      // immutable state based off those changes\n      state.value += 1\n    },\n    decrement: (state) => {\n      state.value -= 1\n    },\n    incrementByAmount: (state, action: PayloadAction<number>) => {\n      state.value += action.payload\n    },\n  },\n})\n\n// Action creators are generated for each case reducer function\nexport const { increment, decrement, incrementByAmount } = counterSlice.actions\n\nexport default counterSlice.reducer\n```\n\n### Add Slice Reducers to the Store\n\nNext, we need to import the reducer function from the counter slice and add it to our store. By defining a field inside the `reducer` parameter, we tell the store to use this slice reducer function to handle all updates to that state.\n\n```ts title=\"app/store.ts\"\n// file: features/counter/counterSlice.ts noEmit\nimport { createSlice } from '@reduxjs/toolkit'\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: {},\n  reducers: {},\n})\n\nexport default counterSlice.reducer\n\n// file: app/store.ts\nimport { configureStore } from '@reduxjs/toolkit'\n// highlight-next-line\nimport counterReducer from '../features/counter/counterSlice'\n\nexport const store = configureStore({\n  reducer: {\n    // highlight-next-line\n    counter: counterReducer,\n  },\n})\n\n// Infer the `RootState` and `AppDispatch` types from the store itself\nexport type RootState = ReturnType<typeof store.getState>\n// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}\nexport type AppDispatch = typeof store.dispatch\n```\n\n### Use Redux State and Actions in React Components\n\nNow we can use the React-Redux hooks to let React components interact with the Redux store. We can read data from the store with `useSelector`, and dispatch actions using `useDispatch`. Create a `src/features/counter/Counter.js` file with a `<Counter>` component inside, then import that component into `App.js` and render it inside of `<App>`.\n\n```ts title=\"features/counter/Counter.ts\"\n// file: features/counter/counterSlice.ts noEmit\nimport { createSlice } from '@reduxjs/toolkit'\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: {\n    value: 0,\n  },\n  reducers: {\n    increment: (state) => {},\n    decrement: (state) => {},\n  },\n})\n\nexport const { increment, decrement } = counterSlice.actions\nexport default counterSlice.reducer\n\n// file: app/store.ts noEmit\nimport { configureStore } from '@reduxjs/toolkit'\nimport counterReducer from '../features/counter/counterSlice'\nexport const store = configureStore({\n  reducer: {\n    counter: counterReducer,\n  },\n})\nexport type RootState = ReturnType<typeof store.getState>\n\n// file: index.tsx noEmit\nimport React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport { Counter } from './features/counter/Counter'\nimport { store } from './app/store'\nimport { Provider } from 'react-redux'\n\nconst container = document.getElementById('root')\n\nif (container) {\n  const root = createRoot(container)\n\n  root.render(\n    // highlight-next-line\n    <Provider store={store}>\n      <Counter />\n    </Provider>,\n  )\n} else {\n  throw new Error(\n    \"Root element with ID 'root' was not found in the document. Ensure there is a corresponding HTML element with the ID 'root' in your HTML file.\",\n  )\n}\n\n// file: features/counter/Counter.tsx\nimport React from 'react'\nimport type { RootState } from '../../app/store'\nimport { useSelector, useDispatch } from 'react-redux'\nimport { decrement, increment } from './counterSlice'\n\nexport function Counter() {\n  const count = useSelector((state: RootState) => state.counter.value)\n  const dispatch = useDispatch()\n\n  return (\n    <div>\n      <div>\n        <button\n          aria-label=\"Increment value\"\n          onClick={() => dispatch(increment())}\n        >\n          Increment\n        </button>\n        <span>{count}</span>\n        <button\n          aria-label=\"Decrement value\"\n          onClick={() => dispatch(decrement())}\n        >\n          Decrement\n        </button>\n      </div>\n    </div>\n  )\n}\n```\n\nNow, any time you click the \"Increment\" and \"Decrement\" buttons:\n\n- The corresponding Redux action will be dispatched to the store\n- The counter slice reducer will see the actions and update its state\n- The `<Counter>` component will see the new state value from the store and re-render itself with the new data\n\n## What You've Learned\n\nThat was a brief overview of how to set up and use Redux Toolkit with React. Recapping the details:\n\n:::tip Summary\n\n- **Create a Redux store with `configureStore`**\n  - `configureStore` accepts a `reducer` function as a named argument\n  - `configureStore` automatically sets up the store with good default settings\n- **Provide the Redux store to the React application components**\n  - Put a React-Redux `<Provider>` component around your `<App />`\n  - Pass the Redux store as `<Provider store={store}>`\n- **Create a Redux \"slice\" reducer with `createSlice`**\n  - Call `createSlice` with a string name, an initial state, and named reducer functions\n  - Reducer functions may \"mutate\" the state using Immer\n  - Export the generated slice reducer and action creators\n- **Use the React-Redux `useSelector/useDispatch` hooks in React components**\n  - Read data from the store with the `useSelector` hook\n  - Get the `dispatch` function with the `useDispatch` hook, and dispatch actions as needed\n\n:::\n\n### Full Counter App Example\n\nThe counter example app shown here is also the\n\nHere's the complete counter application as a running CodeSandbox:\n\n<iframe\n  className=\"codesandbox\"\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-essentials-counter-example/tree/master/?fontsize=14&hidenavigation=1&module=%2Fsrc%2Ffeatures%2Fcounter%2FcounterSlice.js&theme=dark&runonclick=1\"\n  title=\"redux-essentials-example\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\n## What's Next?\n\nWe recommend going through [**the \"Redux Essentials\" and \"Redux Fundamentals\" tutorials in the Redux core docs**](https://redux.js.org/tutorials/index), which will give you a complete understanding of how Redux works, what Redux Toolkit does, and how to use it correctly.\n"
  },
  {
    "path": "docs/tutorials/rtk-query.mdx",
    "content": "---\nid: rtk-query\ntitle: RTK Query\nsidebar_label: RTK Query Quick Start\nhide_title: true\n---\n\n&nbsp;\n\n# RTK Query Quick Start\n\n:::tip What You'll Learn\n\n- How to set up and use Redux Toolkit's \"RTK Query\" data fetching functionality\n\n:::\n\n:::info Prerequisites\n\n- Understanding of [Redux terms and concepts](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow)\n\n:::\n\n## Introduction\n\nWelcome to the Redux Toolkit Query tutorial! **This tutorial will briefly introduce you to Redux Toolkit's \"RTK Query\" data fetching capability and teach you how to start using it correctly**.\n\n:::info\n\nFor a more in-depth tutorial on RTK Query, see the full [\"Redux Essentials\" tutorial](https://redux.js.org/tutorials/essentials/part-7-rtk-query-basics) on the Redux core docs site.\n\n:::\n\nRTK Query is an advanced data fetching and caching tool, designed to simplify common cases for loading data in a web application. RTK Query itself is built on top of the Redux Toolkit core, and leverages RTK's APIs like [`createSlice`](../api/createSlice.mdx) and [`createAsyncThunk`](../api/createAsyncThunk.mdx) to implement its capabilities.\n\nRTK Query is included in the `@reduxjs/toolkit` package as an additional addon. You are not required to use the RTK Query APIs when you use Redux Toolkit, but we think many users will benefit from RTK Query's data fetching and caching in their apps.\n\n### How to Read This Tutorial\n\nFor this tutorial, we assume that you're using Redux Toolkit with React, but you can also use it with other UI layers as well. The examples are based on [a typical Create-React-App folder structure](https://create-react-app.dev/docs/folder-structure) where all the application code is in a `src`, but the patterns can be adapted to whatever project or folder setup you're using.\n\n## Setting up your store and API service\n\nTo see how RTK Query works, let's walk through a basic usage example. For this example, we'll assume you're using React and want to make use of RTK Query's auto-generated React hooks.\n\n### Create an API service\n\nFirst, we'll create a service definition that queries the publicly available [PokeAPI](https://pokeapi.co/).\n\n```ts title=\"src/services/pokemon.ts\"\n// file: services/types.ts noEmit\nexport type Pokemon = {}\n\n// file: services/pokemon.ts\n// Need to use the React-specific entry point to import createApi\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { Pokemon } from './types'\n\n// highlight-start\n// Define a service using a base URL and expected endpoints\nexport const pokemonApi = createApi({\n  reducerPath: 'pokemonApi',\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (builder) => ({\n    getPokemonByName: builder.query<Pokemon, string>({\n      query: (name) => `pokemon/${name}`,\n    }),\n  }),\n})\n//highlight-end\n\n// highlight-start\n// Export hooks for usage in functional components, which are\n// auto-generated based on the defined endpoints\nexport const { useGetPokemonByNameQuery } = pokemonApi\n// highlight-end\n```\n\nWith RTK Query, you usually define your entire API definition in one place. This is most likely different from what you see with other libraries such as `swr` or `react-query`, and there are several reasons for that. Our perspective is that it's _much_ easier to keep track of how requests, cache invalidation, and general app configuration behave when they're all in one central location in comparison to having X number of custom hooks in different files throughout your application.\n\n:::tip\n\nTypically, you should only have one API slice per base URL that your application needs to communicate with. For example, if your site fetches data from both `/api/posts` and `/api/users`, you would have a single API slice with `/api/` as the base URL, and separate endpoint definitions for `posts` and `users`. This allows you to effectively take advantage of [automated re-fetching](../rtk-query/usage/automated-refetching.mdx) by defining [tag](../rtk-query/usage/automated-refetching.mdx#tags) relationships across endpoints.\n\nFor maintainability purposes, you may wish to split up endpoint definitions across multiple files, while still maintaining a single API slice which includes all of these endpoints. See [code splitting](../rtk-query/usage/code-splitting.mdx) for how you can use the `injectEndpoints` property to inject API endpoints from other files into a single API slice definition.\n\n:::\n\n### Add the service to your store\n\nAn RTKQ service generates a \"slice reducer\" that should be included in the Redux root reducer, and a custom middleware that handles the data fetching. Both need to be added to the Redux store.\n\n```ts title=\"src/store.ts\"\n// file: services/pokemon.ts noEmit\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const pokemonApi = createApi({\n  reducerPath: 'pokemonApi',\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (builder) => ({\n    getPokemonByName: builder.query({\n      query: (name: string) => `pokemon/${name}`,\n    }),\n  }),\n})\n\n// file: store.ts\nimport { configureStore } from '@reduxjs/toolkit'\n// Or from '@reduxjs/toolkit/query/react'\nimport { setupListeners } from '@reduxjs/toolkit/query'\nimport { pokemonApi } from './services/pokemon'\n\nexport const store = configureStore({\n  reducer: {\n    // highlight-start\n    // Add the generated reducer as a specific top-level slice\n    [pokemonApi.reducerPath]: pokemonApi.reducer,\n    // highlight-end\n  },\n  // highlight-start\n  // Adding the api middleware enables caching, invalidation, polling,\n  // and other useful features of `rtk-query`.\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(pokemonApi.middleware),\n  // highlight-end\n})\n\n// optional, but required for refetchOnFocus/refetchOnReconnect behaviors\n// see `setupListeners` docs - takes an optional callback as the 2nd arg for customization\nsetupListeners(store.dispatch)\n```\n\n### Wrap your application with the `Provider`\n\nIf you haven't already done so, follow the standard pattern for providing the Redux store to the rest of your React application component tree:\n\n```ts title=\"src/index.tsx\"\n// file: App.tsx noEmit\nimport React from 'react'\nexport default function App() {\n  return <div>...</div>\n}\n\n// file: store.ts noEmit\nimport { configureStore } from '@reduxjs/toolkit'\n\nexport const store = configureStore({\n  reducer: {},\n})\n\n// file: index.tsx\nimport * as React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport { Provider } from 'react-redux'\n\nimport App from './App'\nimport { store } from './store'\n\nconst container = document.getElementById('root')\n\nif (container) {\n  const root = createRoot(container)\n\n  root.render(\n    <Provider store={store}>\n      <App />\n    </Provider>,\n  )\n} else {\n  throw new Error(\n    \"Root element with ID 'root' was not found in the document. Ensure there is a corresponding HTML element with the ID 'root' in your HTML file.\",\n  )\n}\n```\n\n## Use the query in a component\n\nOnce a service has been defined, you can import the hooks to make a request.\n\n```ts title=\"src/App.tsx\"\n// file: services/pokemon.ts noEmit\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const pokemonApi = createApi({\n  reducerPath: 'pokemonApi',\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (builder) => ({\n    getPokemonByName: builder.query({\n      query: (name: string) => `pokemon/${name}`,\n    }),\n  }),\n})\n\nexport const { useGetPokemonByNameQuery } = pokemonApi\n\n// file: App.tsx\nimport * as React from 'react'\n// highlight-next-line\nimport { useGetPokemonByNameQuery } from './services/pokemon'\n\nexport default function App() {\n  // highlight-start\n  // Using a query hook automatically fetches data and returns query values\n  const { data, error, isLoading } = useGetPokemonByNameQuery('bulbasaur')\n  // Individual hooks are also accessible under the generated endpoints:\n  // const { data, error, isLoading } = pokemonApi.endpoints.getPokemonByName.useQuery('bulbasaur')\n  // highlight-end\n\n  return (\n    <div className=\"App\">\n      {error ? (\n        <>Oh no, there was an error</>\n      ) : isLoading ? (\n        <>Loading...</>\n      ) : data ? (\n        <>\n          <h3>{data.species.name}</h3>\n          <img src={data.sprites.front_shiny} alt={data.species.name} />\n        </>\n      ) : null}\n    </div>\n  )\n}\n```\n\nWhen making a request, you're able to track the state in several ways. You can always check `data`, `status`, and `error` to determine the right UI to render. In addition, `useQuery` also provides utility booleans like `isLoading`, `isFetching`, `isSuccess`, and `isError` for the latest request.\n\n#### Basic Example\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/basic?fontsize=12&runonclick=1&hidenavigation=1&theme=dark\"\n  style={{\n    width: '100%',\n    height: '500px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"rtk-query-getting-started-basic\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n\nOkay, that's interesting... but what if you wanted to show multiple pokemon at the same time? What happens if multiple components load the same pokemon?\n\n#### Advanced example\n\nRTK Query ensures that any component that subscribes to the same query will always use the same data. RTK Query automatically de-dupes requests so you don't have to worry about checking in-flight requests and performance optimizations on your end. Let's evaluate the sandbox below - make sure to check the Network panel in your browser's dev tools. You will see 3 requests, even though there are 4 subscribed components - `bulbasaur` only makes one request, and the loading state is synchronized between the two components. For fun, try changing the value of the dropdown from `Off` to `1s` to see this behavior continue when a query is re-ran.\n\n<iframe\n  src=\"https://codesandbox.io/embed/github/reduxjs/redux-toolkit/tree/master/examples/query/react/advanced?file=/src/App.tsx?fontsize=12&runonclick=1&hidenavigation=1&theme=dark\"\n  style={{\n    width: '100%',\n    height: '600px',\n    border: 0,\n    borderRadius: '4px',\n    overflow: 'hidden',\n  }}\n  title=\"rtk-query-getting-started-advanced\"\n  allow=\"geolocation; microphone; camera; midi; vr; accelerometer; gyroscope; payment; ambient-light-sensor; encrypted-media; usb\"\n  sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"\n></iframe>\n"
  },
  {
    "path": "docs/tutorials/typescript.md",
    "content": "---\nid: typescript\ntitle: TypeScript Quick Start\nsidebar_label: TypeScript Quick Start\nhide_title: true\n---\n\n&nbsp;\n\n# Redux Toolkit TypeScript Quick Start\n\n:::tip What You'll Learn\n\n- How to set up and use Redux Toolkit and React-Redux with TypeScript\n\n:::\n\n:::info Prerequisites\n\n- Knowledge of React [Hooks](https://reactjs.org/docs/hooks-intro.html)\n- Understanding of [Redux terms and concepts](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow)\n- Understanding of TypeScript syntax and concepts\n\n:::\n\n## Introduction\n\nWelcome to the Redux Toolkit TypeScript Quick Start tutorial! **This tutorial will briefly show how to use TypeScript with Redux Toolkit**.\n\nThis page focuses on just how to set up the TypeScript aspects. For explanations of what Redux is, how it works, and full examples of how to use Redux Toolkit, [see the tutorials linked in the \"Tutorials Overview\" page](./overview.md).\n\nRedux Toolkit is already written in TypeScript, so its TS type definitions are built in.\n\n[React Redux](https://react-redux.js.org) has its type definitions in a separate [`@types/react-redux` typedefs package](https://npm.im/@types/react-redux) on NPM. In addition to typing the library functions, the types also export some helpers to make it easier to write typesafe interfaces between your Redux store and your React components.\n\nAs of React Redux v7.2.3, the `react-redux` package has a dependency on `@types/react-redux`, so the type definitions will be automatically installed with the library. Otherwise, you'll need to manually install them yourself (typically `npm install @types/react-redux` ).\n\nThe [Redux+TS template for Create-React-App](https://github.com/reduxjs/cra-template-redux-typescript) comes with a working example of these patterns already configured.\n\n## Project Setup\n\n### Define Root State and Dispatch Types\n\nUsing [configureStore](../api/configureStore.mdx) should not need any additional typings. You will, however, want to extract the `RootState` type and the `Dispatch` type so that they can be referenced as needed. Inferring these types from the store itself means that they correctly update as you add more state slices or modify middleware settings.\n\nSince those are types, it's safe to export them directly from your store setup file such as `app/store.ts` and import them directly into other files.\n\n```ts title=\"app/store.ts\"\nimport { configureStore } from '@reduxjs/toolkit'\n// ...\n\nexport const store = configureStore({\n  reducer: {\n    posts: postsReducer,\n    comments: commentsReducer,\n    users: usersReducer,\n  },\n})\n\n// highlight-start\n// Infer the `RootState` and `AppDispatch` types from the store itself\nexport type RootState = ReturnType<typeof store.getState>\n// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}\nexport type AppDispatch = typeof store.dispatch\n// highlight-end\n```\n\n### Define Typed Hooks\n\nWhile it's possible to import the `RootState` and `AppDispatch` types into each component, it's **better to create typed versions of the `useDispatch` and `useSelector` hooks for usage in your application**. This is important for a couple reasons:\n\n- For `useSelector`, it saves you the need to type `(state: RootState)` every time\n- For `useDispatch`, the default `Dispatch` type does not know about thunks. In order to correctly dispatch thunks, you need to use the specific customized `AppDispatch` type from the store that includes the thunk middleware types, and use that with `useDispatch`. Adding a pre-typed `useDispatch` hook keeps you from forgetting to import `AppDispatch` where it's needed.\n\nSince these are actual variables, not types, it's important to define them in a separate file such as `app/hooks.ts`, not the store setup file. This allows you to import them into any component file that needs to use the hooks, and avoids potential circular import dependency issues.\n\n```ts title=\"app/hooks.ts\"\nimport { useDispatch, useSelector } from 'react-redux'\nimport type { RootState, AppDispatch } from './store'\n\n// highlight-start\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = useDispatch.withTypes<AppDispatch>()\nexport const useAppSelector = useSelector.withTypes<RootState>()\n// highlight-end\n```\n\n## Application Usage\n\n### Define Slice State and Action Types\n\nEach slice file should define a type for its initial state value, so that `createSlice` can correctly infer the type of `state` in each case reducer.\n\nAll generated actions should be defined using the `PayloadAction<T>` type from Redux Toolkit, which takes the type of the `action.payload` field as its generic argument.\n\nYou can safely import the `RootState` type from the store file here. It's a circular import, but the TypeScript compiler can correctly handle that for types. This may be needed for use cases like writing selector functions.\n\n```ts title=\"features/counter/counterSlice.ts\"\nimport { createSlice } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\nimport type { RootState } from '../../app/store'\n\n// highlight-start\n// Define a type for the slice state\ninterface CounterState {\n  value: number\n}\n\n// Define the initial state using that type\nconst initialState: CounterState = {\n  value: 0,\n}\n// highlight-end\n\nexport const counterSlice = createSlice({\n  name: 'counter',\n  // `createSlice` will infer the state type from the `initialState` argument\n  initialState,\n  reducers: {\n    increment: (state) => {\n      state.value += 1\n    },\n    decrement: (state) => {\n      state.value -= 1\n    },\n    // highlight-start\n    // Use the PayloadAction type to declare the contents of `action.payload`\n    incrementByAmount: (state, action: PayloadAction<number>) => {\n      // highlight-end\n      state.value += action.payload\n    },\n  },\n})\n\nexport const { increment, decrement, incrementByAmount } = counterSlice.actions\n\n// Other code such as selectors can use the imported `RootState` type\nexport const selectCount = (state: RootState) => state.counter.value\n\nexport default counterSlice.reducer\n```\n\nThe generated action creators will be correctly typed to accept a `payload` argument based on the `PayloadAction<T>` type you provided for the reducer. For example, `incrementByAmount` requires a `number` as its argument.\n\nIn some cases, [TypeScript may unnecessarily tighten the type of the initial state](https://github.com/reduxjs/redux-toolkit/pull/827). If that happens, you can work around it by casting the initial state using `as`, instead of declaring the type of the variable:\n\n```ts\n// Workaround: cast state instead of declaring variable type\nconst initialState = {\n  value: 0,\n} satisfies CounterState as CounterState\n```\n\n### Use Typed Hooks in Components\n\nIn component files, import the pre-typed hooks instead of the standard hooks from React-Redux.\n\n```tsx no-transpile title=\"features/counter/Counter.tsx\"\nimport React, { useState } from 'react'\n\n// highlight-next-line\nimport { useAppSelector, useAppDispatch } from 'app/hooks'\n\nimport { decrement, increment } from './counterSlice'\n\nexport function Counter() {\n  // highlight-start\n  // The `state` arg is correctly typed as `RootState` already\n  const count = useAppSelector((state) => state.counter.value)\n  const dispatch = useAppDispatch()\n  // highlight-end\n\n  // omit rendering logic\n}\n```\n\n## What's Next?\n\nSee [the \"Usage with TypeScript\" page](../usage/usage-with-typescript.md) for extended details on how to use Redux Toolkit's APIs with TypeScript.\n"
  },
  {
    "path": "docs/usage/immer-reducers.md",
    "content": "---\nid: immer-reducers\ntitle: Writing Reducers with Immer\nsidebar_label: Writing Reducers with Immer\nhide_title: true\n---\n\n&nbsp;\n\n# Writing Reducers with Immer\n\nRedux Toolkit's [`createReducer`](../api/createReducer.mdx) and [`createSlice`](../api/createSlice.mdx) automatically use [Immer](https://immerjs.github.io/immer/) internally to let you write simpler immutable update logic using \"mutating\" syntax. This helps simplify most reducer implementations.\n\nBecause Immer is itself an abstraction layer, it's important to understand why Redux Toolkit uses Immer, and how to use it correctly.\n\n## Immutability and Redux\n\n### Basics of Immutability\n\n\"Mutable\" means \"changeable\". If something is \"immutable\", it can never be changed.\n\nJavaScript objects and arrays are all mutable by default. If I create an object, I can change the contents of its fields. If I create an array, I can change the contents as well:\n\n```js\nconst obj = { a: 1, b: 2 }\n// still the same object outside, but the contents have changed\nobj.b = 3\n\nconst arr = ['a', 'b']\n// In the same way, we can change the contents of this array\narr.push('c')\narr[1] = 'd'\n```\n\nThis is called _mutating_ the object or array. It's the same object or array reference in memory, but now the contents inside the object have changed.\n\n**In order to update values immutably, your code must make _copies_ of existing objects/arrays, and then modify the copies**.\n\nWe can do this by hand using JavaScript's array / object spread operators, as well as array methods that return new copies of the array instead of mutating the original array:\n\n```js\nconst obj = {\n  a: {\n    // To safely update obj.a.c, we have to copy each piece\n    c: 3,\n  },\n  b: 2,\n}\n\nconst obj2 = {\n  // copy obj\n  ...obj,\n  // overwrite a\n  a: {\n    // copy obj.a\n    ...obj.a,\n    // overwrite c\n    c: 42,\n  },\n}\n\nconst arr = ['a', 'b']\n// Create a new copy of arr, with \"c\" appended to the end\nconst arr2 = arr.concat('c')\n\n// or, we can make a copy of the original array:\nconst arr3 = arr.slice()\n// and mutate the copy:\narr3.push('c')\n```\n\n:::info Want to Know More?\n\nFor more info on how immutability works in JavaScript, see:\n\n- [A Visual Guide to References in JavaScript](https://daveceddia.com/javascript-references/)\n- [Immutability in React and Redux: The Complete Guide](https://daveceddia.com/react-redux-immutability-guide/)\n\n:::\n\n### Reducers and Immutable Updates\n\nOne of the primary rules of Redux is that **our reducers are _never_ allowed to mutate the original / current state values!**\n\n:::warning\n\n```js\n// ❌ Illegal - by default, this will mutate the state!\nstate.value = 123\n```\n\n:::\n\nThere are several reasons why you must not mutate state in Redux:\n\n- It causes bugs, such as the UI not updating properly to show the latest values\n- It makes it harder to understand why and how the state has been updated\n- It makes it harder to write tests\n- It breaks the ability to use \"time-travel debugging\" correctly\n- It goes against the intended spirit and usage patterns for Redux\n\nSo if we can't change the originals, how do we return an updated state?\n\n:::tip\n\n**Reducers can only make _copies_ of the original values, and then they can mutate the copies.**\n\n```js\n// ✅ This is safe, because we made a copy\nreturn {\n  ...state,\n  value: 123,\n}\n```\n\n:::\n\nWe already saw that we can write immutable updates by hand, by using JavaScript's array / object spread operators and other functions that return copies of the original values.\n\nThis becomes harder when the data is nested. **A critical rule of immutable updates is that you must make a copy of _every_ level of nesting that needs to be updated.**\n\nA typical example of this might look like:\n\n```js\nfunction handwrittenReducer(state, action) {\n  return {\n    ...state,\n    first: {\n      ...state.first,\n      second: {\n        ...state.first.second,\n        [action.someId]: {\n          ...state.first.second[action.someId],\n          fourth: action.someValue,\n        },\n      },\n    },\n  }\n}\n```\n\nHowever, if you're thinking that \"writing immutable updates by hand this way looks hard to remember and do correctly\"... yeah, you're right! :)\n\nWriting immutable update logic by hand _is_ hard, and **accidentally mutating state in reducers is the single most common mistake Redux users make**.\n\n## Immutable Updates with Immer\n\n[Immer](https://immerjs.github.io/immer/) is a library that simplifies the process of writing immutable update logic.\n\nImmer provides a function called `produce`, which accepts two arguments: your original `state`, and a callback function. The callback function is given a \"draft\" version of that state, and inside the callback, it is safe to write code that mutates the draft value. Immer tracks all attempts to mutate the draft value and then replays those mutations using their immutable equivalents to create a safe, immutably updated result:\n\n```js\nimport { produce } from 'immer'\n\nconst baseState = [\n  {\n    todo: 'Learn typescript',\n    done: true,\n  },\n  {\n    todo: 'Try immer',\n    done: false,\n  },\n]\n\nconst nextState = produce(baseState, (draftState) => {\n  // \"mutate\" the draft array\n  draftState.push({ todo: 'Tweet about it' })\n  // \"mutate\" the nested state\n  draftState[1].done = true\n})\n\nconsole.log(baseState === nextState)\n// false - the array was copied\nconsole.log(baseState[0] === nextState[0])\n// true - the first item was unchanged, so same reference\nconsole.log(baseState[1] === nextState[1])\n// false - the second item was copied and updated\n```\n\n### Redux Toolkit and Immer\n\nRedux Toolkit's [`createReducer` API](../api/createReducer.mdx) uses Immer internally automatically. So, it's already safe to \"mutate\" state inside of any case reducer function that is passed to `createReducer`:\n\n```js\nconst todosReducer = createReducer([], (builder) => {\n  builder.addCase('todos/todoAdded', (state, action) => {\n    // \"mutate\" the array by calling push()\n    state.push(action.payload)\n  })\n})\n```\n\nIn turn, `createSlice` uses `createReducer` inside, so it's also safe to \"mutate\" state there as well:\n\n```js\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [],\n  reducers: {\n    todoAdded(state, action) {\n      state.push(action.payload)\n    },\n  },\n})\n```\n\nThis even applies if the case reducer functions are defined outside of the `createSlice/createReducer` call. For example, you could have a reusable case reducer function that expects to \"mutate\" its state, and include it as needed:\n\n```js\nconst addItemToArray = (state, action) => {\n  state.push(action.payload)\n}\n\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [],\n  reducers: {\n    todoAdded: addItemToArray,\n  },\n})\n```\n\nThis works because the \"mutating\" logic is wrapped in Immer's `produce` method internally when it executes.\n\n:::caution\n\nRemember, **the \"mutating\" logic _only_ works correctly when wrapped inside of Immer!** Otherwise, that code _will_ really mutate the data.\n\n:::\n\n## Immer Usage Patterns\n\nThere are several useful patterns to know about and gotchas to watch out for when using Immer in Redux Toolkit.\n\n### Mutating and Returning State\n\nImmer works by tracking attempts to mutate an existing drafted state value, either by assigning to nested fields or by calling functions that mutate the value. That means that **the `state` must be a JS object or array in order for Immer to see the attempted changes**. (You can still have a slice's state be a primitive like a string or a boolean, but since primitives can never be mutated anyway, all you can do is just return a new value.)\n\nIn any given case reducer, **Immer expects that you will either _mutate_ the existing state, _or_ construct a new state value yourself and return it, but _not_ both in the same function!** For example, both of these are valid reducers with Immer:\n\n```js\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [],\n  reducers: {\n    todoAdded(state, action) {\n      // \"Mutate\" the existing state, no return value needed\n      state.push(action.payload)\n    },\n    todoDeleted(state, action.payload) {\n      // Construct a new result array immutably and return it\n      return state.filter(todo => todo.id !== action.payload)\n    }\n  }\n})\n```\n\nHowever, it _is_ possible to use immutable updates to do part of the work and then save the results via a \"mutation\". An example of this might be filtering a nested array:\n\n```js\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: {todos: [], status: 'idle'}\n  reducers: {\n    todoDeleted(state, action.payload) {\n      // Construct a new array immutably\n      const newTodos = state.todos.filter(todo => todo.id !== action.payload)\n      // \"Mutate\" the existing state to save the new array\n      state.todos = newTodos\n    }\n  }\n})\n```\n\nNote that **mutating state in an arrow function with an implicit return breaks this rule and causes an error!** This is because statements and function calls may return a value, and Immer sees both the attempted mutation and _and_ the new returned value and doesn't know which to use as the result. Some potential solutions are using the `void` keyword to skip having a return value, or using curly braces to give the arrow function a body and no return value:\n\n```js\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [],\n  reducers: {\n    // ❌ ERROR: mutates state, but also returns new array size!\n    brokenReducer: (state, action) => state.push(action.payload),\n    // ✅ SAFE: the `void` keyword prevents a return value\n    fixedReducer1: (state, action) => void state.push(action.payload),\n    // ✅ SAFE: curly braces make this a function body and no return\n    fixedReducer2: (state, action) => {\n      state.push(action.payload)\n    },\n  },\n})\n```\n\nWhile writing nested immutable update logic is hard, there are times when it _is_ simpler to do an object spread operation to update multiple fields at once, vs assigning individual fields:\n\n```js\nfunction objectCaseReducer1(state, action) {\n  const { a, b, c, d } = action.payload\n  return {\n    ...state,\n    a,\n    b,\n    c,\n    d,\n  }\n}\n\nfunction objectCaseReducer2(state, action) {\n  const { a, b, c, d } = action.payload\n  // This works, but we keep having to repeat `state.x =`\n  state.a = a\n  state.b = b\n  state.c = c\n  state.d = d\n}\n```\n\nAs an alternative, you can use `Object.assign` to mutate multiple fields at once, since `Object.assign` always mutates the first object that it's given:\n\n```js\nfunction objectCaseReducer3(state, action) {\n  const { a, b, c, d } = action.payload\n  Object.assign(state, { a, b, c, d })\n}\n```\n\n### Resetting and Replacing State\n\nSometimes you may want to replace the entire existing `state`, either because you've loaded some new data, or you want to reset the state back to its initial value.\n\n:::warning\n\n**A common mistake is to try assigning `state = someValue` directly. This will not work!** This only points the local `state` variable to a different reference. That is neither mutating the existing `state` object/array in memory, nor returning an entirely new value, so Immer does not make any actual changes.\n\n:::\n\nInstead, to replace the existing state, you should return the new value directly:\n\n```js\nconst initialState = []\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState,\n  reducers: {\n    brokenTodosLoadedReducer(state, action) {\n      // ❌ ERROR: does not actually mutate or return anything new!\n      state = action.payload\n    },\n    fixedTodosLoadedReducer(state, action) {\n      // ✅ CORRECT: returns a new value to replace the old one\n      return action.payload\n    },\n    correctResetTodosReducer(state, action) {\n      // ✅ CORRECT: returns a new value to replace the old one\n      return initialState\n    },\n  },\n})\n```\n\n### Debugging and Inspecting Drafted State\n\nIt's common to want to log in-progress state from a reducer to see what it looks like as it's being updated, like `console.log(state)`. Unfortunately, browsers display logged Proxy instances in a format that is hard to read or understand:\n\n![Logged proxy draft](/img/usage/immer-reducers/logged-proxy.png)\n\nTo work around this, [Immer includes a `current` function that extracts a copy of the wrapped data](https://immerjs.github.io/immer/current), and RTK re-exports `current`. You can use this in your reducers if you need to log or inspect the work-in-progress state:\n\n```js\nimport { current } from '@reduxjs/toolkit'\n\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: todosAdapter.getInitialState(),\n  reducers: {\n    todoToggled(state, action) {\n      // ❌ ERROR: logs the Proxy-wrapped data\n      console.log(state)\n      // ✅ CORRECT: logs a plain JS copy of the current data\n      console.log(current(state))\n    },\n  },\n})\n```\n\nThe correct output would look like this instead:\n\n![Logged current value](/img/usage/immer-reducers/logged-current-state.png)\n\nImmer also provides [`original` and `isDraft` functions](https://immerjs.github.io/immer/original), which retrieves the original data without any updates applied and check to see if a given value is a Proxy-wrapped draft. As of RTK 1.5.1, both of those are re-exported from RTK as well.\n\n### Updating Nested Data\n\nImmer greatly simplifies updating nested data. Nested objects and arrays are also wrapped in Proxies and drafted, and it's safe to pull out a nested value into its own variable and then mutate it.\n\nHowever, this still only applies to objects and arrays. If we pull out a primitive value into its own variable and try to update it, Immer has nothing to wrap and cannot track any updates:\n\n```js\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [],\n  reducers: {\n    brokenTodoToggled(state, action) {\n      const todo = state.find((todo) => todo.id === action.payload)\n      if (todo) {\n        // ❌ ERROR: Immer can't track updates to a primitive value!\n        let { completed } = todo\n        completed = !completed\n      }\n    },\n    fixedTodoToggled(state, action) {\n      const todo = state.find((todo) => todo.id === action.payload)\n      if (todo) {\n        // ✅ CORRECT: This object is still wrapped in a Proxy, so we can \"mutate\" it\n        todo.completed = !todo.completed\n      }\n    },\n  },\n})\n```\n\nThere _is_ a gotcha here. [Immer will not wrap objects that are newly inserted into the state](https://immerjs.github.io/immer/pitfalls#data-not-originating-from-the-state-will-never-be-drafted). Most of the time this shouldn't matter, but there may be occasions when you want to insert a value and then make further updates to it.\n\nRelated to this, RTK's [`createEntityAdapter` update functions](../api/createEntityAdapter.mdx#crud-functions) can either be used as standalone reducers, or \"mutating\" update functions. These functions determine whether to \"mutate\" or return a new value by checking to see if the state they're given is wrapped in a draft or not. If you are calling these functions yourself inside of a case reducer, be sure you know whether you're passing them a draft value or a plain value.\n\nFinally, it's worth noting that **Immer does not automatically create nested objects or arrays for you - you have to create them yourself**. As an example, say we have a lookup table containing nested arrays, and we want to insert an item into one of those arrays. If we unconditionally try to insert without checking for the existence of that array, the logic will crash when the array doesn't exist. Instead, you'd need to ensure the array exists first:\n\n```js\nconst itemsSlice = createSlice({\n  name: 'items',\n  initialState: { a: [], b: [] },\n  reducers: {\n    brokenNestedItemAdded(state, action) {\n      const { id, item } = action.payload\n      // ❌ ERROR: will crash if no array exists for `id`!\n      state[id].push(item)\n    },\n    fixedNestedItemAdded(state, action) {\n      const { id, item } = action.payload\n      // ✅ CORRECT: ensures the nested array always exists first\n      if (!state[id]) {\n        state[id] = []\n      }\n\n      state[id].push(item)\n    },\n  },\n})\n```\n\n### Linting State Mutations\n\nMany ESLint configs include the https://eslint.org/docs/rules/no-param-reassign rule, which may also warn about mutations to nested fields. That can cause the rule to warn about mutations to `state` in Immer-powered reducers, which is not helpful.\n\nTo resolve this, you can tell the ESLint rule to ignore mutations and assignment to a parameter named `state` only in slice files:\n\n```js\n// @filename .eslintrc.js\nmodule.exports = {\n  // add to your ESLint config definition\n  overrides: [\n    {\n      // feel free to replace with your preferred file pattern - eg. 'src/**/*Slice.ts'\n      files: ['src/**/*.slice.ts'],\n      // avoid state param assignment\n      rules: { 'no-param-reassign': ['error', { props: false }] },\n    },\n  ],\n}\n```\n\n## Why Immer is Built In\n\nWe've received a number of requests over time to make Immer an optional part of RTK's `createSlice` and `createReducer` APIs, rather than strictly required.\n\nOur answer is always the same: **Immer _is required_ in RTK, and that is not going to change**.\n\nIt's worth going over the reasons why we consider Immer to be a critical part of RTK and why we will not make it optional.\n\n### Benefits of Immer\n\nImmer has two primary benefits. First, **Immer drastically simplifies immutable update logic**. [Proper immutable updates are extremely verbose](https://redux.js.org/usage/structuring-reducers/immutable-update-patterns#updating-nested-objects). Those verbose operations are hard to read overall, and also obfuscate what the actual intent of the update statement is. Immer eliminates all the nested spreads and array slices. Not only is the code shorter and easier to read, it's much more clear what actual update is supposed to happen.\n\nSecond, [writing immutable updates correctly is _hard_](https://redux.js.org/usage/structuring-reducers/immutable-update-patterns), and it is really easy to make mistakes (like forgetting to copy a level of nesting in a set of object spreads, copying a top-level array and not the item to be updated inside the array, or forgetting that `array.sort()` mutates the array). This is part of why [accidental mutations has always been the most common cause of Redux bugs](https://redux.js.org/faq/react-redux#why-isnt-my-component-re-rendering-or-my-mapstatetoprops-running). **Immer effectively _eliminates_ accidental mutations**. Not only are there no more spread operations that can be mis-written, but Immer freezes state automatically as well. This causes errors to be thrown if you do accidentally mutate, even outside of a reducer. **Eliminating the #1 cause of Redux bugs is a _huge_ improvement.**\n\nAdditionally, RTK Query uses Immer's patch capabilities to enable [optimistic updates and manual cache updates](../rtk-query/usage/manual-cache-updates.mdx) as well.\n\n### Tradeoffs and Concerns\n\nLike any tool, using Immer does have tradeoffs, and users have expressed a number of concerns about using it.\n\nImmer does add to the overall app bundle size. It's about 8K min, 3.3K min+gz (ref: [Immer docs: Installation](https://immerjs.github.io/immer/installation), [Bundle.js.org analysis](https://bundle.js.org/?q=immer&treeshake=[{default+as+produce+}])). However, that library bundle size starts to pay for itself by shrinking the amount of reducer logic in your app. Additionally, the benefits of more readable code and eliminating mutation bugs are worth the size.\n\nImmer also adds a bit of overhead in runtime performance. However, [per the Immer \"Performance\" docs page, the overhead is not meaningful in practice](https://immerjs.github.io/immer/performance/). Additionally, [reducers are almost never a perf bottleneck in a Redux app anyway](https://github.com/reduxjs/redux-toolkit/issues/242#issuecomment-583296008). Instead, the cost of updating the UI is much more important.\n\nSo, while using Immer isn't \"free\", the bundle and perf costs are small enough to be worth it.\n\nThe most realistic pain point with using Immer is that browser debuggers show Proxies in a confusing way, which makes it hard to inspect state variables while debugging. This is certainly an annoyance. However, this doesn't actually affect runtime behavior, and we've [documented the use of `current` to create a viewable plain JS version of the data](#debugging-and-inspecting-drafted-state) above in this page. (Given the increasingly wide use of Proxies as part of libraries like Mobx and Vue 3, this is also not unique to Immer.)\n\nAnother issue is education and understanding. Redux has always required immutability in reducers, and so seeing \"mutating\" code can be confusing. It's certainly possible that new Redux users might see those \"mutations\" in example code, assume that it's normal for Redux usage, and later try to do the same thing outside of `createSlice`. This would indeed cause real mutations and bugs, because it's outside of Immer's ability to wrap the updates.\n\nWe've addressed this by [repeatedly emphasizing the important of immutability throughout our docs](https://redux.js.org/tutorials/essentials/part-1-overview-concepts#immutability), including multiple highlighted sections emphasizing that [the \"mutations\" only work right thanks to Immer's \"magic\" inside](https://redux.js.org/tutorials/essentials/part-2-app-structure#reducers-and-immutable-updates) and adding this specific docs page you're reading now.\n\n### Architecture and Intent\n\nThere's two more reasons why Immer is not optional.\n\nOne is RTK's architecture. `createSlice` and `createReducer` are implemented by directly importing Immer. There's no easy way to create a version of either of them that would have a hypothetical `immer: false` option. You can't do optional imports, and we need Immer available immediately and synchronously during the initial load of the app.\n\nAnd finally: **Immer is built into RTK by default because we believe it is the best choice for our users!** We _want_ our users to be using Immer, and consider it to be a critical non-negotiable component of RTK. The great benefits like simpler reducer code and preventing accidental mutations far outweigh the relatively small concerns.\n\n## Further Information\n\nSee [the Immer documentation](https://immerjs.github.io/immer/) for more details on Immer's APIs, edge cases, and behavior.\n\nFor historical discussion on why Immer is required, see these issues:\n\n- [RTK #5: Why Immer inside a starter kit?](https://github.com/reduxjs/redux-toolkit/issues/5)\n- [RTK #183: Consider adding an option to remove Immer](https://github.com/reduxjs/redux-toolkit/issues/183)\n- [RTK #242: make `immer` optional for `createReducer`](https://github.com/reduxjs/redux-toolkit/issues/242)\n"
  },
  {
    "path": "docs/usage/migrating-rtk-2.md",
    "content": "---\nid: migrating-rtk-2\ntitle: Migrating to RTK 2.0 and Redux 5.0\nsidebar_label: Migrating to RTK 2.0 and Redux 5.0\nhide_title: true\ntoc_max_heading_level: 4\n---\n\n&nbsp;\n\n<div className=\"migration-guide\">\n\n# Migrating to RTK 2.0 and Redux 5.0\n\n:::tip What You'll Learn\n\n- What's changed in Redux Toolkit 2.0, Redux core 5.0, Reselect 5.0, and Redux Thunk 3.0, including breaking changes and new features\n\n:::\n\n## Introduction\n\nRedux Toolkit has been available since 2019, and today it's the standard way to write Redux apps. We've gone 4+ years without any breaking changes. Now, RTK 2.0 gives us a chance to modernize the packaging, clean up deprecated options, and tighten up some edge cases.\n\n**Redux Toolkit 2.0 is accompanied by major versions of all the other Redux packages: Redux core 5.0, React-Redux 9.0, Reselect 5.0, and Redux Thunk 3.0**.\n\nThis page lists known potentially breaking changes in each of those packages, as well as new features in Redux Toolkit 2.0. As a reminder, **you should not need to actually install or use the core `redux` package directly** - RTK wraps that, and re-exports all methods and types.\n\nIn practice, **most of the \"breaking\" changes should not have an actual effect on end users, and we expect that many projects can just update the package versions with very few code changes needed**.\n\nThe changes most likely to need app code updates are:\n\n- [Object syntax removed for `createReducer` and `createSlice.extraReducers`](#object-syntax-for-createsliceextrareducers-and-createreducer-removed)\n- [`configureStore.middleware` must be a callback](#configurestoremiddleware-must-be-a-callback)\n- [`Middleware` type changed - Middleware `action` and `next` are typed as `unknown`](#middleware-type-changed---middleware-action-and-next-are-typed-as-unknown)\n\n## Packaging Changes (all)\n\nWe've made updates to the build packaging for all of the Redux-related libraries. These are technically \"breaking\", but _should_ be transparent to end users, and actually enable better support for scenarios such as using Redux via ESM files under Node.\n\n#### Addition of `exports` field in `package.json`\n\nWe've migrated the package definitions to include the `exports` field for defining which artifacts to load, with a modern ESM build as the primary artifact (with CJS still included for compatibility purposes).\n\nWe've done local testing of the package, but we ask the community to try out this in your own projects and report any breakages you find!\n\n#### Build Artifact Modernization\n\nWe've updated the build output in several ways:\n\n- **Build output is no longer transpiled!** Instead we target modern JS syntax (ES2020)\n- Moved all build artifacts to live under `./dist/`, instead of separate top-level folders\n- The lowest TypeScript version we test against is now **TS 4.7**.\n\n#### Dropping UMD builds\n\nRedux has always shipped with UMD build artifacts. These are primarily meant for direct import as script tags, such as in a CodePen or a no-bundler build environment.\n\nFor now, we're dropping those build artifacts from the published package, on the grounds that the use cases seem pretty rare today.\n\nWe do have a browser-ready ESM build artifact included at `dist/$PACKAGE_NAME.browser.mjs`, which can be loaded via a script tag that points to that file on Unpkg.\n\nIf you have strong use cases for us continuing to include UMD build artifacts, please let us know!\n\n## Breaking Changes\n\n### Core\n\n#### Action types _must_ be strings\n\nWe've always specifically told our users that [actions and state _must_ be serializable](https://redux.js.org/style-guide/#do-not-put-non-serializable-values-in-state-or-actions), and that `action.type` _should_ be a string. This is both to ensure that actions are serializable, and to help provide a readable action history in the Redux DevTools.\n\n`store.dispatch(action)` now specifically enforces that **`action.type` _must_ be a string** and will throw an error if not, in the same way it throws an error if the action is not a plain object.\n\nIn practice, this was already true 99.99% of the time and shouldn't have any effect on users (especially those using Redux Toolkit and `createSlice`), but there may be some legacy Redux codebases that opted to use Symbols as action types.\n\n#### `createStore` Deprecation\n\nIn [Redux 4.2.0, we marked the original `createStore` method as `@deprecated`](https://github.com/reduxjs/redux/releases/tag/v4.2.0). Strictly speaking, **this is _not_ a breaking change**, nor is it new in 5.0, but we're documenting it here for completeness.\n\n**This deprecation is solely a _visual_ indicator that is meant to encourage users to [migrate their apps from legacy Redux patterns to use the modern Redux Toolkit APIs](https://redux.js.org/usage/migrating-to-modern-redux)**.\n\nThe deprecation results in a **visual strikethrough** when imported and used, like **~~`createStore`~~**, but with **_no_ runtime errors or warnings**.\n\n**`createStore` will continue to work indefinitely, and will _not_ ever be removed**. But, today we want _all_ Redux users to be using Redux Toolkit for all of their Redux logic.\n\nTo fix this, there are three options:\n\n- **[Follow our strong suggestion to switch over to Redux Toolkit and `configureStore`](https://redux.js.org/usage/migrating-to-modern-redux)**\n- Do nothing. It's just a visual strikethrough, and it doesn't affect how your code behaves. Ignore it.\n- Switch to using the `legacy_createStore` API that is now exported, which is the exact same function but with no `@deprecated` tag. The simplest option is to do an aliased import rename, like `import { legacy_createStore as createStore } from 'redux'`\n\n<div class=\"typescript-only\">\n\n#### TypeScript rewrite\n\nIn 2019, we began a community-powered conversion of the Redux codebase to TypeScript. The original effort was discussed in [#3500: Port to TypeScript](https://github.com/reduxjs/redux/issues/3500), and the work was integrated in PR [#3536: Convert to TypeScript](https://github.com/reduxjs/redux/issues/3536).\n\nHowever, the TS-converted code sat around in the repo for several years, unused and unpublished, due to concerns about possible compatibility issues with the existing ecosystem (as well as general inertia on our part).\n\nRedux core v5 is now built from that TS-converted source code. In theory, this should be almost identical in both runtime behavior and types to the 4.x build, but it's very likely that some of the changes may cause types issues.\n\nPlease report any unexpected compatibility issues on [Github](https://github.com/reduxjs/redux/issues)!\n\n#### `AnyAction` deprecated in favour of `UnknownAction`\n\nThe Redux TS types have always exported an `AnyAction` type, which is defined to have `{type: string}` and treat any other field as `any`. This makes it easy to write uses like `console.log(action.whatever)`, but unfortunately does not provide any meaningful type safety.\n\nWe now export an `UnknownAction` type, which treats all fields other than `action.type` as `unknown`. This encourages users to write type guards that check the action object and assert its _specific_ TS type. Inside of those checks, you can access a field with better type safety.\n\n`UnknownAction` is now the default any place in the Redux source that expects an action object.\n\n`AnyAction` still exists for compatibility, but has been marked as deprecated.\n\nNote that [Redux Toolkit's action creators have a `.match()` method](https://redux-toolkit.js.org/api/createAction#actioncreatormatch) that acts as a useful type guard:\n\n```ts\nif (todoAdded.match(someUnknownAction)) {\n  // action is now typed as a PayloadAction<Todo>\n}\n```\n\nYou can also use the new `isAction` util to check if an unknown value is some kind of action object.\n\n#### `Middleware` type changed - Middleware `action` and `next` are typed as `unknown`\n\nPreviously, the `next` parameter is typed as the `D` type parameter passed, and `action` is typed as the `Action` extracted from the dispatch type. Neither of these are a safe assumption:\n\n- `next` would be typed to have **all** of the dispatch extensions, including the ones earlier in the chain that would no longer apply.\n  - Technically it would be _mostly_ safe to type `next` as the default Dispatch implemented by the base redux store, however this would cause `next(action)` to error (as we cannot promise `action` is actually an `Action`) - and it wouldn't account for any following middlewares that return anything other than the action they're given when they see a specific action.\n- `action` is not necessarily a known action, it can be literally anything - for example a thunk would be a function with no `.type` property (so `AnyAction` would be inaccurate)\n\nWe've changed `next` to be `(action: unknown) => unknown` (which is accurate, we have no idea what `next` expects or will return), and changed the `action` parameter to be `unknown` (which as above, is accurate).\n\nIn order to safely interact with values or access fields inside of the `action` argument, you must first do a type guard check to narrow the type, such as `isAction(action)` or `someActionCreator.match(action)`.\n\nThis new type is incompatible with the v4 `Middleware` type, so if a package's middleware is saying it's incompatible, check which version of Redux it's getting its types from! (See [overriding dependencies](#overriding-dependencies) later in this page.)\n\n#### `PreloadedState` type removed in favour of `Reducer` generic\n\nWe've made tweaks to the TS types to improve type safety and behavior.\n\nFirst, the `Reducer` type now has a `PreloadedState` possible generic:\n\n```ts\ntype Reducer<S, A extends Action, PreloadedState = S> = (\n  state: S | PreloadedState | undefined,\n  action: A,\n) => S\n```\n\nPer the explanation in [#4491](https://github.com/reduxjs/redux/pull/4491):\n\nWhy the need for this change? When the store is first created by `createStore`/`configureStore`, the initial state is set to whatever is passed as the `preloadedState` argument (or `undefined` if nothing is passed). That means that the first time that the reducer is called, it is called with the `preloadedState`. After the first call, the reducer is always passed the current state (which is `S`).\n\nFor most normal reducers, `S | undefined` accurately describes what can be passed in for the `preloadedState`. However the `combineReducers` function allows for a preloaded state of `Partial<S> | undefined`.\n\nThe solution is to have a separate generic that represents what the reducer accepts for its preloaded state. That way `createStore` can then use that generic for its `preloadedState` argument.\n\nPreviously, this was handled by a `$CombinedState` type, but that complicated things and led to some user-reported issues. This removes the need for `$CombinedState` altogether.\n\nThis change does include some breaking changes, but overall should not have a huge impact on users upgrading in user-land:\n\n- The `Reducer`, `ReducersMapObject`, and `createStore`/`configureStore` types/function take an additional `PreloadedState` generic which defaults to `S`.\n- The overloads for `combineReducers` are removed in favor of a single function definition that takes the `ReducersMapObject` as its generic parameter. Removing the overloads was necessary with these changes, since sometimes it was choosing the wrong overload.\n- Enhancers that explicitly list the generics for the reducer will need to add the third generic.\n\n</div>\n\n### Toolkit only\n\n#### Object syntax for `createSlice.extraReducers` and `createReducer` removed\n\nRTK's `createReducer` API was originally designed to accept a lookup table of action type strings to case reducers, like `{ \"ADD_TODO\": (state, action) => {} }`. We later added the \"builder callback\" form to allow more flexibility in adding \"matchers\" and a default handler, and did the same for `createSlice.extraReducers`.\n\nWe have removed the \"object\" form for both `createReducer` and `createSlice.extraReducers` in RTK 2.0, as the builder callback form is effectively the same number of lines of code, and works much better with TypeScript.\n\nAs an example, this:\n\n```ts\nconst todoAdded = createAction('todos/todoAdded')\n\ncreateReducer(initialState, {\n  [todoAdded]: (state, action) => {},\n})\n\ncreateSlice({\n  name,\n  initialState,\n  reducers: {\n    /* case reducers here */\n  },\n  extraReducers: {\n    [todoAdded]: (state, action) => {},\n  },\n})\n```\n\nshould be migrated to:\n\n```ts\ncreateReducer(initialState, (builder) => {\n  builder.addCase(todoAdded, (state, action) => {})\n})\n\ncreateSlice({\n  name,\n  initialState,\n  reducers: {\n    /* case reducers here */\n  },\n  extraReducers: (builder) => {\n    builder.addCase(todoAdded, (state, action) => {})\n  },\n})\n```\n\n##### Codemods\n\nTo simplify upgrading codebases, we've published a set of codemods that will automatically transform the deprecated \"object\" syntax into the equivalent \"builder\" syntax.\n\nThe codemods package is available on NPM as [`@reduxjs/rtk-codemods`](https://www.npmjs.com/package/@reduxjs/rtk-codemods). More details are available [here](../api/codemods).\n\nTo run the codemods against your codebase, run `npx @reduxjs/rtk-codemods <TRANSFORM NAME> path/of/files/ or/some**/*glob.js.`\n\nExamples:\n\n```sh\nnpx @reduxjs/rtk-codemods createReducerBuilder ./src\n\nnpx @reduxjs/rtk-codemods createSliceBuilder ./packages/my-app/**/*.ts\n```\n\nWe also recommend re-running Prettier on the codebase before committing the changes.\n\nThese codemods should work, but we would greatly appreciate feedback from more real-world codebases!\n\n#### `configureStore.middleware` must be a callback\n\nSince the beginning, `configureStore` has accepted a direct array value as the `middleware` option. However, providing an array directly prevents `configureStore` from calling `getDefaultMiddleware()`. So, `middleware: [myMiddleware]` means there is no thunk middleware added (or any of the dev-mode checks).\n\nThis is a footgun, and we've had numerous users accidentally do this and cause their apps to fail because the default middleware never got configured.\n\nAs a result, we've now made the `middleware` only accept the callback form. _If_ for some reason you still want to replace _all_ of the built-in middleware, do so by returning an array from the callback:\n\n```ts\nconst store = configureStore({\n  reducer,\n  middleware: (getDefaultMiddleware) => {\n    // WARNING: this means that _none_ of the default middleware are added!\n    return [myMiddleware]\n    // or for TS users, use:\n    // return new Tuple(myMiddleware)\n  },\n})\n```\n\nBut note that **we consistently recommend not replacing the default middleware entirely**, and that you should use `return getDefaultMiddleware().concat(myMiddleware)`.\n\n#### `configureStore.enhancers` must be a callback\n\nSimilarly to `configureStore.middleware`, the `enhancers` field must also be a callback, for the same reasons.\n\nThe callback will receive a `getDefaultEnhancers` function that can be used to customise the batching enhancer [that's now included by default](#configurestore-adds-autobatchenhancer-by-default).\n\nFor example:\n\n```ts\nconst store = configureStore({\n  reducer,\n  enhancers: (getDefaultEnhancers) => {\n    return getDefaultEnhancers({\n      autoBatch: { type: 'tick' },\n    }).concat(myEnhancer)\n  },\n})\n```\n\nIt's important to note that the result of `getDefaultEnhancers` will **also** contain the middleware enhancer created with any configured/default middleware. To help prevent mistakes, `configureStore` will log an error to console if middleware was provided and the middleware enhancer wasn't included in the callback result.\n\n```ts\nconst store = configureStore({\n  reducer,\n  enhancers: (getDefaultEnhancers) => {\n    return [myEnhancer] // we've lost the  middleware here\n    // instead:\n    return getDefaultEnhancers().concat(myEnhancer)\n  },\n})\n```\n\n#### Standalone `getDefaultMiddleware` and `getType` removed\n\nThe standalone version of `getDefaultMiddleware` has been deprecated since v1.6.1, and has now been removed. Use the function passed to the `middleware` callback instead, which has the correct types.\n\nWe have also removed the `getType` export, which was used to extract a type string from action creators made with `createAction`. Instead, use the static property `actionCreator.type`.\n\n#### RTK Query behavior changes\n\nWe've had a number of reports where RTK Query had issues around usage of `dispatch(endpoint.initiate(arg, {subscription: false}))`. There were also reports that multiple triggered lazy queries were resolving the promises at the wrong time. Both of these had the same underlying issue, which was that RTKQ wasn't tracking cache entries in these cases (intentionally). We've reworked the logic to always track cache entries (and remove them as needed), which should resolve those behavior issues.\n\nWe also have had issues raised about trying to run multiple mutations in a row and how tag invalidation behaves. RTKQ now has internal logic to delay tag invalidation briefly, to allow multiple invalidations to get handled together. This is controlled by a new `invalidationBehavior: 'immediately' | 'delayed'` flag on `createApi`. The new default behavior is `'delayed'`. Set it to `'immediately'` to revert to the behavior in RTK 1.9.\n\nIn RTK 1.9, we reworked RTK Query's internals to keep most of the subscription status inside the RTKQ middleware. The values are still synced to the Redux store state, but this is primarily for display by the Redux DevTools \"RTK Query\" panel. Related to the cache entry changes above, we've optimized how often those values get synced to the Redux state for perf.\n\n#### `reactHooksModule` custom hook configuration\n\nPreviously, custom versions of React Redux's hooks (`useSelector`, `useDispatch`, and `useStore`) could be passed separately to `reactHooksModule`, usually to enable using a different context to the default `ReactReduxContext`.\n\nIn practicality, the react hooks module needs all three of these hooks to be provided, and it became an easy mistake to only pass `useSelector` and `useDispatch`, without `useStore`.\n\nThe module has now moved all three of these under the same configuration key, and will check that all three are provided if the key is present.\n\n```ts\n// previously\nconst customCreateApi = buildCreateApi(\n  coreModule(),\n  reactHooksModule({\n    useDispatch: createDispatchHook(MyContext),\n    useSelector: createSelectorHook(MyContext),\n    useStore: createStoreHook(MyContext),\n  }),\n)\n\n// now\nconst customCreateApi = buildCreateApi(\n  coreModule(),\n  reactHooksModule({\n    hooks: {\n      useDispatch: createDispatchHook(MyContext),\n      useSelector: createSelectorHook(MyContext),\n      useStore: createStoreHook(MyContext),\n    },\n  }),\n)\n```\n\n#### Error message extraction\n\nRedux 4.1.0 optimized its bundle size by [extracting error message strings out of production builds](https://github.com/reduxjs/redux/releases/tag/v4.1.0), based on React's approach. We've applied the same technique to RTK. This saves about 1000 bytes from prod bundles (actual benefits will depend on which imports are being used).\n\n<div class=\"typescript-only\">\n\n#### `configureStore` field order for `middleware` matters\n\nIf you are passing _both_ the `middleware` and `enhancers` fields to `configureStore`, the `middleware` field _must_ come first in order for internal TS inference to work properly.\n\n#### Non-default middleware/enhancers must use `Tuple`\n\nWe've seen many cases where users passing the `middleware` parameter to configureStore have tried spreading the array returned by `getDefaultMiddleware()`, or passed an alternate plain array. This unfortunately loses the exact TS types from the individual middleware, and often causes TS problems down the road (such as `dispatch` being typed as `Dispatch<AnyAction>` and not knowing about thunks).\n\n`getDefaultMiddleware()` already used an internal `MiddlewareArray` class, an `Array` subclass that had strongly typed `.concat/prepend()` methods to correctly capture and retain the middleware types.\n\nWe've renamed that type to `Tuple`, and `configureStore`'s TS types now require that you _must_ use `Tuple` if you want to pass your own array of middleware:\n\n```ts\nimport { configureStore, Tuple } from '@reduxjs/toolkit'\n\nconfigureStore({\n  reducer: rootReducer,\n  middleware: (getDefaultMiddleware) => new Tuple(additionalMiddleware, logger),\n})\n```\n\n(Note that this has no effect if you're using RTK with plain JS, and you could still pass a plain array here.)\n\nThis same restriction applies to the `enhancers` field.\n\n#### Entity adapter type updates\n\n`createEntityAdapter` now has an `Id` generic argument, which will be used to strongly type the item IDs anywhere those are exposed. Previously, the ID field type was always `string | number`. TS will now try to infer the exact type from either the `.id` field of your entity type, or the `selectId` return type. You could also fall back to passing that generic type directly. **If you use the `EntityState<Data, Id>` type directly, you _must_ supply both generic arguments!**\n\nThe `.entities` lookup table is now defined to use a standard TS `Record<Id, MyEntityType>`, which assumes that each item lookup exists by default. Previously, it used a `Dictionary<MyEntityType>` type, which assumed the result was `MyEntityType | undefined`. The `Dictionary` type has been removed.\n\nIf you prefer to assume that the lookups _might_ be undefined, use TypeScript's `noUncheckedIndexedAccess` configuration option to control that.\n\n</div>\n\n### Reselect\n\n#### `createSelector` Uses `weakMapMemoize` As Default Memoizer\n\n**`createSelector` now uses a new default memoization function called `weakMapMemoize`**. This memoizer offers an effectively infinite cache size, which should simplify usage with varying arguments, but relies exclusively on reference comparisons.\n\nIf you need to customize equality comparisons, customize `createSelector` to use the original `lruMemoize` method instead:\n\n```ts no-emit\ncreateSelector(inputs, resultFn, {\n  memoize: lruMemoize,\n  memoizeOptions: { equalityCheck: yourEqualityFunction },\n})\n```\n\n#### `defaultMemoize` Renamed to `lruMemoize`\n\nSince the original `defaultMemoize` function is no longer actually the default, we've renamed it to `lruMemoize` for clarity. This only matters if you specifically imported it into your app to customize selectors.\n\n#### `createSelector` Dev-Mode Checks\n\n`createSelector` now does checks in development mode for common mistakes, like input selectors that always return new references, or result functions that immediately return their argument. These checks can be customized at selector creation or globally.\n\nThis is important, as an input selector returning a materially different result with the same parameters means that the output selector will never memoize correctly and be run unnecessarily, thus (potentially) creating a new result and causing rerenders.\n\n```ts\nconst addNumbers = createSelector(\n  // this input selector will always return a new reference when run\n  // so cache will never be used\n  (a, b) => ({ a, b }),\n  ({ a, b }) => ({ total: a + b }),\n)\n// instead, you should have an input selector for each stable piece of data\nconst addNumbersStable = createSelector(\n  (a, b) => a,\n  (a, b) => b,\n  (a, b) => ({\n    total: a + b,\n  }),\n)\n```\n\nThis is done the first time the selector is called, unless configured otherwise. More details are available in the [Reselect docs on dev-mode checks](https://reselect.js.org/api/development-only-stability-checks).\n\nNote that while RTK re-exports `createSelector`, it intentionally does not re-export the function to configure this check globally - if you wish to do so, you should instead depend on `reselect` directly and import it yourself.\n\n<div class=\"typescript-only\">\n\n#### `ParametricSelector` Types Removed\n\nThe `ParametricSelector` and `OutputParametricSelector` types have been removed. Use `Selector` and `OutputSelector` instead.\n\n</div>\n\n### React-Redux\n\n#### Requires React 18\n\nReact-Redux v7 and v8 worked with all versions of React that supported hooks (16.8+, 17, and 18). v8 switched from internal subscription management to React's new `useSyncExternalStore` hook, but used the \"shim\" implementation to provide support for React 16.8 and 17, which did not have that hook built in.\n\n**React-Redux v9 switches to _requiring_ React 18, and does _not_ support React 16 or 17**. This allows us to drop the shim and save a small bit of bundle size.\n\n<div class=\"typescript-only\">\n\n#### Custom context typing\n\nReact Redux supports creating `hooks` (and `connect`) with a [custom context](https://react-redux.js.org/api/hooks#custom-context), but typing this has been fairly non-standard. The pre-v9 types required `Context<ReactReduxContextValue>`, but the context default value was usually initialised with `null` (as the hooks use this to make sure they actually have a provided context). This, in \"best\" cases, would result in something like the below:\n\n```ts title=\"Pre-v9 custom context\"\nimport { createContext } from 'react'\nimport {\n  ReactReduxContextValue,\n  createDispatchHook,\n  createSelectorHook,\n  createStoreHook,\n} from 'react-redux'\nimport { AppStore, RootState, AppDispatch } from './store'\n\n// highlight-next-line\nconst context = createContext<ReactReduxContextValue>(null as any)\n\nexport const useStore = createStoreHook(context).withTypes<AppStore>()\nexport const useDispatch = createDispatchHook(context).withTypes<AppDispatch>()\nexport const useSelector = createSelectorHook(context).withTypes<RootState>()\n```\n\nIn v9, the types now match the runtime behavior. The context is typed to hold `ReactReduxContextValue | null`, and the hooks know that if they receive `null` they'll throw an error so it doesn't affect the return type.\n\nThe above example now becomes:\n\n```ts title=\"v9+ custom context\"\nimport { createContext } from 'react'\nimport {\n  ReactReduxContextValue,\n  createDispatchHook,\n  createSelectorHook,\n  createStoreHook,\n} from 'react-redux'\nimport { AppStore, RootState, AppDispatch } from './store'\n\n// highlight-next-line\nconst context = createContext<ReactReduxContextValue | null>(null)\n\nexport const useStore = createStoreHook(context).withTypes<AppStore>()\nexport const useDispatch = createDispatchHook(context).withTypes<AppDispatch>()\nexport const useSelector = createSelectorHook(context).withTypes<RootState>()\n```\n\n</div>\n\n### Redux Thunk\n\n#### Thunk Uses Named Exports\n\nThe `redux-thunk` package previously used a single default export that was the middleware, with an attached field named `withExtraArgument` that allowed customization.\n\nThe default export has been removed. There are now two named exports: `thunk` (the basic middleware) and `withExtraArgument`.\n\nIf you are using Redux Toolkit, this should have no effect, as RTK already handles this inside of `configureStore`.\n\n## New Features\n\nThese features are new in Redux Toolkit 2.0, and help cover additional use cases that we've seen users ask for in the ecosystem.\n\n### `combineSlices` API with slice reducer injection for code-splitting\n\nThe Redux core has always included `combineReducers`, which takes an object full of \"slice reducer\" functions and generates a reducer that calls those slice reducers. RTK's `createSlice` generates slice reducers + associated action creators, and we've taught the pattern of exporting individual action creators as named exports and the slice reducer as a default export. Meanwhile, we've never had official support for lazy-loading reducers, although we've had [sample code for some \"reducer injection\" patterns in our docs](https://redux.js.org/usage/code-splitting).\n\nThis release includes a new [`combineSlices`](../api/combineSlices) API that is designed to enable lazy-loading of reducers at runtime. It accepts individual slices or an object full of slices as arguments, and automatically calls `combineReducers` using the `sliceObject.name` field as the key for each state field. The generated reducer function has an additional `.inject()` method attached that can be used to dynamically inject additional slices at runtime. It also includes a `.withLazyLoadedSlices()` method that can be used to generate TS types for reducers that will be added later. See [#2776](https://github.com/reduxjs/redux-toolkit/issues/2776) for the original discussion around this idea.\n\nFor now, we are not building this into `configureStore`, so you'll need to call `const rootReducer = combineSlices(.....)` yourself and pass that to `configureStore({reducer: rootReducer})`.\n\n**Basic usage: a mixture of slices and standalone reducers passed to `combineSlices`**\n\n```ts\nconst stringSlice = createSlice({\n  name: 'string',\n  initialState: '',\n  reducers: {},\n})\n\nconst numberSlice = createSlice({\n  name: 'number',\n  initialState: 0,\n  reducers: {},\n})\n\nconst booleanReducer = createReducer(false, () => {})\n\nconst api = createApi(/*  */)\n\nconst combinedReducer = combineSlices(\n  stringSlice,\n  {\n    num: numberSlice.reducer,\n    boolean: booleanReducer,\n  },\n  api,\n)\nexpect(combinedReducer(undefined, dummyAction())).toEqual({\n  string: stringSlice.getInitialState(),\n  num: numberSlice.getInitialState(),\n  boolean: booleanReducer.getInitialState(),\n  api: api.reducer.getInitialState(),\n})\n```\n\n**Basic slice reducer injection**\n\n```ts\n// Create a reducer with a TS type that knows `numberSlice` will be injected\nconst combinedReducer =\n  combineSlices(stringSlice).withLazyLoadedSlices<\n    WithSlice<typeof numberSlice>\n  >()\n\n// `state.number` doesn't exist initially\nexpect(combinedReducer(undefined, dummyAction()).number).toBe(undefined)\n\n// Create a version of the reducer with `numberSlice` injected (mainly useful for types)\nconst injectedReducer = combinedReducer.inject(numberSlice)\n\n// `state.number` now exists, and injectedReducer's type no longer marks it as optional\nexpect(injectedReducer(undefined, dummyAction()).number).toBe(\n  numberSlice.getInitialState(),\n)\n\n// original reducer has also been changed (type is still optional)\nexpect(combinedReducer(undefined, dummyAction()).number).toBe(\n  numberSlice.getInitialState(),\n)\n```\n\n### `selectors` field in `createSlice`\n\nThe existing `createSlice` API now has support for defining [`selectors`](../api/createSlice#selectors) directly as part of the slice. By default, these will be generated with the assumption that the slice is mounted in the root state using `slice.name` as the field, such as `name: \"todos\"` -> `rootState.todos`. Additionally, there's now a `slice.selectSlice` method that does that default root state lookup.\n\nYou can call `sliceObject.getSelectors(selectSliceState)` to generate the selectors with an alternate location, similar to how `entityAdapter.getSelectors()` works.\n\n```ts\nconst slice = createSlice({\n  name: 'counter',\n  initialState: 42,\n  reducers: {},\n  selectors: {\n    selectSlice: (state) => state,\n    selectMultiple: (state, multiplier: number) => state * multiplier,\n  },\n})\n\n// Basic usage\nconst testState = {\n  [slice.name]: slice.getInitialState(),\n}\nconst { selectSlice, selectMultiple } = slice.selectors\nexpect(selectSlice(testState)).toBe(slice.getInitialState())\nexpect(selectMultiple(testState, 2)).toBe(slice.getInitialState() * 2)\n\n// Usage with the slice reducer mounted under a different key\nconst customState = {\n  number: slice.getInitialState(),\n}\nconst { selectSlice, selectMultiple } = slice.getSelectors(\n  (state: typeof customState) => state.number,\n)\nexpect(selectSlice(customState)).toBe(slice.getInitialState())\nexpect(selectMultiple(customState, 2)).toBe(slice.getInitialState() * 2)\n```\n\n### `createSlice.reducers` callback syntax and thunk support\n\nOne of the oldest feature requests we've had is the ability to declare thunks directly inside of `createSlice`. Until now, you've always had to declare them separately, give the thunk a string action prefix, and handle the actions via `createSlice.extraReducers`:\n\n```ts\n// Declare the thunk separately\nconst fetchUserById = createAsyncThunk(\n  'users/fetchByIdStatus',\n  async (userId: number, thunkAPI) => {\n    const response = await userAPI.fetchById(userId)\n    return response.data\n  },\n)\n\nconst usersSlice = createSlice({\n  name: 'users',\n  initialState,\n  reducers: {\n    // standard reducer logic, with auto-generated action types per reducer\n  },\n  extraReducers: (builder) => {\n    // Add reducers for additional action types here, and handle loading state as needed\n    builder.addCase(fetchUserById.fulfilled, (state, action) => {\n      state.entities.push(action.payload)\n    })\n  },\n})\n```\n\nMany users have told us that this separation feels awkward.\n\nWe've _wanted_ to include a way to define thunks directly inside of `createSlice`, and have played around with various prototypes. There were always two major blocking issues, and a secondary concern:\n\n1. It wasn't clear what the syntax for declaring a thunk inside should look like.\n2. Thunks have access to `getState` and `dispatch`, but the `RootState` and `AppDispatch` types are normally inferred from the store, which in turn infers it from the slice state types. Declaring thunks inside `createSlice` would cause circular type inference errors, as the store needs the slice types but the slice needs the store types. We weren't willing to ship an API that would work okay for our JS users but not for our TS users, especially since we _want_ people to use TS with RTK.\n3. You can't do synchronous conditional imports in ES modules, and there's no good way to make the `createAsyncThunk` import optional. Either `createSlice` always depends on it (and adds that to the bundle size), or it can't use `createAsyncThunk` at all.\n\nWe've settled on these compromises:\n\n- **In order to create async thunks with `createSlice`, you specifically need to [set up a custom version of `createSlice` that has access to `createAsyncThunk`](../api/createSlice#createasyncthunk)**.\n- You can declare thunks inside of `createSlice.reducers`, by using a \"creator callback\" syntax for the `reducers` field that is similar to the `build` callback syntax in RTK Query's `createApi` (using typed functions to create fields in an object). Doing this does look a bit different than the existing \"object\" syntax for the `reducers` field, but is still fairly similar.\n- You can customize _some_ of the types for thunks inside of `createSlice`, but you _cannot_ customize the `state` or `dispatch` types. If those are needed, you can manually do an `as` cast, like `getState() as RootState`.\n\nIn practice, we hope these are reasonable tradeoffs. Creating thunks inside of `createSlice` has been widely asked for, so we think it's an API that will see usage. If the TS customization options are a limitation, you can still declare thunks outside of `createSlice` as always, and most async thunks don't need `dispatch` or `getState` - they just fetch data and return. And finally, setting up a custom `createSlice` allows you to opt into `createAsyncThunk` being included in your bundle size (though it may already be included if used directly or as part of RTK Query - in either of these cases there's no _additional_ bundle size).\n\nHere's what the new callback syntax looks like:\n\n```ts\nconst createAppSlice = buildCreateSlice({\n  creators: { asyncThunk: asyncThunkCreator },\n})\n\nconst todosSlice = createAppSlice({\n  name: 'todos',\n  initialState: {\n    loading: false,\n    todos: [],\n    error: null,\n  } as TodoState,\n  reducers: (create) => ({\n    // A normal \"case reducer\", same as always\n    deleteTodo: create.reducer((state, action: PayloadAction<number>) => {\n      state.todos.splice(action.payload, 1)\n    }),\n    // A case reducer with a \"prepare callback\" to customize the action\n    addTodo: create.preparedReducer(\n      (text: string) => {\n        const id = nanoid()\n        return { payload: { id, text } }\n      },\n      // action type is inferred from prepare callback\n      (state, action) => {\n        state.todos.push(action.payload)\n      },\n    ),\n    // An async thunk\n    fetchTodo: create.asyncThunk(\n      // Async payload function as the first argument\n      async (id: string, thunkApi) => {\n        const res = await fetch(`myApi/todos?id=${id}`)\n        return (await res.json()) as Item\n      },\n      // An object containing `{pending?, rejected?, fulfilled?, settled?, options?}` second\n      {\n        pending: (state) => {\n          state.loading = true\n        },\n        rejected: (state, action) => {\n          state.error = action.payload ?? action.error\n        },\n        fulfilled: (state, action) => {\n          state.todos.push(action.payload)\n        },\n        // settled is called for both rejected and fulfilled actions\n        settled: (state, action) => {\n          state.loading = false\n        },\n      },\n    ),\n  }),\n})\n\n// `addTodo` and `deleteTodo` are normal action creators.\n// `fetchTodo` is the async thunk\nexport const { addTodo, deleteTodo, fetchTodo } = todosSlice.actions\n```\n\n#### Codemod\n\n**Using the new callback syntax is entirely optional (the object syntax is still standard)**, but an existing slice would need to be converted before it can take advantage of the new capabilities this syntax provides. To make this easier, a [codemod](../api/codemods) is provided.\n\n```sh\nnpx @reduxjs/rtk-codemods createSliceReducerBuilder ./src/features/todos/slice.ts\n```\n\n### \"Dynamic middleware\" middleware\n\nA Redux store's middleware pipeline is fixed at store creation time and can't be changed later. We _have_ seen ecosystem libraries that tried to allow dynamically adding and removing middleware, potentially useful for things like code splitting.\n\nThis is a relatively niche use case, but we've built [our own version of a \"dynamic middleware\" middleware](../api/createDynamicMiddleware). Add it to the Redux store at setup time, and it lets you add middleware later at runtime. It also comes with a [React hook integration that will automatically add a middleware to the store and return the updated dispatch method.](../api/createDynamicMiddleware#react-integration).\n\n```ts\nimport { createDynamicMiddleware, configureStore } from '@reduxjs/toolkit'\n\nconst dynamicMiddleware = createDynamicMiddleware()\n\nconst store = configureStore({\n  reducer: {\n    todos: todosReducer,\n  },\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().prepend(dynamicMiddleware.middleware),\n})\n\n// later\ndynamicMiddleware.addMiddleware(someOtherMiddleware)\n```\n\n### `configureStore` adds `autoBatchEnhancer` by default\n\n[In v1.9.0, we added a new `autoBatchEnhancer`](https://github.com/reduxjs/redux-toolkit/releases/tag/v1.9.0) that delays notifying subscribers briefly when multiple \"low-priority\" actions are dispatched in a row. This improves perf, as UI updates are typically the most expensive part of the update process. RTK Query marks most of its own internal actions as \"low-pri\" by default, but you have to have the `autoBatchEnhancer` added to the store to benefit from that.\n\nWe've updated `configureStore` to add the `autoBatchEnhancer` to the store setup by default, so that users can benefit from the improved perf without needing to manually tweak the store config themselves.\n\n### `entityAdapter.getSelectors` accepts a `createSelector` function\n\n[`entityAdapter.getSelectors()`](../api/createEntityAdapter#selector-functions) now accepts an options object as its second argument. This allows you to pass in your own preferred `createSelector` method, which will be used to memoize the generated selectors. This could be useful if you want to use one of Reselect's new alternate memoizers, or some other memoization library with an equivalent signature.\n\n### Immer 10.0\n\n[Immer 10.0](https://github.com/immerjs/immer/releases/tag/v10.0.0) is now final, and has several major improvements and updates:\n\n- Much faster update perf\n- Much smaller bundle size\n- Better ESM/CJS package formatting\n- No default export\n- No ES5 fallback\n\nWe've updated RTK to depend on the final Immer 10.0 release.\n\n### Next.js Setup Guide\n\nWe now have a docs page that covers [how to set up Redux properly with Next.js](https://redux.js.org/usage/nextjs). We've seen a lot of questions around using Redux, Next, and the App Router together, and this guide should help provide advice.\n\n(At this time, the Next.js `with-redux` example is still showing outdated patterns - we're going to file a PR shortly to update that to match our docs guide.)\n\n## Overriding dependencies\n\nIt will take a while for packages to update their peer dependencies to allow for Redux core 5.0, and in the meantime changes like the [Middleware type](#middleware-type-changed---middleware-action-and-next-are-typed-as-unknown) will result in perceived incompatibilities.\n\nIt's likely that most libraries will not actually have any practices that are incompatible with 5.0, but due to the peer dependency on 4.0 they end up pulling in old type declarations.\n\nThis can be solved by manually overriding the dependency resolution, which is supported by both `npm` and `yarn`.\n\n### `npm` - `overrides`\n\nNPM supports this through an [`overrides`](https://docs.npmjs.com/cli/v9/configuring-npm/package-json#overrides) field in your `package.json`. You can override the dependency for a specific package, or make sure that every package that pulls in Redux receives the same version.\n\n```json title=\"Individual override - redux-persist\"\n{\n  \"overrides\": {\n    \"redux-persist\": {\n      \"redux\": \"^5.0.0\"\n    }\n  }\n}\n```\n\n```json title=\"Blanket override\"\n{\n  \"overrides\": {\n    \"redux\": \"^5.0.0\"\n  }\n}\n```\n\n### `yarn` - `resolutions`\n\nYarn supports this through a [`resolutions`](https://classic.yarnpkg.com/lang/en/docs/selective-version-resolutions/) field in your `package.json`. Just like with NPM, you can override the dependency for a specific package, or make sure that every package that pulls in Redux receives the same version.\n\n```json title=\"Individual override - redux-persist\"\n{\n  \"resolutions\": {\n    \"redux-persist/redux\": \"^5.0.0\"\n  }\n}\n```\n\n```json title=\"Blanket override\"\n{\n  \"resolutions\": {\n    \"redux\": \"^5.0.0\"\n  }\n}\n```\n\n## Recommendations\n\nBased on changes in 2.0 and previous versions, there have been some shifts in thinking that are good to know about, if non-essential.\n\n### Alternatives to `actionCreator.toString()`\n\nAs part of RTK's original API, action creators made with `createAction` have a custom `toString()` override that returns the action type.\n\nThis was primarily useful for the ([now removed](#object-syntax-for-createsliceextrareducers-and-createreducer-removed)) object syntax for `createReducer`:\n\n```ts\nconst todoAdded = createAction<Todo>('todos/todoAdded')\n\ncreateReducer(initialState, {\n  [todoAdded]: (state, action) => {}, // toString called here, 'todos/todoAdded'\n})\n```\n\nWhile this was convenient (and other libraries in the Redux ecosystem such as `redux-saga` and `redux-observable` have supported this to various capacities), it didn't play well with TypeScript and was generally a bit too \"magic\".\n\n```ts\nconst test = todoAdded.toString()\n//    ^? typed as string, rather than specific action type\n```\n\nOver time, the action creator also gained a static `type` property and `match` method which were more explicit and worked better with TypeScript.\n\n```ts\nconst test = todoAdded.type\n//    ^? 'todos/todoAdded'\n\n// acts as a type predicate\nif (todoAdded.match(unknownAction)) {\n  unknownAction.payload\n  // ^? now typed as PayloadAction<Todo>\n}\n```\n\nFor compatibility, this override is still in place, but we encourage considering using either of the static properties for more understandable code.\n\nFor example, with `redux-observable`:\n\n```ts\n// before (works in runtime, will not filter types properly)\nconst epic = (action$: Observable<Action>) =>\n  action$.pipe(\n    ofType(todoAdded),\n    map((action) => action),\n    //   ^? still Action<any>\n  )\n\n// consider (better type filtering)\nconst epic = (action$: Observable<Action>) =>\n  action$.pipe(\n    filter(todoAdded.match),\n    map((action) => action),\n    //   ^? now PayloadAction<Todo>\n  )\n```\n\nWith `redux-saga`:\n\n```ts\n// before (still works)\nyield takeEvery(todoAdded, saga)\n\n// consider\nyield takeEvery(todoAdded.match, saga)\n// or\nyield takeEvery(todoAdded.type, saga)\n```\n\n## Future plans\n\n### Custom slice reducer creators\n\nWith the addition of the [callback syntax for createSlice](#createslicereducers-callback-syntax-and-thunk-support), the [suggestion](https://github.com/reduxjs/redux-toolkit/issues/3837) was made to enable custom slice reducer creators. These creators would be able to:\n\n- Modify reducer behavior by adding case or matcher reducers\n- Attach actions (or any other useful functions) to `slice.actions`\n- Attach provided case reducers to `slice.caseReducers`\n\nThe creator would need to first return a \"definition\" shape when `createSlice` is first called, which it then handles by adding any necessary reducers and/or actions.\n\nAn API for this is not set in stone, but the existing `create.asyncThunk` creator implemented with a potential API could look like:\n\n```js\nconst asyncThunkCreator = {\n  type: ReducerType.asyncThunk,\n  define(payloadCreator, config) {\n    return {\n      type: ReducerType.asyncThunk, // needs to match reducer type, so correct handler can be called\n      payloadCreator,\n      ...config,\n    }\n  },\n  handle(\n    {\n      // the key the reducer was defined under\n      reducerName,\n      // the autogenerated action type, i.e. `${slice.name}/${reducerName}`\n      type,\n    },\n    // the definition from define()\n    definition,\n    // methods to modify slice\n    context,\n  ) {\n    const { payloadCreator, options, pending, fulfilled, rejected, settled } =\n      definition\n    const asyncThunk = createAsyncThunk(type, payloadCreator, options)\n\n    if (pending) context.addCase(asyncThunk.pending, pending)\n    if (fulfilled) context.addCase(asyncThunk.fulfilled, fulfilled)\n    if (rejected) context.addCase(asyncThunk.rejected, rejected)\n    if (settled) context.addMatcher(asyncThunk.settled, settled)\n\n    context.exposeAction(reducerName, asyncThunk)\n    context.exposeCaseReducer(reducerName, {\n      pending: pending || noop,\n      fulfilled: fulfilled || noop,\n      rejected: rejected || noop,\n      settled: settled || noop,\n    })\n  },\n}\n\nconst createSlice = buildCreateSlice({\n  creators: {\n    asyncThunk: asyncThunkCreator,\n  },\n})\n```\n\nWe're not sure how many people/libraries would actually make use of this though, so any feedback over on the [Github issue](https://github.com/reduxjs/redux-toolkit/issues/3837) is welcome!\n\n### `createSlice.selector` selector factories\n\nThere have been some concerns raised internally about whether `createSlice.selectors` supports memoized selectors sufficiently. You can provide a memoized selector to your `createSlice.selectors` configuration, but you're stuck with that one instance.\n\n```ts\nconst todoSlice = createSlice({\n  name: 'todos',\n  initialState: {\n    todos: [] as Todo[],\n  },\n  reducers: {},\n  selectors: {\n    selectTodosByAuthor = createSelector(\n      (state: TodoState) => state.todos,\n      (state: TodoState, author: string) => author,\n      (todos, author) => todos.filter((todo) => todo.author === author),\n    ),\n  },\n})\n\nexport const { selectTodosByAuthor } = todoSlice.selectors\n```\n\nWith `createSelector`'s default cache size of 1, this can cause caching issues if called in multiple components with different arguments. One typical solution for this (without `createSlice`) is a [selector factory](https://redux.js.org/usage/deriving-data-selectors#creating-unique-selector-instances):\n\n```ts\nexport const makeSelectTodosByAuthor = () =>\n  createSelector(\n    (state: RootState) => state.todos.todos,\n    (state: RootState, author: string) => author,\n    (todos, author) => todos.filter((todo) => todo.author === author),\n  )\n\nfunction AuthorTodos({ author }: { author: string }) {\n  const selectTodosByAuthor = useMemo(makeSelectTodosByAuthor, [])\n  const todos = useSelector((state) => selectTodosByAuthor(state, author))\n}\n```\n\nOf course, with `createSlice.selectors` this is no longer possible, as you need the selector instance when creating your slice.\n\nIn 2.0.0 we have no set solution for this - a few APIs have been floated ([PR 1](https://github.com/reduxjs/redux-toolkit/pull/3671), [PR 2](https://github.com/reduxjs/redux-toolkit/pull/3836)) but nothing was decided upon. If this is something you'd like to see supported, consider providing feedback in the [Github discussion](https://github.com/reduxjs/redux-toolkit/discussions/3387)!\n\n### 3.0 - RTK Query\n\nRTK 2.0 was largely focused on core and toolkit changes. Now that 2.0 is released, we would like to shift our focus to RTK Query, as there are still some rough edges to iron out - some of which may require breaking changes, necessitating a 3.0 release.\n\nIf you have any feedback for what that could look like, please consider chiming in at the [RTK Query API pain points and rough spots feedback thread](https://github.com/reduxjs/redux-toolkit/issues/3692)!\n\n</div>\n"
  },
  {
    "path": "docs/usage/migrating-to-modern-redux.mdx",
    "content": "---\nid: migrating-to-modern-redux\ntitle: Migrating to Modern Redux\ndescription: 'Usage > Setup > Migrating to Modern Redux: how to modernize legacy Redux code'\n---\n\nimport { DetailedExplanation } from '../components/DetailedExplanation'\n\n:::tip What You'll Learn\n\n- How to modernize legacy \"hand-written\" Redux logic to use Redux Toolkit\n- How to modernize legacy React-Redux `connect` components to use the hooks API\n- How to modernize Redux logic and React-Redux components that use TypeScript\n\n:::\n\n## Overview\n\nRedux has been around since 2015, and our recommended patterns for writing Redux code have changed significantly over the years. In the same way that React has evolved from `createClass` to `React.Component` to function components with hooks, Redux has evolved from manual store setup + hand-written reducers with object spreads + React-Redux's `connect`, to Redux Toolkit's `configureStore` + `createSlice` + React-Redux's hooks API.\n\nMany users are working on older Redux codebases that have been around since before these \"modern Redux\" patterns existed. Migrating those codebases to today's recommended modern Redux patterns will result in codebases that are much smaller and easier to maintain.\n\nThe good news is that **you can migrate your code to modern Redux incrementally, piece by piece, with old and new Redux code coexisting and working together!**\n\nThis page covers the general approaches and techniques you can use to modernize an existing legacy Redux codebase.\n\n:::info\n\nFor more details on how \"modern Redux\" with Redux Toolkit + React-Redux hooks simplifies using Redux, see these additional resources:\n\n- [Why Redux Toolkit is How to use Redux Today](../introduction/why-rtk-is-redux-today.md)\n- [Redux Essentials: Redux Toolkit App Structure](https://redux.js.org/tutorials/essentials/part-2-app-structure)\n- [Redux Fundamentals: Modern Redux with Redux Toolkit](https://redux.js.org/tutorials/fundamentals/part-8-modern-redux)\n- [Presentation: Modern Redux with Redux Toolkit](https://blog.isquaredsoftware.com/2022/06/presentations-modern-redux-rtk/)\n\n:::\n\n## Modernizing Redux Logic with Redux Toolkit\n\nThe general approach to migrating Redux logic is:\n\n- Replace the existing manual Redux store setup with Redux Toolkit's `configureStore`\n- Pick an existing slice reducer and its associated actions. Replace those with RTK's `createSlice`. Repeat for one reducer at a time.\n- As needed, replace existing data fetching logic with RTK Query or `createAsyncThunk`\n- Use RTK's other APIs like `createListenerMiddleware` or `createEntityAdapter` as needed\n\n**You should always start by replacing the legacy `createStore` call with `configureStore`**. This is a one-time step, and all of the existing reducers and middleware will continue to work as-is. `configureStore` includes development-mode checks for common mistakes like accidental mutations and non-serializable values, so having those in place will help identify any areas of the codebase where those mistakes are happening.\n\n:::info\n\nYou can see this general approach in action in [**Redux Fundamentals, Part 8: Modern Redux with Redux Toolkit**](https://redux.js.org/tutorials/fundamentals/part-8-modern-redux).\n\n:::\n\n### Store Setup with `configureStore`\n\nA typical legacy Redux store setup file does several different steps:\n\n- Combining the slice reducers into the root reducer\n- Creating the middleware enhancer, usually with the thunk middleware, and possibly other middleware in development mode such as `redux-logger`\n- Adding the Redux DevTools enhancer, and composing the enhancers together\n- Calling `createStore`\n\nHere's what those steps might look like in an existing application:\n\n```js title=\"src/app/store.js\"\nimport { createStore, applyMiddleware, combineReducers, compose } from 'redux'\nimport thunk from 'redux-thunk'\n\nimport postsReducer from '../reducers/postsReducer'\nimport usersReducer from '../reducers/usersReducer'\n\nconst rootReducer = combineReducers({\n  posts: postsReducer,\n  users: usersReducer,\n})\n\nconst middlewareEnhancer = applyMiddleware(thunk)\n\nconst composeWithDevTools =\n  window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose\n\nconst composedEnhancers = composeWithDevTools(middlewareEnhancer)\n\nconst store = createStore(rootReducer, composedEnhancers)\n```\n\n**_All_ of those steps can be replaced with a single call to Redux Toolkit's `configureStore` API**.\n\nRTK's `configureStore` wraps around the original `createStore` method, and handles most of the store setup for us automatically. In fact, we can cut it down to effectively one step:\n\n```js title=\"Basic Store Setup: src/app/store.js\"\nimport { configureStore } from '@reduxjs/toolkit'\n\nimport postsReducer from '../reducers/postsReducer'\nimport usersReducer from '../reducers/usersReducer'\n\n// highlight-start\n// Automatically adds the thunk middleware and the Redux DevTools extension\nconst store = configureStore({\n  // Automatically calls `combineReducers`\n  reducer: {\n    posts: postsReducer,\n    users: usersReducer,\n  },\n})\n// highlight-end\n```\n\nThat one call to `configureStore` did all the work for us:\n\n- It called `combineReducers` to combine `postsReducer` and `usersReducer` into the root reducer function, which will handle a root state that looks like `{posts, users}`\n- It called `createStore` to create a Redux store using that root reducer\n- It automatically added the thunk middleware and called `applyMiddleware`\n- It automatically added more middleware to check for common mistakes like accidentally mutating the state\n- It automatically set up the Redux DevTools Extension connection\n\nIf your store setup requires additional steps, such as adding additional middleware, passing in an `extra` argument to the thunk middleware, or creating a persisted root reducer, you can do that as well. Here's a larger example that shows customizing the built-in middleware and turning on Redux-Persist, which demonstrates some of the options for working with `configureStore`:\n\n<DetailedExplanation title=\"Detailed Example: Custom Store Setup with Persistence and Middleware\">\n\nThis example shows several possible common tasks when setting up a Redux store:\n\n- Combining the reducers separately (sometimes needed due to other architectural constraints)\n- Adding additional middleware, both conditionally and unconditionally\n- Passing an \"extra argument\" into the thunk middleware, such as an API service layer\n- Using the Redux-Persist library, which requires special handling for its non-serializable action types\n- Turning the devtools off in prod, and setting additional devtools options in development\n\nNone of these are _required_, but they do show up frequently in real-world codebases.\n\n```js title=\"Custom Store Setup: src/app/store.js\"\nimport { configureStore, combineReducers } from '@reduxjs/toolkit'\nimport {\n  persistStore,\n  persistReducer,\n  FLUSH,\n  REHYDRATE,\n  PAUSE,\n  PERSIST,\n  PURGE,\n  REGISTER,\n} from 'redux-persist'\nimport storage from 'redux-persist/lib/storage'\nimport { PersistGate } from 'redux-persist/integration/react'\nimport logger from 'redux-logger'\n\nimport postsReducer from '../features/posts/postsSlice'\nimport usersReducer from '../features/users/usersSlice'\nimport { api } from '../features/api/apiSlice'\nimport { serviceLayer } from '../features/api/serviceLayer'\n\nimport stateSanitizerForDevtools from './devtools'\nimport customMiddleware from './someCustomMiddleware'\n\n// Can call `combineReducers` yourself if needed\nconst rootReducer = combineReducers({\n  posts: postsReducer,\n  users: usersReducer,\n  [api.reducerPath]: api.reducer,\n})\n\nconst persistConfig = {\n  key: 'root',\n  version: 1,\n  storage,\n}\n\nconst persistedReducer = persistReducer(persistConfig, rootReducer)\n\nconst store = configureStore({\n  // Can create a root reducer separately and pass that in\n  reducer: rootReducer,\n  middleware: (getDefaultMiddleware) => {\n    const middleware = getDefaultMiddleware({\n      // Pass in a custom `extra` argument to the thunk middleware\n      thunk: {\n        extraArgument: { serviceLayer },\n      },\n      // Customize the built-in serializability dev check\n      serializableCheck: {\n        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],\n      },\n    }).concat(customMiddleware, api.middleware)\n\n    // Conditionally add another middleware in dev\n    if (process.env.NODE_ENV !== 'production') {\n      middleware.push(logger)\n    }\n\n    return middleware\n  },\n  // Turn off devtools in prod, or pass options in dev\n  devTools:\n    process.env.NODE_ENV === 'production'\n      ? false\n      : {\n          stateSanitizer: stateSanitizerForDevtools,\n        },\n})\n```\n\n</DetailedExplanation>\n\n### Reducers and Actions with `createSlice`\n\nA typical legacy Redux codebase has its reducer logic, action creators, and action types spread across separate files, and those files are often in separate folders by type. The reducer logic is written using `switch` statements and hand-written immutable update logic with object spreads and array mapping:\n\n```js title=\"src/constants/todos.js\"\nexport const ADD_TODO = 'ADD_TODO'\nexport const TOGGLE_TODO = 'TOGGLE_TODO'\n```\n\n```js title=\"src/actions/todos.js\"\nimport { ADD_TODO, TOGGLE_TODO } from '../constants/todos'\n\nexport const addTodo = (id, text) => ({\n  type: ADD_TODO,\n  text,\n  id,\n})\n\nexport const toggleTodo = (id) => ({\n  type: TOGGLE_TODO,\n  id,\n})\n```\n\n```js title=\"src/reducers/todos.js\"\nimport { ADD_TODO, TOGGLE_TODO } from '../constants/todos'\n\nconst initialState = []\n\nexport default function todosReducer(state = initialState, action) {\n  switch (action.type) {\n    case ADD_TODO: {\n      return state.concat({\n        id: action.id,\n        text: action.text,\n        completed: false,\n      })\n    }\n    case TOGGLE_TODO: {\n      return state.map((todo) => {\n        if (todo.id !== action.id) {\n          return todo\n        }\n\n        return {\n          ...todo,\n          completed: !todo.completed,\n        }\n      })\n    }\n    default:\n      return state\n  }\n}\n```\n\n**Redux Toolkit's `createSlice` API was designed to eliminate all the \"boilerplate\" with writing reducers, actions, and immutable updates!**\n\nWith Redux Toolkit, there's multiple changes to that legacy code:\n\n- `createSlice` will eliminate the hand-written action creators and action types entirely\n- All of the uniquely-named fields like `action.text` and `action.id` get replaced by `action.payload`, either as an individual value or an object containing those fields\n- The hand-written immutable updates are replaced by \"mutating\" logic in reducers thanks to Immer\n- There's no need for separate files for each type of code\n- We teach having _all_ logic for a given reducer in a single \"slice\" file\n- Instead of having separate folders by \"type of code\", we recommend organizing files by \"features\", with related code living in the same folder\n- Ideally, the naming of the reducers and actions should use the past tense and describe \"a thing that happened\", rather than an imperative \"do this thing now\", such as `todoAdded` instead of `ADD_TODO`\n\nThose separate files for constants, actions, and reducers, would all be replaced by a single \"slice\" file. The modernized slice file would look like this:\n\n```js title=\"src/features/todos/todosSlice.js\"\nimport { createSlice } from '@reduxjs/toolkit'\n\nconst initialState = []\n\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState,\n  reducers: {\n    // highlight-start\n    // Give case reducers meaningful past-tense \"event\"-style names\n    todoAdded(state, action) {\n      const { id, text } = action.payload\n      // \"Mutating\" update syntax thanks to Immer, and no `return` needed\n      state.todos.push({\n        id,\n        text,\n        completed: false,\n      })\n    },\n    // highlight-end\n    todoToggled(state, action) {\n      // Look for the specific nested object to update.\n      // In this case, `action.payload` is the default field in the action,\n      // and can hold the `id` value - no need for `action.id` separately\n      const matchingTodo = state.todos.find(\n        (todo) => todo.id === action.payload,\n      )\n\n      if (matchingTodo) {\n        // Can directly \"mutate\" the nested object\n        matchingTodo.completed = !matchingTodo.completed\n      }\n    },\n  },\n})\n\n// highlight-start\n// `createSlice` automatically generated action creators with these names.\n// export them as named exports from this \"slice\" file\nexport const { todoAdded, todoToggled } = todosSlice.actions\n//highlight-end\n\n// Export the slice reducer as the default export\nexport default todosSlice.reducer\n```\n\nWhen you call `dispatch(todoAdded('Buy milk'))`, whatever single value you pass to the `todoAdded` action creator will automatically get used as the `action.payload` field. If you need to pass in multiple values, do so as an object, like `dispatch(todoAdded({id, text}))`. Alternately, you can use [the \"prepare\" notation inside of a `createSlice` reducer](https://redux.js.org/tutorials/essentials/part-4-using-data#preparing-action-payloads) to accept multiple separate arguments and create the `payload` field. The `prepare` notation is also useful for cases where the action creators were doing additional work, such as generating unique IDs for each item.\n\nWhile Redux Toolkit does not specifically care about your folder and file structures or action naming, [these are the best practices we recommend](https://redux.js.org/style-guide/) because we've found they lead to more maintainable and understandable code.\n\n### Data Fetching with RTK Query\n\nTypical legacy data fetching in a React+Redux app requires many moving pieces and types of code:\n\n- Action creators and action types that represent \"request starting\", \"request succeeded\", and \"request failed\" actions\n- Thunks to dispatch the actions and make the async request\n- Reducers that track loading status and store the cached data\n- Selectors to read those values from the store\n- Dispatching the thunk in a component after mounting, either via `componentDidMount` in a class component or `useEffect` in a function component\n\nThese typically would be split across many different files:\n\n```js title=\"src/constants/todos.js\"\nexport const FETCH_TODOS_STARTED = 'FETCH_TODOS_STARTED'\nexport const FETCH_TODOS_SUCCEEDED = 'FETCH_TODOS_SUCCEEDED'\nexport const FETCH_TODOS_FAILED = 'FETCH_TODOS_FAILED'\n```\n\n```js title=\"src/actions/todos.js\"\nimport axios from 'axios'\nimport {\n  FETCH_TODOS_STARTED,\n  FETCH_TODOS_SUCCEEDED,\n  FETCH_TODOS_FAILED,\n} from '../constants/todos'\n\nexport const fetchTodosStarted = () => ({\n  type: FETCH_TODOS_STARTED,\n})\n\nexport const fetchTodosSucceeded = (todos) => ({\n  type: FETCH_TODOS_SUCCEEDED,\n  todos,\n})\n\nexport const fetchTodosFailed = (error) => ({\n  type: FETCH_TODOS_FAILED,\n  error,\n})\n\nexport const fetchTodos = () => {\n  return async (dispatch) => {\n    dispatch(fetchTodosStarted())\n\n    try {\n      // Axios is common, but also `fetch`, or your own \"API service\" layer\n      const res = await axios.get('/todos')\n      dispatch(fetchTodosSucceeded(res.data))\n    } catch (err) {\n      dispatch(fetchTodosFailed(err))\n    }\n  }\n}\n```\n\n```js title=\"src/reducers/todos.js\"\nimport {\n  FETCH_TODOS_STARTED,\n  FETCH_TODOS_SUCCEEDED,\n  FETCH_TODOS_FAILED,\n} from '../constants/todos'\n\nconst initialState = {\n  status: 'uninitialized',\n  todos: [],\n  error: null,\n}\n\nexport default function todosReducer(state = initialState, action) {\n  switch (action.type) {\n    case FETCH_TODOS_STARTED: {\n      return {\n        ...state,\n        status: 'loading',\n      }\n    }\n    case FETCH_TODOS_SUCCEEDED: {\n      return {\n        ...state,\n        status: 'succeeded',\n        todos: action.todos,\n      }\n    }\n    case FETCH_TODOS_FAILED: {\n      return {\n        ...state,\n        status: 'failed',\n        todos: [],\n        error: action.error,\n      }\n    }\n    default:\n      return state\n  }\n}\n```\n\n```js title=\"src/selectors/todos.js\"\nexport const selectTodosStatus = (state) => state.todos.status\nexport const selectTodos = (state) => state.todos.todos\n```\n\n```js title=\"src/components/TodosList.js\"\nimport { useEffect } from 'react'\nimport { useSelector, useDispatch } from 'react-redux'\nimport { fetchTodos } from '../actions/todos'\nimport { selectTodosStatus, selectTodos } from '../selectors/todos'\n\nexport function TodosList() {\n  const dispatch = useDispatch()\n  const status = useSelector(selectTodosStatus)\n  const todos = useSelector(selectTodos)\n\n  useEffect(() => {\n    dispatch(fetchTodos())\n  }, [dispatch])\n\n  // omit rendering logic here\n}\n```\n\nMany users may be using the `redux-saga` library to manage data fetching, in which case they might have _additional_ \"signal\" action types used to trigger the sagas, and this saga file instead of thunks:\n\n```js title=\"src/sagas/todos.js\"\nimport { put, takeEvery, call } from 'redux-saga/effects'\nimport {\n  FETCH_TODOS_BEGIN,\n  fetchTodosStarted,\n  fetchTodosSucceeded,\n  fetchTodosFailed,\n} from '../actions/todos'\n\n// Saga to actually fetch data\nexport function* fetchTodos() {\n  yield put(fetchTodosStarted())\n\n  try {\n    const res = yield call(axios.get, '/todos')\n    yield put(fetchTodosSucceeded(res.data))\n  } catch (err) {\n    yield put(fetchTodosFailed(err))\n  }\n}\n\n// \"Watcher\" saga that waits for a \"signal\" action, which is\n// dispatched only to kick off logic, not to update state\nexport function* fetchTodosSaga() {\n  yield takeEvery(FETCH_TODOS_BEGIN, fetchTodos)\n}\n```\n\n**_All_ of that code can be replaced with [Redux Toolkit's \"RTK Query\" data fetching and caching layer](https://redux-toolkit.js.org/rtk-query/overview)!**\n\nRTK Query replaces the need to write _any_ actions, thunks, reducers, selectors, or effects to manage data fetching. (In fact, it actually _uses_ all those same tools internally.) Additionally, RTK Query takes care of tracking loading state, deduplicating requests, and managing cache data lifecycles (including removing expired data that is no longer needed).\n\nTo migrate, [set up a single RTK Query \"API slice\" definition and add the generated reducer + middleware to your store](https://redux.js.org/tutorials/essentials/part-7-rtk-query-basics):\n\n```js title=\"src/features/api/apiSlice.js\"\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({\n    // Fill in your own server starting URL here\n    baseUrl: '/',\n  }),\n  endpoints: (build) => ({}),\n})\n```\n\n```js title=\"src/app/store.js\"\nimport { configureStore } from '@reduxjs/toolkit'\n\n// Import the API object\n// highlight-next-line\nimport { api } from '../features/api/apiSlice'\n// Import any other slice reducers as usual here\nimport usersReducer from '../features/users/usersSlice'\n\nexport const store = configureStore({\n  reducer: {\n    // Add the generated RTK Query \"API slice\" caching reducer\n    // highlight-next-line\n    [api.reducerPath]: api.reducer,\n    // Add any other reducers\n    users: usersReducer,\n  },\n  // Add the RTK Query API middleware\n  // highlight-start\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(api.middleware),\n  // highlight-end\n})\n```\n\nThen, add \"endpoints\" that represents the specific data you want to fetch and cache, and export the auto-generated React hooks for each endpoint:\n\n```js title=\"src/features/api/apiSlice.js\"\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({\n    // Fill in your own server starting URL here\n    baseUrl: '/',\n  }),\n  endpoints: (build) => ({\n    // highlight-start\n    // A query endpoint with no arguments\n    getTodos: build.query({\n      query: () => '/todos',\n    }),\n    // A query endpoint with an argument\n    userById: build.query({\n      query: (userId) => `/users/${userId}`,\n    }),\n    // highlight-end\n    // A mutation endpoint\n    updateTodo: build.mutation({\n      query: (updatedTodo) => ({\n        url: `/todos/${updatedTodo.id}`,\n        method: 'POST',\n        body: updatedTodo,\n      }),\n    }),\n  }),\n})\n\n// highlight-next-line\nexport const { useGetTodosQuery, useUserByIdQuery, useUpdateTodoMutation } = api\n```\n\nFinally, use the hooks in your components:\n\n```js title=\"src/features/todos/TodoList.js\"\n// highlight-next-line\nimport { useGetTodosQuery } from '../api/apiSlice'\n\nexport function TodoList() {\n  // highlight-next-line\n  const { data: todos, isFetching, isSuccess } = useGetTodosQuery()\n\n  // omit rendering logic here\n}\n```\n\n### Data Fetching with `createAsyncThunk`\n\n**We _specifically_ recommend using RTK Query for data fetching.** However, some users have told us they aren't ready to make that step yet. In that case, you can at least cut down on some of the boilerplate of hand-written thunks and reducers using RTK's `createAsyncThunk`. It automatically generates the action creators and action types for you, calls the async function you provide to make the request, and dispatches those actions based on the promise lifecycle. The same example with `createAsyncThunk` might look like this:\n\n```js title=\"src/features/todos/todosSlice\"\nimport { createAsyncThunk, createSlice } from '@reduxjs/toolkit'\nimport axios from 'axios'\n\nconst initialState = {\n  status: 'uninitialized',\n  todos: [],\n  error: null,\n}\n\nconst fetchTodos = createAsyncThunk('todos/fetchTodos', async () => {\n  // Just make the async request here, and return the response.\n  // This will automatically dispatch a `pending` action first,\n  // and then `fulfilled` or `rejected` actions based on the promise.\n  // as needed based on the\n  const res = await axios.get('/todos')\n  return res.data\n})\n\nexport const todosSlice = createSlice({\n  name: 'todos',\n  initialState,\n  reducers: {\n    // any additional \"normal\" case reducers here.\n    // these will generate new action creators\n  },\n  extraReducers: (builder) => {\n    // Use `extraReducers` to handle actions that were generated\n    // _outside_ of the slice, such as thunks or in other slices\n    builder\n      .addCase(fetchTodos.pending, (state, action) => {\n        state.status = 'loading'\n      })\n      // Pass the generated action creators to `.addCase()`\n      .addCase(fetchTodos.fulfilled, (state, action) => {\n        // Same \"mutating\" update syntax thanks to Immer\n        state.status = 'succeeded'\n        state.todos = action.payload\n      })\n      .addCase(fetchTodos.rejected, (state, action) => {\n        state.status = 'failed'\n        state.todos = []\n        state.error = action.error\n      })\n  },\n})\n\nexport default todosSlice.reducer\n```\n\nYou'd also still need to write any selectors, and dispatch the `fetchTodos` thunk yourself in a `useEffect` hook.\n\n### Reactive Logic with `createListenerMiddleware`\n\nMany Redux apps have \"reactive\"-style logic that listens for specific actions or state changes, and runs additional logic in response. These behaviors are often implemented using the `redux-saga` or `redux-observable` libraries.\n\nThese libraries are used for a wide variety of tasks. As a basic example, a saga and an epic that listen for an action, wait one second, and then dispatch an additional action might look like this:\n\n```js title=\"src/sagas/ping.js\"\nimport { delay, put, takeEvery } from 'redux-saga/effects'\n\nexport function* ping() {\n  yield delay(1000)\n  yield put({ type: 'PONG' })\n}\n\n// \"Watcher\" saga that waits for a \"signal\" action, which is\n// dispatched only to kick off logic, not to update state\nexport function* pingSaga() {\n  yield takeEvery('PING', ping)\n}\n```\n\n```js title=\"src/epics/ping.js\"\nimport { filter, mapTo } from 'rxjs/operators'\nimport { ofType } from 'redux-observable'\n\nconst pingEpic = (action$) =>\n  action$.pipe(ofType('PING'), delay(1000), mapTo({ type: 'PONG' }))\n```\n\n```js title=\"src/app/store.js\"\nimport { createStore, applyMiddleware } from 'redux'\nimport createSagaMiddleware from 'redux-saga'\nimport { combineEpics, createEpicMiddleware  } from 'redux-observable';\n\n// skip reducers\n\nimport { pingEpic } from '../sagas/ping'\nimport { pingSaga } from '../epics/ping\n\nfunction* rootSaga() {\n  yield pingSaga()\n}\n\nconst rootEpic = combineEpics(\n  pingEpic\n);\n\nconst sagaMiddleware = createSagaMiddleware()\nconst epicMiddleware = createEpicMiddleware()\n\nconst middlewareEnhancer = applyMiddleware(sagaMiddleware, epicMiddleware)\n\nconst store = createStore(rootReducer, middlewareEnhancer)\n\nsagaMiddleware.run(rootSaga)\nepicMiddleware.run(rootEpic)\n```\n\n**The RTK \"listener\" middleware is designed to replace sagas and observables, with a simpler API, smaller bundle size, and better TS support.**\n\nThe saga and epic examples could be replaced with the listener middleware, like this:\n\n```js title=\"src/app/listenerMiddleware.js\"\nimport { createListenerMiddleware } from '@reduxjs/toolkit'\n\n// Best to define this in a separate file, to avoid importing\n// from the store file into the rest of the codebase\nexport const listenerMiddleware = createListenerMiddleware()\n\nexport const { startListening, stopListening } = listenerMiddleware\n```\n\n```js title=\"src/features/ping/pingSlice.js\"\nimport { createSlice } from '@reduxjs/toolkit'\nimport { startListening } from '../../app/listenerMiddleware'\n\nconst pingSlice = createSlice({\n  name: 'ping',\n  initialState,\n  reducers: {\n    pong(state, action) {\n      // state update here\n    },\n  },\n})\n\nexport const { pong } = pingSlice.actions\nexport default pingSlice.reducer\n\n// highlight-start\n// The `startListening()` call could go in different files,\n// depending on your preferred app setup. Here, we just add\n// it directly in a slice file.\nstartListening({\n  // Match this exact action type based on the action creator\n  actionCreator: pong,\n  // Run this effect callback whenever that action is dispatched\n  effect: async (action, listenerApi) => {\n    // Listener effect functions get a `listenerApi` object\n    // with many useful methods built in, including `delay`:\n    await listenerApi.delay(1000)\n    listenerApi.dispatch(pong())\n  },\n})\n// highlight-end\n```\n\n```js title=\"src/app/store.js\"\nimport { configureStore } from '@reduxjs/toolkit'\n\nimport { listenerMiddleware } from './listenerMiddleware'\n\n// omit reducers\n\nexport const store = configureStore({\n  reducer: rootReducer,\n  // Add the listener middleware _before_ the thunk or dev checks\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().prepend(listenerMiddleware.middleware),\n})\n```\n\n### Migrating TypeScript for Redux Logic\n\nLegacy Redux code that uses TypeScript typically follows _very_ verbose patterns for defining types. In particular, many users in the community have decided to manually define TS types for each individual action, and then created \"action type unions\" that try to limit what specific actions can actually be passed to `dispatch`.\n\n**We specifically and strongly recommend _against_ these patterns!**\n\n```ts no-transpile title=\"src/actions/todos.ts\"\nimport { ADD_TODO, TOGGLE_TODO } from '../constants/todos'\n\n// ❌ Common pattern: manually defining types for each action object\ninterface AddTodoAction {\n  type: typeof ADD_TODO\n  text: string\n  id: string\n}\n\ninterface ToggleTodoAction {\n  type: typeof TOGGLE_TODO\n  id: string\n}\n\n// ❌ Common pattern: an \"action type union\" of all possible actions\nexport type TodoActions = AddTodoAction | ToggleTodoAction\n\nexport const addTodo = (id: string, text: string): AddTodoAction => ({\n  type: ADD_TODO,\n  text,\n  id,\n})\n\nexport const toggleTodo = (id: string): ToggleTodoAction => ({\n  type: TOGGLE_TODO,\n  id,\n})\n```\n\n```ts no-transpile title=\"src/reducers/todos.ts\"\nimport { ADD_TODO, TOGGLE_TODO, TodoActions } from '../constants/todos'\n\ninterface Todo {\n  id: string\n  text: string\n  completed: boolean\n}\n\nexport type TodosState = Todo[]\n\nconst initialState: TodosState = []\n\nexport default function todosReducer(\n  state = initialState,\n  action: TodoActions,\n) {\n  switch (action.type) {\n    // omit reducer logic\n    default:\n      return state\n  }\n}\n```\n\n```ts no-transpile title=\"src/app/store.ts\"\nimport { createStore, Dispatch } from 'redux'\n\nimport { TodoActions } from '../actions/todos'\nimport { CounterActions } from '../actions/counter'\nimport { TodosState } from '../reducers/todos'\nimport { CounterState } from '../reducers/counter'\n\n// omit reducer setup\n\nexport const store = createStore(rootReducer)\n\n// ❌ Common pattern: an \"action type union\" of all possible actions\nexport type RootAction = TodoActions | CounterActions\n// ❌ Common pattern: manually defining the root state type with each field\nexport interface RootState {\n  todos: TodosState\n  counter: CounterState\n}\n\n// ❌ Common pattern: limiting what can be dispatched at the types level\nexport type AppDispatch = Dispatch<RootAction>\n```\n\n**Redux Toolkit is designed to drastically simplify TS usage, and our recommendations include _inferring_ types as much as possible!**\n\nPer [our standard TypeScript setup and usage guidelines](../tutorials/typescript.md), start with setting up the store file to infer `AppDispatch` and `RootState` types directly from the store itself. That will correctly include any modifications to `dispatch` that were added by middleware, such as the ability to dispatch thunks, and update the `RootState` type any time you modify a slice's state definition or add more slices.\n\n```ts no-transpile title=\"app/store.ts\"\nimport { configureStore } from '@reduxjs/toolkit'\n// omit any other imports\n\nconst store = configureStore({\n  reducer: {\n    todos: todosReducer,\n    counter: counterReducer,\n  },\n})\n\n// highlight-start\n// Infer the `RootState` and `AppDispatch` types from the store itself\n\n// Inferred state type: {todos: TodosState, counter: CounterState}\nexport type RootState = ReturnType<typeof store.getState>\n\n// Inferred dispatch type: Dispatch & ThunkDispatch<RootState, undefined, UnknownAction>\nexport type AppDispatch = typeof store.dispatch\n// highlight-end\n```\n\nEach slice file should declare and export a type for its own slice state. Then, use the `PayloadAction` type to declare the type of any `action` argument inside of `createSlice.reducers`. The generated action creators will then _also_ have the correct type for the argument they accept, and the type of `action.payload` that they return.\n\n```ts no-transpile title=\"src/features/todos/todosSlice.ts\"\nimport { createSlice, PayloadAction } from '@reduxjs/toolkit'\n\ninterface Todo {\n  id: string\n  text: string\n  completed: boolean\n}\n\n// highlight-start\n// Declare and export a type for the slice's state\nexport type TodosState = Todo[]\n\nconst initialState: TodosState = []\n// highlight-end\n\nconst todosSlice = createSlice({\n  name: 'todos',\n  // The `state` argument type will be inferred for all case reducers\n  // from the type of `initialState`\n  initialState,\n  reducers: {\n    // highlight-start\n    // Use `PayloadAction<YourPayloadTypeHere>` for each `action` argument\n    todoAdded(state, action: PayloadAction<{ id: string; text: string }>) {\n      // omit logic\n    },\n    todoToggled(state, action: PayloadAction<string>) {\n      // omit logic\n    },\n    // highlight-end\n  },\n})\n```\n\n## Modernizing React Components with React-Redux\n\nThe general approach to migrating React-Redux usage in components is:\n\n- Migrate an existing React class component to be a function component\n- Replace the `connect` wrapper with uses of the `useSelector` and `useDispatch` hooks _inside_ the component\n\nYou can do this on an individual per-component basis. Components with `connect` and with hooks can coexist at the same time.\n\nThis page won't cover the process of migrating class components to function components, but will focus on the changes specific to React-Redux.\n\n### Migrating `connect` to Hooks\n\nA typical legacy component using React-Redux's `connect` API might look like this:\n\n```js title=\"src/features/todos/TodoListItem.js\"\nimport { connect } from 'react-redux'\nimport { bindActionCreators } from 'redux'\nimport {\n  todoToggled,\n  todoDeleted,\n  selectTodoById,\n  selectActiveTodoId,\n} from './todosSlice'\n\n// A `mapState` function, possibly using values from `ownProps`,\n// and returning an object with multiple separate fields inside\nconst mapStateToProps = (state, ownProps) => {\n  return {\n    todo: selectTodoById(state, ownProps.todoId),\n    activeTodoId: selectActiveTodoId(state),\n  }\n}\n\n// Several possible variations on how you might see `mapDispatch` written:\n\n// 1) a separate function, manual wrapping of `dispatch`\nconst mapDispatchToProps = (dispatch) => {\n  return {\n    todoDeleted: (id) => dispatch(todoDeleted(id)),\n    todoToggled: (id) => dispatch(todoToggled(id)),\n  }\n}\n\n// 2) A separate function, wrapping with `bindActionCreators`\nconst mapDispatchToProps2 = (dispatch) => {\n  return bindActionCreators(\n    {\n      todoDeleted,\n      todoToggled,\n    },\n    dispatch,\n  )\n}\n\n// 3) An object full of action creators\nconst mapDispatchToProps3 = {\n  todoDeleted,\n  todoToggled,\n}\n\n// The component, which gets all these fields as props\nfunction TodoListItem({ todo, activeTodoId, todoDeleted, todoToggled }) {\n  // rendering logic here\n}\n\n// Finished with the call to `connect`\nexport default connect(mapStateToProps, mapDispatchToProps)(TodoListItem)\n```\n\n**With the React-Redux hooks API, the `connect` call and `mapState/mapDispatch` arguments are replaced by hooks!**\n\n- Each individual field returned in `mapState` becomes a separate `useSelector` call\n- Each function passed in via `mapDispatch` becomes a separate callback function defined inside the component\n\n```js title=\"src/features/todos/TodoListItem.js\"\nimport { useState } from 'react'\nimport { useSelector, useDispatch } from 'react-redux'\nimport {\n  todoAdded,\n  todoToggled,\n  selectTodoById,\n  selectActiveTodoId,\n} from './todosSlice'\n\nexport function TodoListItem({ todoId }) {\n  // highlight-start\n  // Get the actual `dispatch` function with `useDispatch`\n  const dispatch = useDispatch()\n\n  // Select values from the state with `useSelector`\n  const activeTodoId = useSelector(selectActiveTodoId)\n  // Use prop in scope to select a specific value\n  const todo = useSelector((state) => selectTodoById(state, todoId))\n  // highlight-end\n\n  // Create callback functions that dispatch as needed, with arguments\n  const handleToggleClick = () => {\n    dispatch(todoToggled(todoId))\n  }\n\n  const handleDeleteClick = () => {\n    dispatch(todoDeleted(todoId))\n  }\n\n  // omit rendering logic\n}\n```\n\nOne thing that's different is that `connect` optimized rendering performance by preventing the wrapped component from rendering unless its incoming `stateProps+dispatchProps+ownProps` had changed. The hooks cannot do that, since they're _inside_ the component. If you need to prevent [React's normal recursive rendering behavior](https://blog.isquaredsoftware.com/2020/05/blogged-answers-a-mostly-complete-guide-to-react-rendering-behavior/#standard-render-behavior), wrap the component in `React.memo(MyComponent)` yourself.\n\n### Migrating TypeScript for Components\n\nOne of the major downsides with `connect` is that it is _very_ hard to type correctly, and the type declarations end up being extremely verbose. This is due to it being a Higher-Order Component, and also the amount of flexibility in its API (four arguments, all optional, each with multiple possible overloads and variations).\n\nThe community came up with multiple variations on how to handle this, with varying levels of complexity. On the low end, some usages required typing `state` in `mapState()`, and then calculating the types of all the props for the component:\n\n```ts no-transpile title=\"Simple connect TS example\"\nimport { connect } from 'react-redux'\nimport { RootState } from '../../app/store'\nimport {\n  todoToggled,\n  todoDeleted,\n  selectTodoById,\n  selectActiveTodoId,\n} from './todosSlice'\n\ninterface TodoListItemOwnProps {\n  todoId: string\n}\n\nconst mapStateToProps = (state: RootState, ownProps) => {\n  return {\n    todo: selectTodoById(state, ownProps.todoId),\n    activeTodoId: selectActiveTodoId(state),\n  }\n}\n\nconst mapDispatchToProps = {\n  todoDeleted,\n  todoToggled,\n}\n\ntype TodoListItemProps = TodoListItemOwnProps &\n  ReturnType<typeof mapStateToProps> &\n  typeof mapDispatchToProps\n\nfunction TodoListItem({\n  todo,\n  activeTodoId,\n  todoDeleted,\n  todoToggled,\n}: TodoListItemProps) {}\n\nexport default connect(mapStateToProps, mapDispatchToProps)(TodoListItem)\n```\n\nThe use of `typeof mapDispatch` as an object in particular was dangerous, because it would fail if thunks were included.\n\nOther community-created patterns required significantly more overhead, including declaring `mapDispatch` as a function and calling `bindActionCreators` in order to pass through a `dispatch: Dispatch<RootActions>` type, or manually calculating the types of _all_ the props received by the wrapped component and passing those as generics to `connect`.\n\nOne slightly-better alternative was the `ConnectedProps<T>` type that was added to `@types/react-redux` in v7.x, which enabled inferring the type of _all_ the props that would be passed to the component from `connect`. This did require splitting up the call to `connect` into two parts for the inference to work right:\n\n```ts no-transpile title=\"ConnectedProps<T> TS example\"\nimport { connect, ConnectedProps } from 'react-redux'\nimport { RootState } from '../../app/store'\nimport {\n  todoToggled,\n  todoDeleted,\n  selectTodoById,\n  selectActiveTodoId,\n} from './todosSlice'\n\ninterface TodoListItemOwnProps {\n  todoId: string\n}\n\nconst mapStateToProps = (state: RootState, ownProps) => {\n  return {\n    todo: selectTodoById(state, ownProps.todoId),\n    activeTodoId: selectActiveTodoId(state),\n  }\n}\n\nconst mapDispatchToProps = {\n  todoDeleted,\n  todoToggled,\n}\n\n// Call the first part of `connect` to get the function that accepts the component.\n// This knows the types of the props returned by `mapState/mapDispatch`\nconst connector = connect(mapStateToProps, mapDispatchToProps)\n// The `ConnectedProps<T> util type can extract \"the type of all props from Redux\"\ntype PropsFromRedux = ConnectedProps<typeof connector>\n\n// The final component props are \"the props from Redux\" + \"props from the parent\"\ntype TodoListItemProps = PropsFromRedux & TodoListItemOwnProps\n\n// That type can then be used in the component\nfunction TodoListItem({\n  todo,\n  activeTodoId,\n  todoDeleted,\n  todoToggled,\n}: TodoListItemProps) {}\n\n// And the final wrapped component is generated and exported\nexport default connector(TodoListItem)\n```\n\n**The React-Redux hooks API is _much_ simpler to use with TypeScript!** Instead of dealing with layers of component wrapping, type inference, and generics, the hooks are simple functions that take arguments and return a result. All that you need to pass around are the types for `RootState` and `AppDispatch`.\n\nPer [our standard TypeScript setup and usage guidelines](../tutorials/typescript.md), we specifically teach setting up \"pre-typed\" aliases for the hooks, so that those have the correct types baked in, and only use those pre-typed hooks in the app.\n\nFirst, set up the hooks:\n\n```ts no-transpile title=\"src/app/hooks.ts\"\nimport { useDispatch, useSelector } from 'react-redux'\nimport type { RootState, AppDispatch } from './store'\n\n// highlight-start\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = useDispatch.withTypes<AppDispatch>()\nexport const useAppSelector = useSelector.withTypes<RootState>()\n// highlight-end\n```\n\nThen, use them in your components:\n\n```ts no-transpile title=\"src/features/todos/TodoListItem.tsx\"\nimport { useAppSelector, useAppDispatch } from '../../app/hooks'\nimport {\n  todoToggled,\n  todoDeleted,\n  selectTodoById,\n  selectActiveTodoId,\n} from './todosSlice'\n\ninterface TodoListItemProps {\n  todoId: string\n}\n\nfunction TodoListItem({ todoId }: TodoListItemProps) {\n  // highlight-start\n  // Use the pre-typed hooks in the component\n  const dispatch = useAppDispatch()\n  const activeTodoId = useAppSelector(selectActiveTodoId)\n  const todo = useAppSelector((state) => selectTodoById(state, todoId))\n  // highlight-end\n\n  // omit event handlers and rendering logic\n}\n```\n\n## Further Information\n\nSee these docs pages and blog posts for more details:\n\n- **Tutorials**\n  - [Redux Essentials: Redux Toolkit App Structure](https://redux.js.org/tutorials/essentials/part-2-app-structure)\n  - [Redux Fundamentals: Modern Redux with Redux Toolkit](https://redux.js.org/tutorials/fundamentals/part-8-modern-redux)\n  - [Redux TypeScript Quick Start](../tutorials/typescript.md)\n- **Additional Documentation**\n  - [Why Redux Toolkit is How to use Redux Today](../introduction/why-rtk-is-redux-today.md)\n  - [Redux Style Guide: Best Practices and Recommendations](https://redux.js.org/style-guide/)\n  - [Redux core: Usage with TypeScript](https://redux.js.org/usage/usage-with-typescript)\n  - [Redux Toolkit: Usage with TypeScript](./usage-with-typescript.md)\n- **Articles**\n  - [Presentation: Modern Redux with Redux Toolkit](https://blog.isquaredsoftware.com/2022/06/presentations-modern-redux-rtk/)\n  - [Mark Erikson: Redux Toolkit 1.0 Announcement and development history](https://blog.isquaredsoftware.com/2019/10/redux-toolkit-1.0/)\n  - [Lenz Weber: Do Not Create Action Type Unions](https://phryneas.de/redux-typescript-no-discriminating-union)\n"
  },
  {
    "path": "docs/usage/nextjs.mdx",
    "content": "---\nid: nextjs\ntitle: Redux Toolkit Setup with Next.js\nsidebar_label: Setup with Next.js\nhide_title: true\n---\n\n&nbsp;\n\n# Redux Toolkit Setup with Next.js\n\n:::tip What You'll Learn\n\n- How to set up and use Redux Toolkit with the [Next.js framework](https://nextjs.org/docs)\n\n:::\n\n:::info Prerequisites\n\n- Familiarity with [ES6 syntax and features](https://www.taniarascia.com/es6-syntax-and-feature-overview/)\n- Knowledge of React terminology: [JSX](https://reactjs.org/docs/introducing-jsx.html), [State](https://reactjs.org/docs/state-and-lifecycle.html), [Function Components, Props](https://reactjs.org/docs/components-and-props.html), and [Hooks](https://reactjs.org/docs/hooks-intro.html)\n- Understanding of [Redux terms and concepts](https://redux.js.org/tutorials/fundamentals/part-2-concepts-data-flow)\n- Working through the [Quick Start tutorial](../tutorials/quick-start.mdx) and [TypeScript Quick Start tutorial](../tutorials/typescript.md) is recommended, and ideally the full [Redux Essentials](https://redux.js.org/tutorials/essentials/part-1-overview-concepts) tutorial as well\n\n:::\n\n## Introduction\n\n[Next.js](https://nextjs.org/docs) is a popular server side rendering framework for React that presents some unique challenges for using Redux properly. These challenges include:\n\n- **Per-request safe Redux store creation**: A Next.js server can handle multiple requests simultaneously. This means that the Redux store should be created per request and that the store should not be shared across requests.\n- **SSR-friendly store hydration**: Next.js applications are rendered twice, first on the server and again on the client. Failure to render the same page contents on both the client and the server will result in a \"hydration error\". So the Redux store will have to be initialized on the server and then re-initialized on the client with the same data in order to avoid hydration issues.\n- **SPA routing support**: Next.js supports a hybrid model for client side routing. A customer's first page load will get an SSR result from the server. Subsequent page navigation will be handled by the client. This means that with a singleton store defined in the layout, route-specific data will need to be selectively reset on route navigation, while non-route-specific data will need to be retained in the store.\n- **Server caching friendly**: Recent versions of Next.js (specifically applications using the App Router architecture) support aggressive server caching. The ideal store architecture should be compatible with this caching.\n\nThere are two architectures for a Next.js application: the [Pages Router](https://nextjs.org/docs/pages/building-your-application/routing/pages-and-layouts) and the [App Router](https://nextjs.org/docs/app/building-your-application/routing).\n\nThe Pages Router is the original architecture for Next.js. If you're using the Pages Router, Redux setup is primarily handled by using the [`next-redux-wrapper` library](https://github.com/kirill-konshin/next-redux-wrapper), which integrates a Redux store with the Pages router data fetching methods like `getServerSideProps`.\n\n**This guide will focus on the App Router architecture**, as it is the new default architecture option for Next.js.\n\n### How to Read This Guide\n\nThis page assumes that you already have an existing Next.js application based on the App Router architecture.\n\nIf you want to follow along, you can create a new empty Next project with `npx create-next-app my-app` - the default prompts will set up a new project with the App Router enabled. Then, add `@reduxjs/toolkit` and `react-redux` as dependencies.\n\nYou can also create a new Next+Redux project with `npx create-next-app --example with-redux my-app`, which includes the initial setup pieces described in this page.\n\n## The App Router Architecture and Redux\n\nThe primary new feature of the Next.js App Router is the addition of support for React Server Components (RSCs). RSCs are a special type of React component that only renders on the server, as opposed to \"client\" components that render on **both** the client and the server. RSCs can be defined as `async` functions and return promises during rendering as they make async requests for data to render.\n\nRSCs ability to block for data requests means that with the App Router you no longer have `getServerSideProps` to fetch data for rendering. Any component in the tree can make asynchronous requests for data. While this is very convenient it also means that if you define global variables (like the Redux store) they will be shared across requests. This is a problem because the Redux store could be contaminated with data from other requests.\n\nBased on the architecture of the App Router we have these general recommendations for appropriate use of Redux:\n\n- **No global stores** - Because the Redux store is shared across requests, it should not be defined as a global variable. Instead, the store should be created per request.\n- **RSCs should not read or write the Redux store** - RSCs cannot use hooks or context. They aren't meant to be stateful. Having an RSC read or write values from a global store violates the architecture of the Next.js App Router.\n- **The store should only contain mutable data** - We recommend that you use your Redux sparingly for data intended to be global and mutable.\n\nThese recommendations are specific to applications written with the Next.js App Router. Single Page Applications (SPAs) don't execute on the server and therefore can define stores as global variables. SPAs don't need to worry about RSCs since they don't exist in SPAs. And singleton stores can store whatever data you want.\n\n### Folder Structure\n\nNext apps can be created to have the `/app` folder either at the root, or nested under `/src/app`. Your Redux logic should go in a separate folder, alongside the `/app` folder. It's common to put the Redux logic in a folder named `/lib`, but not required.\n\nThe file and folder structure inside of that `/lib` folder is up to you, but we generally recommend [a \"feature folder\"-based structure](https://redux.js.org/style-guide/#structure-files-as-feature-folders-with-single-file-logic) for the Redux logic.\n\nA typical example might look like:\n\n```\n/app\n  layout.tsx\n  page.tsx\n  StoreProvider.tsx\n/lib\n  store.ts\n  /features\n    /todos\n      todosSlice.ts\n```\n\nWe'll use that approach for this guide.\n\n## Initial Setup\n\nSimilar to the [RTK TypeScript Tutorial](../tutorials/typescript.md), we need to create a file for the Redux store, as well as the inferred `RootState` and `AppDispatch` types.\n\nHowever, Next's multi-page architecture requires some differences from that single-page app setup.\n\n### Creating a Redux Store per Request\n\nThe first change is to move from defining store as a global to defining a `makeStore` function that returns a new store for each request:\n\n```ts title=\"lib/store.ts\"\nimport { configureStore } from '@reduxjs/toolkit'\n\nexport const makeStore = () => {\n  return configureStore({\n    reducer: {},\n  })\n}\n\n// Infer the type of makeStore\nexport type AppStore = ReturnType<typeof makeStore>\n// Infer the `RootState` and `AppDispatch` types from the store itself\nexport type RootState = ReturnType<AppStore['getState']>\nexport type AppDispatch = AppStore['dispatch']\n```\n\nNow we have a function, `makeStore`, that we can use to create a store instance per-request while retaining the strong type safety (if you choose to use TypeScript) that Redux Toolkit provides.\n\nWe don't have a `store` variable exported, but we can infer the `RootState` and `AppDispatch` types from the return type of `makeStore`.\n\nYou'll also want to create and export [pre-typed versions of the React-Redux hooks as well](../tutorials/typescript.md#define-typed-hooks), to simplify usage later:\n\n```ts title=\"lib/hooks.ts\"\n// file: lib/store.ts noEmit\nimport { configureStore } from '@reduxjs/toolkit'\n\nexport const makeStore = () => {\n  return configureStore({\n    reducer: {},\n  })\n}\n\n// Infer the type of makeStore\nexport type AppStore = ReturnType<typeof makeStore>\n// Infer the `RootState` and `AppDispatch` types from the store itself\nexport type RootState = ReturnType<AppStore['getState']>\nexport type AppDispatch = AppStore['dispatch']\n\n/* prettier-ignore */\n\n// file: lib/hooks.ts\nimport { useDispatch, useSelector, useStore } from 'react-redux'\nimport type { RootState, AppDispatch, AppStore } from './store'\n\n// highlight-start\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = useDispatch.withTypes<AppDispatch>()\nexport const useAppSelector = useSelector.withTypes<RootState>()\nexport const useAppStore = useStore.withTypes<AppStore>()\n// highlight-end\n```\n\n### Providing the Store\n\nTo use this new `makeStore` function we need to create a new \"client\" component that will create the store and share it using the React-Redux `Provider` component.\n\n```ts title=\"app/StoreProvider.tsx\"\n// file: lib/store.ts noEmit\nimport { configureStore } from '@reduxjs/toolkit'\n\nexport const makeStore = () => {\n  return configureStore({\n    reducer: {},\n  })\n}\n\n// Infer the type of makeStore\nexport type AppStore = ReturnType<typeof makeStore>\n// Infer the `RootState` and `AppDispatch` types from the store itself\nexport type RootState = ReturnType<AppStore['getState']>\nexport type AppDispatch = AppStore['dispatch']\n\n/* prettier-ignore */\n\n// file: app/StoreProvider.tsx\n'use client'\nimport { useRef } from 'react'\nimport { Provider } from 'react-redux'\n// highlight-start\nimport { makeStore, AppStore } from '../lib/store'\n// highlight-end\n\nexport default function StoreProvider({\n  children,\n}: {\n  children: React.ReactNode\n}) {\n  // highlight-start\n  const storeRef = useRef<AppStore>(undefined)\n  if (!storeRef.current) {\n    // Create the store instance the first time this renders\n    storeRef.current = makeStore()\n  }\n  // highlight-end\n\n  return <Provider store={storeRef.current}>{children}</Provider>\n}\n```\n\nIn this example code we are ensuring that this client component is re-render safe by checking the value of the reference to ensure that the store is only created once. This component will only be rendered once per request on the server, but might be re-rendered multiple times on the client if there are stateful client components located above this component in the tree, or if this component also contains other mutable state that causes a re-render.\n\n:::tip Why Client Components?\n\nAny component that interacts with the Redux store (creating it, providing it, reading from it, or writing to it) needs to be a client component. This is because **accessing the store requires React context, and context is only available in client components.**\n\n:::\n\nThe next step is to **include the `StoreProvider` anywhere in the tree above where the store is used**. You can locate the store in the layout component if all the routes using that layout need the store. Or if the store is only used in a specific route you can create and provide the store in that route handler. In all client components further down the tree, you can use the store exactly as you would normally using the hooks provided by `react-redux`.\n\n### Loading Initial Data\n\nIf you need to initialize the store with data from the parent component, then define that data as a prop on the client `StoreProvider` component and use a Redux action on the slice to set the data in the store as shown below.\n\n```ts title=\"src/app/StoreProvider.tsx\"\n// file: lib/features/counter/counterSlice.ts noEmit\nimport { createSlice } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: {\n    value: 0,\n  },\n  reducers: {\n    initializeCount: (state, action: PayloadAction<number>) => {\n      state.value = action.payload\n    },\n  },\n})\n\nexport const { initializeCount } = counterSlice.actions\nexport default counterSlice.reducer\n\n// file: lib/store.ts noEmit\nimport { configureStore } from '@reduxjs/toolkit'\nimport counterReducer from './features/counter/counterSlice'\n\nexport const makeStore = () =>\n  configureStore({\n    reducer: {\n      counter: counterReducer,\n    },\n  })\n\n// Infer the type of makeStore\nexport type AppStore = ReturnType<typeof makeStore>\n// Infer the `RootState` and `AppDispatch` types from the store itself\nexport type RootState = ReturnType<AppStore['getState']>\n// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}\nexport type AppDispatch = AppStore['dispatch']\n\n/* prettier-ignore */\n\n// file: app/StoreProvider.tsx\n'use client'\nimport { useRef } from 'react'\nimport { Provider } from 'react-redux'\nimport { makeStore, AppStore } from '../lib/store'\n// highlight-start\nimport { initializeCount } from '../lib/features/counter/counterSlice'\n// highlight-end\n\nexport default function StoreProvider({\n  count,\n  children,\n}: {\n  count: number\n  children: React.ReactNode\n}) {\n  const storeRef = useRef<AppStore | null>(null)\n  if (!storeRef.current) {\n    storeRef.current = makeStore()\n    // highlight-start\n    storeRef.current.dispatch(initializeCount(count))\n    // highlight-end\n  }\n\n  return <Provider store={storeRef.current}>{children}</Provider>\n}\n```\n\n## Additional Configuration\n\n### Per-route state\n\nIf you use Next.js's support for client side SPA-style navigation by using `next/navigation`, then when customers navigate from page to page only the route component will be re-rendered. This means that if you have a Redux store created and provided in the layout component it will be preserved across route changes. This is not a problem if you are only using the store for global, mutable data. However, if you are using the store for per-route data then you will need to reset the route-specific data in the store when the route changes.\n\nShown below is a `ProductName` example component that uses the Redux store to manage the mutable name of a product. The `ProductName` component is part of a product detail route. In order to ensure that we have the correct name in the store we need to set the value in the store any time the `ProductName` component is initially rendered, which happens on any route change to the product detail route.\n\n```ts title=\"app/ProductName.tsx\"\n// file: lib/features/product/productSlice.ts noEmit\nimport { createSlice } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\n\nexport interface Product {\n  name: string\n}\n\nconst productSlice = createSlice({\n  name: 'product',\n  initialState: {\n    name: '',\n  },\n  reducers: {\n    initializeProduct: (state, action: PayloadAction<Product>) => {\n      state.name = action.payload.name\n    },\n    setProductName: (state, action: PayloadAction<string>) => {\n      state.name = action.payload\n    },\n  },\n})\n\nexport const { initializeProduct, setProductName } = productSlice.actions\nexport default productSlice.reducer\n\n// file: lib/store.ts noEmit\nimport { configureStore } from '@reduxjs/toolkit'\nimport productReducer from './features/product/productSlice'\n\nexport const makeStore = () =>\n  configureStore({\n    reducer: {\n      product: productReducer,\n    },\n  })\n\n// Infer the type of makeStore\nexport type AppStore = ReturnType<typeof makeStore>\n// Infer the `RootState` and `AppDispatch` types from the store itself\nexport type RootState = ReturnType<AppStore['getState']>\n// Inferred type: {posts: PostsState, comments: CommentsState, users: UsersState}\nexport type AppDispatch = AppStore['dispatch']\n\n// file: lib/hooks.ts noEmit\nimport { useDispatch, useSelector, useStore } from 'react-redux'\nimport type { RootState, AppDispatch, AppStore } from './store'\n\n// highlight-start\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = useDispatch.withTypes<AppDispatch>()\nexport const useAppSelector = useSelector.withTypes<RootState>()\nexport const useAppStore = useStore.withTypes<AppStore>()\n// highlight-end\n\n/* prettier-ignore */\n\n// file: app/ProductName.tsx\n'use client'\nimport { useRef } from 'react'\nimport { useAppSelector, useAppDispatch, useAppStore } from '../lib/hooks'\nimport {\n  initializeProduct,\n  setProductName,\n  Product,\n} from '../lib/features/product/productSlice'\n\nexport default function ProductName({ product }: { product: Product }) {\n  // highlight-start\n  // Initialize the store with the product information\n  const store = useAppStore()\n  const initialized = useRef(false)\n  if (!initialized.current) {\n    store.dispatch(initializeProduct(product))\n    initialized.current = true\n  }\n  const name = useAppSelector((state) => state.product.name)\n  const dispatch = useAppDispatch()\n  // highlight-end\n\n  return (\n    <input\n      value={name}\n      onChange={(e) => dispatch(setProductName(e.target.value))}\n    />\n  )\n}\n```\n\nHere we are using the same intialization pattern as before, of dispatching actions to the store, to set the route-specific data. The `initialized` ref is used to ensure that the store is only initialized once per route change.\n\nIt is worth noting that initializing the store with a `useEffect` would not work because `useEffect` only runs on the client. This would result in hydration errors or flicker because the result from a server side render would not match the result from the client side render.\n\n### Caching\n\nThe App Router has four separate caches including `fetch` request and route caches. The most likely cache to cause issues is the route cache. If you have an application that accepts login you may have routes (e.g. the home route, `/`) that render different data based on the user you will need to disable the route cache by using the [`dynamic` export from the route handler](https://nextjs.org/docs/app/api-reference/file-conventions/route-segment-config#dynamic):\n\n```ts\nexport const dynamic = 'force-dynamic'\n```\n\nAfter a mutation you should also invalidate the cache by calling [`revalidatePath`](https://nextjs.org/docs/app/api-reference/functions/revalidatePath) or [`revalidateTag`](https://nextjs.org/docs/app/api-reference/functions/revalidateTag) as appropriate.\n\n### RTK Query\n\nWe recommend using RTK Query for data fetching **on the client only**. Data fetching on the server should use `fetch` requests from `async` RSCs.\n\nYou can learn more about Redux Toolkit Query in the [Redux Toolkit Query tutorial](https://redux-toolkit.js.org/tutorials/rtk-query).\n\n:::note\n\nIn the future, RTK Query may be able to receive data fetched on the server via React Server Components, but that is a future capability that will require changes to both React and RTK Query.\n\n:::\n\n## Checking Your Work\n\nThere are three key areas that you should check to ensure that you have set up Redux Toolkit correctly:\n\n- **Server Side Rendering** - Check the HTML output of the server to ensure that the data in the Redux store is present in the server side rendered output.\n- **Route Change** - Navigate between pages on the same route as well as between different routes to ensure that route-specific data is initialized properly.\n- **Mutations** - Check that the store is compatible with the Next.js App Router caches by performing a mutation and then navigating away from the route and back to the original route to ensure that the data is updated.\n\n## Overall Recommendations\n\nThe App Router presents a dramatically different archtecture for React applications from either the Pages Router or a SPA application. We recommend rethinking your approach to state management in the light of this new architecture. In SPA applications it's not unusual to have a large store that contains all the data, both mutable and immutable, required to drive the application. For App Router applications we recommend that you should:\n\n- **only use Redux for globally shared, mutable data**\n- use a combination of Next.js state (search params, route parameters, form state, etc.), React context and React hooks for all other state management.\n\n## What You've Learned\n\nThat was a brief overview of how to set up and use Redux Toolkit with the App Router:\n\n:::tip Summary\n\n- **Create a Redux store per request by using `configureStore` wrapped in a `makeStore` function**\n- **Provide the Redux store to the React application components using a \"client\" component**\n- **Only interact with the Redux store in client components** because only client components have access to React context\n- **Use the store as you normally would using the hooks provided in React-Redux**\n- **You need to account for the case where you have per-route state in a global store located in the layout**\n\n## What's Next?\n\nWe recommend going through [**the \"Redux Essentials\" and \"Redux Fundamentals\" tutorials in the Redux core docs**](https://redux.js.org/tutorials/index), which will give you a complete understanding of how Redux works, what Redux Toolkit does, and how to use it correctly.\n"
  },
  {
    "path": "docs/usage/usage-guide.md",
    "content": "---\nid: usage-guide\ntitle: Usage Guide\nsidebar_label: Usage Guide\nhide_title: true\n---\n\n&nbsp;\n\n# Usage Guide\n\nThe Redux core library is deliberately unopinionated. It lets you decide how you want to handle everything, like store setup, what your state contains, and how you want to build your reducers.\n\nThis is good in some cases, because it gives you flexibility, but that flexibility isn't always needed. Sometimes we just want the simplest possible way to get started, with some good default behavior out of the box. Or, maybe you're writing a larger application and finding yourself writing some similar code, and you'd like to cut down on how much of that code you have to write by hand.\n\nAs described in the [Quick Start](../introduction/getting-started.md) page, the goal of Redux Toolkit is to help simplify common Redux use cases. It is not intended to be a complete solution for everything you might want to do with Redux, but it should make a lot of the Redux-related code you need to write a lot simpler (or in some cases, eliminate some of the hand-written code entirely).\n\nRedux Toolkit exports several individual functions that you can use in your application, and adds dependencies on some other packages that are commonly used with Redux (like Reselect and Redux-Thunk). This lets you decide how to use these in your own application, whether it be a brand new project or updating a large existing app.\n\nLet's look at some of the ways that Redux Toolkit can help make your Redux-related code better.\n\n## Store Setup\n\nEvery Redux app needs to configure and create a Redux store. This usually involves several steps:\n\n- Importing or creating the root reducer function\n- Setting up middleware, likely including at least one middleware to handle asynchronous logic\n- Configuring the [Redux DevTools Extension](https://github.com/reduxjs/redux-devtools)\n- Possibly altering some of the logic based on whether the application is being built for development or production\n\n### Manual Store Setup\n\nThe following example from the [Configuring Your Store](https://redux.js.org/recipes/configuring-your-store) page in the Redux docs shows a typical store setup process:\n\n```js\nimport { applyMiddleware, createStore } from 'redux'\nimport { composeWithDevTools } from 'redux-devtools-extension'\nimport thunkMiddleware from 'redux-thunk'\n\nimport monitorReducersEnhancer from './enhancers/monitorReducers'\nimport loggerMiddleware from './middleware/logger'\nimport rootReducer from './reducers'\n\nexport default function configureStore(preloadedState) {\n  const middlewares = [loggerMiddleware, thunkMiddleware]\n  const middlewareEnhancer = applyMiddleware(...middlewares)\n\n  const enhancers = [middlewareEnhancer, monitorReducersEnhancer]\n  const composedEnhancers = composeWithDevTools(...enhancers)\n\n  const store = createStore(rootReducer, preloadedState, composedEnhancers)\n\n  if (process.env.NODE_ENV !== 'production' && module.hot) {\n    module.hot.accept('./reducers', () => store.replaceReducer(rootReducer))\n  }\n\n  return store\n}\n```\n\nThis example is readable, but the process isn't always straightforward:\n\n- The basic Redux `createStore` function takes positional arguments: `(rootReducer, preloadedState, enhancer)`. Sometimes it's easy to forget which parameter is which.\n- The process of setting up middleware and enhancers can be confusing, especially if you're trying to add several pieces of configuration.\n- The Redux DevTools Extension docs initially suggest using [some hand-written code that checks the global namespace to see if the extension is available](https://github.com/zalmoxisus/redux-devtools-extension#11-basic-store). Many users copy and paste those snippets, which make the setup code harder to read.\n\n### Simplifying Store Setup with `configureStore`\n\n`configureStore` helps with those issues by:\n\n- Having an options object with \"named\" parameters, which can be easier to read\n- Letting you provide arrays of middleware and enhancers you want to add to the store, and calling `applyMiddleware` and `compose` for you automatically\n- Enabling the Redux DevTools Extension automatically\n\nIn addition, `configureStore` adds some middleware by default, each with a specific goal:\n\n- [`redux-thunk`](https://github.com/reduxjs/redux-thunk) is the most commonly used middleware for working with both synchronous and async logic outside of components\n- In development, middleware that check for common mistakes like mutating the state or using non-serializable values.\n\nThis means the store setup code itself is a bit shorter and easier to read, and also that you get good default behavior out of the box.\n\nThe simplest way to use it is to just pass the root reducer function as a parameter named `reducer`:\n\n```js\nimport { configureStore } from '@reduxjs/toolkit'\nimport rootReducer from './reducers'\n\nconst store = configureStore({\n  reducer: rootReducer,\n})\n\nexport default store\n```\n\nYou can also pass an object full of [\"slice reducers\"](https://redux.js.org/recipes/structuring-reducers/splitting-reducer-logic), and `configureStore` will call [`combineReducers`](https://redux.js.org/api/combinereducers) for you:\n\n```js\nimport { configureStore } from '@reduxjs/toolkit'\n// highlight-start\nimport usersReducer from './usersReducer'\nimport postsReducer from './postsReducer'\n\nconst store = configureStore({\n  reducer: {\n    users: usersReducer,\n    posts: postsReducer,\n  },\n})\n// highlight-end\n\nexport default store\n```\n\nNote that this only works for one level of reducers. If you want to nest reducers, you'll need to call `combineReducers` yourself to handle the nesting.\n\nIf you need to customize the store setup, you can pass additional options. Here's what the hot reloading example might look like using Redux Toolkit:\n\n```js\nimport { configureStore } from '@reduxjs/toolkit'\n\nimport monitorReducersEnhancer from './enhancers/monitorReducers'\nimport loggerMiddleware from './middleware/logger'\nimport rootReducer from './reducers'\n\nexport default function configureAppStore(preloadedState) {\n  const store = configureStore({\n    reducer: rootReducer,\n    middleware: (getDefaultMiddleware) =>\n      getDefaultMiddleware().concat(loggerMiddleware),\n    preloadedState,\n    enhancers: (getDefaultEnhancers) =>\n      getDefaultEnhancers().concat(monitorReducersEnhancer),\n  })\n\n  if (process.env.NODE_ENV !== 'production' && module.hot) {\n    module.hot.accept('./reducers', () => store.replaceReducer(rootReducer))\n  }\n\n  return store\n}\n```\n\nIf you provide the `middleware` argument, `configureStore` will only use whatever middleware you've listed.\nIf you want to have some custom middleware _and_ the defaults all together, you can use the callback notation,\ncall [`getDefaultMiddleware`](../api/getDefaultMiddleware.mdx) and include the results in the `middleware` array you return.\n\n## Writing Reducers\n\n[Reducers](https://redux.js.org/basics/reducers) are the most important Redux concept. A typical reducer function needs to:\n\n- Look at the `type` field of the action object to see how it should respond\n- Update its state immutably, by making copies of the parts of the state that need to change and only modifying those copies\n\nWhile you can [use any conditional logic you want](https://blog.isquaredsoftware.com/2017/05/idiomatic-redux-tao-of-redux-part-2/#switch-statements) in a reducer, the most common approach is a `switch` statement, because it's a straightforward way to handle multiple possible values for a single field. However, many people don't like switch statements. The Redux docs show an example of [writing a function that acts as a lookup table based on action types](https://redux.js.org/recipes/reducing-boilerplate#generating-reducers), but leave it up to users to customize that function themselves.\n\nThe other common pain points around writing reducers have to do with updating state immutably. JavaScript is a mutable language, [updating nested immutable data by hand is hard](https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns), and it's easy to make mistakes.\n\n### Simplifying Reducers with `createReducer`\n\nSince the \"lookup table\" approach is popular, Redux Toolkit includes a `createReducer` function similar to the one shown in the Redux docs. However, our `createReducer` utility has some special \"magic\" that makes it even better. It uses the [Immer](https://github.com/mweststrate/immer) library internally, which lets you write code that \"mutates\" some data, but actually applies the updates immutably. This makes it effectively impossible to accidentally mutate state in a reducer.\n\nIn general, any Redux reducer that uses a `switch` statement can be converted to use `createReducer` directly. Each `case` in the switch becomes a key in the object passed to `createReducer`. Immutable update logic, like spreading objects or copying arrays, can probably be converted to direct \"mutation\". It's also fine to keep the immutable updates as-is and return the updated copies, too.\n\nHere's some examples of how you can use `createReducer`. We'll start with a typical \"todo list\" reducer that uses switch statements and immutable updates:\n\n```js\nfunction todosReducer(state = [], action) {\n  switch (action.type) {\n    case 'ADD_TODO': {\n      return state.concat(action.payload)\n    }\n    case 'TOGGLE_TODO': {\n      const { index } = action.payload\n      return state.map((todo, i) => {\n        if (i !== index) return todo\n\n        return {\n          ...todo,\n          completed: !todo.completed,\n        }\n      })\n    }\n    case 'REMOVE_TODO': {\n      return state.filter((todo, i) => i !== action.payload.index)\n    }\n    default:\n      return state\n  }\n}\n```\n\nNotice that we specifically call `state.concat()` to return a copied array with the new todo entry, `state.map()` to return a copied array for the toggle case, and use the object spread operator to make a copy of the todo that needs to be updated.\n\nWith `createReducer`, we can shorten that example considerably:\n\n```js\nconst todosReducer = createReducer([], (builder) => {\n  builder\n    .addCase('ADD_TODO', (state, action) => {\n      // \"mutate\" the array by calling push()\n      state.push(action.payload)\n    })\n    .addCase('TOGGLE_TODO', (state, action) => {\n      const todo = state[action.payload.index]\n      // \"mutate\" the object by overwriting a field\n      todo.completed = !todo.completed\n    })\n    .addCase('REMOVE_TODO', (state, action) => {\n      // Can still return an immutably-updated value if we want to\n      return state.filter((todo, i) => i !== action.payload.index)\n    })\n})\n```\n\nThe ability to \"mutate\" the state is especially helpful when trying to update deeply nested state. This complex and painful code:\n\n```js\ncase \"UPDATE_VALUE\":\n  return {\n    ...state,\n    first: {\n      ...state.first,\n      second: {\n        ...state.first.second,\n        [action.someId]: {\n          ...state.first.second[action.someId],\n          fourth: action.someValue\n        }\n      }\n    }\n  }\n```\n\nCan be simplified down to just:\n\n```js\nupdateValue(state, action) {\n    const {someId, someValue} = action.payload;\n    state.first.second[someId].fourth = someValue;\n}\n```\n\nMuch better!\n\n### Considerations for Using `createReducer`\n\nWhile the Redux Toolkit `createReducer` function can be really helpful, keep in mind that:\n\n- The \"mutative\" code only works correctly inside of our `createReducer` function\n- Immer won't let you mix \"mutating\" the draft state and also returning a new state value\n\nSee the [`createReducer` API reference](../api/createReducer.mdx) for more details.\n\n## Writing Action Creators\n\nRedux encourages you to [write \"action creator\" functions](https://blog.isquaredsoftware.com/2016/10/idiomatic-redux-why-use-action-creators/) that encapsulate the process of creating an action object. While this is not strictly required, it's a standard part of Redux usage.\n\nMost action creators are very simple. They take some parameters, and return an action object with a specific `type` field and the parameters inside the action. These parameters are typically put in a field called `payload`, which is part of the [Flux Standard Action](https://github.com/redux-utilities/flux-standard-action) convention for organizing the contents of action objects. A typical action creator might look like:\n\n```js\nfunction addTodo(text) {\n  return {\n    type: 'ADD_TODO',\n    payload: { text },\n  }\n}\n```\n\n### Defining Action Creators with `createAction`\n\nWriting action creators by hand can get tedious. Redux Toolkit provides a function called `createAction`, which simply generates an action creator that uses the given action type, and turns its argument into the `payload` field:\n\n```js\nconst addTodo = createAction('ADD_TODO')\naddTodo({ text: 'Buy milk' })\n// {type : \"ADD_TODO\", payload : {text : \"Buy milk\"}})\n```\n\n`createAction` also accepts a \"prepare callback\" argument, which allows you to customize the resulting `payload` field and optionally add a `meta` field. See the [`createAction` API reference](../api/createAction.mdx#using-prepare-callbacks-to-customize-action-contents) for details on defining action creators with a prepare callback.\n\n### Using Action Creators as Action Types\n\nRedux reducers need to look for specific action types to determine how they should update their state. Normally, this is done by defining action type strings and action creator functions separately. Redux Toolkit `createAction` function make this easier, by defining the action type as a `type` field on the action creator.\n\n```js\nconst actionCreator = createAction('SOME_ACTION_TYPE')\n\nconsole.log(actionCreator.type)\n// \"SOME_ACTION_TYPE\"\n\nconst reducer = createReducer({}, (builder) => {\n  // if you use TypeScript, the action type will be correctly inferred\n  builder.addCase(actionCreator, (state, action) => {})\n\n  // Or, you can reference the .type field:\n  // if using TypeScript, the action type cannot be inferred that way\n  builder.addCase(actionCreator.type, (state, action) => {})\n})\n```\n\nThis means you don't have to write or use a separate action type variable, or repeat the name and value of an action type like `const SOME_ACTION_TYPE = \"SOME_ACTION_TYPE\"`.\n\nIf you want to use one of these action creators in a switch statement, you need to reference `actionCreator.type` yourself:\n\n```js\nconst actionCreator = createAction('SOME_ACTION_TYPE')\n\nconst reducer = (state = {}, action) => {\n  switch (action.type) {\n    // ERROR: this won't work correctly!\n    case actionCreator: {\n      break\n    }\n    // CORRECT: this will work as expected\n    case actionCreator.type: {\n      break\n    }\n  }\n}\n```\n\n## Creating Slices of State\n\nRedux state is typically organized into \"slices\", defined by the reducers that are passed to `combineReducers`:\n\n```js\nimport { combineReducers } from 'redux'\nimport usersReducer from './usersReducer'\nimport postsReducer from './postsReducer'\n\nconst rootReducer = combineReducers({\n  users: usersReducer,\n  posts: postsReducer,\n})\n```\n\nIn this example, both `users` and `posts` would be considered \"slices\". Both of the reducers:\n\n- \"Own\" a piece of state, including what the initial value is\n- Define how that state is updated\n- Define which specific actions result in state updates\n\nThe common approach is to define a slice's reducer function in its own file, and the action creators in a second file. Because both functions need to refer to the same action types, those are usually defined in a third file and imported in both places:\n\n```js\n// postsConstants.js\nconst CREATE_POST = 'CREATE_POST'\nconst UPDATE_POST = 'UPDATE_POST'\nconst DELETE_POST = 'DELETE_POST'\n\n// postsActions.js\nimport { CREATE_POST, UPDATE_POST, DELETE_POST } from './postConstants'\n\nexport function addPost(id, title) {\n  return {\n    type: CREATE_POST,\n    payload: { id, title },\n  }\n}\n\n// postsReducer.js\nimport { CREATE_POST, UPDATE_POST, DELETE_POST } from './postConstants'\n\nconst initialState = []\n\nexport default function postsReducer(state = initialState, action) {\n  switch (action.type) {\n    case CREATE_POST: {\n      // omit implementation\n    }\n    default:\n      return state\n  }\n}\n```\n\nThe only truly necessary part here is the reducer itself. Consider the other parts:\n\n- We could have written the action types as inline strings in both places\n- The action creators are good, but they're not _required_ to use Redux - a component could skip supplying a `mapDispatch` argument to `connect`, and just call `this.props.dispatch({type : \"CREATE_POST\", payload : {id : 123, title : \"Hello World\"}})` itself\n- The only reason we're even writing multiple files is because it's common to separate code by what it does\n\nThe [\"ducks\" file structure](https://github.com/erikras/ducks-modular-redux) proposes putting all of your Redux-related logic for a given slice into a single file, like this:\n\n```js\n// postsDuck.js\nconst CREATE_POST = 'CREATE_POST'\nconst UPDATE_POST = 'UPDATE_POST'\nconst DELETE_POST = 'DELETE_POST'\n\nexport function addPost(id, title) {\n  return {\n    type: CREATE_POST,\n    payload: { id, title },\n  }\n}\n\nconst initialState = []\n\nexport default function postsReducer(state = initialState, action) {\n  switch (action.type) {\n    case CREATE_POST: {\n      // Omit actual code\n      break\n    }\n    default:\n      return state\n  }\n}\n```\n\nThat simplifies things because we don't need to have multiple files, and we can remove the redundant imports of the action type constants. But, we still have to write the action types and the action creators by hand.\n\n### Defining Functions in Objects\n\nIn modern JavaScript, there are several legal ways to define both keys and functions in an object (and this isn't specific to Redux), and you can mix and match different key definitions and function definitions. For example, these are all legal ways to define a function inside an object:\n\n```js\nconst keyName = \"ADD_TODO4\";\n\nconst reducerObject = {\n\t// Explicit quotes for the key name, arrow function for the reducer\n\t\"ADD_TODO1\" : (state, action) => { }\n\n\t// Bare key with no quotes, function keyword\n\tADD_TODO2 : function(state, action){  }\n\n\t// Object literal function shorthand\n\tADD_TODO3(state, action) { }\n\n\t// Computed property\n\t[keyName] : (state, action) => { }\n}\n```\n\nUsing the [\"object literal function shorthand\"](https://www.sitepoint.com/es6-enhanced-object-literals/) is probably the shortest code, but feel free to use whichever of those approaches you want.\n\n### Simplifying Slices with `createSlice`\n\nTo simplify this process, Redux Toolkit includes a `createSlice` function that will auto-generate the action types and action creators for you, based on the names of the reducer functions you provide.\n\nHere's how that posts example would look with `createSlice`:\n\n```js\nconst postsSlice = createSlice({\n  name: 'posts',\n  initialState: [],\n  reducers: {\n    createPost(state, action) {},\n    updatePost(state, action) {},\n    deletePost(state, action) {},\n  },\n})\n\nconsole.log(postsSlice)\n/*\n{\n    name: 'posts',\n    actions : {\n        createPost,\n        updatePost,\n        deletePost,\n    },\n    reducer\n}\n*/\n\nconst { createPost } = postsSlice.actions\n\nconsole.log(createPost({ id: 123, title: 'Hello World' }))\n// {type : \"posts/createPost\", payload : {id : 123, title : \"Hello World\"}}\n```\n\n`createSlice` looked at all of the functions that were defined in the `reducers` field, and for every \"case reducer\" function provided, generates an action creator that uses the name of the reducer as the action type itself. So, the `createPost` reducer became an action type of `\"posts/createPost\"`, and the `createPost()` action creator will return an action with that type.\n\n### Exporting and Using Slices\n\nMost of the time, you'll want to define a slice, and export its action creators and reducers. The recommended way to do this is using ES6 destructuring and export syntax:\n\n```js\nconst postsSlice = createSlice({\n  name: 'posts',\n  initialState: [],\n  reducers: {\n    createPost(state, action) {},\n    updatePost(state, action) {},\n    deletePost(state, action) {},\n  },\n})\n\n// Extract the action creators object and the reducer\nconst { actions, reducer } = postsSlice\n// Extract and export each action creator by name\nexport const { createPost, updatePost, deletePost } = actions\n// Export the reducer, either as a default or named export\nexport default reducer\n```\n\nYou could also just export the slice object itself directly if you prefer.\n\nSlices defined this way are very similar in concept to the [\"Redux Ducks\" pattern](https://github.com/erikras/ducks-modular-redux) for defining and exporting action creators and reducers. However, there are a couple potential downsides to be aware of when importing and exporting slices.\n\nFirst, **Redux action types are not meant to be exclusive to a single slice**. Conceptually, each slice reducer \"owns\" its own piece of the Redux state, but it should be able to listen to any action type and update its state appropriately. For example, many different slices might want to respond to a \"user logged out\" action by clearing data or resetting back to initial state values. Keep that in mind as you design your state shape and create your slices.\n\nSecond, **JS modules can have \"circular reference\" problems if two modules try to import each other**. This can result in imports being undefined, which will likely break the code that needs that import. Specifically in the case of \"ducks\" or slices, this can occur if slices defined in two different files both want to respond to actions defined in the other file.\n\nThis CodeSandbox example demonstrates the problem:\n\n<iframe src=\"https://codesandbox.io/embed/rw7ppj4z0m/?runonclick=1\" style={{ width: '100%', height: '500px', border: 0, borderRadius: '4px', overflow: 'hidden' }} sandbox=\"allow-modals allow-forms allow-popups allow-scripts allow-same-origin\"></iframe>\n\nIf you encounter this, you may need to restructure your code in a way that avoids the circular references. This will usually require extracting shared code to a separate common file that both modules can import and use. In this case, you might define some common action types in a separate file using `createAction`, import those action creators into each slice file, and handle them using the `extraReducers` argument.\n\nThe article [How to fix circular dependency issues in JS](https://medium.com/visual-development/how-to-fix-nasty-circular-dependency-issues-once-and-for-all-in-javascript-typescript-a04c987cf0de) has additional info and examples that can help with this issue.\n\n## Asynchronous Logic and Data Fetching\n\n### Using Middleware to Enable Async Logic\n\nBy itself, a Redux store doesn't know anything about async logic. It only knows how to synchronously dispatch actions, update the state by calling the root reducer function, and notify the UI that something has changed. Any asynchronicity has to happen outside the store.\n\nBut, what if you want to have async logic interact with the store by dispatching or checking the current store state? That's where [Redux middleware](https://redux.js.org/advanced/middleware) come in. They extend the store, and allow you to:\n\n- Execute extra logic when any action is dispatched (such as logging the action and state)\n- Pause, modify, delay, replace, or halt dispatched actions\n- Write extra code that has access to `dispatch` and `getState`\n- Teach `dispatch` how to accept other values besides plain action objects, such as functions and promises, by intercepting them and dispatching real action objects instead\n\n[The most common reason to use middleware is to allow different kinds of async logic to interact with the store](https://redux.js.org/faq/actions#how-can-i-represent-side-effects-such-as-ajax-calls-why-do-we-need-things-like-action-creators-thunks-and-middleware-to-do-async-behavior). This allows you to write code that can dispatch actions and check the store state, while keeping that logic separate from your UI.\n\nThere are many kinds of async middleware for Redux, and each lets you write your logic using different syntax. The most common async middleware are:\n\n- [`redux-thunk`](https://github.com/reduxjs/redux-thunk), which lets you write plain functions that may contain async logic directly\n- [`redux-saga`](https://github.com/redux-saga/redux-saga), which uses generator functions that return descriptions of behavior so they can be executed by the middleware\n- [`redux-observable`](https://github.com/redux-observable/redux-observable/), which uses the RxJS observable library to create chains of functions that process actions\n\n[Each of these libraries has different use cases and tradeoffs](https://redux.js.org/faq/actions#what-async-middleware-should-i-use-how-do-you-decide-between-thunks-sagas-observables-or-something-else).\n\n:::tip\n\nRedux Toolkit's [**RTK Query data fetching API**](../rtk-query/overview.md) is a purpose built data fetching and caching solution for Redux apps, and can **eliminate the need to write _any_ thunks or reducers to manage data fetching**. We encourage you to try it out and see if it can help simplify the data fetching code in your own apps!\n\n:::\n\nIf you do need to write data fetching logic yourself, we recommend [using the Redux Thunk middleware as the standard approach](https://github.com/reduxjs/redux-thunk), as it is sufficient for most typical use cases (such as basic AJAX data fetching). In addition, use of the `async/await` syntax in thunks makes them easier to read.\n\n**The Redux Toolkit `configureStore` function [automatically sets up the thunk middleware by default](../api/getDefaultMiddleware.mdx)**, so you can immediately start writing thunks as part of your application code.\n\n### Defining Async Logic in Slices\n\nRedux Toolkit does not currently provide any special APIs or syntax for writing thunk functions. In particular, **they cannot be defined as part of a `createSlice()` call**. You have to write them separate from the reducer logic, exactly the same as with plain Redux code.\n\nThunks typically dispatch plain actions, such as `dispatch(dataLoaded(response.data))`.\n\nMany Redux apps have structured their code using a \"folder-by-type\" approach. In that structure, thunk action creators are usually defined in an \"actions\" file, alongside the plain action creators.\n\nBecause we don't have separate \"actions\" files, **it makes sense to write these thunks directly in our \"slice\" files**. That way, they have access to the plain action creators from the slice, and it's easy to find where the thunk function lives.\n\nA typical slice file that includes thunks would look like this:\n\n```js\n// First, define the reducer and action creators via `createSlice`\nconst usersSlice = createSlice({\n  name: 'users',\n  initialState: {\n    loading: 'idle',\n    users: [],\n  },\n  reducers: {\n    usersLoading(state, action) {\n      // Use a \"state machine\" approach for loading state instead of booleans\n      if (state.loading === 'idle') {\n        state.loading = 'pending'\n      }\n    },\n    usersReceived(state, action) {\n      if (state.loading === 'pending') {\n        state.loading = 'idle'\n        state.users = action.payload\n      }\n    },\n  },\n})\n\n// Destructure and export the plain action creators\nexport const { usersLoading, usersReceived } = usersSlice.actions\n\n// Define a thunk that dispatches those action creators\nconst fetchUsers = () => async (dispatch) => {\n  dispatch(usersLoading())\n  const response = await usersAPI.fetchAll()\n  dispatch(usersReceived(response.data))\n}\n```\n\n### Redux Data Fetching Patterns\n\nData fetching logic for Redux typically follows a predictable pattern:\n\n- A \"start\" action is dispatched before the request to indicate that the request is in progress. This may be used to track loading state, to allow skipping duplicate requests, or show loading indicators in the UI.\n- The async request is made\n- Depending on the request result, the async logic dispatches either a \"success\" action containing the result data, or a \"failure\" action containing error details. The reducer logic clears the loading state in both cases, and either processes the result data from the success case, or stores the error value for potential display.\n\nThese steps are not required, but are [recommended in the Redux tutorials as a suggested pattern](https://redux.js.org/advanced/async-actions).\n\nA typical implementation might look like:\n\n```js\nconst getRepoDetailsStarted = () => ({\n  type: 'repoDetails/fetchStarted',\n})\nconst getRepoDetailsSuccess = (repoDetails) => ({\n  type: 'repoDetails/fetchSucceeded',\n  payload: repoDetails,\n})\nconst getRepoDetailsFailed = (error) => ({\n  type: 'repoDetails/fetchFailed',\n  error,\n})\nconst fetchIssuesCount = (org, repo) => async (dispatch) => {\n  dispatch(getRepoDetailsStarted())\n  try {\n    const repoDetails = await getRepoDetails(org, repo)\n    dispatch(getRepoDetailsSuccess(repoDetails))\n  } catch (err) {\n    dispatch(getRepoDetailsFailed(err.toString()))\n  }\n}\n```\n\nHowever, writing code using this approach is tedious. Each separate type of request needs repeated similar implementation:\n\n- Unique action types need to be defined for the three different cases\n- Each of those action types usually has a corresponding action creator function\n- A thunk has to be written that dispatches the correct actions in the right sequence\n\n`createAsyncThunk` abstracts this pattern by generating the action types and action creators and generating a thunk that dispatches those actions.\n\n### Async Requests with `createAsyncThunk`\n\nAs a developer, you are probably most concerned with the actual logic needed to make an API request, what action type names show up in the Redux action history log, and how your reducers should process the fetched data. The repetitive details of defining the multiple action types and dispatching the actions in the right sequence aren't what matters.\n\n`createAsyncThunk` simplifies this process - you only need to provide a string for the action type prefix and a payload creator callback that does the actual async logic and returns a promise with the result. In return, `createAsyncThunk` will give you a thunk that will take care of dispatching the right actions based on the promise you return, and action types that you can handle in your reducers:\n\n```js {5-11,22-25,30}\nimport { createAsyncThunk, createSlice } from '@reduxjs/toolkit'\nimport { userAPI } from './userAPI'\n\n// First, create the thunk\nconst fetchUserById = createAsyncThunk(\n  'users/fetchByIdStatus',\n  async (userId, thunkAPI) => {\n    const response = await userAPI.fetchById(userId)\n    return response.data\n  },\n)\n\n// Then, handle actions in your reducers:\nconst usersSlice = createSlice({\n  name: 'users',\n  initialState: { entities: [], loading: 'idle' },\n  reducers: {\n    // standard reducer logic, with auto-generated action types per reducer\n  },\n  extraReducers: (builder) => {\n    // Add reducers for additional action types here, and handle loading state as needed\n    builder.addCase(fetchUserById.fulfilled, (state, action) => {\n      // Add user to the state array\n      state.entities.push(action.payload)\n    })\n  },\n})\n\n// Later, dispatch the thunk as needed in the app\ndispatch(fetchUserById(123))\n```\n\nThe thunk action creator accepts a single argument, which will be passed as the first argument to your payload creator callback.\n\nThe payload creator will also receive a `thunkAPI` object containing the parameters that are normally passed to a standard Redux thunk function, as well as an auto-generated unique random request ID string and an [`AbortController.signal` object](https://developer.mozilla.org/en-US/docs/Web/API/AbortController/signal):\n\n```ts\ninterface ThunkAPI {\n  dispatch: Function\n  getState: Function\n  extra?: any\n  requestId: string\n  signal: AbortSignal\n}\n```\n\nYou can use any of these as needed inside the payload callback to determine what the final result should be.\n\n## Managing Normalized Data\n\nMost applications typically deal with data that is deeply nested or relational. The goal of normalizing data is to efficiently organize the data in your state. This is typically done by storing collections as objects with the key of an `id`, while storing a sorted array of those `ids`. For a more in-depth explanation and further examples, there is a great reference in the [Redux docs page on \"Normalizing State Shape\"](https://redux.js.org/recipes/structuring-reducers/normalizing-state-shape).\n\n### Normalizing by hand\n\nNormalizing data doesn't require any special libraries. Here's a basic example of how you might normalize the response from a `fetchAll` API request that returns data in the shape of `{ users: [{id: 1, first_name: 'normalized', last_name: 'person'}] }`, using some hand-written logic:\n\n```js\nimport { createSlice, createAsyncThunk } from '@reduxjs/toolkit'\nimport userAPI from './userAPI'\n\nexport const fetchUsers = createAsyncThunk('users/fetchAll', async () => {\n  const response = await userAPI.fetchAll()\n  return response.data\n})\n\nexport const slice = createSlice({\n  name: 'users',\n  initialState: {\n    ids: [],\n    entities: {},\n  },\n  reducers: {},\n  extraReducers: (builder) => {\n    builder.addCase(fetchUsers.fulfilled, (state, action) => {\n      // reduce the collection by the id property into a shape of { 1: { ...user }}\n      const byId = action.payload.users.reduce((byId, user) => {\n        byId[user.id] = user\n        return byId\n      }, {})\n      state.entities = byId\n      state.ids = Object.keys(byId)\n    })\n  },\n})\n```\n\nAlthough we're capable of writing this code, it does become repetitive, especially if you're handling multiple types of data. In addition, this example only handles loading entries into the state, not updating them.\n\n### Normalizing with `normalizr`\n\n[`normalizr`](https://github.com/paularmstrong/normalizr) is a popular existing library for normalizing data. You can use it on its own without Redux, but it is very commonly used with Redux. The typical usage is to format collections from an API response and then process them in your reducers.\n\n```js\nimport { createSlice, createAsyncThunk } from '@reduxjs/toolkit'\nimport { normalize, schema } from 'normalizr'\n\nimport userAPI from './userAPI'\n\nconst userEntity = new schema.Entity('users')\n\nexport const fetchUsers = createAsyncThunk('users/fetchAll', async () => {\n  const response = await userAPI.fetchAll()\n  // Normalize the data before passing it to our reducer\n  const normalized = normalize(response.data, [userEntity])\n  return normalized.entities\n})\n\nexport const slice = createSlice({\n  name: 'users',\n  initialState: {\n    ids: [],\n    entities: {},\n  },\n  reducers: {},\n  extraReducers: (builder) => {\n    builder.addCase(fetchUsers.fulfilled, (state, action) => {\n      state.entities = action.payload.users\n      state.ids = Object.keys(action.payload.users)\n    })\n  },\n})\n```\n\nAs with the hand-written version, this doesn't handle adding additional entries into the state, or updating them later - it's just loading in everything that was received.\n\n### Normalizing with `createEntityAdapter`\n\nRedux Toolkit's `createEntityAdapter` API provides a standardized way to store your data in a slice by taking a collection and putting it into the shape of `{ ids: [], entities: {} }`. Along with this predefined state shape, it generates a set of reducer functions and selectors that know how to work with the data.\n\n```js\nimport {\n  createSlice,\n  createAsyncThunk,\n  createEntityAdapter,\n} from '@reduxjs/toolkit'\nimport userAPI from './userAPI'\n\nexport const fetchUsers = createAsyncThunk('users/fetchAll', async () => {\n  const response = await userAPI.fetchAll()\n  // In this case, `response.data` would be:\n  // [{id: 1, first_name: 'Example', last_name: 'User'}]\n  return response.data\n})\n\nexport const updateUser = createAsyncThunk('users/updateOne', async (arg) => {\n  const response = await userAPI.updateUser(arg)\n  // In this case, `response.data` would be:\n  // { id: 1, first_name: 'Example', last_name: 'UpdatedLastName'}\n  return response.data\n})\n\nexport const usersAdapter = createEntityAdapter()\n\n// By default, `createEntityAdapter` gives you `{ ids: [], entities: {} }`.\n// If you want to track 'loading' or other keys, you would initialize them here:\n// `getInitialState({ loading: false, activeRequestId: null })`\nconst initialState = usersAdapter.getInitialState()\n\nexport const slice = createSlice({\n  name: 'users',\n  initialState,\n  reducers: {\n    removeUser: usersAdapter.removeOne,\n  },\n  extraReducers: (builder) => {\n    builder.addCase(fetchUsers.fulfilled, usersAdapter.upsertMany)\n    builder.addCase(updateUser.fulfilled, (state, { payload }) => {\n      const { id, ...changes } = payload\n      usersAdapter.updateOne(state, { id, changes })\n    })\n  },\n})\n\nconst reducer = slice.reducer\nexport default reducer\n\nexport const { removeUser } = slice.actions\n```\n\nYou can [view the full code of this example usage on CodeSandbox](https://codesandbox.io/s/rtk-entities-basic-example-1xubt)\n\n### Using `createEntityAdapter` with Normalization Libraries\n\nIf you're already using `normalizr` or another normalization library, you could consider using it along with `createEntityAdapter`. To expand on the examples above, here is a demonstration of how we could use `normalizr` to format a payload, then leverage the utilities `createEntityAdapter` provides.\n\nBy default, the `setAll`, `addMany`, and `upsertMany` CRUD methods expect an array of entities. However, they also allow you to pass in an object that is in the shape of `{ 1: { id: 1, ... }}` as an alternative, which makes it easier to insert pre-normalized data.\n\n```js\n// features/articles/articlesSlice.js\nimport {\n  createSlice,\n  createEntityAdapter,\n  createAsyncThunk,\n  createSelector,\n} from '@reduxjs/toolkit'\nimport fakeAPI from '../../services/fakeAPI'\nimport { normalize, schema } from 'normalizr'\n\n// Define normalizr entity schemas\nexport const userEntity = new schema.Entity('users')\nexport const commentEntity = new schema.Entity('comments', {\n  commenter: userEntity,\n})\nexport const articleEntity = new schema.Entity('articles', {\n  author: userEntity,\n  comments: [commentEntity],\n})\n\nconst articlesAdapter = createEntityAdapter()\n\nexport const fetchArticle = createAsyncThunk(\n  'articles/fetchArticle',\n  async (id) => {\n    const data = await fakeAPI.articles.show(id)\n    // Normalize the data so reducers can load a predictable payload, like:\n    // `action.payload = { users: {}, articles: {}, comments: {} }`\n    const normalized = normalize(data, articleEntity)\n    return normalized.entities\n  }\n)\n\nexport const slice = createSlice({\n  name: 'articles',\n  initialState: articlesAdapter.getInitialState(),\n  reducers: {},\n  extraReducers: (builder) => {\n    builder.addCase(fetchArticle.fulfilled, (state, action) => {\n      // Handle the fetch result by inserting the articles here\n      articlesAdapter.upsertMany(state, action.payload.articles)\n    })\n  },\n})\n\nconst reducer = slice.reducer\nexport default reducer\n\n// features/users/usersSlice.js\n\nimport { createSlice, createEntityAdapter } from '@reduxjs/toolkit'\nimport { fetchArticle } from '../articles/articlesSlice'\n\nconst usersAdapter = createEntityAdapter()\n\nexport const slice = createSlice({\n  name: 'users',\n  initialState: usersAdapter.getInitialState(),\n  reducers: {},\n  extraReducers: (builder) => {\n    builder.addCase(fetchArticle.fulfilled, (state, action) => {\n      // And handle the same fetch result by inserting the users here\n      usersAdapter.upsertMany(state, action.payload.users)\n    })\n  },\n})\n\nconst reducer = slice.reducer\nexport default reducer\n\n// features/comments/commentsSlice.js\n\nimport { createSlice, createEntityAdapter } from '@reduxjs/toolkit'\nimport { fetchArticle } from '../articles/articlesSlice'\n\nconst commentsAdapter = createEntityAdapter()\n\nexport const slice = createSlice({\n  name: 'comments',\n  initialState: commentsAdapter.getInitialState(),\n  reducers: {},\n  extraReducers: (builder) => {\n    builder.addCase(fetchArticle.fulfilled, (state, action) => {\n      // Same for the comments\n      commentsAdapter.upsertMany(state, action.payload.comments)\n    })\n  },\n})\n\nconst reducer = slice.reducer\nexport default reducer\n```\n\nYou can [view the full code of this example `normalizr` usage on CodeSandbox](https://codesandbox.io/s/rtk-entities-basic-example-with-normalizr-bm3ie)\n\n### Using selectors with `createEntityAdapter`\n\nThe entity adapter provides a selector factory that generates the most common selectors for you. Taking the examples above, we can add selectors to our `usersSlice` like this:\n\n```js\n// Rename the exports for readability in component usage\nexport const {\n  selectById: selectUserById,\n  selectIds: selectUserIds,\n  selectEntities: selectUserEntities,\n  selectAll: selectAllUsers,\n  selectTotal: selectTotalUsers,\n} = usersAdapter.getSelectors((state) => state.users)\n```\n\nYou could then use these selectors in a component like this:\n\n```js\nimport React from 'react'\nimport { useSelector } from 'react-redux'\nimport { selectTotalUsers, selectAllUsers } from './usersSlice'\n\nimport styles from './UsersList.module.css'\n\nexport function UsersList() {\n  const count = useSelector(selectTotalUsers)\n  const users = useSelector(selectAllUsers)\n\n  return (\n    <div>\n      <div className={styles.row}>\n        There are <span className={styles.value}>{count}</span> users.{' '}\n        {count === 0 && `Why don't you fetch some more?`}\n      </div>\n      {users.map((user) => (\n        <div key={user.id}>\n          <div>{`${user.first_name} ${user.last_name}`}</div>\n        </div>\n      ))}\n    </div>\n  )\n}\n```\n\n### Specifying Alternate ID Fields\n\nBy default, `createEntityAdapter` assumes that your data has unique IDs in an `entity.id` field. If your data set stores its ID in a different field, you can pass in a `selectId` argument that returns the appropriate field.\n\n```js\n// In this instance, our user data always has a primary key of `idx`\nconst userData = {\n  users: [\n    { idx: 1, first_name: 'Test' },\n    { idx: 2, first_name: 'Two' },\n  ],\n}\n\n// Since our primary key is `idx` and not `id`,\n// pass in an ID selector to return that field instead\nexport const usersAdapter = createEntityAdapter({\n  selectId: (user) => user.idx,\n})\n```\n\n### Sorting Entities\n\n`createEntityAdapter` provides a `sortComparer` argument that you can leverage to sort the collection of `ids` in state. This can be very useful for when you want to guarantee a sort order and your data doesn't come presorted.\n\n```js\n// In this instance, our user data always has a primary key of `id`, so we do not need to provide `selectId`.\nconst userData = {\n  users: [\n    { id: 1, first_name: 'Test' },\n    { id: 2, first_name: 'Banana' },\n  ],\n}\n\n// Sort by `first_name`. `state.ids` would be ordered as\n// `ids: [ 2, 1 ]`, since 'B' comes before 'T'.\n// When using the provided `selectAll` selector, the result would be sorted:\n// [{ id: 2, first_name: 'Banana' }, { id: 1, first_name: 'Test' }]\nexport const usersAdapter = createEntityAdapter({\n  sortComparer: (a, b) => a.first_name.localeCompare(b.first_name),\n})\n```\n\n## Working with Non-Serializable Data\n\nOne of the core usage principles for Redux is that [you should not put non-serializable values in state or actions](https://redux.js.org/style-guide/#do-not-put-non-serializable-values-in-state-or-actions).\n\nHowever, like most rules, there are exceptions. There may be occasions when you have to deal with actions that need to accept non-serializable data. This should be done very rarely and only if necessary, and these non-serializable payloads shouldn't ever make it into your application state through a reducer.\n\nThe [serializability dev check middleware](../api/serializabilityMiddleware.mdx) will automatically warn anytime it detects non-serializable values in your actions or state. We encourage you to leave this middleware active to help avoid accidentally making mistakes. However, if you _do_ need to turnoff those warnings, you can customize the middleware by configuring it to ignore specific action types, or fields in actions and state:\n\n```js\nconfigureStore({\n  //...\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware({\n      serializableCheck: {\n        // Ignore these action types\n        ignoredActions: ['your/action/type'],\n        // Ignore these field paths in all actions\n        ignoredActionPaths: ['meta.arg', 'payload.timestamp'],\n        // Ignore these paths in the state\n        ignoredPaths: ['items.dates'],\n      },\n    }),\n})\n```\n\n### Use with Redux-Persist\n\nIf using Redux-Persist, you should specifically ignore all the action types it dispatches:\n\n```jsx\nimport { createRoot } from 'react-dom/client'\nimport { configureStore } from '@reduxjs/toolkit'\nimport {\n  persistStore,\n  persistReducer,\n  FLUSH,\n  REHYDRATE,\n  PAUSE,\n  PERSIST,\n  PURGE,\n  REGISTER,\n} from 'redux-persist'\nimport storage from 'redux-persist/lib/storage'\nimport { PersistGate } from 'redux-persist/integration/react'\n\nimport App from './App'\nimport rootReducer from './reducers'\n\nconst persistConfig = {\n  key: 'root',\n  version: 1,\n  storage,\n}\n\nconst persistedReducer = persistReducer(persistConfig, rootReducer)\n\nconst store = configureStore({\n  reducer: persistedReducer,\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware({\n      serializableCheck: {\n        ignoredActions: [FLUSH, REHYDRATE, PAUSE, PERSIST, PURGE, REGISTER],\n      },\n    }),\n})\n\nlet persistor = persistStore(store)\n\nconst container = document.getElementById('root')\n\nif (container) {\n  const root = createRoot(container)\n\n  root.render(\n    <Provider store={store}>\n      <PersistGate loading={null} persistor={persistor}>\n        <App />\n      </PersistGate>\n    </Provider>,\n  )\n} else {\n  throw new Error(\n    \"Root element with ID 'root' was not found in the document. Ensure there is a corresponding HTML element with the ID 'root' in your HTML file.\",\n  )\n}\n```\n\nAdditionally, you can purge any persisted state by adding an extra reducer to the specific slice that you would like to clear when calling persistor.purge(). This is especially helpful when you are looking to clear persisted state on a dispatched logout action.\n\n```ts\nimport { PURGE } from \"redux-persist\";\n\n...\nextraReducers: (builder) => {\n    builder.addCase(PURGE, (state) => {\n        customEntityAdapter.removeAll(state);\n    });\n}\n```\n\nIt is also strongly recommended to blacklist any api(s) that you have configured with RTK Query. If the api slice reducer is not blacklisted, the api cache will be automatically persisted and restored which could leave you with phantom subscriptions from components that do not exist any more. Configuring this should look something like this:\n\n```ts\nconst persistConfig = {\n  key: 'root',\n  version: 1,\n  storage,\n  blacklist: [pokemonApi.reducerPath],\n}\n```\n\nSee [Redux Toolkit #121: How to use this with Redux-Persist?](https://github.com/reduxjs/redux-toolkit/issues/121) and [Redux-Persist #988: non-serializable value error](https://github.com/rt2zz/redux-persist/issues/988#issuecomment-552242978) for further discussion.\n\n### Use with React-Redux-Firebase\n\nRRF includes timestamp values in most actions and state as of 3.x, but there are PRs that may improve that behavior as of 4.x.\n\nA possible configuration to work with that behavior could look like:\n\n```ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport {\n  getFirebase,\n  actionTypes as rrfActionTypes,\n} from 'react-redux-firebase'\nimport { constants as rfConstants } from 'redux-firestore'\nimport rootReducer from './rootReducer'\n\nconst store = configureStore({\n  reducer: rootReducer,\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware({\n      serializableCheck: {\n        ignoredActions: [\n          // just ignore every redux-firebase and react-redux-firebase action type\n          ...Object.keys(rfConstants.actionTypes).map(\n            (type) => `${rfConstants.actionsPrefix}/${type}`,\n          ),\n          ...Object.keys(rrfActionTypes).map(\n            (type) => `@@reactReduxFirebase/${type}`,\n          ),\n        ],\n        ignoredPaths: ['firebase', 'firestore'],\n      },\n      thunk: {\n        extraArgument: {\n          getFirebase,\n        },\n      },\n    }),\n})\n\nexport default store\n```\n"
  },
  {
    "path": "docs/usage/usage-with-typescript.md",
    "content": "---\nid: usage-with-typescript\ntitle: Usage With TypeScript\nsidebar_label: Usage With TypeScript\nhide_title: true\n---\n\n&nbsp;\n\n# Usage With TypeScript\n\n:::tip What You'll Learn\n\n- Details on how to use each Redux Toolkit API with TypeScript\n\n:::\n\n## Introduction\n\nRedux Toolkit is written in TypeScript, and its API is designed to enable great integration with TypeScript applications.\n\nThis page provides specific details for each of the different APIs included in Redux Toolkit and how to type them correctly with TypeScript.\n\n**See the [TypeScript Quick Start tutorial page](../tutorials/typescript.md) for a brief overview of how to set up and use Redux Toolkit and React Redux to work with TypeScript**.\n\n:::info\n\nIf you encounter any problems with the types that are not described on this page, please [open an issue](https://github.com/reduxjs/redux-toolkit/issues?q=is%3Aissue+is%3Aopen+sort%3Aupdated-desc) for discussion.\n\n:::\n\n:::tip TypeScript Version Requirement\n\nRedux Toolkit follows [DefinitelyTyped's policy](https://github.com/DefinitelyTyped/DefinitelyTyped#support-window) of supporting TypeScript versions released within the past two years. As of RTK 2.11, this means we support:\n\n| RTK Version | Minimum TypeScript |\n| ----------- | ------------------ |\n| 2.x         | 5.4+               |\n| 1.9.x       | 4.7+               |\n\n<details>\n<summary>Using an older TypeScript version?</summary>\n\nIf you're unable to upgrade TypeScript, RTK may still work with older versions, but you may encounter type errors or missing type inference. We strongly recommend upgrading to take advantage of improved type safety and developer experience.\n\n</details>\n\n:::\n\n## `configureStore`\n\nThe basics of using `configureStore` are shown in [TypeScript Quick Start tutorial page](../tutorials/typescript.md). Here are some additional details that you might find useful.\n\n### Getting the `State` type\n\nThe easiest way of getting the `State` type is to define the root reducer in advance and extract its `ReturnType`.\nIt is recommended to give the type a different name like `RootState` to prevent confusion, as the type name `State` is usually overused.\n\n```typescript\nimport { combineReducers } from '@reduxjs/toolkit'\nconst rootReducer = combineReducers({})\n// highlight-start\nexport type RootState = ReturnType<typeof rootReducer>\n// highlight-end\n```\n\nAlternatively, if you choose to not create a `rootReducer` yourself and instead pass the slice reducers directly to `configureStore()`, you need to slightly modify the typing to correctly infer the root reducer:\n\n```ts\nimport { configureStore } from '@reduxjs/toolkit'\n// ...\nconst store = configureStore({\n  reducer: {\n    one: oneSlice.reducer,\n    two: twoSlice.reducer,\n  },\n})\nexport type RootState = ReturnType<typeof store.getState>\n\nexport default store\n```\n\nIf you pass the reducers directly to `configureStore()` and do not define the root reducer explicitly, there is no reference to `rootReducer`.\nInstead, you can refer to `store.getState`, in order to get the `State` type.\n\n```typescript\nimport { configureStore } from '@reduxjs/toolkit'\nimport rootReducer from './rootReducer'\nconst store = configureStore({\n  reducer: rootReducer,\n})\nexport type RootState = ReturnType<typeof store.getState>\n```\n\n### Getting the `Dispatch` type\n\nIf you want to get the `Dispatch` type from your store, you can extract it after creating the store. It is recommended to give the type a different name like `AppDispatch` to prevent confusion, as the type name `Dispatch` is usually overused. You may also find it to be more convenient to export a hook like `useAppDispatch` shown below, then using it wherever you'd call `useDispatch`.\n\n```typescript\nimport { configureStore } from '@reduxjs/toolkit'\nimport { useDispatch } from 'react-redux'\nimport rootReducer from './rootReducer'\n\nconst store = configureStore({\n  reducer: rootReducer,\n})\n\n// highlight-start\nexport type AppDispatch = typeof store.dispatch\nexport const useAppDispatch = useDispatch.withTypes<AppDispatch>() // Export a hook that can be reused to resolve types\n// highlight-end\n\nexport default store\n```\n\n### Correct typings for the `Dispatch` type\n\nThe type of the `dispatch` function type will be directly inferred from the `middleware` option. So if you add _correctly typed_ middlewares, `dispatch` should already be correctly typed.\n\nAs TypeScript often widens array types when combining arrays using the spread operator, we suggest using the `.concat(...)` and `.prepend(...)` methods of the `Tuple` returned by `getDefaultMiddleware()`.\n\n```ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport additionalMiddleware from 'additional-middleware'\nimport logger from 'redux-logger'\n// @ts-ignore\nimport untypedMiddleware from 'untyped-middleware'\nimport rootReducer from './rootReducer'\n\nexport type RootState = ReturnType<typeof rootReducer>\nconst store = configureStore({\n  reducer: rootReducer,\n  // highlight-start\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware()\n      .prepend(\n        // correctly typed middlewares can just be used\n        additionalMiddleware,\n        // you can also type middlewares manually\n        untypedMiddleware as Middleware<\n          (action: Action<'specialAction'>) => number,\n          RootState\n        >,\n      )\n      // prepend and concat calls can be chained\n      .concat(logger),\n  // highlight-end\n})\n\nexport type AppDispatch = typeof store.dispatch\n\nexport default store\n```\n\n#### Using `Tuple` without `getDefaultMiddleware`\n\nIf you want to skip the usage of `getDefaultMiddleware` altogether, you are required to use `Tuple` for type-safe creation of your `middleware` array. This class extends the default JavaScript `Array` type, only with modified typings for `.concat(...)` and the additional `.prepend(...)` method.\n\nFor example:\n\n```ts\nimport { configureStore, Tuple } from '@reduxjs/toolkit'\n\nconfigureStore({\n  reducer: rootReducer,\n  middleware: () => new Tuple(additionalMiddleware, logger),\n})\n```\n\n### Using the extracted `Dispatch` type with React Redux\n\nBy default, the React Redux `useDispatch` hook does not contain any types that take middlewares into account. If you need a more specific type for the `dispatch` function when dispatching, you may specify the type of the returned `dispatch` function, or create a custom-typed version of `useSelector`. See [the React Redux documentation](https://react-redux.js.org/using-react-redux/static-typing#typing-the-usedispatch-hook) for details.\n\n## `createAction`\n\nFor most use cases, there is no need to have a literal definition of `action.type`, so the following can be used:\n\n```typescript\ncreateAction<number>('test')\n```\n\nThis will result in the created action being of type `PayloadActionCreator<number, string>`.\n\nIn some setups, you will need a literal type for `action.type`, though.\nUnfortunately, TypeScript type definitions do not allow for a mix of manually-defined and inferred type parameters, so you'll have to specify the `type` both in the Generic definition as well as in the actual JavaScript code:\n\n```typescript\ncreateAction<number, 'test'>('test')\n```\n\nIf you are looking for an alternate way of writing this without the duplication, you can use a prepare callback so that both type parameters can be inferred from arguments, removing the need to specify the action type.\n\n```typescript\nfunction withPayloadType<T>() {\n  return (t: T) => ({ payload: t })\n}\ncreateAction('test', withPayloadType<string>())\n```\n\n### Alternative to using a literally-typed `action.type`\n\nIf you are using `action.type` as a discriminator on a discriminated union, for example to correctly type your payload in `case` statements, you might be interested in this alternative:\n\nCreated action creators have a `match` method that acts as a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates):\n\n```typescript\nconst increment = createAction<number>('increment')\nfunction test(action: Action) {\n  if (increment.match(action)) {\n    // action.payload inferred correctly here\n    action.payload\n  }\n}\n```\n\nThis `match` method is also very useful in combination with `redux-observable` and RxJS's `filter` method.\n\n## `createReducer`\n\n### Building Type-Safe Reducer Argument Objects\n\nThe second parameter for `createReducer` is a callback that receives a `ActionReducerMapBuilder` instance:\n\n```typescript {3-10}\nconst increment = createAction<number, 'increment'>('increment')\nconst decrement = createAction<number, 'decrement'>('decrement')\ncreateReducer(0, (builder) =>\n  builder\n    .addCase(increment, (state, action) => {\n      // action is inferred correctly here\n    })\n    .addCase(decrement, (state, action: PayloadAction<string>) => {\n      // this would error out\n    }),\n)\n```\n\n#### Typing `builder.addMatcher`\n\nAs the first `matcher` argument to `builder.addMatcher`, a [type predicate](https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates) function should be used.\nAs a result, the `action` argument for the second `reducer` argument can be inferred by TypeScript:\n\n```ts\nfunction isNumberValueAction(action: UnknownAction): action is PayloadAction<{ value: number }> {\n  return typeof action.payload.value === 'number'\n}\n\ncreateReducer({ value: 0 }, builder =>\n   builder.addMatcher(isNumberValueAction, (state, action) => {\n      state.value += action.payload.value\n   })\n})\n```\n\n## `createSlice`\n\nAs `createSlice` creates your actions as well as your reducer for you, you don't have to worry about type safety here.\nAction types can just be provided inline:\n\n```typescript\nconst slice = createSlice({\n  name: 'test',\n  initialState: 0,\n  reducers: {\n    increment: (state, action: PayloadAction<number>) => state + action.payload,\n  },\n})\n// now available:\nslice.actions.increment(2)\n// also available:\nslice.caseReducers.increment(0, { type: 'increment', payload: 5 })\n```\n\nIf you have too many case reducers and defining them inline would be messy, or you want to reuse case reducers across slices, you can also define them outside the `createSlice` call and type them as `CaseReducer`:\n\n```typescript\ntype State = number\nconst increment: CaseReducer<State, PayloadAction<number>> = (state, action) =>\n  state + action.payload\n\ncreateSlice({\n  name: 'test',\n  initialState: 0,\n  reducers: {\n    increment,\n  },\n})\n```\n\n### Defining the Initial State Type\n\nYou might have noticed that it is not a good idea to pass your `SliceState` type as a generic to `createSlice`. This is due to the fact that in almost all cases, follow-up generic parameters to `createSlice` need to be inferred, and TypeScript cannot mix explicit declaration and inference of generic types within the same \"generic block\".\n\nThe standard approach is to declare an interface or type for your state, create an initial state value that uses that type, and pass the initial state value to `createSlice`. You can also use the construct `initialState: myInitialState satisfies SliceState as SliceState`.\n\n```ts {1,4,8,15}\ntype SliceState = { state: 'loading' } | { state: 'finished'; data: string }\n\n// First approach: define the initial state using that type\nconst initialState: SliceState = { state: 'loading' }\n\ncreateSlice({\n  name: 'test1',\n  initialState, // type SliceState is inferred for the state of the slice\n  reducers: {},\n})\n\n// Or, cast the initial state as necessary\ncreateSlice({\n  name: 'test2',\n  initialState: { state: 'loading' } satisfies SliceState as SliceState,\n  reducers: {},\n})\n```\n\nwhich will result in a `Slice<SliceState, ...>`.\n\n### Defining Action Contents with `prepare` Callbacks\n\nIf you want to add a `meta` or `error` property to your action, or customize the `payload` of your action, you have to use the `prepare` notation.\n\nUsing this notation with TypeScript looks like this:\n\n```ts {5-16}\nconst blogSlice = createSlice({\n  name: 'blogData',\n  initialState,\n  reducers: {\n    receivedAll: {\n      reducer(\n        state,\n        action: PayloadAction<Page[], string, { currentPage: number }>,\n      ) {\n        state.all = action.payload\n        state.meta = action.meta\n      },\n      prepare(payload: Page[], currentPage: number) {\n        return { payload, meta: { currentPage } }\n      },\n    },\n  },\n})\n```\n\n### Generated Action Types for Slices\n\n`createSlice` generates action type strings by combining the `name` field from the slice with the field name of the reducer function, like `'test/increment'`. This is strongly typed as the exact value, thanks to TS's string literal analysis.\n\nYou can also use the `slice.action.myAction.match` [type predicate](https://www.typescriptlang.org/docs/handbook/advanced-types.html#using-type-predicates), which will narrow down an action object to the exact type:\n\n```ts {10}\nconst slice = createSlice({\n  name: 'test',\n  initialState: 0,\n  reducers: {\n    increment: (state, action: PayloadAction<number>) => state + action.payload,\n  },\n})\n\ntype incrementType = typeof slice.actions.increment.type\n// type incrementType = 'test/increment'\n\nfunction myCustomMiddleware(action: Action) {\n  if (slice.actions.increment.match(action)) {\n    // `action` is narrowed down to the type `PayloadAction<number>` here.\n  }\n}\n```\n\nIf you actually _need_ that type, unfortunately there is no other way than manual casting.\n\n### Type safety with `extraReducers`\n\nReducer lookup tables that map an action `type` string to a reducer function are not easy to fully type correctly. This affects both `createReducer` and the `extraReducers` argument for `createSlice`. So, like with `createReducer`, [you should use the \"builder callback\" approach](#building-type-safe-reducer-argument-objects) for defining the reducer object argument.\n\nThis is particularly useful when a slice reducer needs to handle action types generated by other slices, or generated by specific calls to `createAction` (such as the actions generated by [`createAsyncThunk`](../api/createAsyncThunk.mdx)).\n\n```ts {27-30}\nconst fetchUserById = createAsyncThunk(\n  'users/fetchById',\n  // if you type your function argument here\n  async (userId: number) => {\n    const response = await fetch(`https://reqres.in/api/users/${userId}`)\n    return (await response.json()) as Returned\n  },\n)\n\ninterface UsersState {\n  entities: User[]\n  loading: 'idle' | 'pending' | 'succeeded' | 'failed'\n}\n\nconst initialState = {\n  entities: [],\n  loading: 'idle',\n} satisfies UsersState as UsersState\n\nconst usersSlice = createSlice({\n  name: 'users',\n  initialState,\n  reducers: {\n    // fill in primary logic here\n  },\n  extraReducers: (builder) => {\n    builder.addCase(fetchUserById.pending, (state, action) => {\n      // both `state` and `action` are now correctly typed\n      // based on the slice state and the `pending` action creator\n    })\n  },\n})\n```\n\nLike the `builder` in `createReducer`, this `builder` also accepts `addMatcher` (see [typing `builder.matcher`](#typing-builderaddmatcher)) and `addDefaultCase`.\n\n### Payload with All Optional Fields\n\nIf you try to supply a payload type where all fields are optional, like `PayloadAction<Partial<User>>` or `PayloadAction<{value?: string}>`, TS may not be able to infer the action type correctly.\n\nYou can work around this by [using a custom `AtLeastOne` utility type](https://github.com/reduxjs/redux-toolkit/issues/1423#issuecomment-902680573) to help ensure that at least one of the fields must be passed in:\n\n```ts no-transpile\ntype AtLeastOne<T extends Record<string, any>> = keyof T extends infer K\n  ? K extends string\n    ? Pick<T, K & keyof T> & Partial<T>\n    : never\n  : never\n\n// Use this type instead of `Partial<MyPayloadType>`\ntype AtLeastOneUserField = AtLeastOne<User>\n```\n\n### Typing Async Thunks Inside `createSlice`\n\nAs of 2.0, `createSlice` allows [defining thunks inside of `reducers` using a callback syntax](../api/createSlice.mdx#the-reducers-creator-callback-notation).\n\nTyping for the `create.asyncThunk` method works in the same way as [`createAsyncThunk`](#createasyncthunk), with one key difference.\n\nA type for `state` and/or `dispatch` _cannot_ be provided as part of the `ThunkApiConfig`, as this would cause circular types.\n\nInstead, it is necessary to assert the type when needed - `getState() as RootState`. You may also include an explicit return type for the payload function as well, in order to break the circular type inference cycle.\n\n```ts no-transpile\ncreate.asyncThunk<Todo, string, { rejectValue: { error: string } }>(\n  // highlight-start\n  // may need to include an explicit return type\n  async (id: string, thunkApi): Promise<Todo> => {\n    // Cast types for `getState` and `dispatch` manually\n    const state = thunkApi.getState() as RootState\n    const dispatch = thunkApi.dispatch as AppDispatch\n    // highlight-end\n    try {\n      const todo = await fetchTodo()\n      return todo\n    } catch (e) {\n      throw thunkApi.rejectWithValue({\n        error: 'Oh no!',\n      })\n    }\n  },\n)\n```\n\nFor common thunk API configuration options, a [`withTypes` helper](../usage/usage-with-typescript#defining-a-pre-typed-createasyncthunk) is provided:\n\n```ts no-transpile\nreducers: (create) => {\n  const createAThunk = create.asyncThunk.withTypes<{\n    rejectValue: { error: string }\n  }>()\n\n  return {\n    fetchTodo: createAThunk<Todo, string>(async (id, thunkApi) => {\n      throw thunkApi.rejectWithValue({\n        error: 'Oh no!',\n      })\n    }),\n    fetchTodos: createAThunk<Todo[], string>(async (id, thunkApi) => {\n      throw thunkApi.rejectWithValue({\n        error: 'Oh no, not again!',\n      })\n    }),\n  }\n}\n```\n\n### Wrapping `createSlice`\n\nIf you need to reuse reducer logic, it is common to write [\"higher-order reducers\"](https://redux.js.org/recipes/structuring-reducers/reusing-reducer-logic#customizing-behavior-with-higher-order-reducers) that wrap a reducer function with additional common behavior. This can be done with `createSlice` as well, but due to the complexity of the types for `createSlice`, you have to use the `SliceCaseReducers` and `ValidateSliceCaseReducers` types in a very specific way.\n\nHere is an example of such a \"generic\" wrapped `createSlice` call:\n\n```ts\ninterface GenericState<T> {\n  data?: T\n  status: 'loading' | 'finished' | 'error'\n}\n\nconst createGenericSlice = <\n  T,\n  Reducers extends SliceCaseReducers<GenericState<T>>,\n>({\n  name = '',\n  initialState,\n  reducers,\n}: {\n  name: string\n  initialState: GenericState<T>\n  reducers: ValidateSliceCaseReducers<GenericState<T>, Reducers>\n}) => {\n  return createSlice({\n    name,\n    initialState,\n    reducers: {\n      start(state) {\n        state.status = 'loading'\n      },\n      /**\n       * If you want to write to values of the state that depend on the generic\n       * (in this case: `state.data`, which is T), you might need to specify the\n       * State type manually here, as it defaults to `Draft<GenericState<T>>`,\n       * which can sometimes be problematic with yet-unresolved generics.\n       * This is a general problem when working with immer's Draft type and generics.\n       */\n      success(state: GenericState<T>, action: PayloadAction<T>) {\n        state.data = action.payload\n        state.status = 'finished'\n      },\n      ...reducers,\n    },\n  })\n}\n\nconst wrappedSlice = createGenericSlice({\n  name: 'test',\n  initialState: { status: 'loading' } as GenericState<string>,\n  reducers: {\n    magic(state) {\n      state.status = 'finished'\n      state.data = 'hocus pocus'\n    },\n  },\n})\n```\n\n## `createAsyncThunk`\n\n### Basic `createAsyncThunk` Types\n\nIn the most common use cases, you should not need to explicitly declare any types for the `createAsyncThunk` call itself.\n\nJust provide a type for the first argument to the `payloadCreator` argument as you would for any function argument, and the resulting thunk will accept the same type as its input parameter.\nThe return type of the `payloadCreator` will also be reflected in all generated action types.\n\n```ts\ninterface MyData {\n  // ...\n}\n\nconst fetchUserById = createAsyncThunk(\n  'users/fetchById',\n  // highlight-start\n  // Declare the type your function argument here:\n  async (userId: number) => {\n    // highlight-end\n    const response = await fetch(`https://reqres.in/api/users/${userId}`)\n    // Inferred return type: Promise<MyData>\n    // highlight-next-line\n    return (await response.json()) as MyData\n  },\n)\n\n// the parameter of `fetchUserById` is automatically inferred to `number` here\n// and dispatching the resulting thunkAction will return a Promise of a correctly\n// typed \"fulfilled\" or \"rejected\" action.\nconst lastReturnedAction = await store.dispatch(fetchUserById(3))\n```\n\n### Handling responses from async thunks\n\nThe preferred approach to handling responses from thunks is via the `unwrap` method (see [Unwrapping Result Actions](../api/createAsyncThunk.mdx/#unwrapping-result-actions).\n\n```ts\nconst handleClick = async (userData) => {\n  try {\n    const result = await dispatch(updateUser(userData)).unwrap();\n    showToast('success', `Updated ${result.name}`)\n  } catch (error) {\n    showToast('error', `Update failed: ${error.message}`)\n  }\n}\n```\n\n### Typing the `thunkApi` Object\n\nThe second argument to the `payloadCreator`, known as `thunkApi`, is an object containing references to the `dispatch`, `getState`, and `extra` arguments from the thunk middleware as well as a utility function called `rejectWithValue`. If you want to use these from within the `payloadCreator`, you will need to define some generic arguments, as the types for these arguments cannot be inferred. Also, as TS cannot mix explicit and inferred generic parameters, from this point on you'll have to define the `Returned` and `ThunkArg` generic parameter as well.\n\n#### Manually Defining `thunkApi` Types\n\nTo define the types for these arguments, pass an object as the third generic argument, with type declarations for some or all of these fields:\n\n```ts\ntype AsyncThunkConfig = {\n  /** return type for `thunkApi.getState` */\n  state?: unknown\n  /** type for `thunkApi.dispatch` */\n  dispatch?: Dispatch\n  /** type of the `extra` argument for the thunk middleware, which will be passed in as `thunkApi.extra` */\n  extra?: unknown\n  /** type to be passed into `rejectWithValue`'s first argument that will end up on `rejectedAction.payload` */\n  rejectValue?: unknown\n  /** return type of the `serializeError` option callback */\n  serializedErrorType?: unknown\n  /** type to be returned from the `getPendingMeta` option callback & merged into `pendingAction.meta` */\n  pendingMeta?: unknown\n  /** type to be passed into the second argument of `fulfillWithValue` to finally be merged into `fulfilledAction.meta` */\n  fulfilledMeta?: unknown\n  /** type to be passed into the second argument of `rejectWithValue` to finally be merged into `rejectedAction.meta` */\n  rejectedMeta?: unknown\n}\n```\n\n```ts\nconst fetchUserById = createAsyncThunk<\n  // highlight-start\n  // Return type of the payload creator\n  MyData,\n  // First argument to the payload creator\n  number,\n  {\n    // Optional fields for defining thunkApi field types\n    dispatch: AppDispatch\n    state: State\n    extra: {\n      jwt: string\n    }\n  }\n  // highlight-end\n>('users/fetchById', async (userId, thunkApi) => {\n  const response = await fetch(`https://reqres.in/api/users/${userId}`, {\n    headers: {\n      Authorization: `Bearer ${thunkApi.extra.jwt}`,\n    },\n  })\n  return (await response.json()) as MyData\n})\n```\n\nIf you are performing a request that you know will typically either be a success or have an expected error format, you can pass in a type to `rejectValue` and `return rejectWithValue(knownPayload)` in the action creator. This allows you to reference the error payload in the reducer as well as in a component after dispatching the `createAsyncThunk` action.\n\n```ts\ninterface MyKnownError {\n  errorMessage: string\n  // ...\n}\ninterface UserAttributes {\n  id: string\n  first_name: string\n  last_name: string\n  email: string\n}\n\nconst updateUser = createAsyncThunk<\n  // Return type of the payload creator\n  MyData,\n  // First argument to the payload creator\n  UserAttributes,\n  // Types for ThunkAPI\n  {\n    extra: {\n      jwt: string\n    }\n    rejectValue: MyKnownError\n  }\n>('users/update', async (user, thunkApi) => {\n  const { id, ...userData } = user\n  const response = await fetch(`https://reqres.in/api/users/${id}`, {\n    method: 'PUT',\n    headers: {\n      Authorization: `Bearer ${thunkApi.extra.jwt}`,\n    },\n    body: JSON.stringify(userData),\n  })\n  if (response.status === 400) {\n    // Return the known error for future handling\n    return thunkApi.rejectWithValue((await response.json()) as MyKnownError)\n  }\n  return (await response.json()) as MyData\n})\n```\n\nWhile this notation for `state`, `dispatch`, `extra` and `rejectValue` might seem uncommon at first, it allows you to provide only the types for these you actually need - so for example, if you are not accessing `getState` within your `payloadCreator`, there is no need to provide a type for `state`. The same can be said about `rejectValue` - if you don't need to access any potential error payload, you can ignore it.\n\nIn addition, you can leverage checks against `action.payload` and `match` as provided by `createAction` as a type-guard for when you want to access known properties on defined types. Example:\n\n- In a reducer\n\n```ts\nconst usersSlice = createSlice({\n  name: 'users',\n  initialState: {\n    entities: {},\n    error: null,\n  },\n  reducers: {},\n  extraReducers: (builder) => {\n    builder.addCase(updateUser.fulfilled, (state, { payload }) => {\n      state.entities[payload.id] = payload\n    })\n    builder.addCase(updateUser.rejected, (state, action) => {\n      if (action.payload) {\n        // Since we passed in `MyKnownError` to `rejectValue` in `updateUser`, the type information will be available here.\n        state.error = action.payload.errorMessage\n      } else {\n        state.error = action.error\n      }\n    })\n  },\n})\n```\n\n- In a component\n\n```ts\nconst handleUpdateUser = async (userData) => {\n  const resultAction = await dispatch(updateUser(userData))\n  if (updateUser.fulfilled.match(resultAction)) {\n    const user = resultAction.payload\n    showToast('success', `Updated ${user.name}`)\n  } else {\n    if (resultAction.payload) {\n      // Since we passed in `MyKnownError` to `rejectValue` in `updateUser`, the type information will be available here.\n      // Note: this would also be a good place to do any handling that relies on the `rejectedWithValue` payload, such as setting field errors\n      showToast('error', `Update failed: ${resultAction.payload.errorMessage}`)\n    } else {\n      showToast('error', `Update failed: ${resultAction.error.message}`)\n    }\n  }\n}\n```\n\n### Defining a Pre-Typed `createAsyncThunk`\n\nAs of RTK 1.9, you can define a \"pre-typed\" version of `createAsyncThunk` that can have the types for `state`, `dispatch`, and `extra` built in. This lets you set up those types once, so you don't have to repeat them each time you call `createAsyncThunk`.\n\nTo do this, call `createAsyncThunk.withTypes<>()`, and pass in an object containing the field names and types for any of the fields in the `AsyncThunkConfig` type listed above. This might look like:\n\n```ts\nconst createAppAsyncThunk = createAsyncThunk.withTypes<{\n  state: RootState\n  dispatch: AppDispatch\n  rejectValue: string\n  extra: { s: string; n: number }\n}>()\n```\n\nImport and use that pre-typed `createAppAsyncThunk` instead of the original, and the types will be used automatically.\n\n## `createEntityAdapter`\n\nUsage of `createEntityAdapter` with TypeScript varies based on whether your entities are normalized by an `id` property, or whether a custom `selectId` is needed.\n\nIf your entities are normalized by an `id` property, `createEntityAdapter` only requires you to specify the entity type as the single generic argument. For example:\n\n```ts\ninterface Book {\n  id: number\n  title: string\n}\n\n// no selectId needed here, as the entity has an `id` property we can default to\n// highlight-next-line\nconst booksAdapter = createEntityAdapter<Book>({\n  sortComparer: (a, b) => a.title.localeCompare(b.title),\n})\n\nconst booksSlice = createSlice({\n  name: 'books',\n  initialState: booksAdapter.getInitialState(),\n  reducers: {\n    bookAdded: booksAdapter.addOne,\n    booksReceived(state, action: PayloadAction<{ books: Book[] }>) {\n      booksAdapter.setAll(state, action.payload.books)\n    },\n  },\n})\n```\n\nOn the other hand, if the entity needs to be normalized by a different property, we instead recommend passing a custom `selectId` function and annotating there. This allows proper inference of the ID's type, instead of having to provide it manually.\n\n```ts\ninterface Book {\n  bookId: number\n  title: string\n  // ...\n}\n\nconst booksAdapter = createEntityAdapter({\n  // highlight-next-line\n  selectId: (book: Book) => book.bookId,\n  sortComparer: (a, b) => a.title.localeCompare(b.title),\n})\n\nconst booksSlice = createSlice({\n  name: 'books',\n  initialState: booksAdapter.getInitialState(),\n  reducers: {\n    bookAdded: booksAdapter.addOne,\n    booksReceived(state, action: PayloadAction<{ books: Book[] }>) {\n      booksAdapter.setAll(state, action.payload.books)\n    },\n  },\n})\n```\n\n### Using `createEntityAdapter` with `normalizr`\n\nWhen using a library like [`normalizr`](https://github.com/paularmstrong/normalizr/), your normalized data will resemble this shape:\n\n```js\n{\n  result: 1,\n  entities: {\n    1: { id: 1, other: 'property' },\n    2: { id: 2, other: 'property' }\n  }\n}\n```\n\nThe methods `addMany`, `upsertMany`, and `setAll` all allow you to pass in the `entities` portion of this directly with no extra conversion steps. However, the `normalizr` TS typings currently do not correctly reflect that multiple data types may be included in the results, so you will need to specify that type structure yourself.\n\nHere is an example of how that would look:\n\n```ts\ntype Author = { id: number; name: string }\ntype Article = { id: number; title: string }\ntype Comment = { id: number; commenter: number }\n\nexport const fetchArticle = createAsyncThunk(\n  'articles/fetchArticle',\n  async (id: number) => {\n    const data = await fakeAPI.articles.show(id)\n    // Normalize the data so reducers can responded to a predictable payload.\n    // Note: at the time of writing, normalizr does not automatically infer the result,\n    // so we explicitly declare the shape of the returned normalized data as a generic arg.\n    const normalized = normalize<\n      any,\n      {\n        articles: { [key: string]: Article }\n        users: { [key: string]: Author }\n        comments: { [key: string]: Comment }\n      }\n    >(data, articleEntity)\n    return normalized.entities\n  },\n)\n\nexport const slice = createSlice({\n  name: 'articles',\n  initialState: articlesAdapter.getInitialState(),\n  reducers: {},\n  extraReducers: (builder) => {\n    builder.addCase(fetchArticle.fulfilled, (state, action) => {\n      // The type signature on action.payload matches what we passed into the generic for `normalize`, allowing us to access specific properties on `payload.articles` if desired\n      articlesAdapter.upsertMany(state, action.payload.articles)\n    })\n  },\n})\n```\n"
  },
  {
    "path": "docs/virtual/matchers/index.ts",
    "content": "import {\n  createAsyncThunk,\n  createReducer,\n  PayloadAction,\n} from '@reduxjs/toolkit'\n\nexport interface Data {\n  isInteresting: boolean\n  isSpecial: boolean\n}\n\nexport interface Special extends Data {\n  isSpecial: true\n}\n\nexport interface Interesting extends Data {\n  isInteresting: true\n}\n\nexport function isSpecial(\n  action: PayloadAction<Data>,\n): action is PayloadAction<Special> {\n  return action.payload.isSpecial\n}\n\nexport function isInteresting(\n  action: PayloadAction<Data>,\n): action is PayloadAction<Interesting> {\n  return action.payload.isInteresting\n}\n\nexport interface ExampleState {\n  isSpecial: boolean\n  isInteresting: boolean\n}\n\nexport const initialState = {\n  isSpecial: false,\n  isInteresting: false,\n} satisfies ExampleState as ExampleState\n\nexport const isSpecialAndInterestingThunk = createAsyncThunk(\n  'isSpecialAndInterestingThunk',\n  () => {\n    return {\n      isSpecial: true,\n      isInteresting: true,\n    }\n  },\n)\n\nexport const requestThunk1 = createAsyncThunk('requestThunk1', () => ({}))\n\nexport const requestThunk2 = createAsyncThunk('requestThunk2', () => ({}))\n\nexport const loadingReducer = createReducer(initialState, (builder) => {\n  builder.addCase(isSpecialAndInterestingThunk.fulfilled, (state, action) => {\n    if (isSpecial(action)) {\n      state.isSpecial = true\n    } else if (isInteresting(action)) {\n      state.isInteresting = true\n    }\n  })\n})\n"
  },
  {
    "path": "docs/virtual/petstore-api.generated/index.ts",
    "content": "export * from './petstore-api.generated'\n"
  },
  {
    "path": "docs/virtual/petstore-api.generated/petstore-api.generated.ts",
    "content": "import { fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport { createApi } from '@reduxjs/toolkit/query/react'\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/v3' }),\n  tagTypes: [],\n  endpoints: (build) => ({\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: `/pet`, method: 'PUT', body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: `/pet`,\n        method: 'POST',\n        body: queryArg.pet,\n      }),\n    }),\n    findPetsByStatus: build.query<\n      FindPetsByStatusApiResponse,\n      FindPetsByStatusApiArg\n    >({\n      query: (queryArg) => ({\n        url: `/pet/findByStatus`,\n        params: { status: queryArg.status },\n      }),\n    }),\n    findPetsByTags: build.query<\n      FindPetsByTagsApiResponse,\n      FindPetsByTagsApiArg\n    >({\n      query: (queryArg) => ({\n        url: `/pet/findByTags`,\n        params: { tags: queryArg.tags },\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: `/pet/${queryArg.petId}` }),\n    }),\n    updatePetWithForm: build.mutation<\n      UpdatePetWithFormApiResponse,\n      UpdatePetWithFormApiArg\n    >({\n      query: (queryArg) => ({\n        url: `/pet/${queryArg.petId}`,\n        method: 'POST',\n        params: { name: queryArg.name, status: queryArg.status },\n      }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({\n        url: `/pet/${queryArg.petId}`,\n        method: 'DELETE',\n        headers: { api_key: queryArg.apiKey },\n      }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: `/pet/${queryArg.petId}/uploadImage`,\n        method: 'POST',\n        body: queryArg.body,\n        params: { additionalMetadata: queryArg.additionalMetadata },\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: `/store/inventory` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({\n        url: `/store/order`,\n        method: 'POST',\n        body: queryArg.order,\n      }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: `/store/order/${queryArg.orderId}` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({\n        url: `/store/order/${queryArg.orderId}`,\n        method: 'DELETE',\n      }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({\n        url: `/user`,\n        method: 'POST',\n        body: queryArg.user,\n      }),\n    }),\n    createUsersWithListInput: build.mutation<\n      CreateUsersWithListInputApiResponse,\n      CreateUsersWithListInputApiArg\n    >({\n      query: (queryArg) => ({\n        url: `/user/createWithList`,\n        method: 'POST',\n        body: queryArg.body,\n      }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: `/user/login`,\n        params: { username: queryArg.username, password: queryArg.password },\n      }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: `/user/logout` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: `/user/${queryArg.username}` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({\n        url: `/user/${queryArg.username}`,\n        method: 'PUT',\n        body: queryArg.user,\n      }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({\n        url: `/user/${queryArg.username}`,\n        method: 'DELETE',\n      }),\n    }),\n  }),\n})\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet\n}\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet\n}\nexport type FindPetsByStatusApiResponse =\n  /** status 200 successful operation */ Pet[]\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: 'available' | 'pending' | 'sold'\n}\nexport type FindPetsByTagsApiResponse =\n  /** status 200 successful operation */ Pet[]\nexport type FindPetsByTagsApiArg = {\n  /** Tags to filter by */\n  tags?: string[]\n}\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number\n}\nexport type UpdatePetWithFormApiResponse = unknown\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number\n  /** Name of pet that needs to be updated */\n  name?: string\n  /** Status of pet that needs to be updated */\n  status?: string\n}\nexport type DeletePetApiResponse = unknown\nexport type DeletePetApiArg = {\n  apiKey?: string\n  /** Pet id to delete */\n  petId: number\n}\nexport type UploadFileApiResponse =\n  /** status 200 successful operation */ ApiResponse\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number\n  /** Additional Metadata */\n  additionalMetadata?: string\n  body: string\n}\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number\n}\nexport type GetInventoryApiArg = {}\nexport type PlaceOrderApiResponse = /** status 200 successful operation */ Order\nexport type PlaceOrderApiArg = {\n  order: Order\n}\nexport type GetOrderByIdApiResponse =\n  /** status 200 successful operation */ Order\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number\n}\nexport type DeleteOrderApiResponse = unknown\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number\n}\nexport type CreateUserApiResponse = unknown\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User\n}\nexport type CreateUsersWithListInputApiResponse =\n  /** status 200 Successful operation */ User\nexport type CreateUsersWithListInputApiArg = {\n  body: User[]\n}\nexport type LoginUserApiResponse = /** status 200 successful operation */ string\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string\n  /** The password for login in clear text */\n  password?: string\n}\nexport type LogoutUserApiResponse = unknown\nexport type LogoutUserApiArg = {}\nexport type GetUserByNameApiResponse =\n  /** status 200 successful operation */ User\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string\n}\nexport type UpdateUserApiResponse = unknown\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string\n  /** Update an existent user in the store */\n  user: User\n}\nexport type DeleteUserApiResponse = unknown\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string\n}\nexport type Category = {\n  id?: number\n  name?: string\n}\nexport type Tag = {\n  id?: number\n  name?: string\n}\nexport type Pet = {\n  id?: number\n  name: string\n  category?: Category\n  photoUrls: string[]\n  tags?: Tag[]\n  status?: 'available' | 'pending' | 'sold'\n}\nexport type ApiResponse = {\n  code?: number\n  type?: string\n  message?: string\n}\nexport type Order = {\n  id?: number\n  petId?: number\n  quantity?: number\n  shipDate?: string\n  status?: 'placed' | 'approved' | 'delivered'\n  complete?: boolean\n}\nexport type User = {\n  id?: number\n  username?: string\n  firstName?: string\n  lastName?: string\n  email?: string\n  password?: string\n  phone?: string\n  userStatus?: number\n}\nexport const {\n  useUpdatePetMutation,\n  useAddPetMutation,\n  useFindPetsByStatusQuery,\n  useFindPetsByTagsQuery,\n  useGetPetByIdQuery,\n  useUpdatePetWithFormMutation,\n  useDeletePetMutation,\n  useUploadFileMutation,\n  useGetInventoryQuery,\n  usePlaceOrderMutation,\n  useGetOrderByIdQuery,\n  useDeleteOrderMutation,\n  useCreateUserMutation,\n  useCreateUsersWithListInputMutation,\n  useLoginUserQuery,\n  useLogoutUserQuery,\n  useGetUserByNameQuery,\n  useUpdateUserMutation,\n  useDeleteUserMutation,\n} = api\n"
  },
  {
    "path": "docs/virtual/petstore-api.generated/petstore.json",
    "content": "{\n  \"openapi\": \"3.0.2\",\n  \"info\": {\n    \"title\": \"Swagger Petstore - OpenAPI 3.0\",\n    \"description\": \"This is a sample Pet Store Server based on the OpenAPI 3.0 specification.  You can find out more about\\nSwagger at [http://swagger.io](http://swagger.io). In the third iteration of the pet store, we've switched to the design first approach!\\nYou can now help us improve the API whether it's by making changes to the definition itself or to the code.\\nThat way, with time, we can improve the API in general, and expose some of the new features in OAS3.\\n\\nSome useful links:\\n- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore)\\n- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)\",\n    \"termsOfService\": \"http://swagger.io/terms/\",\n    \"contact\": { \"email\": \"apiteam@swagger.io\" },\n    \"license\": {\n      \"name\": \"Apache 2.0\",\n      \"url\": \"http://www.apache.org/licenses/LICENSE-2.0.html\"\n    },\n    \"version\": \"1.0.5\"\n  },\n  \"externalDocs\": {\n    \"description\": \"Find out more about Swagger\",\n    \"url\": \"http://swagger.io\"\n  },\n  \"servers\": [{ \"url\": \"/api/v3\" }],\n  \"tags\": [\n    {\n      \"name\": \"pet\",\n      \"description\": \"Everything about your Pets\",\n      \"externalDocs\": {\n        \"description\": \"Find out more\",\n        \"url\": \"http://swagger.io\"\n      }\n    },\n    { \"name\": \"store\", \"description\": \"Operations about user\" },\n    {\n      \"name\": \"user\",\n      \"description\": \"Access to Petstore orders\",\n      \"externalDocs\": {\n        \"description\": \"Find out more about our store\",\n        \"url\": \"http://swagger.io\"\n      }\n    }\n  ],\n  \"paths\": {\n    \"/pet\": {\n      \"put\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Update an existing pet\",\n        \"description\": \"Update an existing pet by Id\",\n        \"operationId\": \"updatePet\",\n        \"requestBody\": {\n          \"description\": \"Update an existent pet in the store\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n            },\n            \"application/xml\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n            }\n          },\n          \"required\": true\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n              },\n              \"application/json\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n              }\n            }\n          },\n          \"400\": { \"description\": \"Invalid ID supplied\" },\n          \"404\": { \"description\": \"Pet not found\" },\n          \"405\": { \"description\": \"Validation exception\" }\n        },\n        \"security\": [{ \"petstore_auth\": [\"write:pets\", \"read:pets\"] }]\n      },\n      \"post\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Add a new pet to the store\",\n        \"description\": \"Add a new pet to the store\",\n        \"operationId\": \"addPet\",\n        \"requestBody\": {\n          \"description\": \"Create a new pet in the store\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n            },\n            \"application/xml\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n            }\n          },\n          \"required\": true\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n              },\n              \"application/json\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n              }\n            }\n          },\n          \"405\": { \"description\": \"Invalid input\" }\n        },\n        \"security\": [{ \"petstore_auth\": [\"write:pets\", \"read:pets\"] }]\n      }\n    },\n    \"/pet/findByStatus\": {\n      \"get\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Finds Pets by status\",\n        \"description\": \"Multiple status values can be provided with comma separated strings\",\n        \"operationId\": \"findPetsByStatus\",\n        \"parameters\": [\n          {\n            \"name\": \"status\",\n            \"in\": \"query\",\n            \"description\": \"Status values that need to be considered for filter\",\n            \"required\": false,\n            \"explode\": true,\n            \"schema\": {\n              \"type\": \"string\",\n              \"default\": \"available\",\n              \"enum\": [\"available\", \"pending\", \"sold\"]\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": { \"$ref\": \"#/components/schemas/Pet\" }\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": { \"$ref\": \"#/components/schemas/Pet\" }\n                }\n              }\n            }\n          },\n          \"400\": { \"description\": \"Invalid status value\" }\n        },\n        \"security\": [{ \"petstore_auth\": [\"write:pets\", \"read:pets\"] }]\n      }\n    },\n    \"/pet/findByTags\": {\n      \"get\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Finds Pets by tags\",\n        \"description\": \"Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.\",\n        \"operationId\": \"findPetsByTags\",\n        \"parameters\": [\n          {\n            \"name\": \"tags\",\n            \"in\": \"query\",\n            \"description\": \"Tags to filter by\",\n            \"required\": false,\n            \"explode\": true,\n            \"schema\": { \"type\": \"array\", \"items\": { \"type\": \"string\" } }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": { \"$ref\": \"#/components/schemas/Pet\" }\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": { \"$ref\": \"#/components/schemas/Pet\" }\n                }\n              }\n            }\n          },\n          \"400\": { \"description\": \"Invalid tag value\" }\n        },\n        \"security\": [{ \"petstore_auth\": [\"write:pets\", \"read:pets\"] }]\n      }\n    },\n    \"/pet/{petId}\": {\n      \"get\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Find pet by ID\",\n        \"description\": \"Returns a single pet\",\n        \"operationId\": \"getPetById\",\n        \"parameters\": [\n          {\n            \"name\": \"petId\",\n            \"in\": \"path\",\n            \"description\": \"ID of pet to return\",\n            \"required\": true,\n            \"schema\": { \"type\": \"integer\", \"format\": \"int64\" }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n              },\n              \"application/json\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n              }\n            }\n          },\n          \"400\": { \"description\": \"Invalid ID supplied\" },\n          \"404\": { \"description\": \"Pet not found\" }\n        },\n        \"security\": [\n          { \"api_key\": [] },\n          { \"petstore_auth\": [\"write:pets\", \"read:pets\"] }\n        ]\n      },\n      \"post\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Updates a pet in the store with form data\",\n        \"description\": \"\",\n        \"operationId\": \"updatePetWithForm\",\n        \"parameters\": [\n          {\n            \"name\": \"petId\",\n            \"in\": \"path\",\n            \"description\": \"ID of pet that needs to be updated\",\n            \"required\": true,\n            \"schema\": { \"type\": \"integer\", \"format\": \"int64\" }\n          },\n          {\n            \"name\": \"name\",\n            \"in\": \"query\",\n            \"description\": \"Name of pet that needs to be updated\",\n            \"schema\": { \"type\": \"string\" }\n          },\n          {\n            \"name\": \"status\",\n            \"in\": \"query\",\n            \"description\": \"Status of pet that needs to be updated\",\n            \"schema\": { \"type\": \"string\" }\n          }\n        ],\n        \"responses\": { \"405\": { \"description\": \"Invalid input\" } },\n        \"security\": [{ \"petstore_auth\": [\"write:pets\", \"read:pets\"] }]\n      },\n      \"delete\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Deletes a pet\",\n        \"description\": \"\",\n        \"operationId\": \"deletePet\",\n        \"parameters\": [\n          {\n            \"name\": \"api_key\",\n            \"in\": \"header\",\n            \"description\": \"\",\n            \"required\": false,\n            \"schema\": { \"type\": \"string\" }\n          },\n          {\n            \"name\": \"petId\",\n            \"in\": \"path\",\n            \"description\": \"Pet id to delete\",\n            \"required\": true,\n            \"schema\": { \"type\": \"integer\", \"format\": \"int64\" }\n          }\n        ],\n        \"responses\": { \"400\": { \"description\": \"Invalid pet value\" } },\n        \"security\": [{ \"petstore_auth\": [\"write:pets\", \"read:pets\"] }]\n      }\n    },\n    \"/pet/{petId}/uploadImage\": {\n      \"post\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"uploads an image\",\n        \"description\": \"\",\n        \"operationId\": \"uploadFile\",\n        \"parameters\": [\n          {\n            \"name\": \"petId\",\n            \"in\": \"path\",\n            \"description\": \"ID of pet to update\",\n            \"required\": true,\n            \"schema\": { \"type\": \"integer\", \"format\": \"int64\" }\n          },\n          {\n            \"name\": \"additionalMetadata\",\n            \"in\": \"query\",\n            \"description\": \"Additional Metadata\",\n            \"required\": false,\n            \"schema\": { \"type\": \"string\" }\n          }\n        ],\n        \"requestBody\": {\n          \"content\": {\n            \"application/octet-stream\": {\n              \"schema\": { \"type\": \"string\", \"format\": \"binary\" }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/ApiResponse\" }\n              }\n            }\n          }\n        },\n        \"security\": [{ \"petstore_auth\": [\"write:pets\", \"read:pets\"] }]\n      }\n    },\n    \"/store/inventory\": {\n      \"get\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Returns pet inventories by status\",\n        \"description\": \"Returns a map of status codes to quantities\",\n        \"operationId\": \"getInventory\",\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"object\",\n                  \"additionalProperties\": {\n                    \"type\": \"integer\",\n                    \"format\": \"int32\"\n                  }\n                }\n              }\n            }\n          }\n        },\n        \"security\": [{ \"api_key\": [] }]\n      }\n    },\n    \"/store/order\": {\n      \"post\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Place an order for a pet\",\n        \"description\": \"Place a new order in the store\",\n        \"operationId\": \"placeOrder\",\n        \"requestBody\": {\n          \"content\": {\n            \"application/json\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/Order\" }\n            },\n            \"application/xml\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/Order\" }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/Order\" }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/Order\" }\n              }\n            }\n          },\n          \"405\": { \"description\": \"Invalid input\" }\n        }\n      }\n    },\n    \"/store/order/{orderId}\": {\n      \"get\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Find purchase order by ID\",\n        \"description\": \"For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions\",\n        \"operationId\": \"getOrderById\",\n        \"parameters\": [\n          {\n            \"name\": \"orderId\",\n            \"in\": \"path\",\n            \"description\": \"ID of order that needs to be fetched\",\n            \"required\": true,\n            \"schema\": { \"type\": \"integer\", \"format\": \"int64\" }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/Order\" }\n              },\n              \"application/json\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/Order\" }\n              }\n            }\n          },\n          \"400\": { \"description\": \"Invalid ID supplied\" },\n          \"404\": { \"description\": \"Order not found\" }\n        }\n      },\n      \"delete\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Delete purchase order by ID\",\n        \"description\": \"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors\",\n        \"operationId\": \"deleteOrder\",\n        \"parameters\": [\n          {\n            \"name\": \"orderId\",\n            \"in\": \"path\",\n            \"description\": \"ID of the order that needs to be deleted\",\n            \"required\": true,\n            \"schema\": { \"type\": \"integer\", \"format\": \"int64\" }\n          }\n        ],\n        \"responses\": {\n          \"400\": { \"description\": \"Invalid ID supplied\" },\n          \"404\": { \"description\": \"Order not found\" }\n        }\n      }\n    },\n    \"/user\": {\n      \"post\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Create user\",\n        \"description\": \"This can only be done by the logged in user.\",\n        \"operationId\": \"createUser\",\n        \"requestBody\": {\n          \"description\": \"Created user object\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n            },\n            \"application/xml\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n            }\n          }\n        },\n        \"responses\": {\n          \"default\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n              },\n              \"application/xml\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n              }\n            }\n          }\n        }\n      }\n    },\n    \"/user/createWithList\": {\n      \"post\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Creates list of users with given input array\",\n        \"description\": \"Creates list of users with given input array\",\n        \"operationId\": \"createUsersWithListInput\",\n        \"requestBody\": {\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"type\": \"array\",\n                \"items\": { \"$ref\": \"#/components/schemas/User\" }\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n              },\n              \"application/json\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n              }\n            }\n          },\n          \"default\": { \"description\": \"successful operation\" }\n        }\n      }\n    },\n    \"/user/login\": {\n      \"get\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Logs user into the system\",\n        \"description\": \"\",\n        \"operationId\": \"loginUser\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"query\",\n            \"description\": \"The user name for login\",\n            \"required\": false,\n            \"schema\": { \"type\": \"string\" }\n          },\n          {\n            \"name\": \"password\",\n            \"in\": \"query\",\n            \"description\": \"The password for login in clear text\",\n            \"required\": false,\n            \"schema\": { \"type\": \"string\" }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"headers\": {\n              \"X-Rate-Limit\": {\n                \"description\": \"calls per hour allowed by the user\",\n                \"schema\": { \"type\": \"integer\", \"format\": \"int32\" }\n              },\n              \"X-Expires-After\": {\n                \"description\": \"date in UTC when toekn expires\",\n                \"schema\": { \"type\": \"string\", \"format\": \"date-time\" }\n              }\n            },\n            \"content\": {\n              \"application/xml\": { \"schema\": { \"type\": \"string\" } },\n              \"application/json\": { \"schema\": { \"type\": \"string\" } }\n            }\n          },\n          \"400\": { \"description\": \"Invalid username/password supplied\" }\n        }\n      }\n    },\n    \"/user/logout\": {\n      \"get\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Logs out current logged in user session\",\n        \"description\": \"\",\n        \"operationId\": \"logoutUser\",\n        \"parameters\": [],\n        \"responses\": { \"default\": { \"description\": \"successful operation\" } }\n      }\n    },\n    \"/user/{username}\": {\n      \"get\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Get user by user name\",\n        \"description\": \"\",\n        \"operationId\": \"getUserByName\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"path\",\n            \"description\": \"The name that needs to be fetched. Use user1 for testing. \",\n            \"required\": true,\n            \"schema\": { \"type\": \"string\" }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n              },\n              \"application/json\": {\n                \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n              }\n            }\n          },\n          \"400\": { \"description\": \"Invalid username supplied\" },\n          \"404\": { \"description\": \"User not found\" }\n        }\n      },\n      \"put\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Update user\",\n        \"description\": \"This can only be done by the logged in user.\",\n        \"operationId\": \"updateUser\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"path\",\n            \"description\": \"name that need to be deleted\",\n            \"required\": true,\n            \"schema\": { \"type\": \"string\" }\n          }\n        ],\n        \"requestBody\": {\n          \"description\": \"Update an existent user in the store\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n            },\n            \"application/xml\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": { \"$ref\": \"#/components/schemas/User\" }\n            }\n          }\n        },\n        \"responses\": { \"default\": { \"description\": \"successful operation\" } }\n      },\n      \"delete\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Delete user\",\n        \"description\": \"This can only be done by the logged in user.\",\n        \"operationId\": \"deleteUser\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"path\",\n            \"description\": \"The name that needs to be deleted\",\n            \"required\": true,\n            \"schema\": { \"type\": \"string\" }\n          }\n        ],\n        \"responses\": {\n          \"400\": { \"description\": \"Invalid username supplied\" },\n          \"404\": { \"description\": \"User not found\" }\n        }\n      }\n    }\n  },\n  \"components\": {\n    \"schemas\": {\n      \"Order\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": { \"type\": \"integer\", \"format\": \"int64\", \"example\": 10 },\n          \"petId\": { \"type\": \"integer\", \"format\": \"int64\", \"example\": 198772 },\n          \"quantity\": { \"type\": \"integer\", \"format\": \"int32\", \"example\": 7 },\n          \"shipDate\": { \"type\": \"string\", \"format\": \"date-time\" },\n          \"status\": {\n            \"type\": \"string\",\n            \"description\": \"Order Status\",\n            \"example\": \"approved\",\n            \"enum\": [\"placed\", \"approved\", \"delivered\"]\n          },\n          \"complete\": { \"type\": \"boolean\" }\n        },\n        \"xml\": { \"name\": \"order\" }\n      },\n      \"Customer\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": { \"type\": \"integer\", \"format\": \"int64\", \"example\": 100000 },\n          \"username\": { \"type\": \"string\", \"example\": \"fehguy\" },\n          \"address\": {\n            \"type\": \"array\",\n            \"xml\": { \"name\": \"addresses\", \"wrapped\": true },\n            \"items\": { \"$ref\": \"#/components/schemas/Address\" }\n          }\n        },\n        \"xml\": { \"name\": \"customer\" }\n      },\n      \"Address\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"street\": { \"type\": \"string\", \"example\": \"437 Lytton\" },\n          \"city\": { \"type\": \"string\", \"example\": \"Palo Alto\" },\n          \"state\": { \"type\": \"string\", \"example\": \"CA\" },\n          \"zip\": { \"type\": \"string\", \"example\": \"94301\" }\n        },\n        \"xml\": { \"name\": \"address\" }\n      },\n      \"Category\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": { \"type\": \"integer\", \"format\": \"int64\", \"example\": 1 },\n          \"name\": { \"type\": \"string\", \"example\": \"Dogs\" }\n        },\n        \"xml\": { \"name\": \"category\" }\n      },\n      \"User\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": { \"type\": \"integer\", \"format\": \"int64\", \"example\": 10 },\n          \"username\": { \"type\": \"string\", \"example\": \"theUser\" },\n          \"firstName\": { \"type\": \"string\", \"example\": \"John\" },\n          \"lastName\": { \"type\": \"string\", \"example\": \"James\" },\n          \"email\": { \"type\": \"string\", \"example\": \"john@email.com\" },\n          \"password\": { \"type\": \"string\", \"example\": \"12345\" },\n          \"phone\": { \"type\": \"string\", \"example\": \"12345\" },\n          \"userStatus\": {\n            \"type\": \"integer\",\n            \"description\": \"User Status\",\n            \"format\": \"int32\",\n            \"example\": 1\n          }\n        },\n        \"xml\": { \"name\": \"user\" }\n      },\n      \"Tag\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": { \"type\": \"integer\", \"format\": \"int64\" },\n          \"name\": { \"type\": \"string\" }\n        },\n        \"xml\": { \"name\": \"tag\" }\n      },\n      \"Pet\": {\n        \"required\": [\"name\", \"photoUrls\"],\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": { \"type\": \"integer\", \"format\": \"int64\", \"example\": 10 },\n          \"name\": { \"type\": \"string\", \"example\": \"doggie\" },\n          \"category\": { \"$ref\": \"#/components/schemas/Category\" },\n          \"photoUrls\": {\n            \"type\": \"array\",\n            \"xml\": { \"wrapped\": true },\n            \"items\": { \"type\": \"string\", \"xml\": { \"name\": \"photoUrl\" } }\n          },\n          \"tags\": {\n            \"type\": \"array\",\n            \"xml\": { \"wrapped\": true },\n            \"items\": { \"$ref\": \"#/components/schemas/Tag\" }\n          },\n          \"status\": {\n            \"type\": \"string\",\n            \"description\": \"pet status in the store\",\n            \"enum\": [\"available\", \"pending\", \"sold\"]\n          }\n        },\n        \"xml\": { \"name\": \"pet\" }\n      },\n      \"ApiResponse\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"code\": { \"type\": \"integer\", \"format\": \"int32\" },\n          \"type\": { \"type\": \"string\" },\n          \"message\": { \"type\": \"string\" }\n        },\n        \"xml\": { \"name\": \"##default\" }\n      }\n    },\n    \"requestBodies\": {\n      \"Pet\": {\n        \"description\": \"Pet object that needs to be added to the store\",\n        \"content\": {\n          \"application/json\": {\n            \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n          },\n          \"application/xml\": {\n            \"schema\": { \"$ref\": \"#/components/schemas/Pet\" }\n          }\n        }\n      },\n      \"UserArray\": {\n        \"description\": \"List of user object\",\n        \"content\": {\n          \"application/json\": {\n            \"schema\": {\n              \"type\": \"array\",\n              \"items\": { \"$ref\": \"#/components/schemas/User\" }\n            }\n          }\n        }\n      }\n    },\n    \"securitySchemes\": {\n      \"petstore_auth\": {\n        \"type\": \"oauth2\",\n        \"flows\": {\n          \"implicit\": {\n            \"authorizationUrl\": \"https://petstore3.swagger.io/oauth/authorize\",\n            \"scopes\": {\n              \"write:pets\": \"modify pets in your account\",\n              \"read:pets\": \"read your pets\"\n            }\n          }\n        }\n      },\n      \"api_key\": { \"type\": \"apiKey\", \"name\": \"api_key\", \"in\": \"header\" }\n    }\n  }\n}\n"
  },
  {
    "path": "docs/virtual/redux-logger/index.ts",
    "content": "import type { Middleware } from 'redux'\n\ndeclare const logger: Middleware\n\nexport { logger }\n\nexport default logger\n"
  },
  {
    "path": "docs/virtual/your-cool-library/index.ts",
    "content": "declare const toast: { warn(args: any): void }\nexport { toast }\n"
  },
  {
    "path": "errors.json",
    "content": "{\n  \"0\": \"prepareAction did not return an object\",\n  \"1\": \"`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers\",\n  \"2\": \"`middleware` field must be a callback\",\n  \"3\": \"when using a middleware builder function, an array of middleware must be returned\",\n  \"4\": \"each middleware provided to configureStore must be a function\",\n  \"5\": \"`enhancers` field must be a callback\",\n  \"6\": \"`enhancers` callback must return an array\",\n  \"7\": \"each enhancer provided to configureStore must be a function\",\n  \"8\": \"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\",\n  \"9\": \"A case reducer on a non-draftable value must not return undefined\",\n  \"10\": \"No insert provided for key not already in map\",\n  \"11\": \"`name` is a required option for createSlice\",\n  \"12\": \"`context.addCase` cannot be called with an empty action type\",\n  \"13\": \"`context.addCase` cannot be called with two reducers for the same action type: type\",\n  \"14\": \"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\",\n  \"15\": \"selectSlice returned undefined for an uninjected slice reducer\",\n  \"16\": \"selectState returned undefined for an uninjected slice reducer\",\n  \"17\": \"Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.\",\n  \"18\": \"Cannot use `create.asyncThunk` in the built-in `createSlice`. Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.\",\n  \"19\": \"A state mutation was detected between dispatches, in the path ''.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)\",\n  \"20\": \"A state mutation was detected inside a dispatch, in the path: . Take a look at the reducer(s) handling the action . (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)\",\n  \"21\": \"Creating or removing a listener requires one of the known fields for matching an action\",\n  \"22\": \"Unsubscribe not initialized\",\n  \"23\": \": getOriginalState can only be called synchronously\",\n  \"24\": \"The slice reducer for key \\\"\\\" returned undefined when called for selector(). If the state passed to the reducer is undefined, you must explicitly return the initial state. The initial state may not be undefined. If you don't want to set a value for this reducer, you can use null instead of undefined.\",\n  \"25\": \"original must be used on state Proxy\",\n  \"26\": \"`builder.addCase` should only be called before calling `builder.addMatcher`\",\n  \"27\": \"`builder.addCase` should only be called before calling `builder.addDefaultCase`\",\n  \"28\": \"`builder.addCase` cannot be called with an empty action type\",\n  \"29\": \"`builder.addCase` cannot be called with two reducers for the same action type ''\",\n  \"30\": \"`builder.addMatcher` should only be called before calling `builder.addDefaultCase`\",\n  \"31\": \"`builder.addDefaultCase` can only be called once\",\n  \"32\": \" is not a function\",\n  \"33\": \"When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.\",\n  \"34\": \"Warning: Middleware for RTK-Query API at reducerPath \\\"\\\" has not been added to the store.\\nYou must add the middleware for RTK-Query to function correctly!\",\n  \"35\": \"Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.\",\n  \"36\": \"When using custom hooks for context, all  hooks need to be provided: .\\\\nHook  was either not provided or not a function.\",\n  \"37\": \"Warning: Middleware for RTK-Query API at reducerPath \\\"\\\" has not been added to the store.\\n    You must add the middleware for RTK-Query to function correctly!\",\n  \"38\": \"Cannot refetch a query that has not been started yet.\",\n  \"39\": \"called \\\\`injectEndpoints\\\\` to override already-existing endpointName  without specifying \\\\`overrideExisting: true\\\\`\",\n  \"40\": \"maxPages for endpoint '' must be a number greater than 0\",\n  \"41\": \"getPreviousPageParam for endpoint '' must be a function if maxPages is used\",\n  \"42\": \"Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.\",\n  \"43\": \"`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`\"\n}\n"
  },
  {
    "path": "examples/action-listener/counter/package.json",
    "content": "{\n  \"name\": \"@examples-action-listener/counter\",\n  \"version\": \"1.0.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^1.8.0\",\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"clsx\": \"1.1.1\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-scripts\": \"5.0.1\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"lint:ts\": \"tsc --noEmit\",\n    \"test\": \"react-scripts test --runInBand\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  },\n  \"devDependencies\": {\n    \"jest-watch-typeahead\": \"^1.1.0\"\n  }\n}\n"
  },
  {
    "path": "examples/action-listener/counter/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <link\n      rel=\"stylesheet\"\n      href=\"https://unpkg.com/papercss@1.8.2/dist/paper.min.css\"\n    />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <title>Counter Example - Action Middleware</title>\n    <script>\n      ;(function () {\n        'use strict'\n        if (window.matchMedia('(prefers-color-scheme: dark)').matches) {\n          document.documentElement.classList.add('dark')\n        }\n      })()\n    </script>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/action-listener/counter/src/components/App/App.tsx",
    "content": "import React, { useEffect } from 'react'\nimport { Provider } from 'react-redux'\nimport type { Unsubscribe } from '@reduxjs/toolkit'\nimport { setupThemeListeners } from '../../services/theme/listeners'\nimport { setupCounterListeners } from '../../services/counter/listeners'\nimport { ChangeThemeForm } from '../ChangeThemeForm/ChangeThemeForm'\nimport { CounterList } from '../CounterList/CounterList'\nimport { CreateCounterForm } from '../CreateCounterForm/CreateCounterForm'\nimport { store, startAppListening } from '../../store'\n\nexport function App() {\n  useEffect(() => {\n    const subscriptions: Unsubscribe[] = [\n      setupCounterListeners(startAppListening),\n      setupThemeListeners(startAppListening),\n    ]\n\n    return () => subscriptions.forEach((unsubscribe) => unsubscribe())\n  }, [])\n\n  return (\n    <React.StrictMode>\n      <Provider store={store}>\n        <main className={'main'}>\n          <header className=\"App-header\">\n            <h1>Counter example</h1>\n          </header>\n          <ChangeThemeForm />\n          <CreateCounterForm />\n          <CounterList />\n        </main>\n      </Provider>\n    </React.StrictMode>\n  )\n}\n"
  },
  {
    "path": "examples/action-listener/counter/src/components/ChangeThemeForm/ChangeThemeForm.tsx",
    "content": "import { FormEvent, ChangeEvent } from 'react'\nimport { useAppDispatch, useAppSelector } from '../../store'\nimport { themeActions, ThemeState } from '../../services/theme/slice'\nimport styles from './changeThemeForm.module.css'\n\nfunction isChecked(theme: ThemeState): boolean {\n  return theme.colorScheme === 'light'\n}\n\nexport function ChangeThemeForm() {\n  const theme = useAppSelector((state) => state.theme)\n  const appDispatch = useAppDispatch()\n\n  const handleSubmit = (evt: FormEvent) => {\n    evt.preventDefault()\n  }\n\n  const handleChange = (evt: ChangeEvent<HTMLInputElement>) => {\n    appDispatch(\n      themeActions.changeColorScheme(\n        theme.colorScheme === 'light' ? 'dark' : 'light',\n      ),\n    )\n  }\n\n  return (\n    <form action=\"#\" onSubmit={handleSubmit} className={styles.form}>\n      <div className=\"form-group\">\n        <label htmlFor=\"theme-switch\" className={styles.colorSchemeIcon}>\n          <svg\n            aria-hidden=\"true\"\n            xmlns=\"http://www.w3.org/2000/svg\"\n            viewBox=\"0 0 24 24\"\n            fill=\"currentColor\"\n            stroke=\"currentColor\"\n            strokeWidth=\"2\"\n            strokeLinecap=\"round\"\n            strokeLinejoin=\"round\"\n          >\n            {theme.colorScheme === 'light' ? (\n              <>\n                <circle cx=\"12\" cy=\"12\" r=\"5\" />\n                <line x1=\"12\" y1=\"1\" x2=\"12\" y2=\"3\" />\n                <line x1=\"12\" y1=\"21\" x2=\"12\" y2=\"23\" />\n                <line x1=\"4.22\" y1=\"4.22\" x2=\"5.64\" y2=\"5.64\" />\n                <line x1=\"18.36\" y1=\"18.36\" x2=\"19.78\" y2=\"19.78\" />\n                <line x1=\"1\" y1=\"12\" x2=\"3\" y2=\"12\" />\n                <line x1=\"21\" y1=\"12\" x2=\"23\" y2=\"12\" />\n                <line x1=\"4.22\" y1=\"19.78\" x2=\"5.64\" y2=\"18.36\" />\n                <line x1=\"18.36\" y1=\"5.64\" x2=\"19.78\" y2=\"4.22\" />\n              </>\n            ) : (\n              <path d=\"M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z\" />\n            )}\n          </svg>\n        </label>\n        <label htmlFor=\"theme-switch\" className=\"paper-switch\">\n          <input\n            id=\"theme-switch\"\n            name=\"theme-switch\"\n            type=\"checkbox\"\n            checked={isChecked(theme)}\n            onChange={handleChange}\n          />\n          <span className=\"paper-switch-slider round\"></span>\n        </label>\n      </div>\n    </form>\n  )\n}\n"
  },
  {
    "path": "examples/action-listener/counter/src/components/ChangeThemeForm/changeThemeForm.module.css",
    "content": ".form {\n  position: absolute;\n  top: 0.3rem;\n  right: 0.3rem;\n  z-index: 3;\n}\n\n.colorSchemeIcon {\n  width: 1.1rem;\n  margin: 0 !important;\n  padding-top: 0.1rem;\n}\n\n.form :global(.form-group) {\n  display: flex;\n  align-items: center;\n  gap: 0.2rem;\n}\n"
  },
  {
    "path": "examples/action-listener/counter/src/components/Counter/Counter.tsx",
    "content": "import { EntityId } from '@reduxjs/toolkit'\nimport { memo } from 'react'\nimport { counterActions, counterSelectors } from '../../services/counter/slice'\nimport { useAppDispatch, useAppSelector } from '../../store'\nimport styles from './counter.module.css'\nimport clsx from 'clsx'\n\nexport interface CounterProps {\n  counterId: EntityId\n}\n\nconst intervalMs = 1_000\nconst delayMs = 2_000\n\nexport const Counter = memo(function Counter({ counterId }: CounterProps) {\n  const counter = useAppSelector((state) =>\n    counterSelectors.selectById(state, counterId),\n  )\n  const appDispatch = useAppDispatch()\n\n  if (!counter) {\n    return null\n  }\n\n  const { id, value } = counter\n\n  const add = () => appDispatch(counterActions.updateBy({ id, delta: +1 }))\n  const subtract = () => appDispatch(counterActions.updateBy({ id, delta: -1 }))\n  const close = () => appDispatch(counterActions.removeCounter(id))\n  const updateAsync = () =>\n    appDispatch(counterActions.updateByAsync({ id, delayMs, delta: 1 }))\n  const intervalUpdate = () => {\n    if (counter.intervalMs) {\n      appDispatch(counterActions.cancelAsyncUpdates(id))\n    } else {\n      appDispatch(\n        counterActions.updateByPeriodically({ id, delta: 1, intervalMs }),\n      )\n    }\n  }\n\n  return (\n    <section className={clsx('paper', styles.wrapper)}>\n      <button\n        type=\"button\"\n        className={styles.closeBtn}\n        aria-label=\"close\"\n        title=\"close\"\n        onClick={close}\n      >\n        &times;\n      </button>\n      <h4>ID: {id}</h4>\n      <strong className={clsx(styles.counterValue, 'badge')}>{value}</strong>\n      <div className={styles.btnGroup}>\n        <button className=\"btn-small\" type=\"button\" onClick={add}>\n          +\n        </button>\n        <button className=\"btn-small\" type=\"button\" onClick={subtract}>\n          -\n        </button>\n        <button className=\"btn-small\" type=\"button\" onClick={intervalUpdate}>\n          {counter.intervalMs\n            ? `stop periodic update`\n            : `+1 every ${intervalMs / 1_000}s`}\n        </button>\n        <button className=\"btn-small\" onClick={updateAsync}>\n          +1 after {`${delayMs / 1000}s`}\n        </button>\n      </div>\n    </section>\n  )\n})\n"
  },
  {
    "path": "examples/action-listener/counter/src/components/Counter/counter.module.css",
    "content": ".counterValue {\n  font-weight: 700;\n  font-size: 1.3rem;\n}\n\n.closeBtn {\n  position: absolute;\n  right: -8px;\n  top: -8px;\n  border: none;\n  background: transparent;\n  transition: none;\n  box-shadow: none;\n}\n\n.wrapper .closeBtn.closeBtn:hover,\n.wrapper .closeBtn.closeBtn:focus {\n  box-shadow: none;\n  transform: none;\n  border-color: transparent;\n  border: none;\n}\n\n.wrapper {\n  display: grid;\n  grid-template-columns: 1fr auto;\n  grid-template-rows: 1fr 1fr;\n  position: relative;\n  align-items: baseline;\n  padding: 1.5rem 1rem;\n  overflow: hidden;\n}\n\n.btnGroup {\n  display: flex;\n  gap: 4px;\n}\n\n.wrapper .btnGroup button {\n  margin: 0;\n}\n\n.wrapper h4 {\n  font-size: 1rem;\n}\n\n.btnGroup button:not(:first-of-type) {\n  margin-left: 0.4rem;\n}\n\n@media screen and (min-width: 780px) {\n  .wrapper {\n    grid-template-columns: 1fr auto 2fr;\n  }\n\n  .btnGroup {\n    justify-content: flex-end;\n  }\n}\n"
  },
  {
    "path": "examples/action-listener/counter/src/components/CounterList/CounterList.tsx",
    "content": "import { useAppSelector } from '../../store'\nimport { counterSelectors } from '../../services/counter/slice'\nimport { Counter } from '../Counter/Counter'\nimport styles from './counter.module.css'\n\nexport function CounterList() {\n  const counterIds = useAppSelector((state) =>\n    counterSelectors.selectIds(state),\n  )\n\n  return (\n    <article className={styles.wrapper}>\n      <h3>Counters</h3>\n      {counterIds.map((counterId) => (\n        <Counter key={counterId} counterId={counterId} />\n      ))}\n    </article>\n  )\n}\n"
  },
  {
    "path": "examples/action-listener/counter/src/components/CounterList/counter.module.css",
    "content": ".wrapper {\n  display: contents;\n}\n\n.wrapper p {\n  margin: 0.2rem;\n}\n"
  },
  {
    "path": "examples/action-listener/counter/src/components/CreateCounterForm/CreateCounterForm.tsx",
    "content": "import { FormEvent, useState } from 'react'\nimport styles from './createCounter.module.css'\nimport clsx from 'clsx'\nimport { useAppDispatch } from '../../store'\nimport { counterActions } from '../../services/counter/slice'\n\nconst sectionClassname = clsx('paper', styles.section)\n\nexport function CreateCounterForm() {\n  const [initialValue, setInitialValue] = useState(0)\n  const appDispatch = useAppDispatch()\n  const handleSubmit = (evt: FormEvent) => {\n    evt.preventDefault()\n    appDispatch(counterActions.addCounter({ initialValue }))\n  }\n\n  return (\n    <section className={sectionClassname}>\n      <h3 className={styles.heading}>Create counter</h3>\n      <form action=\"#\" className={styles.form} onSubmit={handleSubmit}>\n        <div className=\"form-group\">\n          <label htmlFor=\"input-range\">initial value: {initialValue}</label>\n          <input\n            type=\"range\"\n            name=\"counter-value\"\n            id=\"counter-value\"\n            min={0}\n            max={10}\n            value={initialValue}\n            onChange={({ target }) => {\n              setInitialValue(Number(target.value))\n            }}\n          />\n        </div>\n        <button type=\"submit\">Add counter</button>\n      </form>\n    </section>\n  )\n}\n"
  },
  {
    "path": "examples/action-listener/counter/src/components/CreateCounterForm/createCounter.module.css",
    "content": ".form {\n  padding: 0.5rem 0 0;\n}\n\n.heading {\n  margin: 0;\n}\n\n.form :global(.form-group) {\n  display: flex;\n  gap: 0.5rem;\n}\n\n.form label {\n  width: 150px;\n}\n\n.form input[type='range'] {\n  max-width: 75%;\n}\n\n.section {\n  overflow: hidden;\n}\n"
  },
  {
    "path": "examples/action-listener/counter/src/index.css",
    "content": "body {\n  margin: 0;\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n    sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n    monospace;\n}\n\nh1 {\n  text-align: center;\n  font-size: 2.5rem;\n  margin: 1rem 0;\n}\n\n@media screen and (min-width: 780px) {\n  h1 {\n    font-size: 3.5rem;\n  }\n}\n\nh2,\nh3 {\n  margin: 0.5rem 0;\n}\n\nh4,\nh5,\nh6 {\n  font-size: 1.2rem;\n  margin: 0;\n}\n\n.main {\n  max-width: 90%;\n  margin: 0 auto;\n}\n\n@media screen and (min-width: 780px) {\n  .main {\n    max-width: 720px;\n  }\n}\n\n.dark body {\n  background: var(--main-background);\n}\n"
  },
  {
    "path": "examples/action-listener/counter/src/index.tsx",
    "content": "import ReactDOM from 'react-dom/client'\nimport './index.css'\nimport { store } from './store'\nimport { themeActions } from './services/theme/slice'\nimport { App } from './components/App/App'\n\nif (window.matchMedia('(prefers-color-scheme: dark)').matches) {\n  store.dispatch(themeActions.changeColorScheme('dark'))\n}\n\nconst root = ReactDOM.createRoot(document.getElementById('root') as HTMLElement)\n\nroot.render(<App />)\n"
  },
  {
    "path": "examples/action-listener/counter/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/action-listener/counter/src/services/counter/listeners.ts",
    "content": "import { counterActions, counterSelectors } from './slice'\nimport {\n  UnknownAction,\n  isAllOf,\n  isAnyOf,\n  PayloadAction,\n  Unsubscribe,\n} from '@reduxjs/toolkit'\nimport type { AppListenerEffectAPI, AppStartListening } from '../../store'\n\nfunction shouldStopAsyncTasksOf(id: string) {\n  return isAllOf(\n    isAnyOf(counterActions.cancelAsyncUpdates, counterActions.removeCounter),\n    (action: UnknownAction): action is PayloadAction<string> =>\n      action?.payload === id,\n  )\n}\n\nasync function onUpdateByPeriodically(\n  {\n    payload: { id, delta },\n  }: ReturnType<typeof counterActions.updateByPeriodically>,\n  { dispatch, getState, getOriginalState, condition }: AppListenerEffectAPI,\n) {\n  const counter = counterSelectors.selectById(getState(), id)\n\n  if (!counter || !counter.intervalMs) {\n    console.error(`invalid counter update request`)\n    return\n  }\n\n  const counterBefore = counterSelectors.selectById(getOriginalState(), id)\n\n  if (counterBefore?.intervalMs) {\n    console.error(`counter with id \"${id}\" is already updating periodically`)\n    return\n  }\n\n  const intervalRef = setInterval(() => {\n    dispatch(counterActions.updateBy({ id, delta }))\n  }, counter.intervalMs)\n\n  await condition(shouldStopAsyncTasksOf(id))\n\n  clearInterval(intervalRef)\n  console.log(`stopped periodic update of ${counter.id}`)\n}\n\nasync function onUpdateAsync(\n  {\n    payload: { id, delta, delayMs },\n  }: ReturnType<typeof counterActions.updateByAsync>,\n  { condition, dispatch, getState }: AppListenerEffectAPI,\n) {\n  const counter = counterSelectors.selectById(getState(), id)\n\n  if (!counter) {\n    console.error(`could not find counter with id ${id}`)\n    return\n  }\n\n  if (!(await condition(shouldStopAsyncTasksOf(id), delayMs))) {\n    dispatch(counterActions.updateBy({ id, delta }))\n  } else {\n    console.log(`blocked async update of ${counter.id}`)\n  }\n}\n\n/**\n * Subscribes counter listeners and returns a `teardown` function.\n * @example\n * ```ts\n * useEffect(() => {\n *   const unsubscribe = setupCounterListeners();\n *   return unsubscribe;\n * }, []);\n * ```\n */\nexport function setupCounterListeners(\n  startListening: AppStartListening,\n): Unsubscribe {\n  const subscriptions = [\n    startListening({\n      actionCreator: counterActions.updateByPeriodically,\n      effect: onUpdateByPeriodically,\n    }),\n    startListening({\n      actionCreator: counterActions.updateByAsync,\n      effect: onUpdateAsync,\n    }),\n  ]\n\n  return () => {\n    subscriptions.forEach((unsubscribe) => unsubscribe())\n  }\n}\n"
  },
  {
    "path": "examples/action-listener/counter/src/services/counter/slice.ts",
    "content": "import {\n  createSlice,\n  createEntityAdapter,\n  nanoid,\n  PayloadAction,\n} from '@reduxjs/toolkit'\n\nexport interface Counter {\n  value: number\n  id: string\n  intervalMs?: number\n}\n\nconst counterEntity = createEntityAdapter<Counter>()\n\nexport const counterSlice = createSlice({\n  name: 'counter',\n  initialState: {\n    counters: counterEntity.getInitialState(),\n  },\n  reducers: {\n    addCounter(\n      state,\n      { payload: { initialValue } }: PayloadAction<{ initialValue: number }>,\n    ) {\n      counterEntity.addOne(state.counters, {\n        value: initialValue,\n        id: nanoid(),\n      })\n    },\n    removeCounter(state, { payload }: PayloadAction<string>) {\n      counterEntity.removeOne(state.counters, payload)\n    },\n    updateValue(state, action: PayloadAction<{ id: string; value: number }>) {\n      counterEntity.upsertOne(state.counters, action)\n    },\n    updateBy(\n      state,\n      { payload: { id, delta } }: PayloadAction<{ id: string; delta: number }>,\n    ) {\n      const previousValue = state.counters.entities[id]?.value\n\n      if (typeof previousValue === 'number') {\n        counterEntity.updateOne(state.counters, {\n          id,\n          changes: { value: delta + previousValue },\n        })\n      }\n    },\n    updateByPeriodically(\n      state,\n      {\n        payload: { id, intervalMs },\n      }: PayloadAction<{ id: string; delta: number; intervalMs: number }>,\n    ) {\n      const previousValue = state.counters.entities[id]?.value\n      const previousIntervalMs = state.counters.entities[id]?.intervalMs\n      if (\n        typeof previousValue === 'number' &&\n        Number.isFinite(intervalMs) &&\n        intervalMs > 0 &&\n        !previousIntervalMs\n      ) {\n        counterEntity.updateOne(state.counters, {\n          id,\n          changes: { intervalMs },\n        })\n      }\n    },\n    updateByAsync(\n      _,\n      action: PayloadAction<{ id: string; delta: number; delayMs: number }>,\n    ) {},\n    cancelAsyncUpdates(state, { payload }: PayloadAction<string>) {\n      delete state.counters.entities[payload]?.intervalMs\n    },\n  },\n})\n\nexport const counterActions = counterSlice.actions\n\nexport type CounterSlice = {\n  [counterSlice.name]: ReturnType<(typeof counterSlice)['reducer']>\n}\n\nexport const counterSelectors = counterEntity.getSelectors<CounterSlice>(\n  (state) => state[counterSlice.name].counters,\n)\n"
  },
  {
    "path": "examples/action-listener/counter/src/services/counter/tests/listener.test.ts",
    "content": "import { configureStore, createListenerMiddleware } from '@reduxjs/toolkit'\nimport { setupCounterListeners } from '../listeners'\nimport { counterSlice, counterActions, counterSelectors } from '../slice'\nimport type { AppStartListening } from '../../../store'\n\nfunction delay(timerMs: number): Promise<number> {\n  return new Promise((resolve) => {\n    setTimeout(resolve, timerMs, timerMs)\n  })\n}\n\njest.useRealTimers()\n\ndescribe('counter - listeners', () => {\n  const onMiddlewareError = jest.fn((): void => {}) // https://jestjs.io/docs/mock-function-api\n\n  /**\n   * @see https://redux-toolkit.js.org/api/createListenerMiddleware\n   */\n  const listenerMiddlewareInstance = createListenerMiddleware({\n    onError: onMiddlewareError,\n  })\n\n  function setupTestStore() {\n    return configureStore({\n      reducer: {\n        [counterSlice.name]: counterSlice.reducer,\n      },\n      middleware: (gDM) => gDM().prepend(listenerMiddlewareInstance.middleware),\n    })\n  }\n\n  let store = setupTestStore()\n\n  beforeEach(() => {\n    listenerMiddlewareInstance.clearListeners() // Stops and cancels active listeners https://redux-toolkit.js.org/api/createListenerMiddleware#clearlisteners\n    onMiddlewareError.mockClear() // https://jestjs.io/docs/mock-function-api#mockfnmockclear\n    store = setupTestStore() // resets store state\n\n    setupCounterListeners(\n      listenerMiddlewareInstance.startListening as AppStartListening,\n    )\n  })\n\n  describe('onUpdateAsync', () => {\n    const delayMs = 10\n    const initialValue = 2\n    const delta = 2\n\n    it('asynchronously adds `payload.delta` after `payload.delayMs` to counter', async () => {\n      store.dispatch(counterActions.addCounter({ initialValue }))\n\n      const { id } = counterSelectors.selectAll(store.getState())[0]\n\n      store.dispatch(counterActions.updateByAsync({ id, delayMs, delta }))\n\n      expect(counterSelectors.selectById(store.getState(), id)?.value).toBe(\n        initialValue,\n      )\n\n      await delay(delayMs)\n\n      expect(counterSelectors.selectById(store.getState(), id)?.value).toBe(\n        initialValue + delta,\n      )\n    })\n\n    it('stops updates if cancelAsyncUpdates is dispatched', async () => {\n      store.dispatch(counterActions.addCounter({ initialValue }))\n\n      const { id } = counterSelectors.selectAll(store.getState())[0]\n\n      store.dispatch(counterActions.updateByAsync({ id, delayMs, delta }))\n\n      expect(counterSelectors.selectById(store.getState(), id)?.value).toBe(\n        initialValue,\n      )\n\n      store.dispatch(counterActions.cancelAsyncUpdates(id))\n\n      await delay(delayMs)\n\n      expect(counterSelectors.selectById(store.getState(), id)?.value).toBe(\n        initialValue,\n      )\n    })\n  })\n\n  describe('onUpdateByPeriodically', () => {\n    const intervalMs = 10\n    const initialValue = 2\n    const delta = 2\n\n    it('periodically adds `payload.delta` after `payload.intervalMs` to counter', async () => {\n      store.dispatch(counterActions.addCounter({ initialValue }))\n\n      const { id } = counterSelectors.selectAll(store.getState())[0]\n\n      store.dispatch(\n        counterActions.updateByPeriodically({ id, intervalMs, delta }),\n      )\n\n      for (let i = 0; i < 2; i++) {\n        expect(counterSelectors.selectById(store.getState(), id)?.value).toBe(\n          initialValue + i * delta,\n        )\n\n        await delay(intervalMs)\n\n        expect(counterSelectors.selectById(store.getState(), id)?.value).toBe(\n          initialValue + (i + 1) * delta,\n        )\n      }\n    })\n\n    it('stops updates if cancelAsyncUpdates is dispatched', async () => {\n      store.dispatch(counterActions.addCounter({ initialValue }))\n\n      const { id } = counterSelectors.selectAll(store.getState())[0]\n\n      store.dispatch(\n        counterActions.updateByPeriodically({ id, intervalMs, delta }),\n      )\n\n      await delay(intervalMs)\n      expect(counterSelectors.selectById(store.getState(), id)?.value).toBe(\n        initialValue + delta,\n      )\n\n      store.dispatch(counterActions.cancelAsyncUpdates(id))\n\n      await delay(intervalMs)\n\n      expect(counterSelectors.selectById(store.getState(), id)?.value).toBe(\n        initialValue + delta,\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "examples/action-listener/counter/src/services/theme/listeners.ts",
    "content": "import { themeActions } from './slice'\nimport type { AppStartListening } from '../../store'\nimport { Unsubscribe } from '@reduxjs/toolkit'\n\nfunction onChangeColorScheme(\n  action: ReturnType<typeof themeActions.changeColorScheme>,\n) {\n  document.documentElement.classList.toggle('dark', action.payload !== 'light')\n}\n\nexport function setupThemeListeners(\n  startListening: AppStartListening,\n): Unsubscribe {\n  const listeners = [\n    startListening({\n      actionCreator: themeActions.changeColorScheme,\n      effect: onChangeColorScheme,\n    }),\n  ]\n\n  return () => listeners.forEach((unsubscribe) => unsubscribe())\n}\n"
  },
  {
    "path": "examples/action-listener/counter/src/services/theme/slice.ts",
    "content": "import { createSlice } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\n\nexport type ColorScheme = 'light' | 'dark'\n\nexport interface ThemeState {\n  colorScheme: ColorScheme\n}\n\nexport const themeSlice = createSlice({\n  name: 'theme',\n  initialState: {\n    colorScheme: 'light',\n  } as ThemeState,\n  reducers: {\n    changeColorScheme(state, action: PayloadAction<ColorScheme>) {\n      state.colorScheme = action.payload\n    },\n  },\n})\n\nexport const themeActions = themeSlice.actions\n"
  },
  {
    "path": "examples/action-listener/counter/src/store.ts",
    "content": "import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'\nimport {\n  configureStore,\n  createListenerMiddleware,\n  TypedStartListening,\n  TypedAddListener,\n  ListenerEffectAPI,\n  addListener,\n} from '@reduxjs/toolkit'\nimport { counterSlice } from './services/counter/slice'\nimport { themeSlice } from './services/theme/slice'\n\nconst listenerMiddlewareInstance = createListenerMiddleware({\n  onError: () => console.error,\n})\n\nconst store = configureStore({\n  reducer: {\n    [counterSlice.name]: counterSlice.reducer,\n    [themeSlice.name]: themeSlice.reducer,\n  },\n  middleware: (gDM) => gDM().prepend(listenerMiddlewareInstance.middleware),\n})\n\nexport { store }\n\n// Infer the `RootState` and `AppDispatch` types from the store itself\nexport type RootState = ReturnType<typeof store.getState>\n// @see https://redux-toolkit.js.org/usage/usage-with-typescript#getting-the-dispatch-type\nexport type AppDispatch = typeof store.dispatch\n\nexport type AppListenerEffectAPI = ListenerEffectAPI<RootState, AppDispatch>\n\n// @see https://redux-toolkit.js.org/api/createListenerMiddleware#typescript-usage\nexport type AppStartListening = TypedStartListening<RootState, AppDispatch>\nexport type AppAddListener = TypedAddListener<RootState, AppDispatch>\n\nexport const startAppListening =\n  listenerMiddlewareInstance.startListening as AppStartListening\nexport const addAppListener = addListener as AppAddListener\n\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = () => useDispatch<AppDispatch>()\nexport const useAppSelector: TypedUseSelectorHook<RootState> = useSelector\n"
  },
  {
    "path": "examples/action-listener/counter/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n\n# production\n/build\n\n# misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\ntypesversions\n.cache\n.yarnrc\n.yarn/*\n!.yarn/patches\n!.yarn/releases\n!.yarn/plugins\n!.yarn/sdks\n!.yarn/versions\n.pnp.*\n*.tgz\n"
  },
  {
    "path": "examples/publish-ci/cra4/README.md",
    "content": "# Getting Started with Create React App\n\nThis project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), using the [Redux](https://redux.js.org/) and [Redux Toolkit](https://redux-toolkit.js.org/) TS template.\n\n## Available Scripts\n\nIn the project directory, you can run:\n\n### `npm start`\n\nRuns the app in the development mode.\\\nOpen [http://localhost:3000](http://localhost:3000) to view it in the browser.\n\nThe page will reload if you make edits.\\\nYou will also see any lint errors in the console.\n\n### `npm test`\n\nLaunches the test runner in the interactive watch mode.\\\nSee the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.\n\n### `npm run build`\n\nBuilds the app for production to the `build` folder.\\\nIt correctly bundles React in production mode and optimizes the build for the best performance.\n\nThe build is minified and the filenames include the hashes.\\\nYour app is ready to be deployed!\n\nSee the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.\n\n### `npm run eject`\n\n**Note: this is a one-way operation. Once you `eject`, you can’t go back!**\n\nIf you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.\n\nInstead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.\n\nYou don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.\n\n## Learn More\n\nYou can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).\n\nTo learn React, check out the [React documentation](https://reactjs.org/).\n"
  },
  {
    "path": "examples/publish-ci/cra4/package.json",
    "content": "{\n  \"name\": \"rtk-esm-cra\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^2.0.0-rc.3\",\n    \"msw\": \"^1.3.2\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-redux\": \"^9.0.0-rc.0\",\n    \"react-scripts\": \"^4\",\n    \"web-vitals\": \"^2.1.4\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"eject\": \"react-scripts eject\",\n    \"serve-app\": \"yarn serve -s build\",\n    \"test\": \"yarn playwright test\",\n    \"format\": \"prettier --write \\\"./src/**/*.{ts,tsx}\\\" \\\"**/*.md\\\"\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\",\n      \"react-app/jest\"\n    ]\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  },\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  },\n  \"devDependencies\": {\n    \"@playwright/test\": \"^1.31.1\",\n    \"@testing-library/jest-dom\": \"^5.16.5\",\n    \"@testing-library/react\": \"^13.4.0\",\n    \"@testing-library/user-event\": \"^14.4.3\",\n    \"@types/jest\": \"^27.5.2\",\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^18.0.26\",\n    \"@types/react-dom\": \"^18.0.10\",\n    \"playwright\": \"^1.31.1\",\n    \"prettier\": \"^3.2.5\",\n    \"serve\": \"^14.2.0\",\n    \"typescript\": \"^5.9.3\"\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/playwright.config.ts",
    "content": "import { defineConfig } from '@playwright/test'\nexport default defineConfig({\n  webServer: {\n    command: 'yarn serve-app',\n    port: 3000,\n    timeout: 120 * 1000,\n    reuseExistingServer: !process.env.CI,\n  },\n  timeout: 120 * 1000,\n  use: {\n    headless: true,\n    viewport: { width: 1280, height: 720 },\n    ignoreHTTPSErrors: true,\n  },\n  testDir: 'tests/playwright/',\n})\n"
  },
  {
    "path": "examples/publish-ci/cra4/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React Redux App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/publish-ci/cra4/public/manifest.json",
    "content": "{\n  \"short_name\": \"React App\",\n  \"name\": \"Create React App Sample\",\n  \"icons\": [\n    {\n      \"src\": \"favicon.ico\",\n      \"sizes\": \"64x64 32x32 24x24 16x16\",\n      \"type\": \"image/x-icon\"\n    },\n    {\n      \"src\": \"logo192.png\",\n      \"type\": \"image/png\",\n      \"sizes\": \"192x192\"\n    },\n    {\n      \"src\": \"logo512.png\",\n      \"type\": \"image/png\",\n      \"sizes\": \"512x512\"\n    }\n  ],\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/public/mockServiceWorker.js",
    "content": "/* eslint-disable */\n/* tslint:disable */\n\n/**\n * Mock Service Worker (1.3.2).\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n\nconst INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  self.skipWaiting()\n})\n\nself.addEventListener('activate', function (event) {\n  event.waitUntil(self.clients.claim())\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll({\n    type: 'window',\n  })\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n  const accept = request.headers.get('accept') || ''\n\n  // Bypass server-sent events.\n  if (accept.includes('text/event-stream')) {\n    return\n  }\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  // Generate unique request ID.\n  const requestId = Math.random().toString(16).slice(2)\n\n  event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      if (error.name === 'NetworkError') {\n        console.warn(\n          '[MSW] Successfully emulated a network error for the \"%s %s\" request.',\n          request.method,\n          request.url,\n        )\n        return\n      }\n\n      // At this point, any exception indicates an issue with the original request/response.\n      console.error(\n        `\\\n[MSW] Caught an exception from the \"%s %s\" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,\n        request.method,\n        request.url,\n        `${error.name}: ${error.message}`,\n      )\n    }),\n  )\n})\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMainClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: Object.fromEntries(clonedResponse.headers.entries()),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\n// Resolve the main client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMainClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client?.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll({\n    type: 'window',\n  })\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const clonedRequest = request.clone()\n\n  function passthrough() {\n    // Clone the request because it might've been already used\n    // (i.e. its body has been read and sent to the client).\n    const headers = Object.fromEntries(clonedRequest.headers.entries())\n\n    // Remove MSW-specific request headers so the bypassed requests\n    // comply with the server's CORS preflight check.\n    // Operate with the headers as an object because request \"Headers\"\n    // are immutable.\n    delete headers['x-msw-bypass']\n\n    return fetch(clonedRequest, { headers })\n  }\n\n  // Bypass mocking when the client is not active.\n  if (!client) {\n    return passthrough()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return passthrough()\n  }\n\n  // Bypass requests with the explicit bypass header.\n  // Such requests can be issued by \"ctx.fetch()\".\n  if (request.headers.get('x-msw-bypass') === 'true') {\n    return passthrough()\n  }\n\n  // Notify the client that a request has been intercepted.\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: Object.fromEntries(request.headers.entries()),\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body: await request.text(),\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_RESPONSE': {\n      return respondWithMock(clientMessage.data)\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return passthrough()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.data\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a \"respondWith\" promise emulates a network error.\n      throw networkError\n    }\n  }\n\n  return passthrough()\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(message, [channel.port2])\n  })\n}\n\nfunction sleep(timeMs) {\n  return new Promise((resolve) => {\n    setTimeout(resolve, timeMs)\n  })\n}\n\nasync function respondWithMock(response) {\n  await sleep(response.delay)\n  return new Response(response.body, response)\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/public/robots.txt",
    "content": "# https://www.robotstxt.org/robotstxt.html\nUser-agent: *\nDisallow:\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/App.css",
    "content": ".App {\n  text-align: center;\n}\n\n.App-logo {\n  height: 40vmin;\n  pointer-events: none;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n  .App-logo {\n    animation: App-logo-float infinite 3s ease-in-out;\n  }\n}\n\n.App-header {\n  min-height: 100vh;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: flex-start;\n  font-size: calc(10px + 2vmin);\n}\n\n.App-link {\n  color: rgb(112, 76, 182);\n}\n\n@keyframes App-logo-float {\n  0% {\n    transform: translateY(0);\n  }\n  50% {\n    transform: translateY(10px);\n  }\n  100% {\n    transform: translateY(0px);\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/App.tsx",
    "content": "import { Counter } from './features/counter/Counter'\nimport { TimeDisplay } from './features/time/TimeList'\nimport { Post } from './features/posts/Post'\nimport './App.css'\n\nfunction App() {\n  return (\n    <div className=\"App\">\n      <header className=\"App-header\">\n        <Counter />\n        <TimeDisplay\n          label=\"(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima\"\n          offset=\"-5:00\"\n        />\n        <Post id={1} />\n      </header>\n    </div>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/app/hooks.ts",
    "content": "import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'\nimport type { RootState, AppDispatch } from './store'\n\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = () => useDispatch<AppDispatch>()\nexport const useAppSelector: TypedUseSelectorHook<RootState> = useSelector\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/app/services/post.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport interface Post {\n  id: number\n  name: string\n  fetched_at: string\n}\n\nexport const postApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  reducerPath: 'postApi',\n  tagTypes: ['Posts'],\n  endpoints: (build) => ({\n    getPost: build.query<Post, number>({\n      query: (id) => `posts/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Posts', id }],\n    }),\n  }),\n})\n\nexport const { useGetPostQuery } = postApi\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/app/services/times.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\ninterface TimeResponse {\n  time: string\n}\n\nexport const timeApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  reducerPath: 'timeApi',\n  tagTypes: ['Time'],\n  endpoints: (build) => ({\n    getTime: build.query<TimeResponse, string>({\n      query: (id) => `time/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Time', id }],\n    }),\n  }),\n})\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/app/store.ts",
    "content": "import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'\nimport counterReducer from '../features/counter/counterSlice'\nimport { postApi } from './services/post'\nimport { timeApi } from './services/times'\n\nexport const store = configureStore({\n  reducer: {\n    counter: counterReducer,\n    [postApi.reducerPath]: postApi.reducer,\n    [timeApi.reducerPath]: timeApi.reducer,\n  },\n  middleware: (gDM) => gDM().concat(postApi.middleware, timeApi.middleware),\n})\n\nexport type AppDispatch = typeof store.dispatch\nexport type RootState = ReturnType<typeof store.getState>\nexport type AppThunk<ReturnType = void> = ThunkAction<\n  ReturnType,\n  RootState,\n  unknown,\n  Action<string>\n>\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/features/common/Container.tsx",
    "content": "import { FC, ReactNode } from 'react'\n\nexport const Container: FC<{ children: ReactNode }> = ({ children }) => (\n  <div style={{ textAlign: 'center', padding: 50, margin: '0 auto' }}>\n    {children}\n  </div>\n)\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/features/counter/Counter.module.css",
    "content": ".row {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.row > button {\n  margin-left: 4px;\n  margin-right: 8px;\n}\n\n.row:not(:last-child) {\n  margin-bottom: 16px;\n}\n\n.value {\n  font-size: 78px;\n  padding-left: 16px;\n  padding-right: 16px;\n  margin-top: 2px;\n  font-family: 'Courier New', Courier, monospace;\n}\n\n.button {\n  appearance: none;\n  background: none;\n  font-size: 32px;\n  padding-left: 12px;\n  padding-right: 12px;\n  outline: none;\n  border: 2px solid transparent;\n  color: rgb(112, 76, 182);\n  padding-bottom: 4px;\n  cursor: pointer;\n  background-color: rgba(112, 76, 182, 0.1);\n  border-radius: 2px;\n  transition: all 0.15s;\n}\n\n.textbox {\n  font-size: 32px;\n  padding: 2px;\n  width: 64px;\n  text-align: center;\n  margin-right: 4px;\n}\n\n.button:hover,\n.button:focus {\n  border: 2px solid rgba(112, 76, 182, 0.4);\n}\n\n.button:active {\n  background-color: rgba(112, 76, 182, 0.2);\n}\n\n.asyncButton {\n  composes: button;\n  position: relative;\n}\n\n.asyncButton:after {\n  content: '';\n  background-color: rgba(112, 76, 182, 0.15);\n  display: block;\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  left: 0;\n  top: 0;\n  opacity: 0;\n  transition:\n    width 1s linear,\n    opacity 0.5s ease 1s;\n}\n\n.asyncButton:active:after {\n  width: 0%;\n  opacity: 1;\n  transition: 0s;\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/features/counter/Counter.tsx",
    "content": "import React, { useState } from 'react'\n\nimport { useAppSelector, useAppDispatch } from '../../app/hooks'\nimport {\n  decrement,\n  increment,\n  incrementByAmount,\n  incrementAsync,\n  incrementIfOdd,\n  selectCount,\n} from './counterSlice'\nimport styles from './Counter.module.css'\n\nexport function Counter() {\n  const count = useAppSelector(selectCount)\n  const dispatch = useAppDispatch()\n  const [incrementAmount, setIncrementAmount] = useState('2')\n\n  const incrementValue = Number(incrementAmount) || 0\n\n  return (\n    <div>\n      <h2>Counter</h2>\n      <div className={styles.row}>\n        <button\n          className={styles.button}\n          aria-label=\"Decrement value\"\n          onClick={() => dispatch(decrement())}\n        >\n          -\n        </button>\n        <span className={styles.value} data-testid=\"counter-value\">\n          {count}\n        </span>\n        <button\n          className={styles.button}\n          aria-label=\"Increment value\"\n          onClick={() => dispatch(increment())}\n        >\n          +\n        </button>\n      </div>\n      <div className={styles.row}>\n        <input\n          className={styles.textbox}\n          aria-label=\"Set increment amount\"\n          value={incrementAmount}\n          onChange={(e) => setIncrementAmount(e.target.value)}\n        />\n        <button\n          className={styles.button}\n          onClick={() => dispatch(incrementByAmount(incrementValue))}\n        >\n          Add Amount\n        </button>\n        <button\n          className={styles.asyncButton}\n          onClick={() => dispatch(incrementAsync(incrementValue))}\n        >\n          Add Async\n        </button>\n        <button\n          className={styles.button}\n          onClick={() => dispatch(incrementIfOdd(incrementValue))}\n        >\n          Add If Odd\n        </button>\n      </div>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/features/counter/counterAPI.ts",
    "content": "// A mock function to mimic making an async request for data\nexport function fetchCount(amount = 1) {\n  return new Promise<{ data: number }>((resolve) =>\n    setTimeout(() => resolve({ data: amount }), 500),\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/features/counter/counterSlice.ts",
    "content": "import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'\nimport { RootState, AppThunk } from '../../app/store'\nimport { fetchCount } from './counterAPI'\n\nexport interface CounterState {\n  value: number\n  status: 'idle' | 'loading' | 'failed'\n}\n\nconst initialState: CounterState = {\n  value: 0,\n  status: 'idle',\n}\n\n// The function below is called a thunk and allows us to perform async logic. It\n// can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This\n// will call the thunk with the `dispatch` function as the first argument. Async\n// code can then be executed and other actions can be dispatched. Thunks are\n// typically used to make async requests.\nexport const incrementAsync = createAsyncThunk(\n  'counter/fetchCount',\n  async (amount: number) => {\n    const response = await fetchCount(amount)\n    // The value we return becomes the `fulfilled` action payload\n    return response.data\n  },\n)\n\nexport const counterSlice = createSlice({\n  name: 'counter',\n  initialState,\n  // The `reducers` field lets us define reducers and generate associated actions\n  reducers: {\n    increment: (state) => {\n      // Redux Toolkit allows us to write \"mutating\" logic in reducers. It\n      // doesn't actually mutate the state because it uses the Immer library,\n      // which detects changes to a \"draft state\" and produces a brand new\n      // immutable state based off those changes\n      state.value += 1\n    },\n    decrement: (state) => {\n      state.value -= 1\n    },\n    // Use the PayloadAction type to declare the contents of `action.payload`\n    incrementByAmount: (state, action: PayloadAction<number>) => {\n      state.value += action.payload\n    },\n  },\n  // The `extraReducers` field lets the slice handle actions defined elsewhere,\n  // including actions generated by createAsyncThunk or in other slices.\n  extraReducers: (builder) => {\n    builder\n      .addCase(incrementAsync.pending, (state) => {\n        state.status = 'loading'\n      })\n      .addCase(incrementAsync.fulfilled, (state, action) => {\n        state.status = 'idle'\n        state.value += action.payload\n      })\n      .addCase(incrementAsync.rejected, (state) => {\n        state.status = 'failed'\n      })\n  },\n})\n\nexport const { increment, decrement, incrementByAmount } = counterSlice.actions\n\n// The function below is called a selector and allows us to select a value from\n// the state. Selectors can also be defined inline where they're used instead of\n// in the slice file. For example: `useSelector((state: RootState) => state.counter.value)`\nexport const selectCount = (state: RootState) => state.counter.value\n\n// We can also write thunks by hand, which may contain both sync and async logic.\n// Here's an example of conditionally dispatching actions based on current state.\nexport const incrementIfOdd =\n  (amount: number): AppThunk =>\n  (dispatch, getState) => {\n    const currentValue = selectCount(getState())\n    if (currentValue % 2 === 1) {\n      dispatch(incrementByAmount(amount))\n    }\n  }\n\nexport default counterSlice.reducer\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/features/posts/Post.tsx",
    "content": "import React from 'react'\n\n// import the file that injects \"post\" to make sure it has been loaded\nimport { useGetPostQuery } from '../../app/services/post'\n\nexport const Post = ({ id }: { id: number }) => {\n  const { data, error } = useGetPostQuery(id)\n  const content = error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <div>\n      Title:{' '}\n      <b>\n        <span data-testid=\"post-value\">{data.name}</span>\n      </b>\n    </div>\n  )\n\n  return (\n    <div>\n      <h2>Post</h2>\n      {content}\n    </div>\n  )\n}\nexport default Post\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/features/posts/PostsManager.css",
    "content": ".posts-list {\n  display: flex;\n  flex-direction: column;\n  flex-basis: 100%;\n  flex: 1;\n  min-height: 200px;\n  border-right: 1px solid #eee;\n  padding: 20px;\n  text-align: left;\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/features/time/TimeList.tsx",
    "content": "import * as React from 'react'\nimport { useEffect } from 'react'\nimport { timeApi } from '../../app/services/times'\nimport { useAppDispatch } from '../../app/hooks'\n\nexport const TimeDisplay = ({\n  offset,\n  label,\n}: {\n  offset: string\n  label: string\n}) => {\n  const [data, setData] = React.useState<any>(null)\n  const dispatch = useAppDispatch()\n\n  useEffect(() => {\n    const res = dispatch(timeApi.endpoints.getTime.initiate(offset))\n\n    res.then((value) => {\n      setData(value?.data)\n    })\n    return res.unsubscribe\n  }, [offset, dispatch])\n\n  return (\n    <div>\n      <h2>Time Zone</h2>\n      <ul style={{ textAlign: 'left' }}>\n        <li>Zone: {label}</li>\n        <li>\n          Time:{' '}\n          <span data-testid=\"time-value\">\n            {data?.time ? new Date(data.time).toLocaleTimeString() : 'unknown'}\n          </span>\n        </li>\n      </ul>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/index.css",
    "content": "body {\n  margin: 0;\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n    sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n    monospace;\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport { Provider } from 'react-redux'\nimport { store } from './app/store'\nimport App from './App'\nimport './index.css'\n\nimport { worker } from './mocks/browser'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nasync function render() {\n  await worker.start()\n\n  const rootNode = ReactDOM.createRoot(\n    document.getElementById('root') as HTMLElement,\n  )\n\n  rootNode.render(\n    <React.StrictMode>\n      <Provider store={store}>\n        <App />\n      </Provider>\n    </React.StrictMode>,\n  )\n}\n\nrender()\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './handlers'\n\nexport const worker = setupWorker(...handlers)\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/mocks/handlers.ts",
    "content": "import { rest } from 'msw'\nimport { createEntityAdapter } from '@reduxjs/toolkit'\nimport { Post } from '../app/services/post'\n\n// We're just going to use a simple in-memory store for both the counter and posts\n// The entity adapter will handle modifications when triggered by the MSW handlers\n\nconst adapter = createEntityAdapter<Post>()\n\nlet state = adapter.getInitialState()\nstate = adapter.setAll(state, [\n  { id: 1, name: 'A sample post', fetched_at: new Date().toUTCString() },\n  {\n    id: 2,\n    name: 'A post about rtk-query',\n    fetched_at: new Date().toUTCString(),\n  },\n])\n\nexport { state }\n\nexport const handlers = [\n  rest.get('/time/:offset', (req, res, ctx) => {\n    const { offset } = req.params as { offset: string }\n    const date = new Date()\n    const localDate = date.getTime() // users local time\n    const localOffset = date.getTimezoneOffset() * 60000\n    const formattedOffset = Number(offset.replace(':', '.'))\n    const target = localDate + localOffset + 3600000 * formattedOffset\n    return res(\n      ctx.json({ time: new Date(target).toUTCString() }),\n      ctx.delay(400),\n    )\n  }),\n\n  rest.get('/posts/:id', (req, res, ctx) => {\n    const { id: idParam } = req.params as { id: string }\n    const id = parseInt(idParam, 10)\n    state = adapter.updateOne(state, {\n      id,\n      changes: { fetched_at: new Date().toUTCString() },\n    })\n    return res(ctx.json(state.entities[id]), ctx.delay(400))\n  }),\n]\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/mocks/mockServer.ts",
    "content": "import { setupServer } from 'msw/node'\nimport { handlers } from './handlers'\nimport { state } from './handlers'\n\nexport const mockServer = () => {\n  const server = setupServer(...handlers)\n\n  return { server, state }\n}\n"
  },
  {
    "path": "examples/publish-ci/cra4/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/publish-ci/cra4/tests/playwright/rtkq.test.ts",
    "content": "import { test, expect } from '@playwright/test'\n\ntest('RTK / RTKQ Interactions', async ({ page }) => {\n  page.on('console', (msg) => console.log('Console message: ', msg.text()))\n  await page.goto('http://localhost:3000')\n\n  const counterValue = page.getByTestId('counter-value')\n  const counterText = await counterValue.innerText({ timeout: 0 })\n  expect(counterText).toBe('0')\n\n  const increment = page.getByRole('button', { name: 'Increment value' })\n  await increment.click()\n\n  const counterText2 = await counterValue.innerText({ timeout: 0 })\n  expect(counterText2).toBe('1')\n\n  const timeValue = page.getByTestId('time-value')\n  const postValue = page.getByTestId('post-value')\n\n  await expect(timeValue).toHaveText(/\\d+:\\d+:\\d+\\s+(A|P)M/, { timeout: 10000 })\n  await expect(postValue).toHaveText('A sample post', { timeout: 10000 })\n})\n"
  },
  {
    "path": "examples/publish-ci/cra4/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n\n# production\n/build\n\n# misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\ntypesversions\n.cache\n.yarnrc\n.yarn/*\n!.yarn/patches\n!.yarn/releases\n!.yarn/plugins\n!.yarn/sdks\n!.yarn/versions\n.pnp.*\n*.tgz\n"
  },
  {
    "path": "examples/publish-ci/cra5/README.md",
    "content": "# Getting Started with Create React App\n\nThis project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app), using the [Redux](https://redux.js.org/) and [Redux Toolkit](https://redux-toolkit.js.org/) TS template.\n\n## Available Scripts\n\nIn the project directory, you can run:\n\n### `npm start`\n\nRuns the app in the development mode.\\\nOpen [http://localhost:3000](http://localhost:3000) to view it in the browser.\n\nThe page will reload if you make edits.\\\nYou will also see any lint errors in the console.\n\n### `npm test`\n\nLaunches the test runner in the interactive watch mode.\\\nSee the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.\n\n### `npm run build`\n\nBuilds the app for production to the `build` folder.\\\nIt correctly bundles React in production mode and optimizes the build for the best performance.\n\nThe build is minified and the filenames include the hashes.\\\nYour app is ready to be deployed!\n\nSee the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.\n\n### `npm run eject`\n\n**Note: this is a one-way operation. Once you `eject`, you can’t go back!**\n\nIf you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.\n\nInstead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.\n\nYou don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.\n\n## Learn More\n\nYou can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).\n\nTo learn React, check out the [React documentation](https://reactjs.org/).\n"
  },
  {
    "path": "examples/publish-ci/cra5/package.json",
    "content": "{\n  \"name\": \"rtk-esm-cra\",\n  \"version\": \"0.1.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^2.0.0-rc.3\",\n    \"msw\": \"^1.3.2\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-redux\": \"^9.0.0-rc.0\",\n    \"react-scripts\": \"5\",\n    \"web-vitals\": \"^2.1.4\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"eject\": \"react-scripts eject\",\n    \"serve-app\": \"yarn serve -s build\",\n    \"test\": \"yarn playwright test\",\n    \"format\": \"prettier --write \\\"./src/**/*.{ts,tsx}\\\" \\\"**/*.md\\\"\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\",\n      \"react-app/jest\"\n    ]\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  },\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  },\n  \"devDependencies\": {\n    \"@playwright/test\": \"^1.31.1\",\n    \"@testing-library/jest-dom\": \"^5.16.5\",\n    \"@testing-library/react\": \"^13.4.0\",\n    \"@testing-library/user-event\": \"^14.4.3\",\n    \"@types/jest\": \"^27.5.2\",\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^18.0.26\",\n    \"@types/react-dom\": \"^18.0.10\",\n    \"playwright\": \"^1.31.1\",\n    \"prettier\": \"^3.2.5\",\n    \"serve\": \"^14.2.0\",\n    \"typescript\": \"^5.9.3\"\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/playwright.config.ts",
    "content": "import { defineConfig } from '@playwright/test'\nexport default defineConfig({\n  webServer: {\n    command: 'yarn serve-app',\n    port: 3000,\n    timeout: 120 * 1000,\n    reuseExistingServer: !process.env.CI,\n  },\n  timeout: 120 * 1000,\n  use: {\n    headless: true,\n    viewport: { width: 1280, height: 720 },\n    ignoreHTTPSErrors: true,\n  },\n  testDir: 'tests/playwright/',\n})\n"
  },
  {
    "path": "examples/publish-ci/cra5/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React Redux App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/publish-ci/cra5/public/manifest.json",
    "content": "{\n  \"short_name\": \"React App\",\n  \"name\": \"Create React App Sample\",\n  \"icons\": [\n    {\n      \"src\": \"favicon.ico\",\n      \"sizes\": \"64x64 32x32 24x24 16x16\",\n      \"type\": \"image/x-icon\"\n    },\n    {\n      \"src\": \"logo192.png\",\n      \"type\": \"image/png\",\n      \"sizes\": \"192x192\"\n    },\n    {\n      \"src\": \"logo512.png\",\n      \"type\": \"image/png\",\n      \"sizes\": \"512x512\"\n    }\n  ],\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/public/mockServiceWorker.js",
    "content": "/* eslint-disable */\n/* tslint:disable */\n\n/**\n * Mock Service Worker (1.3.2).\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n\nconst INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  self.skipWaiting()\n})\n\nself.addEventListener('activate', function (event) {\n  event.waitUntil(self.clients.claim())\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll({\n    type: 'window',\n  })\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n  const accept = request.headers.get('accept') || ''\n\n  // Bypass server-sent events.\n  if (accept.includes('text/event-stream')) {\n    return\n  }\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  // Generate unique request ID.\n  const requestId = Math.random().toString(16).slice(2)\n\n  event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      if (error.name === 'NetworkError') {\n        console.warn(\n          '[MSW] Successfully emulated a network error for the \"%s %s\" request.',\n          request.method,\n          request.url,\n        )\n        return\n      }\n\n      // At this point, any exception indicates an issue with the original request/response.\n      console.error(\n        `\\\n[MSW] Caught an exception from the \"%s %s\" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,\n        request.method,\n        request.url,\n        `${error.name}: ${error.message}`,\n      )\n    }),\n  )\n})\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMainClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: Object.fromEntries(clonedResponse.headers.entries()),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\n// Resolve the main client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMainClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client?.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll({\n    type: 'window',\n  })\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const clonedRequest = request.clone()\n\n  function passthrough() {\n    // Clone the request because it might've been already used\n    // (i.e. its body has been read and sent to the client).\n    const headers = Object.fromEntries(clonedRequest.headers.entries())\n\n    // Remove MSW-specific request headers so the bypassed requests\n    // comply with the server's CORS preflight check.\n    // Operate with the headers as an object because request \"Headers\"\n    // are immutable.\n    delete headers['x-msw-bypass']\n\n    return fetch(clonedRequest, { headers })\n  }\n\n  // Bypass mocking when the client is not active.\n  if (!client) {\n    return passthrough()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return passthrough()\n  }\n\n  // Bypass requests with the explicit bypass header.\n  // Such requests can be issued by \"ctx.fetch()\".\n  if (request.headers.get('x-msw-bypass') === 'true') {\n    return passthrough()\n  }\n\n  // Notify the client that a request has been intercepted.\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: Object.fromEntries(request.headers.entries()),\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body: await request.text(),\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_RESPONSE': {\n      return respondWithMock(clientMessage.data)\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return passthrough()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.data\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a \"respondWith\" promise emulates a network error.\n      throw networkError\n    }\n  }\n\n  return passthrough()\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(message, [channel.port2])\n  })\n}\n\nfunction sleep(timeMs) {\n  return new Promise((resolve) => {\n    setTimeout(resolve, timeMs)\n  })\n}\n\nasync function respondWithMock(response) {\n  await sleep(response.delay)\n  return new Response(response.body, response)\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/public/robots.txt",
    "content": "# https://www.robotstxt.org/robotstxt.html\nUser-agent: *\nDisallow:\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/App.css",
    "content": ".App {\n  text-align: center;\n}\n\n.App-logo {\n  height: 40vmin;\n  pointer-events: none;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n  .App-logo {\n    animation: App-logo-float infinite 3s ease-in-out;\n  }\n}\n\n.App-header {\n  min-height: 100vh;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: flex-start;\n  font-size: calc(10px + 2vmin);\n}\n\n.App-link {\n  color: rgb(112, 76, 182);\n}\n\n@keyframes App-logo-float {\n  0% {\n    transform: translateY(0);\n  }\n  50% {\n    transform: translateY(10px);\n  }\n  100% {\n    transform: translateY(0px);\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/App.tsx",
    "content": "import { Counter } from './features/counter/Counter'\nimport { TimeDisplay } from './features/time/TimeList'\nimport { Post } from './features/posts/Post'\nimport './App.css'\n\nfunction App() {\n  return (\n    <div className=\"App\">\n      <header className=\"App-header\">\n        <Counter />\n        <TimeDisplay\n          label=\"(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima\"\n          offset=\"-5:00\"\n        />\n        <Post id={1} />\n      </header>\n    </div>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/app/hooks.ts",
    "content": "import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'\nimport type { RootState, AppDispatch } from './store'\n\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = () => useDispatch<AppDispatch>()\nexport const useAppSelector: TypedUseSelectorHook<RootState> = useSelector\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/app/services/post.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport interface Post {\n  id: number\n  name: string\n  fetched_at: string\n}\n\nexport const postApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  reducerPath: 'postApi',\n  tagTypes: ['Posts'],\n  endpoints: (build) => ({\n    getPost: build.query<Post, number>({\n      query: (id) => `posts/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Posts', id }],\n    }),\n  }),\n})\n\nexport const { useGetPostQuery } = postApi\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/app/services/times.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\ninterface TimeResponse {\n  time: string\n}\n\nexport const timeApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  reducerPath: 'timeApi',\n  tagTypes: ['Time'],\n  endpoints: (build) => ({\n    getTime: build.query<TimeResponse, string>({\n      query: (id) => `time/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Time', id }],\n    }),\n  }),\n})\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/app/store.ts",
    "content": "import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'\nimport counterReducer from '../features/counter/counterSlice'\nimport { postApi } from './services/post'\nimport { timeApi } from './services/times'\n\nexport const store = configureStore({\n  reducer: {\n    counter: counterReducer,\n    [postApi.reducerPath]: postApi.reducer,\n    [timeApi.reducerPath]: timeApi.reducer,\n  },\n  middleware: (gDM) => gDM().concat(postApi.middleware, timeApi.middleware),\n})\n\nexport type AppDispatch = typeof store.dispatch\nexport type RootState = ReturnType<typeof store.getState>\nexport type AppThunk<ReturnType = void> = ThunkAction<\n  ReturnType,\n  RootState,\n  unknown,\n  Action<string>\n>\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/features/common/Container.tsx",
    "content": "import { FC, ReactNode } from 'react'\n\nexport const Container: FC<{ children: ReactNode }> = ({ children }) => (\n  <div style={{ textAlign: 'center', padding: 50, margin: '0 auto' }}>\n    {children}\n  </div>\n)\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/features/counter/Counter.module.css",
    "content": ".row {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.row > button {\n  margin-left: 4px;\n  margin-right: 8px;\n}\n\n.row:not(:last-child) {\n  margin-bottom: 16px;\n}\n\n.value {\n  font-size: 78px;\n  padding-left: 16px;\n  padding-right: 16px;\n  margin-top: 2px;\n  font-family: 'Courier New', Courier, monospace;\n}\n\n.button {\n  appearance: none;\n  background: none;\n  font-size: 32px;\n  padding-left: 12px;\n  padding-right: 12px;\n  outline: none;\n  border: 2px solid transparent;\n  color: rgb(112, 76, 182);\n  padding-bottom: 4px;\n  cursor: pointer;\n  background-color: rgba(112, 76, 182, 0.1);\n  border-radius: 2px;\n  transition: all 0.15s;\n}\n\n.textbox {\n  font-size: 32px;\n  padding: 2px;\n  width: 64px;\n  text-align: center;\n  margin-right: 4px;\n}\n\n.button:hover,\n.button:focus {\n  border: 2px solid rgba(112, 76, 182, 0.4);\n}\n\n.button:active {\n  background-color: rgba(112, 76, 182, 0.2);\n}\n\n.asyncButton {\n  composes: button;\n  position: relative;\n}\n\n.asyncButton:after {\n  content: '';\n  background-color: rgba(112, 76, 182, 0.15);\n  display: block;\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  left: 0;\n  top: 0;\n  opacity: 0;\n  transition:\n    width 1s linear,\n    opacity 0.5s ease 1s;\n}\n\n.asyncButton:active:after {\n  width: 0%;\n  opacity: 1;\n  transition: 0s;\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/features/counter/Counter.tsx",
    "content": "import React, { useState } from 'react'\n\nimport { useAppSelector, useAppDispatch } from '../../app/hooks'\nimport {\n  decrement,\n  increment,\n  incrementByAmount,\n  incrementAsync,\n  incrementIfOdd,\n  selectCount,\n} from './counterSlice'\nimport styles from './Counter.module.css'\n\nexport function Counter() {\n  const count = useAppSelector(selectCount)\n  const dispatch = useAppDispatch()\n  const [incrementAmount, setIncrementAmount] = useState('2')\n\n  const incrementValue = Number(incrementAmount) || 0\n\n  return (\n    <div>\n      <h2>Counter</h2>\n      <div className={styles.row}>\n        <button\n          className={styles.button}\n          aria-label=\"Decrement value\"\n          onClick={() => dispatch(decrement())}\n        >\n          -\n        </button>\n        <span className={styles.value} data-testid=\"counter-value\">\n          {count}\n        </span>\n        <button\n          className={styles.button}\n          aria-label=\"Increment value\"\n          onClick={() => dispatch(increment())}\n        >\n          +\n        </button>\n      </div>\n      <div className={styles.row}>\n        <input\n          className={styles.textbox}\n          aria-label=\"Set increment amount\"\n          value={incrementAmount}\n          onChange={(e) => setIncrementAmount(e.target.value)}\n        />\n        <button\n          className={styles.button}\n          onClick={() => dispatch(incrementByAmount(incrementValue))}\n        >\n          Add Amount\n        </button>\n        <button\n          className={styles.asyncButton}\n          onClick={() => dispatch(incrementAsync(incrementValue))}\n        >\n          Add Async\n        </button>\n        <button\n          className={styles.button}\n          onClick={() => dispatch(incrementIfOdd(incrementValue))}\n        >\n          Add If Odd\n        </button>\n      </div>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/features/counter/counterAPI.ts",
    "content": "// A mock function to mimic making an async request for data\nexport function fetchCount(amount = 1) {\n  return new Promise<{ data: number }>((resolve) =>\n    setTimeout(() => resolve({ data: amount }), 500),\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/features/counter/counterSlice.ts",
    "content": "import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'\nimport { RootState, AppThunk } from '../../app/store'\nimport { fetchCount } from './counterAPI'\n\nexport interface CounterState {\n  value: number\n  status: 'idle' | 'loading' | 'failed'\n}\n\nconst initialState: CounterState = {\n  value: 0,\n  status: 'idle',\n}\n\n// The function below is called a thunk and allows us to perform async logic. It\n// can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This\n// will call the thunk with the `dispatch` function as the first argument. Async\n// code can then be executed and other actions can be dispatched. Thunks are\n// typically used to make async requests.\nexport const incrementAsync = createAsyncThunk(\n  'counter/fetchCount',\n  async (amount: number) => {\n    const response = await fetchCount(amount)\n    // The value we return becomes the `fulfilled` action payload\n    return response.data\n  },\n)\n\nexport const counterSlice = createSlice({\n  name: 'counter',\n  initialState,\n  // The `reducers` field lets us define reducers and generate associated actions\n  reducers: {\n    increment: (state) => {\n      // Redux Toolkit allows us to write \"mutating\" logic in reducers. It\n      // doesn't actually mutate the state because it uses the Immer library,\n      // which detects changes to a \"draft state\" and produces a brand new\n      // immutable state based off those changes\n      state.value += 1\n    },\n    decrement: (state) => {\n      state.value -= 1\n    },\n    // Use the PayloadAction type to declare the contents of `action.payload`\n    incrementByAmount: (state, action: PayloadAction<number>) => {\n      state.value += action.payload\n    },\n  },\n  // The `extraReducers` field lets the slice handle actions defined elsewhere,\n  // including actions generated by createAsyncThunk or in other slices.\n  extraReducers: (builder) => {\n    builder\n      .addCase(incrementAsync.pending, (state) => {\n        state.status = 'loading'\n      })\n      .addCase(incrementAsync.fulfilled, (state, action) => {\n        state.status = 'idle'\n        state.value += action.payload\n      })\n      .addCase(incrementAsync.rejected, (state) => {\n        state.status = 'failed'\n      })\n  },\n})\n\nexport const { increment, decrement, incrementByAmount } = counterSlice.actions\n\n// The function below is called a selector and allows us to select a value from\n// the state. Selectors can also be defined inline where they're used instead of\n// in the slice file. For example: `useSelector((state: RootState) => state.counter.value)`\nexport const selectCount = (state: RootState) => state.counter.value\n\n// We can also write thunks by hand, which may contain both sync and async logic.\n// Here's an example of conditionally dispatching actions based on current state.\nexport const incrementIfOdd =\n  (amount: number): AppThunk =>\n  (dispatch, getState) => {\n    const currentValue = selectCount(getState())\n    if (currentValue % 2 === 1) {\n      dispatch(incrementByAmount(amount))\n    }\n  }\n\nexport default counterSlice.reducer\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/features/posts/Post.tsx",
    "content": "import React from 'react'\n\n// import the file that injects \"post\" to make sure it has been loaded\nimport { useGetPostQuery } from '../../app/services/post'\n\nexport const Post = ({ id }: { id: number }) => {\n  const { data, error } = useGetPostQuery(id)\n  const content = error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <div>\n      Title:{' '}\n      <b>\n        <span data-testid=\"post-value\">{data.name}</span>\n      </b>\n    </div>\n  )\n\n  return (\n    <div>\n      <h2>Post</h2>\n      {content}\n    </div>\n  )\n}\nexport default Post\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/features/posts/PostsManager.css",
    "content": ".posts-list {\n  display: flex;\n  flex-direction: column;\n  flex-basis: 100%;\n  flex: 1;\n  min-height: 200px;\n  border-right: 1px solid #eee;\n  padding: 20px;\n  text-align: left;\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/features/time/TimeList.tsx",
    "content": "import * as React from 'react'\nimport { useEffect } from 'react'\nimport { timeApi } from '../../app/services/times'\nimport { useAppDispatch } from '../../app/hooks'\n\nexport const TimeDisplay = ({\n  offset,\n  label,\n}: {\n  offset: string\n  label: string\n}) => {\n  const [data, setData] = React.useState<any>(null)\n  const dispatch = useAppDispatch()\n\n  useEffect(() => {\n    const res = dispatch(timeApi.endpoints.getTime.initiate(offset))\n\n    res.then((value) => {\n      setData(value?.data)\n    })\n    return res.unsubscribe\n  }, [offset, dispatch])\n\n  return (\n    <div>\n      <h2>Time Zone</h2>\n      <ul style={{ textAlign: 'left' }}>\n        <li>Zone: {label}</li>\n        <li>\n          Time:{' '}\n          <span data-testid=\"time-value\">\n            {data?.time ? new Date(data.time).toLocaleTimeString() : 'unknown'}\n          </span>\n        </li>\n      </ul>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/index.css",
    "content": "body {\n  margin: 0;\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n    sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n    monospace;\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport { Provider } from 'react-redux'\nimport { store } from './app/store'\nimport App from './App'\nimport './index.css'\n\nimport { worker } from './mocks/browser'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nasync function render() {\n  await worker.start()\n\n  const rootNode = ReactDOM.createRoot(\n    document.getElementById('root') as HTMLElement,\n  )\n\n  rootNode.render(\n    <React.StrictMode>\n      <Provider store={store}>\n        <App />\n      </Provider>\n    </React.StrictMode>,\n  )\n}\n\nrender()\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './handlers'\n\nexport const worker = setupWorker(...handlers)\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/mocks/handlers.ts",
    "content": "import { rest } from 'msw'\nimport { createEntityAdapter } from '@reduxjs/toolkit'\nimport { Post } from '../app/services/post'\n\n// We're just going to use a simple in-memory store for both the counter and posts\n// The entity adapter will handle modifications when triggered by the MSW handlers\n\nconst adapter = createEntityAdapter<Post>()\n\nlet state = adapter.getInitialState()\nstate = adapter.setAll(state, [\n  { id: 1, name: 'A sample post', fetched_at: new Date().toUTCString() },\n  {\n    id: 2,\n    name: 'A post about rtk-query',\n    fetched_at: new Date().toUTCString(),\n  },\n])\n\nexport { state }\n\nexport const handlers = [\n  rest.get('/time/:offset', (req, res, ctx) => {\n    const { offset } = req.params as { offset: string }\n    const date = new Date()\n    const localDate = date.getTime() // users local time\n    const localOffset = date.getTimezoneOffset() * 60000\n    const formattedOffset = Number(offset.replace(':', '.'))\n    const target = localDate + localOffset + 3600000 * formattedOffset\n    return res(\n      ctx.json({ time: new Date(target).toUTCString() }),\n      ctx.delay(400),\n    )\n  }),\n\n  rest.get('/posts/:id', (req, res, ctx) => {\n    const { id: idParam } = req.params as { id: string }\n    const id = parseInt(idParam, 10)\n    state = adapter.updateOne(state, {\n      id,\n      changes: { fetched_at: new Date().toUTCString() },\n    })\n    return res(ctx.json(state.entities[id]), ctx.delay(400))\n  }),\n]\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/mocks/mockServer.ts",
    "content": "import { setupServer } from 'msw/node'\nimport { handlers } from './handlers'\nimport { state } from './handlers'\n\nexport const mockServer = () => {\n  const server = setupServer(...handlers)\n\n  return { server, state }\n}\n"
  },
  {
    "path": "examples/publish-ci/cra5/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/publish-ci/cra5/tests/playwright/rtkq.test.ts",
    "content": "import { test, expect } from '@playwright/test'\n\ntest('RTK / RTKQ Interactions', async ({ page }) => {\n  page.on('console', (msg) => console.log('Console message: ', msg.text()))\n  await page.goto('http://localhost:3000')\n\n  const counterValue = page.getByTestId('counter-value')\n  const counterText = await counterValue.innerText({ timeout: 0 })\n  expect(counterText).toBe('0')\n\n  const increment = page.getByRole('button', { name: 'Increment value' })\n  await increment.click()\n\n  const counterText2 = await counterValue.innerText({ timeout: 0 })\n  expect(counterText2).toBe('1')\n\n  const timeValue = page.getByTestId('time-value')\n  const postValue = page.getByTestId('post-value')\n\n  await expect(timeValue).toHaveText(/\\d+:\\d+:\\d+\\s+(A|P)M/, { timeout: 10000 })\n  await expect(postValue).toHaveText('A sample post', { timeout: 10000 })\n})\n"
  },
  {
    "path": "examples/publish-ci/cra5/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "examples/publish-ci/expo/.gitignore",
    "content": "# Learn more https://docs.github.com/en/get-started/getting-started-with-git/ignoring-files\n\n# dependencies\nnode_modules/\n\n# Expo\n.expo/\ndist/\nweb-build/\nexpo-env.d.ts\nbuild/\n\n# Native\n*.orig.*\n*.jks\n*.p8\n*.p12\n*.key\n*.mobileprovision\nandroid/\nios/\n\n# Metro\n.metro-health-check*\n\n# debug\nnpm-debug.*\nyarn-debug.*\nyarn-error.*\n\n# macOS\n.DS_Store\n*.pem\n\n# local env files\n.env*.local\n\n# typescript\n*.tsbuildinfo\n\n# testing\n/coverage\n\n# Yarn\n.yarn/*\n!.yarn/patches\n!.yarn/plugins\n!.yarn/releases\n!.yarn/sdks\n!.yarn/versions\n\n# IDE\n.vscode\n\n.yalc/\nyalc.lock\n"
  },
  {
    "path": "examples/publish-ci/expo/.prettierrc.json",
    "content": "{\n  \"arrowParens\": \"avoid\",\n  \"semi\": false,\n  \"singleQuote\": true\n}\n"
  },
  {
    "path": "examples/publish-ci/expo/App.tsx",
    "content": "import type { JSX } from 'react'\nimport { Provider } from 'react-redux'\nimport { store } from './src/app/store'\nimport { Main } from './src/Main'\n\nexport const App = (): JSX.Element => (\n  <Provider store={store}>\n    <Main />\n  </Provider>\n)\n"
  },
  {
    "path": "examples/publish-ci/expo/README.md",
    "content": "# Expo Template Redux TypeScript\n\nThe official Redux+TS template for Expo.\n\n## :arrow_forward: Usage\n\n```sh\nnpx create-expo my-app --template expo-template-redux-typescript\n```\n\n# Getting Started\n\n> **Note**: Make sure you have completed the [React Native - Environment Setup](https://reactnative.dev/docs/environment-setup) instructions till \"Creating a new application\" step, before proceeding.\n\n## Step 1: Start the Metro Server\n\nFirst, you will need to start **Metro**, the JavaScript _bundler_ that ships _with_ React Native.\n\nTo start Metro, run the following command from the _root_ of your React Native project:\n\n```bash\n# using npm\nnpm start\n```\n\n```bash\n# OR using Yarn\nyarn start\n```\n\n## Step 2: Start your Application\n\nLet Metro Bundler run in its _own_ terminal. Open a _new_ terminal from the _root_ of your React Native project. Run the following command to start your _Android_ or _iOS_ app:\n\n### For Android\n\n```bash\n# using npm\nnpm run android\n```\n\n```bash\n# OR using Yarn\nyarn android\n```\n\n### For iOS\n\n```bash\n# using npm\nnpm run ios\n```\n\n```bash\n# OR using Yarn\nyarn ios\n```\n\nIf everything is set up _correctly_, you should see your new app running in your _Android Emulator_ or _iOS Simulator_ shortly provided you have set up your emulator/simulator correctly.\n\nThis is one way to run your app — you can also run it directly from within Android Studio and Xcode respectively.\n\n## Step 3: Modifying your App\n\nNow that you have successfully run the app, let's modify it.\n\n1. Open `App.tsx` in your text editor of choice and edit some lines.\n2. For **Android**: Press the <kbd>R</kbd> key twice or select **\"Reload\"** from the **Developer Menu** (<kbd>Ctrl</kbd> + <kbd>M</kbd> (on Window and Linux) or <kbd>Cmd ⌘</kbd> + <kbd>M</kbd> (on macOS)) to see your changes!\n\n   For **iOS**: Hit <kbd>Cmd ⌘</kbd> + <kbd>R</kbd> in your iOS Simulator to reload the app and see your changes!\n\n## Congratulations! :tada:\n\nYou've successfully run and modified your Expo App. :partying_face:\n"
  },
  {
    "path": "examples/publish-ci/expo/app.json",
    "content": "{\n  \"expo\": {\n    \"name\": \"expo-template-redux-typescript\",\n    \"slug\": \"expo-template-redux-typescript\",\n    \"version\": \"1.0.0\",\n    \"orientation\": \"portrait\",\n    \"icon\": \"./assets/icon.png\",\n    \"userInterfaceStyle\": \"light\",\n    \"newArchEnabled\": true,\n    \"splash\": {\n      \"image\": \"./assets/splash-icon.png\",\n      \"resizeMode\": \"contain\",\n      \"backgroundColor\": \"#ffffff\"\n    },\n    \"ios\": {\n      \"supportsTablet\": true\n    },\n    \"android\": {\n      \"adaptiveIcon\": {\n        \"foregroundImage\": \"./assets/adaptive-icon.png\",\n        \"backgroundColor\": \"#ffffff\"\n      },\n      \"package\": \"com.anonymous.expotemplatereduxtypescript\"\n    },\n    \"web\": {\n      \"favicon\": \"./assets/favicon.png\"\n    }\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/expo/babel.config.js",
    "content": "/** @import { ConfigFunction } from \"@babel/core\" */\n/** @import { BabelPresetExpoOptions } from \"babel-preset-expo\" */\n\n/**\n * @satisfies {ConfigFunction}\n */\nconst config = api => {\n  api.cache.forever()\n\n  return {\n    presets: [\n      /**\n       * @satisfies {['babel-preset-expo', BabelPresetExpoOptions?]}\n       */\n      (['babel-preset-expo']),\n    ],\n  }\n}\n\nmodule.exports = config\n"
  },
  {
    "path": "examples/publish-ci/expo/eslint.config.mjs",
    "content": "import js from '@eslint/js'\nimport prettierConfig from 'eslint-config-prettier/flat'\nimport jestPlugin from 'eslint-plugin-jest'\nimport reactPlugin from 'eslint-plugin-react'\nimport reactHooksPlugin from 'eslint-plugin-react-hooks'\nimport globals from 'globals'\nimport { config, configs } from 'typescript-eslint'\n\nconst eslintConfig = config(\n  {\n    name: 'global-ignores',\n    ignores: [\n      '**/dist/',\n      '**/build/',\n      '**/lib/',\n      '**/coverage/',\n      '**/__snapshots__/',\n      '**/temp/',\n      '**/.temp/',\n      '**/.tmp/',\n      '**/.yalc/',\n      '**/.yarn/',\n      '**/.docusaurus/',\n      '**/.next/',\n      '**/.expo/',\n      '**/*.snap',\n    ],\n  },\n  {\n    name: `${js.meta.name}/recommended`,\n    ...js.configs.recommended,\n  },\n  configs.strictTypeChecked,\n  configs.stylisticTypeChecked,\n  {\n    name: `${jestPlugin.meta.name}/recommended`,\n    ...jestPlugin.configs['flat/recommended'],\n  },\n  {\n    name: 'eslint-plugin-react/jsx-runtime',\n    ...reactPlugin.configs.flat['jsx-runtime'],\n  },\n  reactHooksPlugin.configs['recommended-latest'],\n  {\n    name: 'main',\n    languageOptions: {\n      ecmaVersion: 2020,\n      globals: globals.node,\n      parserOptions: {\n        projectService: true,\n        tsconfigRootDir: import.meta.dirname,\n      },\n    },\n    rules: {\n      'no-undef': [0],\n      'no-restricted-imports': [\n        2,\n        {\n          paths: [\n            {\n              name: 'react-redux',\n              importNames: ['useSelector', 'useStore', 'useDispatch'],\n              message:\n                'Please use pre-typed versions from `src/app/hooks.ts` instead.',\n            },\n          ],\n        },\n      ],\n      '@typescript-eslint/consistent-type-definitions': [2, 'type'],\n      '@typescript-eslint/consistent-type-imports': [\n        2,\n        {\n          prefer: 'type-imports',\n          fixStyle: 'separate-type-imports',\n          disallowTypeAnnotations: true,\n        },\n      ],\n    },\n\n    linterOptions: {\n      reportUnusedDisableDirectives: 2,\n    },\n  },\n  {\n    name: 'commonjs-files',\n    files: ['metro.config.js'],\n    languageOptions: {\n      sourceType: 'commonjs',\n    },\n    rules: {\n      '@typescript-eslint/no-require-imports': [\n        0,\n        { allow: [], allowAsImport: false },\n      ],\n    },\n  },\n\n  prettierConfig,\n)\n\nexport default eslintConfig\n"
  },
  {
    "path": "examples/publish-ci/expo/globals.d.ts",
    "content": "declare module '*.gif' {\n  const logo: number\n  export default logo\n}\n"
  },
  {
    "path": "examples/publish-ci/expo/index.ts",
    "content": "import { registerRootComponent } from 'expo'\nimport { App } from './App'\n\n// registerRootComponent calls AppRegistry.registerComponent('main', () => App);\n// It also ensures that whether you load the app in Expo Go or in a native build,\n// the environment is set up appropriately\nregisterRootComponent(App)\n"
  },
  {
    "path": "examples/publish-ci/expo/jest-setup.ts",
    "content": "import '@testing-library/react-native'\n"
  },
  {
    "path": "examples/publish-ci/expo/jest.config.ts",
    "content": "import type { Config } from 'jest'\n\nconst config: Config = {\n  preset: 'jest-expo',\n  verbose: true,\n  /**\n   * Without this we will get the following error:\n   * `SyntaxError: Cannot use import statement outside a module`\n   */\n  transformIgnorePatterns: [\n    'node_modules/(?!((jest-)?react-native|...|react-redux))',\n  ],\n  /**\n   * React Native's `jest` preset includes a\n   * [polyfill for `window`](https://github.com/facebook/react-native/blob/acb634bc9662c1103bc7c8ca83cfdc62516d0060/packages/react-native/jest/setup.js#L61-L66).\n   * This polyfill causes React-Redux to use `useEffect`\n   * instead of `useLayoutEffect` for the `useIsomorphicLayoutEffect` hook.\n   * As a result, nested component updates may not be properly batched\n   * when using the `connect` API, leading to potential issues.\n   */\n  globals: {\n    window: undefined,\n    navigator: {\n      product: 'ReactNative',\n    },\n  },\n  setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],\n  fakeTimers: {\n    enableGlobally: true,\n    advanceTimers: true,\n  },\n}\n\nexport default config\n"
  },
  {
    "path": "examples/publish-ci/expo/metro.base.config.ts",
    "content": "import { getDefaultConfig } from '@expo/metro-config'\nimport type { MetroConfig } from 'metro-config'\nimport { mergeConfig } from 'metro-config'\n\nconst config: MetroConfig = mergeConfig(getDefaultConfig(import.meta.dirname))\n\nexport { config }\n"
  },
  {
    "path": "examples/publish-ci/expo/metro.config.js",
    "content": "require('ts-node/register')\n\nconst { config } = require('./metro.base.config.ts')\n\nmodule.exports = config\n"
  },
  {
    "path": "examples/publish-ci/expo/package.json",
    "content": "{\n  \"name\": \"expo-template-redux-typescript\",\n  \"version\": \"1.0.0\",\n  \"main\": \"index.ts\",\n  \"scripts\": {\n    \"android\": \"expo run:android\",\n    \"build\": \"expo prebuild -p android && react-native bundle --entry-file index.ts --bundle-output build/bundle.js --platform android --assets-dest build/assets\",\n    \"format:check\": \"prettier --check .\",\n    \"format\": \"prettier --write .\",\n    \"ios\": \"expo run:ios\",\n    \"lint:fix\": \"eslint --fix .\",\n    \"lint\": \"eslint .\",\n    \"start\": \"expo start\",\n    \"test\": \"jest\",\n    \"type-check\": \"tsc --noEmit\",\n    \"web\": \"expo start --web\"\n  },\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^2.7.0\",\n    \"expo\": \"~53.0.7\",\n    \"expo-status-bar\": \"~2.2.3\",\n    \"react\": \"19.0.0\",\n    \"react-native\": \"0.79.2\",\n    \"react-redux\": \"^9.2.0\"\n  },\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.27.1\",\n    \"@eslint/js\": \"^9.26.0\",\n    \"@react-native-community/cli\": \"^18.0.0\",\n    \"@react-native-community/cli-platform-android\": \"^18.0.0\",\n    \"@react-native-community/cli-platform-ios\": \"^18.0.0\",\n    \"@testing-library/react-native\": \"^13.2.0\",\n    \"@types/babel__core\": \"^7.20.5\",\n    \"@types/jest\": \"^29.5.14\",\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^19.1.2\",\n    \"@types/react-test-renderer\": \"^19.1.0\",\n    \"eslint\": \"^9.26.0\",\n    \"eslint-config-prettier\": \"^10.1.2\",\n    \"eslint-plugin-jest\": \"^28.11.0\",\n    \"eslint-plugin-react\": \"^7.37.5\",\n    \"eslint-plugin-react-hooks\": \"^5.2.0\",\n    \"globals\": \"^16.0.0\",\n    \"jest\": \"^29.7.0\",\n    \"jest-expo\": \"^53.0.4\",\n    \"prettier\": \"^3.5.3\",\n    \"react-test-renderer\": \"19.0.0\",\n    \"ts-node\": \"^10.9.2\",\n    \"typescript\": \"^5.9.3\",\n    \"typescript-eslint\": \"^8.31.1\"\n  },\n  \"private\": true\n}\n"
  },
  {
    "path": "examples/publish-ci/expo/src/Main.test.tsx",
    "content": "import { act, screen } from '@testing-library/react-native'\nimport { Main } from './Main'\nimport { renderWithProviders } from './utils/test-utils'\n\ntest('Main should have correct initial render', () => {\n  renderWithProviders(<Main />)\n\n  const countLabel = screen.getByLabelText('Count')\n\n  const incrementValueInput = screen.getByLabelText('Set increment amount')\n\n  // The app should be rendered correctly\n  expect(screen.getByText(/learn more redux/i)).toBeOnTheScreen()\n\n  // Initial state: count should be 0, incrementValue should be 2\n  expect(countLabel).toHaveTextContent('0')\n  expect(incrementValueInput).toHaveDisplayValue('2')\n})\n\ntest('Increment value and Decrement value should work as expected', async () => {\n  const { user } = renderWithProviders(<Main />)\n\n  const countLabel = screen.getByLabelText('Count')\n\n  const incrementValueButton = screen.getByLabelText('Increment value')\n\n  const decrementValueButton = screen.getByLabelText('Decrement value')\n\n  // Click on \"+\" => Count should be 1\n  await user.press(incrementValueButton)\n  expect(countLabel).toHaveTextContent('1')\n\n  // Click on \"-\" => Count should be 0\n  await user.press(decrementValueButton)\n  expect(countLabel).toHaveTextContent('0')\n})\n\ntest('Add Amount should work as expected', async () => {\n  const { user } = renderWithProviders(<Main />)\n\n  const countLabel = screen.getByLabelText('Count')\n\n  const incrementValueInput = screen.getByLabelText('Set increment amount')\n\n  const addAmountButton = screen.getByText('Add Amount')\n\n  // \"Add Amount\" button is clicked => Count should be 2\n  await user.press(addAmountButton)\n  expect(countLabel).toHaveTextContent('2')\n\n  // incrementValue is 2, click on \"Add Amount\" => Count should be 4\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '2')\n  await user.press(addAmountButton)\n  expect(countLabel).toHaveTextContent('4')\n\n  // [Negative number] incrementValue is -1, click on \"Add Amount\" => Count should be 3\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '-1')\n  await user.press(addAmountButton)\n  expect(countLabel).toHaveTextContent('3')\n})\n\nit('Add Async should work as expected', async () => {\n  const { user } = renderWithProviders(<Main />)\n\n  const addAsyncButton = screen.getByText('Add Async')\n\n  const countLabel = screen.getByLabelText('Count')\n\n  const incrementValueInput = screen.getByLabelText('Set increment amount')\n\n  // \"Add Async\" button is clicked => Count should be 2\n  await user.press(addAsyncButton)\n\n  await act(async () => {\n    await jest.advanceTimersByTimeAsync(500)\n  })\n\n  expect(countLabel).toHaveTextContent('2')\n\n  // incrementValue is 2, click on \"Add Async\" => Count should be 4\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '2')\n\n  await user.press(addAsyncButton)\n\n  await act(async () => {\n    await jest.advanceTimersByTimeAsync(500)\n  })\n\n  expect(countLabel).toHaveTextContent('4')\n\n  // [Negative number] incrementValue is -1, click on \"Add Async\" => Count should be 3\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '-1')\n  await user.press(addAsyncButton)\n\n  await act(async () => {\n    await jest.advanceTimersByTimeAsync(500)\n  })\n\n  expect(countLabel).toHaveTextContent('3')\n})\n\ntest('Add If Odd should work as expected', async () => {\n  const { user } = renderWithProviders(<Main />)\n\n  const countLabel = screen.getByLabelText('Count')\n\n  const addIfOddButton = screen.getByText('Add If Odd')\n\n  const incrementValueInput = screen.getByLabelText('Set increment amount')\n\n  const incrementValueButton = screen.getByLabelText('Increment value')\n\n  // \"Add If Odd\" button is clicked => Count should stay 0\n  await user.press(addIfOddButton)\n  expect(countLabel).toHaveTextContent('0')\n\n  // Click on \"+\" => Count should be updated to 1\n  await user.press(incrementValueButton)\n  expect(countLabel).toHaveTextContent('1')\n\n  // \"Add If Odd\" button is clicked => Count should be updated to 3\n  await user.press(addIfOddButton)\n  expect(countLabel).toHaveTextContent('3')\n\n  // incrementValue is 1, click on \"Add If Odd\" => Count should be updated to 4\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '1')\n  await user.press(addIfOddButton)\n  expect(countLabel).toHaveTextContent('4')\n\n  // click on \"Add If Odd\" => Count should stay 4\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '-1')\n  await user.press(addIfOddButton)\n  expect(countLabel).toHaveTextContent('4')\n})\n"
  },
  {
    "path": "examples/publish-ci/expo/src/Main.tsx",
    "content": "import { StatusBar } from 'expo-status-bar'\nimport type { JSX } from 'react'\nimport {\n  Platform,\n  SafeAreaView,\n  ScrollView,\n  StyleSheet,\n  Text,\n  View,\n  useColorScheme,\n} from 'react-native'\nimport { Header } from './components/Header'\nimport { LearnMoreLinks, LearnReduxLinks } from './components/LearnReduxLinks'\nimport { Section } from './components/Section'\nimport { Colors } from './constants/Colors'\nimport { Counter } from './features/counter/Counter'\nimport { Quotes } from './features/quotes/Quotes'\n\nconst ReloadInstructions = Platform.select({\n  ios: () => (\n    <Text>\n      Press <Text style={styles.highlight}>Cmd + R</Text> in the simulator to\n      reload your app's code.\n    </Text>\n  ),\n  default: () => (\n    <Text>\n      Double tap <Text style={styles.highlight}>R</Text> on your keyboard to\n      reload your app's code.\n    </Text>\n  ),\n})\n\nconst DebugInstructions = Platform.select({\n  ios: () => (\n    <Text>\n      Press <Text style={styles.highlight}>Cmd + D</Text> in the simulator or{' '}\n      <Text style={styles.highlight}>Shake</Text> your device to open the Dev\n      Menu.\n    </Text>\n  ),\n  default: () => (\n    <Text>\n      Press <Text style={styles.highlight}>Cmd or Ctrl + M</Text> or{' '}\n      <Text style={styles.highlight}>Shake</Text> your device to open the Dev\n      Menu.\n    </Text>\n  ),\n})\n\nexport const Main = (): JSX.Element => {\n  const isDarkMode = useColorScheme() === 'dark'\n\n  const backgroundStyle = {\n    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,\n  }\n\n  return (\n    <SafeAreaView style={[backgroundStyle, styles.safeAreaView]}>\n      <StatusBar\n        style={isDarkMode ? 'light' : 'dark'}\n        backgroundColor={backgroundStyle.backgroundColor}\n      />\n      <ScrollView\n        contentInsetAdjustmentBehavior=\"automatic\"\n        style={backgroundStyle}\n      >\n        <Header />\n        <View\n          style={{\n            backgroundColor: isDarkMode ? Colors.black : Colors.white,\n          }}\n        >\n          <Counter />\n          <Quotes />\n          <Section title=\"Step One\">\n            Edit <Text style={styles.highlight}>App.tsx</Text> to change this\n            screen and then come back to see your edits.\n          </Section>\n          <Section title=\"See Your Changes\">\n            <ReloadInstructions />\n          </Section>\n          <Section title=\"Debug\">\n            <DebugInstructions />\n          </Section>\n          <Section title=\"Learn More Redux\">\n            Discover what to do next with Redux:\n          </Section>\n          <LearnReduxLinks />\n          <Section title=\"Learn More React Native\">\n            Read the docs to discover what to do next:\n          </Section>\n          <LearnMoreLinks />\n        </View>\n      </ScrollView>\n    </SafeAreaView>\n  )\n}\n\nconst styles = StyleSheet.create({\n  highlight: {\n    fontWeight: '700',\n  },\n  safeAreaView: {\n    flex: 1,\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/expo/src/app/createAppSlice.ts",
    "content": "import { asyncThunkCreator, buildCreateSlice } from '@reduxjs/toolkit'\n\n// `buildCreateSlice` allows us to create a slice with async thunks.\nexport const createAppSlice = buildCreateSlice({\n  creators: { asyncThunk: asyncThunkCreator },\n})\n"
  },
  {
    "path": "examples/publish-ci/expo/src/app/hooks.ts",
    "content": "// This file serves as a central hub for re-exporting pre-typed Redux hooks.\n// These imports are restricted elsewhere to ensure consistent\n// usage of typed hooks throughout the application.\n// We disable the ESLint rule here because this is the designated place\n// for importing and re-exporting the typed versions of hooks.\n/* eslint-disable no-restricted-imports */\nimport { useEffect } from 'react'\nimport { Animated, useAnimatedValue, useWindowDimensions } from 'react-native'\nimport { useDispatch, useSelector } from 'react-redux'\nimport type { AppDispatch, RootState } from './store'\n\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = useDispatch.withTypes<AppDispatch>()\nexport const useAppSelector = useSelector.withTypes<RootState>()\n\n/**\n * Custom React hook for calculating viewport units\n * based on the current window dimensions.\n *\n * @returns An object containing the calculated viewport heigh and width values.\n */\nexport const useViewportUnits = (): { vh: number; vw: number } => {\n  const { width, height } = useWindowDimensions()\n\n  const vh = height / 100\n  const vw = width / 100\n\n  return { vh, vw }\n}\n\n/**\n * Custom React hook for creating a bounce animation effect.\n *\n * @param value - The maximum height to which the object should bounce. Defaults to 10 if not provided.\n * @returns The {@linkcode Animated.Value} object that can be used to drive animations.\n */\nexport const useBounceAnimation = (value = 10): Animated.Value => {\n  const bounce = useAnimatedValue(0)\n\n  bounce.interpolate({\n    inputRange: [-300, -100, 0, 100, 101],\n    outputRange: [300, 0, 1, 0, 0],\n  })\n\n  useEffect(() => {\n    Animated.loop(\n      Animated.sequence([\n        Animated.timing(bounce, {\n          toValue: value,\n          duration: 1500,\n          useNativeDriver: true,\n        }),\n        Animated.timing(bounce, {\n          toValue: 0,\n          duration: 1500,\n          useNativeDriver: true,\n        }),\n      ]),\n    ).start()\n  }, [bounce, value])\n\n  return bounce\n}\n"
  },
  {
    "path": "examples/publish-ci/expo/src/app/store.ts",
    "content": "import type { Action, ThunkAction } from '@reduxjs/toolkit'\nimport { combineSlices, configureStore } from '@reduxjs/toolkit'\nimport { setupListeners } from '@reduxjs/toolkit/query'\nimport { counterSlice } from '../features/counter/counterSlice'\nimport { quotesApiSlice } from '../features/quotes/quotesApiSlice'\n\n// `combineSlices` automatically combines the reducers using\n// their `reducerPath`s, therefore we no longer need to call `combineReducers`.\nconst rootReducer = combineSlices(counterSlice, quotesApiSlice)\n// Infer the `RootState` type from the root reducer\nexport type RootState = ReturnType<typeof rootReducer>\n\n// The store setup is wrapped in `makeStore` to allow reuse\n// when setting up tests that need the same store config\nexport const makeStore = (preloadedState?: Partial<RootState>) => {\n  const store = configureStore({\n    reducer: rootReducer,\n    // Adding the api middleware enables caching, invalidation, polling,\n    // and other useful features of `rtk-query`.\n    middleware: getDefaultMiddleware => {\n      return getDefaultMiddleware().concat(quotesApiSlice.middleware)\n    },\n    preloadedState,\n  })\n  // configure listeners using the provided defaults\n  // optional, but required for `refetchOnFocus`/`refetchOnReconnect` behaviors\n  setupListeners(store.dispatch)\n  return store\n}\n\nexport const store = makeStore()\n\n// Infer the type of `store`\nexport type AppStore = typeof store\n// Infer the `AppDispatch` type from the store itself\nexport type AppDispatch = AppStore['dispatch']\nexport type AppThunk<ThunkReturnType = void> = ThunkAction<\n  ThunkReturnType,\n  RootState,\n  unknown,\n  Action\n>\n"
  },
  {
    "path": "examples/publish-ci/expo/src/components/AsyncButton.tsx",
    "content": "import type { JSX, PropsWithChildren } from 'react'\nimport type {\n  GestureResponderEvent,\n  PressableProps,\n  ViewStyle,\n} from 'react-native'\nimport {\n  Animated,\n  Pressable,\n  StyleSheet,\n  View,\n  useAnimatedValue,\n} from 'react-native'\n\ntype AsyncButtonProps = PressableProps & PropsWithChildren\n\nexport const AsyncButton = ({\n  onPress,\n  style,\n  children,\n  ...restProps\n}: AsyncButtonProps): JSX.Element => {\n  const progress = useAnimatedValue(0)\n  const opacity = useAnimatedValue(1)\n\n  const _onPress = (e: GestureResponderEvent) => {\n    progress.setValue(0)\n    opacity.setValue(1)\n\n    onPress?.(e)\n\n    Animated.timing(progress, {\n      toValue: 1,\n      duration: 1000,\n      useNativeDriver: false,\n    }).start(({ finished }) => {\n      if (!finished) {\n        return\n      }\n\n      Animated.timing(opacity, {\n        toValue: 0,\n        duration: 200,\n        useNativeDriver: false,\n      }).start()\n    })\n  }\n\n  const progressInterpolate = progress.interpolate({\n    inputRange: [0, 1],\n    outputRange: ['0%', '100%'],\n    extrapolate: 'clamp',\n  })\n\n  const progressStyle: Animated.WithAnimatedObject<ViewStyle> = {\n    width: progressInterpolate,\n    opacity,\n  }\n\n  return (\n    <Pressable style={style} onPress={_onPress} {...restProps}>\n      <View style={StyleSheet.absoluteFill}>\n        <Animated.View style={[styles.progress, progressStyle]} />\n      </View>\n      {children}\n    </Pressable>\n  )\n}\n\nconst styles = StyleSheet.create({\n  progress: {\n    position: 'absolute',\n    top: 0,\n    bottom: 0,\n    left: 0,\n    backgroundColor: 'rgba(112,76,182, 0.15)',\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/expo/src/components/ExternalLink.tsx",
    "content": "import type { JSX } from 'react'\nimport { useCallback } from 'react'\nimport type { TouchableOpacityProps } from 'react-native'\nimport { Alert, Linking, TouchableOpacity } from 'react-native'\n\ntype ExternalLinkProps = TouchableOpacityProps & {\n  url: string\n}\n\nexport const ExternalLink = ({\n  url,\n  ...touchableOpacityProps\n}: ExternalLinkProps): JSX.Element => {\n  const onPress = useCallback(async () => {\n    const supported = await Linking.canOpenURL(url)\n\n    if (supported) {\n      await Linking.openURL(url)\n    } else {\n      Alert.alert(`Don't know how to open this URL: ${url}`)\n    }\n  }, [url])\n\n  return (\n    <TouchableOpacity\n      {...touchableOpacityProps}\n      accessibilityRole=\"button\"\n      onPress={() => {\n        void onPress()\n      }}\n    />\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/expo/src/components/ExternalLinks.tsx",
    "content": "import type { JSX } from 'react'\nimport { Fragment } from 'react'\nimport { StyleSheet, Text, useColorScheme, View } from 'react-native'\nimport { Colors } from '../constants/Colors'\nimport { ExternalLink } from './ExternalLink'\n\nexport type Link = {\n  id: number\n  title: string\n  url: string\n  description: string\n}\n\ntype ExternalLinksProps = {\n  links: Link[]\n}\n\nexport const ExternalLinks = ({ links }: ExternalLinksProps): JSX.Element => {\n  const isDarkMode = useColorScheme() === 'dark'\n\n  return (\n    <View style={styles.container}>\n      {links.map(({ description, id, title, url }) => (\n        <Fragment key={id}>\n          <View\n            style={[\n              styles.separator,\n              { backgroundColor: isDarkMode ? Colors.dark : Colors.light },\n            ]}\n          />\n          <ExternalLink style={styles.linkContainer} url={url}>\n            <Text style={styles.link}>{title}</Text>\n            <Text\n              style={[\n                styles.description,\n                { color: isDarkMode ? Colors.lighter : Colors.dark },\n              ]}\n            >\n              {description}\n            </Text>\n          </ExternalLink>\n        </Fragment>\n      ))}\n    </View>\n  )\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    marginTop: 32,\n    paddingHorizontal: 24,\n  },\n  linkContainer: {\n    flexWrap: 'wrap',\n    flexDirection: 'row',\n    justifyContent: 'space-between',\n    alignItems: 'center',\n    paddingVertical: 8,\n  },\n  link: {\n    flex: 2,\n    fontSize: 18,\n    fontWeight: '400',\n    color: Colors.primary,\n  },\n  description: {\n    flex: 3,\n    paddingVertical: 16,\n    fontWeight: '400',\n    fontSize: 18,\n  },\n  separator: {\n    height: StyleSheet.hairlineWidth,\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/expo/src/components/Header.tsx",
    "content": "import type { JSX } from 'react'\nimport { Animated, StyleSheet, View, useColorScheme } from 'react-native'\nimport { useBounceAnimation, useViewportUnits } from '../app/hooks'\nimport { Colors } from '../constants/Colors'\nimport logo from './logo.gif'\n\nexport const Header = (): JSX.Element => {\n  const isDarkMode = useColorScheme() === 'dark'\n  const { vh } = useViewportUnits()\n  const bounce = useBounceAnimation()\n  const height = 40 * vh\n\n  return (\n    <View\n      style={[\n        styles.container,\n        { backgroundColor: isDarkMode ? Colors.black : Colors.white },\n      ]}\n    >\n      <Animated.Image\n        accessibilityRole=\"image\"\n        source={logo}\n        style={{ height, transform: [{ translateY: bounce }] }}\n      />\n    </View>\n  )\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flexDirection: 'row',\n    justifyContent: 'center',\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/expo/src/components/LearnReduxLinks.tsx",
    "content": "import type { JSX } from 'react'\nimport type { Link } from './ExternalLinks'\nimport { ExternalLinks } from './ExternalLinks'\n\nconst reduxLinks: Link[] = [\n  {\n    id: 1,\n    title: 'React',\n    url: 'https://reactjs.org',\n    description: 'JavaScript library for building user interfaces',\n  },\n  {\n    id: 2,\n    title: 'Redux',\n    url: 'https://redux.js.org',\n    description: 'A Predictable State Container for JS Apps',\n  },\n  {\n    id: 3,\n    title: 'Redux Toolkit',\n    url: 'https://redux-toolkit.js.org',\n    description:\n      'The official, opinionated, batteries-included toolset for efficient Redux development',\n  },\n  {\n    id: 4,\n    title: 'React Redux',\n    url: 'https://react-redux.js.org',\n    description: 'Official React bindings for Redux',\n  },\n  {\n    id: 5,\n    title: 'Reselect',\n    url: 'https://reselect.js.org',\n    description: 'A memoized selector library for Redux',\n  },\n]\n\nconst reactNativeLinks: Link[] = [\n  {\n    id: 1,\n    title: 'The Basics',\n    url: 'https://reactnative.dev/docs/tutorial',\n    description: 'Explains a Hello World for React Native.',\n  },\n  {\n    id: 2,\n    title: 'Style',\n    url: 'https://reactnative.dev/docs/style',\n    description:\n      'Covers how to use the prop named style which controls the visuals.',\n  },\n  {\n    id: 3,\n    title: 'Layout',\n    url: 'https://reactnative.dev/docs/flexbox',\n    description: 'React Native uses flexbox for layout, learn how it works.',\n  },\n  {\n    id: 4,\n    title: 'Components',\n    url: 'https://reactnative.dev/docs/components-and-apis',\n    description: 'The full list of components and APIs inside React Native.',\n  },\n  {\n    id: 5,\n    title: 'Navigation',\n    url: 'https://reactnative.dev/docs/navigation',\n    description:\n      'How to handle moving between screens inside your application.',\n  },\n  {\n    id: 6,\n    title: 'Networking',\n    url: 'https://reactnative.dev/docs/network',\n    description: 'How to use the Fetch API in React Native.',\n  },\n  {\n    id: 7,\n    title: 'Debugging',\n    url: 'https://facebook.github.io/react-native/docs/debugging',\n    description:\n      'Learn about the tools available to debug and inspect your app.',\n  },\n  {\n    id: 8,\n    title: 'Help',\n    url: 'https://facebook.github.io/react-native/help',\n    description:\n      'Need more help? There are many other React Native developers who may have the answer.',\n  },\n  {\n    id: 9,\n    title: 'Follow us',\n    url: 'https://x.com/reactnative',\n    description:\n      'Stay in touch with the community, join in on Q&As and more by following React Native on X.',\n  },\n]\n\nexport const LearnMoreLinks = (): JSX.Element => (\n  <ExternalLinks links={reactNativeLinks} />\n)\n\nexport const LearnReduxLinks = (): JSX.Element => (\n  <ExternalLinks links={reduxLinks} />\n)\n"
  },
  {
    "path": "examples/publish-ci/expo/src/components/Section.tsx",
    "content": "import type { JSX, PropsWithChildren } from 'react'\nimport { StyleSheet, Text, View, useColorScheme } from 'react-native'\nimport { Colors } from '../constants/Colors'\n\ntype SectionProps = PropsWithChildren<{\n  title: string\n}>\n\nexport const Section = ({ children, title }: SectionProps): JSX.Element => {\n  const isDarkMode = useColorScheme() === 'dark'\n\n  return (\n    <View style={styles.sectionContainer}>\n      <Text\n        style={[\n          styles.sectionTitle,\n          { color: isDarkMode ? Colors.white : Colors.black },\n        ]}\n      >\n        {title}\n      </Text>\n      <Text\n        style={[\n          styles.sectionDescription,\n          { color: isDarkMode ? Colors.light : Colors.dark },\n        ]}\n      >\n        {children}\n      </Text>\n    </View>\n  )\n}\n\nconst styles = StyleSheet.create({\n  sectionContainer: {\n    marginTop: 32,\n    paddingHorizontal: 24,\n  },\n  sectionTitle: {\n    fontSize: 24,\n    fontWeight: '600',\n  },\n  sectionDescription: {\n    marginTop: 8,\n    fontSize: 18,\n    fontWeight: '400',\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/expo/src/constants/Colors.ts",
    "content": "type AllColors = {\n  primary: string\n  white: string\n  lighter: string\n  light: string\n  dark: string\n  darker: string\n  black: string\n}\n\nexport const Colors: AllColors = {\n  light: '#DAE1E7',\n  lighter: '#F3F3F3',\n  white: '#FFF',\n  dark: '#444',\n  darker: '#222',\n  black: '#000',\n  primary: '#1292B4',\n}\n"
  },
  {
    "path": "examples/publish-ci/expo/src/features/counter/Counter.tsx",
    "content": "import type { JSX } from 'react'\nimport { useState } from 'react'\nimport {\n  StyleSheet,\n  Text,\n  TextInput,\n  TouchableOpacity,\n  View,\n  useColorScheme,\n} from 'react-native'\nimport { useAppDispatch, useAppSelector } from '../../app/hooks'\nimport { AsyncButton } from '../../components/AsyncButton'\nimport { Colors } from '../../constants/Colors'\nimport {\n  decrement,\n  increment,\n  incrementAsync,\n  incrementByAmount,\n  incrementIfOdd,\n  selectCount,\n  selectStatus,\n} from './counterSlice'\n\nexport const Counter = (): JSX.Element => {\n  const isDarkMode = useColorScheme() === 'dark'\n  const textStyle = {\n    color: isDarkMode ? Colors.light : Colors.dark,\n  }\n\n  const dispatch = useAppDispatch()\n  const count = useAppSelector(selectCount)\n  const status = useAppSelector(selectStatus)\n  const [incrementAmount, setIncrementAmount] = useState('2')\n\n  const incrementValue = Number(incrementAmount) || 0\n\n  return (\n    <View>\n      <View style={styles.row}>\n        <TouchableOpacity\n          style={styles.button}\n          aria-label=\"Decrement value\"\n          onPress={() => dispatch(decrement())}\n        >\n          <Text style={styles.buttonText}>-</Text>\n        </TouchableOpacity>\n        <Text aria-label=\"Count\" style={[styles.value, textStyle]}>\n          {count}\n        </Text>\n        <TouchableOpacity\n          style={styles.button}\n          aria-label=\"Increment value\"\n          onPress={() => dispatch(increment())}\n        >\n          <Text style={styles.buttonText}>+</Text>\n        </TouchableOpacity>\n      </View>\n      <View style={styles.row}>\n        <TextInput\n          aria-label=\"Set increment amount\"\n          style={[styles.textbox, textStyle]}\n          value={incrementAmount}\n          keyboardType=\"numeric\"\n          onChangeText={setIncrementAmount}\n        />\n        <View>\n          <TouchableOpacity\n            style={styles.button}\n            onPress={() => dispatch(incrementByAmount(incrementValue))}\n          >\n            <Text style={styles.buttonText}>Add Amount</Text>\n          </TouchableOpacity>\n          <AsyncButton\n            aria-label=\"Async Button\"\n            style={styles.button}\n            disabled={status !== 'idle'}\n            onPress={() => {\n              void dispatch(incrementAsync(incrementValue))\n            }}\n          >\n            <Text style={styles.buttonText}>Add Async</Text>\n          </AsyncButton>\n          <TouchableOpacity\n            style={styles.button}\n            onPress={() => {\n              dispatch(incrementIfOdd(incrementValue))\n            }}\n          >\n            <Text style={styles.buttonText}>Add If Odd</Text>\n          </TouchableOpacity>\n        </View>\n      </View>\n    </View>\n  )\n}\n\nconst styles = StyleSheet.create({\n  row: {\n    flexDirection: 'row',\n    alignItems: 'center',\n    justifyContent: 'center',\n    flexWrap: 'wrap',\n  },\n  value: {\n    fontSize: 78,\n    paddingHorizontal: 16,\n    marginTop: 2,\n  },\n  button: {\n    backgroundColor: 'rgba(112, 76, 182, 0.1)',\n    borderRadius: 2,\n    paddingLeft: 12,\n    paddingRight: 12,\n    paddingBottom: 4,\n    margin: 2,\n  },\n  buttonText: {\n    color: 'rgb(112, 76, 182)',\n    fontSize: 32,\n    textAlign: 'center',\n  },\n  textbox: {\n    fontSize: 48,\n    padding: 2,\n    width: 64,\n    textAlign: 'center',\n    marginRight: 8,\n    borderWidth: 1,\n    justifyContent: 'center',\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/expo/src/features/counter/counterAPI.ts",
    "content": "// A mock function to mimic making an async request for data\nexport const fetchCount = (amount = 1): Promise<{ data: number }> =>\n  new Promise<{ data: number }>(resolve =>\n    setTimeout(() => {\n      resolve({ data: amount })\n    }, 500),\n  )\n"
  },
  {
    "path": "examples/publish-ci/expo/src/features/counter/counterSlice.test.ts",
    "content": "import { makeStore } from '../../app/store'\nimport type { CounterSliceState } from './counterSlice'\nimport {\n  counterSlice,\n  decrement,\n  increment,\n  incrementByAmount,\n  selectCount,\n} from './counterSlice'\n\ndescribe('counter reducer', () => {\n  const initialState: CounterSliceState = {\n    value: 3,\n    status: 'idle',\n  }\n\n  let store = makeStore()\n\n  beforeEach(() => {\n    store = makeStore({ counter: initialState })\n  })\n\n  it('should handle initial state', () => {\n    expect(counterSlice.reducer(undefined, { type: 'unknown' })).toStrictEqual({\n      value: 0,\n      status: 'idle',\n    })\n  })\n\n  it('should handle increment', () => {\n    expect(selectCount(store.getState())).toBe(3)\n\n    store.dispatch(increment())\n\n    expect(selectCount(store.getState())).toBe(4)\n  })\n\n  it('should handle decrement', () => {\n    expect(selectCount(store.getState())).toBe(3)\n\n    store.dispatch(decrement())\n\n    expect(selectCount(store.getState())).toBe(2)\n  })\n\n  it('should handle incrementByAmount', () => {\n    expect(selectCount(store.getState())).toBe(3)\n\n    store.dispatch(incrementByAmount(2))\n\n    expect(selectCount(store.getState())).toBe(5)\n  })\n})\n"
  },
  {
    "path": "examples/publish-ci/expo/src/features/counter/counterSlice.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit'\nimport { createAppSlice } from '../../app/createAppSlice'\nimport type { AppThunk } from '../../app/store'\nimport { fetchCount } from './counterAPI'\n\nexport type CounterSliceState = {\n  value: number\n  status: 'idle' | 'loading' | 'failed'\n}\n\nconst initialState: CounterSliceState = {\n  value: 0,\n  status: 'idle',\n}\n\n// If you are not using async thunks you can use the standalone `createSlice`.\nexport const counterSlice = createAppSlice({\n  name: 'counter',\n  // `createSlice` will infer the state type from the `initialState` argument\n  initialState,\n  // The `reducers` field lets us define reducers and generate associated actions\n  reducers: create => ({\n    increment: create.reducer(state => {\n      // Redux Toolkit allows us to write \"mutating\" logic in reducers. It\n      // doesn't actually mutate the state because it uses the Immer library,\n      // which detects changes to a \"draft state\" and produces a brand new\n      // immutable state based off those changes\n      state.value += 1\n    }),\n    decrement: create.reducer(state => {\n      state.value -= 1\n    }),\n    // Use the `PayloadAction` type to declare the contents of `action.payload`\n    incrementByAmount: create.reducer(\n      (state, action: PayloadAction<number>) => {\n        state.value += action.payload\n      },\n    ),\n    // The function below is called a thunk and allows us to perform async logic. It\n    // can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This\n    // will call the thunk with the `dispatch` function as the first argument. Async\n    // code can then be executed and other actions can be dispatched. Thunks are\n    // typically used to make async requests.\n    incrementAsync: create.asyncThunk(\n      async (amount: number) => {\n        const response = await fetchCount(amount)\n        // The value we return becomes the `fulfilled` action payload\n        return response.data\n      },\n      {\n        pending: state => {\n          state.status = 'loading'\n        },\n        fulfilled: (state, action) => {\n          state.status = 'idle'\n          state.value += action.payload\n        },\n        rejected: state => {\n          state.status = 'failed'\n        },\n      },\n    ),\n  }),\n  // You can define your selectors here. These selectors receive the slice\n  // state as their first argument.\n  selectors: {\n    selectCount: counter => counter.value,\n    selectStatus: counter => counter.status,\n  },\n})\n\n// Action creators are generated for each case reducer function.\nexport const { decrement, increment, incrementByAmount, incrementAsync } =\n  counterSlice.actions\n\n// Selectors returned by `slice.selectors` take the root state as their first argument.\nexport const { selectCount, selectStatus } = counterSlice.selectors\n\n// We can also write thunks by hand, which may contain both sync and async logic.\n// Here's an example of conditionally dispatching actions based on current state.\nexport const incrementIfOdd =\n  (amount: number): AppThunk =>\n  (dispatch, getState) => {\n    const currentValue = selectCount(getState())\n\n    if (currentValue % 2 === 1 || currentValue % 2 === -1) {\n      dispatch(incrementByAmount(amount))\n    }\n  }\n"
  },
  {
    "path": "examples/publish-ci/expo/src/features/quotes/Quotes.tsx",
    "content": "import type { JSX } from 'react'\nimport { useState } from 'react'\nimport {\n  Modal,\n  ScrollView,\n  StyleSheet,\n  Text,\n  TouchableOpacity,\n  View,\n  useColorScheme,\n} from 'react-native'\nimport { Colors } from '../../constants/Colors'\nimport { useGetQuotesQuery } from './quotesApiSlice'\n\nconst options = [5, 10, 20, 30]\n\nexport const Quotes = (): JSX.Element | null => {\n  const isDarkMode = useColorScheme() === 'dark'\n  const textStyle = {\n    color: isDarkMode ? Colors.light : Colors.dark,\n  }\n  const backgroundStyle = {\n    backgroundColor: isDarkMode ? Colors.darker : Colors.lighter,\n  }\n\n  const [numberOfQuotes, setNumberOfQuotes] = useState(10)\n  const [modalVisible, setModalVisible] = useState(false)\n  // Using a query hook automatically fetches data and returns query values\n  const { data, isError, isLoading, isSuccess } =\n    useGetQuotesQuery(numberOfQuotes)\n\n  if (isError) {\n    return <Text>There was an error!!!</Text>\n  }\n\n  if (isLoading) {\n    return <Text>Loading...</Text>\n  }\n\n  const pickNumberOfQuotes = (value: number) => {\n    setNumberOfQuotes(value)\n    setModalVisible(false)\n  }\n\n  if (isSuccess) {\n    return (\n      <View style={styles.container}>\n        <TouchableOpacity\n          onPress={() => {\n            setModalVisible(true)\n          }}\n          style={styles.button}\n        >\n          <Text style={styles.buttonText}>\n            Select the Quantity of Quotes to Fetch: {numberOfQuotes}\n          </Text>\n        </TouchableOpacity>\n\n        <Modal\n          animationType=\"slide\"\n          transparent={true}\n          visible={modalVisible}\n          style={backgroundStyle}\n          onRequestClose={() => {\n            setModalVisible(false)\n          }}\n        >\n          <View style={[styles.modalView, backgroundStyle]}>\n            <ScrollView style={styles.quotesList}>\n              {options.map(option => (\n                <TouchableOpacity\n                  key={option}\n                  style={styles.option}\n                  onPress={() => {\n                    pickNumberOfQuotes(option)\n                  }}\n                >\n                  <Text style={[styles.optionText, textStyle]}>{option}</Text>\n                </TouchableOpacity>\n              ))}\n            </ScrollView>\n          </View>\n        </Modal>\n\n        {\n          <ScrollView>\n            {data.quotes.map(({ author, quote, id }) => (\n              <View key={id} style={[styles.quoteContainer, backgroundStyle]}>\n                <Text\n                  style={[styles.quoteText, textStyle]}\n                >{`\"${quote}\"`}</Text>\n                <Text style={[styles.author, textStyle]}>- {author}</Text>\n              </View>\n            ))}\n          </ScrollView>\n        }\n      </View>\n    )\n  }\n\n  return null\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    alignItems: 'center',\n    justifyContent: 'center',\n    padding: 20,\n  },\n  button: {\n    padding: 10,\n    backgroundColor: 'rgba(112, 76, 182, 0.1)',\n    borderRadius: 5,\n  },\n  buttonText: {\n    color: 'rgb(112, 76, 182)',\n    fontSize: 18,\n    textAlign: 'center',\n    margin: 5,\n  },\n  modalView: {\n    margin: 20,\n    borderRadius: 5,\n    padding: 20,\n    alignItems: 'center',\n    elevation: 5,\n  },\n  option: {\n    fontSize: 30,\n    padding: 10,\n    borderBottomWidth: 1,\n    borderBottomColor: '#CCC',\n  },\n  optionText: {\n    fontSize: 20,\n  },\n  quotesList: {\n    width: 'auto',\n  },\n  quoteContainer: {\n    padding: 10,\n    borderRadius: 5,\n    marginVertical: 5,\n  },\n  quoteText: {\n    fontStyle: 'italic',\n  },\n  author: {\n    fontWeight: 'bold',\n    textAlign: 'right',\n    marginTop: 5,\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/expo/src/features/quotes/quotesApiSlice.ts",
    "content": "// Need to use the React-specific entry point to import `createApi`\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ntype Quote = {\n  id: number\n  quote: string\n  author: string\n}\n\ntype QuotesApiResponse = {\n  quotes: Quote[]\n  total: number\n  skip: number\n  limit: number\n}\n\n// Define a service using a base URL and expected endpoints\nexport const quotesApiSlice = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/quotes' }),\n  reducerPath: 'quotesApi',\n  // Tag types are used for caching and invalidation.\n  tagTypes: ['Quotes'],\n  endpoints: build => ({\n    // Supply generics for the return type (in this case `QuotesApiResponse`)\n    // and the expected query argument. If there is no argument, use `void`\n    // for the argument type instead.\n    getQuotes: build.query<QuotesApiResponse, number>({\n      query: (limit = 10) => `?limit=${limit.toString()}`,\n      // `providesTags` determines which 'tag' is attached to the\n      // cached data returned by the query.\n      providesTags: (_result, _error, id) => [{ type: 'Quotes', id }],\n    }),\n  }),\n})\n\n// Hooks are auto-generated by RTK-Query\n// Same as `quotesApiSlice.endpoints.getQuotes.useQuery`\nexport const { useGetQuotesQuery } = quotesApiSlice\n"
  },
  {
    "path": "examples/publish-ci/expo/src/utils/test-utils.tsx",
    "content": "import type { RenderOptions } from '@testing-library/react-native'\nimport { render, userEvent } from '@testing-library/react-native'\nimport type { PropsWithChildren, ReactElement } from 'react'\nimport { Provider } from 'react-redux'\nimport type { AppStore, RootState } from '../app/store'\nimport { makeStore } from '../app/store'\n\n/**\n * This type extends the default options for\n * React Testing Library's render function. It allows for\n * additional configuration such as specifying an initial Redux state and\n * a custom store instance.\n */\ntype ExtendedRenderOptions = Omit<RenderOptions, 'queries'> & {\n  /**\n   * Defines a specific portion or the entire initial state for the Redux store.\n   * This is particularly useful for initializing the state in a\n   * controlled manner during testing, allowing components to be rendered\n   * with predetermined state conditions.\n   */\n  preloadedState?: Partial<RootState>\n\n  /**\n   * Allows the use of a specific Redux store instance instead of a\n   * default or global store. This flexibility is beneficial when\n   * testing components with unique store requirements or when isolating\n   * tests from a global store state. The custom store should be configured\n   * to match the structure and middleware of the store used by the application.\n   *\n   * @default makeStore(preloadedState)\n   */\n  store?: AppStore\n}\n\n/**\n * Renders the given React element with Redux Provider and custom store.\n * This function is useful for testing components that are connected to the Redux store.\n *\n * @param ui - The React component or element to render.\n * @param extendedRenderOptions - Optional configuration options for rendering. This includes `preloadedState` for initial Redux state and `store` for a specific Redux store instance. Any additional properties are passed to React Testing Library's render function.\n * @returns An object containing the Redux store used in the render, User event API for simulating user interactions in tests, and all of React Testing Library's query functions for testing the component.\n */\nexport const renderWithProviders = (\n  ui: ReactElement,\n  extendedRenderOptions: ExtendedRenderOptions = {},\n) => {\n  const {\n    preloadedState = {},\n    // Automatically create a store instance if no store was passed in\n    store = makeStore(preloadedState),\n    ...renderOptions\n  } = extendedRenderOptions\n\n  const Wrapper = ({ children }: PropsWithChildren) => (\n    <Provider store={store}>{children}</Provider>\n  )\n\n  // Return an object with the store and all of RTL's query functions\n  return {\n    store,\n    user: userEvent.setup(),\n    ...render(ui, { wrapper: Wrapper, ...renderOptions }),\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/expo/tsconfig.json",
    "content": "{\n  \"extends\": \"expo/tsconfig.base\",\n  \"compilerOptions\": {\n    \"strict\": true\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/next/.eslintrc.js",
    "content": "module.exports = {\n  extends: ['react-app', 'prettier'],\n  parser: '@typescript-eslint/parser',\n  rules: {\n    'jsx-a11y/href-no-hash': 'off',\n    'react/react-in-jsx-scope': 'off',\n    // Taken care of by TypeScript's `noUnusedLocals` / `noUnusedParameters`\n    'no-unused-vars': 'off',\n    '@typescript-eslint/no-unused-vars': 'off',\n    // Silence some bizarre \"rule not found\" TSLint error\n    '@typescript-eslint/no-angle-bracket-type-assertion': 'off',\n    'no-redeclare': 'off',\n    // Silence some bizarre \"rule not found\" TSLint error\n    '@typescript-eslint/no-redeclare': 'off',\n    'no-use-before-define': 'off',\n    '@typescript-eslint/no-use-before-define': ['error', { functions: false }],\n    '@typescript-eslint/consistent-type-imports': ['off'],\n    'react-hooks/exhaustive-deps': [\n      'warn',\n      {\n        additionalHooks: '(usePossiblyImmediateEffect)',\n      },\n    ],\n  },\n}\n"
  },
  {
    "path": "examples/publish-ci/next/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n.yalc\n\n# testing\n/coverage\n\n# next.js\n/.next/\n/out/\n\n# production\n/build\n\n# misc\n.DS_Store\n*.pem\n\n# debug\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n.pnpm-debug.log*\n\n# local env files\n.env*.local\n\n# vercel\n.vercel\n\n# typescript\n*.tsbuildinfo\nnext-env.d.ts\n\ntypesversions\n.cache\n.yarnrc\n.yarn/*\n!.yarn/patches\n!.yarn/releases\n!.yarn/plugins\n!.yarn/sdks\n!.yarn/versions\n.pnp.*\n*.tgz\n"
  },
  {
    "path": "examples/publish-ci/next/README.md",
    "content": "# Redux Toolkit TypeScript Example\n\nThis example shows how to integrate Next.js with [Redux Toolkit](https://redux-toolkit.js.org).\n\nThe **Redux Toolkit** is a standardized way to write Redux logic (create actions and reducers, setup the store with some default middlewares like redux devtools extension). This example demonstrates each of these features with Next.js\n\n## Deploy your own\n\nDeploy the example using [Vercel](https://vercel.com?utm_source=github&utm_medium=readme&utm_campaign=next-example):\n\n[![Deploy with Vercel](https://vercel.com/button)](https://vercel.com/new/git/external?repository-url=https://github.com/vercel/next.js/tree/canary/examples/with-redux&project-name=with-redux&repository-name=with-redux)\n\n## How to use\n\nExecute [`create-next-app`](https://github.com/vercel/next.js/tree/canary/packages/create-next-app) with [npm](https://docs.npmjs.com/cli/init), [Yarn](https://yarnpkg.com/lang/en/docs/cli/create/), or [pnpm](https://pnpm.io) to bootstrap the example:\n\n```bash\nnpx create-next-app --example with-redux with-redux-app\n```\n\n```bash\nyarn create next-app --example with-redux with-redux-app\n```\n\n```bash\npnpm create next-app --example with-redux with-redux-app\n```\n\nDeploy it to the cloud with [Vercel](https://vercel.com/new?utm_source=github&utm_medium=readme&utm_campaign=next-example) ([Documentation](https://nextjs.org/docs/deployment)).\n"
  },
  {
    "path": "examples/publish-ci/next/package.json",
    "content": "{\n  \"private\": true,\n  \"scripts\": {\n    \"dev\": \"next\",\n    \"build\": \"next build\",\n    \"start\": \"next start\",\n    \"type-check\": \"tsc\",\n    \"serve-app\": \"yarn start\",\n    \"test\": \"yarn playwright test\",\n    \"format\": \"prettier --write \\\"./src/**/*.{ts,tsx}\\\" \\\"**/*.md\\\"\"\n  },\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^2.0.0-rc.3\",\n    \"msw\": \"^1.3.2\",\n    \"next\": \"^13.2\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-redux\": \"^9.0.0-rc.0\"\n  },\n  \"devDependencies\": {\n    \"@playwright/test\": \"^1.31.1\",\n    \"@testing-library/jest-dom\": \"^5.16.5\",\n    \"@testing-library/react\": \"^13.4.0\",\n    \"@testing-library/user-event\": \"^14.4.3\",\n    \"@types/jest\": \"^27.5.2\",\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^18.0.26\",\n    \"@types/react-dom\": \"^18.0.10\",\n    \"playwright\": \"^1.31.1\",\n    \"prettier\": \"^3.2.5\",\n    \"serve\": \"^14.2.0\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/next/playwright.config.ts",
    "content": "import { defineConfig } from '@playwright/test'\nexport default defineConfig({\n  webServer: {\n    command: 'yarn serve-app',\n    port: 3000,\n    timeout: 120 * 1000,\n    reuseExistingServer: !process.env.CI,\n  },\n  timeout: 120 * 1000,\n  use: {\n    headless: true,\n    viewport: { width: 1280, height: 720 },\n    ignoreHTTPSErrors: true,\n  },\n  testDir: 'tests/playwright/',\n})\n"
  },
  {
    "path": "examples/publish-ci/next/public/mockServiceWorker.js",
    "content": "/* eslint-disable */\n/* tslint:disable */\n\n/**\n * Mock Service Worker (1.3.2).\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n\nconst INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  self.skipWaiting()\n})\n\nself.addEventListener('activate', function (event) {\n  event.waitUntil(self.clients.claim())\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll({\n    type: 'window',\n  })\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n  const accept = request.headers.get('accept') || ''\n\n  // Bypass server-sent events.\n  if (accept.includes('text/event-stream')) {\n    return\n  }\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  // Generate unique request ID.\n  const requestId = Math.random().toString(16).slice(2)\n\n  event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      if (error.name === 'NetworkError') {\n        console.warn(\n          '[MSW] Successfully emulated a network error for the \"%s %s\" request.',\n          request.method,\n          request.url,\n        )\n        return\n      }\n\n      // At this point, any exception indicates an issue with the original request/response.\n      console.error(\n        `\\\n[MSW] Caught an exception from the \"%s %s\" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,\n        request.method,\n        request.url,\n        `${error.name}: ${error.message}`,\n      )\n    }),\n  )\n})\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMainClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: Object.fromEntries(clonedResponse.headers.entries()),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\n// Resolve the main client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMainClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client?.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll({\n    type: 'window',\n  })\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const clonedRequest = request.clone()\n\n  function passthrough() {\n    // Clone the request because it might've been already used\n    // (i.e. its body has been read and sent to the client).\n    const headers = Object.fromEntries(clonedRequest.headers.entries())\n\n    // Remove MSW-specific request headers so the bypassed requests\n    // comply with the server's CORS preflight check.\n    // Operate with the headers as an object because request \"Headers\"\n    // are immutable.\n    delete headers['x-msw-bypass']\n\n    return fetch(clonedRequest, { headers })\n  }\n\n  // Bypass mocking when the client is not active.\n  if (!client) {\n    return passthrough()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return passthrough()\n  }\n\n  // Bypass requests with the explicit bypass header.\n  // Such requests can be issued by \"ctx.fetch()\".\n  if (request.headers.get('x-msw-bypass') === 'true') {\n    return passthrough()\n  }\n\n  // Notify the client that a request has been intercepted.\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: Object.fromEntries(request.headers.entries()),\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body: await request.text(),\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_RESPONSE': {\n      return respondWithMock(clientMessage.data)\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return passthrough()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.data\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a \"respondWith\" promise emulates a network error.\n      throw networkError\n    }\n  }\n\n  return passthrough()\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(message, [channel.port2])\n  })\n}\n\nfunction sleep(timeMs) {\n  return new Promise((resolve) => {\n    setTimeout(resolve, timeMs)\n  })\n}\n\nasync function respondWithMock(response) {\n  await sleep(response.delay)\n  return new Response(response.body, response)\n}\n"
  },
  {
    "path": "examples/publish-ci/next/setupTests.ts",
    "content": "import '@testing-library/jest-dom'\nimport { loadEnvConfig } from '@next/env'\n\nloadEnvConfig(__dirname, true, { info: () => null, error: console.error })\n"
  },
  {
    "path": "examples/publish-ci/next/src/app-core/hooks.ts",
    "content": "import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'\nimport type { RootState, AppDispatch } from './store'\n\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = () => useDispatch<AppDispatch>()\nexport const useAppSelector: TypedUseSelectorHook<RootState> = useSelector\n"
  },
  {
    "path": "examples/publish-ci/next/src/app-core/services/post.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport interface Post {\n  id: number\n  name: string\n  fetched_at: string\n}\n\nexport const postApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  reducerPath: 'postApi',\n  tagTypes: ['Posts'],\n  endpoints: (build) => ({\n    getPost: build.query<Post, number>({\n      query: (id) => `posts/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Posts', id }],\n    }),\n  }),\n})\n\nexport const { useGetPostQuery } = postApi\n"
  },
  {
    "path": "examples/publish-ci/next/src/app-core/services/times.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\ninterface TimeResponse {\n  time: string\n}\n\nexport const timeApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  reducerPath: 'timeApi',\n  tagTypes: ['Time'],\n  endpoints: (build) => ({\n    getTime: build.query<TimeResponse, string>({\n      query: (id) => `time/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Time', id }],\n    }),\n  }),\n})\n"
  },
  {
    "path": "examples/publish-ci/next/src/app-core/store.ts",
    "content": "import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'\nimport counterReducer from '../features/counter/counterSlice'\nimport { postApi } from './services/post'\nimport { timeApi } from './services/times'\n\nexport const store = configureStore({\n  reducer: {\n    counter: counterReducer,\n    [postApi.reducerPath]: postApi.reducer,\n    [timeApi.reducerPath]: timeApi.reducer,\n  },\n  middleware: (gDM) => gDM().concat(postApi.middleware, timeApi.middleware),\n})\n\nexport type AppDispatch = typeof store.dispatch\nexport type RootState = ReturnType<typeof store.getState>\nexport type AppThunk<ReturnType = void> = ThunkAction<\n  ReturnType,\n  RootState,\n  unknown,\n  Action<string>\n>\n"
  },
  {
    "path": "examples/publish-ci/next/src/features/common/Container.tsx",
    "content": "import { FC, ReactNode } from 'react'\n\nexport const Container: FC<{ children: ReactNode }> = ({ children }) => (\n  <div style={{ textAlign: 'center', padding: 50, margin: '0 auto' }}>\n    {children}\n  </div>\n)\n"
  },
  {
    "path": "examples/publish-ci/next/src/features/counter/Counter.module.css",
    "content": ".row {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.row > button {\n  margin-left: 4px;\n  margin-right: 8px;\n}\n\n.row:not(:last-child) {\n  margin-bottom: 16px;\n}\n\n.value {\n  font-size: 78px;\n  padding-left: 16px;\n  padding-right: 16px;\n  margin-top: 2px;\n  font-family: 'Courier New', Courier, monospace;\n}\n\n.button {\n  appearance: none;\n  background: none;\n  font-size: 32px;\n  padding-left: 12px;\n  padding-right: 12px;\n  outline: none;\n  border: 2px solid transparent;\n  color: rgb(112, 76, 182);\n  padding-bottom: 4px;\n  cursor: pointer;\n  background-color: rgba(112, 76, 182, 0.1);\n  border-radius: 2px;\n  transition: all 0.15s;\n}\n\n.textbox {\n  font-size: 32px;\n  padding: 2px;\n  width: 64px;\n  text-align: center;\n  margin-right: 4px;\n}\n\n.button:hover,\n.button:focus {\n  border: 2px solid rgba(112, 76, 182, 0.4);\n}\n\n.button:active {\n  background-color: rgba(112, 76, 182, 0.2);\n}\n\n.asyncButton {\n  composes: button;\n  position: relative;\n}\n\n.asyncButton:after {\n  content: '';\n  background-color: rgba(112, 76, 182, 0.15);\n  display: block;\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  left: 0;\n  top: 0;\n  opacity: 0;\n  transition:\n    width 1s linear,\n    opacity 0.5s ease 1s;\n}\n\n.asyncButton:active:after {\n  width: 0%;\n  opacity: 1;\n  transition: 0s;\n}\n"
  },
  {
    "path": "examples/publish-ci/next/src/features/counter/Counter.tsx",
    "content": "import React, { useState } from 'react'\n\nimport { useAppSelector, useAppDispatch } from '../../app-core/hooks'\nimport {\n  decrement,\n  increment,\n  incrementByAmount,\n  incrementAsync,\n  incrementIfOdd,\n  selectCount,\n} from './counterSlice'\nimport styles from './Counter.module.css'\n\nexport function Counter() {\n  const count = useAppSelector(selectCount)\n  const dispatch = useAppDispatch()\n  const [incrementAmount, setIncrementAmount] = useState('2')\n\n  const incrementValue = Number(incrementAmount) || 0\n\n  return (\n    <div>\n      <h2>Counter</h2>\n      <div className={styles.row}>\n        <button\n          className={styles.button}\n          aria-label=\"Decrement value\"\n          onClick={() => dispatch(decrement())}\n        >\n          -\n        </button>\n        <span className={styles.value} data-testid=\"counter-value\">\n          {count}\n        </span>\n        <button\n          className={styles.button}\n          aria-label=\"Increment value\"\n          onClick={() => dispatch(increment())}\n        >\n          +\n        </button>\n      </div>\n      <div className={styles.row}>\n        <input\n          className={styles.textbox}\n          aria-label=\"Set increment amount\"\n          value={incrementAmount}\n          onChange={(e) => setIncrementAmount(e.target.value)}\n        />\n        <button\n          className={styles.button}\n          onClick={() => dispatch(incrementByAmount(incrementValue))}\n        >\n          Add Amount\n        </button>\n        <button\n          className={styles.asyncButton}\n          onClick={() => dispatch(incrementAsync(incrementValue))}\n        >\n          Add Async\n        </button>\n        <button\n          className={styles.button}\n          onClick={() => dispatch(incrementIfOdd(incrementValue))}\n        >\n          Add If Odd\n        </button>\n      </div>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/next/src/features/counter/counterAPI.ts",
    "content": "// A mock function to mimic making an async request for data\nexport function fetchCount(amount = 1) {\n  return new Promise<{ data: number }>((resolve) =>\n    setTimeout(() => resolve({ data: amount }), 500),\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/next/src/features/counter/counterSlice.ts",
    "content": "import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'\nimport { RootState, AppThunk } from '../../app-core/store'\nimport { fetchCount } from './counterAPI'\n\nexport interface CounterState {\n  value: number\n  status: 'idle' | 'loading' | 'failed'\n}\n\nconst initialState: CounterState = {\n  value: 0,\n  status: 'idle',\n}\n\n// The function below is called a thunk and allows us to perform async logic. It\n// can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This\n// will call the thunk with the `dispatch` function as the first argument. Async\n// code can then be executed and other actions can be dispatched. Thunks are\n// typically used to make async requests.\nexport const incrementAsync = createAsyncThunk(\n  'counter/fetchCount',\n  async (amount: number) => {\n    const response = await fetchCount(amount)\n    // The value we return becomes the `fulfilled` action payload\n    return response.data\n  },\n)\n\nexport const counterSlice = createSlice({\n  name: 'counter',\n  initialState,\n  // The `reducers` field lets us define reducers and generate associated actions\n  reducers: {\n    increment: (state) => {\n      // Redux Toolkit allows us to write \"mutating\" logic in reducers. It\n      // doesn't actually mutate the state because it uses the Immer library,\n      // which detects changes to a \"draft state\" and produces a brand new\n      // immutable state based off those changes\n      state.value += 1\n    },\n    decrement: (state) => {\n      state.value -= 1\n    },\n    // Use the PayloadAction type to declare the contents of `action.payload`\n    incrementByAmount: (state, action: PayloadAction<number>) => {\n      state.value += action.payload\n    },\n  },\n  // The `extraReducers` field lets the slice handle actions defined elsewhere,\n  // including actions generated by createAsyncThunk or in other slices.\n  extraReducers: (builder) => {\n    builder\n      .addCase(incrementAsync.pending, (state) => {\n        state.status = 'loading'\n      })\n      .addCase(incrementAsync.fulfilled, (state, action) => {\n        state.status = 'idle'\n        state.value += action.payload\n      })\n      .addCase(incrementAsync.rejected, (state) => {\n        state.status = 'failed'\n      })\n  },\n})\n\nexport const { increment, decrement, incrementByAmount } = counterSlice.actions\n\n// The function below is called a selector and allows us to select a value from\n// the state. Selectors can also be defined inline where they're used instead of\n// in the slice file. For example: `useSelector((state: RootState) => state.counter.value)`\nexport const selectCount = (state: RootState) => state.counter.value\n\n// We can also write thunks by hand, which may contain both sync and async logic.\n// Here's an example of conditionally dispatching actions based on current state.\nexport const incrementIfOdd =\n  (amount: number): AppThunk =>\n  (dispatch, getState) => {\n    const currentValue = selectCount(getState())\n    if (currentValue % 2 === 1) {\n      dispatch(incrementByAmount(amount))\n    }\n  }\n\nexport default counterSlice.reducer\n"
  },
  {
    "path": "examples/publish-ci/next/src/features/posts/Post.tsx",
    "content": "import React from 'react'\n\n// import the file that injects \"post\" to make sure it has been loaded\nimport { useGetPostQuery } from '../../app-core/services/post'\n\nexport const Post = ({ id }: { id: number }) => {\n  const { data, error } = useGetPostQuery(id)\n  const content = error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <div>\n      Title:{' '}\n      <b>\n        <span data-testid=\"post-value\">{data.name}</span>\n      </b>\n    </div>\n  )\n\n  return (\n    <div>\n      <h2>Post</h2>\n      {content}\n    </div>\n  )\n}\nexport default Post\n"
  },
  {
    "path": "examples/publish-ci/next/src/features/posts/PostsManager.css",
    "content": ".posts-list {\n  display: flex;\n  flex-direction: column;\n  flex-basis: 100%;\n  flex: 1;\n  min-height: 200px;\n  border-right: 1px solid #eee;\n  padding: 20px;\n  text-align: left;\n}\n"
  },
  {
    "path": "examples/publish-ci/next/src/features/time/TimeList.tsx",
    "content": "import * as React from 'react'\nimport { useEffect } from 'react'\nimport { timeApi } from '../../app-core/services/times'\nimport { useAppDispatch } from '../../app-core/hooks'\n\nexport const TimeDisplay = ({\n  offset,\n  label,\n}: {\n  offset: string\n  label: string\n}) => {\n  const [data, setData] = React.useState<any>(null)\n  const dispatch = useAppDispatch()\n\n  useEffect(() => {\n    const res = dispatch(timeApi.endpoints.getTime.initiate(offset))\n\n    res.then((value) => {\n      setData(value?.data)\n    })\n    return res.unsubscribe\n  }, [offset, dispatch])\n\n  return (\n    <div>\n      <h2>Time Zone</h2>\n      <ul style={{ textAlign: 'left' }}>\n        <li>Zone: {label}</li>\n        <li>\n          Time:{' '}\n          <span data-testid=\"time-value\">\n            {data?.time ? new Date(data.time).toLocaleTimeString() : 'unknown'}\n          </span>\n        </li>\n      </ul>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/next/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './handlers'\n\nexport const worker = setupWorker(...handlers)\n"
  },
  {
    "path": "examples/publish-ci/next/src/mocks/handlers.ts",
    "content": "import { rest } from 'msw'\nimport { createEntityAdapter } from '@reduxjs/toolkit'\nimport { Post } from '../app-core/services/post'\n\n// We're just going to use a simple in-memory store for both the counter and posts\n// The entity adapter will handle modifications when triggered by the MSW handlers\n\nconst adapter = createEntityAdapter<Post>()\n\nlet state = adapter.getInitialState()\nstate = adapter.setAll(state, [\n  { id: 1, name: 'A sample post', fetched_at: new Date().toUTCString() },\n  {\n    id: 2,\n    name: 'A post about rtk-query',\n    fetched_at: new Date().toUTCString(),\n  },\n])\n\nexport { state }\n\nexport const handlers = [\n  rest.get('/time/:offset', (req, res, ctx) => {\n    const { offset } = req.params as { offset: string }\n    const date = new Date()\n    const localDate = date.getTime() // users local time\n    const localOffset = date.getTimezoneOffset() * 60000\n    const formattedOffset = Number(offset.replace(':', '.'))\n    const target = localDate + localOffset + 3600000 * formattedOffset\n    return res(\n      ctx.json({ time: new Date(target).toUTCString() }),\n      ctx.delay(400),\n    )\n  }),\n\n  rest.get('/posts/:id', (req, res, ctx) => {\n    const { id: idParam } = req.params as { id: string }\n    const id = parseInt(idParam, 10)\n    state = adapter.updateOne(state, {\n      id,\n      changes: { fetched_at: new Date().toUTCString() },\n    })\n    return res(ctx.json(state.entities[id]), ctx.delay(400))\n  }),\n]\n"
  },
  {
    "path": "examples/publish-ci/next/src/mocks/mockServer.ts",
    "content": "import { setupServer } from 'msw/node'\nimport { handlers } from './handlers'\nimport { state } from './handlers'\n\nexport const mockServer = () => {\n  const server = setupServer(...handlers)\n\n  return { server, state }\n}\n"
  },
  {
    "path": "examples/publish-ci/next/src/mocks/node.ts",
    "content": "import { setupServer } from 'msw/node'\nimport { handlers } from './handlers'\nimport { state } from './handlers'\n\nexport const mockServer = () => {\n  const server = setupServer(...handlers)\n\n  return { server, state }\n}\n"
  },
  {
    "path": "examples/publish-ci/next/src/pages/_app.tsx",
    "content": "import { useEffect, useState } from 'react'\nimport '../styles/globals.css'\n\nimport { Provider } from 'react-redux'\nimport type { AppProps } from 'next/app'\n\nimport { store } from '../app-core/store'\n\nexport default function MyApp({ Component, pageProps }: AppProps) {\n  const [showComponent, setShowComponent] = useState(false)\n  useEffect(() => {\n    ;(async () => {\n      if (typeof window !== 'undefined') {\n        const { worker } = await import('../mocks/browser')\n        await worker.start()\n        setShowComponent(true)\n      }\n    })()\n  }, [])\n  return (\n    <Provider store={store}>\n      {showComponent && <Component {...pageProps} />}\n    </Provider>\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/next/src/pages/api/counter.ts",
    "content": "import type { NextApiHandler } from 'next'\n\nconst countHandler: NextApiHandler = async (request, response) => {\n  const { amount = 1 } = request.body\n\n  // simulate IO latency\n  await new Promise((resolve) => setTimeout(resolve, 500))\n\n  response.json({ data: amount })\n}\n\nexport default countHandler\n"
  },
  {
    "path": "examples/publish-ci/next/src/pages/index.tsx",
    "content": "import type { NextPage } from 'next'\nimport Head from 'next/head'\n\nimport { Counter } from '../features/counter/Counter'\nimport { TimeDisplay } from '../features/time/TimeList'\nimport { Post } from '../features/posts/Post'\nimport styles from '../styles/Home.module.css'\n\nconst IndexPage: NextPage = () => {\n  return (\n    <div className=\"App\">\n      <header className=\"App-header\">\n        <Counter />\n        <TimeDisplay\n          label=\"(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima\"\n          offset=\"-5:00\"\n        />\n        <Post id={1} />\n      </header>\n    </div>\n  )\n}\n\nexport default IndexPage\n"
  },
  {
    "path": "examples/publish-ci/next/src/styles/Home.module.css",
    "content": ".container {\n  text-align: center;\n}\n\n.logo {\n  height: 40vmin;\n  pointer-events: none;\n}\n\n.header {\n  min-height: 100vh;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  font-size: calc(10px + 2vmin);\n}\n\n.link {\n  color: rgb(112, 76, 182);\n}\n\n@media (prefers-reduced-motion: no-preference) {\n  .logo {\n    animation: logo-float infinite 3s ease-in-out;\n  }\n}\n\n@keyframes logo-float {\n  0% {\n    transform: translateY(0);\n  }\n  50% {\n    transform: translateY(10px);\n  }\n  100% {\n    transform: translateY(0px);\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/next/src/styles/globals.css",
    "content": "html,\nbody {\n  padding: 0;\n  margin: 0;\n  font-family:\n    -apple-system,\n    BlinkMacSystemFont,\n    Segoe UI,\n    Roboto,\n    Oxygen,\n    Ubuntu,\n    Cantarell,\n    Fira Sans,\n    Droid Sans,\n    Helvetica Neue,\n    sans-serif;\n}\n\n.App {\n  text-align: center;\n}\n\n.App-header {\n  min-height: 100vh;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: flex-start;\n  font-size: calc(10px + 2vmin);\n}\n\na {\n  color: inherit;\n  text-decoration: none;\n}\n\n* {\n  box-sizing: border-box;\n}\n"
  },
  {
    "path": "examples/publish-ci/next/tests/playwright/rtkq.test.ts",
    "content": "import { test, expect } from '@playwright/test'\n\ntest('RTK / RTKQ Interactions', async ({ page }) => {\n  page.on('console', (msg) => console.log('Console message: ', msg.text()))\n  await page.goto('http://localhost:3000')\n\n  const counterValue = page.getByTestId('counter-value')\n  const counterText = await counterValue.innerText({ timeout: 0 })\n  expect(counterText).toBe('0')\n\n  const increment = page.getByRole('button', { name: 'Increment value' })\n  await increment.click()\n\n  const counterText2 = await counterValue.innerText({ timeout: 0 })\n  expect(counterText2).toBe('1')\n\n  const timeValue = page.getByTestId('time-value')\n  const postValue = page.getByTestId('post-value')\n\n  await expect(timeValue).toHaveText(/\\d+:\\d+:\\d+\\s+(A|P)M/, { timeout: 10000 })\n  await expect(postValue).toHaveText('A sample post', { timeout: 10000 })\n})\n"
  },
  {
    "path": "examples/publish-ci/next/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"es5\",\n    \"lib\": [\"dom\", \"dom.iterable\", \"esnext\"],\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"strict\": false,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noEmit\": true,\n    \"esModuleInterop\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"jsx\": \"preserve\",\n    \"incremental\": true\n  },\n  \"include\": [\"next-env.d.ts\", \"**/*.ts\", \"**/*.tsx\"],\n  \"exclude\": [\"node_modules\"]\n}\n"
  },
  {
    "path": "examples/publish-ci/next/tsconfig.test.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": {\n    \"jsx\": \"react-jsx\"\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/node-esm/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n\n# production\n/build\n\n# misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\ntypesversions\n.cache\n.yarnrc\n.yarn/*\n!.yarn/patches\n!.yarn/releases\n!.yarn/plugins\n!.yarn/sdks\n!.yarn/versions\n.pnp.*\n*.tgz\n"
  },
  {
    "path": "examples/publish-ci/node-esm/package.json",
    "content": "{\n  \"name\": \"dual-module-test\",\n  \"version\": \"1.0.0\",\n  \"license\": \"MIT\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"build\": \"echo Done\",\n    \"test\": \"node --no-experimental-require-module test-cjs.cjs && node test-esm.mjs\"\n  },\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^2.0.0-rc.3\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-redux\": \"^9.0.0-rc.0\"\n  },\n  \"devDependencies\": {\n    \"resolve-esm\": \"^1.4.0\"\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/node-esm/test-cjs.cjs",
    "content": "const assert = require('node:assert')\nconst path = require('path')\n\nconst { createSlice } = require('@reduxjs/toolkit')\nconst { createApi: createApiPlain } = require('@reduxjs/toolkit/query')\nconst { createApi: createApiReact } = require('@reduxjs/toolkit/query/react')\n\nconsole.log('Testing Node with CJS imports...')\n\nfunction checkFunctionName(fn, name, category) {\n  console.log(`Checking ${category} '${name}' === '${fn.name}'`)\n  assert(\n    fn.name === name,\n    `${category} \\`${name}\\` did not import correctly (name: '${fn.name}')`,\n  )\n}\n\nconst entries = [\n  [createSlice, 'createSlice', 'Core'],\n  [createApiPlain, 'baseCreateApi', 'RTKQ core'],\n  [createApiReact, 'baseCreateApi', 'RTKQ React'],\n]\n\nfor (let [fn, name, category] of entries) {\n  try {\n    checkFunctionName(fn, name, category)\n  } catch (error) {\n    console.error(error)\n  }\n}\n\nconst moduleNames = [\n  ['@reduxjs/toolkit', 'dist/cjs/index.js'],\n  ['@reduxjs/toolkit/query', 'dist/query/cjs/index.js'],\n  ['@reduxjs/toolkit/query/react', 'dist/query/react/cjs/index.js'],\n]\n\nfor (let [moduleName, expectedFilename] of moduleNames) {\n  const modulePath = require.resolve(moduleName)\n  const posixPath = modulePath.split(path.sep).join(path.posix.sep)\n  console.log(`Module: ${moduleName}, path: ${posixPath}`)\n  assert(posixPath.endsWith(expectedFilename))\n}\n\nconsole.log('CJS test succeeded')\n"
  },
  {
    "path": "examples/publish-ci/node-esm/test-esm.mjs",
    "content": "// TODO This entire file doesn't work yet with RTK 1.9.3 master\n\nimport assert from 'node:assert'\nimport path from 'path'\nimport { importMetaResolve } from 'resolve-esm'\n\nimport { createSlice } from '@reduxjs/toolkit'\nimport { createApi as createApiPlain } from '@reduxjs/toolkit/query'\nimport { createApi as createApiReact } from '@reduxjs/toolkit/query/react'\n\nconsole.log('Testing Node with ESM imports...')\n\nfunction checkFunctionName(fn, name, category) {\n  console.log(`Checking ${category} '${name}' === '${fn.name}'`)\n  assert(\n    fn.name === name,\n    `${category} \\`${name}\\` did not import correctly (name: '${fn.name}')`,\n  )\n}\n\nconst entries = [\n  [createSlice, 'createSlice', 'Core'],\n  [createApiPlain, 'baseCreateApi', 'RTKQ core'],\n  [createApiReact, 'baseCreateApi', 'RTKQ React'],\n]\n\nfor (let [fn, name, category] of entries) {\n  try {\n    checkFunctionName(fn, name, category)\n  } catch (error) {\n    console.error(error)\n  }\n}\n\nconst moduleNames = [\n  ['@reduxjs/toolkit', 'dist/redux-toolkit.modern.mjs'],\n  ['@reduxjs/toolkit/query', 'dist/query/rtk-query.modern.mjs'],\n  [\n    '@reduxjs/toolkit/query/react',\n    'dist/query/react/rtk-query-react.modern.mjs',\n  ],\n]\n\n;(async () => {\n  for (let [moduleName, expectedFilename] of moduleNames) {\n    const modulePath = await importMetaResolve(moduleName)\n    const posixPath = modulePath.split(path.sep).join(path.posix.sep)\n    console.log(`Module: ${moduleName}, path: ${posixPath}`)\n    assert(posixPath.endsWith(expectedFilename))\n  }\n})()\n"
  },
  {
    "path": "examples/publish-ci/node-standard/.gitignore",
    "content": "# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n/.pnp\n.pnp.js\n\n# testing\n/coverage\n\n# production\n/build\n\n# misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n\ntypesversions\n.cache\n.yarnrc\n.yarn/*\n!.yarn/patches\n!.yarn/releases\n!.yarn/plugins\n!.yarn/sdks\n!.yarn/versions\n.pnp.*\n*.tgz\n"
  },
  {
    "path": "examples/publish-ci/node-standard/package.json",
    "content": "{\n  \"name\": \"dual-module-test\",\n  \"version\": \"1.0.0\",\n  \"license\": \"MIT\",\n  \"scripts\": {\n    \"build\": \"echo Done\",\n    \"test\": \"node --no-experimental-require-module test-cjs.js && node test-esm.mjs\"\n  },\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^2.0.0-rc.3\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-redux\": \"^9.0.0-rc.0\"\n  },\n  \"devDependencies\": {\n    \"resolve-esm\": \"^1.4.0\"\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/node-standard/test-cjs.js",
    "content": "const assert = require('node:assert')\nconst path = require('path')\n\nconst { createSlice } = require('@reduxjs/toolkit')\nconst { createApi: createApiPlain } = require('@reduxjs/toolkit/query')\nconst { createApi: createApiReact } = require('@reduxjs/toolkit/query/react')\n\nconsole.log('Testing Node with CJS imports...')\n\nfunction checkFunctionName(fn, name, category) {\n  console.log(`Checking ${category} '${name}' === '${fn.name}'`)\n  assert(\n    fn.name === name,\n    `${category} \\`${name}\\` did not import correctly (name: '${fn.name}')`,\n  )\n}\n\nconst entries = [\n  [createSlice, 'createSlice', 'Core'],\n  [createApiPlain, 'baseCreateApi', 'RTKQ core'],\n  [createApiReact, 'baseCreateApi', 'RTKQ React'],\n]\n\nfor (let [fn, name, category] of entries) {\n  try {\n    checkFunctionName(fn, name, category)\n  } catch (error) {\n    console.error(error)\n  }\n}\n\nconst moduleNames = [\n  ['@reduxjs/toolkit', 'dist/cjs/index.js'],\n  ['@reduxjs/toolkit/query', 'dist/query/cjs/index.js'],\n  ['@reduxjs/toolkit/query/react', 'dist/query/react/cjs/index.js'],\n]\n\nfor (let [moduleName, expectedFilename] of moduleNames) {\n  const modulePath = require.resolve(moduleName)\n  const posixPath = modulePath.split(path.sep).join(path.posix.sep)\n  console.log(`Module: ${moduleName}, path: ${posixPath}`)\n  assert(posixPath.endsWith(expectedFilename))\n}\n\nconsole.log('CJS test succeeded')\n"
  },
  {
    "path": "examples/publish-ci/node-standard/test-esm.mjs",
    "content": "// TODO This entire file doesn't work yet with RTK 1.9.3 master\n\nimport assert from 'node:assert'\nimport path from 'path'\nimport { importMetaResolve } from 'resolve-esm'\n\nimport { createSlice } from '@reduxjs/toolkit'\nimport { createApi as createApiPlain } from '@reduxjs/toolkit/query'\nimport { createApi as createApiReact } from '@reduxjs/toolkit/query/react'\n\nconsole.log('Testing Node with ESM imports...')\n\nfunction checkFunctionName(fn, name, category) {\n  console.log(`Checking ${category} '${name}' === '${fn.name}'`)\n  assert(\n    fn.name === name,\n    `${category} \\`${name}\\` did not import correctly (name: '${fn.name}')`,\n  )\n}\n\nconst entries = [\n  [createSlice, 'createSlice', 'Core'],\n  [createApiPlain, 'baseCreateApi', 'RTKQ core'],\n  [createApiReact, 'baseCreateApi', 'RTKQ React'],\n]\n\nfor (let [fn, name, category] of entries) {\n  try {\n    checkFunctionName(fn, name, category)\n  } catch (error) {\n    console.error(error)\n  }\n}\n\nconst moduleNames = [\n  ['@reduxjs/toolkit', 'dist/redux-toolkit.modern.mjs'],\n  ['@reduxjs/toolkit/query', 'dist/query/rtk-query.modern.mjs'],\n  [\n    '@reduxjs/toolkit/query/react',\n    'dist/query/react/rtk-query-react.modern.mjs',\n  ],\n]\n\n;(async () => {\n  for (let [moduleName, expectedFilename] of moduleNames) {\n    const modulePath = await importMetaResolve(moduleName)\n    const posixPath = modulePath.split(path.sep).join(path.posix.sep)\n    console.log(`Module: ${moduleName}, path: ${posixPath}`)\n    assert(posixPath.endsWith(expectedFilename))\n  }\n})()\n"
  },
  {
    "path": "examples/publish-ci/react-native/.bundle/config",
    "content": "BUNDLE_PATH: \"vendor/bundle\"\nBUNDLE_FORCE_RUBY_PLATFORM: 1\n"
  },
  {
    "path": "examples/publish-ci/react-native/.gitignore",
    "content": "# OSX\n#\n.DS_Store\n\n# Xcode\n#\nbuild/\n*.pbxuser\n!default.pbxuser\n*.mode1v3\n!default.mode1v3\n*.mode2v3\n!default.mode2v3\n*.perspectivev3\n!default.perspectivev3\nxcuserdata\n*.xccheckout\n*.moved-aside\nDerivedData\n*.hmap\n*.ipa\n*.xcuserstate\n**/.xcode.env.local\n\n# Android/IntelliJ\n#\nbuild/\ndist/\n.idea\n.gradle\nlocal.properties\n*.iml\n*.hprof\n.cxx/\n*.keystore\n!debug.keystore\n.kotlin/\n\n# node.js\n#\nnode_modules/\nnpm-debug.log\nyarn-error.log\n\n# fastlane\n#\n# It is recommended to not store the screenshots in the git repo. Instead, use fastlane to re-generate the\n# screenshots whenever they are needed.\n# For more information about the recommended setup visit:\n# https://docs.fastlane.tools/best-practices/source-control/\n\n**/fastlane/report.xml\n**/fastlane/Preview.html\n**/fastlane/screenshots\n**/fastlane/test_output\n\n# Bundle artifact\n*.jsbundle\n\n# Ruby / CocoaPods\n**/Pods/\n/vendor/bundle/\n\n# Temporary files created by Metro to check the health of the file watcher\n.metro-health-check*\n\n# testing\n/coverage\n\n# Yarn\n.yarn/*\n!.yarn/patches\n!.yarn/plugins\n!.yarn/releases\n!.yarn/sdks\n!.yarn/versions\n\n#IDE\n.vscode\n\n.yalc/\nyalc.lock\n"
  },
  {
    "path": "examples/publish-ci/react-native/.prettierrc.json",
    "content": "{\n  \"arrowParens\": \"avoid\",\n  \"semi\": false,\n  \"singleQuote\": true\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/.watchmanconfig",
    "content": "{}\n"
  },
  {
    "path": "examples/publish-ci/react-native/App.test.tsx",
    "content": "import type { Action } from '@reduxjs/toolkit'\nimport { configureStore } from '@reduxjs/toolkit'\nimport { act, screen } from '@testing-library/react-native'\nimport type { Dispatch, PropsWithChildren } from 'react'\nimport { Component, PureComponent } from 'react'\nimport type { TextStyle } from 'react-native'\nimport { Button, Text, View } from 'react-native'\nimport { connect, Provider } from 'react-redux'\nimport { App } from './App'\nimport { renderWithProviders } from './src/utils/test-utils'\n\ntest('App should have correct initial render', () => {\n  renderWithProviders(<App />)\n\n  const countLabel = screen.getByLabelText('Count')\n\n  const incrementValueInput = screen.getByLabelText('Set increment amount')\n\n  // The app should be rendered correctly\n  expect(screen.getByText(/learn more redux/i)).toBeOnTheScreen()\n\n  // Initial state: count should be 0, incrementValue should be 2\n  expect(countLabel).toHaveTextContent('0')\n  expect(incrementValueInput).toHaveDisplayValue('2')\n})\n\ntest('Increment value and Decrement value should work as expected', async () => {\n  const { user } = renderWithProviders(<App />)\n\n  const countLabel = screen.getByLabelText('Count')\n\n  const incrementValueButton = screen.getByLabelText('Increment value')\n\n  const decrementValueButton = screen.getByLabelText('Decrement value')\n\n  // Click on \"+\" => Count should be 1\n  await user.press(incrementValueButton)\n  expect(countLabel).toHaveTextContent('1')\n\n  // Click on \"-\" => Count should be 0\n  await user.press(decrementValueButton)\n  expect(countLabel).toHaveTextContent('0')\n})\n\ntest('Add Amount should work as expected', async () => {\n  const { user } = renderWithProviders(<App />)\n\n  const countLabel = screen.getByLabelText('Count')\n\n  const incrementValueInput = screen.getByLabelText('Set increment amount')\n\n  const addAmountButton = screen.getByText('Add Amount')\n\n  // \"Add Amount\" button is clicked => Count should be 2\n  await user.press(addAmountButton)\n  expect(countLabel).toHaveTextContent('2')\n\n  // incrementValue is 2, click on \"Add Amount\" => Count should be 4\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '2')\n  await user.press(addAmountButton)\n  expect(countLabel).toHaveTextContent('4')\n\n  // [Negative number] incrementValue is -1, click on \"Add Amount\" => Count should be 3\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '-1')\n  await user.press(addAmountButton)\n  expect(countLabel).toHaveTextContent('3')\n})\n\nit('Add Async should work as expected', async () => {\n  const { user } = renderWithProviders(<App />)\n\n  const addAsyncButton = screen.getByText('Add Async')\n\n  const countLabel = screen.getByLabelText('Count')\n\n  const incrementValueInput = screen.getByLabelText('Set increment amount')\n\n  // \"Add Async\" button is clicked => Count should be 2\n  await user.press(addAsyncButton)\n\n  await act(async () => {\n    await jest.advanceTimersByTimeAsync(500)\n  })\n\n  expect(countLabel).toHaveTextContent('2')\n\n  // incrementValue is 2, click on \"Add Async\" => Count should be 4\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '2')\n\n  await user.press(addAsyncButton)\n\n  await act(async () => {\n    await jest.advanceTimersByTimeAsync(500)\n  })\n\n  expect(countLabel).toHaveTextContent('4')\n\n  // [Negative number] incrementValue is -1, click on \"Add Async\" => Count should be 3\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '-1')\n  await user.press(addAsyncButton)\n\n  await act(async () => {\n    await jest.advanceTimersByTimeAsync(500)\n  })\n\n  expect(countLabel).toHaveTextContent('3')\n})\n\ntest('Add If Odd should work as expected', async () => {\n  const { user } = renderWithProviders(<App />)\n\n  const countLabel = screen.getByLabelText('Count')\n\n  const addIfOddButton = screen.getByText('Add If Odd')\n\n  const incrementValueInput = screen.getByLabelText('Set increment amount')\n\n  const incrementValueButton = screen.getByLabelText('Increment value')\n\n  // \"Add If Odd\" button is clicked => Count should stay 0\n  await user.press(addIfOddButton)\n  expect(countLabel).toHaveTextContent('0')\n\n  // Click on \"+\" => Count should be updated to 1\n  await user.press(incrementValueButton)\n  expect(countLabel).toHaveTextContent('1')\n\n  // \"Add If Odd\" button is clicked => Count should be updated to 3\n  await user.press(addIfOddButton)\n  expect(countLabel).toHaveTextContent('3')\n\n  // incrementValue is 1, click on \"Add If Odd\" => Count should be updated to 4\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '1')\n  await user.press(addIfOddButton)\n  expect(countLabel).toHaveTextContent('4')\n\n  // click on \"Add If Odd\" => Count should stay 4\n  await user.clear(incrementValueInput)\n  await user.type(incrementValueInput, '-1')\n  await user.press(addIfOddButton)\n  expect(countLabel).toHaveTextContent('4')\n})\n\ntest('React-Redux issue #2150: Nested component updates should be properly batched when using connect', async () => {\n  // Original Issue: https://github.com/reduxjs/react-redux/issues/2150\n  // Solution: https://github.com/reduxjs/react-redux/pull/2156\n\n  // Actions\n  const ADD = 'ADD'\n  const DATE = 'DATE'\n\n  // Action types\n  type AddAction = {} & Action\n  type DateAction = {\n    payload?: { date: number }\n  } & Action\n\n  // Reducer states\n  type DateState = {\n    date: number | null\n  }\n\n  type CounterState = {\n    count: number\n  }\n\n  // Reducers\n  const dateReducer = (\n    state: DateState = { date: null },\n    action: DateAction,\n  ) => {\n    switch (action.type) {\n      case DATE:\n        return {\n          ...state,\n          date: action.payload?.date ?? null,\n        }\n      default:\n        return state\n    }\n  }\n\n  const counterReducer = (\n    state: CounterState = { count: 0 },\n    action: AddAction,\n  ) => {\n    switch (action.type) {\n      case ADD:\n        return {\n          ...state,\n          count: state.count + 1,\n        }\n      default:\n        return state\n    }\n  }\n\n  // Store\n  const store = configureStore({\n    reducer: {\n      counter: counterReducer,\n      dates: dateReducer,\n    },\n  })\n\n  // ======== COMPONENTS =========\n  type CounterProps = {\n    count?: number\n    date?: number | null\n    dispatch: Dispatch<AddAction | DateAction>\n    testID?: string\n  }\n\n  class CounterRaw extends PureComponent<CounterProps> {\n    handleIncrement = () => {\n      this.props.dispatch({ type: ADD })\n    }\n\n    handleDate = () => {\n      this.props.dispatch({ type: DATE, payload: { date: Date.now() } })\n    }\n\n    render() {\n      return (\n        <View style={{ paddingVertical: 20 }}>\n          <Text testID={`${this.props.testID ?? ''}-child`}>\n            Counter Value: {this.props.count}\n          </Text>\n          <Text>date Value: {this.props.date}</Text>\n        </View>\n      )\n    }\n  }\n\n  class ButtonsRaw extends PureComponent<CounterProps> {\n    handleIncrement = () => {\n      this.props.dispatch({ type: ADD })\n    }\n\n    handleDate = () => {\n      this.props.dispatch({ type: DATE, payload: { date: Date.now() } })\n    }\n\n    render() {\n      return (\n        <View>\n          <Button title=\"Update Date\" onPress={this.handleDate} />\n          <View style={{ height: 20 }} />\n          <Button title=\"Increment Counter\" onPress={this.handleIncrement} />\n        </View>\n      )\n    }\n  }\n\n  const mapStateToProps = (state: {\n    counter: CounterState\n    dates: DateState\n  }) => {\n    return { count: state.counter.count, date: state.dates.date }\n  }\n\n  const mapDispatchToProps = (dispatch: Dispatch<AddAction | DateAction>) => ({\n    dispatch,\n  })\n\n  const Buttons = connect(null, mapDispatchToProps)(ButtonsRaw)\n  const Counter = connect(mapStateToProps, mapDispatchToProps)(CounterRaw)\n\n  class Container extends PureComponent<PropsWithChildren> {\n    render() {\n      return this.props.children\n    }\n  }\n\n  const mapStateToPropsBreaking = (_state: unknown) => ({})\n\n  const ContainerBad = connect(mapStateToPropsBreaking, null)(Container)\n\n  const mapStateToPropsNonBlocking1 = (state: { counter: CounterState }) => ({\n    count: state.counter.count,\n  })\n\n  const ContainerNonBlocking1 = connect(\n    mapStateToPropsNonBlocking1,\n    null,\n  )(Container)\n\n  const mapStateToPropsNonBlocking2 = (state: unknown) => ({ state })\n\n  const ContainerNonBlocking2 = connect(\n    mapStateToPropsNonBlocking2,\n    null,\n  )(Container)\n\n  class MainApp extends Component {\n    render() {\n      const $H1: TextStyle = { fontSize: 20 }\n      return (\n        <Provider store={store}>\n          <Buttons />\n          <Text style={$H1}>=Expected=</Text>\n          <View>\n            <Text>\n              I don't have a parent blocking state updates so I should behave as\n              expected\n            </Text>\n            <Counter />\n          </View>\n\n          <Text style={$H1}>=Undesired behavior with react-redux 9.x=</Text>\n          <ContainerBad>\n            <Text>All redux state updates blocked</Text>\n            <Counter testID=\"undesired\" />\n          </ContainerBad>\n\n          <Text style={$H1}>=Partially working in 9.x=</Text>\n          <ContainerNonBlocking1>\n            <Text>\n              I'm inconsistent, if date updates first I don't see it, but once\n              count updates I rerender with count or date changes\n            </Text>\n            <Counter testID=\"inconsistent\" />\n          </ContainerNonBlocking1>\n\n          <Text style={$H1}>=Poor workaround for 9.x?=</Text>\n          <ContainerNonBlocking2>\n            <Text>I see all state changes</Text>\n            <Counter />\n          </ContainerNonBlocking2>\n        </Provider>\n      )\n    }\n  }\n\n  const { user, getByTestId, getByText } = renderWithProviders(<MainApp />)\n\n  expect(getByTestId('undesired-child')).toHaveTextContent('Counter Value: 0')\n\n  await user.press(getByText('Increment Counter'))\n\n  expect(getByTestId('inconsistent-child')).toHaveTextContent(\n    'Counter Value: 1',\n  )\n\n  expect(getByTestId('undesired-child')).toHaveTextContent('Counter Value: 1')\n})\n"
  },
  {
    "path": "examples/publish-ci/react-native/App.tsx",
    "content": "import type { JSX } from 'react'\nimport {\n  SafeAreaView,\n  ScrollView,\n  StatusBar,\n  StyleSheet,\n  Text,\n  View,\n  useColorScheme,\n} from 'react-native'\nimport {\n  DebugInstructions,\n  HermesBadge,\n  LearnMoreLinks,\n  ReloadInstructions,\n} from 'react-native/Libraries/NewAppScreen'\nimport { Header } from './src/components/Header'\nimport { LearnReduxLinks } from './src/components/LearnReduxLinks'\nimport { Section } from './src/components/Section'\nimport { TypedColors } from './src/constants/TypedColors'\nimport { Counter } from './src/features/counter/Counter'\nimport { Quotes } from './src/features/quotes/Quotes'\n\nexport const App = (): JSX.Element => {\n  const isDarkMode = useColorScheme() === 'dark'\n\n  const backgroundStyle = {\n    backgroundColor: isDarkMode ? TypedColors.darker : TypedColors.lighter,\n  }\n\n  return (\n    <SafeAreaView style={backgroundStyle}>\n      <StatusBar\n        barStyle={isDarkMode ? 'light-content' : 'dark-content'}\n        backgroundColor={backgroundStyle.backgroundColor}\n      />\n      <ScrollView\n        contentInsetAdjustmentBehavior=\"automatic\"\n        style={backgroundStyle}\n      >\n        <Header />\n        <HermesBadge />\n        <View\n          style={{\n            backgroundColor: isDarkMode ? TypedColors.black : TypedColors.white,\n          }}\n        >\n          <Counter />\n          <Quotes />\n          <Section title=\"Step One\">\n            Edit <Text style={styles.highlight}>App.tsx</Text> to change this\n            screen and then come back to see your edits.\n          </Section>\n          <Section title=\"See Your Changes\">\n            <ReloadInstructions />\n          </Section>\n          <Section title=\"Debug\">\n            <DebugInstructions />\n          </Section>\n          <Section title=\"Learn More Redux\">\n            Discover what to do next with Redux:\n          </Section>\n          <LearnReduxLinks />\n          <Section title=\"Learn More React Native\">\n            Read the docs to discover what to do next:\n          </Section>\n          <LearnMoreLinks />\n        </View>\n      </ScrollView>\n    </SafeAreaView>\n  )\n}\n\nconst styles = StyleSheet.create({\n  highlight: {\n    fontWeight: '700',\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/react-native/Gemfile",
    "content": "source 'https://rubygems.org'\n\n# You may use http://rbenv.org/ or https://rvm.io/ to install and use this version\nruby \">= 2.6.10\"\n\n# Exclude problematic versions of cocoapods and activesupport that causes build failures.\ngem 'cocoapods', '>= 1.13', '!= 1.15.0', '!= 1.15.1'\ngem 'activesupport', '>= 6.1.7.5', '!= 7.1.0'\ngem 'xcodeproj', '< 1.26.0'\n"
  },
  {
    "path": "examples/publish-ci/react-native/README.md",
    "content": "This is a new [**React Native**](https://reactnative.dev) project, bootstrapped using [`@react-native-community/cli`](https://github.com/react-native-community/cli).\n\n# Getting Started\n\n> **Note**: Make sure you have completed the [React Native - Environment Setup](https://reactnative.dev/docs/environment-setup) instructions till \"Creating a new application\" step, before proceeding.\n\n## Step 1: Start the Metro Server\n\nFirst, you will need to start **Metro**, the JavaScript _bundler_ that ships _with_ React Native.\n\nTo start Metro, run the following command from the _root_ of your React Native project:\n\n```bash\n# using npm\nnpm start\n\n# OR using Yarn\nyarn start\n```\n\n## Step 2: Start your Application\n\nLet Metro Bundler run in its _own_ terminal. Open a _new_ terminal from the _root_ of your React Native project. Run the following command to start your _Android_ or _iOS_ app:\n\n### For Android\n\n```bash\n# using npm\nnpm run android\n\n# OR using Yarn\nyarn android\n```\n\n### For iOS\n\n```bash\n# using npm\nnpm run ios\n\n# OR using Yarn\nyarn ios\n```\n\nIf everything is set up _correctly_, you should see your new app running in your _Android Emulator_ or _iOS Simulator_ shortly provided you have set up your emulator/simulator correctly.\n\nThis is one way to run your app — you can also run it directly from within Android Studio and Xcode respectively.\n\n## Step 3: Modifying your App\n\nNow that you have successfully run the app, let's modify it.\n\n1. Open `App.tsx` in your text editor of choice and edit some lines.\n2. For **Android**: Press the <kbd>R</kbd> key twice or select **\"Reload\"** from the **Developer Menu** (<kbd>Ctrl</kbd> + <kbd>M</kbd> (on Window and Linux) or <kbd>Cmd ⌘</kbd> + <kbd>M</kbd> (on macOS)) to see your changes!\n\n   For **iOS**: Hit <kbd>Cmd ⌘</kbd> + <kbd>R</kbd> in your iOS Simulator to reload the app and see your changes!\n\n## Congratulations! :tada:\n\nYou've successfully run and modified your React Native App. :partying_face:\n\n### Now what?\n\n- If you want to add this new React Native code to an existing application, check out the [Integration guide](https://reactnative.dev/docs/integration-with-existing-apps).\n- If you're curious to learn more about React Native, check out the [Introduction to React Native](https://reactnative.dev/docs/getting-started).\n\n# Troubleshooting\n\nIf you can't get this to work, see the [Troubleshooting](https://reactnative.dev/docs/troubleshooting) page.\n\n# Learn More\n\nTo learn more about React Native, take a look at the following resources:\n\n- [React Native Website](https://reactnative.dev) - learn more about React Native.\n- [Getting Started](https://reactnative.dev/docs/environment-setup) - an **overview** of React Native and how setup your environment.\n- [Learn the Basics](https://reactnative.dev/docs/getting-started) - a **guided tour** of the React Native **basics**.\n- [Blog](https://reactnative.dev/blog) - read the latest official React Native **Blog** posts.\n- [`@facebook/react-native`](https://github.com/facebook/react-native) - the Open Source; GitHub **repository** for React Native.\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/app/build.gradle",
    "content": "apply plugin: \"com.android.application\"\napply plugin: \"org.jetbrains.kotlin.android\"\napply plugin: \"com.facebook.react\"\n\n/**\n * This is the configuration block to customize your React Native Android app.\n * By default you don't need to apply any configuration, just uncomment the lines you need.\n */\nreact {\n    /* Folders */\n    //   The root of your project, i.e. where \"package.json\" lives. Default is '../..'\n    // root = file(\"../../\")\n    //   The folder where the react-native NPM package is. Default is ../../node_modules/react-native\n    // reactNativeDir = file(\"../../node_modules/react-native\")\n    //   The folder where the react-native Codegen package is. Default is ../../node_modules/@react-native/codegen\n    // codegenDir = file(\"../../node_modules/@react-native/codegen\")\n    //   The cli.js file which is the React Native CLI entrypoint. Default is ../../node_modules/react-native/cli.js\n    // cliFile = file(\"../../node_modules/react-native/cli.js\")\n\n    /* Variants */\n    //   The list of variants to that are debuggable. For those we're going to\n    //   skip the bundling of the JS bundle and the assets. By default is just 'debug'.\n    //   If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.\n    // debuggableVariants = [\"liteDebug\", \"prodDebug\"]\n\n    /* Bundling */\n    //   A list containing the node command and its flags. Default is just 'node'.\n    // nodeExecutableAndArgs = [\"node\"]\n    //\n    //   The command to run when bundling. By default is 'bundle'\n    // bundleCommand = \"ram-bundle\"\n    //\n    //   The path to the CLI configuration file. Default is empty.\n    // bundleConfig = file(../rn-cli.config.js)\n    //\n    //   The name of the generated asset file containing your JS bundle\n    // bundleAssetName = \"MyApplication.android.bundle\"\n    //\n    //   The entry file for bundle generation. Default is 'index.android.js' or 'index.js'\n    // entryFile = file(\"../js/MyApplication.android.js\")\n    //\n    //   A list of extra flags to pass to the 'bundle' commands.\n    //   See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle\n    // extraPackagerArgs = []\n\n    /* Hermes Commands */\n    //   The hermes compiler command to run. By default it is 'hermesc'\n    // hermesCommand = \"$rootDir/my-custom-hermesc/bin/hermesc\"\n    //\n    //   The list of flags to pass to the Hermes compiler. By default is \"-O\", \"-output-source-map\"\n    // hermesFlags = [\"-O\", \"-output-source-map\"]\n\n    /* Autolinking */\n    autolinkLibrariesWithApp()\n}\n\n/**\n * Set this to true to Run Proguard on Release builds to minify the Java bytecode.\n */\ndef enableProguardInReleaseBuilds = false\n\n/**\n * The preferred build flavor of JavaScriptCore (JSC)\n *\n * For example, to use the international variant, you can use:\n * `def jscFlavor = 'org.webkit:android-jsc-intl:+'`\n *\n * The international variant includes ICU i18n library and necessary data\n * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that\n * give correct results when using with locales other than en-US. Note that\n * this variant is about 6MiB larger per architecture than default.\n */\ndef jscFlavor = 'org.webkit:android-jsc:+'\n\nandroid {\n    ndkVersion = rootProject.ext.ndkVersion\n    buildToolsVersion rootProject.ext.buildToolsVersion\n    compileSdk = rootProject.ext.compileSdkVersion\n\n    namespace = \"com.reduxTemplate\"\n    defaultConfig {\n        applicationId \"com.reduxTemplate\"\n        minSdkVersion rootProject.ext.minSdkVersion\n        targetSdkVersion rootProject.ext.targetSdkVersion\n        versionCode 1\n        versionName \"1.0\"\n    }\n    signingConfigs {\n        debug {\n            storeFile file('debug.keystore')\n            storePassword 'android'\n            keyAlias 'androiddebugkey'\n            keyPassword 'android'\n        }\n    }\n    buildTypes {\n        debug {\n            signingConfig = signingConfigs.debug\n        }\n        release {\n            // Caution! In production, you need to generate your own keystore file.\n            // see https://reactnative.dev/docs/signed-apk-android.\n            signingConfig = signingConfigs.debug\n            minifyEnabled enableProguardInReleaseBuilds\n            proguardFiles getDefaultProguardFile(\"proguard-android.txt\"), \"proguard-rules.pro\"\n        }\n    }\n}\n\ndependencies {\n    // The version of react-native is set by the React Native Gradle Plugin\n    implementation(\"com.facebook.react:react-android\")\n\n    if (hermesEnabled.toBoolean()) {\n        implementation(\"com.facebook.react:hermes-android\")\n    } else {\n        implementation jscFlavor\n    }\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/app/proguard-rules.pro",
    "content": "# Add project specific ProGuard rules here.\n# By default, the flags in this file are appended to flags specified\n# in /usr/local/Cellar/android-sdk/24.3.3/tools/proguard/proguard-android.txt\n# You can edit the include path and order by changing the proguardFiles\n# directive in build.gradle.\n#\n# For more details, see\n#   http://developer.android.com/guide/developing/tools/proguard.html\n\n# Add any project specific keep options here:\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/app/src/debug/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\">\n\n    <application\n        android:usesCleartextTraffic=\"true\"\n        tools:targetApi=\"28\"\n        tools:ignore=\"GoogleAppIndexingWarning\"/>\n</manifest>\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/app/src/main/AndroidManifest.xml",
    "content": "<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\">\n\n    <uses-permission android:name=\"android.permission.INTERNET\" />\n\n    <application\n      android:name=\".MainApplication\"\n      android:label=\"@string/app_name\"\n      android:icon=\"@mipmap/ic_launcher\"\n      android:roundIcon=\"@mipmap/ic_launcher_round\"\n      android:allowBackup=\"false\"\n      android:theme=\"@style/AppTheme\"\n      android:supportsRtl=\"true\">\n      <activity\n        android:name=\".MainActivity\"\n        android:label=\"@string/app_name\"\n        android:configChanges=\"keyboard|keyboardHidden|orientation|screenLayout|screenSize|smallestScreenSize|uiMode\"\n        android:launchMode=\"singleTask\"\n        android:windowSoftInputMode=\"adjustResize\"\n        android:exported=\"true\">\n        <intent-filter>\n            <action android:name=\"android.intent.action.MAIN\" />\n            <category android:name=\"android.intent.category.LAUNCHER\" />\n        </intent-filter>\n      </activity>\n    </application>\n</manifest>\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/app/src/main/java/com/reduxTemplate/MainActivity.kt",
    "content": "package com.reduxTemplate\n\nimport com.facebook.react.ReactActivity\nimport com.facebook.react.ReactActivityDelegate\nimport com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.fabricEnabled\nimport com.facebook.react.defaults.DefaultReactActivityDelegate\n\nclass MainActivity : ReactActivity() {\n\n  /**\n   * Returns the name of the main component registered from JavaScript. This is used to schedule\n   * rendering of the component.\n   */\n  override fun getMainComponentName(): String = \"reduxTemplate\"\n\n  /**\n   * Returns the instance of the [ReactActivityDelegate]. We use [DefaultReactActivityDelegate]\n   * which allows you to enable New Architecture with a single boolean flags [fabricEnabled]\n   */\n  override fun createReactActivityDelegate(): ReactActivityDelegate =\n      DefaultReactActivityDelegate(this, mainComponentName, fabricEnabled)\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/app/src/main/java/com/reduxTemplate/MainApplication.kt",
    "content": "package com.reduxTemplate\n\nimport android.app.Application\nimport com.facebook.react.PackageList\nimport com.facebook.react.ReactApplication\nimport com.facebook.react.ReactHost\nimport com.facebook.react.ReactNativeHost\nimport com.facebook.react.ReactPackage\nimport com.facebook.react.defaults.DefaultNewArchitectureEntryPoint.load\nimport com.facebook.react.defaults.DefaultReactHost.getDefaultReactHost\nimport com.facebook.react.defaults.DefaultReactNativeHost\nimport com.facebook.react.soloader.OpenSourceMergedSoMapping\nimport com.facebook.soloader.SoLoader\n\nclass MainApplication : Application(), ReactApplication {\n\n  override val reactNativeHost: ReactNativeHost =\n      object : DefaultReactNativeHost(this) {\n        override fun getPackages(): List<ReactPackage> =\n            PackageList(this).packages.apply {\n              // Packages that cannot be autolinked yet can be added manually here, for example:\n              // add(MyReactNativePackage())\n            }\n\n        override fun getJSMainModuleName(): String = \"index\"\n\n        override fun getUseDeveloperSupport(): Boolean = BuildConfig.DEBUG\n\n        override val isNewArchEnabled: Boolean = BuildConfig.IS_NEW_ARCHITECTURE_ENABLED\n        override val isHermesEnabled: Boolean = BuildConfig.IS_HERMES_ENABLED\n      }\n\n  override val reactHost: ReactHost\n    get() = getDefaultReactHost(applicationContext, reactNativeHost)\n\n  override fun onCreate() {\n    super.onCreate()\n    SoLoader.init(this, OpenSourceMergedSoMapping)\n    if (BuildConfig.IS_NEW_ARCHITECTURE_ENABLED) {\n      // If you opted-in for the New Architecture, we load the native entry point for this app.\n      load()\n    }\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/app/src/main/res/drawable/rn_edit_text_material.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<!-- Copyright (C) 2014 The Android Open Source Project\n\n     Licensed under the Apache License, Version 2.0 (the \"License\");\n     you may not use this file except in compliance with the License.\n     You may obtain a copy of the License at\n\n          http://www.apache.org/licenses/LICENSE-2.0\n\n     Unless required by applicable law or agreed to in writing, software\n     distributed under the License is distributed on an \"AS IS\" BASIS,\n     WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n     See the License for the specific language governing permissions and\n     limitations under the License.\n-->\n<inset xmlns:android=\"http://schemas.android.com/apk/res/android\"\n       android:insetLeft=\"@dimen/abc_edit_text_inset_horizontal_material\"\n       android:insetRight=\"@dimen/abc_edit_text_inset_horizontal_material\"\n       android:insetTop=\"@dimen/abc_edit_text_inset_top_material\"\n       android:insetBottom=\"@dimen/abc_edit_text_inset_bottom_material\"\n       >\n\n    <selector>\n        <!--\n          This file is a copy of abc_edit_text_material (https://bit.ly/3k8fX7I).\n          The item below with state_pressed=\"false\" and state_focused=\"false\" causes a NullPointerException.\n          NullPointerException:tempt to invoke virtual method 'android.graphics.drawable.Drawable android.graphics.drawable.Drawable$ConstantState.newDrawable(android.content.res.Resources)'\n\n          <item android:state_pressed=\"false\" android:state_focused=\"false\" android:drawable=\"@drawable/abc_textfield_default_mtrl_alpha\"/>\n\n          For more info, see https://bit.ly/3CdLStv (react-native/pull/29452) and https://bit.ly/3nxOMoR.\n        -->\n        <item android:state_enabled=\"false\" android:drawable=\"@drawable/abc_textfield_default_mtrl_alpha\"/>\n        <item android:drawable=\"@drawable/abc_textfield_activated_mtrl_alpha\"/>\n    </selector>\n\n</inset>\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/app/src/main/res/values/strings.xml",
    "content": "<resources>\n    <string name=\"app_name\">reduxTemplate</string>\n</resources>\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/app/src/main/res/values/styles.xml",
    "content": "<resources>\n\n    <!-- Base application theme. -->\n    <style name=\"AppTheme\" parent=\"Theme.AppCompat.DayNight.NoActionBar\">\n        <!-- Customize your theme here. -->\n        <item name=\"android:editTextBackground\">@drawable/rn_edit_text_material</item>\n    </style>\n\n</resources>\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/build.gradle",
    "content": "buildscript {\n    ext {\n        buildToolsVersion = \"35.0.0\"\n        minSdkVersion = 24\n        compileSdkVersion = 35\n        targetSdkVersion = 34\n        ndkVersion = \"26.1.10909125\"\n        kotlinVersion = \"1.9.24\"\n    }\n    repositories {\n        google()\n        mavenCentral()\n    }\n    dependencies {\n        classpath(\"com.android.tools.build:gradle\")\n        classpath(\"com.facebook.react:react-native-gradle-plugin\")\n        classpath(\"org.jetbrains.kotlin:kotlin-gradle-plugin\")\n    }\n}\n\napply plugin: \"com.facebook.react.rootproject\"\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/gradle/wrapper/gradle-wrapper.properties",
    "content": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-8.14-all.zip\nnetworkTimeout=10000\nvalidateDistributionUrl=true\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/gradle.properties",
    "content": "# Project-wide Gradle settings.\n\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will override*\n# any settings specified in this file.\n\n# For more details on how to configure your build environment visit\n# http://www.gradle.org/docs/current/userguide/build_environment.html\n\n# Specifies the JVM arguments used for the daemon process.\n# The setting is particularly useful for tweaking memory settings.\n# Default value: -Xmx512m -XX:MaxMetaspaceSize=256m\norg.gradle.jvmargs=-Xmx2048m -XX:MaxMetaspaceSize=512m\n\n# When configured, Gradle will run in incubating parallel mode.\n# This option should only be used with decoupled projects. More details, visit\n# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects\n# org.gradle.parallel=true\n\n# AndroidX package structure to make it clearer which packages are bundled with the\n# Android operating system, and which are packaged with your app's APK\n# https://developer.android.com/topic/libraries/support-library/androidx-rn\nandroid.useAndroidX=true\n\n# Use this property to specify which architecture you want to build.\n# You can also override it from the CLI using\n# ./gradlew <task> -PreactNativeArchitectures=x86_64\nreactNativeArchitectures=armeabi-v7a,arm64-v8a,x86,x86_64\n\n# Use this property to enable support to the new architecture.\n# This will allow you to use TurboModules and the Fabric render in\n# your application. You should enable this flag either if you want\n# to write custom TurboModules/Fabric components OR use libraries that\n# are providing them.\nnewArchEnabled=true\n\n# Use this property to enable or disable the Hermes JS engine.\n# If set to false, you will be using JSC instead.\nhermesEnabled=true\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/gradlew",
    "content": "#!/bin/sh\n\n#\n# Copyright © 2015-2021 the original authors.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      https://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n#\n# SPDX-License-Identifier: Apache-2.0\n#\n\n##############################################################################\n#\n#   Gradle start up script for POSIX generated by Gradle.\n#\n#   Important for running:\n#\n#   (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is\n#       noncompliant, but you have some other compliant shell such as ksh or\n#       bash, then to run this script, type that shell name before the whole\n#       command line, like:\n#\n#           ksh Gradle\n#\n#       Busybox and similar reduced shells will NOT work, because this script\n#       requires all of these POSIX shell features:\n#         * functions;\n#         * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,\n#           «${var#prefix}», «${var%suffix}», and «$( cmd )»;\n#         * compound commands having a testable exit status, especially «case»;\n#         * various built-in commands including «command», «set», and «ulimit».\n#\n#   Important for patching:\n#\n#   (2) This script targets any POSIX shell, so it avoids extensions provided\n#       by Bash, Ksh, etc; in particular arrays are avoided.\n#\n#       The \"traditional\" practice of packing multiple parameters into a\n#       space-separated string is a well documented source of bugs and security\n#       problems, so this is (mostly) avoided, by progressively accumulating\n#       options in \"$@\", and eventually passing that to Java.\n#\n#       Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,\n#       and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;\n#       see the in-line comments for details.\n#\n#       There are tweaks for specific operating systems such as AIX, CygWin,\n#       Darwin, MinGW, and NonStop.\n#\n#   (3) This script is generated from the Groovy template\n#       https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt\n#       within the Gradle project.\n#\n#       You can find Gradle at https://github.com/gradle/gradle/.\n#\n##############################################################################\n\n# Attempt to set APP_HOME\n\n# Resolve links: $0 may be a link\napp_path=$0\n\n# Need this for daisy-chained symlinks.\nwhile\n    APP_HOME=${app_path%\"${app_path##*/}\"}  # leaves a trailing /; empty if no leading path\n    [ -h \"$app_path\" ]\ndo\n    ls=$( ls -ld \"$app_path\" )\n    link=${ls#*' -> '}\n    case $link in             #(\n      /*)   app_path=$link ;; #(\n      *)    app_path=$APP_HOME$link ;;\n    esac\ndone\n\n# This is normally unused\n# shellcheck disable=SC2034\nAPP_BASE_NAME=${0##*/}\n# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)\nAPP_HOME=$( cd -P \"${APP_HOME:-./}\" > /dev/null && printf '%s\\n' \"$PWD\" ) || exit\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=maximum\n\nwarn () {\n    echo \"$*\"\n} >&2\n\ndie () {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n} >&2\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\nnonstop=false\ncase \"$( uname )\" in                #(\n  CYGWIN* )         cygwin=true  ;; #(\n  Darwin* )         darwin=true  ;; #(\n  MSYS* | MINGW* )  msys=true    ;; #(\n  NONSTOP* )        nonstop=true ;;\nesac\n\nCLASSPATH=\"\\\\\\\"\\\\\\\"\"\n\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=$JAVA_HOME/jre/sh/java\n    else\n        JAVACMD=$JAVA_HOME/bin/java\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=java\n    if ! command -v java >/dev/null 2>&1\n    then\n        die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nfi\n\n# Increase the maximum file descriptors if we can.\nif ! \"$cygwin\" && ! \"$darwin\" && ! \"$nonstop\" ; then\n    case $MAX_FD in #(\n      max*)\n        # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.\n        # shellcheck disable=SC2039,SC3045\n        MAX_FD=$( ulimit -H -n ) ||\n            warn \"Could not query maximum file descriptor limit\"\n    esac\n    case $MAX_FD in  #(\n      '' | soft) :;; #(\n      *)\n        # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.\n        # shellcheck disable=SC2039,SC3045\n        ulimit -n \"$MAX_FD\" ||\n            warn \"Could not set maximum file descriptor limit to $MAX_FD\"\n    esac\nfi\n\n# Collect all arguments for the java command, stacking in reverse order:\n#   * args from the command line\n#   * the main class name\n#   * -classpath\n#   * -D...appname settings\n#   * --module-path (only if needed)\n#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.\n\n# For Cygwin or MSYS, switch paths to Windows format before running java\nif \"$cygwin\" || \"$msys\" ; then\n    APP_HOME=$( cygpath --path --mixed \"$APP_HOME\" )\n    CLASSPATH=$( cygpath --path --mixed \"$CLASSPATH\" )\n\n    JAVACMD=$( cygpath --unix \"$JAVACMD\" )\n\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    for arg do\n        if\n            case $arg in                                #(\n              -*)   false ;;                            # don't mess with options #(\n              /?*)  t=${arg#/} t=/${t%%/*}              # looks like a POSIX filepath\n                    [ -e \"$t\" ] ;;                      #(\n              *)    false ;;\n            esac\n        then\n            arg=$( cygpath --path --ignore --mixed \"$arg\" )\n        fi\n        # Roll the args list around exactly as many times as the number of\n        # args, so each arg winds up back in the position where it started, but\n        # possibly modified.\n        #\n        # NB: a `for` loop captures its iteration list before it begins, so\n        # changing the positional parameters here affects neither the number of\n        # iterations, nor the values presented in `arg`.\n        shift                   # remove old arg\n        set -- \"$@\" \"$arg\"      # push replacement arg\n    done\nfi\n\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS='\"-Xmx64m\" \"-Xms64m\"'\n\n# Collect all arguments for the java command:\n#   * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,\n#     and any embedded shellness will be escaped.\n#   * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be\n#     treated as '${Hostname}' itself on the command line.\n\nset -- \\\n        \"-Dorg.gradle.appname=$APP_BASE_NAME\" \\\n        -classpath \"$CLASSPATH\" \\\n        -jar \"$APP_HOME/gradle/wrapper/gradle-wrapper.jar\" \\\n        \"$@\"\n\n# Stop when \"xargs\" is not available.\nif ! command -v xargs >/dev/null 2>&1\nthen\n    die \"xargs is not available\"\nfi\n\n# Use \"xargs\" to parse quoted args.\n#\n# With -n1 it outputs one arg per line, with the quotes and backslashes removed.\n#\n# In Bash we could simply go:\n#\n#   readarray ARGS < <( xargs -n1 <<<\"$var\" ) &&\n#   set -- \"${ARGS[@]}\" \"$@\"\n#\n# but POSIX shell has neither arrays nor command substitution, so instead we\n# post-process each arg (as a line of input to sed) to backslash-escape any\n# character that might be a shell metacharacter, then use eval to reverse\n# that process (while maintaining the separation between arguments), and wrap\n# the whole thing up as a single \"set\" statement.\n#\n# This will of course break if any of these variables contains a newline or\n# an unmatched quote.\n#\n\neval \"set -- $(\n        printf '%s\\n' \"$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS\" |\n        xargs -n1 |\n        sed ' s~[^-[:alnum:]+,./:=@_]~\\\\&~g; ' |\n        tr '\\n' ' '\n    )\" '\"$@\"'\n\nexec \"$JAVACMD\" \"$@\"\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/gradlew.bat",
    "content": "@rem\n@rem Copyright 2015 the original author or authors.\n@rem\n@rem Licensed under the Apache License, Version 2.0 (the \"License\");\n@rem you may not use this file except in compliance with the License.\n@rem You may obtain a copy of the License at\n@rem\n@rem      https://www.apache.org/licenses/LICENSE-2.0\n@rem\n@rem Unless required by applicable law or agreed to in writing, software\n@rem distributed under the License is distributed on an \"AS IS\" BASIS,\n@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n@rem See the License for the specific language governing permissions and\n@rem limitations under the License.\n@rem\n@rem SPDX-License-Identifier: Apache-2.0\n@rem\n\n@if \"%DEBUG%\"==\"\" @echo off\n@rem ##########################################################################\n@rem\n@rem  Gradle startup script for Windows\n@rem\n@rem ##########################################################################\n\n@rem Set local scope for the variables with windows NT shell\nif \"%OS%\"==\"Windows_NT\" setlocal\n\nset DIRNAME=%~dp0\nif \"%DIRNAME%\"==\"\" set DIRNAME=.\n@rem This is normally unused\nset APP_BASE_NAME=%~n0\nset APP_HOME=%DIRNAME%\n\n@rem Resolve any \".\" and \"..\" in APP_HOME to make it shorter.\nfor %%i in (\"%APP_HOME%\") do set APP_HOME=%%~fi\n\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nset DEFAULT_JVM_OPTS=\"-Xmx64m\" \"-Xms64m\"\n\n@rem Find java.exe\nif defined JAVA_HOME goto findJavaFromJavaHome\n\nset JAVA_EXE=java.exe\n%JAVA_EXE% -version >NUL 2>&1\nif %ERRORLEVEL% equ 0 goto execute\n\necho. 1>&2\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2\necho. 1>&2\necho Please set the JAVA_HOME variable in your environment to match the 1>&2\necho location of your Java installation. 1>&2\n\ngoto fail\n\n:findJavaFromJavaHome\nset JAVA_HOME=%JAVA_HOME:\"=%\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\n\nif exist \"%JAVA_EXE%\" goto execute\n\necho. 1>&2\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2\necho. 1>&2\necho Please set the JAVA_HOME variable in your environment to match the 1>&2\necho location of your Java installation. 1>&2\n\ngoto fail\n\n:execute\n@rem Setup the command line\n\nset CLASSPATH=\n\n\n@rem Execute Gradle\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" -jar \"%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\" %*\n\n:end\n@rem End local scope for the variables with windows NT shell\nif %ERRORLEVEL% equ 0 goto mainEnd\n\n:fail\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\nrem the _cmd.exe /c_ return code!\nset EXIT_CODE=%ERRORLEVEL%\nif %EXIT_CODE% equ 0 set EXIT_CODE=1\nif not \"\"==\"%GRADLE_EXIT_CONSOLE%\" exit %EXIT_CODE%\nexit /b %EXIT_CODE%\n\n:mainEnd\nif \"%OS%\"==\"Windows_NT\" endlocal\n\n:omega\n"
  },
  {
    "path": "examples/publish-ci/react-native/android/settings.gradle",
    "content": "pluginManagement { includeBuild(\"../node_modules/@react-native/gradle-plugin\") }\nplugins { id(\"com.facebook.react.settings\") }\nextensions.configure(com.facebook.react.ReactSettingsExtension){ ex -> ex.autolinkLibrariesFromCommand() }\nrootProject.name = 'reduxTemplate'\ninclude ':app'\nincludeBuild('../node_modules/@react-native/gradle-plugin')\n"
  },
  {
    "path": "examples/publish-ci/react-native/app.json",
    "content": "{\n  \"name\": \"reduxTemplate\",\n  \"displayName\": \"reduxTemplate\"\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/babel.config.js",
    "content": "/** @import { ConfigFunction } from '@babel/core' */\n\n/**\n * @satisfies {ConfigFunction}\n */\nconst config = api => {\n  api.cache.using(() => process.env.NODE_ENV)\n\n  return {\n    presets: [['module:@react-native/babel-preset']],\n  }\n}\n\nmodule.exports = config\n"
  },
  {
    "path": "examples/publish-ci/react-native/eslint.config.mjs",
    "content": "import js from '@eslint/js'\nimport prettierConfig from 'eslint-config-prettier/flat'\nimport jestPlugin from 'eslint-plugin-jest'\nimport reactPlugin from 'eslint-plugin-react'\nimport reactHooksPlugin from 'eslint-plugin-react-hooks'\nimport globals from 'globals'\nimport { config, configs } from 'typescript-eslint'\n\nconst eslintConfig = config(\n  {\n    name: 'global-ignores',\n    ignores: [\n      '**/dist/',\n      '**/build/',\n      '**/lib/',\n      '**/coverage/',\n      '**/__snapshots__/',\n      '**/temp/',\n      '**/.temp/',\n      '**/.tmp/',\n      '**/.yalc/',\n      '**/.yarn/',\n      '**/.docusaurus/',\n      '**/.next/',\n      '**/.expo/',\n      '**/*.snap',\n    ],\n  },\n  {\n    name: `${js.meta.name}/recommended`,\n    ...js.configs.recommended,\n  },\n  configs.strictTypeChecked,\n  configs.stylisticTypeChecked,\n  {\n    name: `${jestPlugin.meta.name}/recommended`,\n    ...jestPlugin.configs['flat/recommended'],\n  },\n  {\n    name: 'eslint-plugin-react/jsx-runtime',\n    ...reactPlugin.configs.flat['jsx-runtime'],\n  },\n  reactHooksPlugin.configs['recommended-latest'],\n  {\n    name: 'main',\n\n    languageOptions: {\n      ecmaVersion: 2020,\n      globals: globals.node,\n      parserOptions: {\n        projectService: true,\n        tsconfigRootDir: import.meta.dirname,\n      },\n    },\n    rules: {\n      'no-undef': [0],\n      '@typescript-eslint/no-unused-vars': [\n        2,\n        {\n          args: 'all',\n          argsIgnorePattern: '^_',\n          caughtErrors: 'all',\n          caughtErrorsIgnorePattern: '^_',\n          destructuredArrayIgnorePattern: '^_',\n          varsIgnorePattern: '^_',\n          ignoreRestSiblings: true,\n        },\n      ],\n      'no-restricted-imports': [\n        2,\n        {\n          paths: [\n            {\n              name: 'react-redux',\n              importNames: ['useSelector', 'useStore', 'useDispatch'],\n              message:\n                'Please use pre-typed versions from `src/app/hooks.ts` instead.',\n            },\n          ],\n        },\n      ],\n      '@typescript-eslint/consistent-type-definitions': [2, 'type'],\n      '@typescript-eslint/consistent-type-imports': [\n        2,\n        {\n          prefer: 'type-imports',\n          fixStyle: 'separate-type-imports',\n          disallowTypeAnnotations: true,\n        },\n      ],\n    },\n\n    linterOptions: {\n      reportUnusedDisableDirectives: 2,\n    },\n  },\n  {\n    name: 'commonjs-files',\n    files: ['metro.config.js'],\n    languageOptions: {\n      sourceType: 'commonjs',\n    },\n    rules: {\n      '@typescript-eslint/no-require-imports': [\n        0,\n        { allow: [], allowAsImport: false },\n      ],\n    },\n  },\n\n  prettierConfig,\n)\n\nexport default eslintConfig\n"
  },
  {
    "path": "examples/publish-ci/react-native/globals.d.ts",
    "content": "declare module '*.gif' {\n  const logo: number\n  export default logo\n}\n\ndeclare module 'react-native/Libraries/NewAppScreen' {\n  import type { FC } from 'react'\n  export const HermesBadge: FC\n}\n\ndeclare module 'react-native/Libraries/Core/Devtools/openURLInBrowser' {\n  export default function openURLInBrowser(url: string): void\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/index.js",
    "content": "import { AppRegistry } from 'react-native'\nimport { Provider } from 'react-redux'\nimport { App } from './App'\nimport { name as appName } from './app.json'\nimport { store } from './src/app/store'\n\nAppRegistry.registerComponent(appName, () => () => (\n  <Provider store={store}>\n    <App />\n  </Provider>\n))\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/.xcode.env",
    "content": "# This `.xcode.env` file is versioned and is used to source the environment\n# used when running script phases inside Xcode.\n# To customize your local environment, you can create an `.xcode.env.local`\n# file that is not versioned.\n\n# NODE_BINARY variable contains the PATH to the node executable.\n#\n# Customize the NODE_BINARY variable here.\n# For example, to use nvm with brew, add the following line\n# . \"$(brew --prefix nvm)/nvm.sh\" --no-use\nexport NODE_BINARY=$(command -v node)\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/Podfile",
    "content": "# Resolve react_native_pods.rb with node to allow for hoisting\nrequire Pod::Executable.execute_command('node', ['-p',\n  'require.resolve(\n    \"react-native/scripts/react_native_pods.rb\",\n    {paths: [process.argv[1]]},\n  )', __dir__]).strip\n\nplatform :ios, min_ios_version_supported\nprepare_react_native_project!\n\nlinkage = ENV['USE_FRAMEWORKS']\nif linkage != nil\n  Pod::UI.puts \"Configuring Pod with #{linkage}ally linked Frameworks\".green\n  use_frameworks! :linkage => linkage.to_sym\nend\n\ntarget 'reduxTemplate' do\n  config = use_native_modules!\n\n  use_react_native!(\n    :path => config[:reactNativePath],\n    # An absolute path to your application root.\n    :app_path => \"#{Pod::Config.instance.installation_root}/..\"\n  )\n\n  target 'reduxTemplateTests' do\n    inherit! :complete\n    # Pods for testing\n  end\n\n  post_install do |installer|\n    # https://github.com/facebook/react-native/blob/main/packages/react-native/scripts/react_native_pods.rb#L197-L202\n    react_native_post_install(\n      installer,\n      config[:reactNativePath],\n      :mac_catalyst_enabled => false,\n      # :ccache_enabled => true\n    )\n  end\nend\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplate/AppDelegate.h",
    "content": "#import <RCTAppDelegate.h>\n#import <UIKit/UIKit.h>\n\n@interface AppDelegate : RCTAppDelegate\n\n@end\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplate/AppDelegate.mm",
    "content": "#import \"AppDelegate.h\"\n\n#import <React/RCTBundleURLProvider.h>\n\n@implementation AppDelegate\n\n- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions\n{\n  self.moduleName = @\"reduxTemplate\";\n  // You can add your custom initial props in the dictionary below.\n  // They will be passed down to the ViewController used by React Native.\n  self.initialProps = @{};\n\n  return [super application:application didFinishLaunchingWithOptions:launchOptions];\n}\n\n- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge\n{\n  return [self bundleURL];\n}\n\n- (NSURL *)bundleURL\n{\n#if DEBUG\n  return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@\"index\"];\n#else\n  return [[NSBundle mainBundle] URLForResource:@\"main\" withExtension:@\"jsbundle\"];\n#endif\n}\n\n@end\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplate/Images.xcassets/AppIcon.appiconset/Contents.json",
    "content": "{\n  \"images\": [\n    {\n      \"idiom\": \"iphone\",\n      \"scale\": \"2x\",\n      \"size\": \"20x20\"\n    },\n    {\n      \"idiom\": \"iphone\",\n      \"scale\": \"3x\",\n      \"size\": \"20x20\"\n    },\n    {\n      \"idiom\": \"iphone\",\n      \"scale\": \"2x\",\n      \"size\": \"29x29\"\n    },\n    {\n      \"idiom\": \"iphone\",\n      \"scale\": \"3x\",\n      \"size\": \"29x29\"\n    },\n    {\n      \"idiom\": \"iphone\",\n      \"scale\": \"2x\",\n      \"size\": \"40x40\"\n    },\n    {\n      \"idiom\": \"iphone\",\n      \"scale\": \"3x\",\n      \"size\": \"40x40\"\n    },\n    {\n      \"idiom\": \"iphone\",\n      \"scale\": \"2x\",\n      \"size\": \"60x60\"\n    },\n    {\n      \"idiom\": \"iphone\",\n      \"scale\": \"3x\",\n      \"size\": \"60x60\"\n    },\n    {\n      \"idiom\": \"ios-marketing\",\n      \"scale\": \"1x\",\n      \"size\": \"1024x1024\"\n    }\n  ],\n  \"info\": {\n    \"author\": \"xcode\",\n    \"version\": 1\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplate/Images.xcassets/Contents.json",
    "content": "{\n  \"info\": {\n    \"version\": 1,\n    \"author\": \"xcode\"\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplate/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleDisplayName</key>\n\t<string>reduxTemplate</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>APPL</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>$(MARKETING_VERSION)</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>$(CURRENT_PROJECT_VERSION)</string>\n\t<key>LSRequiresIPhoneOS</key>\n\t<true/>\n\t<key>NSAppTransportSecurity</key>\n\t<dict>\n\t  <!-- Do not change NSAllowsArbitraryLoads to true, or you will risk app rejection! -->\n\t\t<key>NSAllowsArbitraryLoads</key>\n\t\t<false/>\n\t\t<key>NSAllowsLocalNetworking</key>\n\t\t<true/>\n\t</dict>\n\t<key>NSLocationWhenInUseUsageDescription</key>\n\t<string></string>\n\t<key>UILaunchStoryboardName</key>\n\t<string>LaunchScreen</string>\n\t<key>UIRequiredDeviceCapabilities</key>\n\t<array>\n\t\t<string>arm64</string>\n\t</array>\n\t<key>UISupportedInterfaceOrientations</key>\n\t<array>\n\t\t<string>UIInterfaceOrientationPortrait</string>\n\t\t<string>UIInterfaceOrientationLandscapeLeft</string>\n\t\t<string>UIInterfaceOrientationLandscapeRight</string>\n\t</array>\n\t<key>UIViewControllerBasedStatusBarAppearance</key>\n\t<false/>\n</dict>\n</plist>\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplate/LaunchScreen.storyboard",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<document type=\"com.apple.InterfaceBuilder3.CocoaTouch.Storyboard.XIB\" version=\"3.0\" toolsVersion=\"15702\" targetRuntime=\"iOS.CocoaTouch\" propertyAccessControl=\"none\" useAutolayout=\"YES\" launchScreen=\"YES\" useTraitCollections=\"YES\" useSafeAreas=\"YES\" colorMatched=\"YES\" initialViewController=\"01J-lp-oVM\">\n    <device id=\"retina4_7\" orientation=\"portrait\" appearance=\"light\"/>\n    <dependencies>\n        <deployment identifier=\"iOS\"/>\n        <plugIn identifier=\"com.apple.InterfaceBuilder.IBCocoaTouchPlugin\" version=\"15704\"/>\n        <capability name=\"Safe area layout guides\" minToolsVersion=\"9.0\"/>\n        <capability name=\"documents saved in the Xcode 8 format\" minToolsVersion=\"8.0\"/>\n    </dependencies>\n    <scenes>\n        <!--View Controller-->\n        <scene sceneID=\"EHf-IW-A2E\">\n            <objects>\n                <viewController id=\"01J-lp-oVM\" sceneMemberID=\"viewController\">\n                    <view key=\"view\" contentMode=\"scaleToFill\" id=\"Ze5-6b-2t3\">\n                        <rect key=\"frame\" x=\"0.0\" y=\"0.0\" width=\"375\" height=\"667\"/>\n                        <autoresizingMask key=\"autoresizingMask\" widthSizable=\"YES\" heightSizable=\"YES\"/>\n                        <subviews>\n                            <label opaque=\"NO\" clipsSubviews=\"YES\" userInteractionEnabled=\"NO\" contentMode=\"left\" horizontalHuggingPriority=\"251\" verticalHuggingPriority=\"251\" text=\"reduxTemplate\" textAlignment=\"center\" lineBreakMode=\"middleTruncation\" baselineAdjustment=\"alignBaselines\" minimumFontSize=\"18\" translatesAutoresizingMaskIntoConstraints=\"NO\" id=\"GJd-Yh-RWb\">\n                                <rect key=\"frame\" x=\"0.0\" y=\"202\" width=\"375\" height=\"43\"/>\n                                <fontDescription key=\"fontDescription\" type=\"boldSystem\" pointSize=\"36\"/>\n                                <nil key=\"highlightedColor\"/>\n                            </label>\n                            <label opaque=\"NO\" clipsSubviews=\"YES\" userInteractionEnabled=\"NO\" contentMode=\"left\" horizontalHuggingPriority=\"251\" verticalHuggingPriority=\"251\" text=\"Powered by React Native\" textAlignment=\"center\" lineBreakMode=\"tailTruncation\" baselineAdjustment=\"alignBaselines\" minimumFontSize=\"9\" translatesAutoresizingMaskIntoConstraints=\"NO\" id=\"MN2-I3-ftu\">\n                                <rect key=\"frame\" x=\"0.0\" y=\"626\" width=\"375\" height=\"21\"/>\n                                <fontDescription key=\"fontDescription\" type=\"system\" pointSize=\"17\"/>\n                                <nil key=\"highlightedColor\"/>\n                            </label>\n                        </subviews>\n                        <color key=\"backgroundColor\" systemColor=\"systemBackgroundColor\" cocoaTouchSystemColor=\"whiteColor\"/>\n                        <constraints>\n                            <constraint firstItem=\"Bcu-3y-fUS\" firstAttribute=\"bottom\" secondItem=\"MN2-I3-ftu\" secondAttribute=\"bottom\" constant=\"20\" id=\"OZV-Vh-mqD\"/>\n                            <constraint firstItem=\"Bcu-3y-fUS\" firstAttribute=\"centerX\" secondItem=\"GJd-Yh-RWb\" secondAttribute=\"centerX\" id=\"Q3B-4B-g5h\"/>\n                            <constraint firstItem=\"MN2-I3-ftu\" firstAttribute=\"centerX\" secondItem=\"Bcu-3y-fUS\" secondAttribute=\"centerX\" id=\"akx-eg-2ui\"/>\n                            <constraint firstItem=\"MN2-I3-ftu\" firstAttribute=\"leading\" secondItem=\"Bcu-3y-fUS\" secondAttribute=\"leading\" id=\"i1E-0Y-4RG\"/>\n                            <constraint firstItem=\"GJd-Yh-RWb\" firstAttribute=\"centerY\" secondItem=\"Ze5-6b-2t3\" secondAttribute=\"bottom\" multiplier=\"1/3\" constant=\"1\" id=\"moa-c2-u7t\"/>\n                            <constraint firstItem=\"GJd-Yh-RWb\" firstAttribute=\"leading\" secondItem=\"Bcu-3y-fUS\" secondAttribute=\"leading\" symbolic=\"YES\" id=\"x7j-FC-K8j\"/>\n                        </constraints>\n                        <viewLayoutGuide key=\"safeArea\" id=\"Bcu-3y-fUS\"/>\n                    </view>\n                </viewController>\n                <placeholder placeholderIdentifier=\"IBFirstResponder\" id=\"iYj-Kq-Ea1\" userLabel=\"First Responder\" sceneMemberID=\"firstResponder\"/>\n            </objects>\n            <point key=\"canvasLocation\" x=\"52.173913043478265\" y=\"375\"/>\n        </scene>\n    </scenes>\n</document>\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplate/PrivacyInfo.xcprivacy",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>NSPrivacyAccessedAPITypes</key>\n\t<array>\n\t\t<dict>\n\t\t\t<key>NSPrivacyAccessedAPIType</key>\n\t\t\t<string>NSPrivacyAccessedAPICategoryFileTimestamp</string>\n\t\t\t<key>NSPrivacyAccessedAPITypeReasons</key>\n\t\t\t<array>\n\t\t\t\t<string>C617.1</string>\n\t\t\t</array>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>NSPrivacyAccessedAPIType</key>\n\t\t\t<string>NSPrivacyAccessedAPICategoryUserDefaults</string>\n\t\t\t<key>NSPrivacyAccessedAPITypeReasons</key>\n\t\t\t<array>\n\t\t\t\t<string>CA92.1</string>\n\t\t\t</array>\n\t\t</dict>\n\t\t<dict>\n\t\t\t<key>NSPrivacyAccessedAPIType</key>\n\t\t\t<string>NSPrivacyAccessedAPICategorySystemBootTime</string>\n\t\t\t<key>NSPrivacyAccessedAPITypeReasons</key>\n\t\t\t<array>\n\t\t\t\t<string>35F9.1</string>\n\t\t\t</array>\n\t\t</dict>\n\t</array>\n\t<key>NSPrivacyCollectedDataTypes</key>\n\t<array/>\n\t<key>NSPrivacyTracking</key>\n\t<false/>\n</dict>\n</plist>\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplate/main.m",
    "content": "#import <UIKit/UIKit.h>\n\n#import \"AppDelegate.h\"\n\nint main(int argc, char *argv[])\n{\n  @autoreleasepool {\n    return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplate.xcodeproj/project.pbxproj",
    "content": "// !$*UTF8*$!\n{\n\tarchiveVersion = 1;\n\tclasses = {\n\t};\n\tobjectVersion = 54;\n\tobjects = {\n\n/* Begin PBXBuildFile section */\n\t\t00E356F31AD99517003FC87E /* reduxTemplateTests.m in Sources */ = {isa = PBXBuildFile; fileRef = 00E356F21AD99517003FC87E /* reduxTemplateTests.m */; };\n\t\t0C80B921A6F3F58F76C31292 /* libPods-reduxTemplate.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 5DCACB8F33CDC322A6C60F78 /* libPods-reduxTemplate.a */; };\n\t\t13B07FBC1A68108700A75B9A /* AppDelegate.mm in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB01A68108700A75B9A /* AppDelegate.mm */; };\n\t\t13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 13B07FB51A68108700A75B9A /* Images.xcassets */; };\n\t\t13B07FC11A68108700A75B9A /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 13B07FB71A68108700A75B9A /* main.m */; };\n\t\t7699B88040F8A987B510C191 /* libPods-reduxTemplate-reduxTemplateTests.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 19F6CBCC0A4E27FBF8BF4A61 /* libPods-reduxTemplate-reduxTemplateTests.a */; };\n\t\t81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */; };\n/* End PBXBuildFile section */\n\n/* Begin PBXContainerItemProxy section */\n\t\t00E356F41AD99517003FC87E /* PBXContainerItemProxy */ = {\n\t\t\tisa = PBXContainerItemProxy;\n\t\t\tcontainerPortal = 83CBB9F71A601CBA00E9B192 /* Project object */;\n\t\t\tproxyType = 1;\n\t\t\tremoteGlobalIDString = 13B07F861A680F5B00A75B9A;\n\t\t\tremoteInfo = reduxTemplate;\n\t\t};\n/* End PBXContainerItemProxy section */\n\n/* Begin PBXFileReference section */\n\t\t00E356EE1AD99517003FC87E /* reduxTemplateTests.xctest */ = {isa = PBXFileReference; explicitFileType = wrapper.cfbundle; includeInIndex = 0; path = reduxTemplateTests.xctest; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t00E356F11AD99517003FC87E /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = \"<group>\"; };\n\t\t00E356F21AD99517003FC87E /* reduxTemplateTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = reduxTemplateTests.m; sourceTree = \"<group>\"; };\n\t\t13B07F961A680F5B00A75B9A /* reduxTemplate.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = reduxTemplate.app; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t13B07FAF1A68108700A75B9A /* AppDelegate.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = AppDelegate.h; path = reduxTemplate/AppDelegate.h; sourceTree = \"<group>\"; };\n\t\t13B07FB01A68108700A75B9A /* AppDelegate.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = AppDelegate.mm; path = reduxTemplate/AppDelegate.mm; sourceTree = \"<group>\"; };\n\t\t13B07FB51A68108700A75B9A /* Images.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; name = Images.xcassets; path = reduxTemplate/Images.xcassets; sourceTree = \"<group>\"; };\n\t\t13B07FB61A68108700A75B9A /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = Info.plist; path = reduxTemplate/Info.plist; sourceTree = \"<group>\"; };\n\t\t13B07FB71A68108700A75B9A /* main.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; name = main.m; path = reduxTemplate/main.m; sourceTree = \"<group>\"; };\n\t\t13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; name = PrivacyInfo.xcprivacy; path = reduxTemplate/PrivacyInfo.xcprivacy; sourceTree = \"<group>\"; };\n\t\t19F6CBCC0A4E27FBF8BF4A61 /* libPods-reduxTemplate-reduxTemplateTests.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = \"libPods-reduxTemplate-reduxTemplateTests.a\"; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t3B4392A12AC88292D35C810B /* Pods-reduxTemplate.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = \"Pods-reduxTemplate.debug.xcconfig\"; path = \"Target Support Files/Pods-reduxTemplate/Pods-reduxTemplate.debug.xcconfig\"; sourceTree = \"<group>\"; };\n\t\t5709B34CF0A7D63546082F79 /* Pods-reduxTemplate.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = \"Pods-reduxTemplate.release.xcconfig\"; path = \"Target Support Files/Pods-reduxTemplate/Pods-reduxTemplate.release.xcconfig\"; sourceTree = \"<group>\"; };\n\t\t5B7EB9410499542E8C5724F5 /* Pods-reduxTemplate-reduxTemplateTests.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = \"Pods-reduxTemplate-reduxTemplateTests.debug.xcconfig\"; path = \"Target Support Files/Pods-reduxTemplate-reduxTemplateTests/Pods-reduxTemplate-reduxTemplateTests.debug.xcconfig\"; sourceTree = \"<group>\"; };\n\t\t5DCACB8F33CDC322A6C60F78 /* libPods-reduxTemplate.a */ = {isa = PBXFileReference; explicitFileType = archive.ar; includeInIndex = 0; path = \"libPods-reduxTemplate.a\"; sourceTree = BUILT_PRODUCTS_DIR; };\n\t\t81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = file.storyboard; name = LaunchScreen.storyboard; path = reduxTemplate/LaunchScreen.storyboard; sourceTree = \"<group>\"; };\n\t\t89C6BE57DB24E9ADA2F236DE /* Pods-reduxTemplate-reduxTemplateTests.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = \"Pods-reduxTemplate-reduxTemplateTests.release.xcconfig\"; path = \"Target Support Files/Pods-reduxTemplate-reduxTemplateTests/Pods-reduxTemplate-reduxTemplateTests.release.xcconfig\"; sourceTree = \"<group>\"; };\n\t\tED297162215061F000B7C4FE /* JavaScriptCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaScriptCore.framework; path = System/Library/Frameworks/JavaScriptCore.framework; sourceTree = SDKROOT; };\n/* End PBXFileReference section */\n\n/* Begin PBXFrameworksBuildPhase section */\n\t\t00E356EB1AD99517003FC87E /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t7699B88040F8A987B510C191 /* libPods-reduxTemplate-reduxTemplateTests.a in Frameworks */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t13B07F8C1A680F5B00A75B9A /* Frameworks */ = {\n\t\t\tisa = PBXFrameworksBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t0C80B921A6F3F58F76C31292 /* libPods-reduxTemplate.a in Frameworks */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXFrameworksBuildPhase section */\n\n/* Begin PBXGroup section */\n\t\t00E356EF1AD99517003FC87E /* reduxTemplateTests */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t00E356F21AD99517003FC87E /* reduxTemplateTests.m */,\n\t\t\t\t00E356F01AD99517003FC87E /* Supporting Files */,\n\t\t\t);\n\t\t\tpath = reduxTemplateTests;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t00E356F01AD99517003FC87E /* Supporting Files */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t00E356F11AD99517003FC87E /* Info.plist */,\n\t\t\t);\n\t\t\tname = \"Supporting Files\";\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t13B07FAE1A68108700A75B9A /* reduxTemplate */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t13B07FAF1A68108700A75B9A /* AppDelegate.h */,\n\t\t\t\t13B07FB01A68108700A75B9A /* AppDelegate.mm */,\n\t\t\t\t13B07FB51A68108700A75B9A /* Images.xcassets */,\n\t\t\t\t13B07FB61A68108700A75B9A /* Info.plist */,\n\t\t\t\t81AB9BB72411601600AC10FF /* LaunchScreen.storyboard */,\n\t\t\t\t13B07FB71A68108700A75B9A /* main.m */,\n\t\t\t\t13B07FB81A68108700A75B9A /* PrivacyInfo.xcprivacy */,\n\t\t\t);\n\t\t\tname = reduxTemplate;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t2D16E6871FA4F8E400B85C8A /* Frameworks */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\tED297162215061F000B7C4FE /* JavaScriptCore.framework */,\n\t\t\t\t5DCACB8F33CDC322A6C60F78 /* libPods-reduxTemplate.a */,\n\t\t\t\t19F6CBCC0A4E27FBF8BF4A61 /* libPods-reduxTemplate-reduxTemplateTests.a */,\n\t\t\t);\n\t\t\tname = Frameworks;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t832341AE1AAA6A7D00B99B32 /* Libraries */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t);\n\t\t\tname = Libraries;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\t83CBB9F61A601CBA00E9B192 = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t13B07FAE1A68108700A75B9A /* reduxTemplate */,\n\t\t\t\t832341AE1AAA6A7D00B99B32 /* Libraries */,\n\t\t\t\t00E356EF1AD99517003FC87E /* reduxTemplateTests */,\n\t\t\t\t83CBBA001A601CBA00E9B192 /* Products */,\n\t\t\t\t2D16E6871FA4F8E400B85C8A /* Frameworks */,\n\t\t\t\tBBD78D7AC51CEA395F1C20DB /* Pods */,\n\t\t\t);\n\t\t\tindentWidth = 2;\n\t\t\tsourceTree = \"<group>\";\n\t\t\ttabWidth = 2;\n\t\t\tusesTabs = 0;\n\t\t};\n\t\t83CBBA001A601CBA00E9B192 /* Products */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t13B07F961A680F5B00A75B9A /* reduxTemplate.app */,\n\t\t\t\t00E356EE1AD99517003FC87E /* reduxTemplateTests.xctest */,\n\t\t\t);\n\t\t\tname = Products;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n\t\tBBD78D7AC51CEA395F1C20DB /* Pods */ = {\n\t\t\tisa = PBXGroup;\n\t\t\tchildren = (\n\t\t\t\t3B4392A12AC88292D35C810B /* Pods-reduxTemplate.debug.xcconfig */,\n\t\t\t\t5709B34CF0A7D63546082F79 /* Pods-reduxTemplate.release.xcconfig */,\n\t\t\t\t5B7EB9410499542E8C5724F5 /* Pods-reduxTemplate-reduxTemplateTests.debug.xcconfig */,\n\t\t\t\t89C6BE57DB24E9ADA2F236DE /* Pods-reduxTemplate-reduxTemplateTests.release.xcconfig */,\n\t\t\t);\n\t\t\tpath = Pods;\n\t\t\tsourceTree = \"<group>\";\n\t\t};\n/* End PBXGroup section */\n\n/* Begin PBXNativeTarget section */\n\t\t00E356ED1AD99517003FC87E /* reduxTemplateTests */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget \"reduxTemplateTests\" */;\n\t\t\tbuildPhases = (\n\t\t\t\tA55EABD7B0C7F3A422A6CC61 /* [CP] Check Pods Manifest.lock */,\n\t\t\t\t00E356EA1AD99517003FC87E /* Sources */,\n\t\t\t\t00E356EB1AD99517003FC87E /* Frameworks */,\n\t\t\t\t00E356EC1AD99517003FC87E /* Resources */,\n\t\t\t\tC59DA0FBD6956966B86A3779 /* [CP] Embed Pods Frameworks */,\n\t\t\t\tF6A41C54EA430FDDC6A6ED99 /* [CP] Copy Pods Resources */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t\t00E356F51AD99517003FC87E /* PBXTargetDependency */,\n\t\t\t);\n\t\t\tname = reduxTemplateTests;\n\t\t\tproductName = reduxTemplateTests;\n\t\t\tproductReference = 00E356EE1AD99517003FC87E /* reduxTemplateTests.xctest */;\n\t\t\tproductType = \"com.apple.product-type.bundle.unit-test\";\n\t\t};\n\t\t13B07F861A680F5B00A75B9A /* reduxTemplate */ = {\n\t\t\tisa = PBXNativeTarget;\n\t\t\tbuildConfigurationList = 13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget \"reduxTemplate\" */;\n\t\t\tbuildPhases = (\n\t\t\t\tC38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */,\n\t\t\t\t13B07F871A680F5B00A75B9A /* Sources */,\n\t\t\t\t13B07F8C1A680F5B00A75B9A /* Frameworks */,\n\t\t\t\t13B07F8E1A680F5B00A75B9A /* Resources */,\n\t\t\t\t00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */,\n\t\t\t\t00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */,\n\t\t\t\tE235C05ADACE081382539298 /* [CP] Copy Pods Resources */,\n\t\t\t);\n\t\t\tbuildRules = (\n\t\t\t);\n\t\t\tdependencies = (\n\t\t\t);\n\t\t\tname = reduxTemplate;\n\t\t\tproductName = reduxTemplate;\n\t\t\tproductReference = 13B07F961A680F5B00A75B9A /* reduxTemplate.app */;\n\t\t\tproductType = \"com.apple.product-type.application\";\n\t\t};\n/* End PBXNativeTarget section */\n\n/* Begin PBXProject section */\n\t\t83CBB9F71A601CBA00E9B192 /* Project object */ = {\n\t\t\tisa = PBXProject;\n\t\t\tattributes = {\n\t\t\t\tLastUpgradeCheck = 1210;\n\t\t\t\tTargetAttributes = {\n\t\t\t\t\t00E356ED1AD99517003FC87E = {\n\t\t\t\t\t\tCreatedOnToolsVersion = 6.2;\n\t\t\t\t\t\tTestTargetID = 13B07F861A680F5B00A75B9A;\n\t\t\t\t\t};\n\t\t\t\t\t13B07F861A680F5B00A75B9A = {\n\t\t\t\t\t\tLastSwiftMigration = 1120;\n\t\t\t\t\t};\n\t\t\t\t};\n\t\t\t};\n\t\t\tbuildConfigurationList = 83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject \"reduxTemplate\" */;\n\t\t\tcompatibilityVersion = \"Xcode 12.0\";\n\t\t\tdevelopmentRegion = en;\n\t\t\thasScannedForEncodings = 0;\n\t\t\tknownRegions = (\n\t\t\t\ten,\n\t\t\t\tBase,\n\t\t\t);\n\t\t\tmainGroup = 83CBB9F61A601CBA00E9B192;\n\t\t\tproductRefGroup = 83CBBA001A601CBA00E9B192 /* Products */;\n\t\t\tprojectDirPath = \"\";\n\t\t\tprojectRoot = \"\";\n\t\t\ttargets = (\n\t\t\t\t13B07F861A680F5B00A75B9A /* reduxTemplate */,\n\t\t\t\t00E356ED1AD99517003FC87E /* reduxTemplateTests */,\n\t\t\t);\n\t\t};\n/* End PBXProject section */\n\n/* Begin PBXResourcesBuildPhase section */\n\t\t00E356EC1AD99517003FC87E /* Resources */ = {\n\t\t\tisa = PBXResourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t13B07F8E1A680F5B00A75B9A /* Resources */ = {\n\t\t\tisa = PBXResourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t81AB9BB82411601600AC10FF /* LaunchScreen.storyboard in Resources */,\n\t\t\t\t13B07FBF1A68108700A75B9A /* Images.xcassets in Resources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXResourcesBuildPhase section */\n\n/* Begin PBXShellScriptBuildPhase section */\n\t\t00DD1BFF1BD5951E006B06BC /* Bundle React Native code and images */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputPaths = (\n\t\t\t\t\"$(SRCROOT)/.xcode.env.local\",\n\t\t\t\t\"$(SRCROOT)/.xcode.env\",\n\t\t\t);\n\t\t\tname = \"Bundle React Native code and images\";\n\t\t\toutputPaths = (\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"set -e\\n\\nWITH_ENVIRONMENT=\\\"$REACT_NATIVE_PATH/scripts/xcode/with-environment.sh\\\"\\nREACT_NATIVE_XCODE=\\\"$REACT_NATIVE_PATH/scripts/react-native-xcode.sh\\\"\\n\\n/bin/sh -c \\\"$WITH_ENVIRONMENT $REACT_NATIVE_XCODE\\\"\\n\";\n\t\t};\n\t\t00EEFC60759A1932668264C0 /* [CP] Embed Pods Frameworks */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputFileListPaths = (\n\t\t\t\t\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate/Pods-reduxTemplate-frameworks-${CONFIGURATION}-input-files.xcfilelist\",\n\t\t\t);\n\t\t\tname = \"[CP] Embed Pods Frameworks\";\n\t\t\toutputFileListPaths = (\n\t\t\t\t\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate/Pods-reduxTemplate-frameworks-${CONFIGURATION}-output-files.xcfilelist\",\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"\\\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate/Pods-reduxTemplate-frameworks.sh\\\"\\n\";\n\t\t\tshowEnvVarsInLog = 0;\n\t\t};\n\t\tA55EABD7B0C7F3A422A6CC61 /* [CP] Check Pods Manifest.lock */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputFileListPaths = (\n\t\t\t);\n\t\t\tinputPaths = (\n\t\t\t\t\"${PODS_PODFILE_DIR_PATH}/Podfile.lock\",\n\t\t\t\t\"${PODS_ROOT}/Manifest.lock\",\n\t\t\t);\n\t\t\tname = \"[CP] Check Pods Manifest.lock\";\n\t\t\toutputFileListPaths = (\n\t\t\t);\n\t\t\toutputPaths = (\n\t\t\t\t\"$(DERIVED_FILE_DIR)/Pods-reduxTemplate-reduxTemplateTests-checkManifestLockResult.txt\",\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"diff \\\"${PODS_PODFILE_DIR_PATH}/Podfile.lock\\\" \\\"${PODS_ROOT}/Manifest.lock\\\" > /dev/null\\nif [ $? != 0 ] ; then\\n    # print error to STDERR\\n    echo \\\"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\\\" >&2\\n    exit 1\\nfi\\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\\necho \\\"SUCCESS\\\" > \\\"${SCRIPT_OUTPUT_FILE_0}\\\"\\n\";\n\t\t\tshowEnvVarsInLog = 0;\n\t\t};\n\t\tC38B50BA6285516D6DCD4F65 /* [CP] Check Pods Manifest.lock */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputFileListPaths = (\n\t\t\t);\n\t\t\tinputPaths = (\n\t\t\t\t\"${PODS_PODFILE_DIR_PATH}/Podfile.lock\",\n\t\t\t\t\"${PODS_ROOT}/Manifest.lock\",\n\t\t\t);\n\t\t\tname = \"[CP] Check Pods Manifest.lock\";\n\t\t\toutputFileListPaths = (\n\t\t\t);\n\t\t\toutputPaths = (\n\t\t\t\t\"$(DERIVED_FILE_DIR)/Pods-reduxTemplate-checkManifestLockResult.txt\",\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"diff \\\"${PODS_PODFILE_DIR_PATH}/Podfile.lock\\\" \\\"${PODS_ROOT}/Manifest.lock\\\" > /dev/null\\nif [ $? != 0 ] ; then\\n    # print error to STDERR\\n    echo \\\"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\\\" >&2\\n    exit 1\\nfi\\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\\necho \\\"SUCCESS\\\" > \\\"${SCRIPT_OUTPUT_FILE_0}\\\"\\n\";\n\t\t\tshowEnvVarsInLog = 0;\n\t\t};\n\t\tC59DA0FBD6956966B86A3779 /* [CP] Embed Pods Frameworks */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputFileListPaths = (\n\t\t\t\t\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate-reduxTemplateTests/Pods-reduxTemplate-reduxTemplateTests-frameworks-${CONFIGURATION}-input-files.xcfilelist\",\n\t\t\t);\n\t\t\tname = \"[CP] Embed Pods Frameworks\";\n\t\t\toutputFileListPaths = (\n\t\t\t\t\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate-reduxTemplateTests/Pods-reduxTemplate-reduxTemplateTests-frameworks-${CONFIGURATION}-output-files.xcfilelist\",\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"\\\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate-reduxTemplateTests/Pods-reduxTemplate-reduxTemplateTests-frameworks.sh\\\"\\n\";\n\t\t\tshowEnvVarsInLog = 0;\n\t\t};\n\t\tE235C05ADACE081382539298 /* [CP] Copy Pods Resources */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputFileListPaths = (\n\t\t\t\t\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate/Pods-reduxTemplate-resources-${CONFIGURATION}-input-files.xcfilelist\",\n\t\t\t);\n\t\t\tname = \"[CP] Copy Pods Resources\";\n\t\t\toutputFileListPaths = (\n\t\t\t\t\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate/Pods-reduxTemplate-resources-${CONFIGURATION}-output-files.xcfilelist\",\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"\\\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate/Pods-reduxTemplate-resources.sh\\\"\\n\";\n\t\t\tshowEnvVarsInLog = 0;\n\t\t};\n\t\tF6A41C54EA430FDDC6A6ED99 /* [CP] Copy Pods Resources */ = {\n\t\t\tisa = PBXShellScriptBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t);\n\t\t\tinputFileListPaths = (\n\t\t\t\t\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate-reduxTemplateTests/Pods-reduxTemplate-reduxTemplateTests-resources-${CONFIGURATION}-input-files.xcfilelist\",\n\t\t\t);\n\t\t\tname = \"[CP] Copy Pods Resources\";\n\t\t\toutputFileListPaths = (\n\t\t\t\t\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate-reduxTemplateTests/Pods-reduxTemplate-reduxTemplateTests-resources-${CONFIGURATION}-output-files.xcfilelist\",\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t\tshellPath = /bin/sh;\n\t\t\tshellScript = \"\\\"${PODS_ROOT}/Target Support Files/Pods-reduxTemplate-reduxTemplateTests/Pods-reduxTemplate-reduxTemplateTests-resources.sh\\\"\\n\";\n\t\t\tshowEnvVarsInLog = 0;\n\t\t};\n/* End PBXShellScriptBuildPhase section */\n\n/* Begin PBXSourcesBuildPhase section */\n\t\t00E356EA1AD99517003FC87E /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t00E356F31AD99517003FC87E /* reduxTemplateTests.m in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n\t\t13B07F871A680F5B00A75B9A /* Sources */ = {\n\t\t\tisa = PBXSourcesBuildPhase;\n\t\t\tbuildActionMask = 2147483647;\n\t\t\tfiles = (\n\t\t\t\t13B07FBC1A68108700A75B9A /* AppDelegate.mm in Sources */,\n\t\t\t\t13B07FC11A68108700A75B9A /* main.m in Sources */,\n\t\t\t);\n\t\t\trunOnlyForDeploymentPostprocessing = 0;\n\t\t};\n/* End PBXSourcesBuildPhase section */\n\n/* Begin PBXTargetDependency section */\n\t\t00E356F51AD99517003FC87E /* PBXTargetDependency */ = {\n\t\t\tisa = PBXTargetDependency;\n\t\t\ttarget = 13B07F861A680F5B00A75B9A /* reduxTemplate */;\n\t\t\ttargetProxy = 00E356F41AD99517003FC87E /* PBXContainerItemProxy */;\n\t\t};\n/* End PBXTargetDependency section */\n\n/* Begin XCBuildConfiguration section */\n\t\t00E356F61AD99517003FC87E /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbaseConfigurationReference = 5B7EB9410499542E8C5724F5 /* Pods-reduxTemplate-reduxTemplateTests.debug.xcconfig */;\n\t\t\tbuildSettings = {\n\t\t\t\tBUNDLE_LOADER = \"$(TEST_HOST)\";\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n\t\t\t\t\t\"DEBUG=1\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tINFOPLIST_FILE = reduxTemplateTests/Info.plist;\n\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 15.1;\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"@executable_path/Frameworks\",\n\t\t\t\t\t\"@loader_path/Frameworks\",\n\t\t\t\t);\n\t\t\t\tOTHER_LDFLAGS = (\n\t\t\t\t\t\"-ObjC\",\n\t\t\t\t\t\"-lc++\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \"org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)\";\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t\tTEST_HOST = \"$(BUILT_PRODUCTS_DIR)/reduxTemplate.app/reduxTemplate\";\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t00E356F71AD99517003FC87E /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbaseConfigurationReference = 89C6BE57DB24E9ADA2F236DE /* Pods-reduxTemplate-reduxTemplateTests.release.xcconfig */;\n\t\t\tbuildSettings = {\n\t\t\t\tBUNDLE_LOADER = \"$(TEST_HOST)\";\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tINFOPLIST_FILE = reduxTemplateTests/Info.plist;\n\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 15.1;\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"@executable_path/Frameworks\",\n\t\t\t\t\t\"@loader_path/Frameworks\",\n\t\t\t\t);\n\t\t\t\tOTHER_LDFLAGS = (\n\t\t\t\t\t\"-ObjC\",\n\t\t\t\t\t\"-lc++\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \"org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)\";\n\t\t\t\tPRODUCT_NAME = \"$(TARGET_NAME)\";\n\t\t\t\tTEST_HOST = \"$(BUILT_PRODUCTS_DIR)/reduxTemplate.app/reduxTemplate\";\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t13B07F941A680F5B00A75B9A /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbaseConfigurationReference = 3B4392A12AC88292D35C810B /* Pods-reduxTemplate.debug.xcconfig */;\n\t\t\tbuildSettings = {\n\t\t\t\tASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCURRENT_PROJECT_VERSION = 1;\n\t\t\t\tENABLE_BITCODE = NO;\n\t\t\t\tINFOPLIST_FILE = reduxTemplate/Info.plist;\n\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 15.1;\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"@executable_path/Frameworks\",\n\t\t\t\t);\n\t\t\t\tMARKETING_VERSION = 1.0;\n\t\t\t\tOTHER_LDFLAGS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"-ObjC\",\n\t\t\t\t\t\"-lc++\",\n\t\t\t\t);\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \"org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)\";\n\t\t\t\tPRODUCT_NAME = reduxTemplate;\n\t\t\t\tSWIFT_OPTIMIZATION_LEVEL = \"-Onone\";\n\t\t\t\tSWIFT_VERSION = 5.0;\n\t\t\t\tVERSIONING_SYSTEM = \"apple-generic\";\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t13B07F951A680F5B00A75B9A /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbaseConfigurationReference = 5709B34CF0A7D63546082F79 /* Pods-reduxTemplate.release.xcconfig */;\n\t\t\tbuildSettings = {\n\t\t\t\tASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCURRENT_PROJECT_VERSION = 1;\n\t\t\t\tINFOPLIST_FILE = reduxTemplate/Info.plist;\n\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 15.1;\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"@executable_path/Frameworks\",\n\t\t\t\t);\n\t\t\t\tMARKETING_VERSION = 1.0;\n\t\t\t\tOTHER_LDFLAGS = (\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t\t\"-ObjC\",\n\t\t\t\t\t\"-lc++\",\n\t\t\t\t);\n\t\t\t\tPRODUCT_BUNDLE_IDENTIFIER = \"org.reactjs.native.example.$(PRODUCT_NAME:rfc1034identifier)\";\n\t\t\t\tPRODUCT_NAME = reduxTemplate;\n\t\t\t\tSWIFT_VERSION = 5.0;\n\t\t\t\tVERSIONING_SYSTEM = \"apple-generic\";\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n\t\t83CBBA201A601CBA00E9B192 /* Debug */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"c++20\";\n\t\t\t\tCLANG_CXX_LIBRARY = \"libc++\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_LITERAL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\t\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"iPhone Developer\";\n\t\t\t\tCOPY_PHASE_STRIP = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\tENABLE_TESTABILITY = YES;\n\t\t\t\t\"EXCLUDED_ARCHS[sdk=iphonesimulator*]\" = \"\";\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu99;\n\t\t\t\tGCC_DYNAMIC_NO_PIC = NO;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_OPTIMIZATION_LEVEL = 0;\n\t\t\t\tGCC_PREPROCESSOR_DEFINITIONS = (\n\t\t\t\t\t\"DEBUG=1\",\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tGCC_SYMBOLS_PRIVATE_EXTERN = NO;\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 15.1;\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (\n\t\t\t\t\t/usr/lib/swift,\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tLIBRARY_SEARCH_PATHS = (\n\t\t\t\t\t\"\\\"$(SDKROOT)/usr/lib/swift\\\"\",\n\t\t\t\t\t\"\\\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\\\"\",\n\t\t\t\t\t\"\\\"$(inherited)\\\"\",\n\t\t\t\t);\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = YES;\n\t\t\t\tONLY_ACTIVE_ARCH = YES;\n\t\t\t\tOTHER_CPLUSPLUSFLAGS = (\n\t\t\t\t\t\"$(OTHER_CFLAGS)\",\n\t\t\t\t\t\"-DFOLLY_NO_CONFIG\",\n\t\t\t\t\t\"-DFOLLY_MOBILE=1\",\n\t\t\t\t\t\"-DFOLLY_USE_LIBCPP=1\",\n\t\t\t\t\t\"-DFOLLY_CFG_NO_COROUTINES=1\",\n\t\t\t\t\t\"-DFOLLY_HAVE_CLOCK_GETTIME=1\",\n\t\t\t\t);\n\t\t\t\tSDKROOT = iphoneos;\n\t\t\t};\n\t\t\tname = Debug;\n\t\t};\n\t\t83CBBA211A601CBA00E9B192 /* Release */ = {\n\t\t\tisa = XCBuildConfiguration;\n\t\t\tbuildSettings = {\n\t\t\t\tALWAYS_SEARCH_USER_PATHS = NO;\n\t\t\t\tCLANG_ANALYZER_LOCALIZABILITY_NONLOCALIZED = YES;\n\t\t\t\tCLANG_CXX_LANGUAGE_STANDARD = \"c++20\";\n\t\t\t\tCLANG_CXX_LIBRARY = \"libc++\";\n\t\t\t\tCLANG_ENABLE_MODULES = YES;\n\t\t\t\tCLANG_ENABLE_OBJC_ARC = YES;\n\t\t\t\tCLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;\n\t\t\t\tCLANG_WARN_BOOL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_COMMA = YES;\n\t\t\t\tCLANG_WARN_CONSTANT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;\n\t\t\t\tCLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;\n\t\t\t\tCLANG_WARN_EMPTY_BODY = YES;\n\t\t\t\tCLANG_WARN_ENUM_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_INFINITE_RECURSION = YES;\n\t\t\t\tCLANG_WARN_INT_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;\n\t\t\t\tCLANG_WARN_OBJC_LITERAL_CONVERSION = YES;\n\t\t\t\tCLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;\n\t\t\t\tCLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;\n\t\t\t\tCLANG_WARN_RANGE_LOOP_ANALYSIS = YES;\n\t\t\t\tCLANG_WARN_STRICT_PROTOTYPES = YES;\n\t\t\t\tCLANG_WARN_SUSPICIOUS_MOVE = YES;\n\t\t\t\tCLANG_WARN_UNREACHABLE_CODE = YES;\n\t\t\t\tCLANG_WARN__DUPLICATE_METHOD_MATCH = YES;\n\t\t\t\t\"CODE_SIGN_IDENTITY[sdk=iphoneos*]\" = \"iPhone Developer\";\n\t\t\t\tCOPY_PHASE_STRIP = YES;\n\t\t\t\tENABLE_NS_ASSERTIONS = NO;\n\t\t\t\tENABLE_STRICT_OBJC_MSGSEND = YES;\n\t\t\t\t\"EXCLUDED_ARCHS[sdk=iphonesimulator*]\" = \"\";\n\t\t\t\tGCC_C_LANGUAGE_STANDARD = gnu99;\n\t\t\t\tGCC_NO_COMMON_BLOCKS = YES;\n\t\t\t\tGCC_WARN_64_TO_32_BIT_CONVERSION = YES;\n\t\t\t\tGCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;\n\t\t\t\tGCC_WARN_UNDECLARED_SELECTOR = YES;\n\t\t\t\tGCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;\n\t\t\t\tGCC_WARN_UNUSED_FUNCTION = YES;\n\t\t\t\tGCC_WARN_UNUSED_VARIABLE = YES;\n\t\t\t\tIPHONEOS_DEPLOYMENT_TARGET = 15.1;\n\t\t\t\tLD_RUNPATH_SEARCH_PATHS = (\n\t\t\t\t\t/usr/lib/swift,\n\t\t\t\t\t\"$(inherited)\",\n\t\t\t\t);\n\t\t\t\tLIBRARY_SEARCH_PATHS = (\n\t\t\t\t\t\"\\\"$(SDKROOT)/usr/lib/swift\\\"\",\n\t\t\t\t\t\"\\\"$(TOOLCHAIN_DIR)/usr/lib/swift/$(PLATFORM_NAME)\\\"\",\n\t\t\t\t\t\"\\\"$(inherited)\\\"\",\n\t\t\t\t);\n\t\t\t\tMTL_ENABLE_DEBUG_INFO = NO;\n\t\t\t\tOTHER_CPLUSPLUSFLAGS = (\n\t\t\t\t\t\"$(OTHER_CFLAGS)\",\n\t\t\t\t\t\"-DFOLLY_NO_CONFIG\",\n\t\t\t\t\t\"-DFOLLY_MOBILE=1\",\n\t\t\t\t\t\"-DFOLLY_USE_LIBCPP=1\",\n\t\t\t\t\t\"-DFOLLY_CFG_NO_COROUTINES=1\",\n\t\t\t\t\t\"-DFOLLY_HAVE_CLOCK_GETTIME=1\",\n\t\t\t\t);\n\t\t\t\tSDKROOT = iphoneos;\n\t\t\t\tVALIDATE_PRODUCT = YES;\n\t\t\t};\n\t\t\tname = Release;\n\t\t};\n/* End XCBuildConfiguration section */\n\n/* Begin XCConfigurationList section */\n\t\t00E357021AD99517003FC87E /* Build configuration list for PBXNativeTarget \"reduxTemplateTests\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t00E356F61AD99517003FC87E /* Debug */,\n\t\t\t\t00E356F71AD99517003FC87E /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t13B07F931A680F5B00A75B9A /* Build configuration list for PBXNativeTarget \"reduxTemplate\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t13B07F941A680F5B00A75B9A /* Debug */,\n\t\t\t\t13B07F951A680F5B00A75B9A /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n\t\t83CBB9FA1A601CBA00E9B192 /* Build configuration list for PBXProject \"reduxTemplate\" */ = {\n\t\t\tisa = XCConfigurationList;\n\t\t\tbuildConfigurations = (\n\t\t\t\t83CBBA201A601CBA00E9B192 /* Debug */,\n\t\t\t\t83CBBA211A601CBA00E9B192 /* Release */,\n\t\t\t);\n\t\t\tdefaultConfigurationIsVisible = 0;\n\t\t\tdefaultConfigurationName = Release;\n\t\t};\n/* End XCConfigurationList section */\n\t};\n\trootObject = 83CBB9F71A601CBA00E9B192 /* Project object */;\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplate.xcodeproj/xcshareddata/xcschemes/reduxTemplate.xcscheme",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<Scheme\n   LastUpgradeVersion = \"1210\"\n   version = \"1.3\">\n   <BuildAction\n      parallelizeBuildables = \"YES\"\n      buildImplicitDependencies = \"YES\">\n      <BuildActionEntries>\n         <BuildActionEntry\n            buildForTesting = \"YES\"\n            buildForRunning = \"YES\"\n            buildForProfiling = \"YES\"\n            buildForArchiving = \"YES\"\n            buildForAnalyzing = \"YES\">\n            <BuildableReference\n               BuildableIdentifier = \"primary\"\n               BlueprintIdentifier = \"13B07F861A680F5B00A75B9A\"\n               BuildableName = \"reduxTemplate.app\"\n               BlueprintName = \"reduxTemplate\"\n               ReferencedContainer = \"container:reduxTemplate.xcodeproj\">\n            </BuildableReference>\n         </BuildActionEntry>\n      </BuildActionEntries>\n   </BuildAction>\n   <TestAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\">\n      <Testables>\n         <TestableReference\n            skipped = \"NO\">\n            <BuildableReference\n               BuildableIdentifier = \"primary\"\n               BlueprintIdentifier = \"00E356ED1AD99517003FC87E\"\n               BuildableName = \"reduxTemplateTests.xctest\"\n               BlueprintName = \"reduxTemplateTests\"\n               ReferencedContainer = \"container:reduxTemplate.xcodeproj\">\n            </BuildableReference>\n         </TestableReference>\n      </Testables>\n   </TestAction>\n   <LaunchAction\n      buildConfiguration = \"Debug\"\n      selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"\n      selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"\n      launchStyle = \"0\"\n      useCustomWorkingDirectory = \"NO\"\n      ignoresPersistentStateOnLaunch = \"NO\"\n      debugDocumentVersioning = \"YES\"\n      debugServiceExtension = \"internal\"\n      allowLocationSimulation = \"YES\">\n      <BuildableProductRunnable\n         runnableDebuggingMode = \"0\">\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"13B07F861A680F5B00A75B9A\"\n            BuildableName = \"reduxTemplate.app\"\n            BlueprintName = \"reduxTemplate\"\n            ReferencedContainer = \"container:reduxTemplate.xcodeproj\">\n         </BuildableReference>\n      </BuildableProductRunnable>\n   </LaunchAction>\n   <ProfileAction\n      buildConfiguration = \"Release\"\n      shouldUseLaunchSchemeArgsEnv = \"YES\"\n      savedToolIdentifier = \"\"\n      useCustomWorkingDirectory = \"NO\"\n      debugDocumentVersioning = \"YES\">\n      <BuildableProductRunnable\n         runnableDebuggingMode = \"0\">\n         <BuildableReference\n            BuildableIdentifier = \"primary\"\n            BlueprintIdentifier = \"13B07F861A680F5B00A75B9A\"\n            BuildableName = \"reduxTemplate.app\"\n            BlueprintName = \"reduxTemplate\"\n            ReferencedContainer = \"container:reduxTemplate.xcodeproj\">\n         </BuildableReference>\n      </BuildableProductRunnable>\n   </ProfileAction>\n   <AnalyzeAction\n      buildConfiguration = \"Debug\">\n   </AnalyzeAction>\n   <ArchiveAction\n      buildConfiguration = \"Release\"\n      revealArchiveInOrganizer = \"YES\">\n   </ArchiveAction>\n</Scheme>\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplateTests/Info.plist",
    "content": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n<dict>\n\t<key>CFBundleDevelopmentRegion</key>\n\t<string>en</string>\n\t<key>CFBundleExecutable</key>\n\t<string>$(EXECUTABLE_NAME)</string>\n\t<key>CFBundleIdentifier</key>\n\t<string>$(PRODUCT_BUNDLE_IDENTIFIER)</string>\n\t<key>CFBundleInfoDictionaryVersion</key>\n\t<string>6.0</string>\n\t<key>CFBundleName</key>\n\t<string>$(PRODUCT_NAME)</string>\n\t<key>CFBundlePackageType</key>\n\t<string>BNDL</string>\n\t<key>CFBundleShortVersionString</key>\n\t<string>1.0</string>\n\t<key>CFBundleSignature</key>\n\t<string>????</string>\n\t<key>CFBundleVersion</key>\n\t<string>1</string>\n</dict>\n</plist>\n"
  },
  {
    "path": "examples/publish-ci/react-native/ios/reduxTemplateTests/reduxTemplateTests.m",
    "content": "#import <UIKit/UIKit.h>\n#import <XCTest/XCTest.h>\n\n#import <React/RCTLog.h>\n#import <React/RCTRootView.h>\n\n#define TIMEOUT_SECONDS 600\n#define TEXT_TO_LOOK_FOR @\"Welcome to React\"\n\n@interface reduxTemplateTests : XCTestCase\n\n@end\n\n@implementation reduxTemplateTests\n\n- (BOOL)findSubviewInView:(UIView *)view matching:(BOOL (^)(UIView *view))test\n{\n  if (test(view)) {\n    return YES;\n  }\n  for (UIView *subview in [view subviews]) {\n    if ([self findSubviewInView:subview matching:test]) {\n      return YES;\n    }\n  }\n  return NO;\n}\n\n- (void)testRendersWelcomeScreen\n{\n  UIViewController *vc = [[[RCTSharedApplication() delegate] window] rootViewController];\n  NSDate *date = [NSDate dateWithTimeIntervalSinceNow:TIMEOUT_SECONDS];\n  BOOL foundElement = NO;\n\n  __block NSString *redboxError = nil;\n#ifdef DEBUG\n  RCTSetLogFunction(\n      ^(RCTLogLevel level, RCTLogSource source, NSString *fileName, NSNumber *lineNumber, NSString *message) {\n        if (level >= RCTLogLevelError) {\n          redboxError = message;\n        }\n      });\n#endif\n\n  while ([date timeIntervalSinceNow] > 0 && !foundElement && !redboxError) {\n    [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];\n    [[NSRunLoop mainRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];\n\n    foundElement = [self findSubviewInView:vc.view\n                                  matching:^BOOL(UIView *view) {\n                                    if ([view.accessibilityLabel isEqualToString:TEXT_TO_LOOK_FOR]) {\n                                      return YES;\n                                    }\n                                    return NO;\n                                  }];\n  }\n\n#ifdef DEBUG\n  RCTSetLogFunction(RCTDefaultLogFunction);\n#endif\n\n  XCTAssertNil(redboxError, @\"RedBox error: %@\", redboxError);\n  XCTAssertTrue(foundElement, @\"Couldn't find element with text '%@' in %d seconds\", TEXT_TO_LOOK_FOR, TIMEOUT_SECONDS);\n}\n\n@end\n"
  },
  {
    "path": "examples/publish-ci/react-native/jest-setup.ts",
    "content": "import '@testing-library/react-native'\n"
  },
  {
    "path": "examples/publish-ci/react-native/jest.config.ts",
    "content": "import type { Config } from 'jest'\n\nconst config: Config = {\n  preset: 'react-native',\n  verbose: true,\n  /**\n   * Without this we will get the following error:\n   * `SyntaxError: Cannot use import statement outside a module`\n   */\n  transformIgnorePatterns: [\n    'node_modules/(?!((jest-)?react-native|...|react-redux))',\n  ],\n  /**\n   * React Native's `jest` preset includes a\n   * [polyfill for `window`](https://github.com/facebook/react-native/blob/acb634bc9662c1103bc7c8ca83cfdc62516d0060/packages/react-native/jest/setup.js#L61-L66).\n   * This polyfill causes React-Redux to use `useEffect`\n   * instead of `useLayoutEffect` for the `useIsomorphicLayoutEffect` hook.\n   * As a result, nested component updates may not be properly batched\n   * when using the `connect` API, leading to potential issues.\n   */\n  globals: {\n    window: undefined,\n    navigator: {\n      product: 'ReactNative',\n    },\n  },\n  setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],\n  fakeTimers: {\n    enableGlobally: true,\n    advanceTimers: true,\n  },\n}\n\nexport default config\n"
  },
  {
    "path": "examples/publish-ci/react-native/metro.config.js",
    "content": "const { getDefaultConfig, mergeConfig } = require('@react-native/metro-config')\n\n/**\n * Metro configuration\n * @see {@link https://reactnative.dev/docs/metro | React Native docs}\n * @see {@link https://facebook.github.io/metro/docs/configuration | Metro docs}\n *\n * @type {import('@react-native/metro-config').MetroConfig}\n */\nconst config = mergeConfig(getDefaultConfig(__dirname))\n\nmodule.exports = config\n"
  },
  {
    "path": "examples/publish-ci/react-native/package.json",
    "content": "{\n  \"name\": \"react-native-template-redux-typescript\",\n  \"version\": \"0.0.1\",\n  \"private\": true,\n  \"scripts\": {\n    \"android\": \"react-native run-android\",\n    \"build\": \"react-native bundle --entry-file index.js --bundle-output build/bundle.js --platform android --assets-dest build/assets\",\n    \"format:check\": \"prettier --check .\",\n    \"format\": \"prettier --write .\",\n    \"ios\": \"react-native run-ios\",\n    \"lint:fix\": \"eslint --fix .\",\n    \"lint\": \"eslint .\",\n    \"start\": \"react-native start\",\n    \"test\": \"jest\",\n    \"type-check\": \"tsc --noEmit\"\n  },\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^2.7.0\",\n    \"react\": \"19.0.0\",\n    \"react-native\": \"^0.79.2\",\n    \"react-redux\": \"^9.2.0\"\n  },\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.27.1\",\n    \"@babel/preset-env\": \"^7.27.1\",\n    \"@babel/runtime\": \"^7.27.1\",\n    \"@eslint/js\": \"^9.26.0\",\n    \"@react-native-community/cli\": \"^18.0.0\",\n    \"@react-native-community/cli-platform-android\": \"^18.0.0\",\n    \"@react-native-community/cli-platform-ios\": \"^18.0.0\",\n    \"@react-native/babel-preset\": \"^0.79.2\",\n    \"@react-native/metro-config\": \"^0.79.2\",\n    \"@react-native/typescript-config\": \"^0.79.2\",\n    \"@testing-library/react-native\": \"^13.2.0\",\n    \"@types/babel__core\": \"^7.20.5\",\n    \"@types/jest\": \"^29.5.14\",\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^19.1.2\",\n    \"@types/react-test-renderer\": \"^19.1.0\",\n    \"babel-jest\": \"^29.7.0\",\n    \"eslint\": \"^9.26.0\",\n    \"eslint-config-prettier\": \"^10.1.2\",\n    \"eslint-plugin-jest\": \"^28.11.0\",\n    \"eslint-plugin-react\": \"^7.37.5\",\n    \"eslint-plugin-react-hooks\": \"^5.2.0\",\n    \"globals\": \"^16.0.0\",\n    \"jest\": \"^29.7.0\",\n    \"prettier\": \"^3.5.3\",\n    \"react-test-renderer\": \"19.0.0\",\n    \"ts-node\": \"^10.9.2\",\n    \"typescript\": \"^5.9.3\",\n    \"typescript-eslint\": \"^8.31.1\"\n  },\n  \"engines\": {\n    \"node\": \">=18\"\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/react-native.config.mjs",
    "content": "/** @type {import('@react-native-community/cli-types').UserConfig} */\nconst config = {\n  project: {\n    ios: {\n      automaticPodsInstallation: true,\n    },\n  },\n}\n\nexport default config\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/app/createAppSlice.ts",
    "content": "import { asyncThunkCreator, buildCreateSlice } from '@reduxjs/toolkit'\n\n// `buildCreateSlice` allows us to create a slice with async thunks.\nexport const createAppSlice = buildCreateSlice({\n  creators: { asyncThunk: asyncThunkCreator },\n})\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/app/hooks.ts",
    "content": "// This file serves as a central hub for re-exporting pre-typed Redux hooks.\n// These imports are restricted elsewhere to ensure consistent\n// usage of typed hooks throughout the application.\n// We disable the ESLint rule here because this is the designated place\n// for importing and re-exporting the typed versions of hooks.\n/* eslint-disable no-restricted-imports */\nimport { useEffect } from 'react'\nimport { Animated, useAnimatedValue, useWindowDimensions } from 'react-native'\nimport { useDispatch, useSelector } from 'react-redux'\nimport type { AppDispatch, RootState } from './store'\n\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = useDispatch.withTypes<AppDispatch>()\nexport const useAppSelector = useSelector.withTypes<RootState>()\n\n/**\n * Custom React hook for calculating viewport units\n * based on the current window dimensions.\n *\n * @returns An object containing the calculated viewport heigh and width values.\n */\nexport const useViewportUnits = (): { vh: number; vw: number } => {\n  const { width, height } = useWindowDimensions()\n\n  const vh = height / 100\n  const vw = width / 100\n\n  return { vh, vw }\n}\n\n/**\n * Custom React hook for creating a bounce animation effect.\n *\n * @param value - The maximum height to which the object should bounce. Defaults to 10 if not provided.\n * @returns The {@linkcode Animated.Value} object that can be used to drive animations.\n */\nexport const useBounceAnimation = (value = 10): Animated.Value => {\n  const bounce = useAnimatedValue(0)\n\n  bounce.interpolate({\n    inputRange: [-300, -100, 0, 100, 101],\n    outputRange: [300, 0, 1, 0, 0],\n  })\n\n  useEffect(() => {\n    Animated.loop(\n      Animated.sequence([\n        Animated.timing(bounce, {\n          toValue: value,\n          duration: 1500,\n          useNativeDriver: true,\n        }),\n        Animated.timing(bounce, {\n          toValue: 0,\n          duration: 1500,\n          useNativeDriver: true,\n        }),\n      ]),\n    ).start()\n  }, [bounce, value])\n\n  return bounce\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/app/store.ts",
    "content": "import type { Action, ThunkAction } from '@reduxjs/toolkit'\nimport { combineSlices, configureStore } from '@reduxjs/toolkit'\nimport { setupListeners } from '@reduxjs/toolkit/query'\nimport { counterSlice } from '../features/counter/counterSlice'\nimport { quotesApiSlice } from '../features/quotes/quotesApiSlice'\n\n// `combineSlices` automatically combines the reducers using\n// their `reducerPath`s, therefore we no longer need to call `combineReducers`.\nconst rootReducer = combineSlices(counterSlice, quotesApiSlice)\n// Infer the `RootState` type from the root reducer\nexport type RootState = ReturnType<typeof rootReducer>\n\n// The store setup is wrapped in `makeStore` to allow reuse\n// when setting up tests that need the same store config\nexport const makeStore = (preloadedState?: Partial<RootState>) => {\n  const store = configureStore({\n    reducer: rootReducer,\n    // Adding the api middleware enables caching, invalidation, polling,\n    // and other useful features of `rtk-query`.\n    middleware: getDefaultMiddleware => {\n      return getDefaultMiddleware().concat(quotesApiSlice.middleware)\n    },\n    preloadedState,\n  })\n  // configure listeners using the provided defaults\n  // optional, but required for `refetchOnFocus`/`refetchOnReconnect` behaviors\n  setupListeners(store.dispatch)\n  return store\n}\n\nexport const store = makeStore()\n\n// Infer the type of `store`\nexport type AppStore = typeof store\n// Infer the `AppDispatch` type from the store itself\nexport type AppDispatch = AppStore['dispatch']\nexport type AppThunk<ThunkReturnType = void> = ThunkAction<\n  ThunkReturnType,\n  RootState,\n  unknown,\n  Action\n>\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/components/AsyncButton.tsx",
    "content": "import type { JSX, PropsWithChildren } from 'react'\nimport type {\n  GestureResponderEvent,\n  PressableProps,\n  ViewStyle,\n} from 'react-native'\nimport {\n  Animated,\n  Pressable,\n  StyleSheet,\n  View,\n  useAnimatedValue,\n} from 'react-native'\n\ntype AsyncButtonProps = PressableProps & PropsWithChildren\n\nexport const AsyncButton = ({\n  onPress,\n  style,\n  children,\n  ...restProps\n}: AsyncButtonProps): JSX.Element => {\n  const progress = useAnimatedValue(0)\n  const opacity = useAnimatedValue(1)\n\n  const _onPress = (e: GestureResponderEvent) => {\n    progress.setValue(0)\n    opacity.setValue(1)\n\n    onPress?.(e)\n\n    Animated.timing(progress, {\n      toValue: 1,\n      duration: 1000,\n      useNativeDriver: false,\n    }).start(({ finished }) => {\n      if (!finished) {\n        return\n      }\n\n      Animated.timing(opacity, {\n        toValue: 0,\n        duration: 200,\n        useNativeDriver: false,\n      }).start()\n    })\n  }\n\n  const progressInterpolate = progress.interpolate({\n    inputRange: [0, 1],\n    outputRange: ['0%', '100%'],\n    extrapolate: 'clamp',\n  })\n\n  const progressStyle: Animated.WithAnimatedObject<ViewStyle> = {\n    width: progressInterpolate,\n    opacity,\n  }\n\n  return (\n    <Pressable style={style} onPress={_onPress} {...restProps}>\n      <View style={StyleSheet.absoluteFill}>\n        <Animated.View style={[styles.progress, progressStyle]} />\n      </View>\n      {children}\n    </Pressable>\n  )\n}\n\nconst styles = StyleSheet.create({\n  progress: {\n    position: 'absolute',\n    top: 0,\n    bottom: 0,\n    left: 0,\n    backgroundColor: 'rgba(112,76,182, 0.15)',\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/components/Header.tsx",
    "content": "import type { JSX } from 'react'\nimport { Animated, StyleSheet, View, useColorScheme } from 'react-native'\nimport { useBounceAnimation, useViewportUnits } from '../app/hooks'\nimport { TypedColors } from '../constants/TypedColors'\nimport logo from './logo.gif'\n\nexport const Header = (): JSX.Element => {\n  const isDarkMode = useColorScheme() === 'dark'\n  const { vh } = useViewportUnits()\n  const bounce = useBounceAnimation()\n  const height = 40 * vh\n\n  return (\n    <View\n      style={[\n        styles.container,\n        { backgroundColor: isDarkMode ? TypedColors.black : TypedColors.white },\n      ]}\n    >\n      <Animated.Image\n        accessibilityRole=\"image\"\n        source={logo}\n        style={{ height, transform: [{ translateY: bounce }] }}\n      />\n    </View>\n  )\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flexDirection: 'row',\n    justifyContent: 'center',\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/components/LearnReduxLinks.tsx",
    "content": "import type { JSX } from 'react'\nimport { Fragment } from 'react'\nimport {\n  StyleSheet,\n  Text,\n  TouchableOpacity,\n  View,\n  useColorScheme,\n} from 'react-native'\nimport openURLInBrowser from 'react-native/Libraries/Core/Devtools/openURLInBrowser'\nimport { TypedColors } from '../constants/TypedColors'\n\ntype Link = {\n  title: string\n  link: string\n  description: string\n}\n\nconst links: Link[] = [\n  {\n    title: 'React',\n    link: 'https://reactjs.org',\n    description: 'JavaScript library for building user interfaces',\n  },\n  {\n    title: 'Redux',\n    link: 'https://redux.js.org',\n    description: 'A Predictable State Container for JS Apps',\n  },\n  {\n    title: 'Redux Toolkit',\n    link: 'https://redux-toolkit.js.org',\n    description:\n      'The official, opinionated, batteries-included toolset for efficient Redux development',\n  },\n  {\n    title: 'React Redux',\n    link: 'https://react-redux.js.org',\n    description: 'Official React bindings for Redux',\n  },\n  {\n    title: 'Reselect',\n    link: 'https://reselect.js.org',\n    description: 'A memoized selector library for Redux',\n  },\n]\n\nexport const LearnReduxLinks = (): JSX.Element => {\n  const isDarkMode = useColorScheme() === 'dark'\n\n  return (\n    <View style={styles.container}>\n      {links.map((item, index) => {\n        return (\n          <Fragment key={index}>\n            <View\n              style={[\n                styles.separator,\n                {\n                  backgroundColor: isDarkMode\n                    ? TypedColors.dark\n                    : TypedColors.light,\n                },\n              ]}\n            />\n            <TouchableOpacity\n              accessibilityRole=\"button\"\n              onPress={() => {\n                openURLInBrowser(item.link)\n              }}\n              style={styles.linkContainer}\n            >\n              <Text style={styles.link}>{item.title}</Text>\n              <Text\n                style={[\n                  styles.description,\n                  { color: isDarkMode ? TypedColors.light : TypedColors.dark },\n                ]}\n              >\n                {item.description}\n              </Text>\n            </TouchableOpacity>\n          </Fragment>\n        )\n      })}\n    </View>\n  )\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    marginTop: 32,\n    paddingHorizontal: 24,\n  },\n  linkContainer: {\n    flexWrap: 'wrap',\n    flexDirection: 'row',\n    justifyContent: 'space-between',\n    alignItems: 'center',\n    paddingVertical: 8,\n  },\n  link: {\n    flex: 2,\n    fontSize: 18,\n    fontWeight: '400',\n    color: TypedColors.primary,\n  },\n  description: {\n    flex: 3,\n    paddingVertical: 16,\n    fontWeight: '400',\n    fontSize: 18,\n  },\n  separator: {\n    height: 1,\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/components/Section.tsx",
    "content": "import type { JSX, PropsWithChildren } from 'react'\nimport { StyleSheet, Text, View, useColorScheme } from 'react-native'\nimport { TypedColors } from '../constants/TypedColors'\n\ntype SectionProps = PropsWithChildren<{\n  title: string\n}>\n\nexport const Section = ({ children, title }: SectionProps): JSX.Element => {\n  const isDarkMode = useColorScheme() === 'dark'\n\n  return (\n    <View style={styles.sectionContainer}>\n      <Text\n        style={[\n          styles.sectionTitle,\n          { color: isDarkMode ? TypedColors.white : TypedColors.black },\n        ]}\n      >\n        {title}\n      </Text>\n      <Text\n        style={[\n          styles.sectionDescription,\n          { color: isDarkMode ? TypedColors.light : TypedColors.dark },\n        ]}\n      >\n        {children}\n      </Text>\n    </View>\n  )\n}\n\nconst styles = StyleSheet.create({\n  sectionContainer: {\n    marginTop: 32,\n    paddingHorizontal: 24,\n  },\n  sectionTitle: {\n    fontSize: 24,\n    fontWeight: '600',\n  },\n  sectionDescription: {\n    marginTop: 8,\n    fontSize: 18,\n    fontWeight: '400',\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/constants/TypedColors.ts",
    "content": "import { Colors } from 'react-native/Libraries/NewAppScreen'\n\ntype AllColors = {\n  primary: string\n  white: string\n  lighter: string\n  light: string\n  dark: string\n  darker: string\n  black: string\n}\n\nexport const TypedColors: AllColors = Colors satisfies AllColors as AllColors\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/features/counter/Counter.tsx",
    "content": "import type { JSX } from 'react'\nimport { useState } from 'react'\nimport {\n  StyleSheet,\n  Text,\n  TextInput,\n  TouchableOpacity,\n  View,\n  useColorScheme,\n} from 'react-native'\nimport { useAppDispatch, useAppSelector } from '../../app/hooks'\nimport { AsyncButton } from '../../components/AsyncButton'\nimport { TypedColors } from '../../constants/TypedColors'\nimport {\n  decrement,\n  increment,\n  incrementAsync,\n  incrementByAmount,\n  incrementIfOdd,\n  selectCount,\n  selectStatus,\n} from './counterSlice'\n\nexport const Counter = (): JSX.Element => {\n  const isDarkMode = useColorScheme() === 'dark'\n  const textStyle = {\n    color: isDarkMode ? TypedColors.light : TypedColors.dark,\n  }\n\n  const dispatch = useAppDispatch()\n  const count = useAppSelector(selectCount)\n  const status = useAppSelector(selectStatus)\n  const [incrementAmount, setIncrementAmount] = useState('2')\n\n  const incrementValue = Number(incrementAmount) || 0\n\n  return (\n    <View>\n      <View style={styles.row}>\n        <TouchableOpacity\n          style={styles.button}\n          aria-label=\"Decrement value\"\n          onPress={() => dispatch(decrement())}\n        >\n          <Text style={styles.buttonText}>-</Text>\n        </TouchableOpacity>\n        <Text aria-label=\"Count\" style={[styles.value, textStyle]}>\n          {count}\n        </Text>\n        <TouchableOpacity\n          style={styles.button}\n          aria-label=\"Increment value\"\n          onPress={() => dispatch(increment())}\n        >\n          <Text style={styles.buttonText}>+</Text>\n        </TouchableOpacity>\n      </View>\n      <View style={styles.row}>\n        <TextInput\n          aria-label=\"Set increment amount\"\n          style={[styles.textbox, textStyle]}\n          value={incrementAmount}\n          keyboardType=\"numeric\"\n          onChangeText={setIncrementAmount}\n        />\n        <View>\n          <TouchableOpacity\n            style={styles.button}\n            onPress={() => dispatch(incrementByAmount(incrementValue))}\n          >\n            <Text style={styles.buttonText}>Add Amount</Text>\n          </TouchableOpacity>\n          <AsyncButton\n            aria-label=\"Async Button\"\n            style={styles.button}\n            disabled={status !== 'idle'}\n            onPress={() => {\n              void dispatch(incrementAsync(incrementValue))\n            }}\n          >\n            <Text style={styles.buttonText}>Add Async</Text>\n          </AsyncButton>\n          <TouchableOpacity\n            style={styles.button}\n            onPress={() => {\n              dispatch(incrementIfOdd(incrementValue))\n            }}\n          >\n            <Text style={styles.buttonText}>Add If Odd</Text>\n          </TouchableOpacity>\n        </View>\n      </View>\n    </View>\n  )\n}\n\nconst styles = StyleSheet.create({\n  row: {\n    flexDirection: 'row',\n    alignItems: 'center',\n    justifyContent: 'center',\n    flexWrap: 'wrap',\n  },\n  value: {\n    fontSize: 78,\n    paddingHorizontal: 16,\n    marginTop: 2,\n  },\n  button: {\n    backgroundColor: 'rgba(112, 76, 182, 0.1)',\n    borderRadius: 2,\n    paddingLeft: 12,\n    paddingRight: 12,\n    paddingBottom: 4,\n    margin: 2,\n  },\n  buttonText: {\n    color: 'rgb(112, 76, 182)',\n    fontSize: 32,\n    textAlign: 'center',\n  },\n  textbox: {\n    fontSize: 48,\n    padding: 2,\n    width: 64,\n    textAlign: 'center',\n    marginRight: 8,\n    borderWidth: 1,\n    justifyContent: 'center',\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/features/counter/counterAPI.ts",
    "content": "// A mock function to mimic making an async request for data\nexport const fetchCount = (amount = 1): Promise<{ data: number }> =>\n  new Promise<{ data: number }>(resolve =>\n    setTimeout(() => {\n      resolve({ data: amount })\n    }, 500),\n  )\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/features/counter/counterSlice.test.ts",
    "content": "import { makeStore } from '../../app/store'\nimport type { CounterSliceState } from './counterSlice'\nimport {\n  counterSlice,\n  decrement,\n  increment,\n  incrementByAmount,\n  selectCount,\n} from './counterSlice'\n\ndescribe('counter reducer', () => {\n  const initialState: CounterSliceState = {\n    value: 3,\n    status: 'idle',\n  }\n\n  let store = makeStore()\n\n  beforeEach(() => {\n    store = makeStore({ counter: initialState })\n  })\n\n  it('should handle initial state', () => {\n    expect(counterSlice.reducer(undefined, { type: 'unknown' })).toStrictEqual({\n      value: 0,\n      status: 'idle',\n    })\n  })\n\n  it('should handle increment', () => {\n    expect(selectCount(store.getState())).toBe(3)\n\n    store.dispatch(increment())\n\n    expect(selectCount(store.getState())).toBe(4)\n  })\n\n  it('should handle decrement', () => {\n    expect(selectCount(store.getState())).toBe(3)\n\n    store.dispatch(decrement())\n\n    expect(selectCount(store.getState())).toBe(2)\n  })\n\n  it('should handle incrementByAmount', () => {\n    expect(selectCount(store.getState())).toBe(3)\n\n    store.dispatch(incrementByAmount(2))\n\n    expect(selectCount(store.getState())).toBe(5)\n  })\n})\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/features/counter/counterSlice.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit'\nimport { createAppSlice } from '../../app/createAppSlice'\nimport type { AppThunk } from '../../app/store'\nimport { fetchCount } from './counterAPI'\n\nexport type CounterSliceState = {\n  value: number\n  status: 'idle' | 'loading' | 'failed'\n}\n\nconst initialState: CounterSliceState = {\n  value: 0,\n  status: 'idle',\n}\n\n// If you are not using async thunks you can use the standalone `createSlice`.\nexport const counterSlice = createAppSlice({\n  name: 'counter',\n  // `createSlice` will infer the state type from the `initialState` argument\n  initialState,\n  // The `reducers` field lets us define reducers and generate associated actions\n  reducers: create => ({\n    increment: create.reducer(state => {\n      // Redux Toolkit allows us to write \"mutating\" logic in reducers. It\n      // doesn't actually mutate the state because it uses the Immer library,\n      // which detects changes to a \"draft state\" and produces a brand new\n      // immutable state based off those changes\n      state.value += 1\n    }),\n    decrement: create.reducer(state => {\n      state.value -= 1\n    }),\n    // Use the `PayloadAction` type to declare the contents of `action.payload`\n    incrementByAmount: create.reducer(\n      (state, action: PayloadAction<number>) => {\n        state.value += action.payload\n      },\n    ),\n    // The function below is called a thunk and allows us to perform async logic. It\n    // can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This\n    // will call the thunk with the `dispatch` function as the first argument. Async\n    // code can then be executed and other actions can be dispatched. Thunks are\n    // typically used to make async requests.\n    incrementAsync: create.asyncThunk(\n      async (amount: number) => {\n        const response = await fetchCount(amount)\n        // The value we return becomes the `fulfilled` action payload\n        return response.data\n      },\n      {\n        pending: state => {\n          state.status = 'loading'\n        },\n        fulfilled: (state, action) => {\n          state.status = 'idle'\n          state.value += action.payload\n        },\n        rejected: state => {\n          state.status = 'failed'\n        },\n      },\n    ),\n  }),\n  // You can define your selectors here. These selectors receive the slice\n  // state as their first argument.\n  selectors: {\n    selectCount: counter => counter.value,\n    selectStatus: counter => counter.status,\n  },\n})\n\n// Action creators are generated for each case reducer function.\nexport const { decrement, increment, incrementByAmount, incrementAsync } =\n  counterSlice.actions\n\n// Selectors returned by `slice.selectors` take the root state as their first argument.\nexport const { selectCount, selectStatus } = counterSlice.selectors\n\n// We can also write thunks by hand, which may contain both sync and async logic.\n// Here's an example of conditionally dispatching actions based on current state.\nexport const incrementIfOdd =\n  (amount: number): AppThunk =>\n  (dispatch, getState) => {\n    const currentValue = selectCount(getState())\n\n    if (currentValue % 2 === 1 || currentValue % 2 === -1) {\n      dispatch(incrementByAmount(amount))\n    }\n  }\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/features/quotes/Quotes.tsx",
    "content": "import type { JSX } from 'react'\nimport { useState } from 'react'\nimport {\n  Modal,\n  ScrollView,\n  StyleSheet,\n  Text,\n  TouchableOpacity,\n  View,\n  useColorScheme,\n} from 'react-native'\nimport { TypedColors } from '../../constants/TypedColors'\nimport { useGetQuotesQuery } from './quotesApiSlice'\n\nconst options = [5, 10, 20, 30]\n\nexport const Quotes = (): JSX.Element | null => {\n  const isDarkMode = useColorScheme() === 'dark'\n  const textStyle = {\n    color: isDarkMode ? TypedColors.light : TypedColors.dark,\n  }\n  const backgroundStyle = {\n    backgroundColor: isDarkMode ? TypedColors.darker : TypedColors.lighter,\n  }\n\n  const [numberOfQuotes, setNumberOfQuotes] = useState(10)\n  const [modalVisible, setModalVisible] = useState(false)\n  // Using a query hook automatically fetches data and returns query values\n  const { data, isError, isLoading, isSuccess } =\n    useGetQuotesQuery(numberOfQuotes)\n\n  if (isError) {\n    return <Text>There was an error!!!</Text>\n  }\n\n  if (isLoading) {\n    return <Text>Loading...</Text>\n  }\n\n  const pickNumberOfQuotes = (value: number) => {\n    setNumberOfQuotes(value)\n    setModalVisible(false)\n  }\n\n  if (isSuccess) {\n    return (\n      <View style={styles.container}>\n        <TouchableOpacity\n          onPress={() => {\n            setModalVisible(true)\n          }}\n          style={styles.button}\n        >\n          <Text style={styles.buttonText}>\n            Select the Quantity of Quotes to Fetch: {numberOfQuotes}\n          </Text>\n        </TouchableOpacity>\n\n        <Modal\n          animationType=\"slide\"\n          transparent={true}\n          visible={modalVisible}\n          style={backgroundStyle}\n          onRequestClose={() => {\n            setModalVisible(false)\n          }}\n        >\n          <View style={[styles.modalView, backgroundStyle]}>\n            <ScrollView style={styles.quotesList}>\n              {options.map(option => (\n                <TouchableOpacity\n                  key={option}\n                  style={styles.option}\n                  onPress={() => {\n                    pickNumberOfQuotes(option)\n                  }}\n                >\n                  <Text style={[styles.optionText, textStyle]}>{option}</Text>\n                </TouchableOpacity>\n              ))}\n            </ScrollView>\n          </View>\n        </Modal>\n\n        {\n          <ScrollView>\n            {data.quotes.map(({ author, quote, id }) => (\n              <View key={id} style={[styles.quoteContainer, backgroundStyle]}>\n                <Text\n                  style={[styles.quoteText, textStyle]}\n                >{`\"${quote}\"`}</Text>\n                <Text style={[styles.author, textStyle]}>- {author}</Text>\n              </View>\n            ))}\n          </ScrollView>\n        }\n      </View>\n    )\n  }\n\n  return null\n}\n\nconst styles = StyleSheet.create({\n  container: {\n    flex: 1,\n    alignItems: 'center',\n    justifyContent: 'center',\n    padding: 20,\n  },\n  button: {\n    padding: 10,\n    backgroundColor: 'rgba(112, 76, 182, 0.1)',\n    borderRadius: 5,\n  },\n  buttonText: {\n    color: 'rgb(112, 76, 182)',\n    fontSize: 18,\n    textAlign: 'center',\n    margin: 5,\n  },\n  modalView: {\n    margin: 20,\n    borderRadius: 5,\n    padding: 20,\n    alignItems: 'center',\n    elevation: 5,\n  },\n  option: {\n    fontSize: 30,\n    padding: 10,\n    borderBottomWidth: 1,\n    borderBottomColor: '#CCC',\n  },\n  optionText: {\n    fontSize: 20,\n  },\n  quotesList: {\n    width: 'auto',\n  },\n  quoteContainer: {\n    padding: 10,\n    borderRadius: 5,\n    marginVertical: 5,\n  },\n  quoteText: {\n    fontStyle: 'italic',\n  },\n  author: {\n    fontWeight: 'bold',\n    textAlign: 'right',\n    marginTop: 5,\n  },\n})\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/features/quotes/quotesApiSlice.ts",
    "content": "// Need to use the React-specific entry point to import `createApi`\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ntype Quote = {\n  id: number\n  quote: string\n  author: string\n}\n\ntype QuotesApiResponse = {\n  quotes: Quote[]\n  total: number\n  skip: number\n  limit: number\n}\n\n// Define a service using a base URL and expected endpoints\nexport const quotesApiSlice = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/quotes' }),\n  reducerPath: 'quotesApi',\n  // Tag types are used for caching and invalidation.\n  tagTypes: ['Quotes'],\n  endpoints: build => ({\n    // Supply generics for the return type (in this case `QuotesApiResponse`)\n    // and the expected query argument. If there is no argument, use `void`\n    // for the argument type instead.\n    getQuotes: build.query<QuotesApiResponse, number>({\n      query: (limit = 10) => `?limit=${limit.toString()}`,\n      // `providesTags` determines which 'tag' is attached to the\n      // cached data returned by the query.\n      providesTags: (_result, _error, id) => [{ type: 'Quotes', id }],\n    }),\n  }),\n})\n\n// Hooks are auto-generated by RTK-Query\n// Same as `quotesApiSlice.endpoints.getQuotes.useQuery`\nexport const { useGetQuotesQuery } = quotesApiSlice\n"
  },
  {
    "path": "examples/publish-ci/react-native/src/utils/test-utils.tsx",
    "content": "import type { RenderOptions } from '@testing-library/react-native'\nimport { render, userEvent } from '@testing-library/react-native'\nimport type { PropsWithChildren, ReactElement } from 'react'\nimport { Provider } from 'react-redux'\nimport type { AppStore, RootState } from '../app/store'\nimport { makeStore } from '../app/store'\n\n/**\n * This type extends the default options for\n * React Testing Library's render function. It allows for\n * additional configuration such as specifying an initial Redux state and\n * a custom store instance.\n */\ntype ExtendedRenderOptions = Omit<RenderOptions, 'queries'> & {\n  /**\n   * Defines a specific portion or the entire initial state for the Redux store.\n   * This is particularly useful for initializing the state in a\n   * controlled manner during testing, allowing components to be rendered\n   * with predetermined state conditions.\n   */\n  preloadedState?: Partial<RootState>\n\n  /**\n   * Allows the use of a specific Redux store instance instead of a\n   * default or global store. This flexibility is beneficial when\n   * testing components with unique store requirements or when isolating\n   * tests from a global store state. The custom store should be configured\n   * to match the structure and middleware of the store used by the application.\n   *\n   * @default makeStore(preloadedState)\n   */\n  store?: AppStore\n}\n\n/**\n * Renders the given React element with Redux Provider and custom store.\n * This function is useful for testing components that are connected to the Redux store.\n *\n * @param ui - The React component or element to render.\n * @param extendedRenderOptions - Optional configuration options for rendering. This includes `preloadedState` for initial Redux state and `store` for a specific Redux store instance. Any additional properties are passed to React Testing Library's render function.\n * @returns An object containing the Redux store used in the render, User event API for simulating user interactions in tests, and all of React Testing Library's query functions for testing the component.\n */\nexport const renderWithProviders = (\n  ui: ReactElement,\n  extendedRenderOptions: ExtendedRenderOptions = {},\n) => {\n  const {\n    preloadedState = {},\n    // Automatically create a store instance if no store was passed in\n    store = makeStore(preloadedState),\n    ...renderOptions\n  } = extendedRenderOptions\n\n  const Wrapper = ({ children }: PropsWithChildren) => (\n    <Provider store={store}>{children}</Provider>\n  )\n\n  // Return an object with the store and all of RTL's query functions\n  return {\n    store,\n    user: userEvent.setup(),\n    ...render(ui, { wrapper: Wrapper, ...renderOptions }),\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/react-native/tsconfig.json",
    "content": "{\n  \"extends\": \"@react-native/typescript-config/tsconfig.json\"\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/.gitignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndist-ssr\n*.local\n.yalc\n\n# Editor directories and files\n.vscode/*\n!.vscode/extensions.json\n.idea\n.DS_Store\n*.suo\n*.ntvs*\n*.njsproj\n*.sln\n*.sw?\n\ntypesversions\n.cache\n.yarnrc\n.yarn/*\n!.yarn/patches\n!.yarn/releases\n!.yarn/plugins\n!.yarn/sdks\n!.yarn/versions\n.pnp.*\n*.tgz\n"
  },
  {
    "path": "examples/publish-ci/vite/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/vite.svg\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>Vite + React + TS</title>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/publish-ci/vite/package.json",
    "content": "{\n  \"name\": \"rtk-esm-vite-normal\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"build\": \"tsc && vite build\",\n    \"serve-app\": \"yarn serve -s dist\",\n    \"test\": \"yarn playwright test\",\n    \"format\": \"prettier --write \\\"./src/**/*.{ts,tsx}\\\" \\\"**/*.md\\\"\"\n  },\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^2.0.0-rc.3\",\n    \"msw\": \"^1.3.2\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-redux\": \"^9.0.0-rc.0\"\n  },\n  \"devDependencies\": {\n    \"@playwright/test\": \"^1.31.1\",\n    \"@testing-library/jest-dom\": \"^5.16.5\",\n    \"@testing-library/react\": \"^13.4.0\",\n    \"@testing-library/user-event\": \"^14.4.3\",\n    \"@types/jest\": \"^27.5.2\",\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^18.0.26\",\n    \"@types/react-dom\": \"^18.0.10\",\n    \"@vitejs/plugin-react\": \"^5\",\n    \"playwright\": \"^1.31.1\",\n    \"prettier\": \"^3.2.5\",\n    \"serve\": \"^14.2.0\",\n    \"typescript\": \"^5.9.3\",\n    \"vite\": \"^7\"\n  },\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/playwright.config.ts",
    "content": "import { defineConfig } from '@playwright/test'\nexport default defineConfig({\n  webServer: {\n    command: 'yarn serve-app',\n    port: 3000,\n    timeout: 120 * 1000,\n    reuseExistingServer: !process.env.CI,\n  },\n  timeout: 120 * 1000,\n  use: {\n    headless: true,\n    viewport: { width: 1280, height: 720 },\n    ignoreHTTPSErrors: true,\n  },\n  testDir: 'tests/playwright/',\n})\n"
  },
  {
    "path": "examples/publish-ci/vite/public/mockServiceWorker.js",
    "content": "/* eslint-disable */\n/* tslint:disable */\n\n/**\n * Mock Service Worker (1.3.2).\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n\nconst INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  self.skipWaiting()\n})\n\nself.addEventListener('activate', function (event) {\n  event.waitUntil(self.clients.claim())\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll({\n    type: 'window',\n  })\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n  const accept = request.headers.get('accept') || ''\n\n  // Bypass server-sent events.\n  if (accept.includes('text/event-stream')) {\n    return\n  }\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  // Generate unique request ID.\n  const requestId = Math.random().toString(16).slice(2)\n\n  event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      if (error.name === 'NetworkError') {\n        console.warn(\n          '[MSW] Successfully emulated a network error for the \"%s %s\" request.',\n          request.method,\n          request.url,\n        )\n        return\n      }\n\n      // At this point, any exception indicates an issue with the original request/response.\n      console.error(\n        `\\\n[MSW] Caught an exception from the \"%s %s\" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,\n        request.method,\n        request.url,\n        `${error.name}: ${error.message}`,\n      )\n    }),\n  )\n})\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMainClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: Object.fromEntries(clonedResponse.headers.entries()),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\n// Resolve the main client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMainClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client?.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll({\n    type: 'window',\n  })\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const clonedRequest = request.clone()\n\n  function passthrough() {\n    // Clone the request because it might've been already used\n    // (i.e. its body has been read and sent to the client).\n    const headers = Object.fromEntries(clonedRequest.headers.entries())\n\n    // Remove MSW-specific request headers so the bypassed requests\n    // comply with the server's CORS preflight check.\n    // Operate with the headers as an object because request \"Headers\"\n    // are immutable.\n    delete headers['x-msw-bypass']\n\n    return fetch(clonedRequest, { headers })\n  }\n\n  // Bypass mocking when the client is not active.\n  if (!client) {\n    return passthrough()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return passthrough()\n  }\n\n  // Bypass requests with the explicit bypass header.\n  // Such requests can be issued by \"ctx.fetch()\".\n  if (request.headers.get('x-msw-bypass') === 'true') {\n    return passthrough()\n  }\n\n  // Notify the client that a request has been intercepted.\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: Object.fromEntries(request.headers.entries()),\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body: await request.text(),\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_RESPONSE': {\n      return respondWithMock(clientMessage.data)\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return passthrough()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.data\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a \"respondWith\" promise emulates a network error.\n      throw networkError\n    }\n  }\n\n  return passthrough()\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(message, [channel.port2])\n  })\n}\n\nfunction sleep(timeMs) {\n  return new Promise((resolve) => {\n    setTimeout(resolve, timeMs)\n  })\n}\n\nasync function respondWithMock(response) {\n  await sleep(response.delay)\n  return new Response(response.body, response)\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/src/App.css",
    "content": ".App {\n  text-align: center;\n}\n\n.App-logo {\n  height: 40vmin;\n  pointer-events: none;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n  .App-logo {\n    animation: App-logo-float infinite 3s ease-in-out;\n  }\n}\n\n.App-header {\n  min-height: 100vh;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: flex-start;\n  font-size: calc(10px + 2vmin);\n}\n\n.App-link {\n  color: rgb(112, 76, 182);\n}\n\n@keyframes App-logo-float {\n  0% {\n    transform: translateY(0);\n  }\n  50% {\n    transform: translateY(10px);\n  }\n  100% {\n    transform: translateY(0px);\n  }\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/src/App.tsx",
    "content": "import { Counter } from './features/counter/Counter'\nimport { TimeDisplay } from './features/time/TimeList'\nimport { Post } from './features/posts/Post'\nimport './App.css'\n\nfunction App() {\n  return (\n    <div className=\"App\">\n      <header className=\"App-header\">\n        <Counter />\n        <TimeDisplay\n          label=\"(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima\"\n          offset=\"-5:00\"\n        />\n        <Post id={1} />\n      </header>\n    </div>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/publish-ci/vite/src/app/hooks.ts",
    "content": "import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'\nimport type { RootState, AppDispatch } from './store'\n\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = () => useDispatch<AppDispatch>()\nexport const useAppSelector: TypedUseSelectorHook<RootState> = useSelector\n"
  },
  {
    "path": "examples/publish-ci/vite/src/app/services/post.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport interface Post {\n  id: number\n  name: string\n  fetched_at: string\n}\n\nexport const postApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  reducerPath: 'postApi',\n  tagTypes: ['Posts'],\n  endpoints: (build) => ({\n    getPost: build.query<Post, number>({\n      query: (id) => `posts/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Posts', id }],\n    }),\n  }),\n})\n\nexport const { useGetPostQuery } = postApi\n"
  },
  {
    "path": "examples/publish-ci/vite/src/app/services/times.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\ninterface TimeResponse {\n  time: string\n}\n\nexport const timeApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  reducerPath: 'timeApi',\n  tagTypes: ['Time'],\n  endpoints: (build) => ({\n    getTime: build.query<TimeResponse, string>({\n      query: (id) => `time/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Time', id }],\n    }),\n  }),\n})\n"
  },
  {
    "path": "examples/publish-ci/vite/src/app/store.ts",
    "content": "import { configureStore, ThunkAction, Action } from '@reduxjs/toolkit'\nimport counterReducer from '../features/counter/counterSlice'\nimport { postApi } from './services/post'\nimport { timeApi } from './services/times'\n\nexport const store = configureStore({\n  reducer: {\n    counter: counterReducer,\n    [postApi.reducerPath]: postApi.reducer,\n    [timeApi.reducerPath]: timeApi.reducer,\n  },\n  middleware: (gDM) => gDM().concat(postApi.middleware, timeApi.middleware),\n})\n\nexport type AppDispatch = typeof store.dispatch\nexport type RootState = ReturnType<typeof store.getState>\nexport type AppThunk<ReturnType = void> = ThunkAction<\n  ReturnType,\n  RootState,\n  unknown,\n  Action<string>\n>\n"
  },
  {
    "path": "examples/publish-ci/vite/src/features/common/Container.tsx",
    "content": "import { FC, ReactNode } from 'react'\n\nexport const Container: FC<{ children: ReactNode }> = ({ children }) => (\n  <div style={{ textAlign: 'center', padding: 50, margin: '0 auto' }}>\n    {children}\n  </div>\n)\n"
  },
  {
    "path": "examples/publish-ci/vite/src/features/counter/Counter.module.css",
    "content": ".row {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.row > button {\n  margin-left: 4px;\n  margin-right: 8px;\n}\n\n.row:not(:last-child) {\n  margin-bottom: 16px;\n}\n\n.value {\n  font-size: 78px;\n  padding-left: 16px;\n  padding-right: 16px;\n  margin-top: 2px;\n  font-family: 'Courier New', Courier, monospace;\n}\n\n.button {\n  appearance: none;\n  background: none;\n  font-size: 32px;\n  padding-left: 12px;\n  padding-right: 12px;\n  outline: none;\n  border: 2px solid transparent;\n  color: rgb(112, 76, 182);\n  padding-bottom: 4px;\n  cursor: pointer;\n  background-color: rgba(112, 76, 182, 0.1);\n  border-radius: 2px;\n  transition: all 0.15s;\n}\n\n.textbox {\n  font-size: 32px;\n  padding: 2px;\n  width: 64px;\n  text-align: center;\n  margin-right: 4px;\n}\n\n.button:hover,\n.button:focus {\n  border: 2px solid rgba(112, 76, 182, 0.4);\n}\n\n.button:active {\n  background-color: rgba(112, 76, 182, 0.2);\n}\n\n.asyncButton {\n  composes: button;\n  position: relative;\n}\n\n.asyncButton:after {\n  content: '';\n  background-color: rgba(112, 76, 182, 0.15);\n  display: block;\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  left: 0;\n  top: 0;\n  opacity: 0;\n  transition:\n    width 1s linear,\n    opacity 0.5s ease 1s;\n}\n\n.asyncButton:active:after {\n  width: 0%;\n  opacity: 1;\n  transition: 0s;\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/src/features/counter/Counter.tsx",
    "content": "import React, { useState } from 'react'\n\nimport { useAppSelector, useAppDispatch } from '../../app/hooks'\nimport {\n  decrement,\n  increment,\n  incrementByAmount,\n  incrementAsync,\n  incrementIfOdd,\n  selectCount,\n} from './counterSlice'\nimport styles from './Counter.module.css'\n\nexport function Counter() {\n  const count = useAppSelector(selectCount)\n  const dispatch = useAppDispatch()\n  const [incrementAmount, setIncrementAmount] = useState('2')\n\n  const incrementValue = Number(incrementAmount) || 0\n\n  return (\n    <div>\n      <h2>Counter</h2>\n      <div className={styles.row}>\n        <button\n          className={styles.button}\n          aria-label=\"Decrement value\"\n          onClick={() => dispatch(decrement())}\n        >\n          -\n        </button>\n        <span className={styles.value} data-testid=\"counter-value\">\n          {count}\n        </span>\n        <button\n          className={styles.button}\n          aria-label=\"Increment value\"\n          onClick={() => dispatch(increment())}\n        >\n          +\n        </button>\n      </div>\n      <div className={styles.row}>\n        <input\n          className={styles.textbox}\n          aria-label=\"Set increment amount\"\n          value={incrementAmount}\n          onChange={(e) => setIncrementAmount(e.target.value)}\n        />\n        <button\n          className={styles.button}\n          onClick={() => dispatch(incrementByAmount(incrementValue))}\n        >\n          Add Amount\n        </button>\n        <button\n          className={styles.asyncButton}\n          onClick={() => dispatch(incrementAsync(incrementValue))}\n        >\n          Add Async\n        </button>\n        <button\n          className={styles.button}\n          onClick={() => dispatch(incrementIfOdd(incrementValue))}\n        >\n          Add If Odd\n        </button>\n      </div>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/src/features/counter/counterAPI.ts",
    "content": "// A mock function to mimic making an async request for data\nexport function fetchCount(amount = 1) {\n  return new Promise<{ data: number }>((resolve) =>\n    setTimeout(() => resolve({ data: amount }), 500),\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/src/features/counter/counterSlice.ts",
    "content": "import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit'\nimport { RootState, AppThunk } from '../../app/store'\nimport { fetchCount } from './counterAPI'\n\nexport interface CounterState {\n  value: number\n  status: 'idle' | 'loading' | 'failed'\n}\n\nconst initialState: CounterState = {\n  value: 0,\n  status: 'idle',\n}\n\n// The function below is called a thunk and allows us to perform async logic. It\n// can be dispatched like a regular action: `dispatch(incrementAsync(10))`. This\n// will call the thunk with the `dispatch` function as the first argument. Async\n// code can then be executed and other actions can be dispatched. Thunks are\n// typically used to make async requests.\nexport const incrementAsync = createAsyncThunk(\n  'counter/fetchCount',\n  async (amount: number) => {\n    const response = await fetchCount(amount)\n    // The value we return becomes the `fulfilled` action payload\n    return response.data\n  },\n)\n\nexport const counterSlice = createSlice({\n  name: 'counter',\n  initialState,\n  // The `reducers` field lets us define reducers and generate associated actions\n  reducers: {\n    increment: (state) => {\n      // Redux Toolkit allows us to write \"mutating\" logic in reducers. It\n      // doesn't actually mutate the state because it uses the Immer library,\n      // which detects changes to a \"draft state\" and produces a brand new\n      // immutable state based off those changes\n      state.value += 1\n    },\n    decrement: (state) => {\n      state.value -= 1\n    },\n    // Use the PayloadAction type to declare the contents of `action.payload`\n    incrementByAmount: (state, action: PayloadAction<number>) => {\n      state.value += action.payload\n    },\n  },\n  // The `extraReducers` field lets the slice handle actions defined elsewhere,\n  // including actions generated by createAsyncThunk or in other slices.\n  extraReducers: (builder) => {\n    builder\n      .addCase(incrementAsync.pending, (state) => {\n        state.status = 'loading'\n      })\n      .addCase(incrementAsync.fulfilled, (state, action) => {\n        state.status = 'idle'\n        state.value += action.payload\n      })\n      .addCase(incrementAsync.rejected, (state) => {\n        state.status = 'failed'\n      })\n  },\n})\n\nexport const { increment, decrement, incrementByAmount } = counterSlice.actions\n\n// The function below is called a selector and allows us to select a value from\n// the state. Selectors can also be defined inline where they're used instead of\n// in the slice file. For example: `useSelector((state: RootState) => state.counter.value)`\nexport const selectCount = (state: RootState) => state.counter.value\n\n// We can also write thunks by hand, which may contain both sync and async logic.\n// Here's an example of conditionally dispatching actions based on current state.\nexport const incrementIfOdd =\n  (amount: number): AppThunk =>\n  (dispatch, getState) => {\n    const currentValue = selectCount(getState())\n    if (currentValue % 2 === 1) {\n      dispatch(incrementByAmount(amount))\n    }\n  }\n\nexport default counterSlice.reducer\n"
  },
  {
    "path": "examples/publish-ci/vite/src/features/posts/Post.tsx",
    "content": "import React from 'react'\n\n// import the file that injects \"post\" to make sure it has been loaded\nimport { useGetPostQuery } from '../../app/services/post'\n\nexport const Post = ({ id }: { id: number }) => {\n  const { data, error } = useGetPostQuery(id)\n  const content = error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <div>\n      Title:{' '}\n      <b>\n        <span data-testid=\"post-value\">{data.name}</span>\n      </b>\n    </div>\n  )\n\n  return (\n    <div>\n      <h2>Post</h2>\n      {content}\n    </div>\n  )\n}\nexport default Post\n"
  },
  {
    "path": "examples/publish-ci/vite/src/features/posts/PostsManager.css",
    "content": ".posts-list {\n  display: flex;\n  flex-direction: column;\n  flex-basis: 100%;\n  flex: 1;\n  min-height: 200px;\n  border-right: 1px solid #eee;\n  padding: 20px;\n  text-align: left;\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/src/features/time/TimeList.tsx",
    "content": "import * as React from 'react'\nimport { useEffect } from 'react'\nimport { timeApi } from '../../app/services/times'\nimport { useAppDispatch } from '../../app/hooks'\n\nexport const TimeDisplay = ({\n  offset,\n  label,\n}: {\n  offset: string\n  label: string\n}) => {\n  const [data, setData] = React.useState<any>(null)\n  const dispatch = useAppDispatch()\n\n  useEffect(() => {\n    const res = dispatch(timeApi.endpoints.getTime.initiate(offset))\n\n    res.then((value) => {\n      setData(value?.data)\n    })\n    return res.unsubscribe\n  }, [offset, dispatch])\n\n  return (\n    <div>\n      <h2>Time Zone</h2>\n      <ul style={{ textAlign: 'left' }}>\n        <li>Zone: {label}</li>\n        <li>\n          Time:{' '}\n          <span data-testid=\"time-value\">\n            {data?.time ? new Date(data.time).toLocaleTimeString() : 'unknown'}\n          </span>\n        </li>\n      </ul>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/src/index.css",
    "content": "body {\n  margin: 0;\n  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', 'Roboto', 'Oxygen',\n    'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans', 'Helvetica Neue',\n    sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n  font-family: source-code-pro, Menlo, Monaco, Consolas, 'Courier New',\n    monospace;\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/src/main.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport { Provider } from 'react-redux'\nimport { store } from './app/store'\nimport App from './App'\nimport './index.css'\n\nimport { worker } from './mocks/browser'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nasync function render() {\n  await worker.start()\n\n  const rootNode = ReactDOM.createRoot(\n    document.getElementById('root') as HTMLElement,\n  )\n\n  rootNode.render(\n    <React.StrictMode>\n      <Provider store={store}>\n        <App />\n      </Provider>\n    </React.StrictMode>,\n  )\n}\n\nrender()\n"
  },
  {
    "path": "examples/publish-ci/vite/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './handlers'\n\nexport const worker = setupWorker(...handlers)\n"
  },
  {
    "path": "examples/publish-ci/vite/src/mocks/handlers.ts",
    "content": "import { rest } from 'msw'\nimport { createEntityAdapter } from '@reduxjs/toolkit'\nimport { Post } from '../app/services/post'\n\n// We're just going to use a simple in-memory store for both the counter and posts\n// The entity adapter will handle modifications when triggered by the MSW handlers\n\nconst adapter = createEntityAdapter<Post>()\n\nlet state = adapter.getInitialState()\nstate = adapter.setAll(state, [\n  { id: 1, name: 'A sample post', fetched_at: new Date().toUTCString() },\n  {\n    id: 2,\n    name: 'A post about rtk-query',\n    fetched_at: new Date().toUTCString(),\n  },\n])\n\nexport { state }\n\nexport const handlers = [\n  rest.get('/time/:offset', (req, res, ctx) => {\n    const { offset } = req.params as { offset: string }\n    const date = new Date()\n    const localDate = date.getTime() // users local time\n    const localOffset = date.getTimezoneOffset() * 60000\n    const formattedOffset = Number(offset.replace(':', '.'))\n    const target = localDate + localOffset + 3600000 * formattedOffset\n    return res(\n      ctx.json({ time: new Date(target).toUTCString() }),\n      ctx.delay(400),\n    )\n  }),\n\n  rest.get('/posts/:id', (req, res, ctx) => {\n    const { id: idParam } = req.params as { id: string }\n    const id = parseInt(idParam, 10)\n    state = adapter.updateOne(state, {\n      id,\n      changes: { fetched_at: new Date().toUTCString() },\n    })\n    return res(ctx.json(state.entities[id]), ctx.delay(400))\n  }),\n]\n"
  },
  {
    "path": "examples/publish-ci/vite/src/mocks/mockServer.ts",
    "content": "import { setupServer } from 'msw/node'\nimport { handlers } from './handlers'\nimport { state } from './handlers'\n\nexport const mockServer = () => {\n  const server = setupServer(...handlers)\n\n  return { server, state }\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/src/vite-env.d.ts",
    "content": "/// <reference types=\"vite/client\" />\n"
  },
  {
    "path": "examples/publish-ci/vite/tests/playwright/rtkq.test.ts",
    "content": "import { test, expect } from '@playwright/test'\n\ntest('RTK / RTKQ Interactions', async ({ page }) => {\n  page.on('console', (msg) => console.log('Console message: ', msg.text()))\n  await page.goto('http://localhost:3000')\n\n  const counterValue = page.getByTestId('counter-value')\n  const counterText = await counterValue.innerText({ timeout: 0 })\n  expect(counterText).toBe('0')\n\n  const increment = page.getByRole('button', { name: 'Increment value' })\n  await increment.click()\n\n  const counterText2 = await counterValue.innerText({ timeout: 0 })\n  expect(counterText2).toBe('1')\n\n  const timeValue = page.getByTestId('time-value')\n  const postValue = page.getByTestId('post-value')\n\n  await expect(timeValue).toHaveText(/\\d+:\\d+:\\d+\\s+(A|P)M/, { timeout: 10000 })\n  await expect(postValue).toHaveText('A sample post', { timeout: 10000 })\n})\n"
  },
  {
    "path": "examples/publish-ci/vite/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"allowJs\": false,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": false,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\"\n  },\n  \"include\": [\"src\"],\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/tsconfig.node.json",
    "content": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"allowSyntheticDefaultImports\": true\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n"
  },
  {
    "path": "examples/publish-ci/vite/vite.config.ts",
    "content": "import { defineConfig } from 'vite'\nimport react from '@vitejs/plugin-react'\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  build: {\n    sourcemap: true,\n  },\n})\n"
  },
  {
    "path": "examples/query/react/advanced/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/advanced\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"getting-started-advanced\",\n  \"keywords\": [],\n  \"main\": \"src/index.tsx\",\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\"\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ]\n}\n"
  },
  {
    "path": "examples/query/react/advanced/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"\n    />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <!--\n      manifest.json provides metadata used when your web app is added to the\n      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n\n  <body>\n    <noscript> You need to enable JavaScript to run this app. </noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/advanced/src/App.tsx",
    "content": "import './styles.css'\nimport { Pokemon } from './Pokemon'\nimport { useState } from 'react'\n\nconst pokemon = ['bulbasaur', 'pikachu', 'ditto', 'bulbasaur']\n\nexport default function App() {\n  const [pollingInterval, setPollingInterval] = useState(0)\n\n  return (\n    <div className=\"App\">\n      <select\n        onChange={(change) => setPollingInterval(Number(change.target.value))}\n      >\n        <option value={0}>Off</option>\n        <option value={1000}>1s</option>\n        <option value={5000}>5s</option>\n      </select>\n      <div>\n        {pokemon.map((poke, index) => (\n          <Pokemon key={index} name={poke} pollingInterval={pollingInterval} />\n        ))}\n      </div>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/advanced/src/Pokemon.tsx",
    "content": "import { useGetPokemonByNameQuery } from './services/pokemon'\n\nexport const Pokemon = ({\n  name,\n  pollingInterval,\n}: {\n  name: string\n  pollingInterval: number\n}) => {\n  const { data, error, isLoading, isFetching } = useGetPokemonByNameQuery(\n    name,\n    {\n      pollingInterval,\n    },\n  )\n\n  return (\n    <>\n      {error ? (\n        <>Oh no, there was an error</>\n      ) : isLoading ? (\n        <>Loading...</>\n      ) : data ? (\n        <>\n          <h3>\n            {data.species.name} {isFetching ? '...' : ''}\n          </h3>\n          <img src={data.sprites.front_shiny} alt={data.species.name} />\n        </>\n      ) : null}\n    </>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/advanced/src/index.tsx",
    "content": "import ReactDOM from 'react-dom/client'\nimport { ApiProvider } from '@reduxjs/toolkit/query/react'\nimport App from './App'\nimport { pokemonApi } from './services/pokemon'\n\nconst rootElement = document.getElementById('root')\n\nconst reactRoot = ReactDOM.createRoot(rootElement as HTMLElement)\n\nreactRoot.render(\n  <ApiProvider api={pokemonApi}>\n    <App />\n  </ApiProvider>,\n)\n"
  },
  {
    "path": "examples/query/react/advanced/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/advanced/src/services/pokemon.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const pokemonApi = createApi({\n  reducerPath: 'pokemonApi',\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  tagTypes: [],\n  endpoints: (build) => ({\n    getPokemonByName: build.query({\n      query: (name: string) => `pokemon/${name}`,\n    }),\n  }),\n})\n\n// Export hooks for usage in functional components\nexport const { useGetPokemonByNameQuery } = pokemonApi\n"
  },
  {
    "path": "examples/query/react/advanced/src/styles.css",
    "content": ".App {\n  font-family: sans-serif;\n  text-align: center;\n}\n"
  },
  {
    "path": "examples/query/react/advanced/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/authentication/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/authentication\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"./src/index.tsx\",\n  \"dependencies\": {\n    \"@chakra-ui/react\": \"2.10.7\",\n    \"@emotion/react\": \"^11.4.0\",\n    \"@emotion/styled\": \"^11.3.0\",\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"framer-motion\": \"^2.9.5\",\n    \"msw\": \"^0.40.2\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-icons\": \"3.11.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-router-dom\": \"6.3.0\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"prebuild\": \"rimraf dist/\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ],\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/authentication/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/authentication/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query Authentication Example\",\n  \"name\": \"Authentication Example\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/authentication/public/mockServiceWorker.js",
    "content": "/**\n * Mock Service Worker.\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n/* eslint-disable */\n/* tslint:disable */\n\nconst INTEGRITY_CHECKSUM = '82ef9b96d8393b6da34527d1d6e19187'\nconst bypassHeaderName = 'x-msw-bypass'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  return self.skipWaiting()\n})\n\nself.addEventListener('activate', async function (event) {\n  return self.clients.claim()\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\n// Resolve the \"master\" client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMasterClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMasterClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: serializeHeaders(clonedResponse.headers),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const requestClone = request.clone()\n  const getOriginalResponse = () => fetch(requestClone)\n\n  // Bypass mocking when the request client is not active.\n  if (!client) {\n    return getOriginalResponse()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return await getOriginalResponse()\n  }\n\n  // Bypass requests with the explicit bypass header\n  if (requestClone.headers.get(bypassHeaderName) === 'true') {\n    const cleanRequestHeaders = serializeHeaders(requestClone.headers)\n\n    // Remove the bypass header to comply with the CORS preflight check.\n    delete cleanRequestHeaders[bypassHeaderName]\n\n    const originalRequest = new Request(requestClone, {\n      headers: new Headers(cleanRequestHeaders),\n    })\n\n    return fetch(originalRequest)\n  }\n\n  // Send the request to the client-side MSW.\n  const reqHeaders = serializeHeaders(request.headers)\n  const body = await request.text()\n\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: reqHeaders,\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body,\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_SUCCESS': {\n      return delayPromise(\n        () => respondWithMock(clientMessage),\n        clientMessage.payload.delay,\n      )\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return getOriginalResponse()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.payload\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a request Promise emulates a network error.\n      throw networkError\n    }\n\n    case 'INTERNAL_ERROR': {\n      const parsedBody = JSON.parse(clientMessage.payload.body)\n\n      console.error(\n        `\\\n[MSW] Request handler function for \"%s %s\" has thrown the following exception:\n\n${parsedBody.errorType}: ${parsedBody.message}\n(see more detailed error stack trace in the mocked response body)\n\nThis exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error.\nIf you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\\\n`,\n        request.method,\n        request.url,\n      )\n\n      return respondWithMock(clientMessage)\n    }\n  }\n\n  return getOriginalResponse()\n}\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  const requestId = uuidv4()\n\n  return event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      console.error(\n        '[MSW] Failed to mock a \"%s\" request to \"%s\": %s',\n        request.method,\n        request.url,\n        error,\n      )\n    }),\n  )\n})\n\nfunction serializeHeaders(headers) {\n  const reqHeaders = {}\n  headers.forEach((value, name) => {\n    reqHeaders[name] = reqHeaders[name]\n      ? [].concat(reqHeaders[name]).concat(value)\n      : value\n  })\n  return reqHeaders\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(JSON.stringify(message), [channel.port2])\n  })\n}\n\nfunction delayPromise(cb, duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => resolve(cb()), duration)\n  })\n}\n\nfunction respondWithMock(clientMessage) {\n  return new Response(clientMessage.payload.body, {\n    ...clientMessage.payload,\n    headers: clientMessage.payload.headers,\n  })\n}\n\nfunction uuidv4() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0\n    const v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n"
  },
  {
    "path": "examples/query/react/authentication/src/App.tsx",
    "content": "import { Routes, Route } from 'react-router-dom'\nimport { Box, Center, VStack } from '@chakra-ui/react'\n\nimport { Login } from './features/auth/Login'\nimport { PrivateOutlet } from './utils/PrivateOutlet'\nimport { ProtectedComponent } from './features/auth/ProtectedComponent'\n\nfunction Hooray() {\n  return (\n    <Center h=\"500px\">\n      <VStack>\n        <Box>Hooray you logged in!</Box>\n        <Box>\n          <ProtectedComponent />\n        </Box>\n      </VStack>\n    </Center>\n  )\n}\n\nfunction App() {\n  return (\n    <Box>\n      <Routes>\n        <Route path=\"/login\" element={<Login />} />\n        <Route path=\"*\" element={<PrivateOutlet />}>\n          <Route index element={<Hooray />} />\n        </Route>\n      </Routes>\n    </Box>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/authentication/src/app/services/auth.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { RootState } from '../store'\n\nexport interface User {\n  first_name: string\n  last_name: string\n}\n\nexport interface UserResponse {\n  user: User\n  token: string\n}\n\nexport interface LoginRequest {\n  username: string\n  password: string\n}\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n    prepareHeaders: (headers, { getState }) => {\n      // By default, if we have a token in the store, let's use that for authenticated requests\n      const token = (getState() as RootState).auth.token\n      if (token) {\n        headers.set('authorization', `Bearer ${token}`)\n      }\n      return headers\n    },\n  }),\n  endpoints: (build) => ({\n    login: build.mutation<UserResponse, LoginRequest>({\n      query: (credentials) => ({\n        url: 'login',\n        method: 'POST',\n        body: credentials,\n      }),\n    }),\n    protected: build.mutation<{ message: string }, void>({\n      query: () => 'protected',\n    }),\n  }),\n})\n\nexport const { useLoginMutation, useProtectedMutation } = api\n"
  },
  {
    "path": "examples/query/react/authentication/src/app/store.ts",
    "content": "import { configureStore } from '@reduxjs/toolkit'\nimport { api } from './services/auth'\nimport authReducer from '../features/auth/authSlice'\n\nexport const store = configureStore({\n  reducer: {\n    [api.reducerPath]: api.reducer,\n    auth: authReducer,\n  },\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(api.middleware),\n})\n\nexport type RootState = ReturnType<typeof store.getState>\nexport type AppDispatch = typeof store.dispatch\n"
  },
  {
    "path": "examples/query/react/authentication/src/features/auth/Login.tsx",
    "content": "import {\n  Box,\n  Button,\n  Center,\n  Divider,\n  Input,\n  InputGroup,\n  InputRightElement,\n  useToast,\n  VStack,\n} from '@chakra-ui/react'\nimport * as React from 'react'\nimport { useDispatch } from 'react-redux'\nimport { useNavigate } from 'react-router-dom'\nimport { setCredentials } from './authSlice'\n\nimport type { LoginRequest } from '../../app/services/auth'\nimport { useLoginMutation } from '../../app/services/auth'\nimport { ProtectedComponent } from './ProtectedComponent'\n\nfunction PasswordInput({\n  name,\n  onChange,\n}: {\n  name: string\n  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void\n}) {\n  const [show, setShow] = React.useState(false)\n  const handleClick = () => setShow(!show)\n\n  return (\n    <InputGroup size=\"md\">\n      <Input\n        pr=\"4.5rem\"\n        type={show ? 'text' : 'password'}\n        placeholder=\"Enter password\"\n        name={name}\n        onChange={onChange}\n      />\n      <InputRightElement width=\"4.5rem\">\n        <Button h=\"1.75rem\" size=\"sm\" onClick={handleClick}>\n          {show ? 'Hide' : 'Show'}\n        </Button>\n      </InputRightElement>\n    </InputGroup>\n  )\n}\n\nexport const Login = () => {\n  const dispatch = useDispatch()\n  const navigate = useNavigate()\n  const toast = useToast()\n\n  const [formState, setFormState] = React.useState<LoginRequest>({\n    username: '',\n    password: '',\n  })\n\n  const [login, { isLoading }] = useLoginMutation()\n\n  const handleChange = ({\n    target: { name, value },\n  }: React.ChangeEvent<HTMLInputElement>) =>\n    setFormState((prev) => ({ ...prev, [name]: value }))\n\n  return (\n    <Center h=\"500px\">\n      <VStack spacing=\"4\">\n        <Box>Hint: enter anything, or leave it blank and hit login</Box>\n        <InputGroup>\n          <Input\n            onChange={handleChange}\n            name=\"username\"\n            type=\"text\"\n            placeholder=\"Email\"\n          />\n        </InputGroup>\n\n        <InputGroup>\n          <PasswordInput onChange={handleChange} name=\"password\" />\n        </InputGroup>\n        <Button\n          width=\"100%\"\n          onClick={async () => {\n            try {\n              const user = await login(formState).unwrap()\n              dispatch(setCredentials(user))\n              navigate('/')\n            } catch (err) {\n              toast({\n                status: 'error',\n                title: 'Error',\n                description: 'Oh no, there was an error!',\n                isClosable: true,\n              })\n            }\n          }}\n          colorScheme=\"green\"\n          isLoading={isLoading}\n        >\n          Login\n        </Button>\n        <Divider />\n        <ProtectedComponent />\n      </VStack>\n    </Center>\n  )\n}\n\nexport default Login\n"
  },
  {
    "path": "examples/query/react/authentication/src/features/auth/ProtectedComponent.tsx",
    "content": "import { Center, VStack, Box, Button } from '@chakra-ui/react'\nimport { useProtectedMutation } from '../../app/services/auth'\n\nexport function ProtectedComponent() {\n  const [attemptAccess, { data, error, isLoading }] = useProtectedMutation()\n\n  return (\n    <Center w=\"400px\">\n      <VStack>\n        <Box>\n          <Button onClick={() => attemptAccess()} isLoading={isLoading}>\n            Make an authenticated request\n          </Button>\n        </Box>\n        <Box>\n          {data ? (\n            <>\n              Data:\n              <pre>{JSON.stringify(data, null, 2)}</pre>\n            </>\n          ) : error ? (\n            <>\n              Error: <pre>{JSON.stringify(error, null, 2)}</pre>\n            </>\n          ) : null}\n        </Box>\n      </VStack>\n    </Center>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/authentication/src/features/auth/authSlice.tsx",
    "content": "import { createSlice } from '@reduxjs/toolkit'\nimport type { PayloadAction } from '@reduxjs/toolkit'\nimport type { User } from '../../app/services/auth'\nimport type { RootState } from '../../app/store'\n\ntype AuthState = {\n  user: User | null\n  token: string | null\n}\n\nconst slice = createSlice({\n  name: 'auth',\n  initialState: { user: null, token: null } as AuthState,\n  reducers: {\n    setCredentials: (\n      state,\n      {\n        payload: { user, token },\n      }: PayloadAction<{ user: User; token: string }>,\n    ) => {\n      state.user = user\n      state.token = token\n    },\n  },\n})\n\nexport const { setCredentials } = slice.actions\n\nexport default slice.reducer\n\nexport const selectCurrentUser = (state: RootState) => state.auth.user\n"
  },
  {
    "path": "examples/query/react/authentication/src/hooks/store.ts",
    "content": "import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'\nimport type { AppDispatch, RootState } from '../app/store'\n\nexport const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector\nexport const useAppDispatch = () => useDispatch<AppDispatch>()\n"
  },
  {
    "path": "examples/query/react/authentication/src/hooks/useAuth.ts",
    "content": "import { useMemo } from 'react'\nimport { useSelector } from 'react-redux'\nimport { selectCurrentUser } from '../features/auth/authSlice'\n\nexport const useAuth = () => {\n  const user = useSelector(selectCurrentUser)\n\n  return useMemo(() => ({ user }), [user])\n}\n"
  },
  {
    "path": "examples/query/react/authentication/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport { BrowserRouter } from 'react-router-dom'\nimport { ChakraProvider } from '@chakra-ui/react'\nimport App from './App'\nimport { store } from './app/store'\nimport { worker } from './mocks/browser'\nimport { Provider } from 'react-redux'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nworker\n  .start({ quiet: true })\n  .then(() => {\n    const rootNode = ReactDOM.createRoot(\n      document.getElementById('root') as HTMLElement,\n    )\n\n    return rootNode.render(\n      <React.StrictMode>\n        <Provider store={store}>\n          <ChakraProvider>\n            <BrowserRouter>\n              <App />\n            </BrowserRouter>\n          </ChakraProvider>\n        </Provider>\n      </React.StrictMode>,\n    )\n  })\n  .catch(console.error)\n"
  },
  {
    "path": "examples/query/react/authentication/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './handlers'\n\nexport const worker = setupWorker(...handlers)\n"
  },
  {
    "path": "examples/query/react/authentication/src/mocks/handlers.ts",
    "content": "import { rest } from 'msw'\nimport { nanoid } from '@reduxjs/toolkit'\n\nconst token = nanoid()\n\nexport const handlers = [\n  rest.get('/protected', (req, res, ctx) => {\n    const headers = req.headers.all()\n    if (headers.authorization !== `Bearer ${token}`) {\n      return res(\n        ctx.json({\n          message: 'You shall not pass. Please login first.',\n        }),\n        ctx.status(401),\n      )\n    }\n    return res(\n      ctx.json({\n        message:\n          'Join us on the Reactiflux Discord server in #redux if you have any questions.',\n      }),\n    )\n  }),\n  rest.post('/login', (req, res, ctx) => {\n    return res(\n      ctx.delay(400),\n      ctx.json({\n        user: {\n          first_name: 'Test',\n          last_name: 'User',\n        },\n        token,\n      }),\n    )\n  }),\n]\n"
  },
  {
    "path": "examples/query/react/authentication/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/authentication/src/utils/PrivateOutlet.tsx",
    "content": "import { Navigate, Outlet, useLocation } from 'react-router-dom'\nimport { useAuth } from '../hooks/useAuth'\n\nexport function PrivateOutlet() {\n  const auth = useAuth()\n  const location = useLocation()\n\n  return auth.user ? (\n    <Outlet />\n  ) : (\n    <Navigate to=\"/login\" state={{ from: location }} />\n  )\n}\n"
  },
  {
    "path": "examples/query/react/authentication/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/authentication-with-extrareducers\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"./src/index.tsx\",\n  \"dependencies\": {\n    \"@chakra-ui/react\": \"2.10.7\",\n    \"@emotion/react\": \"^11.4.0\",\n    \"@emotion/styled\": \"^11.3.0\",\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"framer-motion\": \"^2.9.5\",\n    \"msw\": \"^0.40.2\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-icons\": \"3.11.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-router-dom\": \"6.3.0\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"prebuild\": \"rimraf dist/\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ],\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query Authentication using extraReducers Example\",\n  \"name\": \"Authentication Example\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/public/mockServiceWorker.js",
    "content": "/**\n * Mock Service Worker.\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n/* eslint-disable */\n/* tslint:disable */\n\nconst INTEGRITY_CHECKSUM = '82ef9b96d8393b6da34527d1d6e19187'\nconst bypassHeaderName = 'x-msw-bypass'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  return self.skipWaiting()\n})\n\nself.addEventListener('activate', async function (event) {\n  return self.clients.claim()\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\n// Resolve the \"master\" client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMasterClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMasterClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: serializeHeaders(clonedResponse.headers),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const requestClone = request.clone()\n  const getOriginalResponse = () => fetch(requestClone)\n\n  // Bypass mocking when the request client is not active.\n  if (!client) {\n    return getOriginalResponse()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return await getOriginalResponse()\n  }\n\n  // Bypass requests with the explicit bypass header\n  if (requestClone.headers.get(bypassHeaderName) === 'true') {\n    const cleanRequestHeaders = serializeHeaders(requestClone.headers)\n\n    // Remove the bypass header to comply with the CORS preflight check.\n    delete cleanRequestHeaders[bypassHeaderName]\n\n    const originalRequest = new Request(requestClone, {\n      headers: new Headers(cleanRequestHeaders),\n    })\n\n    return fetch(originalRequest)\n  }\n\n  // Send the request to the client-side MSW.\n  const reqHeaders = serializeHeaders(request.headers)\n  const body = await request.text()\n\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: reqHeaders,\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body,\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_SUCCESS': {\n      return delayPromise(\n        () => respondWithMock(clientMessage),\n        clientMessage.payload.delay,\n      )\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return getOriginalResponse()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.payload\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a request Promise emulates a network error.\n      throw networkError\n    }\n\n    case 'INTERNAL_ERROR': {\n      const parsedBody = JSON.parse(clientMessage.payload.body)\n\n      console.error(\n        `\\\n[MSW] Request handler function for \"%s %s\" has thrown the following exception:\n\n${parsedBody.errorType}: ${parsedBody.message}\n(see more detailed error stack trace in the mocked response body)\n\nThis exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error.\nIf you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\\\n`,\n        request.method,\n        request.url,\n      )\n\n      return respondWithMock(clientMessage)\n    }\n  }\n\n  return getOriginalResponse()\n}\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  const requestId = uuidv4()\n\n  return event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      console.error(\n        '[MSW] Failed to mock a \"%s\" request to \"%s\": %s',\n        request.method,\n        request.url,\n        error,\n      )\n    }),\n  )\n})\n\nfunction serializeHeaders(headers) {\n  const reqHeaders = {}\n  headers.forEach((value, name) => {\n    reqHeaders[name] = reqHeaders[name]\n      ? [].concat(reqHeaders[name]).concat(value)\n      : value\n  })\n  return reqHeaders\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(JSON.stringify(message), [channel.port2])\n  })\n}\n\nfunction delayPromise(cb, duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => resolve(cb()), duration)\n  })\n}\n\nfunction respondWithMock(clientMessage) {\n  return new Response(clientMessage.payload.body, {\n    ...clientMessage.payload,\n    headers: clientMessage.payload.headers,\n  })\n}\n\nfunction uuidv4() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0\n    const v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/App.tsx",
    "content": "import { Routes, Route } from 'react-router-dom'\nimport { Box, Center, VStack } from '@chakra-ui/react'\n\nimport { Login } from './features/auth/Login'\nimport { PrivateOutlet } from './utils/PrivateOutlet'\nimport { ProtectedComponent } from './features/auth/ProtectedComponent'\n\nfunction Hooray() {\n  return (\n    <Center h=\"500px\">\n      <VStack>\n        <Box>Hooray you logged in!</Box>\n        <Box>\n          <ProtectedComponent />\n        </Box>\n      </VStack>\n    </Center>\n  )\n}\n\nfunction App() {\n  return (\n    <Box>\n      <Routes>\n        <Route path=\"/login\" element={<Login />} />\n        <Route path=\"/\" element={<PrivateOutlet />}>\n          <Route index element={<Hooray />} />\n        </Route>\n      </Routes>\n    </Box>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/app/services/auth.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { RootState } from '../store'\n\nexport interface User {\n  first_name: string\n  last_name: string\n}\n\nexport interface UserResponse {\n  user: User\n  token: string\n}\n\nexport interface LoginRequest {\n  username: string\n  password: string\n}\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({\n    baseUrl: '/',\n    prepareHeaders: (headers, { getState }) => {\n      // By default, if we have a token in the store, let's use that for authenticated requests\n      const token = (getState() as RootState).auth.token\n      if (token) {\n        headers.set('authorization', `Bearer ${token}`)\n      }\n      return headers\n    },\n  }),\n  endpoints: (build) => ({\n    login: build.mutation<UserResponse, LoginRequest>({\n      query: (credentials) => ({\n        url: 'login',\n        method: 'POST',\n        body: credentials,\n      }),\n    }),\n    protected: build.mutation<{ message: string }, void>({\n      query: () => 'protected',\n    }),\n  }),\n})\n\nexport const { useLoginMutation, useProtectedMutation } = api\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/app/store.ts",
    "content": "import { configureStore } from '@reduxjs/toolkit'\nimport { api } from './services/auth'\nimport authReducer from '../features/auth/authSlice'\n\nexport const store = configureStore({\n  reducer: {\n    [api.reducerPath]: api.reducer,\n    auth: authReducer,\n  },\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(api.middleware),\n})\n\nexport type RootState = ReturnType<typeof store.getState>\nexport type AppDispatch = typeof store.dispatch\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/features/auth/Login.tsx",
    "content": "import {\n  Box,\n  Button,\n  Center,\n  Divider,\n  Input,\n  InputGroup,\n  InputRightElement,\n  useToast,\n  VStack,\n} from '@chakra-ui/react'\nimport * as React from 'react'\nimport { useDispatch } from 'react-redux'\nimport { useNavigate } from 'react-router-dom'\n\nimport type { LoginRequest } from '../../app/services/auth'\nimport { useLoginMutation } from '../../app/services/auth'\nimport { ProtectedComponent } from './ProtectedComponent'\n\nfunction PasswordInput({\n  name,\n  onChange,\n}: {\n  name: string\n  onChange: (event: React.ChangeEvent<HTMLInputElement>) => void\n}) {\n  const [show, setShow] = React.useState(false)\n  const handleClick = () => setShow(!show)\n\n  return (\n    <InputGroup size=\"md\">\n      <Input\n        pr=\"4.5rem\"\n        type={show ? 'text' : 'password'}\n        placeholder=\"Enter password\"\n        name={name}\n        onChange={onChange}\n      />\n      <InputRightElement width=\"4.5rem\">\n        <Button h=\"1.75rem\" size=\"sm\" onClick={handleClick}>\n          {show ? 'Hide' : 'Show'}\n        </Button>\n      </InputRightElement>\n    </InputGroup>\n  )\n}\n\nexport const Login = () => {\n  const dispatch = useDispatch()\n  const navigate = useNavigate()\n  const toast = useToast()\n\n  const [formState, setFormState] = React.useState<LoginRequest>({\n    username: '',\n    password: '',\n  })\n\n  const [login, { isLoading }] = useLoginMutation()\n\n  const handleChange = ({\n    target: { name, value },\n  }: React.ChangeEvent<HTMLInputElement>) =>\n    setFormState((prev) => ({ ...prev, [name]: value }))\n\n  return (\n    <Center h=\"500px\">\n      <VStack spacing=\"4\">\n        <Box>Hint: enter anything, or leave it blank and hit login</Box>\n        <InputGroup>\n          <Input\n            onChange={handleChange}\n            name=\"username\"\n            type=\"text\"\n            placeholder=\"Email\"\n          />\n        </InputGroup>\n\n        <InputGroup>\n          <PasswordInput onChange={handleChange} name=\"password\" />\n        </InputGroup>\n        <Button\n          width=\"100%\"\n          onClick={async () => {\n            try {\n              await login(formState).unwrap()\n              // Being that the result is handled in extraReducers in authSlice,\n              // we know that we're authenticated after this, so the user\n              // and token will be present in the store\n              navigate('/')\n            } catch (err) {\n              toast({\n                status: 'error',\n                title: 'Error',\n                description: 'Oh no, there was an error!',\n                isClosable: true,\n              })\n            }\n          }}\n          colorScheme=\"green\"\n          isLoading={isLoading}\n        >\n          Login\n        </Button>\n        <Divider />\n        <ProtectedComponent />\n      </VStack>\n    </Center>\n  )\n}\n\nexport default Login\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/features/auth/ProtectedComponent.tsx",
    "content": "import { Center, VStack, Box, Button } from '@chakra-ui/react'\nimport { useProtectedMutation } from '../../app/services/auth'\n\nexport function ProtectedComponent() {\n  const [attemptAccess, { data, error, isLoading }] = useProtectedMutation()\n\n  return (\n    <Center w=\"400px\">\n      <VStack>\n        <Box>\n          <Button onClick={() => attemptAccess()} isLoading={isLoading}>\n            Make an authenticated request\n          </Button>\n        </Box>\n        <Box>\n          {data ? (\n            <>\n              Data:\n              <pre>{JSON.stringify(data, null, 2)}</pre>\n            </>\n          ) : error ? (\n            <>\n              Error: <pre>{JSON.stringify(error, null, 2)}</pre>\n            </>\n          ) : null}\n        </Box>\n      </VStack>\n    </Center>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/features/auth/authSlice.tsx",
    "content": "import { createSlice } from '@reduxjs/toolkit'\nimport { api, User } from '../../app/services/auth'\nimport type { RootState } from '../../app/store'\n\ntype AuthState = {\n  user: User | null\n  token: string | null\n}\n\nconst slice = createSlice({\n  name: 'auth',\n  initialState: { user: null, token: null } as AuthState,\n  reducers: {},\n  extraReducers: (builder) => {\n    builder.addMatcher(\n      api.endpoints.login.matchFulfilled,\n      (state, { payload }) => {\n        state.token = payload.token\n        state.user = payload.user\n      },\n    )\n  },\n})\n\nexport default slice.reducer\n\nexport const selectCurrentUser = (state: RootState) => state.auth.user\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/hooks/store.ts",
    "content": "import { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'\nimport type { AppDispatch, RootState } from '../app/store'\n\nexport const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector\nexport const useAppDispatch = () => useDispatch<AppDispatch>()\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/hooks/useAuth.ts",
    "content": "import { useMemo } from 'react'\nimport { useSelector } from 'react-redux'\nimport { selectCurrentUser } from '../features/auth/authSlice'\n\nexport const useAuth = () => {\n  const user = useSelector(selectCurrentUser)\n\n  return useMemo(() => ({ user }), [user])\n}\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport { BrowserRouter } from 'react-router-dom'\nimport { ChakraProvider } from '@chakra-ui/react'\n\nimport App from './App'\nimport { store } from './app/store'\n\nimport { worker } from './mocks/browser'\nimport { Provider } from 'react-redux'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nworker.start({ quiet: true }).then(() =>\n  ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(\n    <React.StrictMode>\n      <Provider store={store}>\n        <ChakraProvider>\n          <BrowserRouter>\n            <App />\n          </BrowserRouter>\n        </ChakraProvider>\n      </Provider>\n    </React.StrictMode>,\n  ),\n)\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './handlers'\n\nexport const worker = setupWorker(...handlers)\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/mocks/handlers.ts",
    "content": "import { rest } from 'msw'\nimport { nanoid } from '@reduxjs/toolkit'\n\nconst token = nanoid()\n\nexport const handlers = [\n  rest.get('/protected', (req, res, ctx) => {\n    const headers = req.headers.all()\n    if (headers.authorization !== `Bearer ${token}`) {\n      return res(\n        ctx.json({\n          message: 'You shall not pass. Please login first.',\n        }),\n        ctx.status(401),\n      )\n    }\n    return res(\n      ctx.json({\n        message:\n          'Join us on the Reactiflux Discord server in #redux if you have any questions.',\n      }),\n    )\n  }),\n  rest.post('/login', (req, res, ctx) => {\n    return res(\n      ctx.delay(400),\n      ctx.json({\n        user: {\n          first_name: 'Test',\n          last_name: 'User',\n        },\n        token,\n      }),\n    )\n  }),\n]\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/src/utils/PrivateOutlet.tsx",
    "content": "import { Navigate, Outlet, useLocation } from 'react-router-dom'\nimport { useAuth } from '../hooks/useAuth'\n\nexport function PrivateOutlet() {\n  const auth = useAuth()\n  const location = useLocation()\n\n  return auth.user ? (\n    <Outlet />\n  ) : (\n    <Navigate to=\"/login\" state={{ from: location }} />\n  )\n}\n"
  },
  {
    "path": "examples/query/react/authentication-with-extrareducers/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/basic/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/basic\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"getting-started-basic\",\n  \"keywords\": [],\n  \"main\": \"src/index.tsx\",\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@testing-library/dom\": \"^10.4.0\",\n    \"@testing-library/react\": \"^16.1.0\",\n    \"@types/jest\": \"^26.0.23\",\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"msw\": \"^0.40.2\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"test\": \"react-scripts test --runInBand\"\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ]\n}\n"
  },
  {
    "path": "examples/query/react/basic/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"\n    />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <!--\n      manifest.json provides metadata used when your web app is added to the\n      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n\n  <body>\n    <noscript> You need to enable JavaScript to run this app. </noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/basic/src/App.test.tsx",
    "content": "import { rest } from 'msw'\nimport { screen } from '@testing-library/react'\n\nimport App from './App'\nimport { server } from './test/server'\nimport { renderWithProviders } from './test/test-utils'\n\ndescribe('App', () => {\n  it('handles good response', async () => {\n    renderWithProviders(<App />)\n\n    screen.getByText('Loading...')\n\n    await screen.findByRole('heading', { name: /bulbasaur/i })\n\n    const img = screen.getByRole('img', {\n      name: /bulbasaur/i,\n    }) as HTMLImageElement\n\n    expect(img.src).toBe(\n      'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/1.png',\n    )\n  })\n\n  it('handles error response', async () => {\n    // force msw to return error response\n    server.use(\n      rest.get(\n        'https://pokeapi.co/api/v2/pokemon/bulbasaur',\n        (req, res, ctx) => {\n          return res(ctx.status(500))\n        },\n      ),\n    )\n\n    renderWithProviders(<App />)\n\n    screen.getByText('Loading...')\n\n    await screen.findByText('Oh no, there was an error')\n  })\n})\n"
  },
  {
    "path": "examples/query/react/basic/src/App.tsx",
    "content": "import './styles.css'\nimport { useGetPokemonByNameQuery } from './services/pokemon'\n\nexport default function App() {\n  const { data, error, isLoading } = useGetPokemonByNameQuery('bulbasaur')\n\n  return (\n    <div className=\"App\">\n      {error ? (\n        <>Oh no, there was an error</>\n      ) : isLoading ? (\n        <>Loading...</>\n      ) : data ? (\n        <>\n          <h3>{data.species.name}</h3>\n          <img src={data.sprites.front_shiny} alt={data.species.name} />\n        </>\n      ) : null}\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/basic/src/index.tsx",
    "content": "import ReactDOM from 'react-dom/client'\nimport { Provider } from 'react-redux'\n\nimport App from './App'\nimport { setupStore } from './store'\n\nconst store = setupStore()\n\nconst reactRoot = ReactDOM.createRoot(\n  document.getElementById('root') as HTMLElement,\n)\nreactRoot.render(\n  <Provider store={store}>\n    <App />\n  </Provider>,\n)\n"
  },
  {
    "path": "examples/query/react/basic/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/basic/src/services/pokemon.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const pokemonApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  tagTypes: [],\n  endpoints: (build) => ({\n    getPokemonByName: build.query({\n      query: (name: string) => `pokemon/${name}`,\n    }),\n  }),\n})\n\n// Export hooks for usage in functional components\nexport const { useGetPokemonByNameQuery } = pokemonApi\n"
  },
  {
    "path": "examples/query/react/basic/src/setupTests.ts",
    "content": "import { server } from './test/server'\n\n// make debug output for TestingLibrary Errors larger\nprocess.env.DEBUG_PRINT_LIMIT = '15000'\n\n// enable API mocking in test runs using the same request handlers\n// as for the client-side mocking.\nbeforeAll(() => server.listen({ onUnhandledRequest: 'error' }))\nafterAll(() => server.close())\nafterEach(() => server.resetHandlers())\n"
  },
  {
    "path": "examples/query/react/basic/src/store.ts",
    "content": "import { combineReducers, configureStore } from '@reduxjs/toolkit'\nimport type { PreloadedState } from '@reduxjs/toolkit'\nimport { pokemonApi } from './services/pokemon'\n\nconst rootReducer = combineReducers({\n  [pokemonApi.reducerPath]: pokemonApi.reducer,\n})\n\nexport const setupStore = (preloadedState?: PreloadedState<RootState>) => {\n  return configureStore({\n    reducer: rootReducer,\n    middleware: (getDefaultMiddleware) =>\n      // adding the api middleware enables caching, invalidation, polling and other features of `rtk-query`\n      getDefaultMiddleware().concat(pokemonApi.middleware),\n    preloadedState,\n  })\n}\n\nexport type RootState = ReturnType<typeof rootReducer>\nexport type AppStore = ReturnType<typeof setupStore>\nexport type AppDispatch = AppStore['dispatch']\n"
  },
  {
    "path": "examples/query/react/basic/src/styles.css",
    "content": ".App {\n  font-family: sans-serif;\n  text-align: center;\n}\n"
  },
  {
    "path": "examples/query/react/basic/src/test/server/index.ts",
    "content": "import { setupServer } from 'msw/node'\nimport { handlers } from './serverHandlers'\n\nconst server = setupServer(...handlers)\n\nexport { server }\n"
  },
  {
    "path": "examples/query/react/basic/src/test/server/serverHandlers.ts",
    "content": "import { rest } from 'msw'\n\nconst handlers = [\n  rest.get('https://pokeapi.co/api/v2/pokemon/bulbasaur', (req, res, ctx) => {\n    const mockApiResponse = {\n      species: {\n        name: 'bulbasaur',\n      },\n      sprites: {\n        front_shiny:\n          'https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/shiny/1.png',\n      },\n    }\n    return res(ctx.json(mockApiResponse))\n  }),\n]\n\nexport { handlers }\n"
  },
  {
    "path": "examples/query/react/basic/src/test/test-utils.tsx",
    "content": "import { render } from '@testing-library/react'\nimport type { RenderOptions } from '@testing-library/react'\nimport type React from 'react'\nimport type { PropsWithChildren, JSX } from 'react'\nimport { Provider } from 'react-redux'\nimport { setupStore } from '../store'\nimport type { AppStore, RootState } from '../store'\nimport type { PreloadedState } from '@reduxjs/toolkit'\n\n// This type interface extends the default options for render from RTL, as well\n// as allows the user to specify other things such as initialState, store. For\n// future dependencies, such as wanting to test with react-router, you can extend\n// this interface to accept a path and route and use those in a <MemoryRouter />\ninterface ExtendedRenderOptions extends Omit<RenderOptions, 'queries'> {\n  preloadedState?: PreloadedState<RootState>\n  store?: AppStore\n}\n\nfunction renderWithProviders(\n  ui: React.ReactElement,\n  {\n    preloadedState = {},\n    store = setupStore(preloadedState),\n    ...renderOptions\n  }: ExtendedRenderOptions = {},\n) {\n  function Wrapper({ children }: PropsWithChildren<{}>): JSX.Element {\n    return <Provider store={store}>{children}</Provider>\n  }\n  return { store, ...render(ui, { wrapper: Wrapper, ...renderOptions }) }\n}\n\nexport { renderWithProviders }\n"
  },
  {
    "path": "examples/query/react/basic/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/conditional-fetching/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/conditional-fetching\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"src/index.tsx\",\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\"\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ]\n}\n"
  },
  {
    "path": "examples/query/react/conditional-fetching/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"\n    />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <!--\n      manifest.json provides metadata used when your web app is added to the\n      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n\n  <body>\n    <noscript> You need to enable JavaScript to run this app. </noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/conditional-fetching/src/App.tsx",
    "content": "import * as React from 'react'\nimport { Pokemon } from './Pokemon'\nimport { PokemonName, POKEMON_NAMES } from './pokemon.data'\nimport './styles.css'\n\nconst getRandomPokemonName = () =>\n  POKEMON_NAMES[Math.floor(Math.random() * POKEMON_NAMES.length)]\n\nexport default function App() {\n  const [pokemon, setPokemon] = React.useState<PokemonName[]>(['bulbasaur'])\n\n  return (\n    <div className=\"App\">\n      <div>\n        <button\n          onClick={() =>\n            setPokemon((prev) => [...prev, getRandomPokemonName()])\n          }\n        >\n          Add random pokemon\n        </button>\n        <button onClick={() => setPokemon((prev) => [...prev, 'bulbasaur'])}>\n          Add bulbasaur\n        </button>\n      </div>\n\n      {pokemon.map((name, index) => (\n        <Pokemon key={index} name={name} />\n      ))}\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/conditional-fetching/src/Pokemon.tsx",
    "content": "import * as React from 'react'\nimport { useGetPokemonByNameQuery } from './services/pokemon'\nimport type { PokemonName } from './pokemon.data'\n\nexport const Pokemon = ({ name }: { name: PokemonName }) => {\n  const [skip, setSkip] = React.useState(true)\n  const { data, error, isLoading, isUninitialized } = useGetPokemonByNameQuery(\n    name,\n    {\n      skip,\n    },\n  )\n\n  const SkipToggle = () => (\n    <button onClick={() => setSkip((prev) => !prev)}>\n      Toggle Skip ({String(skip)})\n    </button>\n  )\n\n  return (\n    <>\n      {error ? (\n        <>Oh no, there was an error</>\n      ) : isUninitialized ? (\n        <div>\n          {name} - Currently skipped - <SkipToggle />\n        </div>\n      ) : isLoading ? (\n        <>loading...</>\n      ) : data ? (\n        <>\n          <div>\n            <h3>{data.species.name}</h3>\n            <img src={data.sprites.front_shiny} alt={data.species.name} />\n          </div>\n          <SkipToggle />\n        </>\n      ) : null}\n    </>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/conditional-fetching/src/index.tsx",
    "content": "import ReactDOM from 'react-dom/client'\nimport { Provider } from 'react-redux'\n\nimport App from './App'\nimport { store } from './store'\n\nconst reactRoot = ReactDOM.createRoot(\n  document.getElementById('root') as HTMLElement,\n)\nreactRoot.render(\n  <Provider store={store}>\n    <App />\n  </Provider>,\n)\n"
  },
  {
    "path": "examples/query/react/conditional-fetching/src/pokemon.data.ts",
    "content": "export const POKEMON_NAMES = [\n  'bulbasaur',\n  'ivysaur',\n  'venusaur',\n  'charmander',\n  'charmeleon',\n  'charizard',\n  'squirtle',\n  'wartortle',\n  'blastoise',\n  'caterpie',\n  'metapod',\n  'butterfree',\n  'weedle',\n  'kakuna',\n  'beedrill',\n  'pidgey',\n  'pidgeotto',\n  'pidgeot',\n  'rattata',\n  'raticate',\n  'spearow',\n  'fearow',\n  'ekans',\n  'arbok',\n  'pikachu',\n  'raichu',\n  'sandshrew',\n  'sandslash',\n  'nidoran',\n  'nidorina',\n  'nidoqueen',\n  'nidoran',\n  'nidorino',\n  'nidoking',\n  'clefairy',\n  'clefable',\n  'vulpix',\n  'ninetales',\n  'jigglypuff',\n  'wigglytuff',\n  'zubat',\n  'golbat',\n  'oddish',\n  'gloom',\n  'vileplume',\n  'paras',\n  'parasect',\n  'venonat',\n  'venomoth',\n  'diglett',\n  'dugtrio',\n  'meowth',\n  'persian',\n  'psyduck',\n  'golduck',\n  'mankey',\n  'primeape',\n  'growlithe',\n  'arcanine',\n  'poliwag',\n  'poliwhirl',\n  'poliwrath',\n  'abra',\n  'kadabra',\n  'alakazam',\n  'machop',\n  'machoke',\n  'machamp',\n  'bellsprout',\n  'weepinbell',\n  'victreebel',\n  'tentacool',\n  'tentacruel',\n  'geodude',\n  'graveler',\n  'golem',\n  'ponyta',\n  'rapidash',\n  'slowpoke',\n  'slowbro',\n  'magnemite',\n  'magneton',\n  \"farfetch'd\",\n  'doduo',\n  'dodrio',\n  'seel',\n  'dewgong',\n  'grimer',\n  'muk',\n  'shellder',\n  'cloyster',\n  'gastly',\n  'haunter',\n  'gengar',\n  'onix',\n  'drowzee',\n  'hypno',\n  'krabby',\n  'kingler',\n  'voltorb',\n  'electrode',\n  'exeggcute',\n  'exeggutor',\n  'cubone',\n  'marowak',\n  'hitmonlee',\n  'hitmonchan',\n  'lickitung',\n  'koffing',\n  'weezing',\n  'rhyhorn',\n  'rhydon',\n  'chansey',\n  'tangela',\n  'kangaskhan',\n  'horsea',\n  'seadra',\n  'goldeen',\n  'seaking',\n  'staryu',\n  'starmie',\n  'mr. mime',\n  'scyther',\n  'jynx',\n  'electabuzz',\n  'magmar',\n  'pinsir',\n  'tauros',\n  'magikarp',\n  'gyarados',\n  'lapras',\n  'ditto',\n  'eevee',\n  'vaporeon',\n  'jolteon',\n  'flareon',\n  'porygon',\n  'omanyte',\n  'omastar',\n  'kabuto',\n  'kabutops',\n  'aerodactyl',\n  'snorlax',\n  'articuno',\n  'zapdos',\n  'moltres',\n  'dratini',\n  'dragonair',\n  'dragonite',\n  'mewtwo',\n  'mew',\n] as const\n\nexport type PokemonName = (typeof POKEMON_NAMES)[number]\n"
  },
  {
    "path": "examples/query/react/conditional-fetching/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/conditional-fetching/src/services/pokemon.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { PokemonName } from '../pokemon.data'\n\nexport const pokemonApi = createApi({\n  reducerPath: 'pokemonApi',\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (build) => ({\n    getPokemonByName: build.query({\n      query: (name: PokemonName) => `pokemon/${name}`,\n    }),\n  }),\n})\n\n// Export hooks for usage in functional components\nexport const { useGetPokemonByNameQuery } = pokemonApi\n"
  },
  {
    "path": "examples/query/react/conditional-fetching/src/store.ts",
    "content": "import { configureStore } from '@reduxjs/toolkit'\nimport { pokemonApi } from './services/pokemon'\n\nexport const store = configureStore({\n  reducer: {\n    [pokemonApi.reducerPath]: pokemonApi.reducer,\n  },\n  // adding the api middleware enables caching, invalidation, polling and other features of `rtk-query`\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(pokemonApi.middleware),\n})\n"
  },
  {
    "path": "examples/query/react/conditional-fetching/src/styles.css",
    "content": ".App {\n  font-family: sans-serif;\n  text-align: center;\n}\n"
  },
  {
    "path": "examples/query/react/conditional-fetching/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/deduping-queries/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/deduping-queries\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"src/index.tsx\",\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\"\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ]\n}\n"
  },
  {
    "path": "examples/query/react/deduping-queries/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"\n    />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <!--\n      manifest.json provides metadata used when your web app is added to the\n      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n\n  <body>\n    <noscript> You need to enable JavaScript to run this app. </noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/deduping-queries/src/App.tsx",
    "content": "import * as React from 'react'\nimport { Pokemon } from './Pokemon'\n\nexport default function App() {\n  const [pokemon, setPokemon] = React.useState<string[]>(['bulbasaur'])\n\n  React.useEffect(() => {\n    // Add a duplicate of bulbasaur - notice there is no second request?\n    setTimeout(() => {\n      setPokemon((prev) => [...prev, 'bulbasaur'])\n    }, 1500)\n\n    // Add a pokemon that doesn't exist in the cache, will generate a network request\n    setTimeout(() => {\n      setPokemon((prev) => [...prev, 'pikachu'])\n    }, 2000)\n  }, [])\n\n  return (\n    <div className=\"App\">\n      <div>\n        <button onClick={() => setPokemon((prev) => [...prev, 'bulbasaur'])}>\n          Add bulbasaur\n        </button>\n      </div>\n      {pokemon.map((name, index) => (\n        <Pokemon key={index} name={name} />\n      ))}\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/deduping-queries/src/Pokemon.tsx",
    "content": "import { useGetPokemonByNameQuery } from './services/pokemon'\n\nexport const Pokemon = ({ name }: { name: string }) => {\n  const { data, error, isLoading, isFetching, refetch } =\n    useGetPokemonByNameQuery(name)\n\n  return (\n    <div style={{ float: 'left', textAlign: 'center' }}>\n      {error ? (\n        <>Oh no, there was an error</>\n      ) : isLoading ? (\n        <>Loading...</>\n      ) : data ? (\n        <>\n          <h3>{data.species.name}</h3>\n          <div>\n            <img src={data.sprites.front_shiny} alt={data.species.name} />\n          </div>\n          <div>\n            <button onClick={refetch} disabled={isFetching}>\n              {isFetching ? 'Fetching...' : 'Refetch'}\n            </button>\n          </div>\n        </>\n      ) : (\n        'No Data'\n      )}\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/deduping-queries/src/index.tsx",
    "content": "import ReactDOM from 'react-dom/client'\nimport { Provider } from 'react-redux'\n\nimport App from './App'\nimport { store } from './store'\n\nconst reactRoot = ReactDOM.createRoot(\n  document.getElementById('root') as HTMLElement,\n)\n\nreactRoot.render(\n  <Provider store={store}>\n    <App />\n  </Provider>,\n)\n"
  },
  {
    "path": "examples/query/react/deduping-queries/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/deduping-queries/src/services/pokemon.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const pokemonApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (build) => ({\n    getPokemonByName: build.query({\n      query: (name: string) => `pokemon/${name}`,\n    }),\n  }),\n})\n\n// Export hooks for usage in functional components\nexport const { useGetPokemonByNameQuery } = pokemonApi\n"
  },
  {
    "path": "examples/query/react/deduping-queries/src/store.ts",
    "content": "import { configureStore } from '@reduxjs/toolkit'\nimport { pokemonApi } from './services/pokemon'\n\nexport const store = configureStore({\n  reducer: {\n    [pokemonApi.reducerPath]: pokemonApi.reducer,\n  },\n  // adding the api middleware enables caching, invalidation, polling and other features of `rtk-query`\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(pokemonApi.middleware),\n})\n"
  },
  {
    "path": "examples/query/react/deduping-queries/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/graphql/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/graphql\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"./src/index.tsx\",\n  \"dependencies\": {\n    \"@chakra-ui/react\": \"2.10.7\",\n    \"@emotion/react\": \"^11.4.0\",\n    \"@emotion/styled\": \"^11.3.0\",\n    \"@mswjs/data\": \"^0.3.0\",\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"@rtk-query/graphql-request-base-query\": \"^2.0.0\",\n    \"faker\": \"^5.5.3\",\n    \"framer-motion\": \"^2.9.5\",\n    \"graphql\": \"^15.5.0\",\n    \"graphql-request\": \"^3.4.0\",\n    \"msw\": \"0.40.2\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-icons\": \"3.11.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-router-dom\": \"6.3.0\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/faker\": \"^5.5.5\",\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"prebuild\": \"rimraf dist/\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ],\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/graphql/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/graphql/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query Pagination Example\",\n  \"name\": \"Pagination Demo\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/graphql/public/mockServiceWorker.js",
    "content": "/* eslint-disable */\n/* tslint:disable */\n\n/**\n * Mock Service Worker (0.30.1).\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n\nconst INTEGRITY_CHECKSUM = '82ef9b96d8393b6da34527d1d6e19187'\nconst bypassHeaderName = 'x-msw-bypass'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  return self.skipWaiting()\n})\n\nself.addEventListener('activate', async function (event) {\n  return self.clients.claim()\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\n// Resolve the \"master\" client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMasterClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMasterClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: serializeHeaders(clonedResponse.headers),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const requestClone = request.clone()\n  const getOriginalResponse = () => fetch(requestClone)\n\n  // Bypass mocking when the request client is not active.\n  if (!client) {\n    return getOriginalResponse()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return await getOriginalResponse()\n  }\n\n  // Bypass requests with the explicit bypass header\n  if (requestClone.headers.get(bypassHeaderName) === 'true') {\n    const cleanRequestHeaders = serializeHeaders(requestClone.headers)\n\n    // Remove the bypass header to comply with the CORS preflight check.\n    delete cleanRequestHeaders[bypassHeaderName]\n\n    const originalRequest = new Request(requestClone, {\n      headers: new Headers(cleanRequestHeaders),\n    })\n\n    return fetch(originalRequest)\n  }\n\n  // Send the request to the client-side MSW.\n  const reqHeaders = serializeHeaders(request.headers)\n  const body = await request.text()\n\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: reqHeaders,\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body,\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_SUCCESS': {\n      return delayPromise(\n        () => respondWithMock(clientMessage),\n        clientMessage.payload.delay,\n      )\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return getOriginalResponse()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.payload\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a request Promise emulates a network error.\n      throw networkError\n    }\n\n    case 'INTERNAL_ERROR': {\n      const parsedBody = JSON.parse(clientMessage.payload.body)\n\n      console.error(\n        `\\\n[MSW] Request handler function for \"%s %s\" has thrown the following exception:\n\n${parsedBody.errorType}: ${parsedBody.message}\n(see more detailed error stack trace in the mocked response body)\n\nThis exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error.\nIf you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\\\n`,\n        request.method,\n        request.url,\n      )\n\n      return respondWithMock(clientMessage)\n    }\n  }\n\n  return getOriginalResponse()\n}\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  const requestId = uuidv4()\n\n  return event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      console.error(\n        '[MSW] Failed to mock a \"%s\" request to \"%s\": %s',\n        request.method,\n        request.url,\n        error,\n      )\n    }),\n  )\n})\n\nfunction serializeHeaders(headers) {\n  const reqHeaders = {}\n  headers.forEach((value, name) => {\n    reqHeaders[name] = reqHeaders[name]\n      ? [].concat(reqHeaders[name]).concat(value)\n      : value\n  })\n  return reqHeaders\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(JSON.stringify(message), [channel.port2])\n  })\n}\n\nfunction delayPromise(cb, duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => resolve(cb()), duration)\n  })\n}\n\nfunction respondWithMock(clientMessage) {\n  return new Response(clientMessage.payload.body, {\n    ...clientMessage.payload,\n    headers: clientMessage.payload.headers,\n  })\n}\n\nfunction uuidv4() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0\n    const v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n"
  },
  {
    "path": "examples/query/react/graphql/src/App.tsx",
    "content": "import { Route, Routes } from 'react-router-dom'\nimport { PostsManager } from './features/posts/PostsManager'\n\nfunction App() {\n  return (\n    <Routes>\n      <Route path=\"/\" element={<PostsManager />} />\n    </Routes>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/graphql/src/app/services/posts.ts",
    "content": "import { createApi } from '@reduxjs/toolkit/query/react'\nimport { gql } from 'graphql-request'\nimport { graphqlRequestBaseQuery } from '@rtk-query/graphql-request-base-query'\n\nexport const postStatuses = ['draft', 'published', 'pending_review'] as const\n\nexport interface Post {\n  id: string\n  title: string\n  author: string\n  content: string\n  status: (typeof postStatuses)[number]\n  created_at: string\n  updated_at: string\n}\n\nexport interface Pagination {\n  page: number\n  per_page: number\n  total: number\n  total_pages: number\n}\n\nexport interface GetPostsResponse extends Pagination {\n  data: {\n    posts: Post[]\n  }\n}\n\ninterface PostResponse {\n  data: {\n    post: Post\n  }\n}\n\nexport const api = createApi({\n  baseQuery: graphqlRequestBaseQuery({\n    url: '/graphql',\n  }),\n  endpoints: (builder) => ({\n    getPosts: builder.query<\n      GetPostsResponse,\n      { page?: number; per_page?: number }\n    >({\n      query: ({ page, per_page }) => ({\n        document: gql`\n          query GetPosts($page: Int = 1, $per_page: Int = 10) {\n            posts(page: $page, per_page: $per_page) {\n              id\n              title\n            }\n          }\n        `,\n        variables: {\n          page,\n          per_page,\n        },\n      }),\n    }),\n    getPost: builder.query<Post, string>({\n      query: (id) => ({\n        document: gql`\n        query GetPost($id: ID!) {\n          post(id: ${id}) {\n            id\n            title\n            body\n          }\n        }\n        `,\n      }),\n      transformResponse: (response: PostResponse) => response.data.post,\n    }),\n  }),\n})\n\nexport const { useGetPostsQuery, useGetPostQuery } = api\n"
  },
  {
    "path": "examples/query/react/graphql/src/features/posts/PostsManager.tsx",
    "content": "import * as React from 'react'\nimport {\n  Badge,\n  Box,\n  Button,\n  Divider,\n  Flex,\n  Heading,\n  HStack,\n  Icon,\n  List,\n  ListIcon,\n  ListItem,\n  Spacer,\n  Stat,\n  StatLabel,\n  StatNumber,\n} from '@chakra-ui/react'\nimport { MdArrowBack, MdArrowForward, MdBook } from 'react-icons/md'\nimport { Post, useGetPostsQuery } from '../../app/services/posts'\n\nconst getColorForStatus = (status: Post['status']) => {\n  return status === 'draft'\n    ? 'gray'\n    : status === 'pending_review'\n      ? 'orange'\n      : 'green'\n}\n\nconst PostList = () => {\n  const [page, setPage] = React.useState(1)\n  const { data: posts, isLoading, isFetching } = useGetPostsQuery({ page })\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts?.data) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <Box>\n      <HStack spacing=\"14px\">\n        <Button\n          onClick={() => setPage((prev) => prev - 1)}\n          isLoading={isFetching}\n          disabled={page === 1}\n        >\n          <Icon as={MdArrowBack} />\n        </Button>\n        <Button\n          onClick={() => setPage((prev) => prev + 1)}\n          isLoading={isFetching}\n          disabled={page === posts.total_pages}\n        >\n          <Icon as={MdArrowForward} />\n        </Button>\n        <Box>{`${page} / ${posts.total_pages}`}</Box>\n      </HStack>\n      <List spacing={3} mt={6}>\n        {posts?.data.posts.map(({ id, title, status }) => (\n          <ListItem key={id}>\n            <ListIcon as={MdBook} color=\"green.500\" /> {title}{' '}\n            <Badge\n              ml=\"1\"\n              fontSize=\"0.8em\"\n              colorScheme={getColorForStatus(status)}\n            >\n              {status}\n            </Badge>\n          </ListItem>\n        ))}\n      </List>\n    </Box>\n  )\n}\n\nexport const PostsCountStat = () => {\n  const { data: posts } = useGetPostsQuery({})\n\n  return (\n    <Stat>\n      <StatLabel>Total Posts</StatLabel>\n      <StatNumber>{`${posts?.total || 'NA'}`}</StatNumber>\n    </Stat>\n  )\n}\n\nexport const PostsManager = () => {\n  return (\n    <Box>\n      <Flex wrap=\"wrap\" bg=\"#011627\" p={4} color=\"white\">\n        <Box>\n          <Heading size=\"xl\">Manage Posts</Heading>\n        </Box>\n        <Spacer />\n        <Box>\n          <PostsCountStat />\n        </Box>\n      </Flex>\n      <Divider />\n      <Box p={4}>\n        <PostList />\n      </Box>\n    </Box>\n  )\n}\n\nexport default PostsManager\n"
  },
  {
    "path": "examples/query/react/graphql/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport { api } from './app/services/posts'\nimport { ChakraProvider } from '@chakra-ui/react'\n\nimport { BrowserRouter } from 'react-router-dom'\nimport { worker } from './mocks/browser'\nimport { ApiProvider } from '@reduxjs/toolkit/query/react'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nworker.start({ quiet: true }).then(() => {\n  return ReactDOM.createRoot(\n    document.getElementById('root') as HTMLElement,\n  ).render(\n    <React.StrictMode>\n      <ApiProvider api={api}>\n        <ChakraProvider>\n          <BrowserRouter>\n            <App />\n          </BrowserRouter>\n        </ChakraProvider>\n      </ApiProvider>\n    </React.StrictMode>,\n  )\n})\n"
  },
  {
    "path": "examples/query/react/graphql/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './db'\n\nexport const worker = setupWorker(...handlers)\n"
  },
  {
    "path": "examples/query/react/graphql/src/mocks/db.ts",
    "content": "import { nanoid } from '@reduxjs/toolkit'\nimport { factory, primaryKey } from '@mswjs/data'\nimport faker from 'faker'\nimport { graphql } from 'msw'\nimport { postStatuses } from '../app/services/posts'\nimport type { Pagination, Post } from '../app/services/posts'\n\nconst db = factory({\n  post: {\n    id: primaryKey(String),\n    name: String,\n    title: String,\n    author: String,\n    content: String,\n    status: String,\n    created_at: String,\n    updated_at: String,\n  },\n})\n\nconst getRandomStatus = () =>\n  postStatuses[Math.floor(Math.random() * postStatuses.length)]\n\nconst createPostData = (): Post => {\n  const date = faker.date.past().toISOString()\n  return {\n    id: nanoid(),\n    title: faker.lorem.words(),\n    author: faker.name.findName(),\n    content: faker.lorem.paragraphs(),\n    status: getRandomStatus(),\n    created_at: date,\n    updated_at: date,\n  }\n}\n\n;[...new Array(50)].forEach((_) => db.post.create(createPostData()))\n\ntype PaginationOptions = {\n  page: number\n  per_page: number\n}\n\ninterface Posts extends Pagination {\n  data: {\n    posts: Post[]\n  }\n}\n\nexport const handlers = [\n  graphql.query<Posts, PaginationOptions>('GetPosts', (req, res, ctx) => {\n    const { page = 1, per_page = 10 } = req.variables\n\n    const posts = db.post.findMany({\n      take: per_page,\n      skip: Math.max(per_page * (page - 1), 0),\n    })\n\n    return res(\n      ctx.data({\n        data: {\n          posts,\n        } as { posts: Post[] },\n        per_page,\n        page,\n        total_pages: Math.ceil(db.post.count() / per_page),\n        total: db.post.count(),\n      }),\n    )\n  }),\n  ...db.post.toHandlers('graphql'),\n] as const\n"
  },
  {
    "path": "examples/query/react/graphql/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/graphql/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/.introspection.json",
    "content": "{\n  \"__schema\": {\n    \"queryType\": {\n      \"name\": \"Query\"\n    },\n    \"mutationType\": {\n      \"name\": \"Mutation\"\n    },\n    \"subscriptionType\": null,\n    \"types\": [\n      {\n        \"kind\": \"INPUT_OBJECT\",\n        \"name\": \"IdQueryType\",\n        \"description\": null,\n        \"fields\": null,\n        \"inputFields\": [\n          {\n            \"name\": \"equals\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"ID\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"notEquals\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"ID\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"contains\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"ID\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"notContains\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"ID\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"in\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"ID\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"notIn\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"ID\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"interfaces\": null,\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"SCALAR\",\n        \"name\": \"ID\",\n        \"description\": \"The `ID` scalar type represents a unique identifier, often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `\\\"4\\\"`) or integer (such as `4`) input value will be accepted as an ID.\",\n        \"fields\": null,\n        \"inputFields\": null,\n        \"interfaces\": null,\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"OBJECT\",\n        \"name\": \"Mutation\",\n        \"description\": null,\n        \"fields\": [\n          {\n            \"name\": \"createPost\",\n            \"description\": null,\n            \"args\": [\n              {\n                \"name\": \"data\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"INPUT_OBJECT\",\n                  \"name\": \"PostInput\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              }\n            ],\n            \"type\": {\n              \"kind\": \"OBJECT\",\n              \"name\": \"Post\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"updatePost\",\n            \"description\": null,\n            \"args\": [\n              {\n                \"name\": \"where\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"INPUT_OBJECT\",\n                  \"name\": \"PostQueryInput\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              },\n              {\n                \"name\": \"data\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"INPUT_OBJECT\",\n                  \"name\": \"PostInput\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              }\n            ],\n            \"type\": {\n              \"kind\": \"OBJECT\",\n              \"name\": \"Post\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"updatePosts\",\n            \"description\": null,\n            \"args\": [\n              {\n                \"name\": \"where\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"INPUT_OBJECT\",\n                  \"name\": \"PostQueryInput\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              },\n              {\n                \"name\": \"data\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"INPUT_OBJECT\",\n                  \"name\": \"PostInput\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              }\n            ],\n            \"type\": {\n              \"kind\": \"LIST\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"OBJECT\",\n                \"name\": \"Post\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"deletePost\",\n            \"description\": null,\n            \"args\": [\n              {\n                \"name\": \"where\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"INPUT_OBJECT\",\n                  \"name\": \"PostQueryInput\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              }\n            ],\n            \"type\": {\n              \"kind\": \"OBJECT\",\n              \"name\": \"Post\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"deletePosts\",\n            \"description\": null,\n            \"args\": [\n              {\n                \"name\": \"where\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"INPUT_OBJECT\",\n                  \"name\": \"PostQueryInput\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              }\n            ],\n            \"type\": {\n              \"kind\": \"LIST\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"OBJECT\",\n                \"name\": \"Post\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"inputFields\": null,\n        \"interfaces\": [],\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"OBJECT\",\n        \"name\": \"Post\",\n        \"description\": null,\n        \"fields\": [\n          {\n            \"name\": \"id\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"ID\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"name\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"title\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"author\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"content\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"status\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"created_at\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"updated_at\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"inputFields\": null,\n        \"interfaces\": [],\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"SCALAR\",\n        \"name\": \"String\",\n        \"description\": \"The `String` scalar type represents textual data, represented as UTF-8 character sequences. The String type is most often used by GraphQL to represent free-form human-readable text.\",\n        \"fields\": null,\n        \"inputFields\": null,\n        \"interfaces\": null,\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"INPUT_OBJECT\",\n        \"name\": \"PostInput\",\n        \"description\": null,\n        \"fields\": null,\n        \"inputFields\": [\n          {\n            \"name\": \"id\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"ID\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"name\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"title\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"author\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"content\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"status\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"created_at\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"updated_at\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"interfaces\": null,\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"INPUT_OBJECT\",\n        \"name\": \"PostQueryInput\",\n        \"description\": null,\n        \"fields\": null,\n        \"inputFields\": [\n          {\n            \"name\": \"id\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"INPUT_OBJECT\",\n              \"name\": \"IdQueryType\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"name\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"INPUT_OBJECT\",\n              \"name\": \"StringQueryType\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"title\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"INPUT_OBJECT\",\n              \"name\": \"StringQueryType\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"author\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"INPUT_OBJECT\",\n              \"name\": \"StringQueryType\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"content\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"INPUT_OBJECT\",\n              \"name\": \"StringQueryType\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"status\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"INPUT_OBJECT\",\n              \"name\": \"StringQueryType\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"created_at\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"INPUT_OBJECT\",\n              \"name\": \"StringQueryType\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"updated_at\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"INPUT_OBJECT\",\n              \"name\": \"StringQueryType\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"interfaces\": null,\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"OBJECT\",\n        \"name\": \"Query\",\n        \"description\": null,\n        \"fields\": [\n          {\n            \"name\": \"post\",\n            \"description\": null,\n            \"args\": [\n              {\n                \"name\": \"where\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"INPUT_OBJECT\",\n                  \"name\": \"PostQueryInput\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              }\n            ],\n            \"type\": {\n              \"kind\": \"OBJECT\",\n              \"name\": \"Post\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"posts\",\n            \"description\": null,\n            \"args\": [\n              {\n                \"name\": \"take\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"SCALAR\",\n                  \"name\": \"Int\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              },\n              {\n                \"name\": \"skip\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"SCALAR\",\n                  \"name\": \"Int\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              },\n              {\n                \"name\": \"cursor\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"SCALAR\",\n                  \"name\": \"ID\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              },\n              {\n                \"name\": \"where\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"INPUT_OBJECT\",\n                  \"name\": \"PostQueryInput\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": null,\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              }\n            ],\n            \"type\": {\n              \"kind\": \"LIST\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"OBJECT\",\n                \"name\": \"Post\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"inputFields\": null,\n        \"interfaces\": [],\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"SCALAR\",\n        \"name\": \"Int\",\n        \"description\": \"The `Int` scalar type represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1.\",\n        \"fields\": null,\n        \"inputFields\": null,\n        \"interfaces\": null,\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"INPUT_OBJECT\",\n        \"name\": \"StringQueryType\",\n        \"description\": null,\n        \"fields\": null,\n        \"inputFields\": [\n          {\n            \"name\": \"equals\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"notEquals\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"contains\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"notContains\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"in\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"notIn\",\n            \"description\": null,\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"interfaces\": null,\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"SCALAR\",\n        \"name\": \"Boolean\",\n        \"description\": \"The `Boolean` scalar type represents `true` or `false`.\",\n        \"fields\": null,\n        \"inputFields\": null,\n        \"interfaces\": null,\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"OBJECT\",\n        \"name\": \"__Schema\",\n        \"description\": \"A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all available types and directives on the server, as well as the entry points for query, mutation, and subscription operations.\",\n        \"fields\": [\n          {\n            \"name\": \"description\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"types\",\n            \"description\": \"A list of all types supported by this server.\",\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"LIST\",\n                \"name\": null,\n                \"ofType\": {\n                  \"kind\": \"NON_NULL\",\n                  \"name\": null,\n                  \"ofType\": {\n                    \"kind\": \"OBJECT\",\n                    \"name\": \"__Type\",\n                    \"ofType\": null\n                  }\n                }\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"queryType\",\n            \"description\": \"The type that query operations will be rooted at.\",\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"OBJECT\",\n                \"name\": \"__Type\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"mutationType\",\n            \"description\": \"If this server supports mutation, the type that mutation operations will be rooted at.\",\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"OBJECT\",\n              \"name\": \"__Type\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"subscriptionType\",\n            \"description\": \"If this server support subscription, the type that subscription operations will be rooted at.\",\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"OBJECT\",\n              \"name\": \"__Type\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"directives\",\n            \"description\": \"A list of all directives supported by this server.\",\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"LIST\",\n                \"name\": null,\n                \"ofType\": {\n                  \"kind\": \"NON_NULL\",\n                  \"name\": null,\n                  \"ofType\": {\n                    \"kind\": \"OBJECT\",\n                    \"name\": \"__Directive\",\n                    \"ofType\": null\n                  }\n                }\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"inputFields\": null,\n        \"interfaces\": [],\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"OBJECT\",\n        \"name\": \"__Type\",\n        \"description\": \"The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in GraphQL as represented by the `__TypeKind` enum.\\n\\nDepending on the kind of a type, certain fields describe information about that type. Scalar types provide no information beyond a name, description and optional `specifiedByUrl`, while Enum types provide their values. Object and Interface types provide the fields they describe. Abstract types, Union and Interface, provide the Object types possible at runtime. List and NonNull types compose other types.\",\n        \"fields\": [\n          {\n            \"name\": \"kind\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"ENUM\",\n                \"name\": \"__TypeKind\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"name\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"description\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"specifiedByUrl\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"fields\",\n            \"description\": null,\n            \"args\": [\n              {\n                \"name\": \"includeDeprecated\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"SCALAR\",\n                  \"name\": \"Boolean\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": \"false\",\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              }\n            ],\n            \"type\": {\n              \"kind\": \"LIST\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"NON_NULL\",\n                \"name\": null,\n                \"ofType\": {\n                  \"kind\": \"OBJECT\",\n                  \"name\": \"__Field\",\n                  \"ofType\": null\n                }\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"interfaces\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"LIST\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"NON_NULL\",\n                \"name\": null,\n                \"ofType\": {\n                  \"kind\": \"OBJECT\",\n                  \"name\": \"__Type\",\n                  \"ofType\": null\n                }\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"possibleTypes\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"LIST\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"NON_NULL\",\n                \"name\": null,\n                \"ofType\": {\n                  \"kind\": \"OBJECT\",\n                  \"name\": \"__Type\",\n                  \"ofType\": null\n                }\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"enumValues\",\n            \"description\": null,\n            \"args\": [\n              {\n                \"name\": \"includeDeprecated\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"SCALAR\",\n                  \"name\": \"Boolean\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": \"false\",\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              }\n            ],\n            \"type\": {\n              \"kind\": \"LIST\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"NON_NULL\",\n                \"name\": null,\n                \"ofType\": {\n                  \"kind\": \"OBJECT\",\n                  \"name\": \"__EnumValue\",\n                  \"ofType\": null\n                }\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"inputFields\",\n            \"description\": null,\n            \"args\": [\n              {\n                \"name\": \"includeDeprecated\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"SCALAR\",\n                  \"name\": \"Boolean\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": \"false\",\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              }\n            ],\n            \"type\": {\n              \"kind\": \"LIST\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"NON_NULL\",\n                \"name\": null,\n                \"ofType\": {\n                  \"kind\": \"OBJECT\",\n                  \"name\": \"__InputValue\",\n                  \"ofType\": null\n                }\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"ofType\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"OBJECT\",\n              \"name\": \"__Type\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"inputFields\": null,\n        \"interfaces\": [],\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"ENUM\",\n        \"name\": \"__TypeKind\",\n        \"description\": \"An enum describing what kind of type a given `__Type` is.\",\n        \"fields\": null,\n        \"inputFields\": null,\n        \"interfaces\": null,\n        \"enumValues\": [\n          {\n            \"name\": \"SCALAR\",\n            \"description\": \"Indicates this type is a scalar.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"OBJECT\",\n            \"description\": \"Indicates this type is an object. `fields` and `interfaces` are valid fields.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"INTERFACE\",\n            \"description\": \"Indicates this type is an interface. `fields`, `interfaces`, and `possibleTypes` are valid fields.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"UNION\",\n            \"description\": \"Indicates this type is a union. `possibleTypes` is a valid field.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"ENUM\",\n            \"description\": \"Indicates this type is an enum. `enumValues` is a valid field.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"INPUT_OBJECT\",\n            \"description\": \"Indicates this type is an input object. `inputFields` is a valid field.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"LIST\",\n            \"description\": \"Indicates this type is a list. `ofType` is a valid field.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"NON_NULL\",\n            \"description\": \"Indicates this type is a non-null. `ofType` is a valid field.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"OBJECT\",\n        \"name\": \"__Field\",\n        \"description\": \"Object and Interface types are described by a list of Fields, each of which has a name, potentially a list of arguments, and a return type.\",\n        \"fields\": [\n          {\n            \"name\": \"name\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"SCALAR\",\n                \"name\": \"String\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"description\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"args\",\n            \"description\": null,\n            \"args\": [\n              {\n                \"name\": \"includeDeprecated\",\n                \"description\": null,\n                \"type\": {\n                  \"kind\": \"SCALAR\",\n                  \"name\": \"Boolean\",\n                  \"ofType\": null\n                },\n                \"defaultValue\": \"false\",\n                \"isDeprecated\": false,\n                \"deprecationReason\": null\n              }\n            ],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"LIST\",\n                \"name\": null,\n                \"ofType\": {\n                  \"kind\": \"NON_NULL\",\n                  \"name\": null,\n                  \"ofType\": {\n                    \"kind\": \"OBJECT\",\n                    \"name\": \"__InputValue\",\n                    \"ofType\": null\n                  }\n                }\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"type\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"OBJECT\",\n                \"name\": \"__Type\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"isDeprecated\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"SCALAR\",\n                \"name\": \"Boolean\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"deprecationReason\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"inputFields\": null,\n        \"interfaces\": [],\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"OBJECT\",\n        \"name\": \"__InputValue\",\n        \"description\": \"Arguments provided to Fields or Directives and the input fields of an InputObject are represented as Input Values which describe their type and optionally a default value.\",\n        \"fields\": [\n          {\n            \"name\": \"name\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"SCALAR\",\n                \"name\": \"String\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"description\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"type\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"OBJECT\",\n                \"name\": \"__Type\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"defaultValue\",\n            \"description\": \"A GraphQL-formatted string representing the default value for this input value.\",\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"isDeprecated\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"SCALAR\",\n                \"name\": \"Boolean\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"deprecationReason\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"inputFields\": null,\n        \"interfaces\": [],\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"OBJECT\",\n        \"name\": \"__EnumValue\",\n        \"description\": \"One possible value for a given Enum. Enum values are unique values, not a placeholder for a string or numeric value. However an Enum value is returned in a JSON response as a string.\",\n        \"fields\": [\n          {\n            \"name\": \"name\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"SCALAR\",\n                \"name\": \"String\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"description\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"isDeprecated\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"SCALAR\",\n                \"name\": \"Boolean\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"deprecationReason\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"inputFields\": null,\n        \"interfaces\": [],\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"OBJECT\",\n        \"name\": \"__Directive\",\n        \"description\": \"A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document.\\n\\nIn some cases, you need to provide options to alter GraphQL's execution behavior in ways field arguments will not suffice, such as conditionally including or skipping a field. Directives provide this by describing additional information to the executor.\",\n        \"fields\": [\n          {\n            \"name\": \"name\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"SCALAR\",\n                \"name\": \"String\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"description\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"isRepeatable\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"SCALAR\",\n                \"name\": \"Boolean\",\n                \"ofType\": null\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"locations\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"LIST\",\n                \"name\": null,\n                \"ofType\": {\n                  \"kind\": \"NON_NULL\",\n                  \"name\": null,\n                  \"ofType\": {\n                    \"kind\": \"ENUM\",\n                    \"name\": \"__DirectiveLocation\",\n                    \"ofType\": null\n                  }\n                }\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"args\",\n            \"description\": null,\n            \"args\": [],\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"LIST\",\n                \"name\": null,\n                \"ofType\": {\n                  \"kind\": \"NON_NULL\",\n                  \"name\": null,\n                  \"ofType\": {\n                    \"kind\": \"OBJECT\",\n                    \"name\": \"__InputValue\",\n                    \"ofType\": null\n                  }\n                }\n              }\n            },\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"inputFields\": null,\n        \"interfaces\": [],\n        \"enumValues\": null,\n        \"possibleTypes\": null\n      },\n      {\n        \"kind\": \"ENUM\",\n        \"name\": \"__DirectiveLocation\",\n        \"description\": \"A Directive can be adjacent to many parts of the GraphQL language, a __DirectiveLocation describes one such possible adjacencies.\",\n        \"fields\": null,\n        \"inputFields\": null,\n        \"interfaces\": null,\n        \"enumValues\": [\n          {\n            \"name\": \"QUERY\",\n            \"description\": \"Location adjacent to a query operation.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"MUTATION\",\n            \"description\": \"Location adjacent to a mutation operation.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"SUBSCRIPTION\",\n            \"description\": \"Location adjacent to a subscription operation.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"FIELD\",\n            \"description\": \"Location adjacent to a field.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"FRAGMENT_DEFINITION\",\n            \"description\": \"Location adjacent to a fragment definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"FRAGMENT_SPREAD\",\n            \"description\": \"Location adjacent to a fragment spread.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"INLINE_FRAGMENT\",\n            \"description\": \"Location adjacent to an inline fragment.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"VARIABLE_DEFINITION\",\n            \"description\": \"Location adjacent to a variable definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"SCHEMA\",\n            \"description\": \"Location adjacent to a schema definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"SCALAR\",\n            \"description\": \"Location adjacent to a scalar definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"OBJECT\",\n            \"description\": \"Location adjacent to an object type definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"FIELD_DEFINITION\",\n            \"description\": \"Location adjacent to a field definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"ARGUMENT_DEFINITION\",\n            \"description\": \"Location adjacent to an argument definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"INTERFACE\",\n            \"description\": \"Location adjacent to an interface definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"UNION\",\n            \"description\": \"Location adjacent to a union definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"ENUM\",\n            \"description\": \"Location adjacent to an enum definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"ENUM_VALUE\",\n            \"description\": \"Location adjacent to an enum value definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"INPUT_OBJECT\",\n            \"description\": \"Location adjacent to an input object type definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          },\n          {\n            \"name\": \"INPUT_FIELD_DEFINITION\",\n            \"description\": \"Location adjacent to an input object field definition.\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ],\n        \"possibleTypes\": null\n      }\n    ],\n    \"directives\": [\n      {\n        \"name\": \"include\",\n        \"description\": \"Directs the executor to include this field or fragment only when the `if` argument is true.\",\n        \"isRepeatable\": false,\n        \"locations\": [\"FIELD\", \"FRAGMENT_SPREAD\", \"INLINE_FRAGMENT\"],\n        \"args\": [\n          {\n            \"name\": \"if\",\n            \"description\": \"Included when true.\",\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"SCALAR\",\n                \"name\": \"Boolean\",\n                \"ofType\": null\n              }\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ]\n      },\n      {\n        \"name\": \"skip\",\n        \"description\": \"Directs the executor to skip this field or fragment when the `if` argument is true.\",\n        \"isRepeatable\": false,\n        \"locations\": [\"FIELD\", \"FRAGMENT_SPREAD\", \"INLINE_FRAGMENT\"],\n        \"args\": [\n          {\n            \"name\": \"if\",\n            \"description\": \"Skipped when true.\",\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"SCALAR\",\n                \"name\": \"Boolean\",\n                \"ofType\": null\n              }\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ]\n      },\n      {\n        \"name\": \"deprecated\",\n        \"description\": \"Marks an element of a GraphQL schema as no longer supported.\",\n        \"isRepeatable\": false,\n        \"locations\": [\n          \"FIELD_DEFINITION\",\n          \"ARGUMENT_DEFINITION\",\n          \"INPUT_FIELD_DEFINITION\",\n          \"ENUM_VALUE\"\n        ],\n        \"args\": [\n          {\n            \"name\": \"reason\",\n            \"description\": \"Explains why this element was deprecated, usually also including a suggestion for how to access supported similar data. Formatted using the Markdown syntax, as specified by [CommonMark](https://commonmark.org/).\",\n            \"type\": {\n              \"kind\": \"SCALAR\",\n              \"name\": \"String\",\n              \"ofType\": null\n            },\n            \"defaultValue\": \"\\\"No longer supported\\\"\",\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ]\n      },\n      {\n        \"name\": \"specifiedBy\",\n        \"description\": \"Exposes a URL that specifies the behavior of this scalar.\",\n        \"isRepeatable\": false,\n        \"locations\": [\"SCALAR\"],\n        \"args\": [\n          {\n            \"name\": \"url\",\n            \"description\": \"The URL that specifies the behavior of this scalar.\",\n            \"type\": {\n              \"kind\": \"NON_NULL\",\n              \"name\": null,\n              \"ofType\": {\n                \"kind\": \"SCALAR\",\n                \"name\": \"String\",\n                \"ofType\": null\n              }\n            },\n            \"defaultValue\": null,\n            \"isDeprecated\": false,\n            \"deprecationReason\": null\n          }\n        ]\n      }\n    ]\n  }\n}\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/apollo.config.js",
    "content": "// configuration file for the Apollo Graphql VSCode extension\n// https://marketplace.visualstudio.com/items?itemName=apollographql.vscode-apollo\n// https://www.apollographql.com/docs/devtools/editor-plugins/\nmodule.exports = {\n  client: {\n    service: {\n      name: 'locally mocked graphql server',\n      localSchemaFile: __dirname + '/.introspection.json',\n    },\n    includes: ['./src/**/*.graphql'],\n    excludes: ['./src/**/*.ts', './src/**/*.js'],\n  },\n}\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/codegen.yml",
    "content": "overwrite: true\nschema: './src/mocks/schema.js'\ndocuments: 'src/**/*.graphql'\nwatchConfig:\n  usePolling: true\n  interval: 1000\ngenerates:\n  src/app/services/types.generated.ts:\n    plugins:\n      - typescript\n    config:\n      maybeValue: T # normally, this would be T | null, but our msw mock returns everything as nullable, so we want to force these as non-nullalbe\n  src/:\n    preset: near-operation-file\n    presetConfig:\n      baseTypesPath: app/services/types.generated.ts\n    plugins:\n      - add:\n          content: >\n            /* eslint-disable */\n            /**\n             *\n             * THIS FILE IS AUTOGENERATED, DO NOT EDIT IT!\n             *\n             * instead, edit one of the `.graphql` files in this project and run\n             *\n             * npm run graphql-codegen\n             *\n             * for this file to be re-created\n             */\n      - add:\n          content: 'module.hot?.accept();'\n      - typescript-operations\n      - typescript-rtk-query:\n          importBaseApiFrom: 'app/services/baseApi'\n          exportHooks: true\n          overrideExisting: 'module.hot?.status() === \"apply\"'\n    config:\n      maybeValue: T # normally, this would be T | null, but our msw mock returns everything as nullable, so we want to force these as non-nullalbe\n  .introspection.json:\n    plugins:\n      - introspection\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/graphql-codegen\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"./src/index.tsx\",\n  \"dependencies\": {\n    \"@chakra-ui/react\": \"2.10.7\",\n    \"@emotion/react\": \"^11.4.0\",\n    \"@emotion/styled\": \"^11.3.0\",\n    \"@mswjs/data\": \"^0.4.0\",\n    \"@reduxjs/toolkit\": \"^1.6.0\",\n    \"@rtk-query/graphql-request-base-query\": \"^2.0.0\",\n    \"faker\": \"^5.5.3\",\n    \"framer-motion\": \"^2.9.5\",\n    \"graphql\": \"^15.5.0\",\n    \"graphql-request\": \"^3.4.0\",\n    \"msw\": \"0.40.2\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-icons\": \"3.11.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-router-dom\": \"6.3.0\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@graphql-codegen/add\": \"^2.0.2\",\n    \"@graphql-codegen/cli\": \"1.21.5\",\n    \"@graphql-codegen/introspection\": \"^1.18.2\",\n    \"@graphql-codegen/near-operation-file-preset\": \"^1.18.1\",\n    \"@graphql-codegen/typed-document-node\": \"^1.18.6\",\n    \"@graphql-codegen/typescript\": \"1.22.1\",\n    \"@graphql-codegen/typescript-operations\": \"^1.18.0\",\n    \"@graphql-codegen/typescript-rtk-query\": \"^1.1.0\",\n    \"@graphql-typed-document-node/core\": \"^3.1.0\",\n    \"@types/faker\": \"^5.5.5\",\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"@types/webpack-env\": \"^1.16.0\",\n    \"concurrently\": \"^6.2.0\",\n    \"cross-env\": \"^7.0.3\",\n    \"rimraf\": \"^6.1.3\",\n    \"ts-node\": \"^10.0.0\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"scripts\": {\n    \"develop\": \"cross-env CHOKIDAR_USEPOLLING=true yarn start\",\n    \"start\": \"concurrently --restart-tries 20 'npm:watch-*'\",\n    \"watch-CRA\": \"react-scripts start\",\n    \"watch-codegen\": \"graphql-codegen --config codegen.yml --watch 'src/**/*.graphql'\",\n    \"build\": \"react-scripts build\",\n    \"prebuild\": \"rimraf dist/\",\n    \"graphql-codegen\": \"graphql-codegen --config codegen.yml\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ]\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ],\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query Pagination Example\",\n  \"name\": \"Pagination Demo\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/public/mockServiceWorker.js",
    "content": "/**\n * Mock Service Worker.\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n/* eslint-disable */\n/* tslint:disable */\n\nconst INTEGRITY_CHECKSUM = '82ef9b96d8393b6da34527d1d6e19187'\nconst bypassHeaderName = 'x-msw-bypass'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  return self.skipWaiting()\n})\n\nself.addEventListener('activate', async function (event) {\n  return self.clients.claim()\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\n// Resolve the \"master\" client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMasterClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMasterClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: serializeHeaders(clonedResponse.headers),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const requestClone = request.clone()\n  const getOriginalResponse = () => fetch(requestClone)\n\n  // Bypass mocking when the request client is not active.\n  if (!client) {\n    return getOriginalResponse()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return await getOriginalResponse()\n  }\n\n  // Bypass requests with the explicit bypass header\n  if (requestClone.headers.get(bypassHeaderName) === 'true') {\n    const cleanRequestHeaders = serializeHeaders(requestClone.headers)\n\n    // Remove the bypass header to comply with the CORS preflight check.\n    delete cleanRequestHeaders[bypassHeaderName]\n\n    const originalRequest = new Request(requestClone, {\n      headers: new Headers(cleanRequestHeaders),\n    })\n\n    return fetch(originalRequest)\n  }\n\n  // Send the request to the client-side MSW.\n  const reqHeaders = serializeHeaders(request.headers)\n  const body = await request.text()\n\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: reqHeaders,\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body,\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_SUCCESS': {\n      return delayPromise(\n        () => respondWithMock(clientMessage),\n        clientMessage.payload.delay,\n      )\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return getOriginalResponse()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.payload\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a request Promise emulates a network error.\n      throw networkError\n    }\n\n    case 'INTERNAL_ERROR': {\n      const parsedBody = JSON.parse(clientMessage.payload.body)\n\n      console.error(\n        `\\\n[MSW] Request handler function for \"%s %s\" has thrown the following exception:\n\n${parsedBody.errorType}: ${parsedBody.message}\n(see more detailed error stack trace in the mocked response body)\n\nThis exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error.\nIf you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\\\n`,\n        request.method,\n        request.url,\n      )\n\n      return respondWithMock(clientMessage)\n    }\n  }\n\n  return getOriginalResponse()\n}\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  const requestId = uuidv4()\n\n  return event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      console.error(\n        '[MSW] Failed to mock a \"%s\" request to \"%s\": %s',\n        request.method,\n        request.url,\n        error,\n      )\n    }),\n  )\n})\n\nfunction serializeHeaders(headers) {\n  const reqHeaders = {}\n  headers.forEach((value, name) => {\n    reqHeaders[name] = reqHeaders[name]\n      ? [].concat(reqHeaders[name]).concat(value)\n      : value\n  })\n  return reqHeaders\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(JSON.stringify(message), [channel.port2])\n  })\n}\n\nfunction delayPromise(cb, duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => resolve(cb()), duration)\n  })\n}\n\nfunction respondWithMock(clientMessage) {\n  return new Response(clientMessage.payload.body, {\n    ...clientMessage.payload,\n    headers: clientMessage.payload.headers,\n  })\n}\n\nfunction uuidv4() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0\n    const v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/sandbox.config.json",
    "content": "{\n  \"template\": \"node\",\n  \"container\": {\n    \"port\": 3000\n  }\n}\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/App.tsx",
    "content": "import { Route, Routes } from 'react-router-dom'\nimport { PostsManager } from './features/posts/PostsManager'\n\nfunction App() {\n  return (\n    <Routes>\n      <Route path=\"/\" element={<PostsManager />} />\n    </Routes>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/app/services/baseApi.ts",
    "content": "import { createApi } from '@reduxjs/toolkit/query/react'\nimport { graphqlRequestBaseQuery } from '@rtk-query/graphql-request-base-query'\n\nexport const api = createApi({\n  baseQuery: graphqlRequestBaseQuery({\n    url: '/graphql',\n  }),\n  endpoints: () => ({}),\n})\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/app/services/types.generated.ts",
    "content": "export type Maybe<T> = T\nexport type Exact<T extends { [key: string]: unknown }> = {\n  [K in keyof T]: T[K]\n}\nexport type MakeOptional<T, K extends keyof T> = Omit<T, K> & {\n  [SubKey in K]?: Maybe<T[SubKey]>\n}\nexport type MakeMaybe<T, K extends keyof T> = Omit<T, K> & {\n  [SubKey in K]: Maybe<T[SubKey]>\n}\n/** All built-in and custom scalars, mapped to their actual values */\nexport type Scalars = {\n  ID: string\n  String: string\n  Boolean: boolean\n  Int: number\n  Float: number\n}\n\nexport type IdQueryType = {\n  equals?: Maybe<Scalars['ID']>\n  notEquals?: Maybe<Scalars['ID']>\n  contains?: Maybe<Scalars['ID']>\n  notContains?: Maybe<Scalars['ID']>\n  in?: Maybe<Scalars['ID']>\n  notIn?: Maybe<Scalars['ID']>\n}\n\nexport type Mutation = {\n  __typename?: 'Mutation'\n  createPost?: Maybe<Post>\n  updatePost?: Maybe<Post>\n  updatePosts?: Maybe<Array<Maybe<Post>>>\n  deletePost?: Maybe<Post>\n  deletePosts?: Maybe<Array<Maybe<Post>>>\n}\n\nexport type MutationCreatePostArgs = {\n  data?: Maybe<PostInput>\n}\n\nexport type MutationUpdatePostArgs = {\n  where?: Maybe<PostQueryInput>\n  data?: Maybe<PostInput>\n}\n\nexport type MutationUpdatePostsArgs = {\n  where?: Maybe<PostQueryInput>\n  data?: Maybe<PostInput>\n}\n\nexport type MutationDeletePostArgs = {\n  where?: Maybe<PostQueryInput>\n}\n\nexport type MutationDeletePostsArgs = {\n  where?: Maybe<PostQueryInput>\n}\n\nexport type Post = {\n  __typename?: 'Post'\n  id?: Maybe<Scalars['ID']>\n  name?: Maybe<Scalars['String']>\n  title?: Maybe<Scalars['String']>\n  author?: Maybe<Scalars['String']>\n  content?: Maybe<Scalars['String']>\n  status?: Maybe<Scalars['String']>\n  created_at?: Maybe<Scalars['String']>\n  updated_at?: Maybe<Scalars['String']>\n}\n\nexport type PostInput = {\n  id?: Maybe<Scalars['ID']>\n  name?: Maybe<Scalars['String']>\n  title?: Maybe<Scalars['String']>\n  author?: Maybe<Scalars['String']>\n  content?: Maybe<Scalars['String']>\n  status?: Maybe<Scalars['String']>\n  created_at?: Maybe<Scalars['String']>\n  updated_at?: Maybe<Scalars['String']>\n}\n\nexport type PostQueryInput = {\n  id?: Maybe<IdQueryType>\n  name?: Maybe<StringQueryType>\n  title?: Maybe<StringQueryType>\n  author?: Maybe<StringQueryType>\n  content?: Maybe<StringQueryType>\n  status?: Maybe<StringQueryType>\n  created_at?: Maybe<StringQueryType>\n  updated_at?: Maybe<StringQueryType>\n}\n\nexport type Query = {\n  __typename?: 'Query'\n  post?: Maybe<Post>\n  posts?: Maybe<Array<Maybe<Post>>>\n}\n\nexport type QueryPostArgs = {\n  where?: Maybe<PostQueryInput>\n}\n\nexport type QueryPostsArgs = {\n  take?: Maybe<Scalars['Int']>\n  skip?: Maybe<Scalars['Int']>\n  cursor?: Maybe<Scalars['ID']>\n  where?: Maybe<PostQueryInput>\n}\n\nexport type StringQueryType = {\n  equals?: Maybe<Scalars['String']>\n  notEquals?: Maybe<Scalars['String']>\n  contains?: Maybe<Scalars['String']>\n  notContains?: Maybe<Scalars['String']>\n  in?: Maybe<Scalars['String']>\n  notIn?: Maybe<Scalars['String']>\n}\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/features/posts/GetPost.generated.ts",
    "content": "/* eslint-disable */ /**\n *\n * THIS FILE IS AUTOGENERATED, DO NOT EDIT IT!\n *\n * instead, edit one of the `.graphql` files in this project and run\n *\n * npm run graphql-codegen\n *\n * for this file to be re-created\n */\n\nimport * as Types from '../../app/services/types.generated'\n\nimport { api } from 'app/services/baseApi'\nmodule.hot?.accept()\nexport type GetPostQueryVariables = Types.Exact<{\n  id: Types.Scalars['ID']\n}>\n\nexport type GetPostQuery = { __typename?: 'Query' } & {\n  post?: Types.Maybe<\n    { __typename?: 'Post' } & Pick<Types.Post, 'id' | 'title' | 'content'>\n  >\n}\n\nexport const GetPostDocument = `\n    query GetPost($id: ID!) {\n  post(where: {id: {equals: $id}}) {\n    id\n    title\n    content\n  }\n}\n    `\n\nconst injectedRtkApi = api.injectEndpoints({\n  overrideExisting: module.hot?.status() === 'apply',\n  endpoints: (build) => ({\n    GetPost: build.query<GetPostQuery, GetPostQueryVariables>({\n      query: (variables) => ({ document: GetPostDocument, variables }),\n    }),\n  }),\n})\n\nexport { injectedRtkApi as api }\nexport const { useGetPostQuery, useLazyGetPostQuery } = injectedRtkApi\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/features/posts/GetPost.graphql",
    "content": "query GetPost($id: ID!) {\n  post(where: { id: { equals: $id } }) {\n    id\n    title\n    content\n  }\n}\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/features/posts/GetPosts.generated.ts",
    "content": "/* eslint-disable */ /**\n *\n * THIS FILE IS AUTOGENERATED, DO NOT EDIT IT!\n *\n * instead, edit one of the `.graphql` files in this project and run\n *\n * npm run graphql-codegen\n *\n * for this file to be re-created\n */\n\nimport * as Types from '../../app/services/types.generated'\n\nimport { api } from 'app/services/baseApi'\nmodule.hot?.accept()\nexport type GetPostsQueryVariables = Types.Exact<{\n  skip?: Types.Maybe<Types.Scalars['Int']>\n  take?: Types.Maybe<Types.Scalars['Int']>\n}>\n\nexport type GetPostsQuery = { __typename?: 'Query' } & {\n  posts?: Types.Maybe<\n    Array<\n      Types.Maybe<\n        { __typename?: 'Post' } & Pick<Types.Post, 'id' | 'title' | 'status'>\n      >\n    >\n  >\n}\n\nexport const GetPostsDocument = `\n    query GetPosts($skip: Int = 0, $take: Int = 10) {\n  posts(skip: $skip, take: $take) {\n    id\n    title\n    status\n  }\n}\n    `\n\nconst injectedRtkApi = api.injectEndpoints({\n  overrideExisting: module.hot?.status() === 'apply',\n  endpoints: (build) => ({\n    GetPosts: build.query<GetPostsQuery, GetPostsQueryVariables | void>({\n      query: (variables) => ({ document: GetPostsDocument, variables }),\n    }),\n  }),\n})\n\nexport { injectedRtkApi as api }\nexport const { useGetPostsQuery, useLazyGetPostsQuery } = injectedRtkApi\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/features/posts/GetPosts.graphql",
    "content": "query GetPosts($skip: Int = 0, $take: Int = 10) {\n  posts(skip: $skip, take: $take) {\n    id\n    title\n    status\n  }\n}\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/features/posts/PostsManager.tsx",
    "content": "import * as React from 'react'\nimport {\n  Badge,\n  Box,\n  Button,\n  Divider,\n  Flex,\n  Heading,\n  HStack,\n  Icon,\n  List,\n  ListIcon,\n  ListItem,\n  Spacer,\n  Stat,\n  StatLabel,\n  StatNumber,\n} from '@chakra-ui/react'\nimport { MdArrowBack, MdArrowForward, MdBook } from 'react-icons/md'\nimport { useGetPostsQuery } from './GetPosts.generated'\n\nconst getColorForStatus = (status: string | undefined) => {\n  return status === 'draft'\n    ? 'gray'\n    : status === 'pending_review'\n      ? 'orange'\n      : 'green'\n}\n\nconst PostList = () => {\n  const [page, setPage] = React.useState(1)\n  const { data, isLoading, isFetching } = useGetPostsQuery({\n    skip: page * 10,\n    take: 10,\n  })\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  return (\n    <Box>\n      <HStack spacing=\"14px\">\n        <Button\n          onClick={() => setPage((prev) => prev - 1)}\n          isLoading={isFetching}\n          disabled={page === 1}\n        >\n          <Icon as={MdArrowBack} />\n        </Button>\n        <Button\n          onClick={() => setPage((prev) => prev + 1)}\n          isLoading={isFetching}\n        >\n          <Icon as={MdArrowForward} />\n        </Button>\n        <Box>{`${page}`}</Box>\n      </HStack>\n      <List spacing={3} mt={6}>\n        {data?.posts?.length ? (\n          data?.posts.map(({ id, title, status }) => (\n            <ListItem key={id}>\n              <ListIcon as={MdBook} color=\"green.500\" /> {title}{' '}\n              <Badge\n                ml=\"1\"\n                fontSize=\"0.8em\"\n                colorScheme={getColorForStatus(status)}\n              >\n                {status}\n              </Badge>\n            </ListItem>\n          ))\n        ) : (\n          <ListItem>No posts :(</ListItem>\n        )}\n      </List>\n    </Box>\n  )\n}\n\nexport const PostsCountStat = () => {\n  const { data } = useGetPostsQuery({})\n\n  return (\n    <Stat>\n      <StatLabel>Total Posts</StatLabel>\n      <StatNumber>{`${data?.posts?.length || 'NA'}`}</StatNumber>\n    </Stat>\n  )\n}\n\nexport const PostsManager = () => {\n  return (\n    <Box>\n      <Flex wrap=\"wrap\" bg=\"#011627\" p={4} color=\"white\">\n        <Box>\n          <Heading size=\"xl\">Manage Posts</Heading>\n        </Box>\n        <Spacer />\n        <Box>\n          <PostsCountStat />\n        </Box>\n      </Flex>\n      <Divider />\n      <Box p={4}>\n        <PostList />\n      </Box>\n    </Box>\n  )\n}\n\nexport default PostsManager\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport { api } from './app/services/baseApi'\nimport { ChakraProvider } from '@chakra-ui/react'\n\nimport { BrowserRouter } from 'react-router-dom'\nimport { worker } from './mocks/browser'\nimport { ApiProvider } from '@reduxjs/toolkit/query/react'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nworker.start({ quiet: true }).then(() => {\n  return ReactDOM.createRoot(\n    document.getElementById('root') as HTMLElement,\n  ).render(\n    <React.StrictMode>\n      <ApiProvider api={api}>\n        <ChakraProvider>\n          <BrowserRouter>\n            <App />\n          </BrowserRouter>\n        </ChakraProvider>\n      </ApiProvider>\n    </React.StrictMode>,\n  )\n})\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './db'\n\nexport const worker = setupWorker(...handlers)\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/mocks/db.ts",
    "content": "import { nanoid } from '@reduxjs/toolkit'\nimport { factory, primaryKey } from '@mswjs/data'\nimport faker from 'faker'\n\nconst postStatuses = ['draft', 'published', 'pending_review'] as const\n\ninterface Post {\n  id: string\n  title: string\n  author: string\n  content: string\n  status: (typeof postStatuses)[number]\n  created_at: string\n  updated_at: string\n}\n\nconst db = factory({\n  post: {\n    id: primaryKey(String),\n    name: String,\n    title: String,\n    author: String,\n    content: String,\n    status: String,\n    created_at: String,\n    updated_at: String,\n  },\n})\n\nconst getRandomStatus = () =>\n  postStatuses[Math.floor(Math.random() * postStatuses.length)]\n\nconst createPostData = (): Post => {\n  const date = faker.date.past().toISOString()\n  return {\n    id: nanoid(),\n    title: faker.lorem.words(),\n    author: faker.name.findName(),\n    content: faker.lorem.paragraphs(),\n    status: getRandomStatus(),\n    created_at: date,\n    updated_at: date,\n  }\n}\n\n;[...new Array(50)].forEach((_) => db.post.create(createPostData()))\n\nexport const handlers = db.post.toHandlers('graphql')\nexport const schema = db.post.toGraphQLSchema()\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/mocks/schema.js",
    "content": "require('ts-node').register({ compilerOptions: { module: 'commonjs' } })\nmodule.exports = require('./db').schema\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/graphql-codegen/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"baseUrl\": \"src\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/.eslintrc.json",
    "content": "{\n  \"extends\": [\n    \"eslint:recommended\",\n    \"react-app\",\n    \"plugin:react/jsx-runtime\",\n    \"prettier\"\n  ],\n  \"parser\": \"@typescript-eslint/parser\",\n  \"parserOptions\": { \"project\": true, \"tsconfigRootDir\": \"./\" },\n  \"plugins\": [\"@typescript-eslint\"],\n  \"root\": true,\n  \"ignorePatterns\": [\"dist\"],\n  \"rules\": {\n    \"@typescript-eslint/consistent-type-imports\": [\n      2,\n      { \"fixStyle\": \"separate-type-imports\" }\n    ],\n    \"@typescript-eslint/no-restricted-imports\": [\n      2,\n      {\n        \"paths\": [\n          {\n            \"name\": \"react-redux\",\n            \"importNames\": [\"useSelector\", \"useStore\", \"useDispatch\"],\n            \"message\": \"Please use pre-typed versions from `src/app/hooks.ts` instead.\"\n          }\n        ]\n      }\n    ]\n  },\n  \"overrides\": [\n    { \"files\": [\"*.{c,m,}{t,j}s\", \"*.{t,j}sx\"] },\n    { \"files\": [\"*{test,spec}.{t,j}s?(x)\"], \"env\": { \"jest\": true } }\n  ]\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/.gitignore",
    "content": "# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\npnpm-debug.log*\nlerna-debug.log*\n\nnode_modules\ndist\ndist-ssr\n*.local\n\n# Editor directories and files\n.vscode/*\n!.vscode/extensions.json\n.idea\n.DS_Store\n*.suo\n*.ntvs*\n*.njsproj\n*.sln\n*.sw?\n\ntypesversions\n.cache\n.yarnrc\n.yarn/*\n!.yarn/patches\n!.yarn/releases\n!.yarn/plugins\n!.yarn/sdks\n!.yarn/versions\n.pnp.*\n*.tgz"
  },
  {
    "path": "examples/query/react/infinite-queries/.prettierrc.json",
    "content": "{\n  \"semi\": false,\n  \"arrowParens\": \"avoid\"\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/README.md",
    "content": "# RTK Query Infinite Queries Example\n\nThis example shows a variety of usage patterns for RTK Query's infinite query endpoint support, including:\n\n- Basic pagination\n- Infinite scrolling\n- Bidirectional cursors\n- Offset + limit\n- Max pages\n- React Native FlatList\n"
  },
  {
    "path": "examples/query/react/infinite-queries/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"UTF-8\" />\n    <link rel=\"icon\" type=\"image/svg+xml\" href=\"/vite.svg\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n    <title>React Redux App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <script type=\"module\" src=\"/src/main.tsx\"></script>\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/infinite-queries/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/infinite-queries\",\n  \"private\": true,\n  \"version\": \"0.0.0\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"dev\": \"vite\",\n    \"start\": \"vite\",\n    \"build\": \"tsc && vite build\",\n    \"preview\": \"vite preview\",\n    \"test\": \"vitest run\",\n    \"format\": \"prettier --write .\",\n    \"lint\": \"eslint .\",\n    \"lint:fix\": \"eslint --fix .\",\n    \"type-check\": \"tsc --noEmit\"\n  },\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"workspace:^\",\n    \"react\": \"^18.2.0\",\n    \"react-dom\": \"^18.2.0\",\n    \"react-intersection-observer\": \"^9.13.1\",\n    \"react-native-web\": \"^0.19.13\",\n    \"react-redux\": \"^9.1.0\",\n    \"react-router\": \"^7.0.1\"\n  },\n  \"devDependencies\": {\n    \"@testing-library/dom\": \"^9.3.4\",\n    \"@testing-library/jest-dom\": \"^6.2.0\",\n    \"@testing-library/react\": \"^14.1.2\",\n    \"@testing-library/user-event\": \"^14.5.2\",\n    \"@types/react\": \"18.3.12\",\n    \"@types/react-dom\": \"18.3.1\",\n    \"@types/react-native-web\": \"^0.19\",\n    \"@vitejs/plugin-react\": \"^5\",\n    \"jsdom\": \"^23.2.0\",\n    \"msw\": \"^2.6.6\",\n    \"prettier\": \"^3.2.1\",\n    \"typescript\": \"^5.9.3\",\n    \"vite\": \"^7\",\n    \"vitest\": \"^4\"\n  },\n  \"msw\": {\n    \"workerDirectory\": [\n      \"public\"\n    ]\n  }\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/public/mockServiceWorker.js",
    "content": "/* eslint-disable */\n/* tslint:disable */\n\n/**\n * Mock Service Worker.\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n\nconst PACKAGE_VERSION = '2.7.0'\nconst INTEGRITY_CHECKSUM = '00729d72e3b82faf54ca8b9621dbb96f'\nconst IS_MOCKED_RESPONSE = Symbol('isMockedResponse')\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  self.skipWaiting()\n})\n\nself.addEventListener('activate', function (event) {\n  event.waitUntil(self.clients.claim())\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll({\n    type: 'window',\n  })\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: {\n          packageVersion: PACKAGE_VERSION,\n          checksum: INTEGRITY_CHECKSUM,\n        },\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: {\n          client: {\n            id: client.id,\n            frameType: client.frameType,\n          },\n        },\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  // Generate unique request ID.\n  const requestId = crypto.randomUUID()\n  event.respondWith(handleRequest(event, requestId))\n})\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMainClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const responseClone = response.clone()\n\n      sendToClient(\n        client,\n        {\n          type: 'RESPONSE',\n          payload: {\n            requestId,\n            isMockedResponse: IS_MOCKED_RESPONSE in response,\n            type: responseClone.type,\n            status: responseClone.status,\n            statusText: responseClone.statusText,\n            body: responseClone.body,\n            headers: Object.fromEntries(responseClone.headers.entries()),\n          },\n        },\n        [responseClone.body],\n      )\n    })()\n  }\n\n  return response\n}\n\n// Resolve the main client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMainClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (activeClientIds.has(event.clientId)) {\n    return client\n  }\n\n  if (client?.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll({\n    type: 'window',\n  })\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n\n  // Clone the request because it might've been already used\n  // (i.e. its body has been read and sent to the client).\n  const requestClone = request.clone()\n\n  function passthrough() {\n    // Cast the request headers to a new Headers instance\n    // so the headers can be manipulated with.\n    const headers = new Headers(requestClone.headers)\n\n    // Remove the \"accept\" header value that marked this request as passthrough.\n    // This prevents request alteration and also keeps it compliant with the\n    // user-defined CORS policies.\n    const acceptHeader = headers.get('accept')\n    if (acceptHeader) {\n      const values = acceptHeader.split(',').map((value) => value.trim())\n      const filteredValues = values.filter(\n        (value) => value !== 'msw/passthrough',\n      )\n\n      if (filteredValues.length > 0) {\n        headers.set('accept', filteredValues.join(', '))\n      } else {\n        headers.delete('accept')\n      }\n    }\n\n    return fetch(requestClone, { headers })\n  }\n\n  // Bypass mocking when the client is not active.\n  if (!client) {\n    return passthrough()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return passthrough()\n  }\n\n  // Notify the client that a request has been intercepted.\n  const requestBuffer = await request.arrayBuffer()\n  const clientMessage = await sendToClient(\n    client,\n    {\n      type: 'REQUEST',\n      payload: {\n        id: requestId,\n        url: request.url,\n        mode: request.mode,\n        method: request.method,\n        headers: Object.fromEntries(request.headers.entries()),\n        cache: request.cache,\n        credentials: request.credentials,\n        destination: request.destination,\n        integrity: request.integrity,\n        redirect: request.redirect,\n        referrer: request.referrer,\n        referrerPolicy: request.referrerPolicy,\n        body: requestBuffer,\n        keepalive: request.keepalive,\n      },\n    },\n    [requestBuffer],\n  )\n\n  switch (clientMessage.type) {\n    case 'MOCK_RESPONSE': {\n      return respondWithMock(clientMessage.data)\n    }\n\n    case 'PASSTHROUGH': {\n      return passthrough()\n    }\n  }\n\n  return passthrough()\n}\n\nfunction sendToClient(client, message, transferrables = []) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(\n      message,\n      [channel.port2].concat(transferrables.filter(Boolean)),\n    )\n  })\n}\n\nasync function respondWithMock(response) {\n  // Setting response status code to 0 is a no-op.\n  // However, when responding with a \"Response.error()\", the produced Response\n  // instance will have status code set to 0. Since it's not possible to create\n  // a Response instance with status code 0, handle that use-case separately.\n  if (response.status === 0) {\n    return Response.error()\n  }\n\n  const mockedResponse = new Response(response.body, response)\n\n  Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {\n    value: true,\n    enumerable: true,\n  })\n\n  return mockedResponse\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/App.css",
    "content": ".App {\n  margin: 1rem;\n}\n\n.App-logo {\n  height: 40vmin;\n  pointer-events: none;\n}\n\n@media (prefers-reduced-motion: no-preference) {\n  .App-logo {\n    animation: App-logo-float infinite 3s ease-in-out;\n  }\n}\n\n.App-header {\n  min-height: 100vh;\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  font-size: calc(10px + 2vmin);\n}\n\n.App-link {\n  color: rgb(112, 76, 182);\n}\n\n@keyframes App-logo-float {\n  0% {\n    transform: translateY(0);\n  }\n  50% {\n    transform: translateY(10px);\n  }\n  100% {\n    transform: translateY(0px);\n  }\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/App.tsx",
    "content": "import { BrowserRouter, Link, Route, Routes, useLocation } from \"react-router\"\nimport \"./App.css\"\n\nimport { Outlet } from \"react-router\"\nimport BidirectionalCursorInfScroll from \"./features/bidirectional-cursor-infinite-scroll/BidirectionalCursorInfScroll\"\nimport {\n  InfiniteScrollAbout,\n  InfiniteScrollExample,\n} from \"./features/infinite-scroll/InfiniteScrollExample\"\nimport LimitOffsetExample from \"./features/limit-offset/LimitOffsetExample\"\nimport { InfiniteScrollMaxPagesExample } from \"./features/max-pages/InfiniteScrollMaxExample\"\nimport PaginationInfScrollExample from \"./features/pagination-infinite-scroll/PaginationInfScrollExample\"\nimport { PaginationExample } from \"./features/pagination/PaginationExample\"\nimport { FlatlistExample } from \"./features/rn-flatlist/FlatlistExample\"\n\nconst Menu = () => {\n  return (\n    <div>\n      <h2>Examples</h2>\n      <ul>\n        <li>\n          <Link to=\"/examples/pagination\">Pagination</Link>\n        </li>\n        <li>\n          <Link to=\"/examples/infinite-scroll\">Infinite Scroll</Link>\n        </li>\n        <li>\n          <Link to=\"/examples/infinite-scroll-max\">\n            Infinite Scroll + max pages\n          </Link>\n        </li>\n        <li>\n          <Link to=\"/examples/bidirectional-cursor-infinte-scroll\">\n            Bidirectional Cursor-Based Infinite Scroll\n          </Link>\n        </li>\n        <li>\n          <Link to=\"/examples/limit-offset\">\n            Limit and Offset Infinite Scroll\n          </Link>\n        </li>\n        <li>\n          <Link to=\"/examples/pagination-infinite-scroll\">\n            Pagination Infinite Scroll\n          </Link>\n        </li>\n        <li>\n          <Link to=\"/examples/rn-flatlist\">RN FlatList</Link>\n        </li>\n      </ul>\n    </div>\n  )\n}\n\nconst App = () => {\n  return (\n    <BrowserRouter>\n      <div className=\"App\">\n        <h1>RTKQ Infinite Query Example Showcase</h1>\n\n        <Routes>\n          <Route path=\"/\" element={<Menu />} />\n          <Route\n            path=\"/examples\"\n            element={\n              <div>\n                <Link to=\"/\">Back to Menu</Link>\n                <Outlet />\n              </div>\n            }\n          >\n            <Route path=\"pagination\" element={<PaginationExample />} />\n            <Route path=\"infinite-scroll\" element={<InfiniteScrollExample />} />\n            <Route\n              path=\"infinite-scroll/about\"\n              element={<InfiniteScrollAbout />}\n            />\n            <Route\n              path=\"infinite-scroll-max\"\n              element={<InfiniteScrollMaxPagesExample />}\n            />\n            <Route\n              path=\"bidirectional-cursor-infinte-scroll\"\n              element={<BidirectionalCursorInfScroll />}\n            />\n            <Route path=\"limit-offset\" element={<LimitOffsetExample />} />\n            <Route\n              path=\"pagination-infinite-scroll\"\n              element={<PaginationInfScrollExample />}\n            />\n            <Route path=\"rn-flatlist\" element={<FlatlistExample />} />\n          </Route>\n        </Routes>\n      </div>\n    </BrowserRouter>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/app/createAppSlice.ts",
    "content": "import { asyncThunkCreator, buildCreateSlice } from \"@reduxjs/toolkit\"\n\n// `buildCreateSlice` allows us to create a slice with async thunks.\nexport const createAppSlice = buildCreateSlice({\n  creators: { asyncThunk: asyncThunkCreator },\n})\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/app/hooks.ts",
    "content": "// This file serves as a central hub for re-exporting pre-typed Redux hooks.\n// These imports are restricted elsewhere to ensure consistent\n// usage of typed hooks throughout the application.\n// We disable the ESLint rule here because this is the designated place\n// for importing and re-exporting the typed versions of hooks.\n/* eslint-disable @typescript-eslint/no-restricted-imports */\nimport { useDispatch, useSelector } from \"react-redux\"\nimport type { AppDispatch, RootState } from \"./store\"\n\n// Use throughout your app instead of plain `useDispatch` and `useSelector`\nexport const useAppDispatch = useDispatch.withTypes<AppDispatch>()\nexport const useAppSelector = useSelector.withTypes<RootState>()\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/app/store.ts",
    "content": "import type { Action, ThunkAction } from \"@reduxjs/toolkit\"\nimport { combineSlices, configureStore } from \"@reduxjs/toolkit\"\nimport { setupListeners } from \"@reduxjs/toolkit/query\"\nimport { baseApi } from \"../features/baseApi\"\n\n// `combineSlices` automatically combines the reducers using\n// their `reducerPath`s, therefore we no longer need to call `combineReducers`.\nconst rootReducer = combineSlices(baseApi)\n// Infer the `RootState` type from the root reducer\nexport type RootState = ReturnType<typeof rootReducer>\n\n// The store setup is wrapped in `makeStore` to allow reuse\n// when setting up tests that need the same store config\nexport const makeStore = (preloadedState?: Partial<RootState>) => {\n  const store = configureStore({\n    reducer: rootReducer,\n    // Adding the api middleware enables caching, invalidation, polling,\n    // and other useful features of `rtk-query`.\n    middleware: getDefaultMiddleware => {\n      return getDefaultMiddleware().concat(baseApi.middleware)\n    },\n    preloadedState,\n  })\n  // configure listeners using the provided defaults\n  // optional, but required for `refetchOnFocus`/`refetchOnReconnect` behaviors\n  setupListeners(store.dispatch)\n  return store\n}\n\nexport const store = makeStore()\n\n// Infer the type of `store`\nexport type AppStore = typeof store\n// Infer the `AppDispatch` type from the store itself\nexport type AppDispatch = AppStore[\"dispatch\"]\nexport type AppThunk<ThunkReturnType = void> = ThunkAction<\n  ThunkReturnType,\n  RootState,\n  unknown,\n  Action\n>\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/app/useIntersectionCallback.ts",
    "content": "import { useCallback, useRef } from \"react\"\n\nexport function useIntersectionCallback(onIntersectCallback: () => void) {\n  const intersectionObserverRef = useRef<IntersectionObserver | null>(null)\n\n  return useCallback(\n    (node: HTMLDivElement | null) => {\n      if (intersectionObserverRef.current) {\n        intersectionObserverRef.current.disconnect()\n      }\n\n      intersectionObserverRef.current = new IntersectionObserver(entries => {\n        if (entries[0].isIntersecting) {\n          onIntersectCallback()\n        }\n      })\n\n      if (node) intersectionObserverRef.current.observe(node)\n    },\n    [onIntersectCallback],\n  )\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/baseApi.ts",
    "content": "import { createApi, fetchBaseQuery } from \"@reduxjs/toolkit/query/react\"\n\nexport const baseApi = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: \"/\" }),\n  endpoints: build => ({}),\n})\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/bidirectional-cursor-infinite-scroll/BidirectionalCursorInfScroll.tsx",
    "content": "import React, { useCallback, useEffect, useRef, useState } from \"react\"\nimport { Link, useLocation } from \"react-router\"\nimport { useIntersectionCallback } from \"../../app/useIntersectionCallback\"\nimport { apiWithInfiniteScroll } from \"./infiniteScrollApi\"\n\nconst limit = 10\n\nfunction BidirectionalCursorInfScroll({ startingProject = { id: 25 } }) {\n  const {\n    hasPreviousPage,\n    hasNextPage,\n    data,\n    error,\n    isFetching,\n    isLoading,\n    isError,\n    fetchNextPage,\n    fetchPreviousPage,\n    isFetchingNextPage,\n    isFetchingPreviousPage,\n  } =\n    apiWithInfiniteScroll.endpoints.getProjectsBidirectionalCursor.useInfiniteQuery(\n      limit,\n      {\n        initialPageParam: {\n          around: startingProject.id,\n          limit,\n        },\n      },\n    )\n\n  const beforeRef = useIntersectionCallback(fetchPreviousPage)\n  const afterRef = useIntersectionCallback(fetchNextPage)\n\n  const location = useLocation()\n\n  const startingProjectRef = useRef<HTMLDivElement>(null)\n  const [hasCentered, setHasCentered] = useState(false)\n\n  useEffect(() => {\n    if (hasCentered) return\n    const startingElement = startingProjectRef.current\n    if (startingElement) {\n      startingElement.scrollIntoView({\n        behavior: \"auto\",\n        block: \"center\",\n      })\n      setHasCentered(true)\n    }\n  }, [data?.pages, hasCentered])\n\n  return (\n    <div>\n      <h2>Bidirectional Cursor-Based Infinite Scroll</h2>\n      {isLoading ? (\n        <p>Loading...</p>\n      ) : isError ? (\n        <span>Error: {error.message}</span>\n      ) : null}\n      <>\n        <div>\n          <button\n            onClick={() => fetchPreviousPage()}\n            disabled={!hasPreviousPage || isFetchingPreviousPage}\n          >\n            {isFetchingPreviousPage\n              ? \"Loading more...\"\n              : hasPreviousPage\n                ? \"Load Older\"\n                : \"Nothing more to load\"}\n          </button>\n        </div>\n        <div\n          style={{\n            overflow: \"auto\",\n            margin: \"1rem 0px\",\n            height: \"400px\",\n          }}\n        >\n          <div ref={beforeRef} />\n          {data?.pages.map(page => (\n            <React.Fragment key={page.pageInfo?.endCursor}>\n              {page.projects.map((project, index, arr) => {\n                return (\n                  <div\n                    style={{\n                      margin: \"1em 0px\",\n                      border: \"1px solid gray\",\n                      borderRadius: \"5px\",\n                      padding: \"2rem 1rem\",\n                      background: `hsla(${project.id * 30}, 60%, 80%, 1)`,\n                    }}\n                    key={project.id}\n                    ref={\n                      project.id === startingProject.id\n                        ? startingProjectRef\n                        : null\n                    }\n                  >\n                    <div>{`Project ${project.id} (created at: ${project.createdAt})`}</div>\n                    <div>{`Server Time: ${page.serverTime}`}</div>\n                  </div>\n                )\n              })}\n            </React.Fragment>\n          ))}\n          <div ref={afterRef} />\n        </div>\n        <div>\n          <button\n            onClick={() => fetchNextPage()}\n            disabled={!hasNextPage || isFetchingNextPage}\n          >\n            {isFetchingNextPage\n              ? \"Loading more...\"\n              : hasNextPage\n                ? \"Load Newer\"\n                : \"Nothing more to load\"}\n          </button>\n        </div>\n        <div>\n          {isFetching && !isFetchingPreviousPage && !isFetchingNextPage\n            ? \"Background Updating...\"\n            : null}\n        </div>\n      </>\n\n      <hr />\n      <Link to=\"/infinite-scroll/about\" state={{ from: location.pathname }}>\n        Go to another page\n      </Link>\n    </div>\n  )\n}\n\nexport default BidirectionalCursorInfScroll\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/bidirectional-cursor-infinite-scroll/infiniteScrollApi.ts",
    "content": "import { baseApi } from \"../baseApi\"\n\ntype Project = {\n  id: number\n  createdAt: string\n}\n\ntype ProjectsCursorPaginated = {\n  projects: Project[]\n  serverTime: string\n  pageInfo: {\n    startCursor: number\n    endCursor: number\n    hasNextPage: boolean\n    hasPreviousPage: boolean\n  }\n}\n\ntype ProjectsInitialPageParam = {\n  before?: number\n  around?: number\n  after?: number\n  limit: number\n}\ntype QueryParamLimit = number\n\nexport const apiWithInfiniteScroll = baseApi.injectEndpoints({\n  endpoints: build => ({\n    getProjectsBidirectionalCursor: build.infiniteQuery<\n      ProjectsCursorPaginated,\n      QueryParamLimit,\n      ProjectsInitialPageParam\n    >({\n      query: ({ pageParam: { before, after, around, limit } }) => {\n        const params = new URLSearchParams()\n        params.append(\"limit\", String(limit))\n        if (after != null) {\n          params.append(\"after\", String(after))\n        } else if (before != null) {\n          params.append(\"before\", String(before))\n        } else if (around != null) {\n          params.append(\"around\", String(around))\n        }\n\n        return {\n          url: `https://example.com/api/projectsBidirectionalCursor?${params.toString()}`,\n        }\n      },\n      infiniteQueryOptions: {\n        initialPageParam: { limit: 10 },\n        getPreviousPageParam: (\n          firstPage,\n          allPages,\n          firstPageParam,\n          allPageParams,\n        ) => {\n          if (!firstPage.pageInfo.hasPreviousPage) {\n            return undefined\n          }\n          return {\n            before: firstPage.pageInfo.startCursor,\n            limit: firstPageParam.limit,\n          }\n        },\n        getNextPageParam: (\n          lastPage,\n          allPages,\n          lastPageParam,\n          allPageParams,\n        ) => {\n          if (!lastPage.pageInfo.hasNextPage) {\n            return undefined\n          }\n          return {\n            after: lastPage.pageInfo.endCursor,\n            limit: lastPageParam.limit,\n          }\n        },\n      },\n    }),\n  }),\n})\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/infinite-scroll/InfiniteScrollExample.tsx",
    "content": "import React from \"react\"\nimport { useInView } from \"react-intersection-observer\"\nimport { Link } from \"react-router\"\n\nimport { apiWithInfiniteScroll } from \"./infiniteScrollApi\"\nimport type { Project } from \"./infiniteScrollApi\"\n\nexport const InfiniteScrollAbout = () => {\n  return (\n    <a\n      href=\"\"\n      onClick={e => {\n        window.history.back()\n        e.preventDefault()\n      }}\n    >\n      Back\n    </a>\n  )\n}\n\nexport const ProjectRow = ({ project }: { project: Project }) => {\n  return (\n    <p\n      style={{\n        border: \"1px solid gray\",\n        borderRadius: \"5px\",\n        padding: \"5rem 1rem\",\n        background: `hsla(${project.id * 30}, 60%, 80%, 1)`,\n      }}\n      key={project.id}\n    >\n      {project.name}\n    </p>\n  )\n}\n\nexport const InfiniteScrollExample = () => {\n  const {\n    data,\n    error,\n    fetchNextPage,\n    fetchPreviousPage,\n    hasNextPage,\n    isFetchingNextPage,\n    isFetching,\n    isError,\n  } =\n    apiWithInfiniteScroll.endpoints.getProjectsCursor.useInfiniteQuery(\n      \"projects\",\n    )\n\n  const { ref, inView } = useInView()\n\n  React.useEffect(() => {\n    if (inView) {\n      console.log(\"Fetching next page\")\n      fetchNextPage()\n    }\n  }, [fetchNextPage, inView])\n\n  return (\n    <div>\n      <h2>Infinite Scroll Example</h2>\n      {isFetching ? (\n        <p>Loading...</p>\n      ) : isError ? (\n        <span>Error: {error.message}</span>\n      ) : null}\n      {\n        <>\n          <div>\n            <button\n              onClick={() => fetchPreviousPage()}\n              // disabled={!hasPreviousPage || isFetchingPreviousPage}\n            >\n              {/* {isFetchingPreviousPage\n                ? \"Loading more...\"\n                : hasPreviousPage\n                  ? \"Load Older\"\n                  : \"Nothing more to load\"} */}\n            </button>\n          </div>\n          {data?.pages.map(page => (\n            <React.Fragment key={page.nextId}>\n              {page.projects.map(project => (\n                <ProjectRow key={project.id} project={project} />\n              ))}\n            </React.Fragment>\n          ))}\n          <div>\n            <button\n              ref={ref}\n              onClick={() => fetchNextPage()}\n              disabled={!hasNextPage || isFetchingNextPage}\n            >\n              {isFetchingNextPage\n                ? \"Loading more...\"\n                : hasNextPage\n                  ? \"Load Newer\"\n                  : \"Nothing more to load\"}\n            </button>\n          </div>\n          <div>{isFetching ? \"Background Updating...\" : null}</div>\n        </>\n      }\n      <hr />\n      <Link to=\"/infinite-scroll/about\">Go to another page</Link>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/infinite-scroll/infiniteScrollApi.ts",
    "content": "import { baseApi } from \"../baseApi\"\n\nexport type Project = {\n  id: number\n  name: string\n}\n\ntype ProjectsPageCursor = {\n  projects: Project[]\n  nextId: number | null\n  previousId: number | null\n}\n\nexport const apiWithInfiniteScroll = baseApi.injectEndpoints({\n  endpoints: build => ({\n    getProjectsCursor: build.infiniteQuery<ProjectsPageCursor, string, number>({\n      query: ({ pageParam }) =>\n        `https://example.com/api/projectsCursor?cursor=${pageParam}`,\n      infiniteQueryOptions: {\n        initialPageParam: 0,\n        getPreviousPageParam: firstPage => firstPage.previousId,\n        getNextPageParam: (\n          lastPage,\n          allPages,\n          lastPageParam,\n          allPageParams,\n        ) => {\n          return lastPage.nextId\n        },\n      },\n    }),\n  }),\n})\n\n// export const { useGetProjectsQuery } = apiWithPagination\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/limit-offset/LimitOffsetExample.tsx",
    "content": "import { createSelector } from \"@reduxjs/toolkit\"\nimport {\n  BaseQueryFn,\n  TypedUseQueryStateResult,\n} from \"@reduxjs/toolkit/query/react\"\nimport { Link, useLocation } from \"react-router\"\nimport { useIntersectionCallback } from \"../../app/useIntersectionCallback\"\nimport { apiWithInfiniteScroll, ProjectsResponse } from \"./infiniteScrollApi\"\n\ntype ProjectsInfiniteQueryResult = TypedUseQueryStateResult<\n  { pages: ProjectsResponse[] },\n  unknown,\n  BaseQueryFn\n>\n\nconst selectCombinedProjects = createSelector(\n  (res: ProjectsInfiniteQueryResult) => {\n    return res.data\n  },\n  data => data?.pages?.map(item => item?.projects)?.flat(),\n)\n\nfunction LimitOffsetExample() {\n  const {\n    combinedData,\n    hasPreviousPage,\n    hasNextPage,\n    // data,\n    error,\n    isFetching,\n    isLoading,\n    isError,\n    fetchNextPage,\n    fetchPreviousPage,\n    isFetchingNextPage,\n    isFetchingPreviousPage,\n  } = apiWithInfiniteScroll.endpoints.projectsLimitOffset.useInfiniteQuery(\n    undefined,\n    {\n      selectFromResult: result => {\n        return {\n          ...result,\n          combinedData: selectCombinedProjects(result),\n        }\n      },\n    },\n  )\n\n  const intersectionCallbackRef = useIntersectionCallback(fetchNextPage)\n  const location = useLocation()\n\n  return (\n    <div>\n      <h2>Limit and Offset Infinite Scroll</h2>\n      {isLoading ? (\n        <p>Loading...</p>\n      ) : isError ? (\n        <span>Error: {error.message}</span>\n      ) : null}\n\n      <>\n        <div>\n          <button\n            onClick={() => fetchPreviousPage()}\n            disabled={!hasPreviousPage || isFetchingPreviousPage}\n          >\n            {isFetchingPreviousPage\n              ? \"Loading more...\"\n              : hasPreviousPage\n                ? \"Load Older\"\n                : \"Nothing more to load\"}\n          </button>\n        </div>\n        <div\n          style={{\n            overflow: \"auto\",\n            margin: \"1rem 0px\",\n            height: \"400px\",\n          }}\n        >\n          {combinedData?.map((project, index, arr) => {\n            return (\n              <div\n                style={{\n                  margin: \"1em 0px\",\n                  border: \"1px solid gray\",\n                  borderRadius: \"5px\",\n                  padding: \"2rem 1rem\",\n                  background: `hsla(${project.id * 30}, 60%, 80%, 1)`,\n                }}\n                key={project.id}\n              >\n                <div>\n                  <div>{`Project ${project.id} (created at: ${project.createdAt})`}</div>\n                </div>\n              </div>\n            )\n          })}\n\n          <div ref={intersectionCallbackRef} />\n        </div>\n        <div>\n          <button\n            onClick={() => fetchNextPage()}\n            disabled={!hasNextPage || isFetchingNextPage}\n          >\n            {isFetchingNextPage\n              ? \"Loading more...\"\n              : hasNextPage\n                ? \"Load Newer\"\n                : \"Nothing more to load\"}\n          </button>\n        </div>\n        <div>\n          {isFetching && !isFetchingPreviousPage && !isFetchingNextPage\n            ? \"Background Updating...\"\n            : null}\n        </div>\n      </>\n\n      <hr />\n      <Link to=\"/infinite-scroll/about\" state={{ from: location.pathname }}>\n        Go to another page\n      </Link>\n    </div>\n  )\n}\n\nexport default LimitOffsetExample\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/limit-offset/infiniteScrollApi.ts",
    "content": "import { baseApi } from \"../baseApi\"\n\ntype Project = {\n  id: number\n  createdAt: string\n}\n\nexport type ProjectsResponse = {\n  projects: Project[]\n  numFound: number\n  serverTime: string\n}\n\ntype ProjectsInitialPageParam = {\n  offset: number\n  limit: number\n}\n\nexport const apiWithInfiniteScroll = baseApi.injectEndpoints({\n  endpoints: build => ({\n    projectsLimitOffset: build.infiniteQuery<\n      ProjectsResponse,\n      void,\n      ProjectsInitialPageParam\n    >({\n      infiniteQueryOptions: {\n        initialPageParam: {\n          offset: 0,\n          limit: 20,\n        },\n        getNextPageParam: (\n          lastPage,\n          allPages,\n          lastPageParam,\n          allPageParams,\n        ) => {\n          const nextOffset = lastPageParam.offset + lastPageParam.limit\n          const remainingItems = lastPage?.numFound - nextOffset\n\n          if (remainingItems <= 0) {\n            return undefined\n          }\n\n          return {\n            ...lastPageParam,\n            offset: nextOffset,\n          }\n        },\n        getPreviousPageParam: (\n          firstPage,\n          allPages,\n          firstPageParam,\n          allPageParams,\n        ) => {\n          const prevOffset = firstPageParam.offset - firstPageParam.limit\n          if (prevOffset < 0) return undefined\n\n          return {\n            ...firstPageParam,\n            offset: firstPageParam.offset - firstPageParam.limit,\n          }\n        },\n      },\n      query: ({ pageParam: { offset, limit } }) => {\n        return `https://example.com/api/projectsLimitOffset?offset=${offset}&limit=${limit}`\n      },\n    }),\n  }),\n})\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/max-pages/InfiniteScrollMaxExample.tsx",
    "content": "import React from \"react\"\nimport { apiWithInfiniteScrollMax } from \"./infiniteScrollApi\"\n\nexport const InfiniteScrollMaxPagesExample = () => {\n  const {\n    data,\n    error,\n    fetchNextPage,\n    fetchPreviousPage,\n    // hasNextPage,\n    isFetchingNextPage,\n    isFetching,\n    isError,\n  } =\n    apiWithInfiniteScrollMax.endpoints.getProjectsCursorMax.useInfiniteQuery(\n      \"projects\",\n    )\n\n  // TODO This should be built in to RTKQ\n  const hasNextPage = data?.pages[data.pages.length - 1].nextId !== null\n  const hasPreviousPage = data?.pages[0].previousId !== null\n\n  return (\n    <div>\n      <h2>Infinite Query with max pages</h2>\n      <h3>3 pages max</h3>\n      {isFetching ? (\n        <p>Loading...</p>\n      ) : isError ? (\n        <span>Error: {error.message}</span>\n      ) : (\n        <>\n          <div>\n            <button\n              onClick={() => fetchPreviousPage()}\n              disabled={!hasPreviousPage /* || isFetchingPreviousPage*/}\n            >\n              {\n                /*isFetchingPreviousPage\n                  ? 'Loading more...'\n                  :*/ hasPreviousPage ? \"Load Older\" : \"Nothing more to load\"\n              }\n            </button>\n          </div>\n          {data?.pages.map(page => (\n            <React.Fragment key={page.nextId}>\n              {page.projects.map(project => (\n                <p\n                  style={{\n                    border: \"1px solid gray\",\n                    borderRadius: \"5px\",\n                    padding: \"8px\",\n                    fontSize: \"14px\",\n                    background: `hsla(${project.id * 30}, 60%, 80%, 1)`,\n                  }}\n                  key={project.id}\n                >\n                  {project.name}\n                </p>\n              ))}\n            </React.Fragment>\n          ))}\n          <div>\n            <button\n              onClick={() => fetchNextPage()}\n              disabled={!hasNextPage /* || isFetchingNextPage*/}\n            >\n              {isFetchingNextPage\n                ? \"Loading more...\"\n                : hasNextPage\n                  ? \"Load Newer\"\n                  : \"Nothing more to load\"}\n            </button>\n          </div>\n          <div>\n            {isFetching && !isFetchingNextPage\n              ? \"Background Updating...\"\n              : null}\n          </div>\n        </>\n      )}\n      <hr />\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/max-pages/infiniteScrollApi.ts",
    "content": "import { baseApi } from \"../baseApi\"\n\ntype Project = {\n  id: number\n  name: string\n}\n\ntype ProjectsPageCursor = {\n  projects: Project[]\n  nextId: number | null\n  previousId: number | null\n}\n\nexport const apiWithInfiniteScrollMax = baseApi.injectEndpoints({\n  endpoints: build => ({\n    getProjectsCursorMax: build.infiniteQuery<\n      ProjectsPageCursor,\n      string,\n      number\n    >({\n      query: ({ pageParam }) =>\n        `https://example.com/api/projectsCursor?cursor=${pageParam}`,\n      infiniteQueryOptions: {\n        initialPageParam: 0,\n        maxPages: 3,\n        getPreviousPageParam: firstPage => firstPage.previousId ?? undefined,\n        getNextPageParam: lastPage => lastPage.nextId ?? undefined,\n      },\n    }),\n  }),\n})\n\n// export const { useGetProjectsQuery } = apiWithPagination\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/pagination/PaginationExample.tsx",
    "content": "import React from \"react\"\nimport { apiWithPagination } from \"./paginationApi\"\n\n// The React Query example actually just uses a normal query\n// rather than an infinite query, and Dominik confirmed that\n// that \"infinite queries\" should really only be used if you\n// want to display _all_ of the pages.\n// > \"The drawback is shown right in your example: fetching is no longer declarative - you need to keep page in-sync with fetchNextPage. And if you are on page 3 and go back to two, then forward to 3 again it falls apart as fetchNextPage would fetch page 4 instead of refetching page 3\"\n// Still, it's worth exploring how we might use infinite queries\n// for a basic pagination scenario.\n\nexport const PaginationExample = () => {\n  const [page, setPage] = React.useState(0)\n  const {\n    data,\n    error,\n    fetchNextPage,\n    hasNextPage,\n    isFetchingNextPage,\n    isFetching,\n    isError,\n  } = apiWithPagination.endpoints.getProjects.useInfiniteQuery(\"projects\")\n\n  const currentPage = data?.pages[page]\n\n  return (\n    <div>\n      <h2>Pagination Example</h2>\n      <div>Current Page: {page + 1}</div>\n      <button\n        onClick={() => {\n          setPage(old => Math.max(old - 1, 0))\n        }}\n        disabled={page === 0}\n      >\n        Previous Page\n      </button>{\" \"}\n      <button\n        onClick={() => {\n          setPage(old => (currentPage?.hasMore ? old + 1 : old))\n          fetchNextPage()\n        }}\n        disabled={!currentPage?.hasMore}\n      >\n        Next Page\n      </button>\n      <h3>Results</h3>\n      {isFetching ? (\n        <div>Loading...</div>\n      ) : isError ? (\n        <div>Error: {error.message}</div>\n      ) : (\n        <div>\n          {currentPage?.projects.map(project => (\n            <p key={project.id}>{project.name}</p>\n          ))}\n        </div>\n      )}\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/pagination/paginationApi.ts",
    "content": "import { baseApi } from \"../baseApi\"\n\ntype Project = {\n  id: number\n  name: string\n}\n\ntype ProjectsPage = {\n  projects: Project[]\n  hasMore: boolean\n}\n\nexport const apiWithPagination = baseApi.injectEndpoints({\n  endpoints: build => ({\n    getProjects: build.infiniteQuery<ProjectsPage, string, number>({\n      query: ({ pageParam }) =>\n        `https://example.com/api/projects?page=${pageParam}`,\n      infiniteQueryOptions: {\n        initialPageParam: 0,\n        getNextPageParam: (lastPage, pages, lastPageParam, allPageParams) => {\n          if (!lastPage.hasMore) return undefined\n          return pages.length\n        },\n      },\n    }),\n  }),\n})\n\n// export const { useGetProjectsQuery } = apiWithPagination\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/pagination-infinite-scroll/PaginationInfScrollExample.tsx",
    "content": "import { createSelector } from \"@reduxjs/toolkit\"\nimport {\n  BaseQueryFn,\n  TypedUseQueryStateResult,\n} from \"@reduxjs/toolkit/query/react\"\nimport { Link, useLocation } from \"react-router\"\nimport { useIntersectionCallback } from \"../../app/useIntersectionCallback\"\nimport { apiWithInfiniteScroll, ProjectsResponse } from \"./infiniteScrollApi\"\n\ntype ProjectsInfiniteQueryResult = TypedUseQueryStateResult<\n  { pages: ProjectsResponse[] },\n  unknown,\n  BaseQueryFn\n>\n\nconst selectCombinedProjects = createSelector(\n  (res: ProjectsInfiniteQueryResult) => {\n    return res.data\n  },\n  data => data?.pages?.map(item => item?.projects)?.flat(),\n)\n\nfunction PaginationInfScrollExample() {\n  const {\n    combinedData,\n    hasPreviousPage,\n    hasNextPage,\n    // data,\n    error,\n    isFetching,\n    isLoading,\n    isError,\n    fetchNextPage,\n    fetchPreviousPage,\n    isFetchingNextPage,\n    isFetchingPreviousPage,\n  } = apiWithInfiniteScroll.endpoints.projectsPaginated.useInfiniteQuery(\n    undefined,\n    {\n      selectFromResult: result => {\n        return {\n          ...result,\n          combinedData: selectCombinedProjects(result),\n        }\n      },\n    },\n  )\n\n  const intersectionCallbackRef = useIntersectionCallback(fetchNextPage)\n  const location = useLocation()\n\n  return (\n    <div>\n      <h2>Pagination Infinite Scroll</h2>\n      {isLoading ? (\n        <p>Loading...</p>\n      ) : isError ? (\n        <span>Error: {error.message}</span>\n      ) : null}\n\n      <>\n        <div>\n          <button\n            onClick={() => fetchPreviousPage()}\n            disabled={!hasPreviousPage || isFetchingPreviousPage}\n          >\n            {isFetchingPreviousPage\n              ? \"Loading more...\"\n              : hasPreviousPage\n                ? \"Load Older\"\n                : \"Nothing more to load\"}\n          </button>\n        </div>\n        <div\n          style={{\n            overflow: \"auto\",\n            margin: \"1rem 0px\",\n            height: \"400px\",\n          }}\n        >\n          {combinedData?.map((project, index, arr) => {\n            return (\n              <div\n                style={{\n                  margin: \"1em 0px\",\n                  border: \"1px solid gray\",\n                  borderRadius: \"5px\",\n                  padding: \"2rem 1rem\",\n                  background: `hsla(${project.id * 30}, 60%, 80%, 1)`,\n                }}\n                key={project.id}\n              >\n                <div>\n                  <div>{`Project ${project.id} (created at: ${project.createdAt})`}</div>\n                </div>\n              </div>\n            )\n          })}\n\n          <div ref={intersectionCallbackRef} />\n        </div>\n        <div>\n          <button\n            onClick={() => fetchNextPage()}\n            disabled={!hasNextPage || isFetchingNextPage}\n          >\n            {isFetchingNextPage\n              ? \"Loading more...\"\n              : hasNextPage\n                ? \"Load Newer\"\n                : \"Nothing more to load\"}\n          </button>\n        </div>\n        <div>\n          {isFetching && !isFetchingPreviousPage && !isFetchingNextPage\n            ? \"Background Updating...\"\n            : null}\n        </div>\n      </>\n\n      <hr />\n      <Link to=\"/infinite-scroll/about\" state={{ from: location.pathname }}>\n        Go to another page\n      </Link>\n    </div>\n  )\n}\n\nexport default PaginationInfScrollExample\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/pagination-infinite-scroll/infiniteScrollApi.ts",
    "content": "import { baseApi } from \"../baseApi\"\n\ntype Project = {\n  id: number\n  createdAt: string\n}\n\nexport type ProjectsResponse = {\n  projects: Project[]\n  serverTime: string\n  totalPages: number\n}\n\ninterface ProjectsInitialPageParam {\n  page: number\n  size: number\n}\n\nexport const apiWithInfiniteScroll = baseApi.injectEndpoints({\n  endpoints: build => ({\n    projectsPaginated: build.infiniteQuery<\n      ProjectsResponse,\n      void,\n      ProjectsInitialPageParam\n    >({\n      infiniteQueryOptions: {\n        initialPageParam: {\n          page: 0,\n          size: 20,\n        },\n        getNextPageParam: (\n          lastPage,\n          allPages,\n          lastPageParam,\n          allPageParams,\n        ) => {\n          const nextPage = lastPageParam.page + 1\n          const remainingPages = lastPage?.totalPages - nextPage\n\n          if (remainingPages <= 0) {\n            return undefined\n          }\n\n          return {\n            ...lastPageParam,\n            page: nextPage,\n          }\n        },\n        getPreviousPageParam: (\n          firstPage,\n          allPages,\n          firstPageParam,\n          allPageParams,\n        ) => {\n          const prevPage = firstPageParam.page - 1\n          if (prevPage < 0) return undefined\n\n          return {\n            ...firstPageParam,\n            page: prevPage,\n          }\n        },\n      },\n      query: ({ pageParam: { page, size } }) => {\n        return {\n          url: `https://example.com/api/projectsPaginated?page=${page}&size=${size}`,\n          method: \"GET\",\n        }\n      },\n    }),\n  }),\n})\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/features/rn-flatlist/FlatlistExample.tsx",
    "content": "import { ActivityIndicator, FlatList, View, Text } from \"react-native-web\"\nimport { useMemo } from \"react\"\n\nimport { apiWithInfiniteScroll } from \"../infinite-scroll/infiniteScrollApi\"\nimport { ProjectRow } from \"../infinite-scroll/InfiniteScrollExample\"\n\nexport const FlatlistExample = () => {\n  const {\n    data,\n    error,\n    fetchNextPage,\n    fetchPreviousPage,\n    hasNextPage,\n    isFetchingNextPage,\n    isLoading,\n    isFetching,\n    isError,\n    // refetch,\n  } =\n    apiWithInfiniteScroll.endpoints.getProjectsCursor.useInfiniteQuery(\n      \"projects\",\n    )\n\n  const allProjects = useMemo(() => {\n    return data?.pages.flatMap(page => page.projects) ?? []\n  }, [data])\n\n  return (\n    <>\n      <h2>React Native FlatList Example</h2>\n      <View style={{ width: \"100%\", maxHeight: \"600px\" }}>\n        {isLoading ? (\n          <ActivityIndicator />\n        ) : isError ? (\n          <Text>{error?.message}</Text>\n        ) : (\n          <FlatList\n            data={allProjects}\n            keyExtractor={item => item.id.toString()}\n            renderItem={({ item }) => <ProjectRow project={item} />}\n            // onRefresh={refetch}\n            refreshing={isLoading}\n            progressViewOffset={100}\n            onEndReached={() => fetchNextPage()}\n          />\n        )}\n      </View>\n    </>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/index.css",
    "content": "body {\n  margin: 0;\n  font-family: -apple-system, BlinkMacSystemFont, \"Segoe UI\", \"Roboto\", \"Oxygen\",\n    \"Ubuntu\", \"Cantarell\", \"Fira Sans\", \"Droid Sans\", \"Helvetica Neue\",\n    sans-serif;\n  -webkit-font-smoothing: antialiased;\n  -moz-osx-font-smoothing: grayscale;\n}\n\ncode {\n  font-family: source-code-pro, Menlo, Monaco, Consolas, \"Courier New\",\n    monospace;\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/main.tsx",
    "content": "import React from \"react\"\nimport { createRoot } from \"react-dom/client\"\nimport { Provider } from \"react-redux\"\nimport App from \"./App\"\nimport { store } from \"./app/store\"\nimport \"./index.css\"\n\nasync function enableMocking() {\n  if (process.env.NODE_ENV !== \"development\") {\n    return\n  }\n\n  const { worker } = await import(\"./mocks/browser\")\n\n  return worker.start()\n}\n\nenableMocking().then(() => {\n  const container = document.getElementById(\"root\")\n\n  if (container) {\n    const root = createRoot(container)\n\n    root.render(\n      <React.StrictMode>\n        <Provider store={store}>\n          <App />\n        </Provider>\n      </React.StrictMode>,\n    )\n  } else {\n    throw new Error(\n      \"Root element with ID 'root' was not found in the document. Ensure there is a corresponding HTML element with the ID 'root' in your HTML file.\",\n    )\n  }\n})\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/mocks/browser.ts",
    "content": "import { setupWorker } from \"msw/browser\"\nimport { handlers } from \"./handlers\"\n\nexport const worker = setupWorker(...handlers)\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/mocks/handlers.ts",
    "content": "import { http, HttpResponse } from \"msw\"\n\nfunction delay(ms: number) {\n  return new Promise(resolve => setTimeout(resolve, ms))\n}\n\nconst projects = Array.from({ length: 50 }, (_, i) => {\n  return {\n    id: i,\n    createdAt: Date.now() + i * 1000,\n  }\n})\n\nexport const handlers = [\n  http.get(\"https://example.com/api/projects\", async ({ request, params }) => {\n    const url = new URL(request.url)\n    const pageParam = url.searchParams.get(\"page\") || \"0\"\n    const page = parseInt(pageParam, 10)\n\n    const pageSize = 10\n    const maxPages = 5\n\n    await delay(1000)\n\n    const projects = Array(pageSize)\n      .fill(0)\n      .map((_, i) => {\n        const id = page * pageSize + (i + 1)\n        return {\n          name: \"Project \" + id,\n          id,\n        }\n      })\n\n    return HttpResponse.json({\n      projects,\n      // 0-based pagination, so match total count\n      hasMore: page < maxPages - 1,\n    })\n  }),\n  http.get(\n    \"https://example.com/api/projectsCursor\",\n    async ({ request, params }) => {\n      const url = new URL(request.url)\n      const cursorParam = url.searchParams.get(\"cursor\") || \"0\"\n      const cursor = parseInt(cursorParam, 10)\n\n      const pageSize = 10\n      const totalItems = 50\n\n      await delay(1000)\n\n      const projects = Array(pageSize)\n        .fill(0)\n        .map((_, i) => {\n          const id = cursor + i\n          return {\n            name: \"Project \" + id + ` (server time: ${Date.now()})`,\n            id,\n          }\n        })\n\n      const hasNext = cursor < totalItems - pageSize\n      const nextId = hasNext ? projects[projects.length - 1].id + 1 : null\n\n      // Prevent negative cursors\n      const hasPrevious = cursor > -(totalItems - pageSize)\n      const maybePrevCursor = projects[0].id - pageSize\n      const previousId =\n        hasPrevious && maybePrevCursor >= 0 ? maybePrevCursor : null\n\n      return HttpResponse.json({\n        projects,\n        nextId,\n        previousId,\n      })\n    },\n  ),\n  http.get(\n    \"https://example.com/api/projectsBidirectionalCursor\",\n    async ({ request }) => {\n      const url = new URL(request.url)\n      const limit = parseInt(url.searchParams.get(\"limit\") ?? \"5\", 10)\n      const aroundCursor = parseInt(url.searchParams.get(\"around\") ?? \"\", 10)\n      const afterCursor = parseInt(url.searchParams.get(\"after\") ?? \"\", 10)\n      const beforeCursor = parseInt(url.searchParams.get(\"before\") ?? \"\", 10)\n\n      const validateCursor = (cursor: number, cursorType: string): number => {\n        const cursorIndex = projects.findIndex(project => project.id === cursor)\n        if (cursorIndex === -1) {\n          throw new Error(`Invalid \\`${cursorType}\\` cursor.`)\n        }\n        return cursorIndex\n      }\n\n      let resultProjects = []\n      try {\n        if (!isNaN(afterCursor)) {\n          const afterCursorIndex = validateCursor(afterCursor, \"after\")\n          const afterIndex = afterCursorIndex + 1\n          resultProjects = projects.slice(afterIndex, afterIndex + limit)\n        } else if (!isNaN(beforeCursor)) {\n          const beforeCursorIndex = validateCursor(beforeCursor, \"before\")\n          const startIndex = Math.max(0, beforeCursorIndex - limit)\n          resultProjects = projects.slice(startIndex, beforeCursorIndex)\n        } else if (!isNaN(aroundCursor)) {\n          const aroundCursorIndex = validateCursor(aroundCursor, \"around\")\n          const ceiledLimit = Math.ceil(limit / 2)\n\n          const beforeIndex = Math.max(0, aroundCursorIndex - ceiledLimit)\n          const afterIndex = Math.min(\n            projects.length - 1,\n            aroundCursorIndex + ceiledLimit,\n          )\n          const beforeProjects = projects.slice(beforeIndex, aroundCursorIndex)\n          const afterProjects = projects.slice(\n            aroundCursorIndex + 1,\n            afterIndex + 1,\n          )\n\n          resultProjects = [\n            ...beforeProjects,\n            projects[aroundCursorIndex],\n            ...afterProjects,\n          ]\n        } else {\n          resultProjects = projects.slice(0, limit)\n        }\n\n        const startCursor = resultProjects[0]?.id\n        const endCursor = resultProjects[resultProjects.length - 1]?.id\n\n        const hasNextPage = endCursor != null && endCursor < projects.length - 1\n        const hasPreviousPage = startCursor !== 0\n\n        await delay(1000)\n        return HttpResponse.json({\n          projects: resultProjects,\n          serverTime: Date.now(),\n          pageInfo: {\n            startCursor,\n            endCursor,\n            hasNextPage,\n            hasPreviousPage,\n          },\n        })\n      } catch (error) {\n        if (error instanceof Error) {\n          return HttpResponse.json({ message: error.message }, { status: 400 })\n        }\n      }\n    },\n  ),\n  http.get(\n    \"https://example.com/api/projectsLimitOffset\",\n    async ({ request }) => {\n      const url = new URL(request.url)\n      const limit = parseInt(url.searchParams.get(\"limit\") ?? \"5\", 10)\n      let offset = parseInt(url.searchParams.get(\"offset\") ?? \"0\", 10)\n\n      if (isNaN(offset) || offset < 0) {\n        offset = 0\n      }\n      if (isNaN(limit) || limit <= 0) {\n        return HttpResponse.json(\n          {\n            message:\n              \"Invalid 'limit' parameter. It must be a positive integer.\",\n          },\n          { status: 400 },\n        )\n      }\n\n      const result = projects.slice(offset, offset + limit)\n\n      await delay(1000)\n      return HttpResponse.json({\n        projects: result,\n        serverTime: Date.now(),\n        numFound: projects.length,\n      })\n    },\n  ),\n  http.get(\"https://example.com/api/projectsPaginated\", async ({ request }) => {\n    const url = new URL(request.url)\n    const size = parseInt(url.searchParams.get(\"size\") ?? \"5\", 10)\n    let page = parseInt(url.searchParams.get(\"page\") ?? \"0\", 10)\n\n    if (isNaN(page) || page < 0) {\n      page = 0\n    }\n    if (isNaN(size) || size <= 0) {\n      return HttpResponse.json(\n        { message: \"Invalid 'size' parameter. It must be a positive integer.\" },\n        { status: 400 },\n      )\n    }\n\n    const startIndex = page * size\n    const endIndex = startIndex + size\n    const result = projects.slice(startIndex, endIndex)\n\n    await delay(1000)\n    return HttpResponse.json({\n      projects: result,\n      serverTime: Date.now(),\n      totalPages: Math.ceil(projects.length / size), // totalPages is a parameter required for this example, but an API could include additional fields that can be used in certain scenarios, such as determining getNextPageParam or getPreviousPageParam.\n      // totalElements: projects.length,\n      // numberOfElements: result.length,\n      // isLast: endIndex >= projects.length,\n      // isFirst: page === 0,\n    })\n  }),\n]\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/setupTests.ts",
    "content": "import \"@testing-library/jest-dom/vitest\"\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/utils/test-utils.tsx",
    "content": "import type { RenderOptions } from \"@testing-library/react\"\nimport { render } from \"@testing-library/react\"\nimport userEvent from \"@testing-library/user-event\"\nimport type { PropsWithChildren, ReactElement } from \"react\"\nimport { Provider } from \"react-redux\"\nimport type { AppStore, RootState } from \"../app/store\"\nimport { makeStore } from \"../app/store\"\n\n/**\n * This type extends the default options for\n * React Testing Library's render function. It allows for\n * additional configuration such as specifying an initial Redux state and\n * a custom store instance.\n */\ninterface ExtendedRenderOptions extends Omit<RenderOptions, \"queries\"> {\n  /**\n   * Defines a specific portion or the entire initial state for the Redux store.\n   * This is particularly useful for initializing the state in a\n   * controlled manner during testing, allowing components to be rendered\n   * with predetermined state conditions.\n   */\n  preloadedState?: Partial<RootState>\n\n  /**\n   * Allows the use of a specific Redux store instance instead of a\n   * default or global store. This flexibility is beneficial when\n   * testing components with unique store requirements or when isolating\n   * tests from a global store state. The custom store should be configured\n   * to match the structure and middleware of the store used by the application.\n   *\n   * @default makeStore(preloadedState)\n   */\n  store?: AppStore\n}\n\n/**\n * Renders the given React element with Redux Provider and custom store.\n * This function is useful for testing components that are connected to the Redux store.\n *\n * @param ui - The React component or element to render.\n * @param extendedRenderOptions - Optional configuration options for rendering. This includes `preloadedState` for initial Redux state and `store` for a specific Redux store instance. Any additional properties are passed to React Testing Library's render function.\n * @returns An object containing the Redux store used in the render, User event API for simulating user interactions in tests, and all of React Testing Library's query functions for testing the component.\n */\nexport const renderWithProviders = (\n  ui: ReactElement,\n  extendedRenderOptions: ExtendedRenderOptions = {},\n) => {\n  const {\n    preloadedState = {},\n    // Automatically create a store instance if no store was passed in\n    store = makeStore(preloadedState),\n    ...renderOptions\n  } = extendedRenderOptions\n\n  const Wrapper = ({ children }: PropsWithChildren) => (\n    <Provider store={store}>{children}</Provider>\n  )\n\n  // Return an object with the store and all of RTL's query functions\n  return {\n    store,\n    user: userEvent.setup(),\n    ...render(ui, { wrapper: Wrapper, ...renderOptions }),\n  }\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/src/vite-env.d.ts",
    "content": "/// <reference types=\"vite/client\" />\n"
  },
  {
    "path": "examples/query/react/infinite-queries/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"lib\": [\"DOM\", \"DOM.Iterable\", \"ESNext\"],\n    \"allowJs\": false,\n    \"skipLibCheck\": true,\n    \"esModuleInterop\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"strict\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"bundler\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true,\n    \"jsx\": \"react-jsx\",\n    \"types\": [\"vitest/globals\", \"react-native-web\"]\n  },\n  \"references\": [{ \"path\": \"./tsconfig.node.json\" }]\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/tsconfig.node.json",
    "content": "{\n  \"compilerOptions\": {\n    \"composite\": true,\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"bundler\",\n    \"allowSyntheticDefaultImports\": true\n  },\n  \"include\": [\"vite.config.ts\"]\n}\n"
  },
  {
    "path": "examples/query/react/infinite-queries/vite.config.ts",
    "content": "import { defineConfig } from \"vitest/config\"\nimport react from \"@vitejs/plugin-react\"\n\n// https://vitejs.dev/config/\nexport default defineConfig({\n  plugins: [react()],\n  server: {\n    open: true,\n  },\n  test: {\n    globals: true,\n    environment: \"jsdom\",\n    setupFiles: \"src/setupTests\",\n    mockReset: true,\n  },\n})\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/kitchen-sink\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"getting-started-hooks\",\n  \"keywords\": [],\n  \"main\": \"src/index.tsx\",\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"1.8.1\",\n    \"msw\": \"^0.40.2\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-router-dom\": \"6.3.0\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@testing-library/dom\": \"^10.4.0\",\n    \"@testing-library/jest-dom\": \"^5.11.5\",\n    \"@testing-library/react\": \"^16.1.0\",\n    \"@types/jest\": \"^26.0.23\",\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"typescript\": \"^5.9.3\",\n    \"whatwg-fetch\": \"^3.4.1\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"test\": \"react-scripts test --runInBand\"\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ],\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"\n    />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <!--\n      manifest.json provides metadata used when your web app is added to the\n      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n\n  <body>\n    <noscript> You need to enable JavaScript to run this app. </noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query Authentication using extraReducers Example\",\n  \"name\": \"Authentication Example\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/public/mockServiceWorker.js",
    "content": "/* eslint-disable */\n/* tslint:disable */\n\n/**\n * Mock Service Worker (0.41.1).\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n\nconst INTEGRITY_CHECKSUM = '02f4ad4a2797f85668baf196e553d929'\nconst bypassHeaderName = 'x-msw-bypass'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  return self.skipWaiting()\n})\n\nself.addEventListener('activate', async function (event) {\n  return self.clients.claim()\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\n// Resolve the \"main\" client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMainClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMainClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: serializeHeaders(clonedResponse.headers),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const requestClone = request.clone()\n  const getOriginalResponse = () => fetch(requestClone)\n\n  // Bypass mocking when the request client is not active.\n  if (!client) {\n    return getOriginalResponse()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return await getOriginalResponse()\n  }\n\n  // Bypass requests with the explicit bypass header\n  if (requestClone.headers.get(bypassHeaderName) === 'true') {\n    const cleanRequestHeaders = serializeHeaders(requestClone.headers)\n\n    // Remove the bypass header to comply with the CORS preflight check.\n    delete cleanRequestHeaders[bypassHeaderName]\n\n    const originalRequest = new Request(requestClone, {\n      headers: new Headers(cleanRequestHeaders),\n    })\n\n    return fetch(originalRequest)\n  }\n\n  // Send the request to the client-side MSW.\n  const reqHeaders = serializeHeaders(request.headers)\n  const body = await request.text()\n\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: reqHeaders,\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body,\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_SUCCESS': {\n      return delayPromise(\n        () => respondWithMock(clientMessage),\n        clientMessage.payload.delay,\n      )\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return getOriginalResponse()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.payload\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a request Promise emulates a network error.\n      throw networkError\n    }\n\n    case 'INTERNAL_ERROR': {\n      const parsedBody = JSON.parse(clientMessage.payload.body)\n\n      console.error(\n        `\\\n[MSW] Uncaught exception in the request handler for \"%s %s\":\n\n${parsedBody.location}\n\nThis exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses\\\n`,\n        request.method,\n        request.url,\n      )\n\n      return respondWithMock(clientMessage)\n    }\n  }\n\n  return getOriginalResponse()\n}\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n  const accept = request.headers.get('accept') || ''\n\n  // Bypass server-sent events.\n  if (accept.includes('text/event-stream')) {\n    return\n  }\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  const requestId = uuidv4()\n\n  return event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      if (error.name === 'NetworkError') {\n        console.warn(\n          '[MSW] Successfully emulated a network error for the \"%s %s\" request.',\n          request.method,\n          request.url,\n        )\n        return\n      }\n\n      // At this point, any exception indicates an issue with the original request/response.\n      console.error(\n        `\\\n[MSW] Caught an exception from the \"%s %s\" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,\n        request.method,\n        request.url,\n        `${error.name}: ${error.message}`,\n      )\n    }),\n  )\n})\n\nfunction serializeHeaders(headers) {\n  const reqHeaders = {}\n  headers.forEach((value, name) => {\n    reqHeaders[name] = reqHeaders[name]\n      ? [].concat(reqHeaders[name]).concat(value)\n      : value\n  })\n  return reqHeaders\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(JSON.stringify(message), [channel.port2])\n  })\n}\n\nfunction delayPromise(cb, duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => resolve(cb()), duration)\n  })\n}\n\nfunction respondWithMock(clientMessage) {\n  return new Response(clientMessage.payload.body, {\n    ...clientMessage.payload,\n    headers: clientMessage.payload.headers,\n  })\n}\n\nfunction uuidv4() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0\n    const v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/App.css",
    "content": ".row {\n  display: flex;\n  flex-wrap: wrap;\n  width: 100%;\n}\n\n.column {\n  display: flex;\n  flex-direction: column;\n  flex-basis: 100%;\n  flex: 3;\n}\n\n.column-3 {\n  flex: 3;\n}\n\n.column-1 {\n  flex: 1;\n}\n\n.column-2 {\n  flex: 2;\n}\n\n.text-left {\n  text-align: left;\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/App.tsx",
    "content": "import React from 'react'\nimport { Routes, Route, Link } from 'react-router-dom'\nimport { PostsManager } from './features/posts/PostsManager'\nimport { CounterList } from './features/counter/CounterList'\nimport { TimeList } from './features/time/TimeList'\nimport { PollingToggles } from './features/polling/PollingToggles'\nimport { Lazy } from './features/bundleSplitting'\nimport './App.css'\n\nfunction App() {\n  return (\n    <div className=\"App\">\n      <div className=\"row\">\n        <div className=\"column column1\">\n          <span>\n            <Link to=\"/\">Times</Link> | <Link to=\"/posts\">Posts</Link> |{' '}\n            <Link to=\"/counters\">Counter</Link> |{' '}\n            <Link to=\"/bundleSplitting\">Bundle Splitting</Link>\n          </span>\n        </div>\n        <div className=\"column column1\">\n          <PollingToggles />\n        </div>\n      </div>\n      <div></div>\n      <div>\n        <Routes>\n          <Route path=\"/\" element={<TimeList />} />\n          <Route path=\"/counters\" element={<CounterList />} />\n          <Route path=\"/posts/*\" element={<PostsManager />} />\n          <Route path=\"/bundleSplitting\" element={<Lazy />} />\n        </Routes>\n      </div>\n    </div>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/app/services/api.ts",
    "content": "import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\nimport { RootState } from '../store'\n\n// Create our baseQuery instance\nconst baseQuery = fetchBaseQuery({\n  baseUrl: '/',\n  prepareHeaders: (headers, { getState }) => {\n    // By default, if we have a token in the store, let's use that for authenticated requests\n    const token = (getState() as RootState).auth.token\n    if (token) {\n      headers.set('authentication', `Bearer ${token}`)\n    }\n    return headers\n  },\n})\n\nconst baseQueryWithRetry = retry(baseQuery, { maxRetries: 6 })\n\n/**\n * Create a base API to inject endpoints into elsewhere.\n * Components using this API should import from the injected site,\n * in order to get the appropriate types,\n * and to ensure that the file injecting the endpoints is loaded\n */\nexport const api = createApi({\n  /**\n   * `reducerPath` is optional and will not be required by most users.\n   * This is useful if you have multiple API definitions,\n   * e.g. where each has a different domain, with no interaction between endpoints.\n   * Otherwise, a single API definition should be used in order to support tag invalidation,\n   * among other features\n   */\n  reducerPath: 'splitApi',\n  /**\n   * A bare bones base query would just be `baseQuery: fetchBaseQuery({ baseUrl: '/' })`\n   */\n  baseQuery: baseQueryWithRetry,\n  /**\n   * Tag types must be defined in the original API definition\n   * for any tags that would be provided by injected endpoints\n   */\n  tagTypes: ['Time', 'Posts', 'Counter'],\n  /**\n   * This api has endpoints injected in adjacent files,\n   * which is why no endpoints are shown below.\n   * If you want all endpoints defined in the same file, they could be included here instead\n   */\n  endpoints: () => ({}),\n})\n\nexport const enhancedApi = api.enhanceEndpoints({\n  endpoints: () => ({\n    getPost: () => 'test',\n  }),\n})\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/app/services/counter.ts",
    "content": "import { api } from './api'\n\ninterface CountResponse {\n  count: number\n}\n\nexport const counterApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getCount: build.query<CountResponse, void>({\n      query: () => 'count',\n      providesTags: ['Counter'],\n    }),\n    incrementCount: build.mutation<CountResponse, number>({\n      query(amount) {\n        return {\n          url: `increment`,\n          method: 'PUT',\n          body: { amount },\n        }\n      },\n      invalidatesTags: ['Counter'],\n    }),\n    decrementCount: build.mutation<CountResponse, number>({\n      query(amount) {\n        return {\n          url: `decrement`,\n          method: 'PUT',\n          body: { amount },\n        }\n      },\n      invalidatesTags: ['Counter'],\n    }),\n  }),\n})\n\nexport const {\n  useDecrementCountMutation,\n  useGetCountQuery,\n  useIncrementCountMutation,\n} = counterApi\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/app/services/post.ts",
    "content": "import { api } from './api'\nimport { Post } from './posts'\n\nexport const postApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    addPost: build.mutation<Post, Partial<Post>>({\n      query(body) {\n        return {\n          url: `posts`,\n          method: 'POST',\n          body,\n        }\n      },\n      invalidatesTags: ['Posts'],\n    }),\n    getPost: build.query<Post, number>({\n      query: (id) => `posts/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Posts', id }],\n    }),\n    updatePost: build.mutation<Post, Partial<Post>>({\n      query(data) {\n        const { id, ...body } = data\n        return {\n          url: `posts/${id}`,\n          method: 'PUT',\n          body,\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n    deletePost: build.mutation<{ success: boolean; id: number }, number>({\n      query(id) {\n        return {\n          url: `posts/${id}`,\n          method: 'DELETE',\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n  }),\n})\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/app/services/posts.ts",
    "content": "import { retry } from '@reduxjs/toolkit/query/react'\nimport { api } from './api'\n\nexport interface Post {\n  id: number\n  name: string\n  fetched_at: string\n}\n\ntype PostsResponse = Post[]\n\nexport interface User {\n  first_name: string\n  last_name: string\n  email: string\n  phone: string\n}\n\nexport const postsApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    login: build.mutation<{ token: string; user: User }, any>({\n      query: (credentials: any) => ({\n        url: 'login',\n        method: 'POST',\n        body: credentials,\n      }),\n      extraOptions: {\n        backoff: () => {\n          // We intentionally error once on login, and this breaks out of retrying. The next login attempt will succeed.\n          retry.fail({ fake: 'error' })\n        },\n      },\n    }),\n    getPosts: build.query<PostsResponse, void>({\n      query: () => ({ url: 'posts' }),\n      providesTags: (result = []) => [\n        ...result.map(({ id }) => ({ type: 'Posts', id }) as const),\n        { type: 'Posts' as const, id: 'LIST' },\n      ],\n    }),\n    addPost: build.mutation<Post, Partial<Post>>({\n      query: (body) => ({\n        url: `posts`,\n        method: 'POST',\n        body,\n      }),\n      invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n    }),\n    getPost: build.query<Post, number>({\n      query: (id) => `posts/${id}`,\n      providesTags: (_post, _err, id) => [{ type: 'Posts', id }],\n    }),\n    updatePost: build.mutation<Post, Partial<Post>>({\n      query(data) {\n        const { id, ...body } = data\n        return {\n          url: `posts/${id}`,\n          method: 'PUT',\n          body,\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n    deletePost: build.mutation<{ success: boolean; id: number }, number>({\n      query(id) {\n        return {\n          url: `posts/${id}`,\n          method: 'DELETE',\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n    getErrorProne: build.query<{ success: boolean }, void>({\n      query: () => 'error-prone',\n    }),\n  }),\n})\n\nexport const {\n  useAddPostMutation,\n  useDeletePostMutation,\n  useGetPostQuery,\n  useGetPostsQuery,\n  useLoginMutation,\n  useUpdatePostMutation,\n  useGetErrorProneQuery,\n} = postsApi\n\nexport const {\n  endpoints: { login, getPost },\n} = postsApi\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/app/services/times.ts",
    "content": "import { api } from './api'\n\ninterface TimeResponse {\n  time: string\n}\n\nexport const timeApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getTime: build.query<TimeResponse, string>({\n      query: (id) => `time/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Time', id }],\n    }),\n  }),\n})\n\nexport const { usePrefetch: usePrefetchTime, useGetTimeQuery } = timeApi\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/app/store.ts",
    "content": "import { configureStore, ConfigureStoreOptions } from '@reduxjs/toolkit'\nimport { TypedUseSelectorHook, useDispatch, useSelector } from 'react-redux'\nimport { api } from './services/api'\nimport polling from '../features/polling/pollingSlice'\nimport auth from '../features/auth/authSlice'\n\nexport const createStore = (\n  options?: ConfigureStoreOptions['preloadedState'] | undefined,\n) =>\n  configureStore({\n    reducer: {\n      [api.reducerPath]: api.reducer,\n      polling,\n      auth,\n    },\n    middleware: (getDefaultMiddleware) =>\n      getDefaultMiddleware().concat(api.middleware),\n    ...options,\n  })\n\nexport const store = createStore()\n\nexport type AppDispatch = typeof store.dispatch\nexport const useAppDispatch: () => AppDispatch = useDispatch\nexport type RootState = ReturnType<typeof store.getState>\nexport const useTypedSelector: TypedUseSelectorHook<RootState> = useSelector\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/auth/authSlice.ts",
    "content": "import { createSlice } from '@reduxjs/toolkit'\nimport { postsApi } from '../../app/services/posts'\nimport type { User } from '../../app/services/posts'\nimport type { RootState } from '../../app/store'\n\nconst initialState = {\n  user: null,\n  token: null,\n  isAuthenticated: false,\n} as { user: null | User; token: string | null; isAuthenticated: boolean }\n\nconst slice = createSlice({\n  name: 'auth',\n  initialState,\n  reducers: {\n    logout: () => initialState,\n  },\n  extraReducers: (builder) => {\n    builder\n      .addMatcher(postsApi.endpoints.login.matchPending, (state, action) => {\n        console.log('pending', action)\n      })\n      .addMatcher(postsApi.endpoints.login.matchFulfilled, (state, action) => {\n        console.log('fulfilled', action)\n        state.user = action.payload.user\n        state.token = action.payload.token\n        state.isAuthenticated = true\n      })\n      .addMatcher(postsApi.endpoints.login.matchRejected, (state, action) => {\n        console.log('rejected', action)\n      })\n  },\n})\n\nexport const { logout } = slice.actions\nexport default slice.reducer\n\nexport const selectIsAuthenticated = (state: RootState) =>\n  state.auth.isAuthenticated\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/bundleSplitting/Lazy.tsx",
    "content": "import * as React from 'react'\nimport { PostsList } from '.'\n\nexport const Lazy = () => {\n  return (\n    <React.Suspense fallback={<>loading...</>}>\n      <PostsList />\n    </React.Suspense>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/bundleSplitting/Post.tsx",
    "content": "import React from 'react'\n\n// import the file that injects \"post\" to make sure it has been loaded\nimport { postApi } from '../../app/services/post'\n\nfunction assert(condition: any, msg = 'Generic Assertion'): asserts condition {\n  if (!condition) {\n    throw new Error(`Assertion failed: ${msg}`)\n  }\n}\n\nconst Post = ({ id }: { id: number }) => {\n  /*\n   * As accessing these conditionally will cause hooks to error out,\n   * it's best to assert their existence & throw otherwise.\n   * This missing would be a programming error that you should\n   * catch early anyways.\n   */\n  assert(postApi.endpoints.getPost?.useQuery, 'Endpoint `getPost` not loaded!')\n  const { data, error } = postApi.endpoints.getPost.useQuery(id)\n  return error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <h1>{data.name}</h1>\n  )\n}\nexport default Post\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/bundleSplitting/PostsList.tsx",
    "content": "import * as React from 'react'\n\nimport { Post } from '.'\nimport { postsApi } from '../../app/services/posts'\n\nconst PostsList = () => {\n  /**\n   * You can directly use the \"injected\" API.\n   * That way all the injected endpoint are typed on there,\n   * but no endpoints that were injected elsewhere will be typed.\n   *\n   * They *will* be available at runtime if they have been\n   * injected though.\n   */\n\n  const { data, error } = postsApi.endpoints.getPosts.useQuery()\n  const [selected, select] = React.useState<number | undefined>()\n  return error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <>\n      {selected && <Post id={selected} />}\n      <ul>\n        {data.map((post) => (\n          <li key={post.id}>\n            <button onClick={() => select(post.id)}>{post.name}</button>\n          </li>\n        ))}\n      </ul>\n    </>\n  )\n}\nexport default PostsList\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/bundleSplitting/index.ts",
    "content": "import { lazy } from 'react'\n\nexport const PostsList = lazy(() => import('./PostsList'))\n\nexport const Post = lazy(() => import('./Post'))\n\nexport { Lazy } from './Lazy'\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/common/Container.tsx",
    "content": "import { FC, ReactNode } from 'react'\n\nexport const Container: FC<{ children: ReactNode }> = ({ children }) => (\n  <div style={{ textAlign: 'center', padding: 50, margin: '0 auto' }}>\n    {children}\n  </div>\n)\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/counter/Counter.module.css",
    "content": ".row {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.row:not(:last-child) {\n  margin-bottom: 16px;\n}\n\n.value {\n  font-size: 78px;\n  padding-left: 16px;\n  padding-right: 16px;\n  margin-top: 2px;\n  font-family: 'Courier New', Courier, monospace;\n}\n\n.button {\n  appearance: none;\n  background: none;\n  font-size: 32px;\n  padding-left: 12px;\n  padding-right: 12px;\n  outline: none;\n  border: 2px solid transparent;\n  color: rgb(112, 76, 182);\n  padding-bottom: 4px;\n  cursor: pointer;\n  background-color: rgba(112, 76, 182, 0.1);\n  border-radius: 2px;\n  transition: all 0.15s;\n}\n\n.textbox {\n  font-size: 32px;\n  padding: 2px;\n  width: 64px;\n  text-align: center;\n  margin-right: 8px;\n}\n\n.button:hover,\n.button:focus {\n  border: 2px solid rgba(112, 76, 182, 0.4);\n}\n\n.button:active {\n  background-color: rgba(112, 76, 182, 0.2);\n}\n\n.asyncButton {\n  composes: button;\n  position: relative;\n  margin-left: 8px;\n}\n\n.asyncButton:after {\n  content: '';\n  background-color: rgba(112, 76, 182, 0.15);\n  display: block;\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  left: 0;\n  top: 0;\n  opacity: 0;\n  transition:\n    width 1s linear,\n    opacity 0.5s ease 1s;\n}\n\n.asyncButton:active:after {\n  width: 0%;\n  opacity: 1;\n  transition: 0s;\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/counter/Counter.tsx",
    "content": "import React, { useState } from 'react'\nimport styles from './Counter.module.css'\nimport {\n  useDecrementCountMutation,\n  useGetCountQuery,\n  useIncrementCountMutation,\n} from '../../app/services/counter'\n\nexport function Counter({\n  id,\n  onRemove,\n}: {\n  id?: string\n  onRemove?: () => void\n}) {\n  const [pollingInterval, setPollingInterval] = useState(10000)\n  const { data } = useGetCountQuery(undefined, { pollingInterval })\n  const [increment] = useIncrementCountMutation()\n\n  const [decrement] = useDecrementCountMutation()\n\n  return (\n    <div>\n      <div className={styles.row}>\n        <button\n          className={styles.button}\n          aria-label=\"Increment value\"\n          onClick={() => increment(1)}\n        >\n          +\n        </button>\n        <span className={styles.value}>{data?.count || 0}</span>\n        <button\n          className={styles.button}\n          aria-label=\"Decrement value\"\n          onClick={() => decrement(1)}\n        >\n          -\n        </button>\n        <input\n          type=\"number\"\n          name=\"pollingInterval\"\n          value={pollingInterval}\n          onChange={({ target: { valueAsNumber } }) =>\n            setPollingInterval(valueAsNumber)\n          }\n        />\n        {onRemove && <button onClick={onRemove}>Remove {id}</button>}\n      </div>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/counter/CounterList.tsx",
    "content": "import * as React from 'react'\nimport { nanoid } from '@reduxjs/toolkit'\nimport { Container } from '../common/Container'\nimport { Counter } from './Counter'\n\nexport const CounterList = () => {\n  const [counters, setCounters] = React.useState<string[]>([])\n\n  if (!counters.length) {\n    return (\n      <Container>\n        <div>No counters, why don't you add one?</div>\n        <div>\n          <button onClick={() => setCounters((prev) => [...prev, nanoid()])}>\n            Add counter\n          </button>\n        </div>\n      </Container>\n    )\n  }\n\n  return (\n    <Container>\n      <div>\n        <button onClick={() => setCounters((prev) => [...prev, nanoid()])}>\n          Add counter\n        </button>\n      </div>\n      {counters.map((id) => (\n        <Counter\n          key={id}\n          id={id}\n          onRemove={() => setCounters((prev) => prev.filter((el) => el !== id))}\n        />\n      ))}\n    </Container>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/polling/PollingToggles.tsx",
    "content": "import * as React from 'react'\nimport { useAppDispatch, useTypedSelector } from '../../app/store'\nimport {\n  selectGlobalPollingEnabled,\n  selectPollingConfigByApp,\n  toggleGlobalPolling,\n  updatePolling,\n} from './pollingSlice'\n\nconst PollingToggleButton = ({\n  enabled,\n  onClick,\n  children,\n}: {\n  onClick: () => void\n  enabled: boolean\n  children?: React.ReactNode\n}) => {\n  return (\n    <button\n      onClick={onClick}\n      style={enabled ? { background: 'lightgreen' } : {}}\n    >\n      {children}\n    </button>\n  )\n}\n\nexport const PollingToggles = () => {\n  const dispatch = useAppDispatch()\n  const globalPolling = useTypedSelector(selectGlobalPollingEnabled)\n  const timesPolling = useTypedSelector((state) =>\n    selectPollingConfigByApp(state, 'times'),\n  )\n\n  return (\n    <div>\n      <small>Global Polling Configs</small>\n      <div>\n        <PollingToggleButton\n          enabled={globalPolling}\n          onClick={() => dispatch(toggleGlobalPolling())}\n        >\n          Global\n        </PollingToggleButton>\n        <PollingToggleButton\n          enabled={timesPolling.enabled}\n          onClick={() =>\n            dispatch(\n              updatePolling({ app: 'times', enabled: !timesPolling.enabled }),\n            )\n          }\n        >\n          Times\n        </PollingToggleButton>\n      </div>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/polling/pollingSlice.ts",
    "content": "import { createSlice, PayloadAction } from '@reduxjs/toolkit'\nimport type { RootState } from '../../app/store'\n\ntype PollingConfig = {\n  enabled: boolean\n  interval: number\n}\n\ntype SliceState = {\n  enabled: boolean\n  apps: {\n    [key: string]: PollingConfig\n  }\n}\n\nconst initialState: SliceState = {\n  enabled: true,\n  apps: {\n    counters: {\n      enabled: true,\n      interval: 0,\n    },\n    times: {\n      enabled: true,\n      interval: 0,\n    },\n    posts: {\n      enabled: true,\n      interval: 0,\n    },\n  },\n}\n\ntype PollingAppKey = keyof (typeof initialState)['apps']\n\nconst slice = createSlice({\n  name: 'polling',\n  initialState,\n  reducers: {\n    toggleGlobalPolling(state) {\n      state.enabled = !state.enabled\n    },\n    updatePolling(\n      state,\n      {\n        payload,\n      }: PayloadAction<{\n        app: PollingAppKey\n        enabled?: boolean\n        interval?: number\n      }>,\n    ) {\n      const { app, ...rest } = payload\n      state.apps[app] = {\n        ...state.apps[app],\n        ...rest,\n      }\n    },\n  },\n})\n\nexport const { toggleGlobalPolling, updatePolling } = slice.actions\n\nexport default slice.reducer\n\nexport const selectGlobalPollingEnabled = (state: RootState) =>\n  state.polling.enabled\nexport const selectPollingConfigByApp = (\n  state: RootState,\n  app: PollingAppKey,\n) => state.polling.apps[app]\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/posts/PostDetail.tsx",
    "content": "import * as React from 'react'\nimport { useNavigate, useParams } from 'react-router-dom'\nimport { useTypedSelector } from '../../app/store'\nimport {\n  useDeletePostMutation,\n  useGetPostQuery,\n  useUpdatePostMutation,\n} from '../../app/services/posts'\nimport { selectGlobalPollingEnabled } from '../polling/pollingSlice'\n\nconst EditablePostName = ({\n  name: initialName,\n  onUpdate,\n  onCancel,\n  loading = false,\n}: {\n  name: string\n  onUpdate: (name: string) => void\n  onCancel: () => void\n  loading?: boolean\n}) => {\n  const [name, setName] = React.useState(initialName)\n\n  const handleChange = ({\n    target: { value },\n  }: React.ChangeEvent<HTMLInputElement>) => setName(value)\n\n  const handleSubmit: React.FormEventHandler<HTMLFormElement> = (e) => {\n    e.preventDefault()\n    onUpdate(name)\n  }\n  const handleCancel = () => onCancel()\n\n  return (\n    <div>\n      <form onSubmit={handleSubmit}>\n        <input\n          type=\"text\"\n          onChange={handleChange}\n          value={name}\n          disabled={loading}\n        />\n        <button type=\"submit\" disabled={loading}>\n          {loading ? 'Updating...' : 'Update'}\n        </button>\n        <button onClick={handleCancel} disabled={loading}>\n          Cancel\n        </button>\n      </form>\n    </div>\n  )\n}\n\nconst PostJsonDetail = ({ id }: { id: number }) => {\n  const { data: post } = useGetPostQuery(id)\n\n  return (\n    <div className=\"row\" style={{ background: '#eee' }}>\n      <pre>{JSON.stringify(post, null, 2)}</pre>\n    </div>\n  )\n}\n\nexport const PostDetail = () => {\n  const { id } = useParams<{ id: any }>()\n  const navigate = useNavigate()\n  const globalPolling = useTypedSelector(selectGlobalPollingEnabled)\n\n  const [isEditing, setIsEditing] = React.useState(false)\n\n  const {\n    data: post,\n    isFetching,\n    isLoading,\n  } = useGetPostQuery(id, { pollingInterval: globalPolling ? 3000 : 0 })\n\n  const [updatePost, { isLoading: isUpdating }] = useUpdatePostMutation()\n  const [deletePost, { isLoading: isDeleting }] = useDeletePostMutation()\n\n  if (isLoading) {\n    return <div>Loading...</div>\n  }\n\n  if (!post) {\n    return <div>Missing post!</div>\n  }\n\n  return (\n    <div>\n      {isEditing ? (\n        <EditablePostName\n          name={post.name}\n          onUpdate={(name) =>\n            updatePost({ id, name })\n              .then((result) => {\n                // handle the success!\n                console.log('Update Result', result)\n                setIsEditing(false)\n              })\n              .catch((error) => console.error('Update Error', error))\n          }\n          onCancel={() => setIsEditing(false)}\n          loading={isUpdating}\n        />\n      ) : (\n        <React.Fragment>\n          <div className=\"row\">\n            <div className=\"column\">\n              <h3>\n                {post.name} {isFetching ? '...refetching' : ''}\n              </h3>\n            </div>\n            <button\n              onClick={() => setIsEditing(true)}\n              disabled={isDeleting || isUpdating}\n            >\n              {isUpdating ? 'Updating...' : 'Edit'}\n            </button>\n            <button\n              onClick={() => deletePost(id).then(() => navigate('/posts'))}\n              disabled={isDeleting}\n            >\n              {isDeleting ? 'Deleting...' : 'Delete'}\n            </button>\n          </div>\n        </React.Fragment>\n      )}\n      <PostJsonDetail id={id} />\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/posts/PostsManager.css",
    "content": ".posts-list {\n  display: flex;\n  flex-direction: column;\n  flex-basis: 100%;\n  flex: 1;\n  min-height: 200px;\n  border-right: 1px solid #eee;\n  padding: 20px;\n  text-align: left;\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/posts/PostsManager.tsx",
    "content": "import React, { useState } from 'react'\nimport { useDispatch, useSelector } from 'react-redux'\nimport { Route, Routes, useNavigate } from 'react-router-dom'\nimport {\n  Post,\n  useAddPostMutation,\n  useGetPostsQuery,\n  useLoginMutation,\n  useGetErrorProneQuery,\n} from '../../app/services/posts'\nimport { selectIsAuthenticated, logout } from '../auth/authSlice'\nimport { PostDetail } from './PostDetail'\nimport './PostsManager.css'\n\nconst AddPost = () => {\n  const initialValue = { name: '' }\n  const [post, setPost] = useState<Partial<Post>>(initialValue)\n  const [addPost, { isLoading }] = useAddPostMutation()\n\n  const handleChange = ({ target }: React.ChangeEvent<HTMLInputElement>) => {\n    setPost((prev) => ({\n      ...prev,\n      [target.name]: target.value,\n    }))\n  }\n\n  const handleSubmit: React.FormEventHandler<HTMLFormElement> = async (e) => {\n    e.preventDefault()\n    await addPost(post)\n    setPost(initialValue)\n  }\n\n  return (\n    <form onSubmit={handleSubmit}>\n      <div className=\"row\">\n        <div className=\"column column-3\">\n          <input\n            name=\"name\"\n            placeholder=\"New post name\"\n            type=\"text\"\n            onChange={handleChange}\n            value={post.name}\n          />\n        </div>\n        <div className=\"column column-1\">\n          <button type=\"submit\" disabled={isLoading}>\n            {isLoading ? 'Adding...' : 'Add Post'}\n          </button>\n        </div>\n      </div>\n    </form>\n  )\n}\n\nconst PostListItem = ({\n  data: { name, id },\n  onSelect,\n}: {\n  data: Post\n  onSelect: (id: number) => void\n}) => {\n  return (\n    <li>\n      <a href=\"#\" onClick={() => onSelect(id)}>\n        {name}\n      </a>\n    </li>\n  )\n}\n\nconst PostList = () => {\n  const { data: posts, isLoading } = useGetPostsQuery()\n  const navigate = useNavigate()\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <div>\n      {posts.map((post) => (\n        <PostListItem\n          key={post.id}\n          data={post}\n          onSelect={(id) => navigate(`/posts/${id}`)}\n        />\n      ))}\n    </div>\n  )\n}\n\nexport const PostsManager = () => {\n  const [login] = useLoginMutation()\n  const [initRetries, setInitRetries] = useState(false)\n  const { data, error, isFetching } = useGetErrorProneQuery(undefined, {\n    skip: !initRetries,\n  })\n  const dispatch = useDispatch()\n  const isAuthenticated = useSelector(selectIsAuthenticated)\n\n  return (\n    <div>\n      <h3>Posts</h3>\n      {!isAuthenticated ? (\n        <button\n          onClick={() => login({ ignore: 'This will just set the headers' })}\n        >\n          Login\n        </button>\n      ) : (\n        <button onClick={() => dispatch(logout())}>Logout</button>\n      )}\n      <button onClick={() => setInitRetries(true)}>\n        {isFetching ? 'retrying...' : 'Start error prone retries'}\n      </button>\n      <hr />\n      <div className=\"row\">\n        <div className=\"posts-list\">\n          <AddPost />\n          <hr />\n          Posts:\n          <PostList />\n          <hr />\n          List with duplicate subscription:\n          <PostList />\n        </div>\n        <div className=\"column column-3 text-left\">\n          <Routes>\n            <Route path=\"/:id\" element={<PostDetail />} />\n          </Routes>\n        </div>\n      </div>\n    </div>\n  )\n}\n\nexport default PostsManager\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/features/time/TimeList.tsx",
    "content": "import * as React from 'react'\nimport { nanoid } from '@reduxjs/toolkit'\nimport { useEffect } from 'react'\nimport { useGetTimeQuery, usePrefetchTime } from '../../app/services/times'\nimport { Container } from '../common/Container'\nimport { useTypedSelector } from '../../app/store'\nimport {\n  selectGlobalPollingEnabled,\n  selectPollingConfigByApp,\n} from '../polling/pollingSlice'\n\nconst timezones: Record<string, string> = {\n  '-12:00': '(GMT -12:00) Eniwetok, Kwajalein',\n  '-11:00': '(GMT -11:00) Midway Island, Samoa',\n  '-10:00': '(GMT -10:00) Hawaii',\n  '-09:50': '(GMT -9:30) Taiohae',\n  '-09:00': '(GMT -9:00) Alaska',\n  '-08:00': '(GMT -8:00) Pacific Time (US & Canada)',\n  '-07:00': '(GMT -7:00) Mountain Time (US & Canada)',\n  '-06:00': '(GMT -6:00) Central Time (US & Canada), Mexico City',\n  '-05:00': '(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima',\n  '-04:50': '(GMT -4:30) Caracas',\n  '-04:00': '(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz',\n  '-03:50': '(GMT -3:30) Newfoundland',\n  '-03:00': '(GMT -3:00) Brazil, Buenos Aires, Georgetown',\n  '-02:00': '(GMT -2:00) Mid-Atlantic',\n  '-01:00': '(GMT -1:00) Azores, Cape Verde Islands',\n  '+00:00': '(GMT) Western Europe Time, London, Lisbon, Casablanca',\n  '+01:00': '(GMT +1:00) Brussels, Copenhagen, Madrid, Paris',\n  '+02:00': '(GMT +2:00) Kaliningrad, South Africa',\n  '+03:00': '(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg',\n  '+03:50': '(GMT +3:30) Tehran',\n  '+04:00': '(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi',\n  '+04:50': '(GMT +4:30) Kabul',\n  '+05:00': '(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent',\n  '+05:50': '(GMT +5:30) Bombay, Calcutta, Madras, New Delhi',\n  '+05:75': '(GMT +5:45) Kathmandu, Pokhara',\n  '+06:00': '(GMT +6:00) Almaty, Dhaka, Colombo',\n  '+06:50': '(GMT +6:30) Yangon, Mandalay',\n  '+07:00': '(GMT +7:00) Bangkok, Hanoi, Jakarta',\n  '+08:00': '(GMT +8:00) Beijing, Perth, Singapore, Hong Kong',\n  '+08:75': '(GMT +8:45) Eucla',\n  '+09:00': '(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk',\n  '+09:50': '(GMT +9:30) Adelaide, Darwin',\n  '+10:00': '(GMT +10:00) Eastern Australia, Guam, Vladivostok',\n  '+10:50': '(GMT +10:30) Lord Howe Island',\n  '+11:00': '(GMT +11:00) Magadan, Solomon Islands, New Caledonia',\n  '+11:50': '(GMT +11:30) Norfolk Island',\n  '+12:00': '(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka',\n  '+12:75': '(GMT +12:45) Chatham Islands',\n  '+13:00': '(GMT +13:00) Apia, Nukualofa',\n  '+14:00': '(GMT +14:00) Line Islands, Tokelau',\n}\n\nconst TimeZoneSelector = ({\n  onChange,\n}: {\n  onChange: (event: React.ChangeEvent<HTMLSelectElement>) => void\n}) => {\n  return (\n    <select name=\"timezone_offset\" id=\"timezone-offset\" onChange={onChange}>\n      <option value=\"\">Select one...</option>\n      {Object.entries(timezones).map(([value, description]) => (\n        <option key={value} value={value}>\n          {description}\n        </option>\n      ))}\n    </select>\n  )\n}\n\nconst intervalOptions = [\n  { label: '0 - Off', value: 0 },\n  { label: '1s', value: 1000 },\n  { label: '3s', value: 3000 },\n  { label: '5s', value: 5000 },\n  { label: '10s', value: 10000 },\n  { label: '1m', value: 60000 },\n]\n\nconst TimeDisplay = ({ offset, label }: { offset: string; label: string }) => {\n  const globalPolling = useTypedSelector(selectGlobalPollingEnabled)\n  const { enabled: timesPolling } = useTypedSelector((state) =>\n    selectPollingConfigByApp(state, 'times'),\n  )\n\n  const canPoll = globalPolling && timesPolling\n\n  const [pollingInterval, setPollingInterval] = React.useState(0)\n  const { data, refetch, isFetching } = useGetTimeQuery(offset, {\n    pollingInterval: canPoll ? pollingInterval : 0,\n  })\n\n  return (\n    <div style={{ ...(isFetching ? { background: '#e6ffe8' } : {}) }}>\n      <p>\n        {data?.time && new Date(data.time).toLocaleTimeString()} - {label}\n      </p>\n      <p>\n        <button onClick={refetch}>refetch manually</button> Polling Interval:{' '}\n        <select\n          value={pollingInterval}\n          onChange={({ target: { value } }) =>\n            setPollingInterval(Number(value))\n          }\n        >\n          {intervalOptions.map(({ label, value }) => (\n            <option key={value} value={value}>\n              {label}\n            </option>\n          ))}\n        </select>\n      </p>\n    </div>\n  )\n}\n\nexport const TimeList = () => {\n  const [times, setTimes] = React.useState<{ [key: string]: string }>({\n    [nanoid()]: '-08:00',\n  })\n  const [selectedValue, setSelectedValue] = React.useState<string>('')\n\n  const prefetch = usePrefetchTime('getTime')\n\n  useEffect(() => {\n    setTimeout(() => {\n      setTimes((prev) => ({ ...prev, [nanoid()]: '+00:00' }))\n    }, 1000)\n  }, [])\n\n  return (\n    <Container>\n      <h3>\n        Add some times, even duplicates, and watch them automatically refetch in\n        sync!\n      </h3>\n      <p>\n        Notes: shared queries (aka multiple entries of the same time zone) will\n        share the lowest polling interval between them that is greater than 0.\n        If all entries are set to 0, it will stop polling. If you have two\n        entries with a polling time of 5s and one with 0 - off, it will continue\n        at 5s until they are removed or 0'd out.\n        <br />\n        Any new poll starts after the last request has either finished or failed\n        to prevent slow-running requests to immediately double-trigger.\n        <br />\n        <strong>* Background flashes green when query is running</strong>\n        <button onMouseEnter={() => prefetch('+02:00', { force: true })}>\n          Prefetch\n        </button>\n      </p>\n      <TimeZoneSelector\n        onChange={({ target: { value } }) => setSelectedValue(value)}\n      />\n      <button\n        onClick={() =>\n          setTimes((prev) => ({ ...prev, [nanoid()]: selectedValue }))\n        }\n        disabled={!selectedValue}\n      >\n        Track time\n      </button>\n      <hr />\n      {Object.entries(times).map(([key, tz]) => (\n        <TimeDisplay key={key} offset={tz} label={timezones[tz]} />\n      ))}\n    </Container>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport { store } from './app/store'\nimport { Provider } from 'react-redux'\nimport { BrowserRouter } from 'react-router-dom'\nimport { worker } from './mocks/browser'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nasync function render() {\n  if (process.env.NODE_ENV === 'development') {\n    await worker.start()\n  }\n\n  const rootNode = ReactDOM.createRoot(\n    document.getElementById('root') as HTMLElement,\n  )\n\n  rootNode.render(\n    <React.StrictMode>\n      <Provider store={store}>\n        <BrowserRouter>\n          <App />\n        </BrowserRouter>\n      </Provider>\n    </React.StrictMode>,\n  )\n}\n\nrender()\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './handlers'\n\nexport const worker = setupWorker(...handlers)\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/mocks/handlers.ts",
    "content": "import { rest } from 'msw'\nimport { createEntityAdapter, nanoid } from '@reduxjs/toolkit'\nimport { Post } from '../app/services/posts'\n\n// We're just going to use a simple in-memory store for both the counter and posts\n// The entity adapter will handle modifications when triggered by the MSW handlers\n\nlet count = 0\nlet startingId = 3 // Just a silly counter for usage when adding new posts\n\nconst adapter = createEntityAdapter<Post>()\n\nlet state = adapter.getInitialState()\nstate = adapter.setAll(state, [\n  { id: 1, name: 'A sample post', fetched_at: new Date().toUTCString() },\n  {\n    id: 2,\n    name: 'A post about rtk-query',\n    fetched_at: new Date().toUTCString(),\n  },\n])\n\nexport { state }\n\n// Just use a random id for an auth token\nconst token = nanoid()\n\nexport const handlers = [\n  rest.get('/time/:offset', (req, res, ctx) => {\n    const { offset } = req.params as { offset: string }\n    const date = new Date()\n    const localDate = date.getTime() // users local time\n    const localOffset = date.getTimezoneOffset() * 60000\n    const formattedOffset = Number(offset.replace(':', '.'))\n    const target = localDate + localOffset + 3600000 * formattedOffset\n    return res(\n      ctx.json({ time: new Date(target).toUTCString() }),\n      ctx.delay(400),\n    )\n  }),\n\n  rest.put<{ amount: number }>('/increment', (req, res, ctx) => {\n    const { amount } = req.body\n    count = count += amount\n\n    return res(ctx.json({ count }))\n  }),\n\n  rest.put<{ amount: number }>('/decrement', (req, res, ctx) => {\n    const { amount } = req.body\n    count = count -= amount\n\n    return res(ctx.json({ count }))\n  }),\n\n  rest.get('/count', (req, res, ctx) => {\n    return res(ctx.json({ count }))\n  }),\n\n  rest.post('/login', (req, res, ctx) => {\n    return res.once(ctx.json({ message: 'i fail once' }), ctx.status(500))\n  }),\n  rest.post('/login', (req, res, ctx) => {\n    return res(\n      ctx.json({ token, user: { first_name: 'Test', last_name: 'User' } }),\n    )\n  }),\n\n  rest.get('/posts', (req, res, ctx) => {\n    return res(ctx.json(Object.values(state.entities)))\n  }),\n\n  rest.post('/posts', (req, res, ctx) => {\n    let post = req.body as Partial<Post>\n    startingId += 1\n    state = adapter.addOne(state, { ...post, id: startingId } as Post)\n    return res(ctx.json(Object.values(state.entities)), ctx.delay(400))\n  }),\n\n  rest.get('/posts/:id', (req, res, ctx) => {\n    const { id: idParam } = req.params as { id: string }\n    const id = parseInt(idParam, 10)\n    state = adapter.updateOne(state, {\n      id,\n      changes: { fetched_at: new Date().toUTCString() },\n    })\n    return res(ctx.json(state.entities[id]), ctx.delay(400))\n  }),\n\n  rest.put('/posts/:id', (req, res, ctx) => {\n    const { id: idParam } = req.params as { id: string }\n    const id = parseInt(idParam, 10)\n    const changes = req.body as Partial<Post>\n\n    state = adapter.updateOne(state, { id, changes })\n\n    return res(ctx.json(state.entities[id]), ctx.delay(400))\n  }),\n\n  rest.delete('/posts/:id', (req, res, ctx) => {\n    const { id: idParam } = req.params as { id: string }\n    const id = parseInt(idParam, 10)\n\n    state = adapter.removeOne(state, id)\n\n    return res(\n      ctx.json({\n        id,\n        success: true,\n      }),\n      ctx.delay(600),\n    )\n  }),\n\n  rest.get('/error-prone', (req, res, ctx) => {\n    if (Math.random() > 0.1) {\n      return res(ctx.json({ error: 'failed!' }), ctx.status(500))\n    }\n    return res(\n      ctx.json({\n        success: true,\n      }),\n    )\n  }),\n]\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/mocks/mockServer.ts",
    "content": "import { setupServer } from 'msw/node'\nimport { handlers } from './handlers'\nimport { state } from './handlers'\n\nexport const mockServer = () => {\n  const server = setupServer(...handlers)\n\n  return { server, state }\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/mocks/setupTests.tsx",
    "content": "import React from 'react'\nimport { render } from '@testing-library/react'\nimport { Provider } from 'react-redux'\nimport { store } from '../app/store'\nimport {\n  unstable_HistoryRouter as HistoryRouter,\n  Route,\n  Routes,\n} from 'react-router-dom'\nimport { createMemoryHistory } from 'history'\nimport { mockServer } from './mockServer'\nimport 'whatwg-fetch'\n\nexport const setupTests = () => {\n  const { server, state: serverState } = mockServer()\n\n  beforeAll(() => server.listen({ onUnhandledRequest: 'warn' }))\n  afterEach(() => server.resetHandlers())\n  afterAll(() => server.close())\n\n  interface RenderOptions {\n    route: string\n    path?: string\n  }\n  function renderWithProvider(\n    children: React.ReactElement | number | string,\n    { route, path }: RenderOptions = { route: '/', path: '' },\n  ) {\n    const history = createMemoryHistory()\n    history.push(route)\n    return render(\n      <Provider store={store}>\n        <HistoryRouter history={history}>\n          {path ? (\n            <Routes>\n              <Route path={path}>{children}</Route>\n            </Routes>\n          ) : (\n            children\n          )}\n        </HistoryRouter>\n      </Provider>,\n    )\n  }\n\n  return {\n    store,\n    serverState,\n    server,\n    renderWithProvider,\n  }\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/setupTests.ts",
    "content": "// jest-dom adds custom jest matchers for asserting on DOM nodes.\n// allows you to do things like:\n// expect(element).toHaveTextContent(/react/i)\n// learn more: https://github.com/testing-library/jest-dom\nimport '@testing-library/jest-dom/extend-expect'\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/src/styles.css",
    "content": ".App {\n  font-family: sans-serif;\n  text-align: center;\n}\n"
  },
  {
    "path": "examples/query/react/kitchen-sink/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/mutations/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/mutations\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"./src/index.tsx\",\n  \"dependencies\": {\n    \"@chakra-ui/react\": \"2.10.7\",\n    \"@emotion/react\": \"^11.4.0\",\n    \"@emotion/styled\": \"^11.3.0\",\n    \"@mswjs/data\": \"^0.3.0\",\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"framer-motion\": \"^2.9.5\",\n    \"msw\": \"^0.40.2\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-icons\": \"3.11.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-router-dom\": \"6.3.0\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"prebuild\": \"rimraf dist/\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ],\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/mutations/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"\n    />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <!--\n      manifest.json provides metadata used when your web app is added to the\n      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n\n  <body>\n    <noscript> You need to enable JavaScript to run this app. </noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/mutations/public/mockServiceWorker.js",
    "content": "/**\n * Mock Service Worker.\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n/* eslint-disable */\n/* tslint:disable */\n\nconst INTEGRITY_CHECKSUM = '82ef9b96d8393b6da34527d1d6e19187'\nconst bypassHeaderName = 'x-msw-bypass'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  return self.skipWaiting()\n})\n\nself.addEventListener('activate', async function (event) {\n  return self.clients.claim()\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\n// Resolve the \"master\" client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMasterClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMasterClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: serializeHeaders(clonedResponse.headers),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const requestClone = request.clone()\n  const getOriginalResponse = () => fetch(requestClone)\n\n  // Bypass mocking when the request client is not active.\n  if (!client) {\n    return getOriginalResponse()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return await getOriginalResponse()\n  }\n\n  // Bypass requests with the explicit bypass header\n  if (requestClone.headers.get(bypassHeaderName) === 'true') {\n    const cleanRequestHeaders = serializeHeaders(requestClone.headers)\n\n    // Remove the bypass header to comply with the CORS preflight check.\n    delete cleanRequestHeaders[bypassHeaderName]\n\n    const originalRequest = new Request(requestClone, {\n      headers: new Headers(cleanRequestHeaders),\n    })\n\n    return fetch(originalRequest)\n  }\n\n  // Send the request to the client-side MSW.\n  const reqHeaders = serializeHeaders(request.headers)\n  const body = await request.text()\n\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: reqHeaders,\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body,\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_SUCCESS': {\n      return delayPromise(\n        () => respondWithMock(clientMessage),\n        clientMessage.payload.delay,\n      )\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return getOriginalResponse()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.payload\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a request Promise emulates a network error.\n      throw networkError\n    }\n\n    case 'INTERNAL_ERROR': {\n      const parsedBody = JSON.parse(clientMessage.payload.body)\n\n      console.error(\n        `\\\n[MSW] Request handler function for \"%s %s\" has thrown the following exception:\n\n${parsedBody.errorType}: ${parsedBody.message}\n(see more detailed error stack trace in the mocked response body)\n\nThis exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error.\nIf you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\\\n`,\n        request.method,\n        request.url,\n      )\n\n      return respondWithMock(clientMessage)\n    }\n  }\n\n  return getOriginalResponse()\n}\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  const requestId = uuidv4()\n\n  return event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      console.error(\n        '[MSW] Failed to mock a \"%s\" request to \"%s\": %s',\n        request.method,\n        request.url,\n        error,\n      )\n    }),\n  )\n})\n\nfunction serializeHeaders(headers) {\n  const reqHeaders = {}\n  headers.forEach((value, name) => {\n    reqHeaders[name] = reqHeaders[name]\n      ? [].concat(reqHeaders[name]).concat(value)\n      : value\n  })\n  return reqHeaders\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(JSON.stringify(message), [channel.port2])\n  })\n}\n\nfunction delayPromise(cb, duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => resolve(cb()), duration)\n  })\n}\n\nfunction respondWithMock(clientMessage) {\n  return new Response(clientMessage.payload.body, {\n    ...clientMessage.payload,\n    headers: clientMessage.payload.headers,\n  })\n}\n\nfunction uuidv4() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0\n    const v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n"
  },
  {
    "path": "examples/query/react/mutations/src/App.tsx",
    "content": "import { Routes, Route } from 'react-router-dom'\nimport { PostsManager } from './features/posts/PostsManager'\nimport { Box } from '@chakra-ui/react'\n\nfunction App() {\n  return (\n    <Box>\n      <Routes>\n        <Route path=\"*\" element={<PostsManager />} />\n      </Routes>\n    </Box>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/mutations/src/app/services/posts.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport interface Post {\n  id: string\n  name: string\n}\n\ntype PostsResponse = Post[]\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    getPosts: build.query<PostsResponse, void>({\n      query: () => 'posts',\n      providesTags: (result) =>\n        result\n          ? [\n              ...result.map(({ id }) => ({ type: 'Post' as const, id })),\n              { type: 'Post', id: 'LIST' },\n            ]\n          : [{ type: 'Post', id: 'LIST' }],\n    }),\n    addPost: build.mutation<Post, Partial<Post>>({\n      query: (body) => ({\n        url: `posts`,\n        method: 'POST',\n        body,\n      }),\n      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n    }),\n    getPost: build.query<Post, string>({\n      query: (id) => `posts/${id}`,\n      providesTags: (result, error, id) => [{ type: 'Post', id }],\n    }),\n    updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n      query: ({ id, ...patch }) => ({\n        url: `posts/${id}`,\n        method: 'PUT',\n        body: patch,\n      }),\n      invalidatesTags: (result, error, { id }) => [{ type: 'Post', id }],\n    }),\n    deletePost: build.mutation<{ success: boolean; id: number }, number>({\n      query(id) {\n        return {\n          url: `posts/${id}`,\n          method: 'DELETE',\n        }\n      },\n      invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n    }),\n  }),\n})\n\nexport const {\n  useGetPostQuery,\n  useGetPostsQuery,\n  useAddPostMutation,\n  useUpdatePostMutation,\n  useDeletePostMutation,\n} = api\n"
  },
  {
    "path": "examples/query/react/mutations/src/features/posts/PostDetail.tsx",
    "content": "import React, { useState } from 'react'\nimport { useNavigate, useParams } from 'react-router-dom'\nimport {\n  useDeletePostMutation,\n  useGetPostQuery,\n  useUpdatePostMutation,\n} from '../../app/services/posts'\nimport {\n  Box,\n  Button,\n  Center,\n  CloseButton,\n  Flex,\n  Heading,\n  Input,\n  Spacer,\n  Stack,\n  useToast,\n} from '@chakra-ui/react'\n\nconst EditablePostName = ({\n  name: initialName,\n  onUpdate,\n  onCancel,\n  isLoading = false,\n}: {\n  name: string\n  onUpdate: (name: string) => void\n  onCancel: () => void\n  isLoading?: boolean\n}) => {\n  const [name, setName] = useState(initialName)\n\n  const handleChange = ({\n    target: { value },\n  }: React.ChangeEvent<HTMLInputElement>) => setName(value)\n\n  const handleUpdate = () => onUpdate(name)\n  const handleCancel = () => onCancel()\n\n  return (\n    <Flex>\n      <Box flex={10}>\n        <Input\n          type=\"text\"\n          onChange={handleChange}\n          value={name}\n          disabled={isLoading}\n        />\n      </Box>\n      <Spacer />\n      <Box>\n        <Stack spacing={4} direction=\"row\" align=\"center\">\n          <Button onClick={handleUpdate} isLoading={isLoading}>\n            Update\n          </Button>\n          <CloseButton bg=\"red\" onClick={handleCancel} disabled={isLoading} />\n        </Stack>\n      </Box>\n    </Flex>\n  )\n}\n\nconst PostJsonDetail = ({ id }: { id: string }) => {\n  const { data: post } = useGetPostQuery(id)\n\n  return (\n    <Box mt={5} bg=\"#eee\">\n      <pre>{JSON.stringify(post, null, 2)}</pre>\n    </Box>\n  )\n}\n\nexport const PostDetail = () => {\n  const { id } = useParams<{ id: any }>()\n  const navigate = useNavigate()\n\n  const toast = useToast()\n\n  const [isEditing, setIsEditing] = useState(false)\n\n  const { data: post, isLoading } = useGetPostQuery(id)\n\n  const [updatePost, { isLoading: isUpdating }] = useUpdatePostMutation()\n\n  const [deletePost, { isLoading: isDeleting }] = useDeletePostMutation()\n\n  if (isLoading) {\n    return <div>Loading...</div>\n  }\n\n  if (!post) {\n    return (\n      <Center h=\"200px\">\n        <Heading size=\"md\">\n          Post {id} is missing! Try reloading or selecting another post...\n        </Heading>\n      </Center>\n    )\n  }\n\n  return (\n    <Box p={4}>\n      {isEditing ? (\n        <EditablePostName\n          name={post.name}\n          onUpdate={async (name) => {\n            try {\n              await updatePost({ id, name }).unwrap()\n            } catch {\n              toast({\n                title: 'An error occurred',\n                description: \"We couldn't save your changes, try again!\",\n                status: 'error',\n                duration: 2000,\n                isClosable: true,\n              })\n            } finally {\n              setIsEditing(false)\n            }\n          }}\n          onCancel={() => setIsEditing(false)}\n          isLoading={isUpdating}\n        />\n      ) : (\n        <Flex>\n          <Box>\n            <Heading size=\"md\">{post.name}</Heading>\n          </Box>\n          <Spacer />\n          <Box>\n            <Stack spacing={4} direction=\"row\" align=\"center\">\n              <Button\n                onClick={() => setIsEditing(true)}\n                disabled={isDeleting || isUpdating}\n              >\n                {isUpdating ? 'Updating...' : 'Edit'}\n              </Button>\n              <Button\n                onClick={() => deletePost(id).then(() => navigate('/posts'))}\n                disabled={isDeleting}\n                colorScheme=\"red\"\n              >\n                {isDeleting ? 'Deleting...' : 'Delete'}\n              </Button>\n            </Stack>\n          </Box>\n        </Flex>\n      )}\n      <PostJsonDetail id={post.id} />\n    </Box>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/mutations/src/features/posts/PostsManager.tsx",
    "content": "import {\n  Box,\n  Button,\n  Center,\n  Divider,\n  Flex,\n  FormControl,\n  FormLabel,\n  Heading,\n  Input,\n  List,\n  ListIcon,\n  ListItem,\n  Spacer,\n  Stat,\n  StatLabel,\n  StatNumber,\n  useToast,\n} from '@chakra-ui/react'\nimport { MdBook } from 'react-icons/md'\nimport React, { useState } from 'react'\nimport { Route, Routes, useNavigate } from 'react-router-dom'\nimport {\n  Post,\n  useAddPostMutation,\n  useGetPostsQuery,\n} from '../../app/services/posts'\nimport { PostDetail } from './PostDetail'\n\nconst AddPost = () => {\n  const initialValue = { name: '' }\n  const [post, setPost] = useState<Pick<Post, 'name'>>(initialValue)\n  const [addPost, { isLoading }] = useAddPostMutation()\n  const toast = useToast()\n\n  const handleChange = ({ target }: React.ChangeEvent<HTMLInputElement>) => {\n    setPost((prev) => ({\n      ...prev,\n      [target.name]: target.value,\n    }))\n  }\n\n  const handleAddPost = async () => {\n    try {\n      await addPost(post).unwrap()\n      setPost(initialValue)\n    } catch {\n      toast({\n        title: 'An error occurred',\n        description: \"We couldn't save your post, try again!\",\n        status: 'error',\n        duration: 2000,\n        isClosable: true,\n      })\n    }\n  }\n\n  return (\n    <Flex p={5}>\n      <Box flex={10}>\n        <FormControl isInvalid={Boolean(post.name.length < 3 && post.name)}>\n          <FormLabel htmlFor=\"name\">Post name</FormLabel>\n          <Input\n            id=\"name\"\n            name=\"name\"\n            placeholder=\"Enter post name\"\n            value={post.name}\n            onChange={handleChange}\n          />\n        </FormControl>\n      </Box>\n      <Spacer />\n      <Box>\n        <Button\n          mt={8}\n          colorScheme=\"purple\"\n          isLoading={isLoading}\n          onClick={handleAddPost}\n        >\n          Add Post\n        </Button>\n      </Box>\n    </Flex>\n  )\n}\n\nconst PostList = () => {\n  const { data: posts, isLoading } = useGetPostsQuery()\n  const navigate = useNavigate()\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <List spacing={3}>\n      {posts.map(({ id, name }) => (\n        <ListItem key={id} onClick={() => navigate(`/posts/${id}`)}>\n          <ListIcon as={MdBook} color=\"green.500\" /> {name}\n        </ListItem>\n      ))}\n    </List>\n  )\n}\n\nexport const PostsCountStat = () => {\n  const { data: posts } = useGetPostsQuery()\n\n  if (!posts) return null\n\n  return (\n    <Stat>\n      <StatLabel>Active Posts</StatLabel>\n      <StatNumber>{posts?.length}</StatNumber>\n    </Stat>\n  )\n}\n\nexport const PostsManager = () => {\n  return (\n    <Box>\n      <Flex bg=\"#011627\" p={4} color=\"white\">\n        <Box>\n          <Heading size=\"xl\">Manage Posts</Heading>\n        </Box>\n        <Spacer />\n        <Box>\n          <PostsCountStat />\n        </Box>\n      </Flex>\n      <Divider />\n      <AddPost />\n      <Divider />\n      <Flex wrap=\"wrap\">\n        <Box flex={1} borderRight=\"1px solid #eee\">\n          <Box p={4} borderBottom=\"1px solid #eee\">\n            <Heading size=\"sm\">Posts</Heading>\n          </Box>\n          <Box p={4}>\n            <PostList />\n          </Box>\n        </Box>\n        <Box flex={2}>\n          <Routes>\n            <Route path=\"/posts/:id\" element={<PostDetail />} />\n            <Route\n              element={\n                <Center h=\"200px\">\n                  <Heading size=\"md\">Select a post to edit!</Heading>\n                </Center>\n              }\n            />\n          </Routes>\n        </Box>\n      </Flex>\n    </Box>\n  )\n}\n\nexport default PostsManager\n"
  },
  {
    "path": "examples/query/react/mutations/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport { store } from './store'\nimport { Provider } from 'react-redux'\nimport { ChakraProvider } from '@chakra-ui/react'\n\nimport { BrowserRouter } from 'react-router-dom'\nimport { worker } from './mocks/browser'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nworker.start({ quiet: true }).then(() =>\n  ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(\n    <React.StrictMode>\n      <Provider store={store}>\n        <ChakraProvider>\n          <BrowserRouter>\n            <App />\n          </BrowserRouter>\n        </ChakraProvider>\n      </Provider>\n    </React.StrictMode>,\n  ),\n)\n"
  },
  {
    "path": "examples/query/react/mutations/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './db'\n\nexport const worker = setupWorker(...(handlers as any))\n"
  },
  {
    "path": "examples/query/react/mutations/src/mocks/db.ts",
    "content": "import { factory, primaryKey } from '@mswjs/data'\nimport { nanoid } from '@reduxjs/toolkit'\nimport { rest } from 'msw'\nimport { Post } from '../app/services/posts'\n\nconst db = factory({\n  post: {\n    id: primaryKey(String),\n    name: String,\n  },\n})\n\n;[\n  'A sample post',\n  'A post about RTK Query',\n  'How to randomly throw errors, a novella',\n].forEach((name) => {\n  db.post.create({ id: nanoid(), name })\n})\n\nexport const handlers = [\n  rest.post('/posts', async (req, res, ctx) => {\n    const { name } = req.body as Partial<Post>\n\n    if (Math.random() < 0.3) {\n      return res(\n        ctx.json({ error: 'Oh no, there was an error, try again.' }),\n        ctx.status(500),\n        ctx.delay(300),\n      )\n    }\n\n    const post = db.post.create({\n      id: nanoid(),\n      name,\n    })\n\n    return res(ctx.json(post), ctx.delay(300))\n  }),\n  rest.put('/posts/:id', (req, res, ctx) => {\n    const { name } = req.body as Partial<Post>\n\n    if (Math.random() < 0.3) {\n      return res(\n        ctx.json({ error: 'Oh no, there was an error, try again.' }),\n        ctx.status(500),\n        ctx.delay(300),\n      )\n    }\n\n    const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id\n\n    const post = db.post.update({\n      where: {\n        id: {\n          equals: id,\n        },\n      },\n      data: { name },\n    })\n\n    return res(ctx.json(post), ctx.delay(300))\n  }),\n  ...db.post.toHandlers('rest'),\n] as const\n"
  },
  {
    "path": "examples/query/react/mutations/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/mutations/src/store.ts",
    "content": "import { configureStore } from '@reduxjs/toolkit'\nimport { api } from './app/services/posts'\n\nexport const store = configureStore({\n  reducer: {\n    [api.reducerPath]: api.reducer,\n  },\n  // adding the api middleware enables caching, invalidation, polling and other features of `rtk-query`\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(api.middleware),\n})\n"
  },
  {
    "path": "examples/query/react/mutations/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/optimistic-update/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/optimistic-update\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"concepts-optimistic-updates\",\n  \"keywords\": [],\n  \"main\": \"./src/index.tsx\",\n  \"dependencies\": {\n    \"@chakra-ui/react\": \"2.10.7\",\n    \"@emotion/react\": \"^11.4.0\",\n    \"@emotion/styled\": \"^11.3.0\",\n    \"@mswjs/data\": \"^0.3.0\",\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"framer-motion\": \"^2.9.5\",\n    \"msw\": \"^0.40.2\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-icons\": \"3.11.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-router-dom\": \"6.3.0\",\n    \"react-scripts\": \"5.0.1\",\n    \"uuid\": \"^8.3.2\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\",\n    \"whatwg-fetch\": \"^3.4.1\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"prebuild\": \"rimraf dist/\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ],\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/optimistic-update/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/optimistic-update/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query Optimistic Update Example\",\n  \"name\": \"Optimistic Update Example\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/optimistic-update/public/mockServiceWorker.js",
    "content": "/**\n * Mock Service Worker.\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n/* eslint-disable */\n/* tslint:disable */\n\nconst INTEGRITY_CHECKSUM = '82ef9b96d8393b6da34527d1d6e19187'\nconst bypassHeaderName = 'x-msw-bypass'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  return self.skipWaiting()\n})\n\nself.addEventListener('activate', async function (event) {\n  return self.clients.claim()\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\n// Resolve the \"master\" client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMasterClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMasterClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: serializeHeaders(clonedResponse.headers),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const requestClone = request.clone()\n  const getOriginalResponse = () => fetch(requestClone)\n\n  // Bypass mocking when the request client is not active.\n  if (!client) {\n    return getOriginalResponse()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return await getOriginalResponse()\n  }\n\n  // Bypass requests with the explicit bypass header\n  if (requestClone.headers.get(bypassHeaderName) === 'true') {\n    const cleanRequestHeaders = serializeHeaders(requestClone.headers)\n\n    // Remove the bypass header to comply with the CORS preflight check.\n    delete cleanRequestHeaders[bypassHeaderName]\n\n    const originalRequest = new Request(requestClone, {\n      headers: new Headers(cleanRequestHeaders),\n    })\n\n    return fetch(originalRequest)\n  }\n\n  // Send the request to the client-side MSW.\n  const reqHeaders = serializeHeaders(request.headers)\n  const body = await request.text()\n\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: reqHeaders,\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body,\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_SUCCESS': {\n      return delayPromise(\n        () => respondWithMock(clientMessage),\n        clientMessage.payload.delay,\n      )\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return getOriginalResponse()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.payload\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a request Promise emulates a network error.\n      throw networkError\n    }\n\n    case 'INTERNAL_ERROR': {\n      const parsedBody = JSON.parse(clientMessage.payload.body)\n\n      console.error(\n        `\\\n[MSW] Request handler function for \"%s %s\" has thrown the following exception:\n\n${parsedBody.errorType}: ${parsedBody.message}\n(see more detailed error stack trace in the mocked response body)\n\nThis exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error.\nIf you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\\\n`,\n        request.method,\n        request.url,\n      )\n\n      return respondWithMock(clientMessage)\n    }\n  }\n\n  return getOriginalResponse()\n}\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  const requestId = uuidv4()\n\n  return event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      console.error(\n        '[MSW] Failed to mock a \"%s\" request to \"%s\": %s',\n        request.method,\n        request.url,\n        error,\n      )\n    }),\n  )\n})\n\nfunction serializeHeaders(headers) {\n  const reqHeaders = {}\n  headers.forEach((value, name) => {\n    reqHeaders[name] = reqHeaders[name]\n      ? [].concat(reqHeaders[name]).concat(value)\n      : value\n  })\n  return reqHeaders\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(JSON.stringify(message), [channel.port2])\n  })\n}\n\nfunction delayPromise(cb, duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => resolve(cb()), duration)\n  })\n}\n\nfunction respondWithMock(clientMessage) {\n  return new Response(clientMessage.payload.body, {\n    ...clientMessage.payload,\n    headers: clientMessage.payload.headers,\n  })\n}\n\nfunction uuidv4() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0\n    const v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n"
  },
  {
    "path": "examples/query/react/optimistic-update/src/App.tsx",
    "content": "import { Route, Routes } from 'react-router-dom'\nimport { PostsManager } from './features/posts/PostsManager'\n\nfunction App() {\n  return (\n    <Routes>\n      <Route path=\"*\" element={<PostsManager />} />\n    </Routes>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/optimistic-update/src/app/services/posts.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport interface Post {\n  id: string\n  name: string\n}\n\ntype PostsResponse = Post[]\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    getPosts: build.query<PostsResponse, void>({\n      query: () => 'posts',\n      providesTags: (result) =>\n        result\n          ? [\n              ...result.map(({ id }) => ({ type: 'Post' as const, id })),\n              { type: 'Post', id: 'LIST' },\n            ]\n          : [{ type: 'Post', id: 'LIST' }],\n    }),\n    addPost: build.mutation<Post, Partial<Post>>({\n      query: (body) => ({\n        url: `posts`,\n        method: 'POST',\n        body,\n      }),\n      invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n    }),\n    getPost: build.query<Post, string>({\n      query: (id) => `posts/${id}`,\n      providesTags: (result, error, id) => [{ type: 'Post', id }],\n    }),\n    updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n      query: ({ id, ...patch }) => ({\n        url: `posts/${id}`,\n        method: 'PUT',\n        body: patch,\n      }),\n      async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n        const patchResult = dispatch(\n          api.util.updateQueryData('getPost', id, (draft) => {\n            Object.assign(draft, patch)\n          }),\n        )\n        try {\n          await queryFulfilled\n        } catch {\n          patchResult.undo()\n        }\n      },\n      invalidatesTags: (result, error, { id }) => [{ type: 'Post', id }],\n    }),\n    deletePost: build.mutation<{ success: boolean; id: number }, number>({\n      query(id) {\n        return {\n          url: `posts/${id}`,\n          method: 'DELETE',\n        }\n      },\n      invalidatesTags: (result, error, id) => [{ type: 'Post', id }],\n    }),\n  }),\n})\n\nexport const {\n  useGetPostQuery,\n  useGetPostsQuery,\n  useAddPostMutation,\n  useUpdatePostMutation,\n  useDeletePostMutation,\n} = api\n"
  },
  {
    "path": "examples/query/react/optimistic-update/src/features/posts/PostDetail.tsx",
    "content": "import React, { useState } from 'react'\nimport { useNavigate, useParams } from 'react-router-dom'\nimport {\n  useDeletePostMutation,\n  useGetPostQuery,\n  useUpdatePostMutation,\n} from '../../app/services/posts'\nimport {\n  Box,\n  Button,\n  Center,\n  CloseButton,\n  Flex,\n  Heading,\n  Input,\n  Spacer,\n  Stack,\n  useToast,\n} from '@chakra-ui/react'\n\nconst EditablePostName = ({\n  name: initialName,\n  onUpdate,\n  onCancel,\n  isLoading = false,\n}: {\n  name: string\n  onUpdate: (name: string) => void\n  onCancel: () => void\n  isLoading?: boolean\n}) => {\n  const [name, setName] = useState(initialName)\n\n  const handleChange = ({\n    target: { value },\n  }: React.ChangeEvent<HTMLInputElement>) => setName(value)\n\n  const handleUpdate = () => onUpdate(name)\n  const handleCancel = () => onCancel()\n\n  return (\n    <Flex>\n      <Box flex={10}>\n        <Input\n          type=\"text\"\n          onChange={handleChange}\n          value={name}\n          disabled={isLoading}\n        />\n      </Box>\n      <Spacer />\n      <Box>\n        <Stack spacing={4} direction=\"row\" align=\"center\">\n          <Button onClick={handleUpdate} isLoading={isLoading}>\n            Update\n          </Button>\n          <CloseButton bg=\"red\" onClick={handleCancel} disabled={isLoading} />\n        </Stack>\n      </Box>\n    </Flex>\n  )\n}\n\nconst PostJsonDetail = ({ id }: { id: string }) => {\n  const { data: post } = useGetPostQuery(id)\n\n  return (\n    <Box mt={5} bg=\"#eee\">\n      <pre>{JSON.stringify(post, null, 2)}</pre>\n    </Box>\n  )\n}\n\nexport const PostDetail = () => {\n  const { id } = useParams<{ id: any }>()\n  const navigate = useNavigate()\n\n  const toast = useToast()\n\n  const [isEditing, setIsEditing] = useState(false)\n\n  const { data: post, isLoading } = useGetPostQuery(id)\n\n  const [updatePost, { isLoading: isUpdating }] = useUpdatePostMutation()\n\n  const [deletePost, { isLoading: isDeleting }] = useDeletePostMutation()\n\n  if (isLoading) {\n    return <div>Loading...</div>\n  }\n\n  if (!post) {\n    return (\n      <Center h=\"200px\">\n        <Heading size=\"md\">\n          Post {id} is missing! Try reloading or selecting another post...\n        </Heading>\n      </Center>\n    )\n  }\n\n  return (\n    <Box p={4}>\n      {isEditing ? (\n        <EditablePostName\n          name={post.name}\n          onUpdate={async (name) => {\n            try {\n              await updatePost({ id, name }).unwrap()\n            } catch {\n              toast({\n                title: 'An error occurred',\n                description: \"We couldn't save your changes, try again!\",\n                status: 'error',\n                duration: 2000,\n                isClosable: true,\n              })\n            } finally {\n              setIsEditing(false)\n            }\n          }}\n          onCancel={() => setIsEditing(false)}\n          isLoading={isUpdating}\n        />\n      ) : (\n        <Flex>\n          <Box>\n            <Heading size=\"md\">{post.name}</Heading>\n          </Box>\n          <Spacer />\n          <Box>\n            <Stack spacing={4} direction=\"row\" align=\"center\">\n              <Button\n                onClick={() => setIsEditing(true)}\n                disabled={isDeleting || isUpdating}\n              >\n                {isUpdating ? 'Updating...' : 'Edit'}\n              </Button>\n              <Button\n                onClick={() => deletePost(id).then(() => navigate('/posts'))}\n                disabled={isDeleting}\n                colorScheme=\"red\"\n              >\n                {isDeleting ? 'Deleting...' : 'Delete'}\n              </Button>\n            </Stack>\n          </Box>\n        </Flex>\n      )}\n      <PostJsonDetail id={post.id} />\n    </Box>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/optimistic-update/src/features/posts/PostsManager.tsx",
    "content": "import {\n  Box,\n  Button,\n  Center,\n  Divider,\n  Flex,\n  FormControl,\n  FormLabel,\n  Heading,\n  Input,\n  List,\n  ListIcon,\n  ListItem,\n  Spacer,\n  Stat,\n  StatLabel,\n  StatNumber,\n} from '@chakra-ui/react'\nimport { MdBook } from 'react-icons/md'\nimport React, { useState } from 'react'\nimport { Route, Routes, useNavigate } from 'react-router-dom'\nimport {\n  Post,\n  useAddPostMutation,\n  useGetPostQuery,\n  useGetPostsQuery,\n} from '../../app/services/posts'\nimport { PostDetail } from './PostDetail'\nimport { v4 as uuid } from 'uuid'\n\nconst AddPost = () => {\n  const initialValue: Post = { id: uuid(), name: '' }\n  const [post, setPost] = useState(initialValue)\n  const [addPost, { isLoading }] = useAddPostMutation()\n\n  const handleChange = ({ target }: React.ChangeEvent<HTMLInputElement>) => {\n    setPost((prev) => ({\n      ...prev,\n      [target.name]: target.value,\n    }))\n  }\n\n  const handleAddPost = () => addPost(post).then(() => setPost(initialValue))\n\n  return (\n    <Flex p={5}>\n      <Box flex={10}>\n        <FormControl isInvalid={Boolean(post.name.length < 3 && post.name)}>\n          <FormLabel htmlFor=\"name\">Post name</FormLabel>\n          <Input\n            id=\"name\"\n            name=\"name\"\n            placeholder=\"Enter post name\"\n            value={post.name}\n            onChange={handleChange}\n          />\n        </FormControl>\n      </Box>\n      <Spacer />\n      <Box>\n        <Button\n          mt={8}\n          colorScheme=\"purple\"\n          isLoading={isLoading}\n          onClick={handleAddPost}\n        >\n          Add Post\n        </Button>\n      </Box>\n    </Flex>\n  )\n}\n\nconst PostList = () => {\n  const { data: posts, isLoading } = useGetPostsQuery()\n  const navigate = useNavigate()\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <List spacing={3}>\n      {posts.map(({ id, name }) => (\n        <ListItem key={id} onClick={() => navigate(`/posts/${id}`)}>\n          <ListIcon as={MdBook} color=\"green.500\" /> {name}\n        </ListItem>\n      ))}\n    </List>\n  )\n}\n\nconst PostNameSubscribed = ({ id }: { id: string }) => {\n  const { data, isFetching } = useGetPostQuery(id)\n  const navigate = useNavigate()\n\n  console.log('data', data, isFetching)\n\n  if (!data) return null\n\n  return (\n    <ListItem key={id} onClick={() => navigate(`/posts/${id}`)}>\n      <ListIcon as={MdBook} color=\"green.500\" /> {data.name}\n    </ListItem>\n  )\n}\nconst PostListSubscribed = () => {\n  const { data: posts, isLoading } = useGetPostsQuery()\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <List spacing={3}>\n      {posts.map(({ id }) => (\n        <PostNameSubscribed id={id} key={id} />\n      ))}\n    </List>\n  )\n}\n\nexport const PostsCountStat = () => {\n  const { data: posts } = useGetPostsQuery()\n\n  if (!posts) return null\n\n  return (\n    <Stat>\n      <StatLabel>Active Posts</StatLabel>\n      <StatNumber>{posts?.length}</StatNumber>\n    </Stat>\n  )\n}\n\nexport const PostsManager = () => {\n  return (\n    <Box>\n      <Flex bg=\"#011627\" p={4} color=\"white\">\n        <Box>\n          <Heading size=\"xl\">Manage Posts</Heading>\n        </Box>\n        <Spacer />\n        <Box>\n          <PostsCountStat />\n        </Box>\n      </Flex>\n      <Divider />\n      <AddPost />\n      <Divider />\n      <Flex wrap=\"wrap\">\n        <Box flex={1} borderRight=\"1px solid #eee\">\n          <Box p={4} borderBottom=\"1px solid #eee\">\n            <Heading size=\"sm\">Posts</Heading>\n          </Box>\n          <Box p={4}>\n            <PostList />\n          </Box>\n          <Box p={4} borderBottom=\"1px solid #eee\">\n            <Heading size=\"sm\">Posts (subscribed)</Heading>\n          </Box>\n          <Box p={4}>\n            <PostListSubscribed />\n          </Box>\n        </Box>\n        <Box flex={2}>\n          <Routes>\n            <Route path=\"/posts/:id\" element={<PostDetail />} />\n            <Route\n              path=\"*\"\n              element={\n                <Center h=\"200px\">\n                  <Heading size=\"md\">Select a post to edit!</Heading>\n                </Center>\n              }\n            />\n          </Routes>\n        </Box>\n      </Flex>\n    </Box>\n  )\n}\n\nexport default PostsManager\n"
  },
  {
    "path": "examples/query/react/optimistic-update/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport { api } from './app/services/posts'\nimport { ChakraProvider } from '@chakra-ui/react'\n\nimport { BrowserRouter } from 'react-router-dom'\nimport { worker } from './mocks/browser'\nimport { ApiProvider } from '@reduxjs/toolkit/query/react'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nworker.start({ quiet: true }).then(() =>\n  ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(\n    <React.StrictMode>\n      <ApiProvider api={api}>\n        <ChakraProvider>\n          <BrowserRouter>\n            <App />\n          </BrowserRouter>\n        </ChakraProvider>\n      </ApiProvider>\n    </React.StrictMode>,\n  ),\n)\n"
  },
  {
    "path": "examples/query/react/optimistic-update/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './db'\n\nexport const worker = setupWorker(...(handlers as any))\n"
  },
  {
    "path": "examples/query/react/optimistic-update/src/mocks/db.ts",
    "content": "import { factory, primaryKey } from '@mswjs/data'\nimport { rest } from 'msw'\nimport { Post } from '../app/services/posts'\nconst db = factory({\n  post: {\n    id: primaryKey(String),\n    name: String,\n  },\n})\n\ndb.post.create({ id: '1', name: 'A sample post' })\ndb.post.create({ id: '2', name: 'A post about rtk query' })\n\nexport const handlers = [\n  rest.put('/posts/:id', (req, res, ctx) => {\n    const { name } = req.body as Partial<Post>\n\n    if (Math.random() < 0.5) {\n      return res(\n        ctx.json({ error: 'Oh no, there was an error' }),\n        ctx.status(500),\n        ctx.delay(400),\n      )\n    }\n\n    const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id\n\n    const post = db.post.update({\n      where: { id: { equals: id } },\n      data: { name },\n    })\n\n    return res(ctx.json(post), ctx.delay(400))\n  }),\n  ...db.post.toHandlers('rest'),\n] as const\n"
  },
  {
    "path": "examples/query/react/optimistic-update/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/optimistic-update/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/pagination/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/pagination\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"./src/index.tsx\",\n  \"dependencies\": {\n    \"@chakra-ui/react\": \"2.10.7\",\n    \"@emotion/react\": \"^11.4.0\",\n    \"@emotion/styled\": \"^11.3.0\",\n    \"@mswjs/data\": \"^0.3.0\",\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"faker\": \"^5.5.3\",\n    \"framer-motion\": \"^2.9.5\",\n    \"msw\": \"^0.40.2\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-icons\": \"^5.0.1\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/faker\": \"^5.5.5\",\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"prebuild\": \"rimraf dist/\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ],\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/pagination/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/pagination/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query Pagination Example\",\n  \"name\": \"Pagination Demo\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/pagination/public/mockServiceWorker.js",
    "content": "/* eslint-disable */\n/* tslint:disable */\n\n/**\n * Mock Service Worker (0.40.2).\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n\nconst INTEGRITY_CHECKSUM = '02f4ad4a2797f85668baf196e553d929'\nconst bypassHeaderName = 'x-msw-bypass'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  return self.skipWaiting()\n})\n\nself.addEventListener('activate', async function (event) {\n  return self.clients.claim()\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\n// Resolve the \"main\" client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMainClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMainClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: serializeHeaders(clonedResponse.headers),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const requestClone = request.clone()\n  const getOriginalResponse = () => fetch(requestClone)\n\n  // Bypass mocking when the request client is not active.\n  if (!client) {\n    return getOriginalResponse()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return await getOriginalResponse()\n  }\n\n  // Bypass requests with the explicit bypass header\n  if (requestClone.headers.get(bypassHeaderName) === 'true') {\n    const cleanRequestHeaders = serializeHeaders(requestClone.headers)\n\n    // Remove the bypass header to comply with the CORS preflight check.\n    delete cleanRequestHeaders[bypassHeaderName]\n\n    const originalRequest = new Request(requestClone, {\n      headers: new Headers(cleanRequestHeaders),\n    })\n\n    return fetch(originalRequest)\n  }\n\n  // Send the request to the client-side MSW.\n  const reqHeaders = serializeHeaders(request.headers)\n  const body = await request.text()\n\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: reqHeaders,\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body,\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_SUCCESS': {\n      return delayPromise(\n        () => respondWithMock(clientMessage),\n        clientMessage.payload.delay,\n      )\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return getOriginalResponse()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.payload\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a request Promise emulates a network error.\n      throw networkError\n    }\n\n    case 'INTERNAL_ERROR': {\n      const parsedBody = JSON.parse(clientMessage.payload.body)\n\n      console.error(\n        `\\\n[MSW] Uncaught exception in the request handler for \"%s %s\":\n\n${parsedBody.location}\n\nThis exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error, as it indicates a mistake in your code. If you wish to mock an error response, please see this guide: https://mswjs.io/docs/recipes/mocking-error-responses\\\n`,\n        request.method,\n        request.url,\n      )\n\n      return respondWithMock(clientMessage)\n    }\n  }\n\n  return getOriginalResponse()\n}\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n  const accept = request.headers.get('accept') || ''\n\n  // Bypass server-sent events.\n  if (accept.includes('text/event-stream')) {\n    return\n  }\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  const requestId = uuidv4()\n\n  return event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      if (error.name === 'NetworkError') {\n        console.warn(\n          '[MSW] Successfully emulated a network error for the \"%s %s\" request.',\n          request.method,\n          request.url,\n        )\n        return\n      }\n\n      // At this point, any exception indicates an issue with the original request/response.\n      console.error(\n        `\\\n[MSW] Caught an exception from the \"%s %s\" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,\n        request.method,\n        request.url,\n        `${error.name}: ${error.message}`,\n      )\n    }),\n  )\n})\n\nfunction serializeHeaders(headers) {\n  const reqHeaders = {}\n  headers.forEach((value, name) => {\n    reqHeaders[name] = reqHeaders[name]\n      ? [].concat(reqHeaders[name]).concat(value)\n      : value\n  })\n  return reqHeaders\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(JSON.stringify(message), [channel.port2])\n  })\n}\n\nfunction delayPromise(cb, duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => resolve(cb()), duration)\n  })\n}\n\nfunction respondWithMock(clientMessage) {\n  return new Response(clientMessage.payload.body, {\n    ...clientMessage.payload,\n    headers: clientMessage.payload.headers,\n  })\n}\n\nfunction uuidv4() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0\n    const v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n"
  },
  {
    "path": "examples/query/react/pagination/src/App.tsx",
    "content": "import { PostsManager } from './features/posts/PostsManager'\n\nfunction App() {\n  return (\n    <PostsManager />\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/pagination/src/app/services/posts.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const postStatuses = ['draft', 'published', 'pending_review'] as const\n\nexport interface Post {\n  id: string\n  title: string\n  author: string\n  content: string\n  status: (typeof postStatuses)[number]\n  created_at: string\n  updated_at: string\n}\n\ninterface ListResponse<T> {\n  page: number\n  per_page: number\n  total: number\n  total_pages: number\n  data: T[]\n}\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    listPosts: build.query<ListResponse<Post>, number | void>({\n      query: (page = 1) => `posts?page=${page}`,\n    }),\n  }),\n})\n\nexport const { useListPostsQuery } = api\n"
  },
  {
    "path": "examples/query/react/pagination/src/features/posts/PostsManager.tsx",
    "content": "import * as React from 'react'\nimport {\n  Badge,\n  Box,\n  Button,\n  Divider,\n  Flex,\n  Heading,\n  HStack,\n  Icon,\n  List,\n  ListIcon,\n  ListItem,\n  Spacer,\n  Stat,\n  StatLabel,\n  StatNumber,\n} from '@chakra-ui/react'\nimport { MdArrowBack, MdArrowForward, MdBook } from 'react-icons/md'\nimport { Post, useListPostsQuery } from '../../app/services/posts'\n\nconst getColorForStatus = (status: Post['status']) => {\n  return status === 'draft'\n    ? 'gray'\n    : status === 'pending_review'\n      ? 'orange'\n      : 'green'\n}\n\nconst PostList = () => {\n  const [page, setPage] = React.useState(1)\n  const { data: posts, isLoading, isFetching } = useListPostsQuery(page)\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts?.data) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <Box>\n      <HStack spacing=\"14px\">\n        <Button\n          onClick={() => setPage((prev) => prev - 1)}\n          isLoading={isFetching}\n          disabled={page === 1}\n        >\n          <Icon as={MdArrowBack} />\n        </Button>\n        <Button\n          onClick={() => setPage((prev) => prev + 1)}\n          isLoading={isFetching}\n          disabled={page === posts.total_pages}\n        >\n          <Icon as={MdArrowForward} />\n        </Button>\n        <Box>{`${page} / ${posts.total_pages}`}</Box>\n      </HStack>\n      <List spacing={3} mt={6}>\n        {posts?.data.map(({ id, title, status }) => (\n          <ListItem key={id}>\n            <ListIcon as={MdBook} color=\"green.500\" /> {title}{' '}\n            <Badge\n              ml=\"1\"\n              fontSize=\"0.8em\"\n              colorScheme={getColorForStatus(status)}\n            >\n              {status}\n            </Badge>\n          </ListItem>\n        ))}\n      </List>\n    </Box>\n  )\n}\n\nexport const PostsCountStat = () => {\n  const { data: posts } = useListPostsQuery()\n\n  return (\n    <Stat>\n      <StatLabel>Total Posts</StatLabel>\n      <StatNumber>{`${posts?.total || 'NA'}`}</StatNumber>\n    </Stat>\n  )\n}\n\nexport const PostsManager = () => {\n  return (\n    <Box>\n      <Flex wrap=\"wrap\" bg=\"#011627\" p={4} color=\"white\">\n        <Box>\n          <Heading size=\"xl\">Manage Posts</Heading>\n        </Box>\n        <Spacer />\n        <Box>\n          <PostsCountStat />\n        </Box>\n      </Flex>\n      <Divider />\n      <Box p={4}>\n        <PostList />\n      </Box>\n    </Box>\n  )\n}\n\nexport default PostsManager\n"
  },
  {
    "path": "examples/query/react/pagination/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport { api } from './app/services/posts'\nimport { ChakraProvider } from '@chakra-ui/react'\n\nimport { worker } from './mocks/browser'\nimport { ApiProvider } from '@reduxjs/toolkit/query/react'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nworker.start({ quiet: true }).then(() =>\n  ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(\n    <React.StrictMode>\n      <ApiProvider api={api}>\n        <ChakraProvider>\n            <App />\n        </ChakraProvider>\n      </ApiProvider>\n    </React.StrictMode>,\n  ),\n)\n"
  },
  {
    "path": "examples/query/react/pagination/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './db'\n\nexport const worker = setupWorker(...(handlers as any))\n"
  },
  {
    "path": "examples/query/react/pagination/src/mocks/db.ts",
    "content": "import { nanoid } from '@reduxjs/toolkit'\nimport { factory, primaryKey } from '@mswjs/data'\nimport faker from 'faker'\nimport { Post, postStatuses } from '../app/services/posts'\nimport { rest } from 'msw'\n\nconst db = factory({\n  post: {\n    id: primaryKey(String),\n    name: String,\n    title: String,\n    author: String,\n    content: String,\n    status: String,\n    created_at: String,\n    updated_at: String,\n  },\n})\n\nconst getRandomStatus = () =>\n  postStatuses[Math.floor(Math.random() * postStatuses.length)]\n\nconst createPostData = (): Post => {\n  const date = faker.date.past().toISOString()\n  return {\n    id: nanoid(),\n    title: faker.lorem.words(),\n    author: faker.name.findName(),\n    content: faker.lorem.paragraphs(),\n    status: getRandomStatus(),\n    created_at: date,\n    updated_at: date,\n  }\n}\n\n;[...new Array(50)].forEach((_) => db.post.create(createPostData()))\n\nexport const handlers = [\n  rest.get('/posts', (req, res, ctx) => {\n    const page = (req.url.searchParams.get('page') || 1) as number\n    const per_page = (req.url.searchParams.get('per_page') || 10) as number\n    const data = db.post.findMany({\n      take: per_page,\n      skip: Math.max(per_page * (page - 1), 0),\n    })\n\n    return res(\n      ctx.json({\n        data,\n        page,\n        total_pages: Math.ceil(db.post.count() / per_page),\n        total: db.post.count(),\n      }),\n    )\n  }),\n  ...db.post.toHandlers('rest'),\n] as const\n"
  },
  {
    "path": "examples/query/react/pagination/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/pagination/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/polling/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/polling\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"src/index.tsx\",\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\"\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ]\n}\n"
  },
  {
    "path": "examples/query/react/polling/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"\n    />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <!--\n      manifest.json provides metadata used when your web app is added to the\n      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n\n  <body>\n    <noscript> You need to enable JavaScript to run this app. </noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/polling/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query Polling Example\",\n  \"name\": \"Polling Example\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/polling/src/App.tsx",
    "content": "import * as React from 'react'\nimport { Pokemon } from './Pokemon'\nimport { PokemonName, POKEMON_NAMES } from './pokemon.data'\nimport './styles.css'\n\nconst getRandomPokemonName = () =>\n  POKEMON_NAMES[Math.floor(Math.random() * POKEMON_NAMES.length)]\n\nexport default function App() {\n  const [pokemon, setPokemon] = React.useState<PokemonName[]>(['bulbasaur'])\n\n  return (\n    <div className=\"App\">\n      <div>\n        <button\n          onClick={() =>\n            setPokemon((prev) => [...prev, getRandomPokemonName()])\n          }\n        >\n          Add random pokemon\n        </button>\n        <button onClick={() => setPokemon((prev) => [...prev, 'bulbasaur'])}>\n          Add bulbasaur\n        </button>\n      </div>\n\n      {pokemon.map((name, index) => (\n        <Pokemon key={index} name={name} />\n      ))}\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/polling/src/Pokemon.tsx",
    "content": "import * as React from 'react'\nimport { useGetPokemonByNameQuery } from './services/pokemon'\nimport type { PokemonName } from './pokemon.data'\n\nconst intervalOptions = [\n  { label: 'Off', value: 0 },\n  { label: '3s', value: 3000 },\n  { label: '5s', value: 5000 },\n  { label: '10s', value: 10000 },\n  { label: '1m', value: 60000 },\n]\n\nconst getRandomIntervalValue = () =>\n  intervalOptions[Math.floor(Math.random() * intervalOptions.length)].value\n\nexport const Pokemon = ({ name }: { name: PokemonName }) => {\n  const [pollingInterval, setPollingInterval] = React.useState(\n    getRandomIntervalValue(),\n  )\n\n  const { data, error, isLoading, isFetching, refetch } =\n    useGetPokemonByNameQuery(name, {\n      pollingInterval,\n    })\n\n  return (\n    <div\n      style={{\n        float: 'left',\n        textAlign: 'center',\n        ...(isFetching ? { background: '#e6ffe8' } : {}),\n      }}\n    >\n      {error ? (\n        <>Oh no, there was an error loading {name}</>\n      ) : isLoading ? (\n        <>Loading...</>\n      ) : data ? (\n        <>\n          <h3>{data.species.name}</h3>\n          <div style={{ minWidth: 96, minHeight: 96 }}>\n            <img\n              src={data.sprites.front_shiny}\n              alt={data.species.name}\n              style={{ ...(isFetching ? { opacity: 0.3 } : {}) }}\n            />\n          </div>\n          <div>\n            <label style={{ display: 'block' }}>Polling interval</label>\n            <select\n              value={pollingInterval}\n              onChange={({ target: { value } }) =>\n                setPollingInterval(Number(value))\n              }\n            >\n              {intervalOptions.map(({ label, value }) => (\n                <option key={value} value={value}>\n                  {label}\n                </option>\n              ))}\n            </select>\n          </div>\n          <div>\n            <button onClick={refetch} disabled={isFetching}>\n              {isFetching ? 'Loading' : 'Manually refetch'}\n            </button>\n          </div>\n        </>\n      ) : (\n        'No Data'\n      )}\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/polling/src/index.tsx",
    "content": "import ReactDOM from 'react-dom/client'\nimport { Provider } from 'react-redux'\n\nimport App from './App'\nimport { store } from './store'\n\nconst rootElement = document.getElementById('root')\nconst reactRoot = ReactDOM.createRoot(rootElement as HTMLElement)\n\nreactRoot.render(\n  <Provider store={store}>\n    <App />\n  </Provider>,\n)\n"
  },
  {
    "path": "examples/query/react/polling/src/pokemon.data.ts",
    "content": "export const POKEMON_NAMES = [\n  'bulbasaur',\n  'ivysaur',\n  'venusaur',\n  'charmander',\n  'charmeleon',\n  'charizard',\n  'squirtle',\n  'wartortle',\n  'blastoise',\n  'caterpie',\n  'metapod',\n  'butterfree',\n  'weedle',\n  'kakuna',\n  'beedrill',\n  'pidgey',\n  'pidgeotto',\n  'pidgeot',\n  'rattata',\n  'raticate',\n  'spearow',\n  'fearow',\n  'ekans',\n  'arbok',\n  'pikachu',\n  'raichu',\n  'sandshrew',\n  'sandslash',\n  'nidoran',\n  'nidorina',\n  'nidoqueen',\n  'nidoran',\n  'nidorino',\n  'nidoking',\n  'clefairy',\n  'clefable',\n  'vulpix',\n  'ninetales',\n  'jigglypuff',\n  'wigglytuff',\n  'zubat',\n  'golbat',\n  'oddish',\n  'gloom',\n  'vileplume',\n  'paras',\n  'parasect',\n  'venonat',\n  'venomoth',\n  'diglett',\n  'dugtrio',\n  'meowth',\n  'persian',\n  'psyduck',\n  'golduck',\n  'mankey',\n  'primeape',\n  'growlithe',\n  'arcanine',\n  'poliwag',\n  'poliwhirl',\n  'poliwrath',\n  'abra',\n  'kadabra',\n  'alakazam',\n  'machop',\n  'machoke',\n  'machamp',\n  'bellsprout',\n  'weepinbell',\n  'victreebel',\n  'tentacool',\n  'tentacruel',\n  'geodude',\n  'graveler',\n  'golem',\n  'ponyta',\n  'rapidash',\n  'slowpoke',\n  'slowbro',\n  'magnemite',\n  'magneton',\n  \"farfetch'd\",\n  'doduo',\n  'dodrio',\n  'seel',\n  'dewgong',\n  'grimer',\n  'muk',\n  'shellder',\n  'cloyster',\n  'gastly',\n  'haunter',\n  'gengar',\n  'onix',\n  'drowzee',\n  'hypno',\n  'krabby',\n  'kingler',\n  'voltorb',\n  'electrode',\n  'exeggcute',\n  'exeggutor',\n  'cubone',\n  'marowak',\n  'hitmonlee',\n  'hitmonchan',\n  'lickitung',\n  'koffing',\n  'weezing',\n  'rhyhorn',\n  'rhydon',\n  'chansey',\n  'tangela',\n  'kangaskhan',\n  'horsea',\n  'seadra',\n  'goldeen',\n  'seaking',\n  'staryu',\n  'starmie',\n  'mr. mime',\n  'scyther',\n  'jynx',\n  'electabuzz',\n  'magmar',\n  'pinsir',\n  'tauros',\n  'magikarp',\n  'gyarados',\n  'lapras',\n  'ditto',\n  'eevee',\n  'vaporeon',\n  'jolteon',\n  'flareon',\n  'porygon',\n  'omanyte',\n  'omastar',\n  'kabuto',\n  'kabutops',\n  'aerodactyl',\n  'snorlax',\n  'articuno',\n  'zapdos',\n  'moltres',\n  'dratini',\n  'dragonair',\n  'dragonite',\n  'mewtwo',\n  'mew',\n] as const\n\nexport type PokemonName = (typeof POKEMON_NAMES)[number]\n"
  },
  {
    "path": "examples/query/react/polling/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/polling/src/services/pokemon.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport type { PokemonName } from '../pokemon.data'\n\nexport const pokemonApi = createApi({\n  reducerPath: 'pokemonApi',\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n  endpoints: (build) => ({\n    getPokemonByName: build.query({\n      query: (name: PokemonName) => `pokemon/${name}`,\n    }),\n  }),\n})\n\n// Export hooks for usage in functional components\nexport const { useGetPokemonByNameQuery } = pokemonApi\n"
  },
  {
    "path": "examples/query/react/polling/src/store.ts",
    "content": "import { configureStore } from '@reduxjs/toolkit'\nimport { pokemonApi } from './services/pokemon'\n\nexport const store = configureStore({\n  reducer: {\n    [pokemonApi.reducerPath]: pokemonApi.reducer,\n  },\n  // adding the api middleware enables caching, invalidation, polling and other features of `rtk-query`\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(pokemonApi.middleware),\n})\n"
  },
  {
    "path": "examples/query/react/polling/src/styles.css",
    "content": ".App {\n  font-family: sans-serif;\n  text-align: center;\n}\n"
  },
  {
    "path": "examples/query/react/polling/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/prefetching/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/prefetching\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"./src/index.tsx\",\n  \"dependencies\": {\n    \"@chakra-ui/react\": \"2.10.7\",\n    \"@emotion/react\": \"^11.4.0\",\n    \"@emotion/styled\": \"^11.3.0\",\n    \"@mswjs/data\": \"^0.3.0\",\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"faker\": \"^5.5.3\",\n    \"framer-motion\": \"^2.9.5\",\n    \"msw\": \"^0.40.2\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-icons\": \"3.11.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-router-dom\": \"6.3.0\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/faker\": \"^5.5.5\",\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"prebuild\": \"rimraf dist/\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ],\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/prefetching/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/prefetching/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query Demo\",\n  \"name\": \"RTK Query Demo\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/prefetching/public/mockServiceWorker.js",
    "content": "/**\n * Mock Service Worker.\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n/* eslint-disable */\n/* tslint:disable */\n\nconst INTEGRITY_CHECKSUM = '82ef9b96d8393b6da34527d1d6e19187'\nconst bypassHeaderName = 'x-msw-bypass'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  return self.skipWaiting()\n})\n\nself.addEventListener('activate', async function (event) {\n  return self.clients.claim()\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\n// Resolve the \"master\" client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMasterClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMasterClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: serializeHeaders(clonedResponse.headers),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const requestClone = request.clone()\n  const getOriginalResponse = () => fetch(requestClone)\n\n  // Bypass mocking when the request client is not active.\n  if (!client) {\n    return getOriginalResponse()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return await getOriginalResponse()\n  }\n\n  // Bypass requests with the explicit bypass header\n  if (requestClone.headers.get(bypassHeaderName) === 'true') {\n    const cleanRequestHeaders = serializeHeaders(requestClone.headers)\n\n    // Remove the bypass header to comply with the CORS preflight check.\n    delete cleanRequestHeaders[bypassHeaderName]\n\n    const originalRequest = new Request(requestClone, {\n      headers: new Headers(cleanRequestHeaders),\n    })\n\n    return fetch(originalRequest)\n  }\n\n  // Send the request to the client-side MSW.\n  const reqHeaders = serializeHeaders(request.headers)\n  const body = await request.text()\n\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: reqHeaders,\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body,\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_SUCCESS': {\n      return delayPromise(\n        () => respondWithMock(clientMessage),\n        clientMessage.payload.delay,\n      )\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return getOriginalResponse()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.payload\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a request Promise emulates a network error.\n      throw networkError\n    }\n\n    case 'INTERNAL_ERROR': {\n      const parsedBody = JSON.parse(clientMessage.payload.body)\n\n      console.error(\n        `\\\n[MSW] Request handler function for \"%s %s\" has thrown the following exception:\n\n${parsedBody.errorType}: ${parsedBody.message}\n(see more detailed error stack trace in the mocked response body)\n\nThis exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error.\nIf you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\\\n`,\n        request.method,\n        request.url,\n      )\n\n      return respondWithMock(clientMessage)\n    }\n  }\n\n  return getOriginalResponse()\n}\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  const requestId = uuidv4()\n\n  return event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      console.error(\n        '[MSW] Failed to mock a \"%s\" request to \"%s\": %s',\n        request.method,\n        request.url,\n        error,\n      )\n    }),\n  )\n})\n\nfunction serializeHeaders(headers) {\n  const reqHeaders = {}\n  headers.forEach((value, name) => {\n    reqHeaders[name] = reqHeaders[name]\n      ? [].concat(reqHeaders[name]).concat(value)\n      : value\n  })\n  return reqHeaders\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(JSON.stringify(message), [channel.port2])\n  })\n}\n\nfunction delayPromise(cb, duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => resolve(cb()), duration)\n  })\n}\n\nfunction respondWithMock(clientMessage) {\n  return new Response(clientMessage.payload.body, {\n    ...clientMessage.payload,\n    headers: clientMessage.payload.headers,\n  })\n}\n\nfunction uuidv4() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0\n    const v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n"
  },
  {
    "path": "examples/query/react/prefetching/src/App.tsx",
    "content": "import { Route, Routes } from 'react-router-dom'\nimport { PostsManager } from './features/posts/PostsManager'\n\nfunction App() {\n  return (\n    <Routes>\n      <Route path=\"*\" element={<PostsManager />} />\n    </Routes>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/prefetching/src/app/services/posts.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const postStatuses = ['draft', 'published', 'pending_review'] as const\n\nexport interface Post {\n  id: string\n  title: string\n  author: string\n  content: string\n  status: (typeof postStatuses)[number]\n  created_at: string\n  updated_at: string\n}\n\ninterface ListResponse<T> {\n  page: number\n  per_page: number\n  total: number\n  total_pages: number\n  data: T[]\n}\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    listPosts: build.query<ListResponse<Post>, number | void>({\n      query: (page = 1) => `posts?page=${page}`,\n    }),\n  }),\n})\n\nexport const { useListPostsQuery, usePrefetch } = api\n"
  },
  {
    "path": "examples/query/react/prefetching/src/features/posts/PostsManager.tsx",
    "content": "import { useCallback, useState } from 'react'\nimport {\n  Badge,\n  Box,\n  Button,\n  Divider,\n  Flex,\n  Heading,\n  HStack,\n  Icon,\n  List,\n  ListIcon,\n  ListItem,\n  Spacer,\n  Stat,\n  StatLabel,\n  StatNumber,\n} from '@chakra-ui/react'\nimport { MdArrowBack, MdArrowForward, MdBook } from 'react-icons/md'\nimport { Post, usePrefetch, useListPostsQuery } from '../../app/services/posts'\n\nconst getColorForStatus = (status: Post['status']) => {\n  return status === 'draft'\n    ? 'gray'\n    : status === 'pending_review'\n      ? 'orange'\n      : 'green'\n}\n\nconst PostList = () => {\n  const [page, setPage] = useState(1)\n  const { data: posts, isLoading, isFetching } = useListPostsQuery(page)\n  const prefetchPage = usePrefetch('listPosts')\n\n  const prefetchNext = useCallback(() => {\n    prefetchPage(page + 1)\n  }, [prefetchPage, page])\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts?.data) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <Box>\n      <HStack spacing=\"14px\">\n        <Button\n          onClick={() => setPage((prev) => prev - 1)}\n          isLoading={isFetching}\n          disabled={page === 1}\n        >\n          <Icon as={MdArrowBack} />\n        </Button>\n        <Button\n          onClick={() => setPage((prev) => prev + 1)}\n          isLoading={isFetching}\n          disabled={page === posts.total_pages}\n          onMouseEnter={prefetchNext}\n        >\n          <Icon as={MdArrowForward} />\n        </Button>\n        <Box>{`${page} / ${posts.total_pages}`}</Box>\n      </HStack>\n      <List spacing={3} mt={6}>\n        {posts?.data.map(({ id, title, status }) => (\n          <ListItem key={id}>\n            <ListIcon as={MdBook} color=\"green.500\" /> {title}{' '}\n            <Badge\n              ml=\"1\"\n              fontSize=\"0.8em\"\n              colorScheme={getColorForStatus(status)}\n            >\n              {status}\n            </Badge>\n          </ListItem>\n        ))}\n      </List>\n    </Box>\n  )\n}\n\nexport const PostsCountStat = () => {\n  const { data: posts } = useListPostsQuery()\n\n  return (\n    <Stat>\n      <StatLabel>Total Posts</StatLabel>\n      <StatNumber>{`${posts?.total || 'NA'}`}</StatNumber>\n    </Stat>\n  )\n}\n\nexport const PostsManager = () => {\n  return (\n    <Box>\n      <Flex wrap=\"wrap\" bg=\"#011627\" p={4} color=\"white\">\n        <Box>\n          <Heading size=\"xl\">Manage Posts</Heading>\n        </Box>\n        <Spacer />\n        <Box>\n          <PostsCountStat />\n        </Box>\n      </Flex>\n      <Divider />\n      <Box p={4}>\n        <PostList />\n      </Box>\n    </Box>\n  )\n}\n\nexport default PostsManager\n"
  },
  {
    "path": "examples/query/react/prefetching/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport { api } from './app/services/posts'\nimport { ChakraProvider } from '@chakra-ui/react'\n\nimport { BrowserRouter } from 'react-router-dom'\nimport { worker } from './mocks/browser'\nimport { ApiProvider } from '@reduxjs/toolkit/query/react'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nworker.start({ quiet: true }).then(() =>\n  ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(\n    <React.StrictMode>\n      <ApiProvider api={api}>\n        <ChakraProvider>\n          <BrowserRouter>\n            <App />\n          </BrowserRouter>\n        </ChakraProvider>\n      </ApiProvider>\n    </React.StrictMode>,\n  ),\n)\n"
  },
  {
    "path": "examples/query/react/prefetching/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './db'\n\nexport const worker = setupWorker(...(handlers as any))\n"
  },
  {
    "path": "examples/query/react/prefetching/src/mocks/db.ts",
    "content": "import { nanoid } from '@reduxjs/toolkit'\nimport { factory, primaryKey } from '@mswjs/data'\nimport faker from 'faker'\nimport { Post, postStatuses } from '../app/services/posts'\nimport { rest } from 'msw'\n\nconst db = factory({\n  post: {\n    id: primaryKey(String),\n    name: String,\n    title: String,\n    author: String,\n    content: String,\n    status: String,\n    created_at: String,\n    updated_at: String,\n  },\n})\n\nconst getRandomStatus = () =>\n  postStatuses[Math.floor(Math.random() * postStatuses.length)]\n\nconst createPostData = (): Post => {\n  const date = faker.date.past().toISOString()\n  return {\n    id: nanoid(),\n    title: faker.lorem.words(),\n    author: faker.name.findName(),\n    content: faker.lorem.paragraphs(),\n    status: getRandomStatus(),\n    created_at: date,\n    updated_at: date,\n  }\n}\n\n;[...new Array(50)].forEach((_) => db.post.create(createPostData()))\n\nexport const handlers = [\n  rest.get('/posts', (req, res, ctx) => {\n    const page = (req.url.searchParams.get('page') || 1) as number\n    const per_page = (req.url.searchParams.get('per_page') || 10) as number\n    const data = db.post.findMany({\n      take: per_page,\n      skip: Math.max(per_page * (page - 1), 0),\n    })\n\n    return res(\n      ctx.json({\n        data,\n        page,\n        total_pages: Math.ceil(db.post.count() / per_page),\n        total: db.post.count(),\n      }),\n    )\n  }),\n  ...db.post.toHandlers('rest'),\n] as const\n"
  },
  {
    "path": "examples/query/react/prefetching/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/prefetching/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/prefetching-automatic\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"./src/index.tsx\",\n  \"dependencies\": {\n    \"@chakra-ui/react\": \"2.10.7\",\n    \"@emotion/react\": \"^11.4.0\",\n    \"@emotion/styled\": \"^11.3.0\",\n    \"@mswjs/data\": \"^0.3.0\",\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"faker\": \"^5.5.3\",\n    \"framer-motion\": \"^2.9.5\",\n    \"msw\": \"^0.40.2\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-icons\": \"3.11.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-router-dom\": \"6.3.0\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/faker\": \"^5.5.5\",\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"prebuild\": \"rimraf dist/\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ],\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query Demo\",\n  \"name\": \"RTK Query Demo\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/public/mockServiceWorker.js",
    "content": "/**\n * Mock Service Worker.\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n/* eslint-disable */\n/* tslint:disable */\n\nconst INTEGRITY_CHECKSUM = '82ef9b96d8393b6da34527d1d6e19187'\nconst bypassHeaderName = 'x-msw-bypass'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  return self.skipWaiting()\n})\n\nself.addEventListener('activate', async function (event) {\n  return self.clients.claim()\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\n// Resolve the \"master\" client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMasterClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMasterClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: serializeHeaders(clonedResponse.headers),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const requestClone = request.clone()\n  const getOriginalResponse = () => fetch(requestClone)\n\n  // Bypass mocking when the request client is not active.\n  if (!client) {\n    return getOriginalResponse()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return await getOriginalResponse()\n  }\n\n  // Bypass requests with the explicit bypass header\n  if (requestClone.headers.get(bypassHeaderName) === 'true') {\n    const cleanRequestHeaders = serializeHeaders(requestClone.headers)\n\n    // Remove the bypass header to comply with the CORS preflight check.\n    delete cleanRequestHeaders[bypassHeaderName]\n\n    const originalRequest = new Request(requestClone, {\n      headers: new Headers(cleanRequestHeaders),\n    })\n\n    return fetch(originalRequest)\n  }\n\n  // Send the request to the client-side MSW.\n  const reqHeaders = serializeHeaders(request.headers)\n  const body = await request.text()\n\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: reqHeaders,\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body,\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_SUCCESS': {\n      return delayPromise(\n        () => respondWithMock(clientMessage),\n        clientMessage.payload.delay,\n      )\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return getOriginalResponse()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.payload\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a request Promise emulates a network error.\n      throw networkError\n    }\n\n    case 'INTERNAL_ERROR': {\n      const parsedBody = JSON.parse(clientMessage.payload.body)\n\n      console.error(\n        `\\\n[MSW] Request handler function for \"%s %s\" has thrown the following exception:\n\n${parsedBody.errorType}: ${parsedBody.message}\n(see more detailed error stack trace in the mocked response body)\n\nThis exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error.\nIf you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\\\n`,\n        request.method,\n        request.url,\n      )\n\n      return respondWithMock(clientMessage)\n    }\n  }\n\n  return getOriginalResponse()\n}\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  const requestId = uuidv4()\n\n  return event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      console.error(\n        '[MSW] Failed to mock a \"%s\" request to \"%s\": %s',\n        request.method,\n        request.url,\n        error,\n      )\n    }),\n  )\n})\n\nfunction serializeHeaders(headers) {\n  const reqHeaders = {}\n  headers.forEach((value, name) => {\n    reqHeaders[name] = reqHeaders[name]\n      ? [].concat(reqHeaders[name]).concat(value)\n      : value\n  })\n  return reqHeaders\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(JSON.stringify(message), [channel.port2])\n  })\n}\n\nfunction delayPromise(cb, duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => resolve(cb()), duration)\n  })\n}\n\nfunction respondWithMock(clientMessage) {\n  return new Response(clientMessage.payload.body, {\n    ...clientMessage.payload,\n    headers: clientMessage.payload.headers,\n  })\n}\n\nfunction uuidv4() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0\n    const v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/src/App.tsx",
    "content": "import { Route, Routes } from 'react-router-dom'\nimport { PostsManager } from './features/posts/PostsManager'\n\nfunction App() {\n  return (\n    <Routes>\n      <Route path=\"*\" element={<PostsManager />} />\n    </Routes>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/src/app/services/posts.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const postStatuses = ['draft', 'published', 'pending_review'] as const\n\nexport interface Post {\n  id: string\n  title: string\n  author: string\n  content: string\n  status: (typeof postStatuses)[number]\n  created_at: string\n  updated_at: string\n}\n\ninterface ListResponse<T> {\n  page: number\n  per_page: number\n  total: number\n  total_pages: number\n  data: T[]\n}\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    listPosts: build.query<ListResponse<Post>, number | void>({\n      query: (page = 1) => `posts?page=${page}`,\n    }),\n  }),\n})\n\nexport const { useListPostsQuery, usePrefetch } = api\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/src/features/posts/PostsManager.tsx",
    "content": "import { useCallback, useState, useEffect } from 'react'\nimport {\n  Badge,\n  Box,\n  Button,\n  Divider,\n  Flex,\n  Heading,\n  HStack,\n  Icon,\n  List,\n  ListIcon,\n  ListItem,\n  Spacer,\n  Stat,\n  StatLabel,\n  StatNumber,\n} from '@chakra-ui/react'\nimport { MdArrowBack, MdArrowForward, MdBook } from 'react-icons/md'\nimport { Post, usePrefetch, useListPostsQuery } from '../../app/services/posts'\n\nconst getColorForStatus = (status: Post['status']) => {\n  return status === 'draft'\n    ? 'gray'\n    : status === 'pending_review'\n      ? 'orange'\n      : 'green'\n}\n\nconst PostList = () => {\n  const [page, setPage] = useState(1)\n  const { data: posts, isLoading, isFetching } = useListPostsQuery(page)\n  const prefetchPage = usePrefetch('listPosts')\n\n  const prefetchNext = useCallback(() => {\n    prefetchPage(page + 1)\n  }, [prefetchPage, page])\n\n  useEffect(() => {\n    if (page !== posts?.total_pages) {\n      prefetchNext()\n    }\n  }, [posts, page, prefetchNext])\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts?.data) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <Box>\n      <HStack spacing=\"14px\">\n        <Button\n          onClick={() => setPage((prev) => prev - 1)}\n          isLoading={isFetching}\n          disabled={page === 1}\n        >\n          <Icon as={MdArrowBack} />\n        </Button>\n        <Button\n          onClick={() => setPage((prev) => prev + 1)}\n          isLoading={isFetching}\n          disabled={page === posts.total_pages}\n          onMouseEnter={prefetchNext}\n        >\n          <Icon as={MdArrowForward} />\n        </Button>\n        <Box>{`${page} / ${posts.total_pages}`}</Box>\n      </HStack>\n      <List spacing={3} mt={6}>\n        {posts?.data.map(({ id, title, status }) => (\n          <ListItem key={id}>\n            <ListIcon as={MdBook} color=\"green.500\" /> {title}{' '}\n            <Badge\n              ml=\"1\"\n              fontSize=\"0.8em\"\n              colorScheme={getColorForStatus(status)}\n            >\n              {status}\n            </Badge>\n          </ListItem>\n        ))}\n      </List>\n    </Box>\n  )\n}\n\nexport const PostsCountStat = () => {\n  const { data: posts } = useListPostsQuery()\n\n  return (\n    <Stat>\n      <StatLabel>Total Posts</StatLabel>\n      <StatNumber>{`${posts?.total || 'NA'}`}</StatNumber>\n    </Stat>\n  )\n}\n\nexport const PostsManager = () => {\n  return (\n    <Box>\n      <Flex wrap=\"wrap\" bg=\"#011627\" p={4} color=\"white\">\n        <Box>\n          <Heading size=\"xl\">Manage Posts</Heading>\n        </Box>\n        <Spacer />\n        <Box>\n          <PostsCountStat />\n        </Box>\n      </Flex>\n      <Divider />\n      <Box p={4}>\n        <PostList />\n      </Box>\n    </Box>\n  )\n}\n\nexport default PostsManager\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport { api } from './app/services/posts'\nimport { ChakraProvider } from '@chakra-ui/react'\n\nimport { BrowserRouter } from 'react-router-dom'\nimport { worker } from './mocks/browser'\nimport { ApiProvider } from '@reduxjs/toolkit/query/react'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nworker.start({ quiet: true }).then(() =>\n  ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(\n    <React.StrictMode>\n      <ApiProvider api={api}>\n        <ChakraProvider>\n          <BrowserRouter>\n            <App />\n          </BrowserRouter>\n        </ChakraProvider>\n      </ApiProvider>\n    </React.StrictMode>,\n  ),\n)\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './db'\n\nexport const worker = setupWorker(...(handlers as any))\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/src/mocks/db.ts",
    "content": "import { nanoid } from '@reduxjs/toolkit'\nimport { factory, primaryKey } from '@mswjs/data'\nimport faker from 'faker'\nimport { Post, postStatuses } from '../app/services/posts'\nimport { rest } from 'msw'\n\nconst db = factory({\n  post: {\n    id: primaryKey(String),\n    name: String,\n    title: String,\n    author: String,\n    content: String,\n    status: String,\n    created_at: String,\n    updated_at: String,\n  },\n})\n\nconst getRandomStatus = () =>\n  postStatuses[Math.floor(Math.random() * postStatuses.length)]\n\nconst createPostData = (): Post => {\n  const date = faker.date.past().toISOString()\n  return {\n    id: nanoid(),\n    title: faker.lorem.words(),\n    author: faker.name.findName(),\n    content: faker.lorem.paragraphs(),\n    status: getRandomStatus(),\n    created_at: date,\n    updated_at: date,\n  }\n}\n\n;[...new Array(50)].forEach((_) => db.post.create(createPostData()))\n\nexport const handlers = [\n  rest.get('/posts', (req, res, ctx) => {\n    const page = (req.url.searchParams.get('page') || 1) as number\n    const per_page = (req.url.searchParams.get('per_page') || 10) as number\n    const data = db.post.findMany({\n      take: per_page,\n      skip: Math.max(per_page * (page - 1), 0),\n    })\n\n    return res(\n      ctx.json({\n        data,\n        page,\n        total_pages: Math.ceil(db.post.count() / per_page),\n        total: db.post.count(),\n      }),\n    )\n  }),\n  ...db.post.toHandlers('rest'),\n] as const\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/prefetching-automatic-waterfall\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"./src/index.tsx\",\n  \"dependencies\": {\n    \"@chakra-ui/react\": \"2.10.7\",\n    \"@emotion/react\": \"^11.4.0\",\n    \"@emotion/styled\": \"^11.3.0\",\n    \"@mswjs/data\": \"^0.3.0\",\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"faker\": \"^5.5.3\",\n    \"framer-motion\": \"^2.9.5\",\n    \"msw\": \"^0.40.2\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-icons\": \"3.11.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-router-dom\": \"6.3.0\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/faker\": \"^5.5.5\",\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"prebuild\": \"rimraf dist/\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ],\n  \"msw\": {\n    \"workerDirectory\": \"public\"\n  }\n}\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <meta\n      name=\"description\"\n      content=\"Web site created using create-react-app\"\n    />\n    <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" />\n    <!--\n      manifest.json provides metadata used when your web app is installed on a\n      user's mobile device or desktop. See https://developers.google.com/web/fundamentals/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>You need to enable JavaScript to run this app.</noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query Demo\",\n  \"name\": \"RTK Query Demo\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/public/mockServiceWorker.js",
    "content": "/**\n * Mock Service Worker.\n * @see https://github.com/mswjs/msw\n * - Please do NOT modify this file.\n * - Please do NOT serve this file on production.\n */\n/* eslint-disable */\n/* tslint:disable */\n\nconst INTEGRITY_CHECKSUM = '82ef9b96d8393b6da34527d1d6e19187'\nconst bypassHeaderName = 'x-msw-bypass'\nconst activeClientIds = new Set()\n\nself.addEventListener('install', function () {\n  return self.skipWaiting()\n})\n\nself.addEventListener('activate', async function (event) {\n  return self.clients.claim()\n})\n\nself.addEventListener('message', async function (event) {\n  const clientId = event.source.id\n\n  if (!clientId || !self.clients) {\n    return\n  }\n\n  const client = await self.clients.get(clientId)\n\n  if (!client) {\n    return\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  switch (event.data) {\n    case 'KEEPALIVE_REQUEST': {\n      sendToClient(client, {\n        type: 'KEEPALIVE_RESPONSE',\n      })\n      break\n    }\n\n    case 'INTEGRITY_CHECK_REQUEST': {\n      sendToClient(client, {\n        type: 'INTEGRITY_CHECK_RESPONSE',\n        payload: INTEGRITY_CHECKSUM,\n      })\n      break\n    }\n\n    case 'MOCK_ACTIVATE': {\n      activeClientIds.add(clientId)\n\n      sendToClient(client, {\n        type: 'MOCKING_ENABLED',\n        payload: true,\n      })\n      break\n    }\n\n    case 'MOCK_DEACTIVATE': {\n      activeClientIds.delete(clientId)\n      break\n    }\n\n    case 'CLIENT_CLOSED': {\n      activeClientIds.delete(clientId)\n\n      const remainingClients = allClients.filter((client) => {\n        return client.id !== clientId\n      })\n\n      // Unregister itself when there are no more clients\n      if (remainingClients.length === 0) {\n        self.registration.unregister()\n      }\n\n      break\n    }\n  }\n})\n\n// Resolve the \"master\" client for the given event.\n// Client that issues a request doesn't necessarily equal the client\n// that registered the worker. It's with the latter the worker should\n// communicate with during the response resolving phase.\nasync function resolveMasterClient(event) {\n  const client = await self.clients.get(event.clientId)\n\n  if (client.frameType === 'top-level') {\n    return client\n  }\n\n  const allClients = await self.clients.matchAll()\n\n  return allClients\n    .filter((client) => {\n      // Get only those clients that are currently visible.\n      return client.visibilityState === 'visible'\n    })\n    .find((client) => {\n      // Find the client ID that's recorded in the\n      // set of clients that have registered the worker.\n      return activeClientIds.has(client.id)\n    })\n}\n\nasync function handleRequest(event, requestId) {\n  const client = await resolveMasterClient(event)\n  const response = await getResponse(event, client, requestId)\n\n  // Send back the response clone for the \"response:*\" life-cycle events.\n  // Ensure MSW is active and ready to handle the message, otherwise\n  // this message will pend indefinitely.\n  if (client && activeClientIds.has(client.id)) {\n    ;(async function () {\n      const clonedResponse = response.clone()\n      sendToClient(client, {\n        type: 'RESPONSE',\n        payload: {\n          requestId,\n          type: clonedResponse.type,\n          ok: clonedResponse.ok,\n          status: clonedResponse.status,\n          statusText: clonedResponse.statusText,\n          body:\n            clonedResponse.body === null ? null : await clonedResponse.text(),\n          headers: serializeHeaders(clonedResponse.headers),\n          redirected: clonedResponse.redirected,\n        },\n      })\n    })()\n  }\n\n  return response\n}\n\nasync function getResponse(event, client, requestId) {\n  const { request } = event\n  const requestClone = request.clone()\n  const getOriginalResponse = () => fetch(requestClone)\n\n  // Bypass mocking when the request client is not active.\n  if (!client) {\n    return getOriginalResponse()\n  }\n\n  // Bypass initial page load requests (i.e. static assets).\n  // The absence of the immediate/parent client in the map of the active clients\n  // means that MSW hasn't dispatched the \"MOCK_ACTIVATE\" event yet\n  // and is not ready to handle requests.\n  if (!activeClientIds.has(client.id)) {\n    return await getOriginalResponse()\n  }\n\n  // Bypass requests with the explicit bypass header\n  if (requestClone.headers.get(bypassHeaderName) === 'true') {\n    const cleanRequestHeaders = serializeHeaders(requestClone.headers)\n\n    // Remove the bypass header to comply with the CORS preflight check.\n    delete cleanRequestHeaders[bypassHeaderName]\n\n    const originalRequest = new Request(requestClone, {\n      headers: new Headers(cleanRequestHeaders),\n    })\n\n    return fetch(originalRequest)\n  }\n\n  // Send the request to the client-side MSW.\n  const reqHeaders = serializeHeaders(request.headers)\n  const body = await request.text()\n\n  const clientMessage = await sendToClient(client, {\n    type: 'REQUEST',\n    payload: {\n      id: requestId,\n      url: request.url,\n      method: request.method,\n      headers: reqHeaders,\n      cache: request.cache,\n      mode: request.mode,\n      credentials: request.credentials,\n      destination: request.destination,\n      integrity: request.integrity,\n      redirect: request.redirect,\n      referrer: request.referrer,\n      referrerPolicy: request.referrerPolicy,\n      body,\n      bodyUsed: request.bodyUsed,\n      keepalive: request.keepalive,\n    },\n  })\n\n  switch (clientMessage.type) {\n    case 'MOCK_SUCCESS': {\n      return delayPromise(\n        () => respondWithMock(clientMessage),\n        clientMessage.payload.delay,\n      )\n    }\n\n    case 'MOCK_NOT_FOUND': {\n      return getOriginalResponse()\n    }\n\n    case 'NETWORK_ERROR': {\n      const { name, message } = clientMessage.payload\n      const networkError = new Error(message)\n      networkError.name = name\n\n      // Rejecting a request Promise emulates a network error.\n      throw networkError\n    }\n\n    case 'INTERNAL_ERROR': {\n      const parsedBody = JSON.parse(clientMessage.payload.body)\n\n      console.error(\n        `\\\n[MSW] Request handler function for \"%s %s\" has thrown the following exception:\n\n${parsedBody.errorType}: ${parsedBody.message}\n(see more detailed error stack trace in the mocked response body)\n\nThis exception has been gracefully handled as a 500 response, however, it's strongly recommended to resolve this error.\nIf you wish to mock an error response, please refer to this guide: https://mswjs.io/docs/recipes/mocking-error-responses\\\n`,\n        request.method,\n        request.url,\n      )\n\n      return respondWithMock(clientMessage)\n    }\n  }\n\n  return getOriginalResponse()\n}\n\nself.addEventListener('fetch', function (event) {\n  const { request } = event\n\n  // Bypass navigation requests.\n  if (request.mode === 'navigate') {\n    return\n  }\n\n  // Opening the DevTools triggers the \"only-if-cached\" request\n  // that cannot be handled by the worker. Bypass such requests.\n  if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {\n    return\n  }\n\n  // Bypass all requests when there are no active clients.\n  // Prevents the self-unregistered worked from handling requests\n  // after it's been deleted (still remains active until the next reload).\n  if (activeClientIds.size === 0) {\n    return\n  }\n\n  const requestId = uuidv4()\n\n  return event.respondWith(\n    handleRequest(event, requestId).catch((error) => {\n      console.error(\n        '[MSW] Failed to mock a \"%s\" request to \"%s\": %s',\n        request.method,\n        request.url,\n        error,\n      )\n    }),\n  )\n})\n\nfunction serializeHeaders(headers) {\n  const reqHeaders = {}\n  headers.forEach((value, name) => {\n    reqHeaders[name] = reqHeaders[name]\n      ? [].concat(reqHeaders[name]).concat(value)\n      : value\n  })\n  return reqHeaders\n}\n\nfunction sendToClient(client, message) {\n  return new Promise((resolve, reject) => {\n    const channel = new MessageChannel()\n\n    channel.port1.onmessage = (event) => {\n      if (event.data && event.data.error) {\n        return reject(event.data.error)\n      }\n\n      resolve(event.data)\n    }\n\n    client.postMessage(JSON.stringify(message), [channel.port2])\n  })\n}\n\nfunction delayPromise(cb, duration) {\n  return new Promise((resolve) => {\n    setTimeout(() => resolve(cb()), duration)\n  })\n}\n\nfunction respondWithMock(clientMessage) {\n  return new Response(clientMessage.payload.body, {\n    ...clientMessage.payload,\n    headers: clientMessage.payload.headers,\n  })\n}\n\nfunction uuidv4() {\n  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {\n    const r = (Math.random() * 16) | 0\n    const v = c == 'x' ? r : (r & 0x3) | 0x8\n    return v.toString(16)\n  })\n}\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/src/App.tsx",
    "content": "import { Route, Routes } from 'react-router-dom'\nimport { PostsManager } from './features/posts/PostsManager'\n\nfunction App() {\n  return (\n    <Routes>\n      <Route path=\"*\" element={<PostsManager />} />\n    </Routes>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/src/app/services/posts.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const postStatuses = ['draft', 'published', 'pending_review'] as const\n\nexport interface Post {\n  id: string\n  title: string\n  author: string\n  content: string\n  status: (typeof postStatuses)[number]\n  created_at: string\n  updated_at: string\n}\n\ninterface ListResponse<T> {\n  page: number\n  per_page: number\n  total: number\n  total_pages: number\n  data: T[]\n}\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n  endpoints: (build) => ({\n    listPosts: build.query<ListResponse<Post>, number | void>({\n      query: (page = 1) => `posts?page=${page}`,\n    }),\n  }),\n})\n\nexport const { useListPostsQuery, usePrefetch } = api\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/src/features/posts/PostsManager.tsx",
    "content": "import { useCallback, useState, useEffect } from 'react'\nimport {\n  Badge,\n  Box,\n  Button,\n  Divider,\n  Flex,\n  Heading,\n  HStack,\n  Icon,\n  List,\n  ListIcon,\n  ListItem,\n  Spacer,\n  Stat,\n  StatLabel,\n  StatNumber,\n} from '@chakra-ui/react'\nimport { MdArrowBack, MdArrowForward, MdBook } from 'react-icons/md'\nimport { Post, usePrefetch, useListPostsQuery } from '../../app/services/posts'\n\nconst getColorForStatus = (status: Post['status']) => {\n  return status === 'draft'\n    ? 'gray'\n    : status === 'pending_review'\n      ? 'orange'\n      : 'green'\n}\n\nconst PostList = () => {\n  const [page, setPage] = useState(1)\n  const [hasPrefetchedAll, setHasPrefetchedAll] = useState(false)\n\n  const { data: posts, isLoading, isFetching } = useListPostsQuery(page)\n\n  const prefetchPage = usePrefetch('listPosts')\n\n  const prefetchNext = useCallback(() => {\n    prefetchPage(page + 1)\n  }, [prefetchPage, page])\n\n  useEffect(() => {\n    if (!hasPrefetchedAll) {\n      if (posts && posts.total_pages > 1) {\n        ;[...new Array(posts.total_pages)].forEach((page, index) => {\n          if (index >= posts.total_pages) return\n          prefetchPage(index + 1, { force: true })\n        })\n        setHasPrefetchedAll(true)\n      }\n    }\n  }, [posts, page, prefetchPage, hasPrefetchedAll])\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts?.data) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <Box>\n      <HStack spacing=\"14px\">\n        <Button\n          onClick={() => setPage((prev) => prev - 1)}\n          isLoading={isFetching}\n          disabled={page === 1}\n        >\n          <Icon as={MdArrowBack} />\n        </Button>\n        <Button\n          onClick={() => setPage((prev) => prev + 1)}\n          isLoading={isFetching}\n          disabled={page === posts.total_pages}\n          onMouseEnter={prefetchNext}\n        >\n          <Icon as={MdArrowForward} />\n        </Button>\n        <Box>{`${page} / ${posts.total_pages}`}</Box>\n      </HStack>\n      <List spacing={3} mt={6}>\n        {posts?.data.map(({ id, title, status }) => (\n          <ListItem key={id}>\n            <ListIcon as={MdBook} color=\"green.500\" /> {title}{' '}\n            <Badge\n              ml=\"1\"\n              fontSize=\"0.8em\"\n              colorScheme={getColorForStatus(status)}\n            >\n              {status}\n            </Badge>\n          </ListItem>\n        ))}\n      </List>\n    </Box>\n  )\n}\nexport const PostsCountStat = () => {\n  const { data: posts } = useListPostsQuery()\n\n  return (\n    <Stat>\n      <StatLabel>Total Posts</StatLabel>\n      <StatNumber>{`${posts?.total || 'NA'}`}</StatNumber>\n    </Stat>\n  )\n}\n\nexport const PostsManager = () => {\n  return (\n    <Box>\n      <Flex wrap=\"wrap\" bg=\"#011627\" p={4} color=\"white\">\n        <Box>\n          <Heading size=\"xl\">Manage Posts</Heading>\n        </Box>\n        <Spacer />\n        <Box>\n          <PostsCountStat />\n        </Box>\n      </Flex>\n      <Divider />\n      <Box p={4}>\n        <PostList />\n      </Box>\n    </Box>\n  )\n}\n\nexport default PostsManager\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/src/index.tsx",
    "content": "import React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport App from './App'\nimport { api } from './app/services/posts'\nimport { ChakraProvider } from '@chakra-ui/react'\n\nimport { BrowserRouter } from 'react-router-dom'\nimport { worker } from './mocks/browser'\nimport { ApiProvider } from '@reduxjs/toolkit/query/react'\n\n// Initialize the msw worker, wait for the service worker registration to resolve, then mount\nworker.start({ quiet: true }).then(() =>\n  ReactDOM.createRoot(document.getElementById('root') as HTMLElement).render(\n    <React.StrictMode>\n      <ApiProvider api={api}>\n        <ChakraProvider>\n          <BrowserRouter>\n            <App />\n          </BrowserRouter>\n        </ChakraProvider>\n      </ApiProvider>\n    </React.StrictMode>,\n  ),\n)\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/src/mocks/browser.ts",
    "content": "import { setupWorker } from 'msw'\nimport { handlers } from './db'\n\nexport const worker = setupWorker(...(handlers as any))\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/src/mocks/db.ts",
    "content": "import { nanoid } from '@reduxjs/toolkit'\nimport { factory, primaryKey } from '@mswjs/data'\nimport faker from 'faker'\nimport { Post, postStatuses } from '../app/services/posts'\nimport { rest } from 'msw'\n\nconst db = factory({\n  post: {\n    id: primaryKey(String),\n    name: String,\n    title: String,\n    author: String,\n    content: String,\n    status: String,\n    created_at: String,\n    updated_at: String,\n  },\n})\n\nconst getRandomStatus = () =>\n  postStatuses[Math.floor(Math.random() * postStatuses.length)]\n\nconst createPostData = (): Post => {\n  const date = faker.date.past().toISOString()\n  return {\n    id: nanoid(),\n    title: faker.lorem.words(),\n    author: faker.name.findName(),\n    content: faker.lorem.paragraphs(),\n    status: getRandomStatus(),\n    created_at: date,\n    updated_at: date,\n  }\n}\n\n;[...new Array(50)].forEach((_) => db.post.create(createPostData()))\n\nexport const handlers = [\n  rest.get('/posts', (req, res, ctx) => {\n    const page = (req.url.searchParams.get('page') || 1) as number\n    const per_page = (req.url.searchParams.get('per_page') || 10) as number\n    const data = db.post.findMany({\n      take: per_page,\n      skip: Math.max(per_page * (page - 1), 0),\n    })\n\n    return res(\n      ctx.json({\n        data,\n        page,\n        total_pages: Math.ceil(db.post.count() / per_page),\n        total: db.post.count(),\n      }),\n    )\n  }),\n  ...db.post.toHandlers('rest'),\n] as const\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/prefetching-automatic-waterfall/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/query/react/with-apiprovider/package.json",
    "content": "{\n  \"name\": \"@examples-query-react/with-apiprovider\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"keywords\": [],\n  \"main\": \"src/index.tsx\",\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"^1.6.0-rc.1\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"react-scripts\": \"5.0.1\"\n  },\n  \"devDependencies\": {\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"eslintConfig\": {\n    \"extends\": [\n      \"react-app\"\n    ],\n    \"rules\": {\n      \"react/react-in-jsx-scope\": \"off\"\n    }\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\"\n  },\n  \"browserslist\": [\n    \">0.2%\",\n    \"not dead\",\n    \"not ie <= 11\",\n    \"not op_mini all\"\n  ]\n}\n"
  },
  {
    "path": "examples/query/react/with-apiprovider/public/index.html",
    "content": "<!doctype html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\" />\n    <meta\n      name=\"viewport\"\n      content=\"width=device-width, initial-scale=1, shrink-to-fit=no\"\n    />\n    <meta name=\"theme-color\" content=\"#000000\" />\n    <!--\n      manifest.json provides metadata used when your web app is added to the\n      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" />\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\" />\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n\n  <body>\n    <noscript> You need to enable JavaScript to run this app. </noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "examples/query/react/with-apiprovider/public/manifest.json",
    "content": "{\n  \"short_name\": \"RTK Query ApiProvider Example\",\n  \"name\": \"ApiProvider Example\",\n  \"start_url\": \".\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "examples/query/react/with-apiprovider/src/App.tsx",
    "content": "import {\n  createApi,\n  fetchBaseQuery,\n  ApiProvider,\n} from '@reduxjs/toolkit/query/react'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2' }),\n  endpoints: (build) => ({\n    getPokemonByName: build.query({\n      query: (name: string) => `pokemon/${name}`,\n    }),\n  }),\n})\n\nfunction Pokemon() {\n  const { data, refetch, isFetching } =\n    api.useGetPokemonByNameQuery('bulbasaur')\n\n  return (\n    <div>\n      <button onClick={refetch}>Refetch</button>\n      <div>\n        <b>isFetching?</b>: {String(isFetching)}\n      </div>\n      <hr />\n      <pre>{JSON.stringify(data, null, 2)}</pre>\n    </div>\n  )\n}\n\nexport default function App() {\n  return (\n    <ApiProvider api={api}>\n      <Pokemon />\n    </ApiProvider>\n  )\n}\n"
  },
  {
    "path": "examples/query/react/with-apiprovider/src/index.tsx",
    "content": "import ReactDOM from 'react-dom/client'\nimport App from './App'\n\nconst rootElement = document.getElementById('root')\n\nconst reactRoot = ReactDOM.createRoot(rootElement as HTMLElement)\n\nreactRoot.render(<App />)\n"
  },
  {
    "path": "examples/query/react/with-apiprovider/src/react-app-env.d.ts",
    "content": "/// <reference types=\"react-scripts\" />\n"
  },
  {
    "path": "examples/query/react/with-apiprovider/tsconfig.json",
    "content": "{\n  \"include\": [\"./src/**/*\"],\n  \"compilerOptions\": {\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"lib\": [\"dom\", \"es2015\"],\n    \"jsx\": \"react-jsx\",\n    \"target\": \"es5\",\n    \"allowJs\": true,\n    \"skipLibCheck\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"module\": \"esnext\",\n    \"moduleResolution\": \"node\",\n    \"resolveJsonModule\": true,\n    \"isolatedModules\": true,\n    \"noEmit\": true\n  }\n}\n"
  },
  {
    "path": "examples/type-portability/bundler/package.json",
    "content": "{\n  \"name\": \"@examples-type-portability/bundler\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"testing type portability for moduleResolution Bundler\",\n  \"keywords\": [],\n  \"main\": \"src/index.tsx\",\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"workspace:^\",\n    \"react\": \"^19.2.4\",\n    \"react-dom\": \"^19.2.4\",\n    \"react-redux\": \"^9.2.0\",\n    \"react-router-dom\": \"^7.13.0\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^19.2.13\",\n    \"@types/react-dom\": \"^19.2.3\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\",\n    \"vite\": \"^7.3.1\"\n  },\n  \"scripts\": {\n    \"clean\": \"rimraf dist\",\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"test\": \"yarn clean && tsc -p tsconfig.json\"\n  }\n}\n"
  },
  {
    "path": "examples/type-portability/bundler/src/App.tsx",
    "content": "import { Link, Route, Routes } from 'react-router-dom'\nimport { Lazy } from './features/bundleSplitting'\nimport { CounterList } from './features/counter/CounterList'\nimport { PollingToggles } from './features/polling/PollingToggles'\nimport { PostsManager } from './features/posts/PostsManager'\nimport { TimeList } from './features/time/TimeList'\n\nexport function App() {\n  return (\n    <div className=\"App\">\n      <div className=\"row\">\n        <div className=\"column column1\">\n          <span>\n            <Link to=\"/\">Times</Link> | <Link to=\"/posts\">Posts</Link> |{' '}\n            <Link to=\"/counters\">Counter</Link> |{' '}\n            <Link to=\"/bundleSplitting\">Bundle Splitting</Link>\n          </span>\n        </div>\n        <div className=\"column column1\">\n          <PollingToggles />\n        </div>\n      </div>\n      <div />\n      <div>\n        <Routes>\n          <Route path=\"/\" element={<TimeList />} />\n          <Route path=\"/counters\" element={<CounterList />} />\n          <Route path=\"/posts/*\" element={<PostsManager />} />\n          <Route path=\"/bundleSplitting\" element={<Lazy />} />\n        </Routes>\n      </div>\n    </div>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/type-portability/bundler/src/app/customModule.ts",
    "content": "import type {\n  Api,\n  BaseQueryFn,\n  CoreModule,\n  EndpointDefinitions,\n  Module,\n} from '@reduxjs/toolkit/query'\nimport { buildCreateApi, coreModule } from '@reduxjs/toolkit/query'\n\nexport const customModuleName = Symbol('customModule')\nexport type CustomModule = typeof customModuleName\n\n// If we remove this, We should get a TypeScript error.\ndeclare module '@reduxjs/toolkit/query' {\n  export interface ApiModules<\n    BaseQuery extends BaseQueryFn,\n    Definitions extends EndpointDefinitions,\n    ReducerPath extends string,\n    TagTypes extends string,\n  > {\n    [customModuleName]: {\n      endpoints: {\n        [K in keyof Definitions]: {\n          myEndpointProperty: string\n        }\n      }\n    }\n  }\n}\n\nexport const myModule = (): Module<CustomModule> => ({\n  name: customModuleName,\n  init(api, options, context) {\n    // initialize stuff here if you need to\n\n    return {\n      injectEndpoint(endpoint, definition) {\n        const anyApi = api as any as Api<\n          any,\n          Record<string, any>,\n          string,\n          string,\n          CustomModule | CoreModule\n        >\n        anyApi.endpoints[endpoint].myEndpointProperty = 'test'\n      },\n    }\n  },\n})\n\nexport const myCreateApi = buildCreateApi(coreModule(), myModule())\n"
  },
  {
    "path": "examples/type-portability/bundler/src/app/dynamicMiddleware.ts",
    "content": "import { createDynamicMiddleware } from '@reduxjs/toolkit'\n\nexport const dynamicMiddleware = createDynamicMiddleware()\n\nexport const { addMiddleware, instanceId, middleware, withMiddleware } =\n  dynamicMiddleware\n\nexport const { withTypes, match, type } = withMiddleware\n\nexport const { withTypes: _withTypes } = addMiddleware\n"
  },
  {
    "path": "examples/type-portability/bundler/src/app/dynamicReactMiddleware.ts",
    "content": "import { createDynamicMiddleware } from '@reduxjs/toolkit/react'\nimport { listenerMiddleware } from './listenerMiddleware'\n\nexport const dynamicReactMiddleware = createDynamicMiddleware()\n\nexport const {\n  addMiddleware,\n  createDispatchWithMiddlewareHook,\n  createDispatchWithMiddlewareHookFactory,\n  instanceId,\n  middleware,\n  withMiddleware,\n} = dynamicReactMiddleware\n\nexport const { withTypes } = addMiddleware\n\nexport const useDispatchWithMiddleware = createDispatchWithMiddlewareHook(\n  listenerMiddleware.middleware,\n)\n"
  },
  {
    "path": "examples/type-portability/bundler/src/app/hooks.ts",
    "content": "import { useDispatch, useSelector, useStore } from 'react-redux'\nimport type { AppDispatch, AppStore, RootState } from './store'\n\nexport const useAppDispatch = useDispatch.withTypes<AppDispatch>()\nexport const useAppSelector = useSelector.withTypes<RootState>()\nexport const useAppStore = useStore.withTypes<AppStore>()\n"
  },
  {
    "path": "examples/type-portability/bundler/src/app/listenerMiddleware.ts",
    "content": "import { createListenerMiddleware } from '@reduxjs/toolkit'\n\nexport const listenerMiddleware = createListenerMiddleware()\n\nexport const { clearListeners, middleware, startListening, stopListening } =\n  listenerMiddleware\n\nexport const { withTypes } = startListening\n\nexport const { withTypes: _withTypes } = stopListening\n"
  },
  {
    "path": "examples/type-portability/bundler/src/app/services/api.ts",
    "content": "import {\n  createApi,\n  fakeBaseQuery,\n  fetchBaseQuery,\n  retry,\n} from '@reduxjs/toolkit/query/react'\nimport type { RootState } from '../store'\n\nexport const baseQuery = fetchBaseQuery({\n  baseUrl: '/',\n  prepareHeaders: (headers, { getState }) => {\n    const { token } = (getState() as RootState).auth\n\n    if (token) {\n      headers.set('authentication', `Bearer ${token}`)\n    }\n\n    return headers\n  },\n})\n\nexport const baseQueryWithRetry = retry(baseQuery, { maxRetries: 6 })\n\nexport const apiSlice = createApi({\n  reducerPath: 'api',\n  baseQuery: baseQueryWithRetry,\n  tagTypes: ['Time', 'Posts', 'Counter'],\n  endpoints: () => ({}),\n})\n\nexport const enhancedApi = apiSlice.enhanceEndpoints({\n  endpoints: () => ({\n    getPost: () => 'test',\n  }),\n})\n\nexport const emptyApi = createApi({\n  baseQuery: fakeBaseQuery(),\n  endpoints: () => ({}),\n})\n\nexport const {\n  endpoints: _endpoints,\n  enhanceEndpoints: _enhanceEndpoints,\n  injectEndpoints: _injectEndpoints,\n  internalActions: _internalActions,\n  middleware: _middleware,\n  reducer: _reducer,\n  reducerPath: _reducerPath,\n  usePrefetch: _usePrefetch,\n  util: _util,\n} = apiSlice\n\nexport const {\n  endpoints,\n  enhanceEndpoints,\n  injectEndpoints,\n  internalActions,\n  middleware,\n  reducer,\n  reducerPath,\n  usePrefetch,\n  util,\n} = enhancedApi\n\nexport const {\n  cacheEntriesUpserted,\n  internal_getRTKQSubscriptions,\n  middlewareRegistered,\n  onFocus,\n  onFocusLost,\n  onOffline,\n  onOnline,\n  queryResultPatched,\n  removeMutationResult,\n  removeQueryResult,\n  resetApiState: _resetApiState,\n  subscriptionsUpdated,\n  unsubscribeQueryResult,\n  updateProvidedBy,\n  updateSubscriptionOptions,\n} = internalActions\n\nexport const { match, type } = updateSubscriptionOptions\n\nexport const {\n  getRunningMutationsThunk,\n  getRunningMutationThunk,\n  getRunningQueriesThunk,\n  getRunningQueryThunk,\n  invalidateTags,\n  patchQueryData,\n  prefetch,\n  resetApiState,\n  selectCachedArgsForQuery,\n  selectInvalidatedBy,\n  updateQueryData,\n  upsertQueryData,\n  upsertQueryEntries,\n} = util\n\nexport const { match: _match, type: _type } = invalidateTags\n\nexport const { match: __match } = upsertQueryEntries\n"
  },
  {
    "path": "examples/type-portability/bundler/src/app/services/counter.ts",
    "content": "import { apiSlice } from './api'\n\nexport interface CountResponse {\n  count: number\n}\n\nexport const counterApi = apiSlice.injectEndpoints({\n  endpoints: (build) => ({\n    getCount: build.query<CountResponse, void>({\n      query: () => 'count',\n      providesTags: ['Counter'],\n    }),\n    incrementCount: build.mutation<CountResponse, number>({\n      query(amount) {\n        return {\n          url: `increment`,\n          method: 'PUT',\n          body: { amount },\n        }\n      },\n      invalidatesTags: ['Counter'],\n    }),\n    decrementCount: build.mutation<CountResponse, number>({\n      query(amount) {\n        return {\n          url: `decrement`,\n          method: 'PUT',\n          body: { amount },\n        }\n      },\n      invalidatesTags: ['Counter'],\n    }),\n  }),\n})\n\nexport const {\n  useDecrementCountMutation,\n  useGetCountQuery,\n  useIncrementCountMutation,\n  useLazyGetCountQuery,\n  endpoints,\n  enhanceEndpoints,\n  injectEndpoints,\n  internalActions,\n  middleware,\n  reducer,\n  reducerPath,\n  usePrefetch,\n  util,\n} = counterApi\n\nexport const { decrementCount, getCount, incrementCount } = endpoints\n\nexport const {\n  cacheEntriesUpserted,\n  internal_getRTKQSubscriptions,\n  middlewareRegistered,\n  onFocus,\n  onFocusLost,\n  onOffline,\n  onOnline,\n  queryResultPatched,\n  removeMutationResult,\n  removeQueryResult,\n  resetApiState: _resetApiState,\n  subscriptionsUpdated,\n  unsubscribeQueryResult,\n  updateProvidedBy,\n  updateSubscriptionOptions,\n} = internalActions\n\nexport const { match, type } = cacheEntriesUpserted\n\nexport const { match: _match, type: _type } = updateSubscriptionOptions\n\nexport const {\n  getRunningMutationsThunk,\n  getRunningMutationThunk,\n  getRunningQueriesThunk,\n  getRunningQueryThunk,\n  invalidateTags,\n  patchQueryData,\n  prefetch,\n  resetApiState,\n  selectCachedArgsForQuery,\n  selectInvalidatedBy,\n  updateQueryData,\n  upsertQueryData,\n  upsertQueryEntries,\n} = util\n\nexport const { match: __match, type: __type } = invalidateTags\n\nexport const { match: ___match } = upsertQueryEntries\n"
  },
  {
    "path": "examples/type-portability/bundler/src/app/services/post.ts",
    "content": "import { apiSlice } from './api'\nimport type { Post } from './posts'\n\nexport const postApi = apiSlice.injectEndpoints({\n  endpoints: (build) => ({\n    addPost: build.mutation<Post, Partial<Post>>({\n      query(body) {\n        return {\n          url: `posts`,\n          method: 'POST',\n          body,\n        }\n      },\n      invalidatesTags: ['Posts'],\n    }),\n    getPost: build.query<Post, number>({\n      query: (id) => `posts/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Posts', id }],\n    }),\n    updatePost: build.mutation<Post, Partial<Post>>({\n      query(data) {\n        const { id, ...body } = data\n        return {\n          url: `posts/${id}`,\n          method: 'PUT',\n          body,\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n    deletePost: build.mutation<{ success: boolean; id: number }, number>({\n      query(id) {\n        return {\n          url: `posts/${id}`,\n          method: 'DELETE',\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n  }),\n})\n\nexport const {\n  endpoints,\n  enhanceEndpoints,\n  injectEndpoints,\n  internalActions,\n  middleware,\n  reducer,\n  reducerPath,\n  useAddPostMutation,\n  useDeletePostMutation,\n  useGetPostQuery,\n  useLazyGetPostQuery,\n  usePrefetch,\n  useUpdatePostMutation,\n  util,\n} = postApi\n\nexport const { addPost, deletePost, getPost, updatePost } = endpoints\n\nexport const {\n  Types,\n  initiate,\n  matchFulfilled,\n  matchPending,\n  matchRejected,\n  name,\n  select,\n  useMutation,\n} = addPost\n\nexport const {\n  BaseQuery,\n  MutationDefinition,\n  QueryArg,\n  RawResultType,\n  ReducerPath,\n  ResultType,\n  TagTypes,\n} = Types\n\nexport const {\n  argSchema,\n  catchSchemaFailure,\n  errorResponseSchema,\n  extraOptions,\n  invalidatesTags,\n  metaSchema,\n  onCacheEntryAdded,\n  onQueryStarted,\n  onSchemaFailure,\n  providesTags,\n  query,\n  queryFn,\n  rawErrorResponseSchema,\n  rawResponseSchema,\n  responseSchema,\n  skipSchemaValidation,\n  structuralSharing,\n  transformErrorResponse,\n  transformResponse,\n  type: __type,\n  Types: _Types,\n} = MutationDefinition\n\nexport const { fetched_at, id, name: _name } = QueryArg\n\nexport const {\n  cacheEntriesUpserted,\n  internal_getRTKQSubscriptions,\n  middlewareRegistered,\n  onFocus,\n  onFocusLost,\n  onOffline,\n  onOnline,\n  queryResultPatched,\n  removeMutationResult,\n  removeQueryResult,\n  resetApiState: _resetApiState,\n  subscriptionsUpdated,\n  unsubscribeQueryResult,\n  updateProvidedBy,\n  updateSubscriptionOptions,\n} = internalActions\n\nexport const { match, type } = cacheEntriesUpserted\n\nexport const { match: _match, type: _type } = updateSubscriptionOptions\n\nexport const {\n  getRunningMutationsThunk,\n  getRunningMutationThunk,\n  getRunningQueriesThunk,\n  getRunningQueryThunk,\n  invalidateTags,\n  patchQueryData,\n  prefetch,\n  resetApiState,\n  selectCachedArgsForQuery,\n  selectInvalidatedBy,\n  updateQueryData,\n  upsertQueryData,\n  upsertQueryEntries,\n} = util\n\nexport const { match: __match } = upsertQueryEntries\n\nexport const { match: ___match, type: ___type } = invalidateTags\n"
  },
  {
    "path": "examples/type-portability/bundler/src/app/services/posts.ts",
    "content": "import { retry } from '@reduxjs/toolkit/query/react'\nimport { apiSlice } from './api'\n\nexport interface Post {\n  id: number\n  name: string\n  fetched_at: string\n}\n\nexport type PostsResponse = Post[]\n\nexport interface User {\n  first_name: string\n  last_name: string\n  email: string\n  phone: string\n}\n\nexport const postsApi = apiSlice.injectEndpoints({\n  endpoints: (build) => ({\n    login: build.mutation<{ token: string; user: User }, any>({\n      query: (credentials: any) => ({\n        url: 'login',\n        method: 'POST',\n        body: credentials,\n      }),\n      extraOptions: {\n        backoff: () => {\n          // We intentionally error once on login, and this breaks out of retrying. The next login attempt will succeed.\n          retry.fail({ fake: 'error' })\n        },\n      },\n    }),\n    getPosts: build.query<PostsResponse, void>({\n      query: () => ({ url: 'posts' }),\n      providesTags: (result = []) => [\n        ...result.map(({ id }) => ({ type: 'Posts', id }) as const),\n        { type: 'Posts' as const, id: 'LIST' },\n      ],\n    }),\n    addPost: build.mutation<Post, Partial<Post>>({\n      query: (body) => ({\n        url: `posts`,\n        method: 'POST',\n        body,\n      }),\n      invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n    }),\n    getPost: build.query<Post, number>({\n      query: (id) => `posts/${id}`,\n      providesTags: (_post, _err, id) => [{ type: 'Posts', id }],\n    }),\n    updatePost: build.mutation<Post, Partial<Post>>({\n      query(data) {\n        const { id, ...body } = data\n        return {\n          url: `posts/${id}`,\n          method: 'PUT',\n          body,\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n    deletePost: build.mutation<{ success: boolean; id: number }, number>({\n      query(id) {\n        return {\n          url: `posts/${id}`,\n          method: 'DELETE',\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n    getErrorProne: build.query<{ success: boolean }, void>({\n      query: () => 'error-prone',\n    }),\n    getInfinitePosts: build.infiniteQuery<PostsResponse, void, number>({\n      queryFn: ({ pageParam = 0 }) => ({\n        data: [],\n      }),\n      infiniteQueryOptions: {\n        initialPageParam: 0,\n        getNextPageParam: (lastPage) =>\n          lastPage.length === 0 ? undefined : lastPage[lastPage.length - 1].id,\n      },\n    }),\n  }),\n})\n\nexport const {\n  useAddPostMutation,\n  useDeletePostMutation,\n  useGetPostQuery,\n  useGetPostsQuery,\n  useLoginMutation,\n  useUpdatePostMutation,\n  useGetErrorProneQuery,\n  useLazyGetErrorProneQuery,\n  useLazyGetPostQuery,\n  useLazyGetPostsQuery,\n  useGetInfinitePostsInfiniteQuery,\n  endpoints,\n  enhanceEndpoints,\n  injectEndpoints,\n  internalActions,\n  middleware,\n  reducer,\n  reducerPath,\n  usePrefetch,\n  util,\n} = postsApi\n\nexport const {\n  addPost,\n  deletePost,\n  getErrorProne,\n  getPost,\n  getPosts,\n  login,\n  updatePost,\n  getInfinitePosts,\n} = endpoints\n\nexport const {\n  Types,\n  initiate,\n  matchFulfilled,\n  matchPending,\n  matchRejected,\n  name,\n  select,\n  useMutation,\n} = addPost\n\nexport const {\n  Types: _Types,\n  initiate: _initiate,\n  matchFulfilled: _matchFulfilled,\n  matchPending: _matchPending,\n  matchRejected: _matchRejected,\n  name: _name,\n  select: _select,\n  useMutation: _useMutation,\n} = deletePost\n\nexport const {\n  Types: __Types,\n  initiate: __initiate,\n  matchFulfilled: __matchFulfilled,\n  matchPending: __matchPending,\n  matchRejected: __matchRejected,\n  name: __name,\n  select: __select,\n  useQueryState,\n  useLazyQuery,\n  useLazyQuerySubscription,\n  useQuery,\n  useQuerySubscription,\n} = getErrorProne\n\nexport const {\n  Types: ___Types,\n  initiate: ___initiate,\n  matchFulfilled: ___matchFulfilled,\n  matchPending: ___matchPending,\n  matchRejected: ___matchRejected,\n  name: ___name,\n  select: ___select,\n  useQueryState: ___useQueryState,\n  useLazyQuery: ___useLazyQuery,\n  useLazyQuerySubscription: ___useLazyQuerySubscription,\n  useQuery: ___useQuery,\n  useQuerySubscription: ___useQuerySubscription,\n} = getPost\n\nexport const {\n  Types: ____Types,\n  initiate: ____initiate,\n  matchFulfilled: ____matchFulfilled,\n  matchPending: ____matchPending,\n  matchRejected: ____matchRejected,\n  name: ____name,\n  select: ____select,\n  useMutation: ____useMutation,\n} = login\n\nexport const {\n  Types: _____Types,\n  initiate: _____initiate,\n  matchFulfilled: _____matchFulfilled,\n  matchPending: _____matchPending,\n  matchRejected: _____matchRejected,\n  name: _____name,\n  select: _____select,\n  useMutation: _____useMutation,\n} = updatePost\n\nexport const {\n  Types: ______Types,\n  initiate: ______initiate,\n  matchFulfilled: ______matchFulfilled,\n  matchPending: ______matchPending,\n  matchRejected: ______matchRejected,\n  name: ______name,\n  select: ______select,\n  useInfiniteQueryState: ______useQueryState,\n  useInfiniteQuery: ______useQuery,\n  useInfiniteQuerySubscription: ______useQuerySubscription,\n} = getInfinitePosts\n\nexport const {\n  cacheEntriesUpserted,\n  internal_getRTKQSubscriptions,\n  middlewareRegistered,\n  onFocus,\n  onFocusLost,\n  onOffline,\n  onOnline,\n  queryResultPatched,\n  removeMutationResult,\n  removeQueryResult,\n  resetApiState: _resetApiState,\n  subscriptionsUpdated,\n  unsubscribeQueryResult,\n  updateProvidedBy,\n  updateSubscriptionOptions,\n} = internalActions\n\nexport const {\n  getRunningMutationsThunk,\n  getRunningMutationThunk,\n  getRunningQueriesThunk,\n  getRunningQueryThunk,\n  invalidateTags,\n  patchQueryData,\n  prefetch,\n  resetApiState,\n  selectCachedArgsForQuery,\n  selectInvalidatedBy,\n  updateQueryData,\n  upsertQueryData,\n  upsertQueryEntries,\n} = util\n"
  },
  {
    "path": "examples/type-portability/bundler/src/app/services/times.ts",
    "content": "import { apiSlice } from './api'\n\nexport interface TimeResponse {\n  time: string\n}\n\nexport const timeApi = apiSlice.injectEndpoints({\n  endpoints: (build) => ({\n    getTime: build.query<TimeResponse, string>({\n      query: (id) => `time/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Time', id }],\n    }),\n  }),\n})\n\nexport const {\n  useLazyGetTimeQuery,\n  usePrefetch: usePrefetchTime,\n  useGetTimeQuery,\n  endpoints,\n  enhanceEndpoints,\n  injectEndpoints,\n  internalActions,\n  middleware,\n  reducer,\n  reducerPath,\n  util,\n} = timeApi\n\nexport const { getTime } = endpoints\n\nexport const {\n  Types,\n  initiate,\n  matchFulfilled,\n  matchPending,\n  matchRejected,\n  name,\n  select,\n  useQuery,\n  useLazyQuery,\n  useQuerySubscription,\n  useQueryState,\n  useLazyQuerySubscription,\n} = getTime\n\nexport const {\n  cacheEntriesUpserted,\n  internal_getRTKQSubscriptions,\n  middlewareRegistered,\n  onFocus,\n  onFocusLost,\n  onOffline,\n  onOnline,\n  queryResultPatched,\n  removeMutationResult,\n  removeQueryResult,\n  resetApiState: _resetApiState,\n  subscriptionsUpdated,\n  unsubscribeQueryResult,\n  updateProvidedBy,\n  updateSubscriptionOptions,\n} = internalActions\n\nexport const {\n  getRunningMutationsThunk,\n  getRunningMutationThunk,\n  getRunningQueriesThunk,\n  getRunningQueryThunk,\n  invalidateTags,\n  patchQueryData,\n  prefetch,\n  resetApiState,\n  selectCachedArgsForQuery,\n  selectInvalidatedBy,\n  updateQueryData,\n  upsertQueryData,\n  upsertQueryEntries,\n} = util\n"
  },
  {
    "path": "examples/type-portability/bundler/src/app/store.ts",
    "content": "import { combineSlices, configureStore } from '@reduxjs/toolkit'\nimport { setupListeners } from '@reduxjs/toolkit/query'\nimport { authSlice } from '../features/auth/authSlice'\nimport { pollingSlice } from '../features/polling/pollingSlice'\nimport { dynamicMiddleware } from './dynamicMiddleware'\nimport { dynamicReactMiddleware } from './dynamicReactMiddleware'\nimport { listenerMiddleware } from './listenerMiddleware'\nimport { apiSlice } from './services/api'\n\nexport const rootReducer = combineSlices(pollingSlice, authSlice, apiSlice)\n\nexport const { inject, selector, withLazyLoadedSlices } = rootReducer\n\nexport const { original } = selector\n\nexport type RootState = ReturnType<typeof rootReducer>\n\nexport const setupStore = (preloadedState?: Partial<RootState>) =>\n  configureStore({\n    reducer: rootReducer,\n    middleware: (getDefaultMiddleware) =>\n      getDefaultMiddleware()\n        .prepend(listenerMiddleware.middleware)\n        .prepend(dynamicMiddleware.middleware)\n        .prepend(dynamicReactMiddleware.middleware)\n        .concat(apiSlice.middleware),\n    preloadedState,\n    enhancers: (getDefaultEnhancers) => getDefaultEnhancers(),\n  })\n\nexport const store = setupStore()\n\nsetupListeners(store.dispatch)\n\nexport const { dispatch, getState, replaceReducer, subscribe } = store\n\nexport type AppStore = typeof store\nexport type AppDispatch = typeof store.dispatch\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/auth/authSlice.ts",
    "content": "import { createSlice } from '@reduxjs/toolkit'\nimport type { User } from '../../app/services/posts'\nimport { postsApi } from '../../app/services/posts'\n\nexport const initialState = {\n  user: null,\n  token: null,\n  isAuthenticated: false,\n} as { user: null | User; token: string | null; isAuthenticated: boolean }\n\nexport const authSlice = createSlice({\n  name: 'auth',\n  initialState,\n  reducers: {\n    logout: () => initialState,\n  },\n  extraReducers: (builder) => {\n    builder\n      .addMatcher(postsApi.endpoints.login.matchPending, (state, action) => {\n        console.log('pending', action)\n      })\n      .addMatcher(postsApi.endpoints.login.matchFulfilled, (state, action) => {\n        console.log('fulfilled', action)\n        state.user = action.payload.user\n        state.token = action.payload.token\n        state.isAuthenticated = true\n      })\n      .addMatcher(postsApi.endpoints.login.matchRejected, (state, action) => {\n        console.log('rejected', action)\n      })\n  },\n  selectors: {\n    selectIsAuthenticated: (authState) => authState.isAuthenticated,\n  },\n})\n\nexport const {\n  actions,\n  caseReducers,\n  getInitialState,\n  getSelectors,\n  injectInto,\n  name,\n  reducer,\n  reducerPath,\n  selectSlice,\n  selectors,\n} = authSlice\n\nexport const { selectIsAuthenticated } = getSelectors(selectSlice)\n\nexport const { unwrapped } = selectIsAuthenticated\n\nexport const { logout: _logout } = caseReducers\n\nexport const { logout } = authSlice.actions\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/bundleSplitting/Lazy.tsx",
    "content": "import { Suspense } from 'react'\nimport { PostsList } from '.'\n\nexport const Lazy = () => {\n  return (\n    <Suspense fallback={<>loading...</>}>\n      <PostsList />\n    </Suspense>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/bundleSplitting/Post.tsx",
    "content": "// import the file that injects \"post\" to make sure it has been loaded\nimport { postApi } from '../../app/services/post'\n\nexport function assert(\n  condition: any,\n  msg = 'Generic Assertion',\n): asserts condition {\n  if (!condition) {\n    throw new Error(`Assertion failed: ${msg}`)\n  }\n}\n\nexport const Post = ({ id }: { id: number }) => {\n  assert(postApi.endpoints.getPost?.useQuery, 'Endpoint `getPost` not loaded!')\n\n  const { data, error } = postApi.endpoints.getPost.useQuery(id)\n\n  return error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <h1>{data.name}</h1>\n  )\n}\n\nexport default Post\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/bundleSplitting/PostsList.tsx",
    "content": "import { useState } from 'react'\nimport { Post } from '.'\nimport { postsApi } from '../../app/services/posts'\n\nexport const PostsList = () => {\n  const { data, error } = postsApi.endpoints.getPosts.useQuery()\n  const [selected, select] = useState<number | undefined>()\n\n  return error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <>\n      {selected && <Post id={selected} />}\n      <ul>\n        {data.map((post) => (\n          <li key={post.id}>\n            <button onClick={() => select(post.id)}>{post.name}</button>\n          </li>\n        ))}\n      </ul>\n    </>\n  )\n}\n\nexport default PostsList\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/bundleSplitting/index.ts",
    "content": "import { lazy } from 'react'\n\nexport const PostsList = lazy(() => import('./PostsList'))\n\nexport const Post = lazy(() => import('./Post'))\n\nexport { Lazy } from './Lazy'\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/common/Container.tsx",
    "content": "import type { FC, ReactNode } from 'react'\n\nexport const Container: FC<{ children: ReactNode }> = ({ children }) => (\n  <div style={{ textAlign: 'center', padding: 50, margin: '0 auto' }}>\n    {children}\n  </div>\n)\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/counter/Counter.tsx",
    "content": "import { useState } from 'react'\nimport {\n  useDecrementCountMutation,\n  useGetCountQuery,\n  useIncrementCountMutation,\n} from '../../app/services/counter'\n\nexport function Counter({\n  id,\n  onRemove,\n}: {\n  id?: string\n  onRemove?: () => void\n}) {\n  const [pollingInterval, setPollingInterval] = useState(10_000)\n  const { data } = useGetCountQuery(undefined, { pollingInterval })\n  const [increment] = useIncrementCountMutation()\n\n  const [decrement] = useDecrementCountMutation()\n\n  return (\n    <div>\n      <div>\n        <button aria-label=\"Increment value\" onClick={() => increment(1)}>\n          +\n        </button>\n        <span>{data?.count || 0}</span>\n        <button aria-label=\"Decrement value\" onClick={() => decrement(1)}>\n          -\n        </button>\n        <input\n          type=\"number\"\n          name=\"pollingInterval\"\n          value={pollingInterval}\n          onChange={({ target: { valueAsNumber } }) =>\n            setPollingInterval(valueAsNumber)\n          }\n        />\n        {onRemove && <button onClick={onRemove}>Remove {id}</button>}\n      </div>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/counter/CounterList.tsx",
    "content": "import { nanoid } from '@reduxjs/toolkit'\nimport { useState } from 'react'\nimport { Container } from '../common/Container'\nimport { Counter } from './Counter'\n\nexport const CounterList = () => {\n  const [counters, setCounters] = useState<string[]>([])\n\n  if (!counters.length) {\n    return (\n      <Container>\n        <div>No counters, why don't you add one?</div>\n        <div>\n          <button onClick={() => setCounters((prev) => [...prev, nanoid()])}>\n            Add counter\n          </button>\n        </div>\n      </Container>\n    )\n  }\n\n  return (\n    <Container>\n      <div>\n        <button onClick={() => setCounters((prev) => [...prev, nanoid()])}>\n          Add counter\n        </button>\n      </div>\n      {counters.map((id) => (\n        <Counter\n          key={id}\n          id={id}\n          onRemove={() => setCounters((prev) => prev.filter((el) => el !== id))}\n        />\n      ))}\n    </Container>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/polling/PollingToggles.tsx",
    "content": "import type { ReactNode } from 'react'\nimport { useAppDispatch, useAppSelector } from '../../app/hooks'\nimport {\n  selectGlobalPollingEnabled,\n  selectPollingConfigByApp,\n  toggleGlobalPolling,\n  updatePolling,\n} from './pollingSlice'\n\nexport const PollingToggleButton = ({\n  enabled,\n  onClick,\n  children,\n}: {\n  onClick: () => void\n  enabled: boolean\n  children?: ReactNode\n}) => {\n  return (\n    <button\n      onClick={onClick}\n      style={enabled ? { background: 'lightgreen' } : {}}\n    >\n      {children}\n    </button>\n  )\n}\n\nexport const PollingToggles = () => {\n  const dispatch = useAppDispatch()\n  const globalPolling = useAppSelector(selectGlobalPollingEnabled)\n  const timesPolling = useAppSelector((state) =>\n    selectPollingConfigByApp(state, 'times'),\n  )\n\n  return (\n    <div>\n      <small>Global Polling Configs</small>\n      <div>\n        <PollingToggleButton\n          enabled={globalPolling}\n          onClick={() => dispatch(toggleGlobalPolling())}\n        >\n          Global\n        </PollingToggleButton>\n        <PollingToggleButton\n          enabled={timesPolling.enabled}\n          onClick={() =>\n            dispatch(\n              updatePolling({ app: 'times', enabled: !timesPolling.enabled }),\n            )\n          }\n        >\n          Times\n        </PollingToggleButton>\n      </div>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/polling/pollingSlice.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit'\nimport { createSlice } from '@reduxjs/toolkit'\nimport type { RootState } from '../../app/store'\n\nexport type PollingConfig = {\n  enabled: boolean\n  interval: number\n}\n\nexport type SliceState = {\n  enabled: boolean\n  apps: {\n    [key: string]: PollingConfig\n  }\n}\n\nexport const initialState: SliceState = {\n  enabled: true,\n  apps: {\n    counters: {\n      enabled: true,\n      interval: 0,\n    },\n    times: {\n      enabled: true,\n      interval: 0,\n    },\n    posts: {\n      enabled: true,\n      interval: 0,\n    },\n  },\n}\n\nexport type PollingAppKey = keyof (typeof initialState)['apps']\n\nexport const pollingSlice = createSlice({\n  name: 'polling',\n  initialState,\n  reducers: (creators) => {\n    return {\n      toggleGlobalPolling: creators.reducer((state) => {\n        state.enabled = !state.enabled\n      }),\n      updatePolling(\n        state,\n        {\n          payload,\n        }: PayloadAction<{\n          app: PollingAppKey\n          enabled?: boolean\n          interval?: number\n        }>,\n      ) {\n        const { app, ...rest } = payload\n        state.apps[app] = {\n          ...state.apps[app],\n          ...rest,\n        }\n      },\n    }\n  },\n  selectors: {\n    selectGlobalPollingEnabled: (pollingState) => pollingState.enabled,\n  },\n})\n\nexport const {\n  actions,\n  caseReducers,\n  getInitialState,\n  getSelectors,\n  injectInto,\n  name,\n  reducer,\n  reducerPath,\n  selectSlice,\n  selectors,\n} = pollingSlice\n\nexport const {\n  toggleGlobalPolling: _toggleGlobalPolling,\n  updatePolling: _updatePolling,\n} = caseReducers\n\nexport const { toggleGlobalPolling, updatePolling } = pollingSlice.actions\n\nexport const { selectGlobalPollingEnabled } = selectors\n\nexport const { unwrapped } = selectGlobalPollingEnabled\n\nexport const selectPollingConfigByApp = (\n  state: RootState,\n  app: PollingAppKey,\n) => state.polling.apps[app]\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/posts/PostDetail.tsx",
    "content": "import type { ChangeEvent, SubmitEventHandler } from 'react'\nimport { useState } from 'react'\nimport { useNavigate, useParams } from 'react-router-dom'\nimport { useAppSelector } from '../../app/hooks'\nimport {\n  useDeletePostMutation,\n  useGetPostQuery,\n  useUpdatePostMutation,\n} from '../../app/services/posts'\nimport { selectGlobalPollingEnabled } from '../polling/pollingSlice'\n\nexport const EditablePostName = ({\n  name: initialName,\n  onUpdate,\n  onCancel,\n  loading = false,\n}: {\n  name: string\n  onUpdate: (name: string) => void\n  onCancel: () => void\n  loading?: boolean\n}) => {\n  const [name, setName] = useState(initialName)\n\n  const handleChange = ({ target: { value } }: ChangeEvent<HTMLInputElement>) =>\n    setName(value)\n\n  const handleSubmit: SubmitEventHandler<HTMLFormElement> = (e) => {\n    e.preventDefault()\n    onUpdate(name)\n  }\n  const handleCancel = () => onCancel()\n\n  return (\n    <div>\n      <form onSubmit={handleSubmit}>\n        <input\n          type=\"text\"\n          onChange={handleChange}\n          value={name}\n          disabled={loading}\n        />\n        <button type=\"submit\" disabled={loading}>\n          {loading ? 'Updating...' : 'Update'}\n        </button>\n        <button onClick={handleCancel} disabled={loading}>\n          Cancel\n        </button>\n      </form>\n    </div>\n  )\n}\n\nexport const PostJsonDetail = ({ id }: { id: number }) => {\n  const { data: post } = useGetPostQuery(id)\n\n  return (\n    <div className=\"row\" style={{ background: '#eee' }}>\n      <pre>{JSON.stringify(post, null, 2)}</pre>\n    </div>\n  )\n}\n\nexport const PostDetail = () => {\n  const { id } = useParams<{ id: any }>()\n  const navigate = useNavigate()\n  const globalPolling = useAppSelector(selectGlobalPollingEnabled)\n\n  const [isEditing, setIsEditing] = useState(false)\n\n  const {\n    data: post,\n    isFetching,\n    isLoading,\n  } = useGetPostQuery(id, { pollingInterval: globalPolling ? 3000 : 0 })\n\n  const [updatePost, { isLoading: isUpdating }] = useUpdatePostMutation()\n  const [deletePost, { isLoading: isDeleting }] = useDeletePostMutation()\n\n  if (isLoading) {\n    return <div>Loading...</div>\n  }\n\n  if (!post) {\n    return <div>Missing post!</div>\n  }\n\n  return (\n    <div>\n      {isEditing ? (\n        <EditablePostName\n          name={post.name}\n          onUpdate={(name) =>\n            updatePost({ id, name })\n              .then((result) => {\n                // handle the success!\n                console.log('Update Result', result)\n                setIsEditing(false)\n              })\n              .catch((error) => console.error('Update Error', error))\n          }\n          onCancel={() => setIsEditing(false)}\n          loading={isUpdating}\n        />\n      ) : (\n        <div className=\"row\">\n          <div className=\"column\">\n            <h3>\n              {post.name} {isFetching ? '...refetching' : ''}\n            </h3>\n          </div>\n          <button\n            onClick={() => setIsEditing(true)}\n            disabled={isDeleting || isUpdating}\n          >\n            {isUpdating ? 'Updating...' : 'Edit'}\n          </button>\n          <button\n            onClick={() => deletePost(id).then(() => navigate('/posts'))}\n            disabled={isDeleting}\n          >\n            {isDeleting ? 'Deleting...' : 'Delete'}\n          </button>\n        </div>\n      )}\n      <PostJsonDetail id={id} />\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/posts/PostsManager.tsx",
    "content": "import type { ChangeEvent, SubmitEventHandler } from 'react'\nimport { useState } from 'react'\nimport { useDispatch, useSelector } from 'react-redux'\nimport { Route, Routes, useNavigate } from 'react-router-dom'\nimport type { Post } from '../../app/services/posts'\nimport {\n  useAddPostMutation,\n  useGetErrorProneQuery,\n  useGetInfinitePostsInfiniteQuery,\n  useGetPostsQuery,\n  useLoginMutation,\n} from '../../app/services/posts'\nimport { logout, selectIsAuthenticated } from '../auth/authSlice'\nimport { PostDetail } from './PostDetail'\n\nexport const AddPost = () => {\n  const initialValue = { name: '' }\n  const [post, setPost] = useState<Partial<Post>>(initialValue)\n  const [addPost, { isLoading }] = useAddPostMutation()\n\n  const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => {\n    setPost((prev) => ({\n      ...prev,\n      [target.name]: target.value,\n    }))\n  }\n\n  const handleSubmit: SubmitEventHandler<HTMLFormElement> = async (e) => {\n    e.preventDefault()\n    await addPost(post)\n    setPost(initialValue)\n  }\n\n  return (\n    <form onSubmit={handleSubmit}>\n      <div className=\"row\">\n        <div className=\"column column-3\">\n          <input\n            name=\"name\"\n            placeholder=\"New post name\"\n            type=\"text\"\n            onChange={handleChange}\n            value={post.name}\n          />\n        </div>\n        <div className=\"column column-1\">\n          <button type=\"submit\" disabled={isLoading}>\n            {isLoading ? 'Adding...' : 'Add Post'}\n          </button>\n        </div>\n      </div>\n    </form>\n  )\n}\n\nexport const PostListItem = ({\n  data: { name, id },\n  onSelect,\n}: {\n  data: Post\n  onSelect: (id: number) => void\n}) => {\n  return (\n    <li>\n      <a href=\"#\" onClick={() => onSelect(id)}>\n        {name}\n      </a>\n    </li>\n  )\n}\n\nexport const PostList = () => {\n  const { data: posts, isLoading } = useGetPostsQuery()\n  useGetInfinitePostsInfiniteQuery()\n  const navigate = useNavigate()\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <div>\n      {posts.map((post) => (\n        <PostListItem\n          key={post.id}\n          data={post}\n          onSelect={(id) => navigate(`/posts/${id}`)}\n        />\n      ))}\n    </div>\n  )\n}\n\nexport const PostsManager = () => {\n  const [login] = useLoginMutation()\n  const [initRetries, setInitRetries] = useState(false)\n  const { data, error, isFetching } = useGetErrorProneQuery(undefined, {\n    skip: !initRetries,\n  })\n  const dispatch = useDispatch()\n  const isAuthenticated = useSelector(selectIsAuthenticated)\n\n  return (\n    <div>\n      <h3>Posts</h3>\n      {!isAuthenticated ? (\n        <button\n          onClick={() => login({ ignore: 'This will just set the headers' })}\n        >\n          Login\n        </button>\n      ) : (\n        <button onClick={() => dispatch(logout())}>Logout</button>\n      )}\n      <button onClick={() => setInitRetries(true)}>\n        {isFetching ? 'retrying...' : 'Start error prone retries'}\n      </button>\n      <hr />\n      <div className=\"row\">\n        <div className=\"posts-list\">\n          <AddPost />\n          <hr />\n          Posts:\n          <PostList />\n          <hr />\n          List with duplicate subscription:\n          <PostList />\n        </div>\n        <div className=\"column column-3 text-left\">\n          <Routes>\n            <Route path=\"/:id\" element={<PostDetail />} />\n          </Routes>\n        </div>\n      </div>\n    </div>\n  )\n}\n\nexport default PostsManager\n"
  },
  {
    "path": "examples/type-portability/bundler/src/features/time/TimeList.tsx",
    "content": "import { nanoid } from '@reduxjs/toolkit'\nimport * as React from 'react'\nimport { useEffect } from 'react'\nimport { useAppSelector } from '../../app/hooks'\nimport { useGetTimeQuery, usePrefetchTime } from '../../app/services/times'\nimport { Container } from '../common/Container'\nimport {\n  selectGlobalPollingEnabled,\n  selectPollingConfigByApp,\n} from '../polling/pollingSlice'\n\nexport const timezones: Record<string, string> = {\n  '-12:00': '(GMT -12:00) Eniwetok, Kwajalein',\n  '-11:00': '(GMT -11:00) Midway Island, Samoa',\n  '-10:00': '(GMT -10:00) Hawaii',\n  '-09:50': '(GMT -9:30) Taiohae',\n  '-09:00': '(GMT -9:00) Alaska',\n  '-08:00': '(GMT -8:00) Pacific Time (US & Canada)',\n  '-07:00': '(GMT -7:00) Mountain Time (US & Canada)',\n  '-06:00': '(GMT -6:00) Central Time (US & Canada), Mexico City',\n  '-05:00': '(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima',\n  '-04:50': '(GMT -4:30) Caracas',\n  '-04:00': '(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz',\n  '-03:50': '(GMT -3:30) Newfoundland',\n  '-03:00': '(GMT -3:00) Brazil, Buenos Aires, Georgetown',\n  '-02:00': '(GMT -2:00) Mid-Atlantic',\n  '-01:00': '(GMT -1:00) Azores, Cape Verde Islands',\n  '+00:00': '(GMT) Western Europe Time, London, Lisbon, Casablanca',\n  '+01:00': '(GMT +1:00) Brussels, Copenhagen, Madrid, Paris',\n  '+02:00': '(GMT +2:00) Kaliningrad, South Africa',\n  '+03:00': '(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg',\n  '+03:50': '(GMT +3:30) Tehran',\n  '+04:00': '(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi',\n  '+04:50': '(GMT +4:30) Kabul',\n  '+05:00': '(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent',\n  '+05:50': '(GMT +5:30) Bombay, Calcutta, Madras, New Delhi',\n  '+05:75': '(GMT +5:45) Kathmandu, Pokhara',\n  '+06:00': '(GMT +6:00) Almaty, Dhaka, Colombo',\n  '+06:50': '(GMT +6:30) Yangon, Mandalay',\n  '+07:00': '(GMT +7:00) Bangkok, Hanoi, Jakarta',\n  '+08:00': '(GMT +8:00) Beijing, Perth, Singapore, Hong Kong',\n  '+08:75': '(GMT +8:45) Eucla',\n  '+09:00': '(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk',\n  '+09:50': '(GMT +9:30) Adelaide, Darwin',\n  '+10:00': '(GMT +10:00) Eastern Australia, Guam, Vladivostok',\n  '+10:50': '(GMT +10:30) Lord Howe Island',\n  '+11:00': '(GMT +11:00) Magadan, Solomon Islands, New Caledonia',\n  '+11:50': '(GMT +11:30) Norfolk Island',\n  '+12:00': '(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka',\n  '+12:75': '(GMT +12:45) Chatham Islands',\n  '+13:00': '(GMT +13:00) Apia, Nukualofa',\n  '+14:00': '(GMT +14:00) Line Islands, Tokelau',\n}\n\nexport const TimeZoneSelector = ({\n  onChange,\n}: {\n  onChange: (event: React.ChangeEvent<HTMLSelectElement>) => void\n}) => {\n  return (\n    <select name=\"timezone_offset\" id=\"timezone-offset\" onChange={onChange}>\n      <option value=\"\">Select one...</option>\n      {Object.entries(timezones).map(([value, description]) => (\n        <option key={value} value={value}>\n          {description}\n        </option>\n      ))}\n    </select>\n  )\n}\n\nexport const intervalOptions = [\n  { label: '0 - Off', value: 0 },\n  { label: '1s', value: 1000 },\n  { label: '3s', value: 3000 },\n  { label: '5s', value: 5000 },\n  { label: '10s', value: 10_000 },\n  { label: '1m', value: 60_000 },\n]\n\nexport const TimeDisplay = ({ offset, label }: { offset: string; label: string }) => {\n  const globalPolling = useAppSelector(selectGlobalPollingEnabled)\n  const { enabled: timesPolling } = useAppSelector((state) =>\n    selectPollingConfigByApp(state, 'times'),\n  )\n\n  const canPoll = globalPolling && timesPolling\n\n  const [pollingInterval, setPollingInterval] = React.useState(0)\n  const { data, refetch, isFetching } = useGetTimeQuery(offset, {\n    pollingInterval: canPoll ? pollingInterval : 0,\n  })\n\n  return (\n    <div style={{ ...(isFetching ? { background: '#e6ffe8' } : {}) }}>\n      <p>\n        {data?.time && new Date(data.time).toLocaleTimeString()} - {label}\n      </p>\n      <p>\n        <button onClick={refetch}>refetch manually</button> Polling Interval:{' '}\n        <select\n          value={pollingInterval}\n          onChange={({ target: { value } }) =>\n            setPollingInterval(Number(value))\n          }\n        >\n          {intervalOptions.map(({ label, value }) => (\n            <option key={value} value={value}>\n              {label}\n            </option>\n          ))}\n        </select>\n      </p>\n    </div>\n  )\n}\n\nexport const TimeList = () => {\n  const [times, setTimes] = React.useState<{ [key: string]: string }>({\n    [nanoid()]: '-08:00',\n  })\n  const [selectedValue, setSelectedValue] = React.useState<string>('')\n\n  const prefetch = usePrefetchTime('getTime')\n\n  useEffect(() => {\n    setTimeout(() => {\n      setTimes((prev) => ({ ...prev, [nanoid()]: '+00:00' }))\n    }, 1000)\n  }, [])\n\n  return (\n    <Container>\n      <h3>\n        Add some times, even duplicates, and watch them automatically refetch in\n        sync!\n      </h3>\n      <p>\n        Notes: shared queries (aka multiple entries of the same time zone) will\n        share the lowest polling interval between them that is greater than 0.\n        If all entries are set to 0, it will stop polling. If you have two\n        entries with a polling time of 5s and one with 0 - off, it will continue\n        at 5s until they are removed or 0'd out.\n        <br />\n        Any new poll starts after the last request has either finished or failed\n        to prevent slow-running requests to immediately double-trigger.\n        <br />\n        <strong>* Background flashes green when query is running</strong>\n        <button onMouseEnter={() => prefetch('+02:00', { force: true })}>\n          Prefetch\n        </button>\n      </p>\n      <TimeZoneSelector\n        onChange={({ target: { value } }) => setSelectedValue(value)}\n      />\n      <button\n        onClick={() =>\n          setTimes((prev) => ({ ...prev, [nanoid()]: selectedValue }))\n        }\n        disabled={!selectedValue}\n      >\n        Track time\n      </button>\n      <hr />\n      {Object.entries(times).map(([key, tz]) => (\n        <TimeDisplay key={key} offset={tz} label={timezones[tz]} />\n      ))}\n    </Container>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/bundler/src/index.tsx",
    "content": "import * as React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport { Provider } from 'react-redux'\nimport App from './App'\nimport { store } from './app/store'\n\nexport const container = document.getElementById('root')\n\nif (container) {\n  const root = createRoot(container)\n\n  root.render(\n    <React.StrictMode>\n      <Provider store={store}>\n        <App />\n      </Provider>\n    </React.StrictMode>,\n  )\n} else {\n  throw new Error(\n    \"Root element with ID 'root' was not found in the document. Ensure there is a corresponding HTML element with the ID 'root' in your HTML file.\",\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/bundler/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"allowJs\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"checkJs\": true,\n    \"declaration\": true,\n    \"emitDeclarationOnly\": false,\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"isolatedModules\": true,\n    \"jsx\": \"react-jsx\",\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Bundler\",\n    \"noEmit\": false,\n    \"noEmitOnError\": true,\n    \"noErrorTruncation\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"outDir\": \"./dist\",\n    \"resolveJsonModule\": true,\n    \"rootDir\": \"./src\",\n    \"skipLibCheck\": true,\n    \"strict\": true,\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"useUnknownInCatchVariables\": true,\n    \"verbatimModuleSyntax\": true\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/package.json",
    "content": "{\n  \"name\": \"@examples-type-portability/nodenext-cjs\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"testing type portability for moduleResolution NodeNext and type commonjs\",\n  \"keywords\": [],\n  \"main\": \"src/index.tsx\",\n  \"type\": \"commonjs\",\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"workspace:^\",\n    \"react\": \"^19.2.4\",\n    \"react-dom\": \"^19.2.4\",\n    \"react-redux\": \"^9.2.0\",\n    \"react-router-dom\": \"^7.13.0\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^19.2.13\",\n    \"@types/react-dom\": \"^19.2.3\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\",\n    \"vite\": \"^7.3.1\"\n  },\n  \"scripts\": {\n    \"clean\": \"rimraf dist\",\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"test\": \"yarn clean && tsc -p tsconfig.json\"\n  }\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/App.tsx",
    "content": "import ReactRouterDom = require('react-router-dom')\nimport bundleSplitting = require('./features/bundleSplitting/index.js')\nimport CounterListModule = require('./features/counter/CounterList.js')\nimport PollingTogglesModule = require('./features/polling/PollingToggles.js')\nimport PostsManagerModule = require('./features/posts/PostsManager.js')\nimport TimeListModule = require('./features/time/TimeList.js')\n\nimport Link = ReactRouterDom.Link\nimport Route = ReactRouterDom.Route\nimport Routes = ReactRouterDom.Routes\n\nimport Lazy = bundleSplitting.Lazy\n\nconst { CounterList } = CounterListModule\nconst { PollingToggles } = PollingTogglesModule\nconst { PostsManager } = PostsManagerModule\nconst { TimeList } = TimeListModule\n\nfunction App() {\n  return (\n    <div className=\"App\">\n      <div className=\"row\">\n        <div className=\"column column1\">\n          <span>\n            <Link to=\"/\">Times</Link> | <Link to=\"/posts\">Posts</Link> |{' '}\n            <Link to=\"/counters\">Counter</Link> |{' '}\n            <Link to=\"/bundleSplitting\">Bundle Splitting</Link>\n          </span>\n        </div>\n        <div className=\"column column1\">\n          <PollingToggles />\n        </div>\n      </div>\n      <div />\n      <div>\n        <Routes>\n          <Route path=\"/\" element={<TimeList />} />\n          <Route path=\"/counters\" element={<CounterList />} />\n          <Route path=\"/posts/*\" element={<PostsManager />} />\n          <Route path=\"/bundleSplitting\" element={<Lazy />} />\n        </Routes>\n      </div>\n    </div>\n  )\n}\n\nexport = App\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/app/customModule.ts",
    "content": "import type {\n  Api,\n  BaseQueryFn,\n  CoreModule,\n  EndpointDefinitions,\n  Module,\n} from '@reduxjs/toolkit/query'\n\nimport RTKQuery = require('@reduxjs/toolkit/query')\n\nimport coreModule = RTKQuery.coreModule\nimport buildCreateApi = RTKQuery.buildCreateApi\n\nnamespace customModuleFile {\n  export const customModuleName = Symbol('customModule')\n  export type CustomModule = typeof customModuleName\n\n  export const myModule = (): Module<CustomModule> => ({\n    name: customModuleName,\n    init(api, options, context) {\n      // initialize stuff here if you need to\n\n      return {\n        injectEndpoint(endpoint, definition) {\n          const anyApi = api as any as Api<\n            any,\n            Record<string, any>,\n            string,\n            string,\n            CustomModule | CoreModule\n          >\n          anyApi.endpoints[endpoint].myEndpointProperty = 'test'\n        },\n      }\n    },\n  })\n\n  export const myCreateApi = buildCreateApi(coreModule(), myModule())\n}\n\n// If we remove this, We should get a TypeScript error.\ndeclare module '@reduxjs/toolkit/query' {\n  export interface ApiModules<\n    BaseQuery extends BaseQueryFn,\n    Definitions extends EndpointDefinitions,\n    ReducerPath extends string,\n    TagTypes extends string,\n  > {\n    [customModuleFile.customModuleName]: {\n      endpoints: {\n        [K in keyof Definitions]: {\n          myEndpointProperty: string\n        }\n      }\n    }\n  }\n}\n\nexport = customModuleFile\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/app/dynamicMiddleware.ts",
    "content": "import ReduxToolkit = require('@reduxjs/toolkit')\n\nnamespace dynamicMiddlewareModule {\n  import createDynamicMiddleware = ReduxToolkit.createDynamicMiddleware\n\n  export const dynamicMiddleware = createDynamicMiddleware()\n\n  export const { addMiddleware, instanceId, middleware, withMiddleware } =\n    dynamicMiddleware\n\n  export const { withTypes, match, type } = withMiddleware\n\n  export const { withTypes: _withTypes } = addMiddleware\n}\n\nexport = dynamicMiddlewareModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/app/dynamicReactMiddleware.ts",
    "content": "import ReduxToolkitReact = require('@reduxjs/toolkit/react')\nimport listenerMiddlewareModule = require('./listenerMiddleware.js')\n\nnamespace dynamicReactMiddlewareModule {\n  import createDynamicMiddleware = ReduxToolkitReact.createDynamicMiddleware\n\n  import listenerMiddleware = listenerMiddlewareModule.listenerMiddleware\n\n  export const dynamicReactMiddleware = createDynamicMiddleware()\n\n  export const {\n    addMiddleware,\n    createDispatchWithMiddlewareHook,\n    createDispatchWithMiddlewareHookFactory,\n    instanceId,\n    middleware,\n    withMiddleware,\n  } = dynamicReactMiddleware\n\n  export const { withTypes } = addMiddleware\n\n  export const useDispatchWithMiddleware = createDispatchWithMiddlewareHook(\n    listenerMiddleware.middleware,\n  )\n}\n\nexport = dynamicReactMiddlewareModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/app/hooks.ts",
    "content": "import ReactRedux = require('react-redux')\n\nimport type { AppDispatch, AppStore, RootState } from './store.js'\n\nnamespace hooksModule {\n  import useDispatch = ReactRedux.useDispatch\n  import useSelector = ReactRedux.useSelector\n  import useStore = ReactRedux.useStore\n\n  export const useAppDispatch = useDispatch.withTypes<AppDispatch>()\n  export const useAppSelector = useSelector.withTypes<RootState>()\n  export const useAppStore = useStore.withTypes<AppStore>()\n}\n\nexport = hooksModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/app/listenerMiddleware.ts",
    "content": "import ReduxToolkit = require('@reduxjs/toolkit')\n\nnamespace listenerMiddlewareModule {\n  import createListenerMiddleware = ReduxToolkit.createListenerMiddleware\n\n  export const listenerMiddleware = createListenerMiddleware()\n\n  export const { clearListeners, middleware, startListening, stopListening } =\n    listenerMiddleware\n\n  export const { withTypes } = startListening\n\n  export const { withTypes: _withTypes } = stopListening\n}\n\nexport = listenerMiddlewareModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/app/services/api.ts",
    "content": "import RTKQueryReact = require('@reduxjs/toolkit/query/react')\n\nimport type { RootState } from '../store.js'\n\nnamespace apiModule {\n  import createApi = RTKQueryReact.createApi\n  import fetchBaseQuery = RTKQueryReact.fetchBaseQuery\n  import retry = RTKQueryReact.retry\n  import fakeBaseQuery = RTKQueryReact.fakeBaseQuery\n\n  export const baseQuery = fetchBaseQuery({\n    baseUrl: '/',\n    prepareHeaders: (headers, { getState }) => {\n      const { token } = (getState() as RootState).auth\n\n      if (token) {\n        headers.set('authentication', `Bearer ${token}`)\n      }\n\n      return headers\n    },\n  })\n\n  export const baseQueryWithRetry = retry(baseQuery, { maxRetries: 6 })\n\n  export const apiSlice = createApi({\n    reducerPath: 'api',\n    baseQuery: baseQueryWithRetry,\n    tagTypes: ['Time', 'Posts', 'Counter'],\n    endpoints: () => ({}),\n  })\n\n  export const enhancedApi = apiSlice.enhanceEndpoints({\n    endpoints: () => ({\n      getPost: () => 'test',\n    }),\n  })\n\n  export const emptyApi = createApi({\n    baseQuery: fakeBaseQuery(),\n    endpoints: () => ({}),\n  })\n\n  export const {\n    endpoints: _endpoints,\n    enhanceEndpoints: _enhanceEndpoints,\n    injectEndpoints: _injectEndpoints,\n    internalActions: _internalActions,\n    middleware: _middleware,\n    reducer: _reducer,\n    reducerPath: _reducerPath,\n    usePrefetch: _usePrefetch,\n    util: _util,\n  } = apiSlice\n\n  export const {\n    endpoints,\n    enhanceEndpoints,\n    injectEndpoints,\n    internalActions,\n    middleware,\n    reducer,\n    reducerPath,\n    usePrefetch,\n    util,\n  } = enhancedApi\n\n  export const {\n    cacheEntriesUpserted,\n    internal_getRTKQSubscriptions,\n    middlewareRegistered,\n    onFocus,\n    onFocusLost,\n    onOffline,\n    onOnline,\n    queryResultPatched,\n    removeMutationResult,\n    removeQueryResult,\n    resetApiState: _resetApiState,\n    subscriptionsUpdated,\n    unsubscribeQueryResult,\n    updateProvidedBy,\n    updateSubscriptionOptions,\n  } = internalActions\n\n  export const { match, type } = updateSubscriptionOptions\n\n  export const {\n    getRunningMutationsThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningQueryThunk,\n    invalidateTags,\n    patchQueryData,\n    prefetch,\n    resetApiState,\n    selectCachedArgsForQuery,\n    selectInvalidatedBy,\n    updateQueryData,\n    upsertQueryData,\n    upsertQueryEntries,\n  } = util\n\n  export const { match: _match, type: _type } = invalidateTags\n\n  export const { match: __match } = upsertQueryEntries\n}\n\nexport = apiModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/app/services/counter.ts",
    "content": "import apiModule = require('./api.js')\n\nnamespace counterModule {\n  import apiSlice = apiModule.apiSlice\n\n  export interface CountResponse {\n    count: number\n  }\n\n  export const counterApi = apiSlice.injectEndpoints({\n    endpoints: (build) => ({\n      getCount: build.query<CountResponse, void>({\n        query: () => 'count',\n        providesTags: ['Counter'],\n      }),\n      incrementCount: build.mutation<CountResponse, number>({\n        query(amount) {\n          return {\n            url: `increment`,\n            method: 'PUT',\n            body: { amount },\n          }\n        },\n        invalidatesTags: ['Counter'],\n      }),\n      decrementCount: build.mutation<CountResponse, number>({\n        query(amount) {\n          return {\n            url: `decrement`,\n            method: 'PUT',\n            body: { amount },\n          }\n        },\n        invalidatesTags: ['Counter'],\n      }),\n    }),\n  })\n\n  export const {\n    useDecrementCountMutation,\n    useGetCountQuery,\n    useIncrementCountMutation,\n    useLazyGetCountQuery,\n    endpoints,\n    enhanceEndpoints,\n    injectEndpoints,\n    internalActions,\n    middleware,\n    reducer,\n    reducerPath,\n    usePrefetch,\n    util,\n  } = counterApi\n\n  export const { decrementCount, getCount, incrementCount } = endpoints\n\n  export const {\n    cacheEntriesUpserted,\n    internal_getRTKQSubscriptions,\n    middlewareRegistered,\n    onFocus,\n    onFocusLost,\n    onOffline,\n    onOnline,\n    queryResultPatched,\n    removeMutationResult,\n    removeQueryResult,\n    resetApiState: _resetApiState,\n    subscriptionsUpdated,\n    unsubscribeQueryResult,\n    updateProvidedBy,\n    updateSubscriptionOptions,\n  } = internalActions\n\n  export const { match, type } = cacheEntriesUpserted\n\n  export const { match: _match, type: _type } = updateSubscriptionOptions\n\n  export const {\n    getRunningMutationsThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningQueryThunk,\n    invalidateTags,\n    patchQueryData,\n    prefetch,\n    resetApiState,\n    selectCachedArgsForQuery,\n    selectInvalidatedBy,\n    updateQueryData,\n    upsertQueryData,\n    upsertQueryEntries,\n  } = util\n\n  export const { match: __match, type: __type } = invalidateTags\n\n  export const { match: ___match } = upsertQueryEntries\n}\n\nexport = counterModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/app/services/post.ts",
    "content": "import apiModule = require('./api.js')\n\nimport type { Post } from './posts.js'\n\nnamespace postModule {\n  import apiSlice = apiModule.apiSlice\n\n  export const postApi = apiSlice.injectEndpoints({\n    endpoints: (build) => ({\n      addPost: build.mutation<Post, Partial<Post>>({\n        query(body) {\n          return {\n            url: `posts`,\n            method: 'POST',\n            body,\n          }\n        },\n        invalidatesTags: ['Posts'],\n      }),\n      getPost: build.query<Post, number>({\n        query: (id) => `posts/${id}`,\n        providesTags: (_result, _err, id) => [{ type: 'Posts', id }],\n      }),\n      updatePost: build.mutation<Post, Partial<Post>>({\n        query(data) {\n          const { id, ...body } = data\n          return {\n            url: `posts/${id}`,\n            method: 'PUT',\n            body,\n          }\n        },\n        invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n      }),\n      deletePost: build.mutation<{ success: boolean; id: number }, number>({\n        query(id) {\n          return {\n            url: `posts/${id}`,\n            method: 'DELETE',\n          }\n        },\n        invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n      }),\n    }),\n  })\n\n  export const {\n    endpoints,\n    enhanceEndpoints,\n    injectEndpoints,\n    internalActions,\n    middleware,\n    reducer,\n    reducerPath,\n    useAddPostMutation,\n    useDeletePostMutation,\n    useGetPostQuery,\n    useLazyGetPostQuery,\n    usePrefetch,\n    useUpdatePostMutation,\n    util,\n  } = postApi\n\n  export const { addPost, deletePost, getPost, updatePost } = endpoints\n\n  export const {\n    Types,\n    initiate,\n    matchFulfilled,\n    matchPending,\n    matchRejected,\n    name,\n    select,\n    useMutation,\n  } = addPost\n\n  export const {\n    BaseQuery,\n    MutationDefinition,\n    QueryArg,\n    RawResultType,\n    ReducerPath,\n    ResultType,\n    TagTypes,\n  } = Types\n\n  export const {\n    argSchema,\n    catchSchemaFailure,\n    errorResponseSchema,\n    extraOptions,\n    invalidatesTags,\n    metaSchema,\n    onCacheEntryAdded,\n    onQueryStarted,\n    onSchemaFailure,\n    providesTags,\n    query,\n    queryFn,\n    rawErrorResponseSchema,\n    rawResponseSchema,\n    responseSchema,\n    skipSchemaValidation,\n    structuralSharing,\n    transformErrorResponse,\n    transformResponse,\n    type: __type,\n    Types: _Types,\n  } = MutationDefinition\n\n  export const { fetched_at, id, name: _name } = QueryArg\n\n  export const {\n    cacheEntriesUpserted,\n    internal_getRTKQSubscriptions,\n    middlewareRegistered,\n    onFocus,\n    onFocusLost,\n    onOffline,\n    onOnline,\n    queryResultPatched,\n    removeMutationResult,\n    removeQueryResult,\n    resetApiState: _resetApiState,\n    subscriptionsUpdated,\n    unsubscribeQueryResult,\n    updateProvidedBy,\n    updateSubscriptionOptions,\n  } = internalActions\n\n  export const { match, type } = cacheEntriesUpserted\n\n  export const { match: _match, type: _type } = updateSubscriptionOptions\n\n  export const {\n    getRunningMutationsThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningQueryThunk,\n    invalidateTags,\n    patchQueryData,\n    prefetch,\n    resetApiState,\n    selectCachedArgsForQuery,\n    selectInvalidatedBy,\n    updateQueryData,\n    upsertQueryData,\n    upsertQueryEntries,\n  } = util\n\n  export const { match: __match } = upsertQueryEntries\n\n  export const { match: ___match, type: ___type } = invalidateTags\n}\n\nexport = postModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/app/services/posts.ts",
    "content": "import RTKQueryReact = require('@reduxjs/toolkit/query/react')\nimport apiModule = require('./api.js')\n\nnamespace postsModule {\n  import retry = RTKQueryReact.retry\n  import apiSlice = apiModule.apiSlice\n\n  export interface Post {\n    id: number\n    name: string\n    fetched_at: string\n  }\n\n  export type PostsResponse = Post[]\n\n  export interface User {\n    first_name: string\n    last_name: string\n    email: string\n    phone: string\n  }\n\n  export const postsApi = apiSlice.injectEndpoints({\n    endpoints: (build) => ({\n      login: build.mutation<{ token: string; user: User }, any>({\n        query: (credentials: any) => ({\n          url: 'login',\n          method: 'POST',\n          body: credentials,\n        }),\n        extraOptions: {\n          backoff: () => {\n            retry.fail({ fake: 'error' }) // We intentionally error once on login, and this breaks out of retrying. The next login attempt will succeed.\n          },\n        },\n      }),\n      getPosts: build.query<PostsResponse, void>({\n        query: () => ({ url: 'posts' }),\n        providesTags: (result = []) => [\n          ...result.map(({ id }) => ({ type: 'Posts', id }) as const),\n          { type: 'Posts' as const, id: 'LIST' },\n        ],\n      }),\n      addPost: build.mutation<Post, Partial<Post>>({\n        query: (body) => ({\n          url: `posts`,\n          method: 'POST',\n          body,\n        }),\n        invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n      }),\n      getPost: build.query<Post, number>({\n        query: (id) => `posts/${id}`,\n        providesTags: (_post, _err, id) => [{ type: 'Posts', id }],\n      }),\n      updatePost: build.mutation<Post, Partial<Post>>({\n        query(data) {\n          const { id, ...body } = data\n          return {\n            url: `posts/${id}`,\n            method: 'PUT',\n            body,\n          }\n        },\n        invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n      }),\n      deletePost: build.mutation<{ success: boolean; id: number }, number>({\n        query(id) {\n          return {\n            url: `posts/${id}`,\n            method: 'DELETE',\n          }\n        },\n        invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n      }),\n      getErrorProne: build.query<{ success: boolean }, void>({\n        query: () => 'error-prone',\n      }),\n      getInfinitePosts: build.infiniteQuery<PostsResponse, void, number>({\n        queryFn: ({ pageParam = 0 }) => ({\n          data: [],\n        }),\n        infiniteQueryOptions: {\n          initialPageParam: 0,\n          getNextPageParam: (lastPage) =>\n            lastPage.length === 0\n              ? undefined\n              : lastPage[lastPage.length - 1].id,\n        },\n      }),\n    }),\n  })\n\n  export const {\n    useAddPostMutation,\n    useDeletePostMutation,\n    useGetPostQuery,\n    useGetPostsQuery,\n    useLoginMutation,\n    useUpdatePostMutation,\n    useGetErrorProneQuery,\n    useLazyGetErrorProneQuery,\n    useLazyGetPostQuery,\n    useLazyGetPostsQuery,\n    useGetInfinitePostsInfiniteQuery,\n    endpoints,\n    enhanceEndpoints,\n    injectEndpoints,\n    internalActions,\n    middleware,\n    reducer,\n    reducerPath,\n    usePrefetch,\n    util,\n  } = postsApi\n\n  export const {\n    addPost,\n    deletePost,\n    getErrorProne,\n    getPost,\n    getPosts,\n    login,\n    updatePost,\n    getInfinitePosts,\n  } = endpoints\n\n  export const {\n    Types,\n    initiate,\n    matchFulfilled,\n    matchPending,\n    matchRejected,\n    name,\n    select,\n    useMutation,\n  } = addPost\n\n  export const {\n    Types: _Types,\n    initiate: _initiate,\n    matchFulfilled: _matchFulfilled,\n    matchPending: _matchPending,\n    matchRejected: _matchRejected,\n    name: _name,\n    select: _select,\n    useMutation: _useMutation,\n  } = deletePost\n\n  export const {\n    Types: __Types,\n    initiate: __initiate,\n    matchFulfilled: __matchFulfilled,\n    matchPending: __matchPending,\n    matchRejected: __matchRejected,\n    name: __name,\n    select: __select,\n    useQueryState,\n    useLazyQuery,\n    useLazyQuerySubscription,\n    useQuery,\n    useQuerySubscription,\n  } = getErrorProne\n\n  export const {\n    Types: ___Types,\n    initiate: ___initiate,\n    matchFulfilled: ___matchFulfilled,\n    matchPending: ___matchPending,\n    matchRejected: ___matchRejected,\n    name: ___name,\n    select: ___select,\n    useQueryState: ___useQueryState,\n    useLazyQuery: ___useLazyQuery,\n    useLazyQuerySubscription: ___useLazyQuerySubscription,\n    useQuery: ___useQuery,\n    useQuerySubscription: ___useQuerySubscription,\n  } = getPost\n\n  export const {\n    Types: ____Types,\n    initiate: ____initiate,\n    matchFulfilled: ____matchFulfilled,\n    matchPending: ____matchPending,\n    matchRejected: ____matchRejected,\n    name: ____name,\n    select: ____select,\n    useMutation: ____useMutation,\n  } = login\n\n  export const {\n    Types: _____Types,\n    initiate: _____initiate,\n    matchFulfilled: _____matchFulfilled,\n    matchPending: _____matchPending,\n    matchRejected: _____matchRejected,\n    name: _____name,\n    select: _____select,\n    useMutation: _____useMutation,\n  } = updatePost\n\n  export const {\n    Types: ______Types,\n    initiate: ______initiate,\n    matchFulfilled: ______matchFulfilled,\n    matchPending: ______matchPending,\n    matchRejected: ______matchRejected,\n    name: ______name,\n    select: ______select,\n    useInfiniteQueryState: ______useQueryState,\n    useInfiniteQuery: ______useQuery,\n    useInfiniteQuerySubscription: ______useQuerySubscription,\n  } = getInfinitePosts\n\n  export const {\n    cacheEntriesUpserted,\n    internal_getRTKQSubscriptions,\n    middlewareRegistered,\n    onFocus,\n    onFocusLost,\n    onOffline,\n    onOnline,\n    queryResultPatched,\n    removeMutationResult,\n    removeQueryResult,\n    resetApiState: _resetApiState,\n    subscriptionsUpdated,\n    unsubscribeQueryResult,\n    updateProvidedBy,\n    updateSubscriptionOptions,\n  } = internalActions\n\n  export const {\n    getRunningMutationsThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningQueryThunk,\n    invalidateTags,\n    patchQueryData,\n    prefetch,\n    resetApiState,\n    selectCachedArgsForQuery,\n    selectInvalidatedBy,\n    updateQueryData,\n    upsertQueryData,\n    upsertQueryEntries,\n  } = util\n}\n\nexport = postsModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/app/services/times.ts",
    "content": "import apiModule = require('./api.js')\n\nnamespace timesModule {\n  import apiSlice = apiModule.apiSlice\n\n  export interface TimeResponse {\n    time: string\n  }\n\n  export const timeApi = apiSlice.injectEndpoints({\n    endpoints: (build) => ({\n      getTime: build.query<TimeResponse, string>({\n        query: (id) => `time/${id}`,\n        providesTags: (_result, _err, id) => [{ type: 'Time', id }],\n      }),\n    }),\n  })\n\n  export const {\n    useLazyGetTimeQuery,\n    usePrefetch: usePrefetchTime,\n    useGetTimeQuery,\n    endpoints,\n    enhanceEndpoints,\n    injectEndpoints,\n    internalActions,\n    middleware,\n    reducer,\n    reducerPath,\n    util,\n  } = timeApi\n\n  export const { getTime } = endpoints\n\n  export const {\n    Types,\n    initiate,\n    matchFulfilled,\n    matchPending,\n    matchRejected,\n    name,\n    select,\n    useQuery,\n    useLazyQuery,\n    useQuerySubscription,\n    useQueryState,\n    useLazyQuerySubscription,\n  } = getTime\n\n  export const {\n    cacheEntriesUpserted,\n    internal_getRTKQSubscriptions,\n    middlewareRegistered,\n    onFocus,\n    onFocusLost,\n    onOffline,\n    onOnline,\n    queryResultPatched,\n    removeMutationResult,\n    removeQueryResult,\n    resetApiState: _resetApiState,\n    subscriptionsUpdated,\n    unsubscribeQueryResult,\n    updateProvidedBy,\n    updateSubscriptionOptions,\n  } = internalActions\n\n  export const {\n    getRunningMutationsThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningQueryThunk,\n    invalidateTags,\n    patchQueryData,\n    prefetch,\n    resetApiState,\n    selectCachedArgsForQuery,\n    selectInvalidatedBy,\n    updateQueryData,\n    upsertQueryData,\n    upsertQueryEntries,\n  } = util\n}\n\nexport = timesModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/app/store.ts",
    "content": "import ReduxToolkit = require('@reduxjs/toolkit')\nimport RTKQuery = require('@reduxjs/toolkit/query')\nimport authSliceModule = require('../features/auth/authSlice.js')\nimport pollingSliceModule = require('../features/polling/pollingSlice.js')\nimport dynamicMiddlewareModule = require('./dynamicMiddleware.js')\nimport dynamicReactMiddlewareModule = require('./dynamicReactMiddleware.js')\nimport listenerMiddlewareModule = require('./listenerMiddleware.js')\nimport apiModule = require('./services/api.js')\n\nnamespace storeModule {\n  import combineSlices = ReduxToolkit.combineSlices\n  import configureStore = ReduxToolkit.configureStore\n  import setupListeners = RTKQuery.setupListeners\n  import authSlice = authSliceModule.authSlice\n  import pollingSlice = pollingSliceModule.pollingSlice\n  import dynamicMiddleware = dynamicMiddlewareModule.dynamicMiddleware\n  import dynamicReactMiddleware = dynamicReactMiddlewareModule.dynamicReactMiddleware\n  import listenerMiddleware = listenerMiddlewareModule.listenerMiddleware\n  import apiSlice = apiModule.apiSlice\n\n  export const rootReducer = combineSlices(pollingSlice, authSlice, apiSlice)\n\n  export const { inject, selector, withLazyLoadedSlices } = rootReducer\n\n  export const { original } = selector\n\n  export type RootState = ReturnType<typeof rootReducer>\n\n  export const setupStore = (preloadedState?: Partial<RootState>) =>\n    configureStore({\n      reducer: rootReducer,\n      middleware: (getDefaultMiddleware) =>\n        getDefaultMiddleware()\n          .prepend(listenerMiddleware.middleware)\n          .prepend(dynamicMiddleware.middleware)\n          .prepend(dynamicReactMiddleware.middleware)\n          .concat(apiSlice.middleware),\n      preloadedState,\n      enhancers: (getDefaultEnhancers) => getDefaultEnhancers(),\n    })\n\n  export const store = setupStore()\n\n  setupListeners(store.dispatch)\n\n  export const { dispatch, getState, replaceReducer, subscribe } = store\n\n  export type AppStore = typeof store\n  export type AppDispatch = typeof store.dispatch\n}\n\nexport = storeModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/auth/authSlice.ts",
    "content": "import ReduxToolkit = require('@reduxjs/toolkit')\nimport postsModule = require('../../app/services/posts.js')\n\nimport type { User } from '../../app/services/posts.js'\n\nnamespace authSliceModule {\n  import createSlice = ReduxToolkit.createSlice\n  import postsApi = postsModule.postsApi\n\n  export const initialState = {\n    user: null,\n    token: null,\n    isAuthenticated: false,\n  } as { user: null | User; token: string | null; isAuthenticated: boolean }\n\n  export const authSlice = createSlice({\n    name: 'auth',\n    initialState,\n    reducers: {\n      logout: () => initialState,\n    },\n    extraReducers: (builder) => {\n      builder\n        .addMatcher(postsApi.endpoints.login.matchPending, (state, action) => {\n          console.log('pending', action)\n        })\n        .addMatcher(\n          postsApi.endpoints.login.matchFulfilled,\n          (state, action) => {\n            console.log('fulfilled', action)\n            state.user = action.payload.user\n            state.token = action.payload.token\n            state.isAuthenticated = true\n          },\n        )\n        .addMatcher(postsApi.endpoints.login.matchRejected, (state, action) => {\n          console.log('rejected', action)\n        })\n    },\n    selectors: {\n      selectIsAuthenticated: (authState) => authState.isAuthenticated,\n    },\n  })\n\n  export const {\n    actions,\n    caseReducers,\n    getInitialState,\n    getSelectors,\n    injectInto,\n    name,\n    reducer,\n    reducerPath,\n    selectSlice,\n    selectors,\n  } = authSlice\n\n  export const { selectIsAuthenticated } = getSelectors(selectSlice)\n\n  export const { unwrapped } = selectIsAuthenticated\n\n  export const { logout: _logout } = caseReducers\n\n  export const { logout } = authSlice.actions\n}\n\nexport = authSliceModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/bundleSplitting/Lazy.tsx",
    "content": "import React = require('react')\nimport bundleSplittingModule = require('./index.js')\n\nnamespace lazyModule {\n  import Suspense = React.Suspense\n  import PostsList = bundleSplittingModule.PostsList\n\n  export const Lazy = () => {\n    return (\n      <Suspense fallback={<>loading...</>}>\n        <PostsList />\n      </Suspense>\n    )\n  }\n}\n\nexport = lazyModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/bundleSplitting/Post.tsx",
    "content": "import postModule = require('../../app/services/post.js')\n\nimport postApi = postModule.postApi\n\nfunction assert(condition: any, msg = 'Generic Assertion'): asserts condition {\n  if (!condition) {\n    throw new Error(`Assertion failed: ${msg}`)\n  }\n}\n\nconst Post = ({ id }: { id: number }) => {\n  assert(postApi.endpoints.getPost?.useQuery, 'Endpoint `getPost` not loaded!')\n\n  const { data, error } = postApi.endpoints.getPost.useQuery(id)\n\n  return error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <h1>{data.name}</h1>\n  )\n}\n\nexport = Post\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/bundleSplitting/PostsList.tsx",
    "content": "import React = require('react')\nimport bundleSplittingModule = require('./index.js')\nimport postsModule = require('../../app/services/posts.js')\n\nimport useState = React.useState\nimport Post = bundleSplittingModule.Post\nimport postsApi = postsModule.postsApi\n\nconst PostsList = () => {\n  const { data, error } = postsApi.endpoints.getPosts.useQuery()\n  const [selected, select] = useState<number | undefined>()\n\n  return error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <>\n      {selected && <Post id={selected} />}\n      <ul>\n        {data.map((post) => (\n          <li key={post.id}>\n            <button onClick={() => select(post.id)}>{post.name}</button>\n          </li>\n        ))}\n      </ul>\n    </>\n  )\n}\n\nexport = PostsList\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/bundleSplitting/index.ts",
    "content": "import React = require('react')\nimport lazyModule = require('./Lazy.js')\n\nnamespace bundleSplitting {\n  import lazy = React.lazy\n\n  export const PostsList = lazy(() => import('./PostsList.js'))\n\n  export const Post = lazy(() => import('./Post.js'))\n\n  export import Lazy = lazyModule.Lazy\n}\n\nexport = bundleSplitting\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/common/Container.tsx",
    "content": "import type { FC, ReactNode } from 'react'\n\nconst Container: FC<{ children: ReactNode }> = ({ children }) => (\n  <div style={{ textAlign: 'center', padding: 50, margin: '0 auto' }}>\n    {children}\n  </div>\n)\n\nexport = { Container }\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/counter/Counter.tsx",
    "content": "import React = require('react')\nimport counterModule = require('../../app/services/counter.js')\n\nimport useState = React.useState\nimport useDecrementCountMutation = counterModule.useDecrementCountMutation\nimport useGetCountQuery = counterModule.useGetCountQuery\nimport useIncrementCountMutation = counterModule.useIncrementCountMutation\n\nfunction Counter({ id, onRemove }: { id?: string; onRemove?: () => void }) {\n  const [pollingInterval, setPollingInterval] = useState(10_000)\n  const { data } = useGetCountQuery(undefined, { pollingInterval })\n  const [increment] = useIncrementCountMutation()\n  const [decrement] = useDecrementCountMutation()\n\n  return (\n    <div>\n      <div>\n        <button aria-label=\"Increment value\" onClick={() => increment(1)}>\n          +\n        </button>\n        <span>{data?.count || 0}</span>\n        <button aria-label=\"Decrement value\" onClick={() => decrement(1)}>\n          -\n        </button>\n        <input\n          type=\"number\"\n          name=\"pollingInterval\"\n          value={pollingInterval}\n          onChange={({ target: { valueAsNumber } }) =>\n            setPollingInterval(valueAsNumber)\n          }\n        />\n        {onRemove && <button onClick={onRemove}>Remove {id}</button>}\n      </div>\n    </div>\n  )\n}\n\nexport = { Counter }\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/counter/CounterList.tsx",
    "content": "import ReduxToolkit = require('@reduxjs/toolkit')\nimport React = require('react')\nimport ContainerModule = require('../common/Container.js')\nimport CounterModule = require('./Counter.js')\n\nimport nanoid = ReduxToolkit.nanoid\nimport useState = React.useState\n\nconst { Container } = ContainerModule\nconst { Counter } = CounterModule\n\nconst CounterList = () => {\n  const [counters, setCounters] = useState<string[]>([])\n\n  if (!counters.length) {\n    return (\n      <Container>\n        <div>No counters, why don't you add one?</div>\n        <div>\n          <button onClick={() => setCounters((prev) => [...prev, nanoid()])}>\n            Add counter\n          </button>\n        </div>\n      </Container>\n    )\n  }\n\n  return (\n    <Container>\n      <div>\n        <button onClick={() => setCounters((prev) => [...prev, nanoid()])}>\n          Add counter\n        </button>\n      </div>\n      {counters.map((id) => (\n        <Counter\n          key={id}\n          id={id}\n          onRemove={() => setCounters((prev) => prev.filter((el) => el !== id))}\n        />\n      ))}\n    </Container>\n  )\n}\n\nexport = { CounterList }\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/polling/PollingToggles.tsx",
    "content": "import hooksModule = require('../../app/hooks.js')\nimport pollingSliceModule = require('./pollingSlice.js')\n\nimport type { ReactNode } from 'react'\n\nimport useAppDispatch = hooksModule.useAppDispatch\nimport useAppSelector = hooksModule.useAppSelector\nimport selectGlobalPollingEnabled = pollingSliceModule.selectGlobalPollingEnabled\nimport selectPollingConfigByApp = pollingSliceModule.selectPollingConfigByApp\nimport toggleGlobalPolling = pollingSliceModule.toggleGlobalPolling\nimport updatePolling = pollingSliceModule.updatePolling\n\nconst PollingToggleButton = ({\n  enabled,\n  onClick,\n  children,\n}: {\n  onClick: () => void\n  enabled: boolean\n  children?: ReactNode\n}) => {\n  return (\n    <button\n      onClick={onClick}\n      style={enabled ? { background: 'lightgreen' } : {}}\n    >\n      {children}\n    </button>\n  )\n}\n\nconst PollingToggles = () => {\n  const dispatch = useAppDispatch()\n  const globalPolling = useAppSelector(selectGlobalPollingEnabled)\n  const timesPolling = useAppSelector((state) =>\n    selectPollingConfigByApp(state, 'times'),\n  )\n\n  return (\n    <div>\n      <small>Global Polling Configs</small>\n      <div>\n        <PollingToggleButton\n          enabled={globalPolling}\n          onClick={() => dispatch(toggleGlobalPolling())}\n        >\n          Global\n        </PollingToggleButton>\n        <PollingToggleButton\n          enabled={timesPolling.enabled}\n          onClick={() =>\n            dispatch(\n              updatePolling({ app: 'times', enabled: !timesPolling.enabled }),\n            )\n          }\n        >\n          Times\n        </PollingToggleButton>\n      </div>\n    </div>\n  )\n}\n\nexport = { PollingToggleButton, PollingToggles }\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/polling/pollingSlice.ts",
    "content": "import ReduxToolkit = require('@reduxjs/toolkit')\n\nimport type { PayloadAction } from '@reduxjs/toolkit'\nimport type { RootState } from '../../app/store.js'\n\nnamespace pollingSliceModule {\n  import createSlice = ReduxToolkit.createSlice\n\n  export type PollingConfig = {\n    enabled: boolean\n    interval: number\n  }\n\n  export type SliceState = {\n    enabled: boolean\n    apps: {\n      [key: string]: PollingConfig\n    }\n  }\n\n  export const initialState: SliceState = {\n    enabled: true,\n    apps: {\n      counters: {\n        enabled: true,\n        interval: 0,\n      },\n      times: {\n        enabled: true,\n        interval: 0,\n      },\n      posts: {\n        enabled: true,\n        interval: 0,\n      },\n    },\n  }\n\n  export type PollingAppKey = keyof (typeof initialState)['apps']\n\n  export const pollingSlice = createSlice({\n    name: 'polling',\n    initialState,\n    reducers: (creators) => {\n      return {\n        toggleGlobalPolling: creators.reducer((state) => {\n          state.enabled = !state.enabled\n        }),\n        updatePolling(\n          state,\n          {\n            payload,\n          }: PayloadAction<{\n            app: PollingAppKey\n            enabled?: boolean\n            interval?: number\n          }>,\n        ) {\n          const { app, ...rest } = payload\n          state.apps[app] = {\n            ...state.apps[app],\n            ...rest,\n          }\n        },\n      }\n    },\n    selectors: {\n      selectGlobalPollingEnabled: (pollingState) => pollingState.enabled,\n    },\n  })\n\n  export const {\n    actions,\n    caseReducers,\n    getInitialState,\n    getSelectors,\n    injectInto,\n    name,\n    reducer,\n    reducerPath,\n    selectSlice,\n    selectors,\n  } = pollingSlice\n\n  export const {\n    toggleGlobalPolling: _toggleGlobalPolling,\n    updatePolling: _updatePolling,\n  } = caseReducers\n\n  export const { toggleGlobalPolling, updatePolling } = pollingSlice.actions\n\n  export const { selectGlobalPollingEnabled } = selectors\n\n  export const { unwrapped } = selectGlobalPollingEnabled\n\n  export const selectPollingConfigByApp = (\n    state: RootState,\n    app: PollingAppKey,\n  ) => state.polling.apps[app]\n}\n\nexport = pollingSliceModule\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/posts/PostDetail.tsx",
    "content": "import React = require('react')\nimport ReactRouterDom = require('react-router-dom')\nimport hooksModule = require('../../app/hooks.js')\nimport postsModule = require('../../app/services/posts.js')\nimport pollingSliceModule = require('../polling/pollingSlice.js')\n\nimport type { ChangeEvent, SubmitEventHandler } from 'react'\n\nimport useState = React.useState\nimport useNavigate = ReactRouterDom.useNavigate\nimport useParams = ReactRouterDom.useParams\nimport useAppSelector = hooksModule.useAppSelector\nimport useDeletePostMutation = postsModule.useDeletePostMutation\nimport useGetPostQuery = postsModule.useGetPostQuery\nimport useUpdatePostMutation = postsModule.useUpdatePostMutation\nimport selectGlobalPollingEnabled = pollingSliceModule.selectGlobalPollingEnabled\n\nconst EditablePostName = ({\n  name: initialName,\n  onUpdate,\n  onCancel,\n  loading = false,\n}: {\n  name: string\n  onUpdate: (name: string) => void\n  onCancel: () => void\n  loading?: boolean\n}) => {\n  const [name, setName] = useState(initialName)\n\n  const handleChange = ({ target: { value } }: ChangeEvent<HTMLInputElement>) =>\n    setName(value)\n\n  const handleSubmit: SubmitEventHandler<HTMLFormElement> = (e) => {\n    e.preventDefault()\n    onUpdate(name)\n  }\n  const handleCancel = () => onCancel()\n\n  return (\n    <div>\n      <form onSubmit={handleSubmit}>\n        <input\n          type=\"text\"\n          onChange={handleChange}\n          value={name}\n          disabled={loading}\n        />\n        <button type=\"submit\" disabled={loading}>\n          {loading ? 'Updating...' : 'Update'}\n        </button>\n        <button onClick={handleCancel} disabled={loading}>\n          Cancel\n        </button>\n      </form>\n    </div>\n  )\n}\n\nconst PostJsonDetail = ({ id }: { id: number }) => {\n  const { data: post } = useGetPostQuery(id)\n\n  return (\n    <div className=\"row\" style={{ background: '#eee' }}>\n      <pre>{JSON.stringify(post, null, 2)}</pre>\n    </div>\n  )\n}\n\nconst PostDetail = () => {\n  const { id } = useParams<{ id: any }>()\n  const navigate = useNavigate()\n  const globalPolling = useAppSelector(selectGlobalPollingEnabled)\n\n  const [isEditing, setIsEditing] = useState(false)\n\n  const {\n    data: post,\n    isFetching,\n    isLoading,\n  } = useGetPostQuery(id, { pollingInterval: globalPolling ? 3000 : 0 })\n\n  const [updatePost, { isLoading: isUpdating }] = useUpdatePostMutation()\n  const [deletePost, { isLoading: isDeleting }] = useDeletePostMutation()\n\n  if (isLoading) {\n    return <div>Loading...</div>\n  }\n\n  if (!post) {\n    return <div>Missing post!</div>\n  }\n\n  return (\n    <div>\n      {isEditing ? (\n        <EditablePostName\n          name={post.name}\n          onUpdate={(name) =>\n            updatePost({ id, name })\n              .then((result) => {\n                // handle the success!\n                console.log('Update Result', result)\n                setIsEditing(false)\n              })\n              .catch((error) => console.error('Update Error', error))\n          }\n          onCancel={() => setIsEditing(false)}\n          loading={isUpdating}\n        />\n      ) : (\n        <div className=\"row\">\n          <div className=\"column\">\n            <h3>\n              {post.name} {isFetching ? '...refetching' : ''}\n            </h3>\n          </div>\n          <button\n            onClick={() => setIsEditing(true)}\n            disabled={isDeleting || isUpdating}\n          >\n            {isUpdating ? 'Updating...' : 'Edit'}\n          </button>\n          <button\n            onClick={() => deletePost(id).then(() => navigate('/posts'))}\n            disabled={isDeleting}\n          >\n            {isDeleting ? 'Deleting...' : 'Delete'}\n          </button>\n        </div>\n      )}\n      <PostJsonDetail id={id} />\n    </div>\n  )\n}\n\nexport = { EditablePostName, PostJsonDetail, PostDetail }\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/posts/PostsManager.tsx",
    "content": "import React = require('react')\nimport ReactRedux = require('react-redux')\nimport ReactRouterDom = require('react-router-dom')\nimport postsModule = require('../../app/services/posts.js')\nimport authSliceModule = require('../auth/authSlice.js')\nimport PostDetailModule = require('./PostDetail.js')\n\nimport type { ChangeEvent, SubmitEventHandler } from 'react'\nimport type { Post } from '../../app/services/posts.js'\n\nimport useState = React.useState\nimport useDispatch = ReactRedux.useDispatch\nimport useSelector = ReactRedux.useSelector\nimport Route = ReactRouterDom.Route\nimport Routes = ReactRouterDom.Routes\nimport useNavigate = ReactRouterDom.useNavigate\nimport useAddPostMutation = postsModule.useAddPostMutation\nimport useGetErrorProneQuery = postsModule.useGetErrorProneQuery\nimport useGetPostsQuery = postsModule.useGetPostsQuery\nimport useLoginMutation = postsModule.useLoginMutation\nimport useGetInfinitePostsInfiniteQuery = postsModule.useGetInfinitePostsInfiniteQuery\nimport logout = authSliceModule.logout\nimport selectIsAuthenticated = authSliceModule.selectIsAuthenticated\n\nconst { PostDetail } = PostDetailModule\n\nconst AddPost = () => {\n  const initialValue = { name: '' }\n  const [post, setPost] = useState<Partial<Post>>(initialValue)\n  const [addPost, { isLoading }] = useAddPostMutation()\n\n  const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => {\n    setPost((prev) => ({\n      ...prev,\n      [target.name]: target.value,\n    }))\n  }\n\n  const handleSubmit: SubmitEventHandler<HTMLFormElement> = async (e) => {\n    e.preventDefault()\n    await addPost(post)\n    setPost(initialValue)\n  }\n\n  return (\n    <form onSubmit={handleSubmit}>\n      <div className=\"row\">\n        <div className=\"column column-3\">\n          <input\n            name=\"name\"\n            placeholder=\"New post name\"\n            type=\"text\"\n            onChange={handleChange}\n            value={post.name}\n          />\n        </div>\n        <div className=\"column column-1\">\n          <button type=\"submit\" disabled={isLoading}>\n            {isLoading ? 'Adding...' : 'Add Post'}\n          </button>\n        </div>\n      </div>\n    </form>\n  )\n}\n\nconst PostListItem = ({\n  data: { name, id },\n  onSelect,\n}: {\n  data: Post\n  onSelect: (id: number) => void\n}) => {\n  return (\n    <li>\n      <a href=\"#\" onClick={() => onSelect(id)}>\n        {name}\n      </a>\n    </li>\n  )\n}\n\nconst PostList = () => {\n  const { data: posts, isLoading } = useGetPostsQuery()\n  useGetInfinitePostsInfiniteQuery()\n  const navigate = useNavigate()\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <div>\n      {posts.map((post) => (\n        <PostListItem\n          key={post.id}\n          data={post}\n          onSelect={(id) => navigate(`/posts/${id}`)}\n        />\n      ))}\n    </div>\n  )\n}\n\nconst PostsManager = () => {\n  const [login] = useLoginMutation()\n  const [initRetries, setInitRetries] = useState(false)\n  const { data, error, isFetching } = useGetErrorProneQuery(undefined, {\n    skip: !initRetries,\n  })\n  const dispatch = useDispatch()\n  const isAuthenticated = useSelector(selectIsAuthenticated)\n\n  return (\n    <div>\n      <h3>Posts</h3>\n      {!isAuthenticated ? (\n        <button\n          onClick={() => login({ ignore: 'This will just set the headers' })}\n        >\n          Login\n        </button>\n      ) : (\n        <button onClick={() => dispatch(logout())}>Logout</button>\n      )}\n      <button onClick={() => setInitRetries(true)}>\n        {isFetching ? 'retrying...' : 'Start error prone retries'}\n      </button>\n      <hr />\n      <div className=\"row\">\n        <div className=\"posts-list\">\n          <AddPost />\n          <hr />\n          Posts:\n          <PostList />\n          <hr />\n          List with duplicate subscription:\n          <PostList />\n        </div>\n        <div className=\"column column-3 text-left\">\n          <Routes>\n            <Route path=\"/:id\" element={<PostDetail />} />\n          </Routes>\n        </div>\n      </div>\n    </div>\n  )\n}\n\nexport = { AddPost, PostListItem, PostList, PostsManager }\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/features/time/TimeList.tsx",
    "content": "import ReduxToolkit = require('@reduxjs/toolkit')\nimport React = require('react')\nimport hooksModule = require('../../app/hooks.js')\nimport timesModule = require('../../app/services/times.js')\nimport ContainerModule = require('../common/Container.js')\nimport pollingSliceModule = require('../polling/pollingSlice.js')\n\nimport nanoid = ReduxToolkit.nanoid\nimport useState = React.useState\nimport useEffect = React.useEffect\nimport useAppSelector = hooksModule.useAppSelector\nimport useGetTimeQuery = timesModule.useGetTimeQuery\nimport usePrefetchTime = timesModule.usePrefetchTime\n\nconst { Container } = ContainerModule\n\nimport selectPollingConfigByApp = pollingSliceModule.selectPollingConfigByApp\nimport selectGlobalPollingEnabled = pollingSliceModule.selectGlobalPollingEnabled\n\nconst timezones: Record<string, string> = {\n  '-12:00': '(GMT -12:00) Eniwetok, Kwajalein',\n  '-11:00': '(GMT -11:00) Midway Island, Samoa',\n  '-10:00': '(GMT -10:00) Hawaii',\n  '-09:50': '(GMT -9:30) Taiohae',\n  '-09:00': '(GMT -9:00) Alaska',\n  '-08:00': '(GMT -8:00) Pacific Time (US & Canada)',\n  '-07:00': '(GMT -7:00) Mountain Time (US & Canada)',\n  '-06:00': '(GMT -6:00) Central Time (US & Canada), Mexico City',\n  '-05:00': '(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima',\n  '-04:50': '(GMT -4:30) Caracas',\n  '-04:00': '(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz',\n  '-03:50': '(GMT -3:30) Newfoundland',\n  '-03:00': '(GMT -3:00) Brazil, Buenos Aires, Georgetown',\n  '-02:00': '(GMT -2:00) Mid-Atlantic',\n  '-01:00': '(GMT -1:00) Azores, Cape Verde Islands',\n  '+00:00': '(GMT) Western Europe Time, London, Lisbon, Casablanca',\n  '+01:00': '(GMT +1:00) Brussels, Copenhagen, Madrid, Paris',\n  '+02:00': '(GMT +2:00) Kaliningrad, South Africa',\n  '+03:00': '(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg',\n  '+03:50': '(GMT +3:30) Tehran',\n  '+04:00': '(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi',\n  '+04:50': '(GMT +4:30) Kabul',\n  '+05:00': '(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent',\n  '+05:50': '(GMT +5:30) Bombay, Calcutta, Madras, New Delhi',\n  '+05:75': '(GMT +5:45) Kathmandu, Pokhara',\n  '+06:00': '(GMT +6:00) Almaty, Dhaka, Colombo',\n  '+06:50': '(GMT +6:30) Yangon, Mandalay',\n  '+07:00': '(GMT +7:00) Bangkok, Hanoi, Jakarta',\n  '+08:00': '(GMT +8:00) Beijing, Perth, Singapore, Hong Kong',\n  '+08:75': '(GMT +8:45) Eucla',\n  '+09:00': '(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk',\n  '+09:50': '(GMT +9:30) Adelaide, Darwin',\n  '+10:00': '(GMT +10:00) Eastern Australia, Guam, Vladivostok',\n  '+10:50': '(GMT +10:30) Lord Howe Island',\n  '+11:00': '(GMT +11:00) Magadan, Solomon Islands, New Caledonia',\n  '+11:50': '(GMT +11:30) Norfolk Island',\n  '+12:00': '(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka',\n  '+12:75': '(GMT +12:45) Chatham Islands',\n  '+13:00': '(GMT +13:00) Apia, Nukualofa',\n  '+14:00': '(GMT +14:00) Line Islands, Tokelau',\n}\n\nconst TimeZoneSelector = ({\n  onChange,\n}: {\n  onChange: (event: React.ChangeEvent<HTMLSelectElement>) => void\n}) => {\n  return (\n    <select name=\"timezone_offset\" id=\"timezone-offset\" onChange={onChange}>\n      <option value=\"\">Select one...</option>\n      {Object.entries(timezones).map(([value, description]) => (\n        <option key={value} value={value}>\n          {description}\n        </option>\n      ))}\n    </select>\n  )\n}\n\nconst intervalOptions = [\n  { label: '0 - Off', value: 0 },\n  { label: '1s', value: 1000 },\n  { label: '3s', value: 3000 },\n  { label: '5s', value: 5000 },\n  { label: '10s', value: 10_000 },\n  { label: '1m', value: 60_000 },\n]\n\nconst TimeDisplay = ({ offset, label }: { offset: string; label: string }) => {\n  const globalPolling = useAppSelector(selectGlobalPollingEnabled)\n  const { enabled: timesPolling } = useAppSelector((state) =>\n    selectPollingConfigByApp(state, 'times'),\n  )\n\n  const canPoll = globalPolling && timesPolling\n\n  const [pollingInterval, setPollingInterval] = useState(0)\n  const { data, refetch, isFetching } = useGetTimeQuery(offset, {\n    pollingInterval: canPoll ? pollingInterval : 0,\n  })\n\n  return (\n    <div style={{ ...(isFetching ? { background: '#e6ffe8' } : {}) }}>\n      <p>\n        {data?.time && new Date(data.time).toLocaleTimeString()} - {label}\n      </p>\n      <p>\n        <button onClick={refetch}>refetch manually</button> Polling Interval:{' '}\n        <select\n          value={pollingInterval}\n          onChange={({ target: { value } }) =>\n            setPollingInterval(Number(value))\n          }\n        >\n          {intervalOptions.map(({ label, value }) => (\n            <option key={value} value={value}>\n              {label}\n            </option>\n          ))}\n        </select>\n      </p>\n    </div>\n  )\n}\n\nconst TimeList = () => {\n  const [times, setTimes] = useState<{ [key: string]: string }>({\n    [nanoid()]: '-08:00',\n  })\n  const [selectedValue, setSelectedValue] = useState<string>('')\n\n  const prefetch = usePrefetchTime('getTime')\n\n  useEffect(() => {\n    setTimeout(() => {\n      setTimes((prev) => ({ ...prev, [nanoid()]: '+00:00' }))\n    }, 1000)\n  }, [])\n\n  return (\n    <Container>\n      <h3>\n        Add some times, even duplicates, and watch them automatically refetch in\n        sync!\n      </h3>\n      <p>\n        Notes: shared queries (aka multiple entries of the same time zone) will\n        share the lowest polling interval between them that is greater than 0.\n        If all entries are set to 0, it will stop polling. If you have two\n        entries with a polling time of 5s and one with 0 - off, it will continue\n        at 5s until they are removed or 0'd out.\n        <br />\n        Any new poll starts after the last request has either finished or failed\n        to prevent slow-running requests to immediately double-trigger.\n        <br />\n        <strong>* Background flashes green when query is running</strong>\n        <button onMouseEnter={() => prefetch('+02:00', { force: true })}>\n          Prefetch\n        </button>\n      </p>\n      <TimeZoneSelector\n        onChange={({ target: { value } }) => setSelectedValue(value)}\n      />\n      <button\n        onClick={() =>\n          setTimes((prev) => ({ ...prev, [nanoid()]: selectedValue }))\n        }\n        disabled={!selectedValue}\n      >\n        Track time\n      </button>\n      <hr />\n      {Object.entries(times).map(([key, tz]) => (\n        <TimeDisplay key={key} offset={tz} label={timezones[tz]} />\n      ))}\n    </Container>\n  )\n}\n\nexport = { timezones, TimeZoneSelector, intervalOptions, TimeDisplay, TimeList }\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/src/index.tsx",
    "content": "import React = require('react')\nimport ReactDomClient = require('react-dom/client')\nimport ReactRedux = require('react-redux')\nimport App = require('./App.js')\nimport storeModule = require('./app/store.js')\n\nimport createRoot = ReactDomClient.createRoot\nimport Provider = ReactRedux.Provider\nimport store = storeModule.store\n\nconst container = document.getElementById('root')\n\nexport = { container }\n\nif (container) {\n  const root = createRoot(container)\n\n  root.render(\n    <React.StrictMode>\n      <Provider store={store}>\n        <App />\n      </Provider>\n    </React.StrictMode>,\n  )\n} else {\n  throw new Error(\n    \"Root element with ID 'root' was not found in the document. Ensure there is a corresponding HTML element with the ID 'root' in your HTML file.\",\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-cjs/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"allowJs\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"checkJs\": true,\n    \"declaration\": true,\n    \"emitDeclarationOnly\": false,\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"isolatedModules\": true,\n    \"jsx\": \"react-jsx\",\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"noEmit\": false,\n    \"noEmitOnError\": true,\n    \"noErrorTruncation\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"outDir\": \"./dist\",\n    \"resolveJsonModule\": true,\n    \"rootDir\": \"./src\",\n    \"skipLibCheck\": true,\n    \"strict\": true,\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"useUnknownInCatchVariables\": true,\n    \"verbatimModuleSyntax\": true\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/package.json",
    "content": "{\n  \"name\": \"@examples-type-portability/nodenext-esm\",\n  \"private\": true,\n  \"version\": \"1.0.0\",\n  \"description\": \"testing type portability for moduleResolution NodeNext and type module\",\n  \"keywords\": [],\n  \"main\": \"src/index.tsx\",\n  \"type\": \"module\",\n  \"dependencies\": {\n    \"@reduxjs/toolkit\": \"workspace:^\",\n    \"react\": \"^19.2.4\",\n    \"react-dom\": \"^19.2.4\",\n    \"react-redux\": \"^9.2.0\",\n    \"react-router-dom\": \"^7.13.0\"\n  },\n  \"devDependencies\": {\n    \"@types/node\": \"^25.5.0\",\n    \"@types/react\": \"^19.2.13\",\n    \"@types/react-dom\": \"^19.2.3\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\",\n    \"vite\": \"^7.3.1\"\n  },\n  \"scripts\": {\n    \"clean\": \"rimraf dist\",\n    \"dev\": \"vite\",\n    \"build\": \"vite build\",\n    \"test\": \"yarn clean && tsc -p tsconfig.json\"\n  }\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/App.tsx",
    "content": "import { Link, Route, Routes } from 'react-router-dom'\nimport { Lazy } from './features/bundleSplitting/index.js'\nimport { CounterList } from './features/counter/CounterList.js'\nimport { PollingToggles } from './features/polling/PollingToggles.js'\nimport { PostsManager } from './features/posts/PostsManager.js'\nimport { TimeList } from './features/time/TimeList.js'\n\nexport function App() {\n  return (\n    <div className=\"App\">\n      <div className=\"row\">\n        <div className=\"column column1\">\n          <span>\n            <Link to=\"/\">Times</Link> | <Link to=\"/posts\">Posts</Link> |{' '}\n            <Link to=\"/counters\">Counter</Link> |{' '}\n            <Link to=\"/bundleSplitting\">Bundle Splitting</Link>\n          </span>\n        </div>\n        <div className=\"column column1\">\n          <PollingToggles />\n        </div>\n      </div>\n      <div />\n      <div>\n        <Routes>\n          <Route path=\"/\" element={<TimeList />} />\n          <Route path=\"/counters\" element={<CounterList />} />\n          <Route path=\"/posts/*\" element={<PostsManager />} />\n          <Route path=\"/bundleSplitting\" element={<Lazy />} />\n        </Routes>\n      </div>\n    </div>\n  )\n}\n\nexport default App\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/app/customModule.ts",
    "content": "import type {\n  Api,\n  BaseQueryFn,\n  CoreModule,\n  EndpointDefinitions,\n  Module,\n} from '@reduxjs/toolkit/query'\nimport { buildCreateApi, coreModule } from '@reduxjs/toolkit/query'\n\nexport const customModuleName = Symbol('customModule')\nexport type CustomModule = typeof customModuleName\n\n// If we remove this, We should get a TypeScript error.\ndeclare module '@reduxjs/toolkit/query' {\n  export interface ApiModules<\n    BaseQuery extends BaseQueryFn,\n    Definitions extends EndpointDefinitions,\n    ReducerPath extends string,\n    TagTypes extends string,\n  > {\n    [customModuleName]: {\n      endpoints: {\n        [K in keyof Definitions]: {\n          myEndpointProperty: string\n        }\n      }\n    }\n  }\n}\n\nexport const myModule = (): Module<CustomModule> => ({\n  name: customModuleName,\n  init(api, options, context) {\n    // initialize stuff here if you need to\n\n    return {\n      injectEndpoint(endpoint, definition) {\n        const anyApi = api as any as Api<\n          any,\n          Record<string, any>,\n          string,\n          string,\n          CustomModule | CoreModule\n        >\n        anyApi.endpoints[endpoint].myEndpointProperty = 'test'\n      },\n    }\n  },\n})\n\nexport const myCreateApi = buildCreateApi(coreModule(), myModule())\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/app/dynamicMiddleware.ts",
    "content": "import { createDynamicMiddleware } from '@reduxjs/toolkit'\n\nexport const dynamicMiddleware = createDynamicMiddleware()\n\nexport const { addMiddleware, instanceId, middleware, withMiddleware } =\n  dynamicMiddleware\n\nexport const { withTypes, match, type } = withMiddleware\n\nexport const { withTypes: _withTypes } = addMiddleware\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/app/dynamicReactMiddleware.ts",
    "content": "import { createDynamicMiddleware } from '@reduxjs/toolkit/react'\nimport { listenerMiddleware } from './listenerMiddleware.js'\n\nexport const dynamicReactMiddleware = createDynamicMiddleware()\n\nexport const {\n  addMiddleware,\n  createDispatchWithMiddlewareHook,\n  createDispatchWithMiddlewareHookFactory,\n  instanceId,\n  middleware,\n  withMiddleware,\n} = dynamicReactMiddleware\n\nexport const { withTypes } = addMiddleware\n\nexport const useDispatchWithMiddleware = createDispatchWithMiddlewareHook(\n  listenerMiddleware.middleware,\n)\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/app/hooks.ts",
    "content": "import { useDispatch, useSelector, useStore } from 'react-redux'\nimport type { AppDispatch, AppStore, RootState } from './store.js'\n\nexport const useAppDispatch = useDispatch.withTypes<AppDispatch>()\nexport const useAppSelector = useSelector.withTypes<RootState>()\nexport const useAppStore = useStore.withTypes<AppStore>()\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/app/listenerMiddleware.ts",
    "content": "import { createListenerMiddleware } from '@reduxjs/toolkit'\n\nexport const listenerMiddleware = createListenerMiddleware()\n\nexport const { clearListeners, middleware, startListening, stopListening } =\n  listenerMiddleware\n\nexport const { withTypes } = startListening\n\nexport const { withTypes: _withTypes } = stopListening\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/app/services/api.ts",
    "content": "import {\n  createApi,\n  fakeBaseQuery,\n  fetchBaseQuery,\n  retry,\n} from '@reduxjs/toolkit/query/react'\nimport type { RootState } from '../store.js'\n\nexport const baseQuery = fetchBaseQuery({\n  baseUrl: '/',\n  prepareHeaders: (headers, { getState }) => {\n    const { token } = (getState() as RootState).auth\n\n    if (token) {\n      headers.set('authentication', `Bearer ${token}`)\n    }\n\n    return headers\n  },\n})\n\nexport const baseQueryWithRetry = retry(baseQuery, { maxRetries: 6 })\n\nexport const apiSlice = createApi({\n  reducerPath: 'api',\n  baseQuery: baseQueryWithRetry,\n  tagTypes: ['Time', 'Posts', 'Counter'],\n  endpoints: () => ({}),\n})\n\nexport const enhancedApi = apiSlice.enhanceEndpoints({\n  endpoints: () => ({\n    getPost: () => 'test',\n  }),\n})\n\nexport const emptyApi = createApi({\n  baseQuery: fakeBaseQuery(),\n  endpoints: () => ({}),\n})\n\nexport const {\n  endpoints: _endpoints,\n  enhanceEndpoints: _enhanceEndpoints,\n  injectEndpoints: _injectEndpoints,\n  internalActions: _internalActions,\n  middleware: _middleware,\n  reducer: _reducer,\n  reducerPath: _reducerPath,\n  usePrefetch: _usePrefetch,\n  util: _util,\n} = apiSlice\n\nexport const {\n  endpoints,\n  enhanceEndpoints,\n  injectEndpoints,\n  internalActions,\n  middleware,\n  reducer,\n  reducerPath,\n  usePrefetch,\n  util,\n} = enhancedApi\n\nexport const {\n  cacheEntriesUpserted,\n  internal_getRTKQSubscriptions,\n  middlewareRegistered,\n  onFocus,\n  onFocusLost,\n  onOffline,\n  onOnline,\n  queryResultPatched,\n  removeMutationResult,\n  removeQueryResult,\n  resetApiState: _resetApiState,\n  subscriptionsUpdated,\n  unsubscribeQueryResult,\n  updateProvidedBy,\n  updateSubscriptionOptions,\n} = internalActions\n\nexport const { match, type } = updateSubscriptionOptions\n\nexport const {\n  getRunningMutationsThunk,\n  getRunningMutationThunk,\n  getRunningQueriesThunk,\n  getRunningQueryThunk,\n  invalidateTags,\n  patchQueryData,\n  prefetch,\n  resetApiState,\n  selectCachedArgsForQuery,\n  selectInvalidatedBy,\n  updateQueryData,\n  upsertQueryData,\n  upsertQueryEntries,\n} = util\n\nexport const { match: _match, type: _type } = invalidateTags\n\nexport const { match: __match } = upsertQueryEntries\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/app/services/counter.ts",
    "content": "import { apiSlice } from './api.js'\n\nexport interface CountResponse {\n  count: number\n}\n\nexport const counterApi = apiSlice.injectEndpoints({\n  endpoints: (build) => ({\n    getCount: build.query<CountResponse, void>({\n      query: () => 'count',\n      providesTags: ['Counter'],\n    }),\n    incrementCount: build.mutation<CountResponse, number>({\n      query(amount) {\n        return {\n          url: `increment`,\n          method: 'PUT',\n          body: { amount },\n        }\n      },\n      invalidatesTags: ['Counter'],\n    }),\n    decrementCount: build.mutation<CountResponse, number>({\n      query(amount) {\n        return {\n          url: `decrement`,\n          method: 'PUT',\n          body: { amount },\n        }\n      },\n      invalidatesTags: ['Counter'],\n    }),\n  }),\n})\n\nexport const {\n  useDecrementCountMutation,\n  useGetCountQuery,\n  useIncrementCountMutation,\n  useLazyGetCountQuery,\n  endpoints,\n  enhanceEndpoints,\n  injectEndpoints,\n  internalActions,\n  middleware,\n  reducer,\n  reducerPath,\n  usePrefetch,\n  util,\n} = counterApi\n\nexport const { decrementCount, getCount, incrementCount } = endpoints\n\nexport const {\n  cacheEntriesUpserted,\n  internal_getRTKQSubscriptions,\n  middlewareRegistered,\n  onFocus,\n  onFocusLost,\n  onOffline,\n  onOnline,\n  queryResultPatched,\n  removeMutationResult,\n  removeQueryResult,\n  resetApiState: _resetApiState,\n  subscriptionsUpdated,\n  unsubscribeQueryResult,\n  updateProvidedBy,\n  updateSubscriptionOptions,\n} = internalActions\n\nexport const { match, type } = cacheEntriesUpserted\n\nexport const { match: _match, type: _type } = updateSubscriptionOptions\n\nexport const {\n  getRunningMutationsThunk,\n  getRunningMutationThunk,\n  getRunningQueriesThunk,\n  getRunningQueryThunk,\n  invalidateTags,\n  patchQueryData,\n  prefetch,\n  resetApiState,\n  selectCachedArgsForQuery,\n  selectInvalidatedBy,\n  updateQueryData,\n  upsertQueryData,\n  upsertQueryEntries,\n} = util\n\nexport const { match: __match, type: __type } = invalidateTags\n\nexport const { match: ___match } = upsertQueryEntries\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/app/services/post.ts",
    "content": "import { apiSlice } from './api.js'\nimport type { Post } from './posts.js'\n\nexport const postApi = apiSlice.injectEndpoints({\n  endpoints: (build) => ({\n    addPost: build.mutation<Post, Partial<Post>>({\n      query(body) {\n        return {\n          url: `posts`,\n          method: 'POST',\n          body,\n        }\n      },\n      invalidatesTags: ['Posts'],\n    }),\n    getPost: build.query<Post, number>({\n      query: (id) => `posts/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Posts', id }],\n    }),\n    updatePost: build.mutation<Post, Partial<Post>>({\n      query(data) {\n        const { id, ...body } = data\n        return {\n          url: `posts/${id}`,\n          method: 'PUT',\n          body,\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n    deletePost: build.mutation<{ success: boolean; id: number }, number>({\n      query(id) {\n        return {\n          url: `posts/${id}`,\n          method: 'DELETE',\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n  }),\n})\n\nexport const {\n  endpoints,\n  enhanceEndpoints,\n  injectEndpoints,\n  internalActions,\n  middleware,\n  reducer,\n  reducerPath,\n  useAddPostMutation,\n  useDeletePostMutation,\n  useGetPostQuery,\n  useLazyGetPostQuery,\n  usePrefetch,\n  useUpdatePostMutation,\n  util,\n} = postApi\n\nexport const { addPost, deletePost, getPost, updatePost } = endpoints\n\nexport const {\n  Types,\n  initiate,\n  matchFulfilled,\n  matchPending,\n  matchRejected,\n  name,\n  select,\n  useMutation,\n} = addPost\n\nexport const {\n  BaseQuery,\n  MutationDefinition,\n  QueryArg,\n  RawResultType,\n  ReducerPath,\n  ResultType,\n  TagTypes,\n} = Types\n\nexport const {\n  argSchema,\n  catchSchemaFailure,\n  errorResponseSchema,\n  extraOptions,\n  invalidatesTags,\n  metaSchema,\n  onCacheEntryAdded,\n  onQueryStarted,\n  onSchemaFailure,\n  providesTags,\n  query,\n  queryFn,\n  rawErrorResponseSchema,\n  rawResponseSchema,\n  responseSchema,\n  skipSchemaValidation,\n  structuralSharing,\n  transformErrorResponse,\n  transformResponse,\n  type: __type,\n  Types: _Types,\n} = MutationDefinition\n\nexport const { fetched_at, id, name: _name } = QueryArg\n\nexport const {\n  cacheEntriesUpserted,\n  internal_getRTKQSubscriptions,\n  middlewareRegistered,\n  onFocus,\n  onFocusLost,\n  onOffline,\n  onOnline,\n  queryResultPatched,\n  removeMutationResult,\n  removeQueryResult,\n  resetApiState: _resetApiState,\n  subscriptionsUpdated,\n  unsubscribeQueryResult,\n  updateProvidedBy,\n  updateSubscriptionOptions,\n} = internalActions\n\nexport const { match, type } = cacheEntriesUpserted\n\nexport const { match: _match, type: _type } = updateSubscriptionOptions\n\nexport const {\n  getRunningMutationsThunk,\n  getRunningMutationThunk,\n  getRunningQueriesThunk,\n  getRunningQueryThunk,\n  invalidateTags,\n  patchQueryData,\n  prefetch,\n  resetApiState,\n  selectCachedArgsForQuery,\n  selectInvalidatedBy,\n  updateQueryData,\n  upsertQueryData,\n  upsertQueryEntries,\n} = util\n\nexport const { match: __match } = upsertQueryEntries\n\nexport const { match: ___match, type: ___type } = invalidateTags\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/app/services/posts.ts",
    "content": "import { retry } from '@reduxjs/toolkit/query/react'\nimport { apiSlice } from './api.js'\n\nexport interface Post {\n  id: number\n  name: string\n  fetched_at: string\n}\n\nexport type PostsResponse = Post[]\n\nexport interface User {\n  first_name: string\n  last_name: string\n  email: string\n  phone: string\n}\n\nexport const postsApi = apiSlice.injectEndpoints({\n  endpoints: (build) => ({\n    login: build.mutation<{ token: string; user: User }, any>({\n      query: (credentials: any) => ({\n        url: 'login',\n        method: 'POST',\n        body: credentials,\n      }),\n      extraOptions: {\n        backoff: () => {\n          // We intentionally error once on login, and this breaks out of retrying. The next login attempt will succeed.\n          retry.fail({ fake: 'error' })\n        },\n      },\n    }),\n    getPosts: build.query<PostsResponse, void>({\n      query: () => ({ url: 'posts' }),\n      providesTags: (result = []) => [\n        ...result.map(({ id }) => ({ type: 'Posts', id }) as const),\n        { type: 'Posts' as const, id: 'LIST' },\n      ],\n    }),\n    addPost: build.mutation<Post, Partial<Post>>({\n      query: (body) => ({\n        url: `posts`,\n        method: 'POST',\n        body,\n      }),\n      invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n    }),\n    getPost: build.query<Post, number>({\n      query: (id) => `posts/${id}`,\n      providesTags: (_post, _err, id) => [{ type: 'Posts', id }],\n    }),\n    updatePost: build.mutation<Post, Partial<Post>>({\n      query(data) {\n        const { id, ...body } = data\n        return {\n          url: `posts/${id}`,\n          method: 'PUT',\n          body,\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n    deletePost: build.mutation<{ success: boolean; id: number }, number>({\n      query(id) {\n        return {\n          url: `posts/${id}`,\n          method: 'DELETE',\n        }\n      },\n      invalidatesTags: (post) => [{ type: 'Posts', id: post?.id }],\n    }),\n    getErrorProne: build.query<{ success: boolean }, void>({\n      query: () => 'error-prone',\n    }),\n    getInfinitePosts: build.infiniteQuery<PostsResponse, void, number>({\n      queryFn: ({ pageParam = 0 }) => ({\n        data: [],\n      }),\n      infiniteQueryOptions: {\n        initialPageParam: 0,\n        getNextPageParam: (lastPage) =>\n          lastPage.length === 0 ? undefined : lastPage[lastPage.length - 1].id,\n      },\n    }),\n  }),\n})\n\nexport const {\n  useAddPostMutation,\n  useDeletePostMutation,\n  useGetPostQuery,\n  useGetPostsQuery,\n  useLoginMutation,\n  useUpdatePostMutation,\n  useGetErrorProneQuery,\n  useLazyGetErrorProneQuery,\n  useLazyGetPostQuery,\n  useLazyGetPostsQuery,\n  useGetInfinitePostsInfiniteQuery,\n  endpoints,\n  enhanceEndpoints,\n  injectEndpoints,\n  internalActions,\n  middleware,\n  reducer,\n  reducerPath,\n  usePrefetch,\n  util,\n} = postsApi\n\nexport const {\n  addPost,\n  deletePost,\n  getErrorProne,\n  getPost,\n  getPosts,\n  login,\n  updatePost,\n  getInfinitePosts,\n} = endpoints\n\nexport const {\n  Types,\n  initiate,\n  matchFulfilled,\n  matchPending,\n  matchRejected,\n  name,\n  select,\n  useMutation,\n} = addPost\n\nexport const {\n  Types: _Types,\n  initiate: _initiate,\n  matchFulfilled: _matchFulfilled,\n  matchPending: _matchPending,\n  matchRejected: _matchRejected,\n  name: _name,\n  select: _select,\n  useMutation: _useMutation,\n} = deletePost\n\nexport const {\n  Types: __Types,\n  initiate: __initiate,\n  matchFulfilled: __matchFulfilled,\n  matchPending: __matchPending,\n  matchRejected: __matchRejected,\n  name: __name,\n  select: __select,\n  useQueryState,\n  useLazyQuery,\n  useLazyQuerySubscription,\n  useQuery,\n  useQuerySubscription,\n} = getErrorProne\n\nexport const {\n  Types: ___Types,\n  initiate: ___initiate,\n  matchFulfilled: ___matchFulfilled,\n  matchPending: ___matchPending,\n  matchRejected: ___matchRejected,\n  name: ___name,\n  select: ___select,\n  useQueryState: ___useQueryState,\n  useLazyQuery: ___useLazyQuery,\n  useLazyQuerySubscription: ___useLazyQuerySubscription,\n  useQuery: ___useQuery,\n  useQuerySubscription: ___useQuerySubscription,\n} = getPost\n\nexport const {\n  Types: ____Types,\n  initiate: ____initiate,\n  matchFulfilled: ____matchFulfilled,\n  matchPending: ____matchPending,\n  matchRejected: ____matchRejected,\n  name: ____name,\n  select: ____select,\n  useMutation: ____useMutation,\n} = login\n\nexport const {\n  Types: _____Types,\n  initiate: _____initiate,\n  matchFulfilled: _____matchFulfilled,\n  matchPending: _____matchPending,\n  matchRejected: _____matchRejected,\n  name: _____name,\n  select: _____select,\n  useMutation: _____useMutation,\n} = updatePost\n\nexport const {\n  Types: ______Types,\n  initiate: ______initiate,\n  matchFulfilled: ______matchFulfilled,\n  matchPending: ______matchPending,\n  matchRejected: ______matchRejected,\n  name: ______name,\n  select: ______select,\n  useInfiniteQueryState: ______useQueryState,\n  useInfiniteQuery: ______useQuery,\n  useInfiniteQuerySubscription: ______useQuerySubscription,\n} = getInfinitePosts\n\nexport const {\n  cacheEntriesUpserted,\n  internal_getRTKQSubscriptions,\n  middlewareRegistered,\n  onFocus,\n  onFocusLost,\n  onOffline,\n  onOnline,\n  queryResultPatched,\n  removeMutationResult,\n  removeQueryResult,\n  resetApiState: _resetApiState,\n  subscriptionsUpdated,\n  unsubscribeQueryResult,\n  updateProvidedBy,\n  updateSubscriptionOptions,\n} = internalActions\n\nexport const {\n  getRunningMutationsThunk,\n  getRunningMutationThunk,\n  getRunningQueriesThunk,\n  getRunningQueryThunk,\n  invalidateTags,\n  patchQueryData,\n  prefetch,\n  resetApiState,\n  selectCachedArgsForQuery,\n  selectInvalidatedBy,\n  updateQueryData,\n  upsertQueryData,\n  upsertQueryEntries,\n} = util\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/app/services/times.ts",
    "content": "import { apiSlice } from './api.js'\n\nexport interface TimeResponse {\n  time: string\n}\n\nexport const timeApi = apiSlice.injectEndpoints({\n  endpoints: (build) => ({\n    getTime: build.query<TimeResponse, string>({\n      query: (id) => `time/${id}`,\n      providesTags: (_result, _err, id) => [{ type: 'Time', id }],\n    }),\n  }),\n})\n\nexport const {\n  useLazyGetTimeQuery,\n  usePrefetch: usePrefetchTime,\n  useGetTimeQuery,\n  endpoints,\n  enhanceEndpoints,\n  injectEndpoints,\n  internalActions,\n  middleware,\n  reducer,\n  reducerPath,\n  util,\n} = timeApi\n\nexport const { getTime } = endpoints\n\nexport const {\n  Types,\n  initiate,\n  matchFulfilled,\n  matchPending,\n  matchRejected,\n  name,\n  select,\n  useQuery,\n  useLazyQuery,\n  useQuerySubscription,\n  useQueryState,\n  useLazyQuerySubscription,\n} = getTime\n\nexport const {\n  cacheEntriesUpserted,\n  internal_getRTKQSubscriptions,\n  middlewareRegistered,\n  onFocus,\n  onFocusLost,\n  onOffline,\n  onOnline,\n  queryResultPatched,\n  removeMutationResult,\n  removeQueryResult,\n  resetApiState: _resetApiState,\n  subscriptionsUpdated,\n  unsubscribeQueryResult,\n  updateProvidedBy,\n  updateSubscriptionOptions,\n} = internalActions\n\nexport const {\n  getRunningMutationsThunk,\n  getRunningMutationThunk,\n  getRunningQueriesThunk,\n  getRunningQueryThunk,\n  invalidateTags,\n  patchQueryData,\n  prefetch,\n  resetApiState,\n  selectCachedArgsForQuery,\n  selectInvalidatedBy,\n  updateQueryData,\n  upsertQueryData,\n  upsertQueryEntries,\n} = util\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/app/store.ts",
    "content": "import { combineSlices, configureStore } from '@reduxjs/toolkit'\nimport { setupListeners } from '@reduxjs/toolkit/query'\nimport { authSlice } from '../features/auth/authSlice.js'\nimport { pollingSlice } from '../features/polling/pollingSlice.js'\nimport { dynamicMiddleware } from './dynamicMiddleware.js'\nimport { dynamicReactMiddleware } from './dynamicReactMiddleware.js'\nimport { listenerMiddleware } from './listenerMiddleware.js'\nimport { apiSlice } from './services/api.js'\n\nexport const rootReducer = combineSlices(pollingSlice, authSlice, apiSlice)\n\nexport const { inject, selector, withLazyLoadedSlices } = rootReducer\n\nexport const { original } = selector\n\nexport type RootState = ReturnType<typeof rootReducer>\n\nexport const setupStore = (preloadedState?: Partial<RootState>) =>\n  configureStore({\n    reducer: rootReducer,\n    middleware: (getDefaultMiddleware) =>\n      getDefaultMiddleware()\n        .prepend(listenerMiddleware.middleware)\n        .prepend(dynamicMiddleware.middleware)\n        .prepend(dynamicReactMiddleware.middleware)\n        .concat(apiSlice.middleware),\n    preloadedState,\n    enhancers: (getDefaultEnhancers) => getDefaultEnhancers(),\n  })\n\nexport const store = setupStore()\n\nsetupListeners(store.dispatch)\n\nexport const { dispatch, getState, replaceReducer, subscribe } = store\n\nexport type AppStore = typeof store\nexport type AppDispatch = typeof store.dispatch\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/auth/authSlice.ts",
    "content": "import { createSlice } from '@reduxjs/toolkit'\nimport type { User } from '../../app/services/posts.js'\nimport { postsApi } from '../../app/services/posts.js'\n\nexport const initialState = {\n  user: null,\n  token: null,\n  isAuthenticated: false,\n} as { user: null | User; token: string | null; isAuthenticated: boolean }\n\nexport const authSlice = createSlice({\n  name: 'auth',\n  initialState,\n  reducers: {\n    logout: () => initialState,\n  },\n  extraReducers: (builder) => {\n    builder\n      .addMatcher(postsApi.endpoints.login.matchPending, (state, action) => {\n        console.log('pending', action)\n      })\n      .addMatcher(postsApi.endpoints.login.matchFulfilled, (state, action) => {\n        console.log('fulfilled', action)\n        state.user = action.payload.user\n        state.token = action.payload.token\n        state.isAuthenticated = true\n      })\n      .addMatcher(postsApi.endpoints.login.matchRejected, (state, action) => {\n        console.log('rejected', action)\n      })\n  },\n  selectors: {\n    selectIsAuthenticated: (authState) => authState.isAuthenticated,\n  },\n})\n\nexport const {\n  actions,\n  caseReducers,\n  getInitialState,\n  getSelectors,\n  injectInto,\n  name,\n  reducer,\n  reducerPath,\n  selectSlice,\n  selectors,\n} = authSlice\n\nexport const { selectIsAuthenticated } = getSelectors(selectSlice)\n\nexport const { unwrapped } = selectIsAuthenticated\n\nexport const { logout: _logout } = caseReducers\n\nexport const { logout } = authSlice.actions\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/bundleSplitting/Lazy.tsx",
    "content": "import { Suspense } from 'react'\nimport { PostsList } from './index.js'\n\nexport const Lazy = () => {\n  return (\n    <Suspense fallback={<>loading...</>}>\n      <PostsList />\n    </Suspense>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/bundleSplitting/Post.tsx",
    "content": "// import the file that injects \"post\" to make sure it has been loaded\nimport { postApi } from '../../app/services/post.js'\n\nexport function assert(\n  condition: any,\n  msg = 'Generic Assertion',\n): asserts condition {\n  if (!condition) {\n    throw new Error(`Assertion failed: ${msg}`)\n  }\n}\n\nexport const Post = ({ id }: { id: number }) => {\n  assert(postApi.endpoints.getPost?.useQuery, 'Endpoint `getPost` not loaded!')\n\n  const { data, error } = postApi.endpoints.getPost.useQuery(id)\n\n  return error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <h1>{data.name}</h1>\n  )\n}\n\nexport default Post\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/bundleSplitting/PostsList.tsx",
    "content": "import { useState } from 'react'\nimport { postsApi } from '../../app/services/posts.js'\nimport { Post } from './index.js'\n\nexport const PostsList = () => {\n  const { data, error } = postsApi.endpoints.getPosts.useQuery()\n  const [selected, select] = useState<number | undefined>()\n\n  return error ? (\n    <>there was an error</>\n  ) : !data ? (\n    <>loading</>\n  ) : (\n    <>\n      {selected && <Post id={selected} />}\n      <ul>\n        {data.map((post) => (\n          <li key={post.id}>\n            <button onClick={() => select(post.id)}>{post.name}</button>\n          </li>\n        ))}\n      </ul>\n    </>\n  )\n}\n\nexport default PostsList\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/bundleSplitting/index.ts",
    "content": "import { lazy } from 'react'\n\nexport const PostsList = lazy(() => import('./PostsList.js'))\n\nexport const Post = lazy(() => import('./Post.js'))\n\nexport { Lazy } from './Lazy.js'\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/common/Container.tsx",
    "content": "import type { FC, ReactNode } from 'react'\n\nexport const Container: FC<{ children: ReactNode }> = ({ children }) => (\n  <div style={{ textAlign: 'center', padding: 50, margin: '0 auto' }}>\n    {children}\n  </div>\n)\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/counter/Counter.tsx",
    "content": "import { useState } from 'react'\nimport {\n  useDecrementCountMutation,\n  useGetCountQuery,\n  useIncrementCountMutation,\n} from '../../app/services/counter.js'\n\nexport function Counter({\n  id,\n  onRemove,\n}: {\n  id?: string\n  onRemove?: () => void\n}) {\n  const [pollingInterval, setPollingInterval] = useState(10_000)\n  const { data } = useGetCountQuery(undefined, { pollingInterval })\n  const [increment] = useIncrementCountMutation()\n\n  const [decrement] = useDecrementCountMutation()\n\n  return (\n    <div>\n      <div>\n        <button aria-label=\"Increment value\" onClick={() => increment(1)}>\n          +\n        </button>\n        <span>{data?.count || 0}</span>\n        <button aria-label=\"Decrement value\" onClick={() => decrement(1)}>\n          -\n        </button>\n        <input\n          type=\"number\"\n          name=\"pollingInterval\"\n          value={pollingInterval}\n          onChange={({ target: { valueAsNumber } }) =>\n            setPollingInterval(valueAsNumber)\n          }\n        />\n        {onRemove && <button onClick={onRemove}>Remove {id}</button>}\n      </div>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/counter/CounterList.tsx",
    "content": "import { nanoid } from '@reduxjs/toolkit'\nimport { useState } from 'react'\nimport { Container } from '../common/Container.js'\nimport { Counter } from './Counter.js'\n\nexport const CounterList = () => {\n  const [counters, setCounters] = useState<string[]>([])\n\n  if (!counters.length) {\n    return (\n      <Container>\n        <div>No counters, why don't you add one?</div>\n        <div>\n          <button onClick={() => setCounters((prev) => [...prev, nanoid()])}>\n            Add counter\n          </button>\n        </div>\n      </Container>\n    )\n  }\n\n  return (\n    <Container>\n      <div>\n        <button onClick={() => setCounters((prev) => [...prev, nanoid()])}>\n          Add counter\n        </button>\n      </div>\n      {counters.map((id) => (\n        <Counter\n          key={id}\n          id={id}\n          onRemove={() => setCounters((prev) => prev.filter((el) => el !== id))}\n        />\n      ))}\n    </Container>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/polling/PollingToggles.tsx",
    "content": "import type { ReactNode } from 'react'\nimport { useAppDispatch, useAppSelector } from '../../app/hooks.js'\nimport {\n  selectGlobalPollingEnabled,\n  selectPollingConfigByApp,\n  toggleGlobalPolling,\n  updatePolling,\n} from './pollingSlice.js'\n\nexport const PollingToggleButton = ({\n  enabled,\n  onClick,\n  children,\n}: {\n  onClick: () => void\n  enabled: boolean\n  children?: ReactNode\n}) => {\n  return (\n    <button\n      onClick={onClick}\n      style={enabled ? { background: 'lightgreen' } : {}}\n    >\n      {children}\n    </button>\n  )\n}\n\nexport const PollingToggles = () => {\n  const dispatch = useAppDispatch()\n  const globalPolling = useAppSelector(selectGlobalPollingEnabled)\n  const timesPolling = useAppSelector((state) =>\n    selectPollingConfigByApp(state, 'times'),\n  )\n\n  return (\n    <div>\n      <small>Global Polling Configs</small>\n      <div>\n        <PollingToggleButton\n          enabled={globalPolling}\n          onClick={() => dispatch(toggleGlobalPolling())}\n        >\n          Global\n        </PollingToggleButton>\n        <PollingToggleButton\n          enabled={timesPolling.enabled}\n          onClick={() =>\n            dispatch(\n              updatePolling({ app: 'times', enabled: !timesPolling.enabled }),\n            )\n          }\n        >\n          Times\n        </PollingToggleButton>\n      </div>\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/polling/pollingSlice.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit'\nimport { createSlice } from '@reduxjs/toolkit'\nimport type { RootState } from '../../app/store.js'\n\nexport type PollingConfig = {\n  enabled: boolean\n  interval: number\n}\n\nexport type SliceState = {\n  enabled: boolean\n  apps: {\n    [key: string]: PollingConfig\n  }\n}\n\nexport const initialState: SliceState = {\n  enabled: true,\n  apps: {\n    counters: {\n      enabled: true,\n      interval: 0,\n    },\n    times: {\n      enabled: true,\n      interval: 0,\n    },\n    posts: {\n      enabled: true,\n      interval: 0,\n    },\n  },\n}\n\nexport type PollingAppKey = keyof (typeof initialState)['apps']\n\nexport const pollingSlice = createSlice({\n  name: 'polling',\n  initialState,\n  reducers: (creators) => {\n    return {\n      toggleGlobalPolling: creators.reducer((state) => {\n        state.enabled = !state.enabled\n      }),\n      updatePolling(\n        state,\n        {\n          payload,\n        }: PayloadAction<{\n          app: PollingAppKey\n          enabled?: boolean\n          interval?: number\n        }>,\n      ) {\n        const { app, ...rest } = payload\n        state.apps[app] = {\n          ...state.apps[app],\n          ...rest,\n        }\n      },\n    }\n  },\n  selectors: {\n    selectGlobalPollingEnabled: (pollingState) => pollingState.enabled,\n  },\n})\n\nexport const {\n  actions,\n  caseReducers,\n  getInitialState,\n  getSelectors,\n  injectInto,\n  name,\n  reducer,\n  reducerPath,\n  selectSlice,\n  selectors,\n} = pollingSlice\n\nexport const {\n  toggleGlobalPolling: _toggleGlobalPolling,\n  updatePolling: _updatePolling,\n} = caseReducers\n\nexport const { toggleGlobalPolling, updatePolling } = pollingSlice.actions\n\nexport const { selectGlobalPollingEnabled } = selectors\n\nexport const { unwrapped } = selectGlobalPollingEnabled\n\nexport const selectPollingConfigByApp = (\n  state: RootState,\n  app: PollingAppKey,\n) => state.polling.apps[app]\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/posts/PostDetail.tsx",
    "content": "import type { ChangeEvent, SubmitEventHandler } from 'react'\nimport { useState } from 'react'\nimport { useNavigate, useParams } from 'react-router-dom'\nimport { useAppSelector } from '../../app/hooks.js'\nimport {\n  useDeletePostMutation,\n  useGetPostQuery,\n  useUpdatePostMutation,\n} from '../../app/services/posts.js'\nimport { selectGlobalPollingEnabled } from '../polling/pollingSlice.js'\n\nexport const EditablePostName = ({\n  name: initialName,\n  onUpdate,\n  onCancel,\n  loading = false,\n}: {\n  name: string\n  onUpdate: (name: string) => void\n  onCancel: () => void\n  loading?: boolean\n}) => {\n  const [name, setName] = useState(initialName)\n\n  const handleChange = ({ target: { value } }: ChangeEvent<HTMLInputElement>) =>\n    setName(value)\n\n  const handleSubmit: SubmitEventHandler<HTMLFormElement> = (e) => {\n    e.preventDefault()\n    onUpdate(name)\n  }\n  const handleCancel = () => onCancel()\n\n  return (\n    <div>\n      <form onSubmit={handleSubmit}>\n        <input\n          type=\"text\"\n          onChange={handleChange}\n          value={name}\n          disabled={loading}\n        />\n        <button type=\"submit\" disabled={loading}>\n          {loading ? 'Updating...' : 'Update'}\n        </button>\n        <button onClick={handleCancel} disabled={loading}>\n          Cancel\n        </button>\n      </form>\n    </div>\n  )\n}\n\nexport const PostJsonDetail = ({ id }: { id: number }) => {\n  const { data: post } = useGetPostQuery(id)\n\n  return (\n    <div className=\"row\" style={{ background: '#eee' }}>\n      <pre>{JSON.stringify(post, null, 2)}</pre>\n    </div>\n  )\n}\n\nexport const PostDetail = () => {\n  const { id } = useParams<{ id: any }>()\n  const navigate = useNavigate()\n  const globalPolling = useAppSelector(selectGlobalPollingEnabled)\n\n  const [isEditing, setIsEditing] = useState(false)\n\n  const {\n    data: post,\n    isFetching,\n    isLoading,\n  } = useGetPostQuery(id, { pollingInterval: globalPolling ? 3000 : 0 })\n\n  const [updatePost, { isLoading: isUpdating }] = useUpdatePostMutation()\n  const [deletePost, { isLoading: isDeleting }] = useDeletePostMutation()\n\n  if (isLoading) {\n    return <div>Loading...</div>\n  }\n\n  if (!post) {\n    return <div>Missing post!</div>\n  }\n\n  return (\n    <div>\n      {isEditing ? (\n        <EditablePostName\n          name={post.name}\n          onUpdate={(name) =>\n            updatePost({ id, name })\n              .then((result) => {\n                // handle the success!\n                console.log('Update Result', result)\n                setIsEditing(false)\n              })\n              .catch((error) => console.error('Update Error', error))\n          }\n          onCancel={() => setIsEditing(false)}\n          loading={isUpdating}\n        />\n      ) : (\n        <div className=\"row\">\n          <div className=\"column\">\n            <h3>\n              {post.name} {isFetching ? '...refetching' : ''}\n            </h3>\n          </div>\n          <button\n            onClick={() => setIsEditing(true)}\n            disabled={isDeleting || isUpdating}\n          >\n            {isUpdating ? 'Updating...' : 'Edit'}\n          </button>\n          <button\n            onClick={() => deletePost(id).then(() => navigate('/posts'))}\n            disabled={isDeleting}\n          >\n            {isDeleting ? 'Deleting...' : 'Delete'}\n          </button>\n        </div>\n      )}\n      <PostJsonDetail id={id} />\n    </div>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/posts/PostsManager.tsx",
    "content": "import type { ChangeEvent, SubmitEventHandler } from 'react'\nimport { useState } from 'react'\nimport { useDispatch, useSelector } from 'react-redux'\nimport { Route, Routes, useNavigate } from 'react-router-dom'\nimport type { Post } from '../../app/services/posts.js'\nimport {\n  useAddPostMutation,\n  useGetErrorProneQuery,\n  useGetInfinitePostsInfiniteQuery,\n  useGetPostsQuery,\n  useLoginMutation,\n} from '../../app/services/posts.js'\nimport { logout, selectIsAuthenticated } from '../auth/authSlice.js'\nimport { PostDetail } from './PostDetail.js'\n\nexport const AddPost = () => {\n  const initialValue = { name: '' }\n  const [post, setPost] = useState<Partial<Post>>(initialValue)\n  const [addPost, { isLoading }] = useAddPostMutation()\n\n  const handleChange = ({ target }: ChangeEvent<HTMLInputElement>) => {\n    setPost((prev) => ({\n      ...prev,\n      [target.name]: target.value,\n    }))\n  }\n\n  const handleSubmit: SubmitEventHandler<HTMLFormElement> = async (e) => {\n    e.preventDefault()\n    await addPost(post)\n    setPost(initialValue)\n  }\n\n  return (\n    <form onSubmit={handleSubmit}>\n      <div className=\"row\">\n        <div className=\"column column-3\">\n          <input\n            name=\"name\"\n            placeholder=\"New post name\"\n            type=\"text\"\n            onChange={handleChange}\n            value={post.name}\n          />\n        </div>\n        <div className=\"column column-1\">\n          <button type=\"submit\" disabled={isLoading}>\n            {isLoading ? 'Adding...' : 'Add Post'}\n          </button>\n        </div>\n      </div>\n    </form>\n  )\n}\n\nexport const PostListItem = ({\n  data: { name, id },\n  onSelect,\n}: {\n  data: Post\n  onSelect: (id: number) => void\n}) => {\n  return (\n    <li>\n      <a href=\"#\" onClick={() => onSelect(id)}>\n        {name}\n      </a>\n    </li>\n  )\n}\n\nexport const PostList = () => {\n  const { data: posts, isLoading } = useGetPostsQuery()\n  useGetInfinitePostsInfiniteQuery()\n  const navigate = useNavigate()\n\n  if (isLoading) {\n    return <div>Loading</div>\n  }\n\n  if (!posts) {\n    return <div>No posts :(</div>\n  }\n\n  return (\n    <div>\n      {posts.map((post) => (\n        <PostListItem\n          key={post.id}\n          data={post}\n          onSelect={(id) => navigate(`/posts/${id}`)}\n        />\n      ))}\n    </div>\n  )\n}\n\nexport const PostsManager = () => {\n  const [login] = useLoginMutation()\n  const [initRetries, setInitRetries] = useState(false)\n  const { data, error, isFetching } = useGetErrorProneQuery(undefined, {\n    skip: !initRetries,\n  })\n  const dispatch = useDispatch()\n  const isAuthenticated = useSelector(selectIsAuthenticated)\n\n  return (\n    <div>\n      <h3>Posts</h3>\n      {!isAuthenticated ? (\n        <button\n          onClick={() => login({ ignore: 'This will just set the headers' })}\n        >\n          Login\n        </button>\n      ) : (\n        <button onClick={() => dispatch(logout())}>Logout</button>\n      )}\n      <button onClick={() => setInitRetries(true)}>\n        {isFetching ? 'retrying...' : 'Start error prone retries'}\n      </button>\n      <hr />\n      <div className=\"row\">\n        <div className=\"posts-list\">\n          <AddPost />\n          <hr />\n          Posts:\n          <PostList />\n          <hr />\n          List with duplicate subscription:\n          <PostList />\n        </div>\n        <div className=\"column column-3 text-left\">\n          <Routes>\n            <Route path=\"/:id\" element={<PostDetail />} />\n          </Routes>\n        </div>\n      </div>\n    </div>\n  )\n}\n\nexport default PostsManager\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/features/time/TimeList.tsx",
    "content": "import { nanoid } from '@reduxjs/toolkit'\nimport * as React from 'react'\nimport { useEffect } from 'react'\nimport { useAppSelector } from '../../app/hooks.js'\nimport { useGetTimeQuery, usePrefetchTime } from '../../app/services/times.js'\nimport { Container } from '../common/Container.js'\nimport {\n  selectGlobalPollingEnabled,\n  selectPollingConfigByApp,\n} from '../polling/pollingSlice.js'\n\nexport const timezones: Record<string, string> = {\n  '-12:00': '(GMT -12:00) Eniwetok, Kwajalein',\n  '-11:00': '(GMT -11:00) Midway Island, Samoa',\n  '-10:00': '(GMT -10:00) Hawaii',\n  '-09:50': '(GMT -9:30) Taiohae',\n  '-09:00': '(GMT -9:00) Alaska',\n  '-08:00': '(GMT -8:00) Pacific Time (US & Canada)',\n  '-07:00': '(GMT -7:00) Mountain Time (US & Canada)',\n  '-06:00': '(GMT -6:00) Central Time (US & Canada), Mexico City',\n  '-05:00': '(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima',\n  '-04:50': '(GMT -4:30) Caracas',\n  '-04:00': '(GMT -4:00) Atlantic Time (Canada), Caracas, La Paz',\n  '-03:50': '(GMT -3:30) Newfoundland',\n  '-03:00': '(GMT -3:00) Brazil, Buenos Aires, Georgetown',\n  '-02:00': '(GMT -2:00) Mid-Atlantic',\n  '-01:00': '(GMT -1:00) Azores, Cape Verde Islands',\n  '+00:00': '(GMT) Western Europe Time, London, Lisbon, Casablanca',\n  '+01:00': '(GMT +1:00) Brussels, Copenhagen, Madrid, Paris',\n  '+02:00': '(GMT +2:00) Kaliningrad, South Africa',\n  '+03:00': '(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg',\n  '+03:50': '(GMT +3:30) Tehran',\n  '+04:00': '(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi',\n  '+04:50': '(GMT +4:30) Kabul',\n  '+05:00': '(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent',\n  '+05:50': '(GMT +5:30) Bombay, Calcutta, Madras, New Delhi',\n  '+05:75': '(GMT +5:45) Kathmandu, Pokhara',\n  '+06:00': '(GMT +6:00) Almaty, Dhaka, Colombo',\n  '+06:50': '(GMT +6:30) Yangon, Mandalay',\n  '+07:00': '(GMT +7:00) Bangkok, Hanoi, Jakarta',\n  '+08:00': '(GMT +8:00) Beijing, Perth, Singapore, Hong Kong',\n  '+08:75': '(GMT +8:45) Eucla',\n  '+09:00': '(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk',\n  '+09:50': '(GMT +9:30) Adelaide, Darwin',\n  '+10:00': '(GMT +10:00) Eastern Australia, Guam, Vladivostok',\n  '+10:50': '(GMT +10:30) Lord Howe Island',\n  '+11:00': '(GMT +11:00) Magadan, Solomon Islands, New Caledonia',\n  '+11:50': '(GMT +11:30) Norfolk Island',\n  '+12:00': '(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka',\n  '+12:75': '(GMT +12:45) Chatham Islands',\n  '+13:00': '(GMT +13:00) Apia, Nukualofa',\n  '+14:00': '(GMT +14:00) Line Islands, Tokelau',\n}\n\nexport const TimeZoneSelector = ({\n  onChange,\n}: {\n  onChange: (event: React.ChangeEvent<HTMLSelectElement>) => void\n}) => {\n  return (\n    <select name=\"timezone_offset\" id=\"timezone-offset\" onChange={onChange}>\n      <option value=\"\">Select one...</option>\n      {Object.entries(timezones).map(([value, description]) => (\n        <option key={value} value={value}>\n          {description}\n        </option>\n      ))}\n    </select>\n  )\n}\n\nexport const intervalOptions = [\n  { label: '0 - Off', value: 0 },\n  { label: '1s', value: 1000 },\n  { label: '3s', value: 3000 },\n  { label: '5s', value: 5000 },\n  { label: '10s', value: 10_000 },\n  { label: '1m', value: 60_000 },\n]\n\nexport const TimeDisplay = ({ offset, label }: { offset: string; label: string }) => {\n  const globalPolling = useAppSelector(selectGlobalPollingEnabled)\n  const { enabled: timesPolling } = useAppSelector((state) =>\n    selectPollingConfigByApp(state, 'times'),\n  )\n\n  const canPoll = globalPolling && timesPolling\n\n  const [pollingInterval, setPollingInterval] = React.useState(0)\n  const { data, refetch, isFetching } = useGetTimeQuery(offset, {\n    pollingInterval: canPoll ? pollingInterval : 0,\n  })\n\n  return (\n    <div style={{ ...(isFetching ? { background: '#e6ffe8' } : {}) }}>\n      <p>\n        {data?.time && new Date(data.time).toLocaleTimeString()} - {label}\n      </p>\n      <p>\n        <button onClick={refetch}>refetch manually</button> Polling Interval:{' '}\n        <select\n          value={pollingInterval}\n          onChange={({ target: { value } }) =>\n            setPollingInterval(Number(value))\n          }\n        >\n          {intervalOptions.map(({ label, value }) => (\n            <option key={value} value={value}>\n              {label}\n            </option>\n          ))}\n        </select>\n      </p>\n    </div>\n  )\n}\n\nexport const TimeList = () => {\n  const [times, setTimes] = React.useState<{ [key: string]: string }>({\n    [nanoid()]: '-08:00',\n  })\n  const [selectedValue, setSelectedValue] = React.useState<string>('')\n\n  const prefetch = usePrefetchTime('getTime')\n\n  useEffect(() => {\n    setTimeout(() => {\n      setTimes((prev) => ({ ...prev, [nanoid()]: '+00:00' }))\n    }, 1000)\n  }, [])\n\n  return (\n    <Container>\n      <h3>\n        Add some times, even duplicates, and watch them automatically refetch in\n        sync!\n      </h3>\n      <p>\n        Notes: shared queries (aka multiple entries of the same time zone) will\n        share the lowest polling interval between them that is greater than 0.\n        If all entries are set to 0, it will stop polling. If you have two\n        entries with a polling time of 5s and one with 0 - off, it will continue\n        at 5s until they are removed or 0'd out.\n        <br />\n        Any new poll starts after the last request has either finished or failed\n        to prevent slow-running requests to immediately double-trigger.\n        <br />\n        <strong>* Background flashes green when query is running</strong>\n        <button onMouseEnter={() => prefetch('+02:00', { force: true })}>\n          Prefetch\n        </button>\n      </p>\n      <TimeZoneSelector\n        onChange={({ target: { value } }) => setSelectedValue(value)}\n      />\n      <button\n        onClick={() =>\n          setTimes((prev) => ({ ...prev, [nanoid()]: selectedValue }))\n        }\n        disabled={!selectedValue}\n      >\n        Track time\n      </button>\n      <hr />\n      {Object.entries(times).map(([key, tz]) => (\n        <TimeDisplay key={key} offset={tz} label={timezones[tz]} />\n      ))}\n    </Container>\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/src/index.tsx",
    "content": "import * as React from 'react'\nimport { createRoot } from 'react-dom/client'\nimport { Provider } from 'react-redux'\nimport App from './App.js'\nimport { store } from './app/store.js'\n\nexport const container = document.getElementById('root')\n\nif (container) {\n  const root = createRoot(container)\n\n  root.render(\n    <React.StrictMode>\n      <Provider store={store}>\n        <App />\n      </Provider>\n    </React.StrictMode>,\n  )\n} else {\n  throw new Error(\n    \"Root element with ID 'root' was not found in the document. Ensure there is a corresponding HTML element with the ID 'root' in your HTML file.\",\n  )\n}\n"
  },
  {
    "path": "examples/type-portability/nodenext-esm/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"allowJs\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"checkJs\": true,\n    \"declaration\": true,\n    \"emitDeclarationOnly\": false,\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"isolatedModules\": true,\n    \"jsx\": \"react-jsx\",\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"noEmit\": false,\n    \"noEmitOnError\": true,\n    \"noErrorTruncation\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"outDir\": \"./dist\",\n    \"resolveJsonModule\": true,\n    \"rootDir\": \"./src\",\n    \"skipLibCheck\": true,\n    \"strict\": true,\n    \"target\": \"ESNext\",\n    \"useDefineForClassFields\": true,\n    \"useUnknownInCatchVariables\": true,\n    \"verbatimModuleSyntax\": true\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "netlify.toml",
    "content": "[build]\n  base    = \"website\"\n  publish = \"build\"\n  command = \"pushd ../packages/toolkit && yarn build && popd && yarn run netlify-build && ls  && cp _redirects ./build\"\n  ignore = \"git diff --quiet HEAD^ HEAD docs website\"\n\n[build.environment]\nNODE_VERSION = \"20\"\nNODE_OPTIONS = \"--max_old_space_size=4096\"\nNETLIFY_USE_YARN = \"true\"\nYARN_VERSION = \"1.22.10\"\n\n[[plugins]]\n  package = \"netlify-plugin-cache\"\n  [plugins.inputs]\n    paths = [\n      \"node_modules/.cache\",\n      \"website/node_modules/.cache\",\n      \".yarn/.cache\"\n    ]"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"rtk-monorepo\",\n  \"private\": true,\n  \"description\": \"The official, opinionated, batteries-included toolset for efficient Redux development\",\n  \"author\": \"Mark Erikson <mark@isquaredsoftware.com>\",\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/reduxjs/redux-toolkit.git\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/reduxjs/redux-toolkit/issues\"\n  },\n  \"homepage\": \"https://redux-toolkit.js.org\",\n  \"directories\": {\n    \"example\": \"example\"\n  },\n  \"workspaces\": [\n    \"packages/*\",\n    \"docs\",\n    \"website\",\n    \"examples/query/react/*\",\n    \"examples/action-listener/*\",\n    \"examples/type-portability/*\"\n  ],\n  \"devDependencies\": {\n    \"@babel/code-frame\": \"^7.24.2\",\n    \"@babel/core\": \"^7.24.3\",\n    \"@babel/generator\": \"^7.24.1\",\n    \"@babel/helper-compilation-targets\": \"^7.23.6\",\n    \"@babel/traverse\": \"^7.24.1\",\n    \"@babel/types\": \"^7.24.0\",\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"@typescript-eslint/eslint-plugin\": \"6.12.0\",\n    \"@typescript-eslint/parser\": \"6.12.0\",\n    \"eslint\": \"^7.25.0\",\n    \"eslint-config-prettier\": \"^9.1.0\",\n    \"eslint-config-react-app\": \"^7.0.1\",\n    \"eslint-plugin-flowtype\": \"^5.7.2\",\n    \"eslint-plugin-import\": \"^2.22.1\",\n    \"eslint-plugin-jsx-a11y\": \"^6.4.1\",\n    \"eslint-plugin-prettier\": \"^5.1.3\",\n    \"eslint-plugin-react\": \"^7.23.2\",\n    \"eslint-plugin-react-hooks\": \"^4.2.0\",\n    \"netlify-plugin-cache\": \"^1.0.3\",\n    \"prettier\": \"^3.2.5\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-redux\": \"^9.1.2\",\n    \"release-it\": \"^14.12.5\",\n    \"serve\": \"^14.2.0\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"scripts\": {\n    \"build\": \"yarn build:packages\",\n    \"test\": \"yarn test:packages\",\n    \"build:examples\": \"yarn workspaces foreach -A --include '@reduxjs/*' --include '@examples-query-react/*' --include '@examples-action-listener/*' -vtp run build\",\n    \"build:docs\": \"yarn workspace website run build\",\n    \"build:packages\": \"yarn workspaces foreach -A --include '@reduxjs/*' --include '@rtk-query/*' --topological-dev run build\",\n    \"test:packages\": \"yarn workspaces foreach -A --include '@reduxjs/*' --include '@rtk-query/*'  --include '@rtk-incubator/*' run test\",\n    \"dev:docs\": \"yarn workspace website run start\"\n  },\n  \"packageManager\": \"yarn@4.4.1\"\n}\n"
  },
  {
    "path": "packages/rtk-codemods/.eslintrc.json",
    "content": "{\n  \"env\": { \"node\": true },\n  \"extends\": [\"eslint:recommended\"],\n  \"ignorePatterns\": [\"node_modules\"],\n  \"parserOptions\": { \"ecmaVersion\": \"latest\" },\n  \"plugins\": [\"node\"],\n  \"rules\": {\n    \"no-unused-vars\": [0],\n    \"eol-last\": [0]\n  }\n}\n"
  },
  {
    "path": "packages/rtk-codemods/.github/workflows/ci.yml",
    "content": "name: CI\n\non:\n  push:\n    branches:\n      - master\n      - main\n      - 'v*' # older version branches\n    tags:\n      - '*'\n  pull_request: {}\n  schedule:\n    - cron: '0 6 * * 0' # weekly, on sundays\n\njobs:\n  lint:\n    name: Linting\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n      - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: 24.x\n      - name: install dependencies\n        run: yarn install --frozen-lockfile\n      - name: linting\n        run: yarn lint\n\n  test:\n    name: Tests\n    runs-on: ubuntu-latest\n\n    strategy:\n      matrix:\n        node: ['24.x']\n\n    steps:\n      - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n      - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: ${{ matrix.node }}\n      - name: install dependencies\n        run: yarn install --frozen-lockfile\n      - name: test\n        run: yarn test\n\n  floating-test:\n    name: Floating dependencies\n    runs-on: ubuntu-latest\n\n    steps:\n      - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5\n      - uses: actions/setup-node@a0853c24544627f65ddf259abe73b1d18a591444 # v5\n        with:\n          node-version: '24.x'\n      - name: install dependencies\n        run: yarn install --no-lockfile\n      - name: test\n        run: yarn test\n"
  },
  {
    "path": "packages/rtk-codemods/.gitignore",
    "content": "# Dependencies\n/node_modules\n\n# Production\n/build\n\n# Generated files\n.docusaurus\n.cache-loader\n\n# Misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n.cache\n.yarnrc\n.yarn/*\n!.yarn/patches\n!.yarn/releases\n!.yarn/plugins\n!.yarn/sdks\n!.yarn/versions\n.pnp.*\n*.tgz\n\n/.eslintcache\n"
  },
  {
    "path": "packages/rtk-codemods/.prettierrc.json",
    "content": "{\n  \"singleQuote\": true,\n  \"trailingComma\": \"none\",\n  \"printWidth\": 80,\n  \"semi\": false\n}\n"
  },
  {
    "path": "packages/rtk-codemods/.release-it.json",
    "content": "{\n  \"hooks\": {\n    \"after:bump\": \"yarn && git add -u\"\n  },\n  \"git\": {\n    \"commitMessage\": \"Release @reduxjs/rtk-codemods ${version}\",\n    \"tagName\": \"@reduxjs/rtk-codemods@${version}\"\n  },\n  \"npm\": {\n    \"publish\": false\n  }\n}\n"
  },
  {
    "path": "packages/rtk-codemods/README.md",
    "content": "# RTK Codemods\n\nA collection of codemods for updating legacy Redux Toolkit API usage patterns to modern patterns.\n\n## Usage\n\nTo run a specific codemod from this project, you would run the following:\n\n```bash\nnpx @reduxjs/rtk-codemods <TRANSFORM NAME> path/of/files/ or/some**/*glob.js\n\n# or\n\nyarn global add @reduxjs/rtk-codemods\nrtk-codemods <TRANSFORM NAME> path/of/files/ or/some**/*glob.js\n```\n\n## Local Usage\n\n```\nnode ./bin/cli.mjs <TRANSFORM NAME> path/of/files/ or/some**/*glob.js\n```\n\n## Transforms\n\n<!--TRANSFORMS_START-->\n\n- [createReducerBuilder](transforms/createReducerBuilder/README.md)\n- [createSliceBuilder](transforms/createSliceBuilder/README.md)\n- [createSliceReducerBuilder](transforms/createSliceReducerBuilder/README.md)\n<!--TRANSFORMS_END-->\n\n## Contributing\n\n### Installation\n\n- clone the repo\n- change into the repo directory\n- `yarn`\n\n### Running tests\n\n- `yarn test`\n\n### Update Documentation\n\n- `yarn update-docs`\n"
  },
  {
    "path": "packages/rtk-codemods/bin/cli.mjs",
    "content": "#!/usr/bin/env node\nimport { execaSync } from 'execa'\nimport { globbySync } from 'globby'\nimport { createRequire } from 'node:module'\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst require = createRequire(import.meta.url)\n\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = path.dirname(__filename)\n\nconst transformerDirectory = path.join(\n  __dirname,\n  '..',\n  'transforms',\n  `${process.argv[2]}/index.ts`\n)\n\nconst jscodeshiftExecutable = require.resolve('.bin/jscodeshift')\n\nconst extensions = 'ts,js,tsx,jsx'\n\nexecaSync(\n  jscodeshiftExecutable,\n  [\n    '-t',\n    transformerDirectory,\n    '--extensions',\n    extensions,\n    ...(process.argv.slice(3).length === 1\n      ? globbySync(process.argv[3])\n      : globbySync(process.argv.slice(3)))\n  ],\n  {\n    stdio: 'inherit',\n    stripFinalNewline: false\n  }\n)\n"
  },
  {
    "path": "packages/rtk-codemods/package.json",
    "content": "{\n  \"name\": \"@reduxjs/rtk-codemods\",\n  \"version\": \"0.1.2\",\n  \"scripts\": {\n    \"lint\": \"eslint .\",\n    \"test\": \"vitest --run\",\n    \"test:watch\": \"vitest --watch\",\n    \"test:coverage\": \"vitest --coverage\"\n  },\n  \"bin\": \"./bin/cli.mjs\",\n  \"files\": [\n    \"bin/*\",\n    \"transforms/**/index.ts\",\n    \"transforms/**/README.md\",\n    \"package.json\",\n    \"README.md\"\n  ],\n  \"keywords\": [\n    \"codemod-cli\",\n    \"redux\",\n    \"redux-toolkit\",\n    \"codemod\"\n  ],\n  \"dependencies\": {\n    \"execa\": \"^8.0.1\",\n    \"globby\": \"^14.0.0\",\n    \"jscodeshift\": \"^0.15.1\",\n    \"ts-node\": \"^10.9.2\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"devDependencies\": {\n    \"@types/jscodeshift\": \"^0.11.11\",\n    \"@types/node\": \"^25.5.0\",\n    \"@typescript-eslint/parser\": \"^6.19.1\",\n    \"eslint\": \"^8.56.0\",\n    \"eslint-config-prettier\": \"^9.1.0\",\n    \"eslint-plugin-node\": \"^11.1.0\",\n    \"eslint-plugin-prettier\": \"^5.1.3\",\n    \"prettier\": \"^3.2.5\",\n    \"vitest\": \"^4\"\n  },\n  \"engines\": {\n    \"node\": \">= 16\"\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/reduxjs/redux-toolkit.git\"\n  }\n}\n"
  },
  {
    "path": "packages/rtk-codemods/transformTestUtils.ts",
    "content": "import { globbySync } from 'globby'\nimport type { Transform } from 'jscodeshift'\nimport type { TestOptions } from 'jscodeshift/src/testUtils'\nimport { runInlineTest } from 'jscodeshift/src/testUtils'\nimport fs from 'node:fs'\nimport path from 'node:path'\nimport { describe, it } from 'vitest'\n\nexport const runTransformTest = (\n  name: string,\n  transform: Transform,\n  parser: TestOptions['parser'],\n  fixturePath: string\n) => {\n  describe(name, () => {\n    globbySync('**/*.input.*', {\n      cwd: fixturePath,\n      absolute: true,\n      objectMode: true\n    })\n      .map((entry) => entry.name)\n      .forEach((filename) => {\n        const extension = path.extname(filename)\n        const testName = filename.replace(`.input${extension}`, '')\n        const testInputPath = path.join(fixturePath, `${testName}${extension}`)\n        const inputPath = path.join(\n          fixturePath,\n          `${testName}.input${extension}`\n        )\n        const outputPath = path.join(\n          fixturePath,\n          `${testName}.output${extension}`\n        )\n\n        const inputFileContent = fs.readFileSync(inputPath, 'utf8')\n\n        const expectedOutput = fs.readFileSync(outputPath, 'utf8')\n\n        describe(`${testName}${extension}`, () => {\n          it('transforms correctly', () => {\n            runInlineTest(\n              transform,\n              {},\n              {\n                path: testInputPath,\n                source: inputFileContent\n              },\n              expectedOutput,\n              { parser }\n            )\n          })\n\n          it('is idempotent', () => {\n            runInlineTest(\n              transform,\n              {},\n              {\n                path: testInputPath,\n                source: inputFileContent\n              },\n              expectedOutput,\n              { parser }\n            )\n          })\n        })\n      })\n  })\n}\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/.gitkeep",
    "content": ""
  },
  {
    "path": "packages/rtk-codemods/transforms/createReducerBuilder/README.md",
    "content": "# createReducerBuilder\n\nRewrites uses of the \"object\" syntax for Redux Toolkit's `createReducer` API to use the \"builder callback\" syntax instead, in preparation for removal of the object syntax in RTK 2.0.\n\nShould work with both JS and TS files.\n\n## Usage\n\n```bash\nnpx @reduxjs/rtk-codemods createReducerBuilder path/of/files/ or/some**/*glob.js\n\n# or\n\nyarn global add @reduxjs/rtk-codemods\nrtk-codemods createReducerBuilder path/of/files/ or/some**/*glob.js\n```\n\n## Local Usage\n\n```\nnode ./bin/cli.mjs createReducerBuilder path/of/files/ or/some**/*glob.js\n```\n\n## Input / Output\n\n<!--FIXTURES_TOC_START-->\n\n- [basic-ts](#basic-ts)\n- [basic](#basic)\n<!--FIXTURES_TOC_END-->\n\n## <!--FIXTURES_CONTENT_START-->\n\n<a id=\"basic-ts\">**basic-ts**</a>\n\n**Input** (<small>[basic-ts.input.ts](transforms\\createReducerBuilder__testfixtures__\\basic-ts.input.ts)</small>):\n\n```ts\ncreateReducer(initialState, {\n  [todoAdded]: (state: SliceState, action: PayloadAction<string>) => {\n    // stuff\n  }\n})\n\ncreateReducer(initialState, {\n  [todoAdded](state: SliceState, action: PayloadAction<string>) {\n    // stuff\n  }\n})\n```\n\n**Output** (<small>[basic-ts.output.ts](transforms\\createReducerBuilder__testfixtures__\\basic-ts.output.ts)</small>):\n\n```ts\ncreateReducer(initialState, (builder) => {\n  builder.addCase(\n    todoAdded,\n    (state: SliceState, action: PayloadAction<string>) => {\n      // stuff\n    }\n  )\n})\n\ncreateReducer(initialState, (builder) => {\n  builder.addCase(\n    todoAdded,\n    (state: SliceState, action: PayloadAction<string>) => {\n      // stuff\n    }\n  )\n})\n```\n\n---\n\n<a id=\"basic\">**basic**</a>\n\n**Input** (<small>[basic.input.js](transforms\\createReducerBuilder__testfixtures__\\basic.input.js)</small>):\n\n```js\ncreateReducer(initialState, {\n  [todoAdded1a]: (state, action) => {\n    // stuff\n  },\n  [todoAdded1b]: (state, action) => action.payload,\n  [todoAdded1c + 'test']: (state, action) => {\n    // stuff\n  },\n  [todoAdded1d](state, action) {\n    // stuff\n  },\n  [todoAdded1e]: function (state, action) {\n    // stuff\n  },\n  todoAdded1f: (state, action) => {\n    //stuff\n  }\n})\n\ncreateReducer(initialState, {\n  [todoAdded2a]: (state, action) => {\n    // stuff\n  },\n  [todoAdded2b](state, action) {\n    // stuff\n  },\n  [todoAdded2c]: function (state, action) {\n    // stuff\n  }\n})\n```\n\n**Output** (<small>[basic.output.js](transforms\\createReducerBuilder__testfixtures__\\basic.output.js)</small>):\n\n```js\ncreateReducer(initialState, (builder) => {\n  builder.addCase(todoAdded1a, (state, action) => {\n    // stuff\n  })\n\n  builder.addCase(todoAdded1b, (state, action) => action.payload)\n\n  builder.addCase(todoAdded1c + 'test', (state, action) => {\n    // stuff\n  })\n\n  builder.addCase(todoAdded1d, (state, action) => {\n    // stuff\n  })\n\n  builder.addCase(todoAdded1e, (state, action) => {\n    // stuff\n  })\n\n  builder.addCase(todoAdded1f, (state, action) => {\n    //stuff\n  })\n})\n\ncreateReducer(initialState, (builder) => {\n  builder.addCase(todoAdded2a, (state, action) => {\n    // stuff\n  })\n\n  builder.addCase(todoAdded2b, (state, action) => {\n    // stuff\n  })\n\n  builder.addCase(todoAdded2c, (state, action) => {\n    // stuff\n  })\n})\n```\n\n<!--FIXTURES_CONTENT_END-->\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createReducerBuilder/__testfixtures__/basic-ts.input.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit'\nimport { createEntityAdapter, createReducer } from '@reduxjs/toolkit'\n\nexport interface Todo {\n  id: string\n  title: string\n}\n\n// This only included to make sure the codemod does not\n// throw a runtime error when faced with TS 4.7+ syntax such as\n// the `satisfies` operator and instantiation expressions\nconst someString = 'someString' satisfies string\n\nexport const todoAdapter = createEntityAdapter<Todo>()\n\nconst todoInitialState = todoAdapter.getInitialState()\n\nexport type TodoSliceState = typeof todoInitialState\n\nconst { addOne } = todoAdapter\n\ncreateReducer(todoInitialState, {\n  [todoAdded1a]: (state: TodoSliceState, action: PayloadAction<string>) => {\n    // stuff\n  },\n  [todoAdded1b]: (state: TodoSliceState, action: PayloadAction<string>) =>\n    action.payload,\n  [todoAdded1c + 'test']: (state: TodoSliceState, action: PayloadAction<string>) => {\n    // stuff\n  },\n  [todoAdded1d](state: TodoSliceState, action: PayloadAction<string>) {\n    // stuff\n  },\n  [todoAdded1e]: function (\n    state: TodoSliceState,\n    action: PayloadAction<string>\n  ) {\n    // stuff\n  },\n  todoAdded1f: (state: TodoSliceState, action: PayloadAction<string>) => {\n    //stuff\n  },\n  [todoAdded1g]: addOne,\n  todoAdded1h: todoAdapter.addOne\n})\n\ncreateReducer(todoInitialState, {\n  [todoAdded2a]: (state: TodoSliceState, action: PayloadAction<string>) => {\n    // stuff\n  },\n  [todoAdded2b](state: TodoSliceState, action: PayloadAction<string>) {\n    // stuff\n  },\n  [todoAdded2c]: function (\n    state: TodoSliceState,\n    action: PayloadAction<string>\n  ) {\n    // stuff\n  }\n})\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createReducerBuilder/__testfixtures__/basic-ts.output.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit'\nimport { createEntityAdapter, createReducer } from '@reduxjs/toolkit'\n\nexport interface Todo {\n  id: string\n  title: string\n}\n\n// This only included to make sure the codemod does not\n// throw a runtime error when faced with TS 4.7+ syntax such as\n// the `satisfies` operator and instantiation expressions\nconst someString = 'someString' satisfies string\n\nexport const todoAdapter = createEntityAdapter<Todo>()\n\nconst todoInitialState = todoAdapter.getInitialState()\n\nexport type TodoSliceState = typeof todoInitialState\n\nconst { addOne } = todoAdapter\n\ncreateReducer(todoInitialState, (builder) => {\n  builder.addCase(todoAdded1a, (state: TodoSliceState, action: PayloadAction<string>) => {\n    // stuff\n  });\n\n  builder.addCase(\n    todoAdded1b,\n    (state: TodoSliceState, action: PayloadAction<string>) => action.payload\n  );\n\n  builder.addCase(\n    todoAdded1c + 'test',\n    (state: TodoSliceState, action: PayloadAction<string>) => {\n      // stuff\n    }\n  );\n\n  builder.addCase(todoAdded1d, (state: TodoSliceState, action: PayloadAction<string>) => {\n    // stuff\n  });\n\n  builder.addCase(todoAdded1e, (state: TodoSliceState, action: PayloadAction<string>) => {\n    // stuff\n  });\n\n  builder.addCase(todoAdded1f, (state: TodoSliceState, action: PayloadAction<string>) => {\n    //stuff\n  });\n\n  builder.addCase(todoAdded1g, addOne);\n  builder.addCase(todoAdded1h, todoAdapter.addOne);\n})\n\ncreateReducer(todoInitialState, (builder) => {\n  builder.addCase(todoAdded2a, (state: TodoSliceState, action: PayloadAction<string>) => {\n    // stuff\n  });\n\n  builder.addCase(todoAdded2b, (state: TodoSliceState, action: PayloadAction<string>) => {\n    // stuff\n  });\n\n  builder.addCase(todoAdded2c, (state: TodoSliceState, action: PayloadAction<string>) => {\n    // stuff\n  });\n})\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createReducerBuilder/__testfixtures__/basic.input.js",
    "content": "import { createEntityAdapter, createReducer } from '@reduxjs/toolkit';\n\nexport const todoAdapter = createEntityAdapter();\n\nconst todoInitialState = todoAdapter.getInitialState();\n\nconst { addOne } = todoAdapter;\n\ncreateReducer(todoInitialState, {\n    [todoAdded1a]: (state, action) => {\n        // stuff\n    },\n    [todoAdded1b]: (state, action) => action.payload,\n    [todoAdded1c + 'test']: (state, action) => {\n        // stuff\n    },\n    [todoAdded1d](state, action) {\n        // stuff\n    },\n    [todoAdded1e]: function (state, action) {\n        // stuff\n    },\n    todoAdded1f: (state, action) => {\n        //stuff\n    },\n    [todoAdded1g]: addOne,\n    todoAdded1h: todoAdapter.addOne,\n});\n\ncreateReducer(todoInitialState, {\n    [todoAdded2a]: (state, action) => {\n        // stuff\n    },\n    [todoAdded2b](state, action) {\n        // stuff\n    },\n    [todoAdded2c]: function (state, action) {\n        // stuff\n    }\n});\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createReducerBuilder/__testfixtures__/basic.output.js",
    "content": "import { createEntityAdapter, createReducer } from '@reduxjs/toolkit';\n\nexport const todoAdapter = createEntityAdapter();\n\nconst todoInitialState = todoAdapter.getInitialState();\n\nconst { addOne } = todoAdapter;\n\ncreateReducer(todoInitialState, (builder) => {\n    builder.addCase(todoAdded1a, (state, action) => {\n        // stuff\n    });\n\n    builder.addCase(todoAdded1b, (state, action) => action.payload);\n\n    builder.addCase(todoAdded1c + 'test', (state, action) => {\n        // stuff\n    });\n\n    builder.addCase(todoAdded1d, (state, action) => {\n        // stuff\n    });\n\n    builder.addCase(todoAdded1e, (state, action) => {\n        // stuff\n    });\n\n    builder.addCase(todoAdded1f, (state, action) => {\n        //stuff\n    });\n\n    builder.addCase(todoAdded1g, addOne);\n    builder.addCase(todoAdded1h, todoAdapter.addOne);\n});\n\ncreateReducer(todoInitialState, (builder) => {\n    builder.addCase(todoAdded2a, (state, action) => {\n        // stuff\n    });\n\n    builder.addCase(todoAdded2b, (state, action) => {\n        // stuff\n    });\n\n    builder.addCase(todoAdded2c, (state, action) => {\n        // stuff\n    });\n});\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createReducerBuilder/createReducerBuilder.test.ts",
    "content": "import path from 'node:path'\nimport { runTransformTest } from '../../transformTestUtils'\nimport transform, { parser } from './index'\n\nrunTransformTest(\n  'createReducerBuilder',\n  transform,\n  parser,\n  path.join(__dirname, '__testfixtures__')\n)\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createReducerBuilder/index.ts",
    "content": "import type { ExpressionKind, SpreadElementKind } from 'ast-types/gen/kinds'\nimport type {\n  ExpressionStatement,\n  JSCodeshift,\n  ObjectExpression,\n  Transform\n} from 'jscodeshift'\nimport type { TestOptions } from 'jscodeshift/src/testUtils'\n\nfunction wrapInAddCaseExpression(\n  j: JSCodeshift,\n  addCaseArgs: (ExpressionKind | SpreadElementKind)[]\n) {\n  const identifier = j.identifier('builder')\n  return j.expressionStatement(\n    j.callExpression(\n      j.memberExpression(identifier, j.identifier('addCase'), false),\n      addCaseArgs\n    )\n  )\n}\n\nexport function reducerPropsToBuilderExpression(\n  j: JSCodeshift,\n  defNode: ObjectExpression\n) {\n  const caseExpressions: ExpressionStatement[] = []\n  for (const property of defNode.properties) {\n    let addCaseArgs: (ExpressionKind | SpreadElementKind)[] = []\n    switch (property.type) {\n      case 'ObjectMethod': {\n        const { key, params, body } = property\n        if (body) {\n          addCaseArgs = [key, j.arrowFunctionExpression(params, body)]\n        }\n        break\n      }\n      case 'ObjectProperty': {\n        const { key } = property\n\n        switch (property.value.type) {\n          case 'ArrowFunctionExpression':\n          case 'FunctionExpression': {\n            const { params, body } = property.value\n            if (body) {\n              addCaseArgs = [key, j.arrowFunctionExpression(params, body)]\n            }\n            break\n          }\n          case 'Identifier':\n          case 'MemberExpression': {\n            const { value } = property\n            addCaseArgs = [key, value]\n            break\n          }\n        }\n      }\n    }\n    if (!addCaseArgs.length) {\n      continue\n    }\n    caseExpressions.push(wrapInAddCaseExpression(j, addCaseArgs))\n  }\n\n  return j.arrowFunctionExpression(\n    [j.identifier('builder')],\n    j.blockStatement(caseExpressions)\n  )\n}\n\nconst transform: Transform = (file, api) => {\n  const j = api.jscodeshift\n\n  return j(file.source)\n    .find(j.CallExpression, {\n      callee: { name: 'createReducer' },\n      arguments: [{}, { type: 'ObjectExpression' }]\n    })\n    .forEach((path) => {\n      const reducerObjectExpression = path.node.arguments[1] as ObjectExpression\n      j(path).replaceWith(\n        j.callExpression(j.identifier('createReducer'), [\n          path.node.arguments[0],\n          reducerPropsToBuilderExpression(j, reducerObjectExpression)\n        ])\n      )\n    })\n    .toSource({\n      arrowParensAlways: true,\n      lineTerminator: '\\n'\n    })\n}\n\nexport const parser = 'tsx' satisfies TestOptions['parser']\n\nexport default transform\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceBuilder/README.md",
    "content": "# createSliceBuilder\n\nRewrites uses of the `extraReducers` \"object\" syntax for Redux Toolkit's `createSlice` API to use the \"builder callback\" syntax instead, in preparation for removal of the object syntax in RTK 2.0.\n\nShould work with both JS and TS files.\n\n## Usage\n\n```bash\nnpx @reduxjs/rtk-codemods createSliceBuilder path/of/files/ or/some**/*glob.js\n\n# or\n\nyarn global add @reduxjs/rtk-codemods\nrtk-codemods createSliceBuilder path/of/files/ or/some**/*glob.js\n```\n\n## Local Usage\n\n```\nnode ./bin/cli.mjs createSliceBuilder path/of/files/ or/some**/*glob.js\n```\n\n## Input / Output\n\n<!--FIXTURES_TOC_START-->\n\n- [basic-ts](#basic-ts)\n- [basic](#basic)\n<!--FIXTURES_TOC_END-->\n\n## <!--FIXTURES_CONTENT_START-->\n\n<a id=\"basic-ts\">**basic-ts**</a>\n\n**Input** (<small>[basic-ts.input.ts](transforms\\createSliceBuilder__testfixtures__\\basic-ts.input.ts)</small>):\n\n```ts\nconst slice1 = createSlice({\n  name: 'a',\n  initialState,\n  extraReducers: {\n    [todoAdded]: (state: SliceState, action: PayloadAction<string>) => {\n      // stuff\n    }\n  }\n})\n\nconst slice2 = createSlice({\n  name: 'b',\n  initialState,\n  extraReducers: {\n    [todoAdded](state: SliceState, action: PayloadAction<string>) {\n      // stuff\n    }\n  }\n})\n```\n\n**Output** (<small>[basic-ts.output.ts](transforms\\createSliceBuilder__testfixtures__\\basic-ts.output.ts)</small>):\n\n```ts\nconst slice1 = createSlice({\n  name: 'a',\n  initialState,\n\n  extraReducers: (builder) => {\n    builder.addCase(\n      todoAdded,\n      (state: SliceState, action: PayloadAction<string>) => {\n        // stuff\n      }\n    )\n  }\n})\n\nconst slice2 = createSlice({\n  name: 'b',\n  initialState,\n\n  extraReducers: (builder) => {\n    builder.addCase(\n      todoAdded,\n      (state: SliceState, action: PayloadAction<string>) => {\n        // stuff\n      }\n    )\n  }\n})\n```\n\n---\n\n<a id=\"basic\">**basic**</a>\n\n**Input** (<small>[basic.input.js](transforms\\createSliceBuilder__testfixtures__\\basic.input.js)</small>):\n\n```js\nconst slice1 = createSlice({\n  name: 'a',\n  initialState: {},\n  extraReducers: {\n    [todoAdded1a]: (state, action) => {\n      // stuff\n    },\n    [todoAdded1b]: (state, action) => action.payload,\n    [todoAdded1c + 'test']: (state, action) => {\n      // stuff\n    },\n    [todoAdded1d](state, action) {\n      // stuff\n    },\n    [todoAdded1e]: function (state, action) {\n      // stuff\n    },\n    todoAdded1f: (state, action) => {\n      //stuff\n    }\n  }\n})\n\nconst slice2 = createSlice({\n  name: 'b',\n  initialState: {},\n  extraReducers: {\n    [todoAdded2a]: (state, action) => {\n      // stuff\n    },\n    [todoAdded2b](state, action) {\n      // stuff\n    },\n    [todoAdded2c]: function (state, action) {\n      // stuff\n    }\n  }\n})\n```\n\n**Output** (<small>[basic.output.js](transforms\\createSliceBuilder__testfixtures__\\basic.output.js)</small>):\n\n```js\nconst slice1 = createSlice({\n  name: 'a',\n  initialState: {},\n\n  extraReducers: (builder) => {\n    builder.addCase(todoAdded1a, (state, action) => {\n      // stuff\n    })\n\n    builder.addCase(todoAdded1b, (state, action) => action.payload)\n\n    builder.addCase(todoAdded1c + 'test', (state, action) => {\n      // stuff\n    })\n\n    builder.addCase(todoAdded1d, (state, action) => {\n      // stuff\n    })\n\n    builder.addCase(todoAdded1e, (state, action) => {\n      // stuff\n    })\n\n    builder.addCase(todoAdded1f, (state, action) => {\n      //stuff\n    })\n  }\n})\n\nconst slice2 = createSlice({\n  name: 'b',\n  initialState: {},\n\n  extraReducers: (builder) => {\n    builder.addCase(todoAdded2a, (state, action) => {\n      // stuff\n    })\n\n    builder.addCase(todoAdded2b, (state, action) => {\n      // stuff\n    })\n\n    builder.addCase(todoAdded2c, (state, action) => {\n      // stuff\n    })\n  }\n})\n```\n\n<!--FIXTURES_CONTENT_END-->\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceBuilder/__testfixtures__/basic-ts.input.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit';\nimport {\n  createAsyncThunk,\n  createEntityAdapter,\n  createSlice\n} from '@reduxjs/toolkit';\n\nexport interface Todo {\n  id: string\n  title: string\n}\n\nexport const todoAdapter = createEntityAdapter<Todo>()\n\nconst todoInitialState = todoAdapter.getInitialState()\n\nexport type TodoSliceState = typeof todoInitialState\n\nconst fetchCount = (amount = 1) => {\n  return new Promise<{ data: number }>((resolve) =>\n    setTimeout(() => resolve({ data: amount }), 500)\n  )\n}\n\nexport const incrementAsync = createAsyncThunk(\n  'counter/fetchCount',\n  async (amount: number) => {\n    const response = await fetchCount(amount)\n    return response.data\n  }\n)\n\nconst { addOne } = todoAdapter\n\nconst todoSlice = createSlice({\n  name: 'todo',\n  initialState: todoInitialState,\n  reducers: {\n    deleteTodo: todoAdapter.removeOne\n  },\n  extraReducers: {\n    [incrementAsync.pending]: (\n      state: TodoSliceState,\n      action: PayloadAction<string>\n    ) => {\n      // stuff\n    },\n    [incrementAsync.rejected]: todoAdapter.removeAll,\n    [incrementAsync.fulfilled](\n      state: TodoSliceState,\n      action: PayloadAction<string>) {\n      // stuff\n    },\n    todoAdded: todoAdapter.addOne,\n\n    [todoAdded1a]: (state: TodoSliceState, action: PayloadAction<string>) => {\n      // stuff\n    },\n    [todoAdded1b]: (state: TodoSliceState, action: PayloadAction<string>) => action.payload,\n    [todoAdded1c + 'test']: (state:TodoSliceState, action: PayloadAction<string>) => {\n      // stuff\n    },\n    [todoAdded1d](state: TodoSliceState, action: PayloadAction<string>) {\n      // stuff\n    },\n    [todoAdded1e]: function(state: TodoSliceState, action: PayloadAction<string>) {\n      // stuff\n    },\n    todoAdded1f: (state: TodoSliceState, action: PayloadAction<string>) => {\n      //stuff\n    },\n    [todoAdded1g]: addOne,\n    todoAdded1h: todoAdapter.addOne,\n  }\n})\n\nexport const { deleteTodo } = todoSlice.actions\n\nexport interface CounterSliceState {\n  value: number\n  status: 'idle' | 'loading' | 'failed'\n}\n\nconst counterInitialState: CounterSliceState = {\n  value: 0,\n  status: 'idle'\n}\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: counterInitialState,\n  extraReducers: {\n    [deleteTodo](state: CounterSliceState, action: PayloadAction<string>) {\n      // stuff\n    }\n  }\n})\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceBuilder/__testfixtures__/basic-ts.output.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit';\nimport {\n  createAsyncThunk,\n  createEntityAdapter,\n  createSlice\n} from '@reduxjs/toolkit';\n\nexport interface Todo {\n  id: string\n  title: string\n}\n\nexport const todoAdapter = createEntityAdapter<Todo>()\n\nconst todoInitialState = todoAdapter.getInitialState()\n\nexport type TodoSliceState = typeof todoInitialState\n\nconst fetchCount = (amount = 1) => {\n  return new Promise<{ data: number }>((resolve) =>\n    setTimeout(() => resolve({ data: amount }), 500)\n  )\n}\n\nexport const incrementAsync = createAsyncThunk(\n  'counter/fetchCount',\n  async (amount: number) => {\n    const response = await fetchCount(amount)\n    return response.data\n  }\n)\n\nconst { addOne } = todoAdapter\n\nconst todoSlice = createSlice({\n  name: 'todo',\n  initialState: todoInitialState,\n\n  reducers: {\n    deleteTodo: todoAdapter.removeOne\n  },\n\n  extraReducers: (builder) => {\n    builder.addCase(\n      incrementAsync.pending,\n      (state: TodoSliceState, action: PayloadAction<string>) => {\n        // stuff\n      }\n    );\n\n    builder.addCase(incrementAsync.rejected, todoAdapter.removeAll);\n\n    builder.addCase(\n      incrementAsync.fulfilled,\n      (state: TodoSliceState, action: PayloadAction<string>) => {\n        // stuff\n      }\n    );\n\n    builder.addCase(todoAdded, todoAdapter.addOne);\n\n    builder.addCase(todoAdded1a, (state: TodoSliceState, action: PayloadAction<string>) => {\n      // stuff\n    });\n\n    builder.addCase(\n      todoAdded1b,\n      (state: TodoSliceState, action: PayloadAction<string>) => action.payload\n    );\n\n    builder.addCase(\n      todoAdded1c + 'test',\n      (state:TodoSliceState, action: PayloadAction<string>) => {\n        // stuff\n      }\n    );\n\n    builder.addCase(todoAdded1d, (state: TodoSliceState, action: PayloadAction<string>) => {\n      // stuff\n    });\n\n    builder.addCase(todoAdded1e, (state: TodoSliceState, action: PayloadAction<string>) => {\n      // stuff\n    });\n\n    builder.addCase(todoAdded1f, (state: TodoSliceState, action: PayloadAction<string>) => {\n      //stuff\n    });\n\n    builder.addCase(todoAdded1g, addOne);\n    builder.addCase(todoAdded1h, todoAdapter.addOne);\n  }\n})\n\nexport const { deleteTodo } = todoSlice.actions\n\nexport interface CounterSliceState {\n  value: number\n  status: 'idle' | 'loading' | 'failed'\n}\n\nconst counterInitialState: CounterSliceState = {\n  value: 0,\n  status: 'idle'\n}\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: counterInitialState,\n\n  extraReducers: (builder) => {\n    builder.addCase(deleteTodo, (state: CounterSliceState, action: PayloadAction<string>) => {\n      // stuff\n    });\n  }\n})\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceBuilder/__testfixtures__/basic.input.js",
    "content": "import { createAsyncThunk, createEntityAdapter, createSlice } from '@reduxjs/toolkit';\n\nexport const todoAdapter = createEntityAdapter();\n\nconst todoInitialState = todoAdapter.getInitialState();\n\nconst fetchCount = (amount = 1) => {\n    return new Promise((resolve) => setTimeout(() => resolve({ data: amount }), 500));\n};\n\nexport const incrementAsync = createAsyncThunk('counter/fetchCount', async (amount) => {\n    const response = await fetchCount(amount);\n    return response.data;\n});\n\nconst { addOne } = todoAdapter;\n\nconst todoSlice = createSlice({\n    name: 'todo',\n    initialState: todoInitialState,\n    reducers: {\n        deleteTodo: todoAdapter.removeOne\n    },\n    extraReducers: {\n        [incrementAsync.pending]: (state, action) => {\n            // stuff\n        },\n        [incrementAsync.rejected]: todoAdapter.removeAll,\n        [incrementAsync.fulfilled](state, action) {\n            // stuff\n        },\n        todoAdded: todoAdapter.addOne,\n\n        [todoAdded1a]: (state, action) => {\n            // stuff\n        },\n        [todoAdded1b]: (state, action) => action.payload,\n        [todoAdded1c + 'test']: (state, action) => {\n            // stuff\n        },\n        [todoAdded1d](state, action) {\n            // stuff\n        },\n        [todoAdded1e]: function (state, action) {\n            // stuff\n        },\n        todoAdded1f: (state, action) => {\n            //stuff\n        },\n        [todoAdded1g]: addOne,\n        todoAdded1h: todoAdapter.addOne,\n    }\n});\n\nexport const { deleteTodo } = todoSlice.actions;\n\nconst counterInitialState = {\n    value: 0,\n    status: 'idle'\n};\n\nconst counterSlice = createSlice({\n    name: 'counter',\n    initialState: counterInitialState,\n    extraReducers: {\n        [deleteTodo](state, action) {\n            // stuff\n        }\n    }\n});\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceBuilder/__testfixtures__/basic.output.js",
    "content": "import { createAsyncThunk, createEntityAdapter, createSlice } from '@reduxjs/toolkit';\n\nexport const todoAdapter = createEntityAdapter();\n\nconst todoInitialState = todoAdapter.getInitialState();\n\nconst fetchCount = (amount = 1) => {\n    return new Promise((resolve) => setTimeout(() => resolve({ data: amount }), 500));\n};\n\nexport const incrementAsync = createAsyncThunk('counter/fetchCount', async (amount) => {\n    const response = await fetchCount(amount);\n    return response.data;\n});\n\nconst { addOne } = todoAdapter;\n\nconst todoSlice = createSlice({\n    name: 'todo',\n    initialState: todoInitialState,\n\n    reducers: {\n        deleteTodo: todoAdapter.removeOne\n    },\n\n    extraReducers: (builder) => {\n        builder.addCase(incrementAsync.pending, (state, action) => {\n            // stuff\n        });\n\n        builder.addCase(incrementAsync.rejected, todoAdapter.removeAll);\n\n        builder.addCase(incrementAsync.fulfilled, (state, action) => {\n            // stuff\n        });\n\n        builder.addCase(todoAdded, todoAdapter.addOne);\n\n        builder.addCase(todoAdded1a, (state, action) => {\n            // stuff\n        });\n\n        builder.addCase(todoAdded1b, (state, action) => action.payload);\n\n        builder.addCase(todoAdded1c + 'test', (state, action) => {\n            // stuff\n        });\n\n        builder.addCase(todoAdded1d, (state, action) => {\n            // stuff\n        });\n\n        builder.addCase(todoAdded1e, (state, action) => {\n            // stuff\n        });\n\n        builder.addCase(todoAdded1f, (state, action) => {\n            //stuff\n        });\n\n        builder.addCase(todoAdded1g, addOne);\n        builder.addCase(todoAdded1h, todoAdapter.addOne);\n    }\n});\n\nexport const { deleteTodo } = todoSlice.actions;\n\nconst counterInitialState = {\n    value: 0,\n    status: 'idle'\n};\n\nconst counterSlice = createSlice({\n    name: 'counter',\n    initialState: counterInitialState,\n\n    extraReducers: (builder) => {\n        builder.addCase(deleteTodo, (state, action) => {\n            // stuff\n        });\n    }\n});\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceBuilder/createSliceBuilder.test.ts",
    "content": "import path from 'node:path'\nimport { runTransformTest } from '../../transformTestUtils'\nimport transform, { parser } from './index'\n\nrunTransformTest(\n  'createSliceBuilder',\n  transform,\n  parser,\n  path.join(__dirname, '__testfixtures__')\n)\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceBuilder/index.ts",
    "content": "import type { ExpressionKind, SpreadElementKind } from 'ast-types/gen/kinds'\nimport type {\n  ExpressionStatement,\n  JSCodeshift,\n  ObjectExpression,\n  Transform\n} from 'jscodeshift'\nimport type { TestOptions } from 'jscodeshift/src/testUtils'\n\nfunction wrapInAddCaseExpression(\n  j: JSCodeshift,\n  addCaseArgs: (ExpressionKind | SpreadElementKind)[]\n) {\n  const identifier = j.identifier('builder')\n  return j.expressionStatement(\n    j.callExpression(\n      j.memberExpression(identifier, j.identifier('addCase'), false),\n      addCaseArgs\n    )\n  )\n}\n\nexport function reducerPropsToBuilderExpression(\n  j: JSCodeshift,\n  defNode: ObjectExpression\n) {\n  const caseExpressions: ExpressionStatement[] = []\n  for (const property of defNode.properties) {\n    let addCaseArgs: (ExpressionKind | SpreadElementKind)[] = []\n    switch (property.type) {\n      case 'ObjectMethod': {\n        const { key, params, body } = property\n        if (body) {\n          addCaseArgs = [key, j.arrowFunctionExpression(params, body)]\n        }\n        break\n      }\n      case 'ObjectProperty': {\n        const { key } = property\n\n        switch (property.value.type) {\n          case 'ArrowFunctionExpression':\n          case 'FunctionExpression': {\n            const { params, body } = property.value\n            if (body) {\n              addCaseArgs = [key, j.arrowFunctionExpression(params, body)]\n            }\n            break\n          }\n          case 'Identifier':\n          case 'MemberExpression': {\n            const { value } = property\n            addCaseArgs = [key, value]\n            break\n          }\n        }\n      }\n    }\n    if (!addCaseArgs.length) {\n      continue\n    }\n    caseExpressions.push(wrapInAddCaseExpression(j, addCaseArgs))\n  }\n\n  return j.arrowFunctionExpression(\n    [j.identifier('builder')],\n    j.blockStatement(caseExpressions)\n  )\n}\n\nconst transform: Transform = (file, api) => {\n  const j = api.jscodeshift\n\n  return j(file.source)\n    .find(j.CallExpression, {\n      callee: { name: 'createSlice' },\n      arguments: [{ type: 'ObjectExpression' }]\n    })\n\n    .filter((path) => {\n      const createSliceArgsObject = path.node.arguments[0] as ObjectExpression\n      return createSliceArgsObject.properties.some(\n        (p) =>\n          p.type === 'ObjectProperty' &&\n          p.key.type === 'Identifier' &&\n          p.key.name === 'extraReducers' &&\n          p.value.type === 'ObjectExpression'\n      )\n    })\n    .forEach((path) => {\n      const createSliceArgsObject = path.node.arguments[0] as ObjectExpression\n      j(path).replaceWith(\n        j.callExpression(j.identifier('createSlice'), [\n          j.objectExpression(\n            createSliceArgsObject.properties.map((p) => {\n              if (\n                p.type === 'ObjectProperty' &&\n                p.key.type === 'Identifier' &&\n                p.key.name === 'extraReducers' &&\n                p.value.type === 'ObjectExpression'\n              ) {\n                const expressionStatement = reducerPropsToBuilderExpression(\n                  j,\n                  p.value as ObjectExpression\n                )\n                return j.objectProperty(p.key, expressionStatement)\n              }\n              return p\n            })\n          )\n        ])\n      )\n    })\n    .toSource({\n      arrowParensAlways: true,\n      lineTerminator: '\\n'\n    })\n}\n\nexport const parser = 'tsx' satisfies TestOptions['parser']\n\nexport default transform\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceReducerBuilder/README.md",
    "content": "# createSliceReducerBuilder\n\nRewrites uses of Redux Toolkit's `createSlice` API to use the \"builder callback\" syntax for the `reducers` field, to make it easier to add prepared reducers and thunks inside of `createSlice`.\n\nNote that unlike the `createReducerBuilder` and `createSliceBuilder` transforms (which both were fixes for deprecated/removed overloads), this is entirely optional. You do not _need_ to apply this to an entire codebase unless you specifically want to. Otherwise, feel free to apply to specific slice files as needed.\n\nShould work with both JS and TS files.\n\n## Usage\n\n```\nnpx @reduxjs/rtk-codemods createSliceReducerBuilder path/of/files/ or/some**/*glob.js\n\n# or\n\nyarn global add @reduxjs/rtk-codemods\n@reduxjs/rtk-codemods createSliceReducerBuilder path/of/files/ or/some**/*glob.js\n```\n\n## Local Usage\n\n```\nnode ./bin/cli.mjs createSliceReducerBuilder path/of/files/ or/some**/*glob.js\n```\n\n## Input / Output\n\n<!--FIXTURES_TOC_START-->\n<!--FIXTURES_TOC_END-->\n\n<!--FIXTURES_CONTENT_START-->\n<!--FIXTURES_CONTENT_END-->\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceReducerBuilder/__testfixtures__/basic-ts.input.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit'\nimport { createEntityAdapter, createSlice, nanoid } from '@reduxjs/toolkit'\n\nfunction withPayload(): any {\n  throw new Error('Function not implemented.')\n}\n\nexport interface Todo {\n  id: string\n  title: string\n}\n\nexport const todoAdapter = createEntityAdapter<Todo>()\n\nconst todoSlice = createSlice({\n  name: 'todo',\n  initialState: todoAdapter.getInitialState(),\n  reducers: {\n    property: () => {},\n    method(state, action: PayloadAction<Todo>) {\n      todoAdapter.addOne(state, action)\n    },\n    identifier: todoAdapter.removeOne,\n    preparedProperty: {\n      prepare: (todo: Omit<Todo, 'id'>) => ({\n        payload: { id: nanoid(), ...todo }\n      }),\n      reducer: () => {}\n    },\n    preparedMethod: {\n      prepare(todo: Omit<Todo, 'id'>) {\n        return { payload: { id: nanoid(), ...todo } }\n      },\n      reducer(state, action: PayloadAction<Todo>) {\n        todoAdapter.addOne(state, action)\n      }\n    },\n    preparedIdentifier: {\n      prepare: withPayload(),\n      reducer: todoAdapter.setMany\n    }\n  }\n})"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceReducerBuilder/__testfixtures__/basic-ts.output.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit'\nimport { createEntityAdapter, createSlice, nanoid } from '@reduxjs/toolkit'\n\nfunction withPayload(): any {\n  throw new Error('Function not implemented.')\n}\n\nexport interface Todo {\n  id: string\n  title: string\n}\n\nexport const todoAdapter = createEntityAdapter<Todo>()\n\nconst todoSlice = createSlice({\n  name: 'todo',\n  initialState: todoAdapter.getInitialState(),\n\n  reducers: (create) => ({\n    property: create.reducer(() => {}),\n\n    method: create.reducer((state, action: PayloadAction<Todo>) => {\n      todoAdapter.addOne(state, action)\n    }),\n\n    identifier: create.reducer(todoAdapter.removeOne),\n\n    preparedProperty: create.preparedReducer((todo: Omit<Todo, 'id'>) => ({\n      payload: { id: nanoid(), ...todo }\n    }), () => {}),\n\n    preparedMethod: create.preparedReducer((todo: Omit<Todo, 'id'>) => {\n      return { payload: { id: nanoid(), ...todo } }\n    }, (state, action: PayloadAction<Todo>) => {\n      todoAdapter.addOne(state, action)\n    }),\n\n    preparedIdentifier: create.preparedReducer(withPayload(), todoAdapter.setMany)\n  })\n})"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceReducerBuilder/__testfixtures__/basic.input.js",
    "content": "import { createEntityAdapter, createSlice, nanoid } from '@reduxjs/toolkit'\n\nfunction withPayload() {\n    throw new Error('Function not implemented.')\n}\n\nexport const todoAdapter = createEntityAdapter()\n\nconst todoSlice = createSlice({\n    name: 'todo',\n    initialState: todoAdapter.getInitialState(),\n    reducers: {\n        property: () => { },\n        method(state, action) {\n            todoAdapter.addOne(state, action)\n        },\n        identifier: todoAdapter.removeOne,\n        preparedProperty: {\n            prepare: (todo) => ({\n                payload: { id: nanoid(), ...todo }\n            }),\n            reducer: () => { }\n        },\n        preparedMethod: {\n            prepare(todo) {\n                return { payload: { id: nanoid(), ...todo } }\n            },\n            reducer(state, action) {\n                todoAdapter.addOne(state, action)\n            }\n        },\n        preparedIdentifier: {\n            prepare: withPayload(),\n            reducer: todoAdapter.setMany\n        }\n    }\n})\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceReducerBuilder/__testfixtures__/basic.output.js",
    "content": "import { createEntityAdapter, createSlice, nanoid } from '@reduxjs/toolkit'\n\nfunction withPayload() {\n    throw new Error('Function not implemented.')\n}\n\nexport const todoAdapter = createEntityAdapter()\n\nconst todoSlice = createSlice({\n    name: 'todo',\n    initialState: todoAdapter.getInitialState(),\n\n    reducers: (create) => ({\n        property: create.reducer(() => { }),\n\n        method: create.reducer((state, action) => {\n            todoAdapter.addOne(state, action)\n        }),\n\n        identifier: create.reducer(todoAdapter.removeOne),\n\n        preparedProperty: create.preparedReducer((todo) => ({\n            payload: { id: nanoid(), ...todo }\n        }), () => { }),\n\n        preparedMethod: create.preparedReducer((todo) => {\n            return { payload: { id: nanoid(), ...todo } }\n        }, (state, action) => {\n            todoAdapter.addOne(state, action)\n        }),\n\n        preparedIdentifier: create.preparedReducer(withPayload(), todoAdapter.setMany)\n    })\n})\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceReducerBuilder/createSliceReducerBuilder.test.ts",
    "content": "import path from 'node:path'\nimport { runTransformTest } from '../../transformTestUtils'\nimport transform, { parser } from './index'\n\nrunTransformTest(\n  'createSliceReducerBuilder',\n  transform,\n  parser,\n  path.join(__dirname, '__testfixtures__')\n)\n"
  },
  {
    "path": "packages/rtk-codemods/transforms/createSliceReducerBuilder/index.ts",
    "content": "import type { ExpressionKind } from 'ast-types/gen/kinds'\nimport type {\n  JSCodeshift,\n  ObjectExpression,\n  ObjectProperty,\n  Transform\n} from 'jscodeshift'\nimport type { TestOptions } from 'jscodeshift/src/testUtils'\n\ntype CreatorCallRestArguments =\n  | [type: 'reducer', reducer: ExpressionKind]\n  | [type: 'preparedReducer', prepare: ExpressionKind, reducer: ExpressionKind]\n\nfunction creatorCall(j: JSCodeshift, ...rest: CreatorCallRestArguments) {\n  const [type, ...restArgs] = rest\n\n  return j.callExpression(\n    j.memberExpression(j.identifier('create'), j.identifier(type)),\n    restArgs\n  )\n}\n\nexport function reducerPropsToBuilderExpression(\n  j: JSCodeshift,\n  defNode: ObjectExpression\n) {\n  const returnedObject = j.objectExpression([])\n  for (const property of defNode.properties) {\n    let finalProp: ObjectProperty | undefined\n    switch (property.type) {\n      case 'ObjectMethod': {\n        const { key, params, body } = property\n        finalProp = j.objectProperty(\n          key,\n          creatorCall(j, 'reducer', j.arrowFunctionExpression(params, body))\n        )\n        break\n      }\n      case 'ObjectProperty': {\n        const { key } = property\n\n        switch (property.value.type) {\n          case 'ObjectExpression': {\n            const preparedReducerParams: {\n              prepare?: ExpressionKind\n              reducer?: ExpressionKind\n            } = {}\n\n            for (const objProp of property.value.properties) {\n              switch (objProp.type) {\n                case 'ObjectMethod': {\n                  const { key, params, body } = objProp\n                  if (\n                    key.type === 'Identifier' &&\n                    (key.name === 'reducer' || key.name === 'prepare')\n                  ) {\n                    preparedReducerParams[key.name] = j.arrowFunctionExpression(\n                      params,\n                      body\n                    )\n                  }\n                  break\n                }\n                case 'ObjectProperty': {\n                  const { key, value } = objProp\n\n                  let finalExpression: ExpressionKind | undefined = undefined\n\n                  switch (value.type) {\n                    case 'ArrowFunctionExpression':\n                    case 'FunctionExpression':\n                    case 'Identifier':\n                    case 'MemberExpression':\n                    case 'CallExpression': {\n                      finalExpression = value\n                    }\n                  }\n\n                  if (\n                    key.type === 'Identifier' &&\n                    (key.name === 'reducer' || key.name === 'prepare') &&\n                    finalExpression\n                  ) {\n                    preparedReducerParams[key.name] = finalExpression\n                  }\n                  break\n                }\n              }\n            }\n\n            if (\n              preparedReducerParams.prepare &&\n              preparedReducerParams.reducer\n            ) {\n              finalProp = j.objectProperty(\n                key,\n                creatorCall(\n                  j,\n                  'preparedReducer',\n                  preparedReducerParams.prepare,\n                  preparedReducerParams.reducer\n                )\n              )\n            } else if (preparedReducerParams.reducer) {\n              finalProp = j.objectProperty(\n                key,\n                creatorCall(j, 'reducer', preparedReducerParams.reducer)\n              )\n            }\n            break\n          }\n          case 'ArrowFunctionExpression':\n          case 'FunctionExpression':\n          case 'Identifier':\n          case 'MemberExpression':\n          case 'CallExpression': {\n            const { value } = property\n            finalProp = j.objectProperty(key, creatorCall(j, 'reducer', value))\n            break\n          }\n        }\n        break\n      }\n    }\n    if (!finalProp) {\n      continue\n    }\n    returnedObject.properties.push(finalProp)\n  }\n\n  return j.arrowFunctionExpression(\n    [j.identifier('create')],\n    returnedObject,\n    true\n  )\n}\n\nconst transform: Transform = (file, api) => {\n  const j = api.jscodeshift\n\n  return j(file.source)\n    .find(j.CallExpression, {\n      callee: { name: 'createSlice' },\n      arguments: [{ type: 'ObjectExpression' }]\n    })\n\n    .filter((path) => {\n      const createSliceArgsObject = path.node.arguments[0] as ObjectExpression\n      return createSliceArgsObject.properties.some(\n        (p) =>\n          p.type === 'ObjectProperty' &&\n          p.key.type === 'Identifier' &&\n          p.key.name === 'reducers' &&\n          p.value.type === 'ObjectExpression'\n      )\n    })\n    .forEach((path) => {\n      const createSliceArgsObject = path.node.arguments[0] as ObjectExpression\n      j(path).replaceWith(\n        j.callExpression(j.identifier('createSlice'), [\n          j.objectExpression(\n            createSliceArgsObject.properties.map((p) => {\n              if (\n                p.type === 'ObjectProperty' &&\n                p.key.type === 'Identifier' &&\n                p.key.name === 'reducers' &&\n                p.value.type === 'ObjectExpression'\n              ) {\n                const expressionStatement = reducerPropsToBuilderExpression(\n                  j,\n                  p.value\n                )\n                return j.objectProperty(p.key, expressionStatement)\n              }\n              return p\n            })\n          )\n        ])\n      )\n    })\n    .toSource({\n      arrowParensAlways: true,\n      lineTerminator: '\\n'\n    })\n}\n\nexport const parser = 'tsx' satisfies TestOptions['parser']\n\nexport default transform\n"
  },
  {
    "path": "packages/rtk-codemods/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"allowSyntheticDefaultImports\": true,\n    \"noUnusedLocals\": false,\n    \"noUnusedParameters\": false,\n    \"isolatedModules\": true,\n    \"checkJs\": true,\n    \"baseUrl\": \".\",\n    \"noEmit\": true,\n    \"strict\": true,\n    \"target\": \"ESNext\",\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Node\",\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true,\n    \"allowJs\": true,\n    \"jsx\": \"preserve\",\n    \"noErrorTruncation\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"paths\": {\n      \"@reduxjs/toolkit\": [\"../toolkit/src/index.ts\"], // @remap-prod-remove-line\n      \"@reduxjs/toolkit/query\": [\"../toolkit/src/query/index.ts\"], // @remap-prod-remove-line\n      \"@reduxjs/toolkit/react\": [\"../toolkit/src/react/index.ts\"], // @remap-prod-remove-line\n      \"@reduxjs/toolkit/query/react\": [\"../toolkit/src/query/react/index.ts\"] // @remap-prod-remove-line\n    }\n  },\n  \"include\": [\"**/*.ts\", \"**/*.tsx\", \"bin/cli.mjs\"]\n}\n"
  },
  {
    "path": "packages/rtk-codemods/vitest.config.mts",
    "content": "import { defineConfig } from 'vitest/config'\n\nexport default defineConfig({\n  test: {\n    globals: true\n  }\n})\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/.gitignore",
    "content": "### https://raw.github.com/github/gitignore/218a941be92679ce67d0484547e3e142b2f5f6f0/Node.gitignore\n\n# Logs\nlogs\n*.log\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\nlerna-debug.log*\n\n# Diagnostic reports (https://nodejs.org/api/report.html)\nreport.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json\n\n# Runtime data\npids\n*.pid\n*.seed\n*.pid.lock\n\n# Directory for instrumented libs generated by jscoverage/JSCover\nlib-cov\n\n# Coverage directory used by tools like istanbul\ncoverage\n*.lcov\n\n# nyc test coverage\n.nyc_output\n\n# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)\n.grunt\n\n# Bower dependency directory (https://bower.io/)\nbower_components\n\n# node-waf configuration\n.lock-wscript\n\n# Compiled binary addons (https://nodejs.org/api/addons.html)\nbuild/Release\n\n# Dependency directories\nnode_modules/\njspm_packages/\n\n# Snowpack dependency directory (https://snowpack.dev/)\nweb_modules/\n\n# TypeScript cache\n*.tsbuildinfo\n\n# Optional npm cache directory\n.npm\n\n# Optional eslint cache\n.eslintcache\n\n# Microbundle cache\n.rpt2_cache/\n.rts2_cache_cjs/\n.rts2_cache_es/\n.rts2_cache_umd/\n\n# Optional REPL history\n.node_repl_history\n\n# Output of 'npm pack'\n*.tgz\n\n# Yarn Integrity file\n.yarn-integrity\n\n# dotenv environment variables file\n.env\n.env.test\n\n# parcel-bundler cache (https://parceljs.org/)\n.cache\n.parcel-cache\n\n# Next.js build output\n.next\nout\n\n# Nuxt.js build / generate output\n.nuxt\ndist\n\n# Gatsby files\n.cache/\n# Comment in the public line in if your project uses Gatsby and not Next.js\n# https://nextjs.org/blog/next-9-1#public-directory-support\n# public\n\n# vuepress build output\n.vuepress/dist\n\n# Serverless directories\n.serverless/\n\n# FuseBox cache\n.fusebox/\n\n# DynamoDB Local files\n.dynamodb/\n\n# TernJS port file\n.tern-port\n\n# Stores VSCode versions used for testing VSCode extensions\n.vscode-test\n\n# yarn v2\n.yarn/cache\n.yarn/unplugged\n.yarn/build-state.yml\n.yarn/install-state.gz\n.pnp.*\n\n\n### https://raw.github.com/github/gitignore/218a941be92679ce67d0484547e3e142b2f5f6f0/Global/VisualStudioCode.gitignore\n\n.vscode/*\n!.vscode/settings.json\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/extensions.json\n*.code-workspace\n\n.idea/*\n\n# Local History for Visual Studio Code\n.history/\n\n.yalc/\nyalc.lock\nlib\nyarn.lock\ntest/tmp/example.ts\ntest/tmp/emptyApi.ts\ntest/tmp/out.ts"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/.prettierrc",
    "content": "{\n  \"endOfLine\": \"auto\",\n  \"printWidth\": 120,\n  \"semi\": true,\n  \"singleQuote\": true,\n  \"trailingComma\": \"es5\"\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/.release-it.json",
    "content": "{\n  \"hooks\": {\n    \"after:bump\": \"yarn && git add -u\"\n  },\n  \"git\": {\n    \"commitMessage\": \"Release @rtk-query/codegen-openapi ${version}\",\n    \"tagName\": \"@rtk-query/codegen-openapi@${version}\"\n  },\n  \"npm\": {\n    \"publish\": false,\n    \"versionArgs\": [\"--workspaces-update=false\"]\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/ChangeLog.md",
    "content": "# Changelog\n\nAll notable changes to the `RTK Query - Code Generator` for `Open API` project will be documented in this file.\n\nThe format is based on [Keep a Changelog](https://keepachangelog.com/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).\n\n## 1.2.0 - 2023-11-09\n\nThis version adds a new `mergeReadWriteOnly` configuration option (default to `false`) that, when set to `true` will not generate separate types for read-only and write-only properties.\n\n## 1.1.3 - 2023-10-11\n\n### Added\n\n- Adds a temporary workaround for [4.9.0 and 4.10.0 generate circular types oazapfts/oazapfts#491](https://github.com/oazapfts/oazapfts/issues/491)\n\n## 1.1.2 - 2023-10-11\n\n### Added\n\n- Support for Read Only Properties in the Open API spec. Previously, this property was ignored.\n  - Now if the readOnly property is present and set to `true` in a schema, it will split the type into two types: one with the read only property suffixed as 'Read' and the other without the read only properties, using the same type name as before.\n  - This may cause issues if you had your OpenAPI spec properly typed/configured, as it will remove the read onyl types from your existing type. You will need to switch to the new type suffixed as 'Read' to avoid missing property names.\n\n## 1.1.1 - 2023-10-11\n\n### Changed\n\n- Codegen: better handling of duplicate param names ([Codegen: better handling of duplicate param names #3780](https://github.com/reduxjs/redux-toolkit/pull/3780))\n  - If a parameter name is both used in a query and a parameter, it will be prefixed with `query`/`param` now to avoid conflicts\n\n## 1.1.0 - 2023-10-11\n\n### Added\n\n- Option of generating real TS enums instead of string unions [Adds the option of generating real TS enums instead of string unions #2854](https://github.com/reduxjs/redux-toolkit/pull/2854)\n- Compatibility with TypeScript 5.x versions as the codegen relies on the TypeScript AST for code generation\n  - As a result also needs a higher TypeScript version to work with (old version range was 4.1-4.5)\n- Changes depenendcy from a temporarily patched old version of `oazapfts` back to the current upstream version\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/README.md",
    "content": "<p align=\"center\">\n  <img src=\"https://raw.githubusercontent.com/rtk-incubator/rtk-query/main/logo.png\" width=\"400\" />\n</p>\n<h2 align=\"center\">\nCode Generator\n</h2>\n\n<p align=\"center\">\n   <a href=\"https://discord.gg/0ZcbPKXt5bZ6au5t\" target=\"_blank\">\n    <img src=\"https://img.shields.io/badge/chat-online-green\" alt=\"Discord server\" />\n  </a>\n</p>\n\n### Introduction\n\nThis is a utility library meant to be used with [RTK Query](https://redux-toolkit.js.org/rtk-query/overview) that will generate a typed API client from an OpenAPI schema.\n\n### Documentation\n\n[View the RTK Query Code Generation docs](https://redux-toolkit.js.org/rtk-query/usage/code-generation)\n\nIf you use an AI agent, run `npx @tanstack/intent@latest install` to install agent skills.\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/package.json",
    "content": "{\n  \"name\": \"@rtk-query/codegen-openapi\",\n  \"version\": \"2.2.0\",\n  \"main\": \"lib/index.js\",\n  \"types\": \"lib/index.d.ts\",\n  \"module\": \"lib/index.mjs\",\n  \"author\": \"Lenz Weber\",\n  \"license\": \"MIT\",\n  \"sideEffects\": false,\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": {\n      \"import\": {\n        \"types\": \"./lib/index.d.mts\",\n        \"default\": \"./lib/index.mjs\"\n      },\n      \"default\": {\n        \"types\": \"./lib/index.d.ts\",\n        \"default\": \"./lib/index.js\"\n      }\n    },\n    \"./cli\": \"./lib/bin/cli.mjs\"\n  },\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/reduxjs/redux-toolkit.git\"\n  },\n  \"bugs\": {\n    \"url\": \"https://github.com/reduxjs/redux-toolkit/issues\"\n  },\n  \"homepage\": \"https://redux-toolkit.js.org\",\n  \"bin\": {\n    \"rtk-query-codegen-openapi\": \"lib/bin/cli.mjs\"\n  },\n  \"scripts\": {\n    \"build\": \"yarn clean && tsup && chmod +x lib/bin/cli.mjs\",\n    \"clean\": \"rimraf lib\",\n    \"prepack\": \"yarn build && chmod +x lib/bin/cli.mjs\",\n    \"format\": \"prettier --write \\\"src/**/*.ts\\\"\",\n    \"test:update\": \"vitest --run --update\",\n    \"test:update:enum\": \"lib/bin/cli.mjs test/config.example.enum.ts\",\n    \"test\": \"vitest --run --typecheck\",\n    \"test:watch\": \"vitest --watch\",\n    \"cli\": \"esr src/bin/cli.ts\"\n  },\n  \"files\": [\n    \"lib\",\n    \"src\",\n    \"skills\",\n    \"!skills/_artifacts\"\n  ],\n  \"devDependencies\": {\n    \"@babel/core\": \"^7.12.10\",\n    \"@babel/preset-env\": \"^7.12.11\",\n    \"@babel/preset-typescript\": \"^7.12.7\",\n    \"@oazapfts/runtime\": \"^1.0.3\",\n    \"@reduxjs/toolkit\": \"^1.6.0\",\n    \"@tanstack/intent\": \"^0.0.19\",\n    \"@types/commander\": \"^2.12.2\",\n    \"@types/glob-to-regexp\": \"^0.4.0\",\n    \"@types/lodash.camelcase\": \"^4.3.9\",\n    \"@types/node\": \"^25.5.0\",\n    \"@types/semver\": \"^7.3.9\",\n    \"chalk\": \"^4.1.0\",\n    \"del\": \"^6.0.0\",\n    \"esbuild\": \"^0.25.1\",\n    \"esbuild-runner\": \"^2.2.1\",\n    \"husky\": \"^4.3.6\",\n    \"msw\": \"^2.1.5\",\n    \"node-fetch\": \"^3.3.2\",\n    \"openapi-types\": \"^9.1.0\",\n    \"pretty-quick\": \"^4.0.0\",\n    \"rimraf\": \"^6.1.3\",\n    \"ts-node\": \"^10.9.2\",\n    \"tsup\": \"^8.4.0\",\n    \"vite-tsconfig-paths\": \"^5.0.1\",\n    \"vitest\": \"^4\",\n    \"yalc\": \"^1.0.0-pre.47\"\n  },\n  \"dependencies\": {\n    \"@apidevtools/swagger-parser\": \"^10.1.1\",\n    \"commander\": \"^6.2.0\",\n    \"lodash.camelcase\": \"^4.3.0\",\n    \"oazapfts\": \"^6.4.0\",\n    \"prettier\": \"^3.2.5\",\n    \"semver\": \"^7.3.5\",\n    \"swagger2openapi\": \"^7.0.4\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"husky\": {\n    \"hooks\": {\n      \"pre-commit\": \"pretty-quick --staged\"\n    }\n  },\n  \"keywords\": [\n    \"tanstack-intent\"\n  ]\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/skills/manage-server-data/generate-rtk-query-from-openapi/SKILL.md",
    "content": "---\nname: manage-server-data/generate-rtk-query-from-openapi\ndescription: >\n  Use this when generating RTK Query endpoints from OpenAPI schemas with\n  @rtk-query/codegen-openapi. Covers the empty API pattern, filterEndpoints,\n  endpointOverrides, generated tags, and reviewing generated output before it\n  becomes part of the app.\ntype: composition\nlibrary: \"@rtk-query/codegen-openapi\"\nlibrary_version: \"2.2.0\"\nrequires:\n  - manage-server-data/adopt-rtk-query\nsources:\n  - \"reduxjs/redux-toolkit:docs/rtk-query/usage/code-generation.mdx\"\n  - \"reduxjs/redux-toolkit:packages/rtk-query-codegen-openapi/src/types.ts\"\n  - \"reduxjs/redux-toolkit:packages/rtk-query-codegen-openapi/src/generate.ts\"\n  - \"reduxjs/redux-toolkit:packages/rtk-query-codegen-openapi/README.md\"\n---\n\n# Generate RTK Query From OpenAPI\n\n## Setup\n\n```ts\n// file: src/store/emptyApi.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const emptySplitApi = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  endpoints: () => ({}),\n})\n\n// file: openapi-config.ts\nimport type { ConfigFile } from '@rtk-query/codegen-openapi'\n\nconst config: ConfigFile = {\n  schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  apiImport: 'emptySplitApi',\n  outputFile: './src/store/petApi.ts',\n  exportName: 'petApi',\n  hooks: true,\n}\n\nexport default config\n```\n\nRun:\n\n```bash\nnpx @rtk-query/codegen-openapi openapi-config.ts\n```\n\n## Core Patterns\n\n### Generate into an empty shared API\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const emptySplitApi = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  endpoints: () => ({}),\n})\n```\n\nCodegen works best when it extends a single RTK Query architecture instead of creating standalone API roots.\n\n### Filter endpoints when the schema is too broad\n\n```ts\nimport type { ConfigFile } from '@rtk-query/codegen-openapi'\n\nconst config: ConfigFile = {\n  schemaFile: './openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  apiImport: 'emptySplitApi',\n  outputFile: './src/store/userApi.ts',\n  exportName: 'userApi',\n  hooks: true,\n  filterEndpoints: ['loginUser', /User/],\n}\n\nexport default config\n```\n\nStart with a narrow slice of the schema if the full surface area is too noisy or the package boundaries differ from the OpenAPI file.\n\n### Use `endpointOverrides` to fix generation results\n\n```ts\nimport type { ConfigFile } from '@rtk-query/codegen-openapi'\n\nconst config: ConfigFile = {\n  schemaFile: './openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  apiImport: 'emptySplitApi',\n  outputFile: './src/store/petApi.ts',\n  exportName: 'petApi',\n  hooks: true,\n  tag: true,\n  endpointOverrides: [\n    {\n      pattern: 'loginUser',\n      type: 'mutation',\n    },\n    {\n      pattern: /.*/,\n      parameterFilter: (_name, parameter) => parameter.in !== 'header',\n    },\n    {\n      pattern: 'getPetById',\n      providesTags: ['SinglePet'],\n    },\n  ],\n}\n\nexport default config\n```\n\nReview generated endpoints and override type, parameter, or tag behavior instead of hand-editing the emitted file.\n\n## Common Mistakes\n\n### HIGH Assuming generated tags are already specific enough\n\nWrong:\n\n```ts\nconst config: ConfigFile = {\n  schemaFile: './openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  apiImport: 'emptySplitApi',\n  outputFile: './src/store/petApi.ts',\n  exportName: 'petApi',\n  tag: true,\n}\n```\n\nCorrect:\n\n```ts\nconst config: ConfigFile = {\n  schemaFile: './openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  apiImport: 'emptySplitApi',\n  outputFile: './src/store/petApi.ts',\n  exportName: 'petApi',\n  tag: true,\n  endpointOverrides: [\n    {\n      pattern: 'getPetById',\n      providesTags: ['SinglePet'],\n    },\n  ],\n}\n```\n\nGenerated tags are string-only by default, so they can invalidate more cache than intended.\n\nSource: reduxjs/redux-toolkit:docs/rtk-query/usage/code-generation.mdx\n\n### HIGH Generating a brand-new API root instead of extending an empty one\n\nWrong:\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ntype Pet = { id: string; name: string }\n\nexport const petApi = createApi({\n  reducerPath: 'petApi',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  endpoints: (build) => ({\n    getPetById: build.query<Pet, string>({\n      query: (id) => `pets/${id}`,\n    }),\n  }),\n})\n```\n\nCorrect:\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const emptySplitApi = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  endpoints: () => ({}),\n})\n```\n\nGenerated code should plug into one RTK Query architecture so invalidation and store wiring stay coherent.\n\nSource: reduxjs/redux-toolkit:docs/rtk-query/usage/code-generation.mdx\n\n### MEDIUM Trusting generated shapes without overrides or review\n\nWrong:\n\n```ts\nconst config: ConfigFile = {\n  schemaFile: './openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  apiImport: 'emptySplitApi',\n  outputFile: './src/store/petApi.ts',\n  exportName: 'petApi',\n}\n```\n\nCorrect:\n\n```ts\nconst config: ConfigFile = {\n  schemaFile: './openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  apiImport: 'emptySplitApi',\n  outputFile: './src/store/petApi.ts',\n  exportName: 'petApi',\n  endpointOverrides: [\n    {\n      pattern: 'loginUser',\n      type: 'mutation',\n    },\n  ],\n}\n```\n\nReal schemas often need type, parameter, or tag correction; treat generated output as reviewed source, not gospel.\n\nSource: reduxjs/redux-toolkit:docs/rtk-query/usage/code-generation.mdx\n\n## References\n\n- [Codegen override patterns and review checklist](references/codegen-overrides.md)\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/skills/manage-server-data/generate-rtk-query-from-openapi/references/codegen-overrides.md",
    "content": "# Codegen Overrides\n\n## Common override targets\n\n| Need | Override |\n| --- | --- |\n| Query should really be a mutation | `type: 'mutation'` |\n| Header or optional parameters should be omitted | `parameterFilter` |\n| Generated tags are too coarse | `providesTags` / `invalidatesTags` |\n\n## Example: split one schema into multiple outputs\n\n```ts\nimport type { ConfigFile } from '@rtk-query/codegen-openapi'\n\nconst config: ConfigFile = {\n  schemaFile: './openapi.json',\n  apiFile: './src/store/emptyApi.ts',\n  apiImport: 'emptySplitApi',\n  outputFiles: {\n    './src/store/userApi.ts': {\n      exportName: 'userApi',\n      filterEndpoints: [/user/i],\n      hooks: true,\n    },\n    './src/store/orderApi.ts': {\n      exportName: 'orderApi',\n      filterEndpoints: [/order/i],\n      hooks: true,\n    },\n  },\n}\n\nexport default config\n```\n\n## Review checklist\n\n- Does every generated endpoint belong in the shared API root?\n- Did any query or mutation type need correction?\n- Are generated tags specific enough for real invalidation needs?\n- Did the schema force parameters into the signature that the app should hide?\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/bin/cli.ts",
    "content": "#!/usr/bin/env node\n\nimport { generateEndpoints, parseConfig } from '@rtk-query/codegen-openapi';\nimport program from 'commander';\nimport { createRequire } from 'node:module';\nimport { dirname, resolve } from 'node:path';\n\nconst require = createRequire(__filename);\n\nlet ts = false;\ntry {\n  if (require.resolve('esbuild') && require.resolve('esbuild-runner')) {\n    require('esbuild-runner/register');\n  }\n  ts = true;\n} catch {}\n\ntry {\n  if (!ts) {\n    if (require.resolve('typescript') && require.resolve('ts-node')) {\n      (require('ts-node') as typeof import('ts-node')).register({\n        transpileOnly: true,\n        compilerOptions: {\n          target: 'es6',\n          module: 'commonjs',\n        },\n      });\n    }\n\n    ts = true;\n  }\n} catch {}\n\n// tslint:disable-next-line\nconst meta = require('../../package.json');\n\nprogram.version(meta.version).usage('</path/to/config.js>').parse(process.argv);\n\nconst configFile = program.args[0];\n\nif (program.args.length === 0 || !/\\.([mc]?(jsx?|tsx?)|jsonc?)?$/.test(configFile)) {\n  program.help();\n} else {\n  if (/\\.[mc]?tsx?$/.test(configFile) && !ts) {\n    console.error('Encountered a TypeScript configfile, but neither esbuild-runner nor ts-node are installed.');\n    process.exit(1);\n  }\n  run(resolve(process.cwd(), configFile));\n}\n\nasync function run(configFile: string) {\n  process.chdir(dirname(configFile));\n\n  const unparsedConfig = require(configFile);\n\n  for (const config of parseConfig(unparsedConfig.default ?? unparsedConfig)) {\n    try {\n      console.log(`Generating ${config.outputFile}`);\n      await generateEndpoints(config);\n      console.log(`Done`);\n    } catch (err) {\n      console.error(err);\n      process.exit(1);\n    }\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/codegen.ts",
    "content": "import { factory } from './utils/factory';\nimport ts from 'typescript';\n\nconst defaultEndpointBuilder = factory.createIdentifier('build');\n\nexport type ObjectPropertyDefinitions = Record<string, ts.Expression | undefined>;\nexport function generateObjectProperties(obj: ObjectPropertyDefinitions) {\n  return Object.entries(obj)\n    .filter(([_, v]) => v)\n    .map(([k, v]) => factory.createPropertyAssignment(factory.createIdentifier(k), v as ts.Expression));\n}\n\nexport function generateImportNode(pkg: string, namedImports: Record<string, string>, defaultImportName?: string) {\n  return factory.createImportDeclaration(\n    undefined,\n    factory.createImportClause(\n      false,\n      defaultImportName !== undefined ? factory.createIdentifier(defaultImportName) : undefined,\n      factory.createNamedImports(\n        Object.entries(namedImports).map(([propertyName, name]) =>\n          factory.createImportSpecifier(\n            name === propertyName ? undefined : factory.createIdentifier(propertyName),\n            factory.createIdentifier(name)\n          )\n        )\n      )\n    ),\n    factory.createStringLiteral(pkg)\n  );\n}\n\nexport function generateCreateApiCall({\n  endpointBuilder = defaultEndpointBuilder,\n  endpointDefinitions,\n  tag,\n}: {\n  endpointBuilder?: ts.Identifier;\n  endpointDefinitions: ts.ObjectLiteralExpression;\n  tag: boolean;\n}) {\n  const injectEndpointsObjectLiteralExpression = factory.createObjectLiteralExpression(\n    generateObjectProperties({\n      endpoints: factory.createArrowFunction(\n        undefined,\n        undefined,\n        [factory.createParameterDeclaration(undefined, undefined, endpointBuilder, undefined, undefined, undefined)],\n        undefined,\n        factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken),\n        factory.createParenthesizedExpression(endpointDefinitions)\n      ),\n      overrideExisting: factory.createFalse(),\n    }),\n    true\n  );\n  if (tag) {\n    const enhanceEndpointsObjectLiteralExpression = factory.createObjectLiteralExpression(\n      [factory.createShorthandPropertyAssignment(factory.createIdentifier('addTagTypes'), undefined)],\n      true\n    );\n    return factory.createVariableStatement(\n      undefined,\n      factory.createVariableDeclarationList(\n        [\n          factory.createVariableDeclaration(\n            factory.createIdentifier('injectedRtkApi'),\n            undefined,\n            undefined,\n            factory.createCallExpression(\n              factory.createPropertyAccessExpression(\n                factory.createCallExpression(\n                  factory.createPropertyAccessExpression(\n                    factory.createIdentifier('api'),\n                    factory.createIdentifier('enhanceEndpoints')\n                  ),\n                  undefined,\n                  [enhanceEndpointsObjectLiteralExpression]\n                ),\n                factory.createIdentifier('injectEndpoints')\n              ),\n              undefined,\n              [injectEndpointsObjectLiteralExpression]\n            )\n          ),\n        ],\n        ts.NodeFlags.Const\n      )\n    );\n  }\n\n  return factory.createVariableStatement(\n    undefined,\n    factory.createVariableDeclarationList(\n      [\n        factory.createVariableDeclaration(\n          factory.createIdentifier('injectedRtkApi'),\n          undefined,\n          undefined,\n          factory.createCallExpression(\n            factory.createPropertyAccessExpression(\n              factory.createIdentifier('api'),\n              factory.createIdentifier('injectEndpoints')\n            ),\n            undefined,\n            [injectEndpointsObjectLiteralExpression]\n          )\n        ),\n      ],\n      ts.NodeFlags.Const\n    )\n  );\n}\n\nexport function generateEndpointDefinition({\n  operationName,\n  type,\n  Response,\n  QueryArg,\n  queryFn,\n  endpointBuilder = defaultEndpointBuilder,\n  extraEndpointsProps,\n  tags,\n  tagOverrides,\n}: {\n  operationName: string;\n  type: 'query' | 'mutation';\n  Response: ts.TypeReferenceNode;\n  QueryArg: ts.TypeReferenceNode;\n  queryFn: ts.Expression;\n  endpointBuilder?: ts.Identifier;\n  extraEndpointsProps: ObjectPropertyDefinitions;\n  tags?: string[];\n  tagOverrides?: { providesTags?: string[]; invalidatesTags?: string[] };\n}) {\n  const objectProperties = generateObjectProperties({ query: queryFn, ...extraEndpointsProps });\n  const providesTags =\n    tagOverrides && 'providesTags' in tagOverrides\n      ? tagOverrides.providesTags\n      : type === 'query'\n        ? tags\n        : undefined;\n  const invalidatesTags =\n    tagOverrides && 'invalidatesTags' in tagOverrides\n      ? tagOverrides.invalidatesTags\n      : type === 'mutation'\n        ? tags\n        : undefined;\n\n  if (providesTags !== undefined) {\n    objectProperties.push(\n      factory.createPropertyAssignment(\n        factory.createIdentifier('providesTags'),\n        factory.createArrayLiteralExpression(providesTags.map((tag) => factory.createStringLiteral(tag)), false)\n      )\n    );\n  }\n\n  if (invalidatesTags !== undefined) {\n    objectProperties.push(\n      factory.createPropertyAssignment(\n        factory.createIdentifier('invalidatesTags'),\n        factory.createArrayLiteralExpression(invalidatesTags.map((tag) => factory.createStringLiteral(tag)), false)\n      )\n    );\n  }\n  return factory.createPropertyAssignment(\n    factory.createIdentifier(operationName),\n\n    factory.createCallExpression(\n      factory.createPropertyAccessExpression(endpointBuilder, factory.createIdentifier(type)),\n      [Response, QueryArg],\n      [factory.createObjectLiteralExpression(objectProperties, true)]\n    )\n  );\n}\n\nexport function generateTagTypes({ addTagTypes }: { addTagTypes: string[] }) {\n  return factory.createVariableStatement(\n    [factory.createModifier(ts.SyntaxKind.ExportKeyword)],\n    factory.createVariableDeclarationList(\n      [\n        factory.createVariableDeclaration(\n          factory.createIdentifier('addTagTypes'),\n          undefined,\n          undefined,\n          factory.createAsExpression(\n            factory.createArrayLiteralExpression(\n              addTagTypes.map((tagType) => factory.createStringLiteral(tagType)),\n              true\n            ),\n            factory.createTypeReferenceNode(factory.createIdentifier('const'), undefined)\n          )\n        ),\n      ],\n      ts.NodeFlags.Const\n    )\n  );\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/generate.ts",
    "content": "import camelCase from 'lodash.camelcase';\nimport path from 'node:path';\nimport ApiGenerator, {\n  getOperationName as _getOperationName,\n  createPropertyAssignment,\n  createQuestionToken,\n  getReferenceName,\n  isReference,\n  isValidIdentifier,\n  keywordType,\n  supportDeepObjects,\n} from 'oazapfts/generate';\nimport type { OpenAPIV3 } from 'openapi-types';\nimport ts from 'typescript';\nimport type { ObjectPropertyDefinitions } from './codegen';\nimport { generateCreateApiCall, generateEndpointDefinition, generateImportNode, generateTagTypes } from './codegen';\nimport { generateReactHooks } from './generators/react-hooks';\nimport type {\n  EndpointMatcher,\n  EndpointOverrides,\n  GenerationOptions,\n  OperationDefinition,\n  ParameterDefinition,\n  ParameterMatcher,\n  TextMatcher,\n} from './types';\nimport { capitalize, getOperationDefinitions, getV3Doc, removeUndefined, isQuery as testIsQuery } from './utils';\nimport { factory } from './utils/factory';\n\nconst generatedApiName = 'injectedRtkApi';\nconst v3DocCache: Record<string, OpenAPIV3.Document> = {};\n\nfunction defaultIsDataResponse(code: string, includeDefault: boolean) {\n  if (includeDefault && code === 'default') {\n    return true;\n  }\n  const parsedCode = Number(code);\n  return !Number.isNaN(parsedCode) && parsedCode >= 200 && parsedCode < 300;\n}\n\nfunction getOperationName({ verb, path, operation }: Pick<OperationDefinition, 'verb' | 'path' | 'operation'>) {\n  return _getOperationName(verb, path, operation.operationId);\n}\n\nfunction getTags({ verb, pathItem }: Pick<OperationDefinition, 'verb' | 'pathItem'>): string[] {\n  return verb ? pathItem[verb]?.tags || [] : [];\n}\n\nfunction patternMatches(pattern?: TextMatcher) {\n  const filters = Array.isArray(pattern) ? pattern : [pattern];\n  return function matcher(operationName: string) {\n    if (!pattern) return true;\n    return filters.some((filter) =>\n      typeof filter === 'string' ? filter === operationName : filter?.test(operationName)\n    );\n  };\n}\n\nfunction operationMatches(pattern?: EndpointMatcher) {\n  const checkMatch = typeof pattern === 'function' ? pattern : patternMatches(pattern);\n  return function matcher(operationDefinition: OperationDefinition) {\n    if (!pattern) return true;\n    const operationName = getOperationName(operationDefinition);\n    return checkMatch(operationName, operationDefinition);\n  };\n}\n\nfunction argumentMatches(pattern?: ParameterMatcher) {\n  const checkMatch = typeof pattern === 'function' ? pattern : patternMatches(pattern);\n  return function matcher(argumentDefinition: ParameterDefinition) {\n    if (!pattern || argumentDefinition.in === 'path') return true;\n    const argumentName = argumentDefinition.name;\n    return checkMatch(argumentName, argumentDefinition);\n  };\n}\n\nfunction withQueryComment<T extends ts.Node>(node: T, def: QueryArgDefinition, hasTrailingNewLine: boolean): T {\n  const comment = def.origin === 'param' ? def.param.description : def.body.description;\n  if (comment) {\n    return ts.addSyntheticLeadingComment(\n      node,\n      ts.SyntaxKind.MultiLineCommentTrivia,\n      `* ${comment} `,\n      hasTrailingNewLine\n    );\n  }\n  return node;\n}\n\nfunction getPatternFromProperty(\n  property: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject,\n  apiGen: ApiGenerator\n): string | null {\n  const resolved = apiGen.resolve(property);\n  if (!resolved || typeof resolved !== 'object' || !('pattern' in resolved)) return null;\n  if (resolved.type !== 'string') return null;\n  const pattern = resolved.pattern;\n  return typeof pattern === 'string' && pattern.length > 0 ? pattern : null;\n}\n\nfunction generateRegexConstantsForType(\n  typeName: string,\n  schema: OpenAPIV3.SchemaObject | OpenAPIV3.ReferenceObject,\n  apiGen: ApiGenerator\n): ts.VariableStatement[] {\n  const resolvedSchema = apiGen.resolve(schema);\n  if (!resolvedSchema || !('properties' in resolvedSchema) || !resolvedSchema.properties) return [];\n\n  const constants: ts.VariableStatement[] = [];\n\n  for (const [propertyName, property] of Object.entries(resolvedSchema.properties)) {\n    const pattern = getPatternFromProperty(property, apiGen);\n    if (!pattern) continue;\n\n    const constantName = camelCase(`${typeName} ${propertyName} Pattern`);\n    const escapedPattern = pattern.replaceAll('/', String.raw`\\/`);\n    const regexLiteral = factory.createRegularExpressionLiteral(`/${escapedPattern}/`);\n\n    constants.push(\n      factory.createVariableStatement(\n        [factory.createModifier(ts.SyntaxKind.ExportKeyword)],\n        factory.createVariableDeclarationList(\n          [\n            factory.createVariableDeclaration(\n              factory.createIdentifier(constantName),\n              undefined,\n              undefined,\n              regexLiteral\n            ),\n          ],\n          ts.NodeFlags.Const\n        )\n      )\n    );\n  }\n\n  return constants;\n}\n\nexport function getOverrides(\n  operation: OperationDefinition,\n  endpointOverrides?: EndpointOverrides[]\n): EndpointOverrides | undefined {\n  return endpointOverrides?.find((override) => operationMatches(override.pattern)(operation));\n}\n\nexport async function generateApi(\n  spec: string,\n  {\n    apiFile,\n    apiImport = 'api',\n    exportName = 'enhancedApi',\n    argSuffix = 'ApiArg',\n    responseSuffix = 'ApiResponse',\n    operationNameSuffix = '',\n    hooks = false,\n    tag = false,\n    outputFile,\n    isDataResponse = defaultIsDataResponse,\n    filterEndpoints,\n    endpointOverrides,\n    unionUndefined,\n    encodePathParams = false,\n    encodeQueryParams = false,\n    flattenArg = false,\n    includeDefault = false,\n    useEnumType = false,\n    mergeReadWriteOnly = false,\n    httpResolverOptions,\n    useUnknown = false,\n    esmExtensions = false,\n    outputRegexConstants = false,\n  }: GenerationOptions\n) {\n  const v3Doc = (v3DocCache[spec] ??= await getV3Doc(spec, httpResolverOptions));\n\n  const apiGen = new ApiGenerator(v3Doc, {\n    unionUndefined,\n    useEnumType,\n    mergeReadWriteOnly,\n    useUnknown,\n  });\n\n  // temporary workaround for https://github.com/oazapfts/oazapfts/issues/491\n  if (apiGen.spec.components?.schemas) {\n    apiGen.preprocessComponents(apiGen.spec.components.schemas);\n  }\n\n  const operationDefinitions = getOperationDefinitions(v3Doc).filter(operationMatches(filterEndpoints));\n\n  const resultFile = ts.createSourceFile(\n    'someFileName.ts',\n    '',\n    ts.ScriptTarget.Latest,\n    /*setParentNodes*/ false,\n    ts.ScriptKind.TS\n  );\n  const printer = ts.createPrinter({ newLine: ts.NewLineKind.LineFeed });\n\n  const interfaces: Record<string, ts.InterfaceDeclaration | ts.TypeAliasDeclaration> = {};\n  function registerInterface(declaration: ts.InterfaceDeclaration | ts.TypeAliasDeclaration) {\n    const name = declaration.name.escapedText.toString();\n    if (name in interfaces) {\n      throw new Error(`interface/type alias ${name} already registered`);\n    }\n    interfaces[name] = declaration;\n    return declaration;\n  }\n\n  if (outputFile) {\n    outputFile = path.resolve(process.cwd(), outputFile);\n    if (apiFile.startsWith('.')) {\n      apiFile = path.relative(path.dirname(outputFile), apiFile);\n      apiFile = apiFile.replace(/\\\\/g, '/');\n      if (!apiFile.startsWith('.')) apiFile = `./${apiFile}`;\n    }\n  }\n\n  if (esmExtensions === true) {\n    // Convert TS/JSX extensions to their JS equivalents\n    apiFile = apiFile\n      .replace(/\\.mts$/, '.mjs')\n      .replace(/\\.[jt]sx$/, '.jsx')\n      .replace(/\\.ts$/, '.js');\n  } else {\n    // Remove all extensions\n    apiFile = apiFile.replace(/\\.[jt]sx?$/, '');\n  }\n\n  return printer.printNode(\n    ts.EmitHint.Unspecified,\n    factory.createSourceFile(\n      [\n        generateImportNode(apiFile, { [apiImport]: 'api' }),\n        ...(tag ? [generateTagTypes({ addTagTypes: extractAllTagTypes({ operationDefinitions }) })] : []),\n        generateCreateApiCall({\n          tag,\n          endpointDefinitions: factory.createObjectLiteralExpression(\n            operationDefinitions.map((operationDefinition) =>\n              generateEndpoint({\n                operationDefinition,\n                overrides: getOverrides(operationDefinition, endpointOverrides),\n              })\n            ),\n            true\n          ),\n        }),\n        factory.createExportDeclaration(\n          undefined,\n          false,\n          factory.createNamedExports([\n            factory.createExportSpecifier(\n              factory.createIdentifier(generatedApiName),\n              factory.createIdentifier(exportName)\n            ),\n          ]),\n          undefined\n        ),\n        ...Object.values(interfaces),\n        ...(outputRegexConstants\n          ? apiGen.aliases.flatMap((alias) => {\n              if (!ts.isInterfaceDeclaration(alias) && !ts.isTypeAliasDeclaration(alias)) return [alias];\n\n              const typeName = alias.name.escapedText.toString();\n              const schema = v3Doc.components?.schemas?.[typeName];\n              if (!schema) return [alias];\n\n              const regexConstants = generateRegexConstantsForType(typeName, schema, apiGen);\n              return regexConstants.length > 0 ? [alias, ...regexConstants] : [alias];\n            })\n          : apiGen.aliases),\n        ...apiGen.enumAliases,\n        ...(hooks\n          ? [\n              generateReactHooks({\n                exportName: generatedApiName,\n                operationDefinitions,\n                endpointOverrides,\n                config: hooks,\n                operationNameSuffix,\n              }),\n            ]\n          : []),\n      ],\n      factory.createToken(ts.SyntaxKind.EndOfFileToken),\n      ts.NodeFlags.None\n    ),\n    resultFile\n  );\n\n  function extractAllTagTypes({ operationDefinitions }: { operationDefinitions: OperationDefinition[] }) {\n    const allTagTypes = new Set<string>();\n\n    for (const operationDefinition of operationDefinitions) {\n      const { verb, pathItem } = operationDefinition;\n      for (const tag of getTags({ verb, pathItem })) {\n        allTagTypes.add(tag);\n      }\n    }\n    return [...allTagTypes];\n  }\n\n  function generateEndpoint({\n    operationDefinition,\n    overrides,\n  }: {\n    operationDefinition: OperationDefinition;\n    overrides?: EndpointOverrides;\n  }) {\n    const {\n      verb,\n      path,\n      pathItem,\n      operation,\n      operation: { responses, requestBody },\n    } = operationDefinition;\n    const operationName = getOperationName({ verb, path, operation });\n    const tags = tag ? getTags({ verb, pathItem }) : undefined;\n    const isQuery = testIsQuery(verb, overrides);\n\n    const returnsJson = apiGen.getResponseType(responses) === 'json';\n    let ResponseType: ts.TypeNode = factory.createKeywordTypeNode(ts.SyntaxKind.UnknownKeyword);\n    if (returnsJson) {\n      const returnTypes = Object.entries(responses || {})\n        .map(\n          ([code, response]) =>\n            [\n              code,\n              apiGen.resolve(response),\n              apiGen.getTypeFromResponse(response, 'readOnly') ||\n                factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword),\n            ] as const\n        )\n        .filter(([status, response]) =>\n          isDataResponse(status, includeDefault, apiGen.resolve(response), responses || {})\n        )\n        .filter(([_1, _2, type]) => type !== keywordType.void)\n        .map(([code, response, type]) =>\n          ts.addSyntheticLeadingComment(\n            { ...type },\n            ts.SyntaxKind.MultiLineCommentTrivia,\n            `* status ${code} ${response.description} `,\n            false\n          )\n        );\n      if (returnTypes.length > 0) {\n        ResponseType = factory.createUnionTypeNode(returnTypes);\n      }\n    }\n\n    const ResponseTypeName = factory.createTypeReferenceNode(\n      registerInterface(\n        factory.createTypeAliasDeclaration(\n          [factory.createModifier(ts.SyntaxKind.ExportKeyword)],\n          capitalize(operationName + operationNameSuffix + responseSuffix),\n          undefined,\n          ResponseType\n        )\n      ).name\n    );\n\n    const operationParameters = apiGen.resolveArray(operation.parameters);\n    const pathItemParameters = apiGen\n      .resolveArray(pathItem.parameters)\n      .filter((pp) => !operationParameters.some((op) => op.name === pp.name && op.in === pp.in));\n\n    const parameters = supportDeepObjects([...pathItemParameters, ...operationParameters]).filter(\n      argumentMatches(overrides?.parameterFilter)\n    );\n\n    const allNames = parameters.map((p) => p.name);\n    const queryArg: QueryArgDefinitions = {};\n    function generateName(name: string, potentialPrefix: string) {\n      const isPureSnakeCase = /^[a-zA-Z][a-zA-Z0-9_]*$/.test(name);\n      // prefix with `query`, `path` or `body` if there are multiple paramters with the same name\n      const hasNamingConflict = allNames.filter((n) => n === name).length > 1;\n      if (hasNamingConflict) {\n        name = `${potentialPrefix}_${name}`;\n      }\n      // convert to camelCase if the name is pure snake_case and there are no naming conflicts\n      const camelCaseName = camelCase(name);\n      if (isPureSnakeCase && !allNames.includes(camelCaseName)) {\n        name = camelCaseName;\n      }\n      // if there are still any naming conflicts, prepend with underscore\n      while (name in queryArg) {\n        name = `_${name}`;\n      }\n      return name;\n    }\n\n    for (const param of parameters) {\n      const name = generateName(param.name, param.in);\n      queryArg[name] = {\n        origin: 'param',\n        name,\n        originalName: param.name,\n        type: apiGen.getTypeFromSchema(isReference(param) ? param : param.schema, undefined, 'writeOnly'),\n        required: param.required,\n        param,\n      };\n    }\n\n    if (requestBody) {\n      const body = apiGen.resolve(requestBody);\n      const schema = apiGen.getSchemaFromContent(body.content);\n      const type = apiGen.getTypeFromSchema(schema);\n      const schemaName = camelCase(\n        (type as any).name ||\n          getReferenceName(schema) ||\n          (typeof schema === 'object' && 'title' in schema && schema.title) ||\n          'body'\n      );\n      const name = generateName(schemaName in queryArg ? 'body' : schemaName, 'body');\n\n      queryArg[name] = {\n        origin: 'body',\n        name,\n        originalName: schemaName,\n        type: apiGen.getTypeFromSchema(schema, undefined, 'writeOnly'),\n        required: true,\n        body,\n      };\n    }\n\n    const propertyName = (name: string | ts.PropertyName): ts.PropertyName => {\n      if (typeof name === 'string') {\n        return isValidIdentifier(name) ? factory.createIdentifier(name) : factory.createStringLiteral(name);\n      }\n      return name;\n    };\n\n    const queryArgValues = Object.values(queryArg);\n\n    const isFlatArg = flattenArg && queryArgValues.length === 1;\n    const QueryArg = factory.createTypeReferenceNode(\n      registerInterface(\n        factory.createTypeAliasDeclaration(\n          [factory.createModifier(ts.SyntaxKind.ExportKeyword)],\n          capitalize(operationName + operationNameSuffix + argSuffix),\n          undefined,\n          queryArgValues.length > 0\n            ? isFlatArg\n              ? withQueryComment(\n                  factory.createUnionTypeNode([\n                    queryArgValues[0].type,\n                    ...(!queryArgValues[0].required\n                      ? [factory.createKeywordTypeNode(ts.SyntaxKind.UndefinedKeyword)]\n                      : []),\n                  ]),\n                  queryArgValues[0],\n                  false\n                )\n              : factory.createTypeLiteralNode(\n                  queryArgValues.map((def) =>\n                    withQueryComment(\n                      factory.createPropertySignature(\n                        undefined,\n                        propertyName(def.name),\n                        createQuestionToken(!def.required),\n                        def.type\n                      ),\n                      def,\n                      true\n                    )\n                  )\n                )\n            : factory.createKeywordTypeNode(ts.SyntaxKind.VoidKeyword)\n        )\n      ).name\n    );\n\n    const tagOverrides =\n      overrides && (overrides.providesTags !== undefined || overrides.invalidatesTags !== undefined)\n        ? {\n            ...(overrides.providesTags !== undefined ? { providesTags: overrides.providesTags } : {}),\n            ...(overrides.invalidatesTags !== undefined ? { invalidatesTags: overrides.invalidatesTags } : {}),\n          }\n        : undefined;\n\n    return generateEndpointDefinition({\n      operationName: operationNameSuffix ? capitalize(operationName + operationNameSuffix) : operationName,\n      type: isQuery ? 'query' : 'mutation',\n      Response: ResponseTypeName,\n      QueryArg,\n      queryFn: generateQueryFn({\n        operationDefinition,\n        queryArg,\n        isQuery,\n        isFlatArg,\n        encodePathParams,\n        encodeQueryParams,\n      }),\n      extraEndpointsProps: isQuery\n        ? generateQueryEndpointProps({ operationDefinition })\n        : generateMutationEndpointProps({ operationDefinition }),\n      tags,\n      tagOverrides,\n    });\n  }\n\n  function generateQueryFn({\n    operationDefinition,\n    queryArg,\n    isFlatArg,\n    isQuery,\n    encodePathParams,\n    encodeQueryParams,\n  }: {\n    operationDefinition: OperationDefinition;\n    queryArg: QueryArgDefinitions;\n    isFlatArg: boolean;\n    isQuery: boolean;\n    encodePathParams: boolean;\n    encodeQueryParams: boolean;\n  }) {\n    const { path, verb } = operationDefinition;\n\n    const bodyParameter = Object.values(queryArg).find((def) => def.origin === 'body');\n\n    const rootObject = factory.createIdentifier('queryArg');\n\n    function pickParams(paramIn: string) {\n      return Object.values(queryArg).filter((def) => def.origin === 'param' && def.param.in === paramIn);\n    }\n\n    function createObjectLiteralProperty(parameters: QueryArgDefinition[], propertyName: string) {\n      if (parameters.length === 0) return undefined;\n\n      const properties = parameters.map((param) => {\n        const value = isFlatArg ? rootObject : accessProperty(rootObject, param.name);\n\n        const encodedValue =\n          encodeQueryParams && param.param?.in === 'query'\n            ? factory.createConditionalExpression(\n                factory.createBinaryExpression(value, ts.SyntaxKind.ExclamationEqualsToken, factory.createNull()),\n                undefined,\n                factory.createCallExpression(factory.createIdentifier('encodeURIComponent'), undefined, [\n                  factory.createCallExpression(factory.createIdentifier('String'), undefined, [value]),\n                ]),\n                undefined,\n                factory.createIdentifier('undefined')\n              )\n            : value;\n\n        return createPropertyAssignment(param.originalName, encodedValue);\n      });\n\n      return factory.createPropertyAssignment(\n        factory.createIdentifier(propertyName),\n        factory.createObjectLiteralExpression(properties, true)\n      );\n    }\n\n    return factory.createArrowFunction(\n      undefined,\n      undefined,\n      Object.keys(queryArg).length\n        ? [factory.createParameterDeclaration(undefined, undefined, rootObject, undefined, undefined, undefined)]\n        : [],\n      undefined,\n      factory.createToken(ts.SyntaxKind.EqualsGreaterThanToken),\n      factory.createParenthesizedExpression(\n        factory.createObjectLiteralExpression(\n          [\n            factory.createPropertyAssignment(\n              factory.createIdentifier('url'),\n              generatePathExpression(path, pickParams('path'), rootObject, isFlatArg, encodePathParams)\n            ),\n            isQuery && verb.toUpperCase() === 'GET'\n              ? undefined\n              : factory.createPropertyAssignment(\n                  factory.createIdentifier('method'),\n                  factory.createStringLiteral(verb.toUpperCase())\n                ),\n            bodyParameter === undefined\n              ? undefined\n              : factory.createPropertyAssignment(\n                  factory.createIdentifier('body'),\n                  isFlatArg\n                    ? rootObject\n                    : factory.createPropertyAccessExpression(rootObject, factory.createIdentifier(bodyParameter.name))\n                ),\n            createObjectLiteralProperty(pickParams('cookie'), 'cookies'),\n            createObjectLiteralProperty(pickParams('header'), 'headers'),\n            createObjectLiteralProperty(pickParams('query'), 'params'),\n          ].filter(removeUndefined),\n          false\n        )\n      )\n    );\n  }\n\n  // eslint-disable-next-line no-empty-pattern\n  function generateQueryEndpointProps({}: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions {\n    return {}; /* TODO needs implementation - skip for now */\n  }\n\n  // eslint-disable-next-line no-empty-pattern\n  function generateMutationEndpointProps({}: { operationDefinition: OperationDefinition }): ObjectPropertyDefinitions {\n    return {}; /* TODO needs implementation - skip for now */\n  }\n}\n\nfunction accessProperty(rootObject: ts.Identifier, propertyName: string) {\n  return isValidIdentifier(propertyName)\n    ? factory.createPropertyAccessExpression(rootObject, factory.createIdentifier(propertyName))\n    : factory.createElementAccessExpression(rootObject, factory.createStringLiteral(propertyName));\n}\n\nfunction generatePathExpression(\n  path: string,\n  pathParameters: QueryArgDefinition[],\n  rootObject: ts.Identifier,\n  isFlatArg: boolean,\n  encodePathParams: boolean\n) {\n  const expressions: Array<[string, string]> = [];\n\n  const head = path.replace(/\\{(.*?)}(.*?)(?=\\{|$)/g, (_, expression, literal) => {\n    const param = pathParameters.find((p) => p.originalName === expression);\n    if (!param) {\n      throw new Error(`path parameter ${expression} does not seem to be defined in '${path}'!`);\n    }\n    expressions.push([param.name, literal]);\n    return '';\n  });\n\n  return expressions.length\n    ? factory.createTemplateExpression(\n        factory.createTemplateHead(head),\n        expressions.map(([prop, literal], index) => {\n          const value = isFlatArg ? rootObject : accessProperty(rootObject, prop);\n          const encodedValue = encodePathParams\n            ? factory.createCallExpression(factory.createIdentifier('encodeURIComponent'), undefined, [\n                factory.createCallExpression(factory.createIdentifier('String'), undefined, [value]),\n              ])\n            : value;\n          return factory.createTemplateSpan(\n            encodedValue,\n            index === expressions.length - 1\n              ? factory.createTemplateTail(literal)\n              : factory.createTemplateMiddle(literal)\n          );\n        })\n      )\n    : factory.createNoSubstitutionTemplateLiteral(head);\n}\n\ntype QueryArgDefinition = {\n  name: string;\n  originalName: string;\n  type: ts.TypeNode;\n  required?: boolean;\n  param?: OpenAPIV3.ParameterObject;\n} & (\n  | {\n      origin: 'param';\n      param: OpenAPIV3.ParameterObject;\n    }\n  | {\n      origin: 'body';\n      body: OpenAPIV3.RequestBodyObject;\n    }\n);\ntype QueryArgDefinitions = Record<string, QueryArgDefinition>;\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/generators/react-hooks.ts",
    "content": "import ts from 'typescript';\nimport { getOperationName } from 'oazapfts/generate';\nimport { capitalize, isQuery } from '../utils';\nimport type { OperationDefinition, EndpointOverrides, ConfigFile } from '../types';\nimport { getOverrides } from '../generate';\nimport { factory } from '../utils/factory';\n\ntype HooksConfigOptions = NonNullable<ConfigFile['hooks']>;\n\ntype GetReactHookNameParams = {\n  operationDefinition: OperationDefinition;\n  endpointOverrides: EndpointOverrides[] | undefined;\n  config: HooksConfigOptions;\n  operationNameSuffix?: string;\n};\n\ntype CreateBindingParams = {\n  operationDefinition: OperationDefinition;\n  overrides?: EndpointOverrides;\n  isLazy?: boolean;\n  operationNameSuffix?: string;\n};\n\nconst createBinding = ({\n  operationDefinition: { verb, path, operation },\n  overrides,\n  isLazy = false,\n  operationNameSuffix,\n}: CreateBindingParams) =>\n  factory.createBindingElement(\n    undefined,\n    undefined,\n    factory.createIdentifier(\n      `use${isLazy ? 'Lazy' : ''}${capitalize(getOperationName(verb, path, operation.operationId))}${operationNameSuffix ?? ''}${\n        isQuery(verb, overrides) ? 'Query' : 'Mutation'\n      }`\n    ),\n    undefined\n  );\n\nconst getReactHookName = ({ operationDefinition, endpointOverrides, config, operationNameSuffix }: GetReactHookNameParams) => {\n  const overrides = getOverrides(operationDefinition, endpointOverrides);\n\n  const baseParams = {\n    operationDefinition,\n    overrides,\n    operationNameSuffix,\n  };\n\n  const _isQuery = isQuery(operationDefinition.verb, overrides);\n\n  // If `config` is true, just generate everything\n  if (typeof config === 'boolean') {\n    return createBinding(baseParams);\n  }\n\n  // `config` is an object and we need to check for the configuration of each property\n  if (_isQuery) {\n    return [\n      ...(config.queries ? [createBinding(baseParams)] : []),\n      ...(config.lazyQueries ? [createBinding({ ...baseParams, isLazy: true })] : []),\n    ];\n  }\n\n  return config.mutations ? createBinding(baseParams) : [];\n};\n\ntype GenerateReactHooksParams = {\n  exportName: string;\n  operationDefinitions: OperationDefinition[];\n  endpointOverrides: EndpointOverrides[] | undefined;\n  config: HooksConfigOptions;\n  operationNameSuffix?: string;\n};\nexport const generateReactHooks = ({\n  exportName,\n  operationDefinitions,\n  endpointOverrides,\n  config,\n  operationNameSuffix,\n}: GenerateReactHooksParams) =>\n  factory.createVariableStatement(\n    [factory.createModifier(ts.SyntaxKind.ExportKeyword)],\n    factory.createVariableDeclarationList(\n      [\n        factory.createVariableDeclaration(\n          factory.createObjectBindingPattern(\n            operationDefinitions\n              .map((operationDefinition) => getReactHookName({ operationDefinition, endpointOverrides, config, operationNameSuffix }))\n              .flat()\n          ),\n          undefined,\n          undefined,\n          factory.createIdentifier(exportName)\n        ),\n      ],\n      ts.NodeFlags.Const\n    )\n  );\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/index.ts",
    "content": "import fs from 'node:fs';\nimport { createRequire } from 'node:module';\nimport path from 'node:path';\nimport { generateApi } from './generate';\nimport type { CommonOptions, ConfigFile, GenerationOptions, OutputFileOptions } from './types';\nimport { isValidUrl, prettify } from './utils';\nexport type { ConfigFile } from './types';\n\nconst require = createRequire(__filename);\n\nexport async function generateEndpoints(options: GenerationOptions): Promise<string | void> {\n  const schemaLocation = options.schemaFile;\n\n  const schemaAbsPath = isValidUrl(options.schemaFile)\n    ? options.schemaFile\n    : path.resolve(process.cwd(), schemaLocation);\n\n  const sourceCode = await enforceOazapftsTsVersion(async () => {\n    return generateApi(schemaAbsPath, options);\n  });\n  const { outputFile, prettierConfigFile } = options;\n  if (outputFile) {\n    fs.writeFileSync(\n      path.resolve(process.cwd(), outputFile),\n      await prettify(outputFile, sourceCode, prettierConfigFile)\n    );\n  } else {\n    return await prettify(null, sourceCode, prettierConfigFile);\n  }\n}\n\nexport function parseConfig(fullConfig: ConfigFile) {\n  const outFiles: (CommonOptions & OutputFileOptions)[] = [];\n\n  if ('outputFiles' in fullConfig) {\n    const { outputFiles, ...commonConfig } = fullConfig;\n    for (const [outputFile, specificConfig] of Object.entries(outputFiles)) {\n      outFiles.push({\n        ...commonConfig,\n        ...specificConfig,\n        outputFile,\n      });\n    }\n  } else {\n    outFiles.push(fullConfig);\n  }\n  return outFiles;\n}\n\n/**\n * Enforces `oazapfts` to use the same TypeScript version as this module itself uses.\n * That should prevent enums from running out of sync if both libraries use different TS versions.\n */\nfunction enforceOazapftsTsVersion<T>(cb: () => T): T {\n  const ozTsPath = require.resolve('typescript', { paths: [require.resolve('oazapfts')] });\n  const tsPath = require.resolve('typescript');\n  const originalEntry = require.cache[ozTsPath];\n  try {\n    require.cache[ozTsPath] = require.cache[tsPath];\n    return cb();\n  } finally {\n    if (originalEntry) {\n      require.cache[ozTsPath] = originalEntry;\n    } else {\n      delete require.cache[ozTsPath];\n    }\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/types.ts",
    "content": "import type SwaggerParser from '@apidevtools/swagger-parser';\nimport type { OpenAPIV3 } from 'openapi-types';\n\nexport type OperationDefinition = {\n  path: string;\n  verb: (typeof operationKeys)[number];\n  pathItem: OpenAPIV3.PathItemObject;\n  operation: OpenAPIV3.OperationObject;\n};\n\nexport type ParameterDefinition = OpenAPIV3.ParameterObject;\n\ntype Require<T, K extends keyof T> = { [k in K]-?: NonNullable<T[k]> } & Omit<T, K>;\ntype Optional<T, K extends keyof T> = { [k in K]?: NonNullable<T[k]> } & Omit<T, K>;\ntype Id<T> = { [K in keyof T]: T[K] } & {};\ntype AtLeastOneKey<T> = {\n  [K in keyof T]-?: Pick<T, K> & Partial<T>;\n}[keyof T];\n\nexport const operationKeys = ['get', 'put', 'post', 'delete', 'options', 'head', 'patch', 'trace'] as const;\n\nexport type GenerationOptions = Id<\n  CommonOptions &\n    Optional<OutputFileOptions, 'outputFile'> & {\n      isDataResponse?(\n        code: string,\n        includeDefault: boolean,\n        response: OpenAPIV3.ResponseObject,\n        allResponses: OpenAPIV3.ResponsesObject\n      ): boolean;\n    }\n>;\n\nexport interface CommonOptions {\n  apiFile: string;\n  /**\n   * filename or url\n   */\n  schemaFile: string;\n  /**\n   * @default \"api\"\n   */\n  apiImport?: string;\n  /**\n   * @default \"enhancedApi\"\n   */\n  exportName?: string;\n  /**\n   * @default \"ApiArg\"\n   */\n  argSuffix?: string;\n  /**\n   * @default \"ApiResponse\"\n   */\n  responseSuffix?: string;\n  /**\n   * @default \"\"\n   */\n  operationNameSuffix?: string;\n  /**\n   * `true` will generate hooks for queries and mutations, but no lazyQueries\n   * @default false\n   */\n  hooks?: boolean | { queries: boolean; lazyQueries: boolean; mutations: boolean };\n  /**\n   * `true` will generate a union type for `undefined` properties like: `{ id?: string | undefined }` instead of `{ id?: string }`\n   * @default false\n   */\n  unionUndefined?: boolean;\n  /**\n   * `true` will result in all generated endpoints having `providesTags`/`invalidatesTags` declarations for the `tags` of their respective operation definition\n   * @default false\n   * @see https://redux-toolkit.js.org/rtk-query/usage/code-generation for more information\n   */\n  tag?: boolean;\n  /**\n   * `true` will add `encodeURIComponent` to the generated path parameters\n   * @default false\n   */\n  encodePathParams?: boolean;\n  /**\n   * `true` will add `encodeURIComponent` to the generated query parameters\n   * @default false\n   */\n  encodeQueryParams?: boolean;\n  /**\n   * `true` will \"flatten\" the arg so that you can do things like `useGetEntityById(1)` instead of `useGetEntityById({ entityId: 1 })`\n   * @default false\n   */\n  flattenArg?: boolean;\n  /**\n   * If set to `true`, the default response type will be included in the generated code for all endpoints.\n   * @default false\n   * @see https://swagger.io/docs/specification/describing-responses/#default\n   */\n  includeDefault?: boolean;\n  /**\n   * `true` will not generate separate types for read-only and write-only properties.\n   * @default false\n   */\n  mergeReadWriteOnly?: boolean;\n  /**\n   * HTTPResolverOptions object that is passed to the SwaggerParser bundle function.\n   */\n  httpResolverOptions?: SwaggerParser.HTTPResolverOptions;\n\n  /**\n   * If present the given file will be used as prettier config when formatting the generated code. If undefined the default prettier config\n   * resolution mechanism will be used.\n   * @default undefined\n   */\n  prettierConfigFile?: string;\n\n  /**\n   * Determines the fallback type for empty schemas.\n   *\n   * If set to **`true`**, **`unknown`** will be used\n   * instead of **`any`** when a schema is empty.\n   *\n   * @default false\n   * @since 2.1.0\n   */\n  useUnknown?: boolean;\n  /**\n   * @default false\n   * Will generate imports with file extension matching the expected compiled output of the api file\n   */\n  esmExtensions?: boolean;\n  /**\n   * @default false\n   * Will generate regex constants for pattern keywords in the schema\n   */\n  outputRegexConstants?: boolean;\n}\n\nexport type TextMatcher = string | RegExp | (string | RegExp)[];\n\nexport type EndpointMatcherFunction = (operationName: string, operationDefinition: OperationDefinition) => boolean;\n\nexport type EndpointMatcher = TextMatcher | EndpointMatcherFunction;\n\nexport type ParameterMatcherFunction = (parameterName: string, parameterDefinition: ParameterDefinition) => boolean;\n\nexport type ParameterMatcher = TextMatcher | ParameterMatcherFunction;\n\nexport interface OutputFileOptions extends Partial<CommonOptions> {\n  outputFile: string;\n  filterEndpoints?: EndpointMatcher;\n  endpointOverrides?: EndpointOverrides[];\n  /**\n   * If passed as true it will generate TS enums instead of union of strings\n   * @default false\n   */\n  useEnumType?: boolean;\n}\n\n/**\n * Configuration for overriding specific endpoint behaviors during code generation.\n * At least one override option (besides `pattern`) must be specified.\n */\nexport type EndpointOverrides = {\n  /** Pattern to match endpoint names. Can be a string, RegExp, or matcher function. */\n  pattern: EndpointMatcher;\n} & AtLeastOneKey<{\n  /** Override the endpoint type (query vs mutation) when the inferred type is incorrect. */\n  type: 'mutation' | 'query';\n  /** Filter which parameters are included in the generated endpoint. Path parameters cannot be filtered. */\n  parameterFilter: ParameterMatcher;\n  /**\n   * Override providesTags for this endpoint.\n   * Takes precedence over auto-generated tags from OpenAPI spec.\n   * Use an empty array to explicitly omit providesTags.\n   * Works regardless of the global `tag` setting and endpoint type.\n   * @example ['Pet', 'SinglePet']\n   */\n  providesTags: string[];\n  /**\n   * Override invalidatesTags for this endpoint.\n   * Takes precedence over auto-generated tags from OpenAPI spec.\n   * Use an empty array to explicitly omit invalidatesTags.\n   * Works regardless of the global `tag` setting and endpoint type.\n   * @example ['Pet', 'PetList']\n   */\n  invalidatesTags: string[];\n}>;\n\nexport type ConfigFile =\n  | Id<Require<CommonOptions & OutputFileOptions, 'outputFile'>>\n  | Id<\n      Omit<CommonOptions, 'outputFile'> & {\n        outputFiles: { [outputFile: string]: Omit<OutputFileOptions, 'outputFile'> };\n      }\n    >;\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/utils/capitalize.ts",
    "content": "export function capitalize(str: string) {\n  return str.replace(str[0], str[0].toUpperCase());\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/utils/factory.ts",
    "content": "import ts from 'typescript';\nimport semver from 'semver';\n\nconst originalFactory = ts.factory;\n\nfunction createImportSpecifier(propertyName: ts.Identifier | undefined, name: ts.Identifier): ts.ImportSpecifier {\n  if (semver.satisfies(ts.version, '>= 4.5'))\n    // @ts-ignore\n    return originalFactory.createImportSpecifier(false, propertyName, name);\n  // @ts-ignore\n  return originalFactory.createImportSpecifier(propertyName, name);\n}\n\nfunction createExportSpecifier(\n  propertyName: string | ts.Identifier | undefined,\n  name: string | ts.Identifier\n): ts.ExportSpecifier {\n  if (semver.satisfies(ts.version, '>= 4.5'))\n    // @ts-ignore\n    return originalFactory.createExportSpecifier(false, propertyName, name);\n  // @ts-ignore\n  return originalFactory.createExportSpecifier(propertyName, name);\n}\n\nexport const factory = {\n  ...originalFactory,\n  createImportSpecifier,\n  createExportSpecifier,\n};\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/utils/getOperationDefinitions.ts",
    "content": "import type { OpenAPIV3 } from 'openapi-types';\nimport type { OperationDefinition } from '../types';\nimport { operationKeys } from '../types';\n\nexport function getOperationDefinitions(v3Doc: OpenAPIV3.Document): OperationDefinition[] {\n  return Object.entries(v3Doc.paths).flatMap(([path, pathItem]) =>\n    !pathItem\n      ? []\n      : Object.entries(pathItem)\n          .filter((arg): arg is [(typeof operationKeys)[number], OpenAPIV3.OperationObject] =>\n            operationKeys.includes(arg[0] as any)\n          )\n          .map(([verb, operation]) => ({\n            path,\n            verb,\n            pathItem,\n            operation,\n          }))\n  );\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/utils/getV3Doc.ts",
    "content": "import SwaggerParser from '@apidevtools/swagger-parser';\nimport type { OpenAPIV3 } from 'openapi-types';\n// @ts-ignore\nimport converter from 'swagger2openapi';\n\nexport async function getV3Doc(\n  spec: string,\n  httpResolverOptions?: SwaggerParser.HTTPResolverOptions\n): Promise<OpenAPIV3.Document> {\n  const doc = await SwaggerParser.bundle(spec, {\n    resolve: {\n      http: httpResolverOptions,\n    },\n  });\n\n  const isOpenApiV3 = 'openapi' in doc && doc.openapi.startsWith('3');\n\n  if (isOpenApiV3) {\n    return doc as OpenAPIV3.Document;\n  } else {\n    const result = await converter.convertObj(doc, {});\n    return result.openapi as OpenAPIV3.Document;\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/utils/index.ts",
    "content": "export * from './capitalize';\nexport * from './getOperationDefinitions';\nexport * from './getV3Doc';\nexport * from './isQuery';\nexport * from './isValidUrl';\nexport * from './prettier';\nexport * from './messages';\nexport * from './removeUndefined';\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/utils/isQuery.ts",
    "content": "import type { EndpointOverrides, operationKeys } from '../types';\n\nexport function isQuery(verb: (typeof operationKeys)[number], overrides: EndpointOverrides | undefined) {\n  if (overrides?.type) {\n    return overrides.type === 'query';\n  }\n  return verb === 'get';\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/utils/isValidUrl.ts",
    "content": "export function isValidUrl(string: string) {\n  try {\n    new URL(string);\n  } catch (_) {\n    return false;\n  }\n\n  return true;\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/utils/messages.ts",
    "content": "export const MESSAGES = {\n  NAMED_EXPORT_MISSING: `You specified a named export that does not exist or was empty.`,\n  DEFAULT_EXPORT_MISSING: `Specified file exists, but no default export was found for the --baseQuery`,\n  FILE_NOT_FOUND: `Unable to locate the specified file provided to --baseQuery`,\n  TSCONFIG_FILE_NOT_FOUND: `Unable to locate the specified file provided to -c, --config`,\n  BASE_URL_IGNORED: `The url provided to --baseUrl is ignored when using --baseQuery`,\n};\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/utils/prettier.ts",
    "content": "import path from 'node:path';\nimport prettier from 'prettier';\nimport type { BuiltInParserName } from 'prettier';\n\nconst EXTENSION_TO_PARSER: Record<string, BuiltInParserName> = {\n  ts: 'typescript',\n  tsx: 'typescript',\n  js: 'babel',\n  jsx: 'babel',\n  'js.flow': 'flow',\n  flow: 'flow',\n  gql: 'graphql',\n  graphql: 'graphql',\n  css: 'scss',\n  scss: 'scss',\n  less: 'scss',\n  stylus: 'scss',\n  markdown: 'markdown',\n  md: 'markdown',\n  json: 'json',\n};\n\nexport async function prettify(filePath: string | null, content: string, prettierConfigFile?: string): Promise<string> {\n  let config = null;\n  let parser = 'typescript';\n\n  if (filePath) {\n    const fileExtension = path.extname(filePath).slice(1);\n    parser = EXTENSION_TO_PARSER[fileExtension];\n    config = await prettier.resolveConfig(process.cwd(), {\n      useCache: true,\n      editorconfig: !prettierConfigFile,\n      config: prettierConfigFile,\n    });\n  } else if (prettierConfigFile) {\n    config = await prettier.resolveConfig(process.cwd(), {\n      useCache: true,\n      config: prettierConfigFile,\n    });\n  }\n\n  return prettier.format(content, {\n    parser,\n    ...config,\n  });\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/src/utils/removeUndefined.ts",
    "content": "export function removeUndefined<T>(t: T | undefined): t is T {\n  return typeof t !== 'undefined';\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/__snapshots__/cli.test.ts.snap",
    "content": "// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html\n\nexports[`CLI options testing > generation with \\`config.example.js\\` 1`] = `\n\"import { api } from '../fixtures/emptyApi';\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: 'PUT', body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: 'POST', body: queryArg.pet }),\n    }),\n    findPetsByStatus: build.query<FindPetsByStatusApiResponse, FindPetsByStatusApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/findByStatus\\`,\n        params: {\n          status: queryArg.status,\n        },\n      }),\n    }),\n    findPetsByTags: build.query<FindPetsByTagsApiResponse, FindPetsByTagsApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/findByTags\\`,\n        params: {\n          tags: queryArg.tags,\n        },\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n    updatePetWithForm: build.mutation<UpdatePetWithFormApiResponse, UpdatePetWithFormApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: 'POST',\n        params: {\n          name: queryArg.name,\n          status: queryArg.status,\n        },\n      }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: 'DELETE',\n        headers: {\n          api_key: queryArg.apiKey,\n        },\n      }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n        method: 'POST',\n        body: queryArg.body,\n        params: {\n          additionalMetadata: queryArg.additionalMetadata,\n        },\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: \\`/store/inventory\\` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order\\`, method: 'POST', body: queryArg.order }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\`, method: 'DELETE' }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user\\`, method: 'POST', body: queryArg.user }),\n    }),\n    createUsersWithListInput: build.mutation<CreateUsersWithListInputApiResponse, CreateUsersWithListInputApiArg>({\n      query: (queryArg) => ({ url: \\`/user/createWithList\\`, method: 'POST', body: queryArg.body }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        params: {\n          username: queryArg.username,\n          password: queryArg.password,\n        },\n      }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: \\`/user/logout\\` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\`, method: 'PUT', body: queryArg.user }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\`, method: 'DELETE' }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse = /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: 'available' | 'pending' | 'sold';\n};\nexport type FindPetsByTagsApiResponse = /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = {\n  /** Tags to filter by */\n  tags?: string[];\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n  /** Status of pet that needs to be updated */\n  status?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  apiKey?: string;\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse = /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse = /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse = /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse = /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse = /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse = /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number;\n  name?: string;\n};\nexport type Tag = {\n  id?: number;\n  name?: string;\n};\nexport type Pet = {\n  id?: number;\n  name: string;\n  category?: Category;\n  photoUrls: string[];\n  tags?: Tag[];\n  /** pet status in the store */\n  status?: 'available' | 'pending' | 'sold';\n};\nexport type ApiResponse = {\n  code?: number;\n  type?: string;\n  message?: string;\n};\nexport type Order = {\n  id?: number;\n  petId?: number;\n  quantity?: number;\n  shipDate?: string;\n  /** Order Status */\n  status?: 'placed' | 'approved' | 'delivered';\n  complete?: boolean;\n};\nexport type User = {\n  id?: number;\n  username?: string;\n  firstName?: string;\n  lastName?: string;\n  email?: string;\n  password?: string;\n  phone?: string;\n  website?: string;\n  /** User Status */\n  userStatus?: number;\n};\n\"\n`;\n\nexports[`CLI options testing > paths are relative to config file, not to cwd 1`] = `\n\"import { api } from '../fixtures/emptyApi';\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: 'PUT', body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: 'POST', body: queryArg.pet }),\n    }),\n    findPetsByStatus: build.query<FindPetsByStatusApiResponse, FindPetsByStatusApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/findByStatus\\`,\n        params: {\n          status: queryArg.status,\n        },\n      }),\n    }),\n    findPetsByTags: build.query<FindPetsByTagsApiResponse, FindPetsByTagsApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/findByTags\\`,\n        params: {\n          tags: queryArg.tags,\n        },\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n    updatePetWithForm: build.mutation<UpdatePetWithFormApiResponse, UpdatePetWithFormApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: 'POST',\n        params: {\n          name: queryArg.name,\n          status: queryArg.status,\n        },\n      }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: 'DELETE',\n        headers: {\n          api_key: queryArg.apiKey,\n        },\n      }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n        method: 'POST',\n        body: queryArg.body,\n        params: {\n          additionalMetadata: queryArg.additionalMetadata,\n        },\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: \\`/store/inventory\\` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order\\`, method: 'POST', body: queryArg.order }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\`, method: 'DELETE' }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user\\`, method: 'POST', body: queryArg.user }),\n    }),\n    createUsersWithListInput: build.mutation<CreateUsersWithListInputApiResponse, CreateUsersWithListInputApiArg>({\n      query: (queryArg) => ({ url: \\`/user/createWithList\\`, method: 'POST', body: queryArg.body }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        params: {\n          username: queryArg.username,\n          password: queryArg.password,\n        },\n      }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: \\`/user/logout\\` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\`, method: 'PUT', body: queryArg.user }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\`, method: 'DELETE' }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse = /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: 'available' | 'pending' | 'sold';\n};\nexport type FindPetsByTagsApiResponse = /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = {\n  /** Tags to filter by */\n  tags?: string[];\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n  /** Status of pet that needs to be updated */\n  status?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  apiKey?: string;\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse = /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse = /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse = /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse = /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse = /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse = /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number;\n  name?: string;\n};\nexport type Tag = {\n  id?: number;\n  name?: string;\n};\nexport type Pet = {\n  id?: number;\n  name: string;\n  category?: Category;\n  photoUrls: string[];\n  tags?: Tag[];\n  /** pet status in the store */\n  status?: 'available' | 'pending' | 'sold';\n};\nexport type ApiResponse = {\n  code?: number;\n  type?: string;\n  message?: string;\n};\nexport type Order = {\n  id?: number;\n  petId?: number;\n  quantity?: number;\n  shipDate?: string;\n  /** Order Status */\n  status?: 'placed' | 'approved' | 'delivered';\n  complete?: boolean;\n};\nexport type User = {\n  id?: number;\n  username?: string;\n  firstName?: string;\n  lastName?: string;\n  email?: string;\n  password?: string;\n  phone?: string;\n  website?: string;\n  /** User Status */\n  userStatus?: number;\n};\n\"\n`;\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/__snapshots__/generateEndpoints.test.ts.snap",
    "content": "// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html\n\nexports[`CLI options testing > generation with \\`config.example.js\\` 1`] = `\n\"import { api } from '../fixtures/emptyApi';\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: 'PUT', body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: 'POST', body: queryArg.pet }),\n    }),\n    findPetsByStatus: build.query<FindPetsByStatusApiResponse, FindPetsByStatusApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/findByStatus\\`,\n        params: {\n          status: queryArg.status,\n        },\n      }),\n    }),\n    findPetsByTags: build.query<FindPetsByTagsApiResponse, FindPetsByTagsApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/findByTags\\`,\n        params: {\n          tags: queryArg.tags,\n        },\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n    updatePetWithForm: build.mutation<UpdatePetWithFormApiResponse, UpdatePetWithFormApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: 'POST',\n        params: {\n          name: queryArg.name,\n          status: queryArg.status,\n        },\n      }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: 'DELETE',\n        headers: {\n          api_key: queryArg.apiKey,\n        },\n      }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n        method: 'POST',\n        body: queryArg.body,\n        params: {\n          additionalMetadata: queryArg.additionalMetadata,\n        },\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: \\`/store/inventory\\` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order\\`, method: 'POST', body: queryArg.order }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\`, method: 'DELETE' }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user\\`, method: 'POST', body: queryArg.user }),\n    }),\n    createUsersWithListInput: build.mutation<CreateUsersWithListInputApiResponse, CreateUsersWithListInputApiArg>({\n      query: (queryArg) => ({ url: \\`/user/createWithList\\`, method: 'POST', body: queryArg.body }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        params: {\n          username: queryArg.username,\n          password: queryArg.password,\n        },\n      }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: \\`/user/logout\\` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\`, method: 'PUT', body: queryArg.user }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\`, method: 'DELETE' }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse = /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: 'available' | 'pending' | 'sold';\n};\nexport type FindPetsByTagsApiResponse = /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = {\n  /** Tags to filter by */\n  tags?: string[];\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n  /** Status of pet that needs to be updated */\n  status?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  apiKey?: string;\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse = /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse = /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse = /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse = /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse = /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse = /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number;\n  name?: string;\n};\nexport type Tag = {\n  id?: number;\n  name?: string;\n};\nexport type Pet = {\n  id?: number;\n  name: string;\n  category?: Category;\n  photoUrls: string[];\n  tags?: Tag[];\n  /** pet status in the store */\n  status?: 'available' | 'pending' | 'sold';\n};\nexport type ApiResponse = {\n  code?: number;\n  type?: string;\n  message?: string;\n};\nexport type Order = {\n  id?: number;\n  petId?: number;\n  quantity?: number;\n  shipDate?: string;\n  /** Order Status */\n  status?: 'placed' | 'approved' | 'delivered';\n  complete?: boolean;\n};\nexport type User = {\n  id?: number;\n  username?: string;\n  firstName?: string;\n  lastName?: string;\n  email?: string;\n  password?: string;\n  phone?: string;\n  website?: string;\n  /** User Status */\n  userStatus?: number;\n};\n\"\n`;\n\nexports[`CLI options testing > paths are relative to config file, not to cwd 1`] = `\n\"import { api } from '../fixtures/emptyApi';\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: 'PUT', body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: 'POST', body: queryArg.pet }),\n    }),\n    findPetsByStatus: build.query<FindPetsByStatusApiResponse, FindPetsByStatusApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/findByStatus\\`,\n        params: {\n          status: queryArg.status,\n        },\n      }),\n    }),\n    findPetsByTags: build.query<FindPetsByTagsApiResponse, FindPetsByTagsApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/findByTags\\`,\n        params: {\n          tags: queryArg.tags,\n        },\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n    updatePetWithForm: build.mutation<UpdatePetWithFormApiResponse, UpdatePetWithFormApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: 'POST',\n        params: {\n          name: queryArg.name,\n          status: queryArg.status,\n        },\n      }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: 'DELETE',\n        headers: {\n          api_key: queryArg.apiKey,\n        },\n      }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n        method: 'POST',\n        body: queryArg.body,\n        params: {\n          additionalMetadata: queryArg.additionalMetadata,\n        },\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: \\`/store/inventory\\` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order\\`, method: 'POST', body: queryArg.order }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\`, method: 'DELETE' }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user\\`, method: 'POST', body: queryArg.user }),\n    }),\n    createUsersWithListInput: build.mutation<CreateUsersWithListInputApiResponse, CreateUsersWithListInputApiArg>({\n      query: (queryArg) => ({ url: \\`/user/createWithList\\`, method: 'POST', body: queryArg.body }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        params: {\n          username: queryArg.username,\n          password: queryArg.password,\n        },\n      }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: \\`/user/logout\\` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\`, method: 'PUT', body: queryArg.user }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\`, method: 'DELETE' }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse = /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: 'available' | 'pending' | 'sold';\n};\nexport type FindPetsByTagsApiResponse = /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = {\n  /** Tags to filter by */\n  tags?: string[];\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n  /** Status of pet that needs to be updated */\n  status?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  apiKey?: string;\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse = /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse = /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse = /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse = /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse = /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse = /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number;\n  name?: string;\n};\nexport type Tag = {\n  id?: number;\n  name?: string;\n};\nexport type Pet = {\n  id?: number;\n  name: string;\n  category?: Category;\n  photoUrls: string[];\n  tags?: Tag[];\n  /** pet status in the store */\n  status?: 'available' | 'pending' | 'sold';\n};\nexport type ApiResponse = {\n  code?: number;\n  type?: string;\n  message?: string;\n};\nexport type Order = {\n  id?: number;\n  petId?: number;\n  quantity?: number;\n  shipDate?: string;\n  /** Order Status */\n  status?: 'placed' | 'approved' | 'delivered';\n  complete?: boolean;\n};\nexport type User = {\n  id?: number;\n  username?: string;\n  firstName?: string;\n  lastName?: string;\n  email?: string;\n  password?: string;\n  phone?: string;\n  website?: string;\n  /** User Status */\n  userStatus?: number;\n};\n\"\n`;\n\nexports[`calling without \\`outputFile\\` returns the generated api 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getHealthcheck: build.query<\n      GetHealthcheckApiResponse,\n      GetHealthcheckApiArg\n    >({\n      query: () => ({ url: \\`/healthcheck\\` }),\n    }),\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: \"PUT\", body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    findPetsByStatus: build.query<\n      FindPetsByStatusApiResponse,\n      FindPetsByStatusApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/findByStatus\\`,\n        params: {\n          status: queryArg.status,\n        },\n      }),\n    }),\n    findPetsByTags: build.query<\n      FindPetsByTagsApiResponse,\n      FindPetsByTagsApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/findByTags\\`,\n        params: {\n          tags: queryArg.tags,\n        },\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n    updatePetWithForm: build.mutation<\n      UpdatePetWithFormApiResponse,\n      UpdatePetWithFormApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"POST\",\n        params: {\n          name: queryArg.name,\n          status: queryArg.status,\n        },\n      }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"DELETE\",\n        headers: {\n          api_key: queryArg.apiKey,\n        },\n      }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n        method: \"POST\",\n        body: queryArg.body,\n        params: {\n          additionalMetadata: queryArg.additionalMetadata,\n        },\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: \\`/store/inventory\\` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order\\`,\n        method: \"POST\",\n        body: queryArg.order,\n      }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order/\\${queryArg.orderId}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user\\`,\n        method: \"POST\",\n        body: queryArg.user,\n      }),\n    }),\n    createUsersWithListInput: build.mutation<\n      CreateUsersWithListInputApiResponse,\n      CreateUsersWithListInputApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/user/createWithList\\`,\n        method: \"POST\",\n        body: queryArg.body,\n      }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        params: {\n          username: queryArg.username,\n          password: queryArg.password,\n        },\n      }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: \\`/user/logout\\` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"PUT\",\n        body: queryArg.user,\n      }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetHealthcheckApiResponse = /** status 200 OK */ {\n  message: string;\n};\nexport type GetHealthcheckApiArg = void;\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: \"available\" | \"pending\" | \"sold\";\n};\nexport type FindPetsByTagsApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = {\n  /** Tags to filter by */\n  tags?: string[];\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n  /** Status of pet that needs to be updated */\n  status?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  apiKey?: string;\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse =\n  /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse =\n  /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse =\n  /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse =\n  /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse =\n  /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Tag = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Pet = {\n  id?: number | undefined;\n  name: string;\n  category?: Category | undefined;\n  photoUrls: string[];\n  tags?: Tag[] | undefined;\n  /** pet status in the store */\n  status?: (\"available\" | \"pending\" | \"sold\") | undefined;\n};\nexport type ApiResponse = {\n  code?: number | undefined;\n  type?: string | undefined;\n  message?: string | undefined;\n};\nexport type Order = {\n  id?: number | undefined;\n  petId?: number | undefined;\n  quantity?: number | undefined;\n  shipDate?: string | undefined;\n  /** Order Status */\n  status?: (\"placed\" | \"approved\" | \"delivered\") | undefined;\n  complete?: boolean | undefined;\n};\nexport type User = {\n  id?: number | undefined;\n  username?: string | undefined;\n  firstName?: string | undefined;\n  lastName?: string | undefined;\n  email?: string | undefined;\n  password?: string | undefined;\n  phone?: string | undefined;\n  website?: string | undefined;\n  /** User Status */\n  userStatus?: number | undefined;\n};\n\"\n`;\n\nexports[`duplicate parameter names must be prefixed with a path or query prefix 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    patchApiV1ListByItemId: build.mutation<\n      PatchApiV1ListByItemIdApiResponse,\n      PatchApiV1ListByItemIdApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/api/v1/list/\\${queryArg[\"item.id\"]}\\`,\n        method: \"PATCH\",\n      }),\n    }),\n    patchApiV2BySomeName: build.mutation<\n      PatchApiV2BySomeNameApiResponse,\n      PatchApiV2BySomeNameApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/api/v2/\\${queryArg.pathSomeName}\\`,\n        method: \"PATCH\",\n        params: {\n          some_name: queryArg.querySomeName,\n        },\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type PatchApiV1ListByItemIdApiResponse =\n  /** status 200 A successful response. */ string;\nexport type PatchApiV1ListByItemIdApiArg = {\n  \"item.id\": string;\n};\nexport type PatchApiV2BySomeNameApiResponse =\n  /** status 200 A successful response. */ string;\nexport type PatchApiV2BySomeNameApiArg = {\n  pathSomeName: string;\n  querySomeName: string;\n};\n\"\n`;\n\nexports[`endpoint filtering > should only have endpoints loginUser, placeOrder, getOrderById, deleteOrder 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order\\`,\n        method: \"POST\",\n        body: queryArg.order,\n      }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order/\\${queryArg.orderId}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        params: {\n          username: queryArg.username,\n          password: queryArg.password,\n        },\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type PlaceOrderApiResponse =\n  /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse =\n  /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type LoginUserApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport type Order = {\n  id?: number | undefined;\n  petId?: number | undefined;\n  quantity?: number | undefined;\n  shipDate?: string | undefined;\n  /** Order Status */\n  status?: (\"placed\" | \"approved\" | \"delivered\") | undefined;\n  complete?: boolean | undefined;\n};\n\"\n`;\n\nexports[`endpoint overrides > overrides endpoint type > loginUser should be a mutation 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    loginUser: build.mutation<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        method: \"GET\",\n        params: {\n          username: queryArg.username,\n          password: queryArg.password,\n        },\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type LoginUserApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\n\"\n`;\n\nexports[`endpoint overrides > should apply first matching filter only > should remove all parameters except for findPetsByStatus 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getHealthcheck: build.query<\n      GetHealthcheckApiResponse,\n      GetHealthcheckApiArg\n    >({\n      query: () => ({ url: \\`/healthcheck\\` }),\n    }),\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: \"PUT\", body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    findPetsByStatus: build.query<\n      FindPetsByStatusApiResponse,\n      FindPetsByStatusApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/findByStatus\\`,\n        params: {\n          status: queryArg.status,\n        },\n      }),\n    }),\n    findPetsByTags: build.query<\n      FindPetsByTagsApiResponse,\n      FindPetsByTagsApiArg\n    >({\n      query: () => ({ url: \\`/pet/findByTags\\` }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n    updatePetWithForm: build.mutation<\n      UpdatePetWithFormApiResponse,\n      UpdatePetWithFormApiArg\n    >({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\`, method: \"POST\" }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n        method: \"POST\",\n        body: queryArg.body,\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: \\`/store/inventory\\` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order\\`,\n        method: \"POST\",\n        body: queryArg.order,\n      }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order/\\${queryArg.orderId}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user\\`,\n        method: \"POST\",\n        body: queryArg.user,\n      }),\n    }),\n    createUsersWithListInput: build.mutation<\n      CreateUsersWithListInputApiResponse,\n      CreateUsersWithListInputApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/user/createWithList\\`,\n        method: \"POST\",\n        body: queryArg.body,\n      }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: () => ({ url: \\`/user/login\\` }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: \\`/user/logout\\` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"PUT\",\n        body: queryArg.user,\n      }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetHealthcheckApiResponse = /** status 200 OK */ {\n  message: string;\n};\nexport type GetHealthcheckApiArg = void;\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: \"available\" | \"pending\" | \"sold\";\n};\nexport type FindPetsByTagsApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = void;\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse =\n  /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse =\n  /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse =\n  /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse =\n  /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserApiArg = void;\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse =\n  /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Tag = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Pet = {\n  id?: number | undefined;\n  name: string;\n  category?: Category | undefined;\n  photoUrls: string[];\n  tags?: Tag[] | undefined;\n  /** pet status in the store */\n  status?: (\"available\" | \"pending\" | \"sold\") | undefined;\n};\nexport type ApiResponse = {\n  code?: number | undefined;\n  type?: string | undefined;\n  message?: string | undefined;\n};\nexport type Order = {\n  id?: number | undefined;\n  petId?: number | undefined;\n  quantity?: number | undefined;\n  shipDate?: string | undefined;\n  /** Order Status */\n  status?: (\"placed\" | \"approved\" | \"delivered\") | undefined;\n  complete?: boolean | undefined;\n};\nexport type User = {\n  id?: number | undefined;\n  username?: string | undefined;\n  firstName?: string | undefined;\n  lastName?: string | undefined;\n  email?: string | undefined;\n  password?: string | undefined;\n  phone?: string | undefined;\n  website?: string | undefined;\n  /** User Status */\n  userStatus?: number | undefined;\n};\n\"\n`;\n\nexports[`endpoint overrides > should filter by array of parameter strings / regex > should only have the parameters with an \"e\" or \"f\" 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getHealthcheck: build.query<\n      GetHealthcheckApiResponse,\n      GetHealthcheckApiArg\n    >({\n      query: () => ({ url: \\`/healthcheck\\` }),\n    }),\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: \"PUT\", body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    findPetsByStatus: build.query<\n      FindPetsByStatusApiResponse,\n      FindPetsByStatusApiArg\n    >({\n      query: () => ({ url: \\`/pet/findByStatus\\` }),\n    }),\n    findPetsByTags: build.query<\n      FindPetsByTagsApiResponse,\n      FindPetsByTagsApiArg\n    >({\n      query: () => ({ url: \\`/pet/findByTags\\` }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n    updatePetWithForm: build.mutation<\n      UpdatePetWithFormApiResponse,\n      UpdatePetWithFormApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"POST\",\n        params: {\n          name: queryArg.name,\n        },\n      }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"DELETE\",\n        headers: {\n          api_key: queryArg.apiKey,\n        },\n      }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n        method: \"POST\",\n        body: queryArg.body,\n        params: {\n          additionalMetadata: queryArg.additionalMetadata,\n        },\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: \\`/store/inventory\\` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order\\`,\n        method: \"POST\",\n        body: queryArg.order,\n      }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order/\\${queryArg.orderId}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user\\`,\n        method: \"POST\",\n        body: queryArg.user,\n      }),\n    }),\n    createUsersWithListInput: build.mutation<\n      CreateUsersWithListInputApiResponse,\n      CreateUsersWithListInputApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/user/createWithList\\`,\n        method: \"POST\",\n        body: queryArg.body,\n      }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        params: {\n          username: queryArg.username,\n        },\n      }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: \\`/user/logout\\` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"PUT\",\n        body: queryArg.user,\n      }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetHealthcheckApiResponse = /** status 200 OK */ {\n  message: string;\n};\nexport type GetHealthcheckApiArg = void;\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = void;\nexport type FindPetsByTagsApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = void;\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  apiKey?: string;\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse =\n  /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse =\n  /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse =\n  /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse =\n  /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n};\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse =\n  /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Tag = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Pet = {\n  id?: number | undefined;\n  name: string;\n  category?: Category | undefined;\n  photoUrls: string[];\n  tags?: Tag[] | undefined;\n  /** pet status in the store */\n  status?: (\"available\" | \"pending\" | \"sold\") | undefined;\n};\nexport type ApiResponse = {\n  code?: number | undefined;\n  type?: string | undefined;\n  message?: string | undefined;\n};\nexport type Order = {\n  id?: number | undefined;\n  petId?: number | undefined;\n  quantity?: number | undefined;\n  shipDate?: string | undefined;\n  /** Order Status */\n  status?: (\"placed\" | \"approved\" | \"delivered\") | undefined;\n  complete?: boolean | undefined;\n};\nexport type User = {\n  id?: number | undefined;\n  username?: string | undefined;\n  firstName?: string | undefined;\n  lastName?: string | undefined;\n  email?: string | undefined;\n  password?: string | undefined;\n  phone?: string | undefined;\n  website?: string | undefined;\n  /** User Status */\n  userStatus?: number | undefined;\n};\n\"\n`;\n\nexports[`endpoint overrides > should filter by function > should remove any parameters from the header 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getHealthcheck: build.query<\n      GetHealthcheckApiResponse,\n      GetHealthcheckApiArg\n    >({\n      query: () => ({ url: \\`/healthcheck\\` }),\n    }),\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: \"PUT\", body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    findPetsByStatus: build.query<\n      FindPetsByStatusApiResponse,\n      FindPetsByStatusApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/findByStatus\\`,\n        params: {\n          status: queryArg.status,\n        },\n      }),\n    }),\n    findPetsByTags: build.query<\n      FindPetsByTagsApiResponse,\n      FindPetsByTagsApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/findByTags\\`,\n        params: {\n          tags: queryArg.tags,\n        },\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n    updatePetWithForm: build.mutation<\n      UpdatePetWithFormApiResponse,\n      UpdatePetWithFormApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"POST\",\n        params: {\n          name: queryArg.name,\n          status: queryArg.status,\n        },\n      }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n        method: \"POST\",\n        body: queryArg.body,\n        params: {\n          additionalMetadata: queryArg.additionalMetadata,\n        },\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: \\`/store/inventory\\` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order\\`,\n        method: \"POST\",\n        body: queryArg.order,\n      }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order/\\${queryArg.orderId}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user\\`,\n        method: \"POST\",\n        body: queryArg.user,\n      }),\n    }),\n    createUsersWithListInput: build.mutation<\n      CreateUsersWithListInputApiResponse,\n      CreateUsersWithListInputApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/user/createWithList\\`,\n        method: \"POST\",\n        body: queryArg.body,\n      }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        params: {\n          username: queryArg.username,\n          password: queryArg.password,\n        },\n      }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: \\`/user/logout\\` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"PUT\",\n        body: queryArg.user,\n      }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetHealthcheckApiResponse = /** status 200 OK */ {\n  message: string;\n};\nexport type GetHealthcheckApiArg = void;\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: \"available\" | \"pending\" | \"sold\";\n};\nexport type FindPetsByTagsApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = {\n  /** Tags to filter by */\n  tags?: string[];\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n  /** Status of pet that needs to be updated */\n  status?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse =\n  /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse =\n  /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse =\n  /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse =\n  /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse =\n  /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Tag = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Pet = {\n  id?: number | undefined;\n  name: string;\n  category?: Category | undefined;\n  photoUrls: string[];\n  tags?: Tag[] | undefined;\n  /** pet status in the store */\n  status?: (\"available\" | \"pending\" | \"sold\") | undefined;\n};\nexport type ApiResponse = {\n  code?: number | undefined;\n  type?: string | undefined;\n  message?: string | undefined;\n};\nexport type Order = {\n  id?: number | undefined;\n  petId?: number | undefined;\n  quantity?: number | undefined;\n  shipDate?: string | undefined;\n  /** Order Status */\n  status?: (\"placed\" | \"approved\" | \"delivered\") | undefined;\n  complete?: boolean | undefined;\n};\nexport type User = {\n  id?: number | undefined;\n  username?: string | undefined;\n  firstName?: string | undefined;\n  lastName?: string | undefined;\n  email?: string | undefined;\n  password?: string | undefined;\n  phone?: string | undefined;\n  website?: string | undefined;\n  /** User Status */\n  userStatus?: number | undefined;\n};\n\"\n`;\n\nexports[`endpoint overrides > should override parameters by regex > should only have the parameters with an \"e\" 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getHealthcheck: build.query<\n      GetHealthcheckApiResponse,\n      GetHealthcheckApiArg\n    >({\n      query: () => ({ url: \\`/healthcheck\\` }),\n    }),\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: \"PUT\", body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    findPetsByStatus: build.query<\n      FindPetsByStatusApiResponse,\n      FindPetsByStatusApiArg\n    >({\n      query: () => ({ url: \\`/pet/findByStatus\\` }),\n    }),\n    findPetsByTags: build.query<\n      FindPetsByTagsApiResponse,\n      FindPetsByTagsApiArg\n    >({\n      query: () => ({ url: \\`/pet/findByTags\\` }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n    updatePetWithForm: build.mutation<\n      UpdatePetWithFormApiResponse,\n      UpdatePetWithFormApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"POST\",\n        params: {\n          name: queryArg.name,\n        },\n      }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"DELETE\",\n        headers: {\n          api_key: queryArg.apiKey,\n        },\n      }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n        method: \"POST\",\n        body: queryArg.body,\n        params: {\n          additionalMetadata: queryArg.additionalMetadata,\n        },\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: \\`/store/inventory\\` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order\\`,\n        method: \"POST\",\n        body: queryArg.order,\n      }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order/\\${queryArg.orderId}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user\\`,\n        method: \"POST\",\n        body: queryArg.user,\n      }),\n    }),\n    createUsersWithListInput: build.mutation<\n      CreateUsersWithListInputApiResponse,\n      CreateUsersWithListInputApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/user/createWithList\\`,\n        method: \"POST\",\n        body: queryArg.body,\n      }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        params: {\n          username: queryArg.username,\n        },\n      }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: \\`/user/logout\\` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"PUT\",\n        body: queryArg.user,\n      }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetHealthcheckApiResponse = /** status 200 OK */ {\n  message: string;\n};\nexport type GetHealthcheckApiArg = void;\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = void;\nexport type FindPetsByTagsApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = void;\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  apiKey?: string;\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse =\n  /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse =\n  /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse =\n  /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse =\n  /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n};\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse =\n  /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Tag = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Pet = {\n  id?: number | undefined;\n  name: string;\n  category?: Category | undefined;\n  photoUrls: string[];\n  tags?: Tag[] | undefined;\n  /** pet status in the store */\n  status?: (\"available\" | \"pending\" | \"sold\") | undefined;\n};\nexport type ApiResponse = {\n  code?: number | undefined;\n  type?: string | undefined;\n  message?: string | undefined;\n};\nexport type Order = {\n  id?: number | undefined;\n  petId?: number | undefined;\n  quantity?: number | undefined;\n  shipDate?: string | undefined;\n  /** Order Status */\n  status?: (\"placed\" | \"approved\" | \"delivered\") | undefined;\n  complete?: boolean | undefined;\n};\nexport type User = {\n  id?: number | undefined;\n  username?: string | undefined;\n  firstName?: string | undefined;\n  lastName?: string | undefined;\n  email?: string | undefined;\n  password?: string | undefined;\n  phone?: string | undefined;\n  website?: string | undefined;\n  /** User Status */\n  userStatus?: number | undefined;\n};\n\"\n`;\n\nexports[`endpoint overrides > should override parameters by string > should only have the \"status\" parameter from the endpoints 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getHealthcheck: build.query<\n      GetHealthcheckApiResponse,\n      GetHealthcheckApiArg\n    >({\n      query: () => ({ url: \\`/healthcheck\\` }),\n    }),\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: \"PUT\", body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    findPetsByStatus: build.query<\n      FindPetsByStatusApiResponse,\n      FindPetsByStatusApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/findByStatus\\`,\n        params: {\n          status: queryArg.status,\n        },\n      }),\n    }),\n    findPetsByTags: build.query<\n      FindPetsByTagsApiResponse,\n      FindPetsByTagsApiArg\n    >({\n      query: () => ({ url: \\`/pet/findByTags\\` }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n    updatePetWithForm: build.mutation<\n      UpdatePetWithFormApiResponse,\n      UpdatePetWithFormApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"POST\",\n        params: {\n          status: queryArg.status,\n        },\n      }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n        method: \"POST\",\n        body: queryArg.body,\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: \\`/store/inventory\\` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order\\`,\n        method: \"POST\",\n        body: queryArg.order,\n      }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order/\\${queryArg.orderId}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user\\`,\n        method: \"POST\",\n        body: queryArg.user,\n      }),\n    }),\n    createUsersWithListInput: build.mutation<\n      CreateUsersWithListInputApiResponse,\n      CreateUsersWithListInputApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/user/createWithList\\`,\n        method: \"POST\",\n        body: queryArg.body,\n      }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: () => ({ url: \\`/user/login\\` }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: \\`/user/logout\\` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"PUT\",\n        body: queryArg.user,\n      }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetHealthcheckApiResponse = /** status 200 OK */ {\n  message: string;\n};\nexport type GetHealthcheckApiArg = void;\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: \"available\" | \"pending\" | \"sold\";\n};\nexport type FindPetsByTagsApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = void;\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Status of pet that needs to be updated */\n  status?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse =\n  /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse =\n  /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse =\n  /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse =\n  /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserApiArg = void;\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse =\n  /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Tag = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Pet = {\n  id?: number | undefined;\n  name: string;\n  category?: Category | undefined;\n  photoUrls: string[];\n  tags?: Tag[] | undefined;\n  /** pet status in the store */\n  status?: (\"available\" | \"pending\" | \"sold\") | undefined;\n};\nexport type ApiResponse = {\n  code?: number | undefined;\n  type?: string | undefined;\n  message?: string | undefined;\n};\nexport type Order = {\n  id?: number | undefined;\n  petId?: number | undefined;\n  quantity?: number | undefined;\n  shipDate?: string | undefined;\n  /** Order Status */\n  status?: (\"placed\" | \"approved\" | \"delivered\") | undefined;\n  complete?: boolean | undefined;\n};\nexport type User = {\n  id?: number | undefined;\n  username?: string | undefined;\n  firstName?: string | undefined;\n  lastName?: string | undefined;\n  email?: string | undefined;\n  password?: string | undefined;\n  phone?: string | undefined;\n  website?: string | undefined;\n  /** User Status */\n  userStatus?: number | undefined;\n};\n\"\n`;\n\nexports[`falls back to the \\`title\\` parameter for the body parameter name when no other name is available 1`] = `\n\"import { api } from \"fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    postV1Export: build.mutation<PostV1ExportApiResponse, PostV1ExportApiArg>({\n      query: (queryArg) => ({\n        url: \\`/v1/export\\`,\n        method: \"POST\",\n        body: queryArg.exportedEntityIds,\n      }),\n    }),\n    postV1Import: build.mutation<PostV1ImportApiResponse, PostV1ImportApiArg>({\n      query: (queryArg) => ({\n        url: \\`/v1/import\\`,\n        method: \"POST\",\n        body: queryArg.rawData,\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type PostV1ExportApiResponse = unknown;\nexport type PostV1ExportApiArg = {\n  exportedEntityIds: IdList;\n};\nexport type PostV1ImportApiResponse = unknown;\nexport type PostV1ImportApiArg = {\n  rawData: string;\n};\nexport type IdList = number[];\n\"\n`;\n\nexports[`hooks generation > should generate an \\`useGetPetByIdQuery\\` query hook and an \\`useAddPetMutation\\` mutation hook 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type Category = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Tag = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Pet = {\n  id?: number | undefined;\n  name: string;\n  category?: Category | undefined;\n  photoUrls: string[];\n  tags?: Tag[] | undefined;\n  /** pet status in the store */\n  status?: (\"available\" | \"pending\" | \"sold\") | undefined;\n};\nexport const { useAddPetMutation, useGetPetByIdQuery } = injectedRtkApi;\n\"\n`;\n\nexports[`hooks generation uses overrides > should generate an \\`useLoginMutation\\` mutation hook 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    loginUser: build.mutation<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        method: \"GET\",\n        params: {\n          username: queryArg.username,\n          password: queryArg.password,\n        },\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type LoginUserApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport const { useLoginUserMutation } = injectedRtkApi;\n\"\n`;\n\nexports[`hooks generation with operationNameSuffix > should generate an \\`useGetPetByIdMySuffixQuery\\` query hook and an \\`useAddPetMySuffixMutation\\` mutation hook 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    AddPetMySuffix: build.mutation<\n      AddPetMySuffixApiResponse,\n      AddPetMySuffixApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    GetPetByIdMySuffix: build.query<\n      GetPetByIdMySuffixApiResponse,\n      GetPetByIdMySuffixApiArg\n    >({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type AddPetMySuffixApiResponse =\n  /** status 200 Successful operation */ Pet;\nexport type AddPetMySuffixApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type GetPetByIdMySuffixApiResponse =\n  /** status 200 successful operation */ Pet;\nexport type GetPetByIdMySuffixApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type Category = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Tag = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Pet = {\n  id?: number | undefined;\n  name: string;\n  category?: Category | undefined;\n  photoUrls: string[];\n  tags?: Tag[] | undefined;\n  /** pet status in the store */\n  status?: (\"available\" | \"pending\" | \"sold\") | undefined;\n};\nexport const { useAddPetMySuffixMutation, useGetPetByIdMySuffixQuery } =\n  injectedRtkApi;\n\"\n`;\n\nexports[`openapi spec > readOnly / writeOnly are merged 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getExample: build.query<GetExampleApiResponse, GetExampleApiArg>({\n      query: () => ({ url: \\`/example\\` }),\n    }),\n    setExample: build.mutation<SetExampleApiResponse, SetExampleApiArg>({\n      query: (queryArg) => ({\n        url: \\`/example\\`,\n        method: \"POST\",\n        body: queryArg.exampleSchema,\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetExampleApiResponse = /** status 200 OK */ ExampleSchema;\nexport type GetExampleApiArg = void;\nexport type SetExampleApiResponse = /** status 200 OK */ ExampleSchema;\nexport type SetExampleApiArg = {\n  exampleSchema: ExampleSchema;\n};\nexport type ExampleSchema = {\n  always_present: string;\n  read_only_prop: string;\n  write_only_prop: string;\n};\n\"\n`;\n\nexports[`openapi spec > readOnly / writeOnly are respected 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getExample: build.query<GetExampleApiResponse, GetExampleApiArg>({\n      query: () => ({ url: \\`/example\\` }),\n    }),\n    setExample: build.mutation<SetExampleApiResponse, SetExampleApiArg>({\n      query: (queryArg) => ({\n        url: \\`/example\\`,\n        method: \"POST\",\n        body: queryArg.exampleSchema,\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetExampleApiResponse = /** status 200 OK */ ExampleSchemaRead;\nexport type GetExampleApiArg = void;\nexport type SetExampleApiResponse = /** status 200 OK */ ExampleSchemaRead;\nexport type SetExampleApiArg = {\n  exampleSchema: ExampleSchemaWrite;\n};\nexport type ExampleSchema = {\n  always_present: string;\n};\nexport type ExampleSchemaRead = {\n  always_present: string;\n  read_only_prop: string;\n};\nexport type ExampleSchemaWrite = {\n  always_present: string;\n  write_only_prop: string;\n};\n\"\n`;\n\nexports[`operation suffixes are applied 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    GetHealthcheckV2: build.query<\n      GetHealthcheckV2ApiResponse,\n      GetHealthcheckV2ApiArg\n    >({\n      query: () => ({ url: \\`/healthcheck\\` }),\n    }),\n    UpdatePetV2: build.mutation<UpdatePetV2ApiResponse, UpdatePetV2ApiArg>({\n      query: (queryArg) => ({ url: \\`/pet\\`, method: \"PUT\", body: queryArg.pet }),\n    }),\n    AddPetV2: build.mutation<AddPetV2ApiResponse, AddPetV2ApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    FindPetsByStatusV2: build.query<\n      FindPetsByStatusV2ApiResponse,\n      FindPetsByStatusV2ApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/findByStatus\\`,\n        params: {\n          status: queryArg.status,\n        },\n      }),\n    }),\n    FindPetsByTagsV2: build.query<\n      FindPetsByTagsV2ApiResponse,\n      FindPetsByTagsV2ApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/findByTags\\`,\n        params: {\n          tags: queryArg.tags,\n        },\n      }),\n    }),\n    GetPetByIdV2: build.query<GetPetByIdV2ApiResponse, GetPetByIdV2ApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n    UpdatePetWithFormV2: build.mutation<\n      UpdatePetWithFormV2ApiResponse,\n      UpdatePetWithFormV2ApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"POST\",\n        params: {\n          name: queryArg.name,\n          status: queryArg.status,\n        },\n      }),\n    }),\n    DeletePetV2: build.mutation<DeletePetV2ApiResponse, DeletePetV2ApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}\\`,\n        method: \"DELETE\",\n        headers: {\n          api_key: queryArg.apiKey,\n        },\n      }),\n    }),\n    UploadFileV2: build.mutation<UploadFileV2ApiResponse, UploadFileV2ApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n        method: \"POST\",\n        body: queryArg.body,\n        params: {\n          additionalMetadata: queryArg.additionalMetadata,\n        },\n      }),\n    }),\n    GetInventoryV2: build.query<\n      GetInventoryV2ApiResponse,\n      GetInventoryV2ApiArg\n    >({\n      query: () => ({ url: \\`/store/inventory\\` }),\n    }),\n    PlaceOrderV2: build.mutation<PlaceOrderV2ApiResponse, PlaceOrderV2ApiArg>({\n      query: (queryArg) => ({\n        url: \\`/store/order\\`,\n        method: \"POST\",\n        body: queryArg.order,\n      }),\n    }),\n    GetOrderByIdV2: build.query<\n      GetOrderByIdV2ApiResponse,\n      GetOrderByIdV2ApiArg\n    >({\n      query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n    }),\n    DeleteOrderV2: build.mutation<\n      DeleteOrderV2ApiResponse,\n      DeleteOrderV2ApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/store/order/\\${queryArg.orderId}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n    CreateUserV2: build.mutation<CreateUserV2ApiResponse, CreateUserV2ApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user\\`,\n        method: \"POST\",\n        body: queryArg.user,\n      }),\n    }),\n    CreateUsersWithListInputV2: build.mutation<\n      CreateUsersWithListInputV2ApiResponse,\n      CreateUsersWithListInputV2ApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/user/createWithList\\`,\n        method: \"POST\",\n        body: queryArg.body,\n      }),\n    }),\n    LoginUserV2: build.query<LoginUserV2ApiResponse, LoginUserV2ApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/login\\`,\n        params: {\n          username: queryArg.username,\n          password: queryArg.password,\n        },\n      }),\n    }),\n    LogoutUserV2: build.query<LogoutUserV2ApiResponse, LogoutUserV2ApiArg>({\n      query: () => ({ url: \\`/user/logout\\` }),\n    }),\n    GetUserByNameV2: build.query<\n      GetUserByNameV2ApiResponse,\n      GetUserByNameV2ApiArg\n    >({\n      query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n    }),\n    UpdateUserV2: build.mutation<UpdateUserV2ApiResponse, UpdateUserV2ApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"PUT\",\n        body: queryArg.user,\n      }),\n    }),\n    DeleteUserV2: build.mutation<DeleteUserV2ApiResponse, DeleteUserV2ApiArg>({\n      query: (queryArg) => ({\n        url: \\`/user/\\${queryArg.username}\\`,\n        method: \"DELETE\",\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetHealthcheckV2ApiResponse = /** status 200 OK */ {\n  message: string;\n};\nexport type GetHealthcheckV2ApiArg = void;\nexport type UpdatePetV2ApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetV2ApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetV2ApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetV2ApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusV2ApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusV2ApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: \"available\" | \"pending\" | \"sold\";\n};\nexport type FindPetsByTagsV2ApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsV2ApiArg = {\n  /** Tags to filter by */\n  tags?: string[];\n};\nexport type GetPetByIdV2ApiResponse =\n  /** status 200 successful operation */ Pet;\nexport type GetPetByIdV2ApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormV2ApiResponse = unknown;\nexport type UpdatePetWithFormV2ApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n  /** Status of pet that needs to be updated */\n  status?: string;\n};\nexport type DeletePetV2ApiResponse = unknown;\nexport type DeletePetV2ApiArg = {\n  apiKey?: string;\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileV2ApiResponse =\n  /** status 200 successful operation */ ApiResponse;\nexport type UploadFileV2ApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: Blob;\n};\nexport type GetInventoryV2ApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryV2ApiArg = void;\nexport type PlaceOrderV2ApiResponse =\n  /** status 200 successful operation */ Order;\nexport type PlaceOrderV2ApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdV2ApiResponse =\n  /** status 200 successful operation */ Order;\nexport type GetOrderByIdV2ApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderV2ApiResponse = unknown;\nexport type DeleteOrderV2ApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserV2ApiResponse = unknown;\nexport type CreateUserV2ApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputV2ApiResponse =\n  /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputV2ApiArg = {\n  body: User[];\n};\nexport type LoginUserV2ApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserV2ApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport type LogoutUserV2ApiResponse = unknown;\nexport type LogoutUserV2ApiArg = void;\nexport type GetUserByNameV2ApiResponse =\n  /** status 200 successful operation */ User;\nexport type GetUserByNameV2ApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserV2ApiResponse = unknown;\nexport type UpdateUserV2ApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserV2ApiResponse = unknown;\nexport type DeleteUserV2ApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Tag = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Pet = {\n  id?: number | undefined;\n  name: string;\n  category?: Category | undefined;\n  photoUrls: string[];\n  tags?: Tag[] | undefined;\n  /** pet status in the store */\n  status?: (\"available\" | \"pending\" | \"sold\") | undefined;\n};\nexport type ApiResponse = {\n  code?: number | undefined;\n  type?: string | undefined;\n  message?: string | undefined;\n};\nexport type Order = {\n  id?: number | undefined;\n  petId?: number | undefined;\n  quantity?: number | undefined;\n  shipDate?: string | undefined;\n  /** Order Status */\n  status?: (\"placed\" | \"approved\" | \"delivered\") | undefined;\n  complete?: boolean | undefined;\n};\nexport type User = {\n  id?: number | undefined;\n  username?: string | undefined;\n  firstName?: string | undefined;\n  lastName?: string | undefined;\n  email?: string | undefined;\n  password?: string | undefined;\n  phone?: string | undefined;\n  website?: string | undefined;\n  /** User Status */\n  userStatus?: number | undefined;\n};\n\"\n`;\n\nexports[`query parameters > parameters overridden in swagger should also be overridden in the code 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getUsersById: build.query<GetUsersByIdApiResponse, GetUsersByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/users/\\${queryArg.id}\\` }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetUsersByIdApiResponse = unknown;\nexport type GetUsersByIdApiArg = {\n  id: number;\n};\n\"\n`;\n\nexports[`should use brackets in a querystring urls arg, when the arg contains full stops 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    patchApiV1ListByItemId: build.mutation<\n      PatchApiV1ListByItemIdApiResponse,\n      PatchApiV1ListByItemIdApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/api/v1/list/\\${queryArg[\"item.id\"]}\\`,\n        method: \"PATCH\",\n      }),\n    }),\n    patchApiV2BySomeName: build.mutation<\n      PatchApiV2BySomeNameApiResponse,\n      PatchApiV2BySomeNameApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/api/v2/\\${queryArg.pathSomeName}\\`,\n        method: \"PATCH\",\n        params: {\n          some_name: queryArg.querySomeName,\n        },\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type PatchApiV1ListByItemIdApiResponse =\n  /** status 200 A successful response. */ string;\nexport type PatchApiV1ListByItemIdApiArg = {\n  \"item.id\": string;\n};\nexport type PatchApiV2BySomeNameApiResponse =\n  /** status 200 A successful response. */ string;\nexport type PatchApiV2BySomeNameApiArg = {\n  pathSomeName: string;\n  querySomeName: string;\n};\n\"\n`;\n\nexports[`supports granular hooks generation that includes all query types 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type Category = {\n  id?: number;\n  name?: string;\n};\nexport type Tag = {\n  id?: number;\n  name?: string;\n};\nexport type Pet = {\n  id?: number;\n  name: string;\n  category?: Category;\n  photoUrls: string[];\n  tags?: Tag[];\n  /** pet status in the store */\n  status?: \"available\" | \"pending\" | \"sold\";\n};\nexport const { useAddPetMutation, useGetPetByIdQuery, useLazyGetPetByIdQuery } =\n  injectedRtkApi;\n\"\n`;\n\nexports[`supports granular hooks generation with only lazy queries 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type Category = {\n  id?: number;\n  name?: string;\n};\nexport type Tag = {\n  id?: number;\n  name?: string;\n};\nexport type Pet = {\n  id?: number;\n  name: string;\n  category?: Category;\n  photoUrls: string[];\n  tags?: Tag[];\n  /** pet status in the store */\n  status?: \"available\" | \"pending\" | \"sold\";\n};\nexport const { useLazyGetPetByIdQuery } = injectedRtkApi;\n\"\n`;\n\nexports[`supports granular hooks generation with only mutations 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type Category = {\n  id?: number;\n  name?: string;\n};\nexport type Tag = {\n  id?: number;\n  name?: string;\n};\nexport type Pet = {\n  id?: number;\n  name: string;\n  category?: Category;\n  photoUrls: string[];\n  tags?: Tag[];\n  /** pet status in the store */\n  status?: \"available\" | \"pending\" | \"sold\";\n};\nexport const { useAddPetMutation } = injectedRtkApi;\n\"\n`;\n\nexports[`supports granular hooks generation with only queries 1`] = `\n\"import { api } from \"./fixtures/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({\n        url: \\`/pet\\`,\n        method: \"POST\",\n        body: queryArg.pet,\n      }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type Category = {\n  id?: number;\n  name?: string;\n};\nexport type Tag = {\n  id?: number;\n  name?: string;\n};\nexport type Pet = {\n  id?: number;\n  name: string;\n  category?: Category;\n  photoUrls: string[];\n  tags?: Tag[];\n  /** pet status in the store */\n  status?: \"available\" | \"pending\" | \"sold\";\n};\nexport const { useGetPetByIdQuery } = injectedRtkApi;\n\"\n`;\n\nexports[`tests from issues > issue #2002: should be able to generate proper intersection types 1`] = `\n\"import { api } from \"./tmp/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getApiV1Animals: build.query<\n      GetApiV1AnimalsApiResponse,\n      GetApiV1AnimalsApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/api/v1/animals\\`,\n        params: {\n          type: queryArg[\"type\"],\n        },\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetApiV1AnimalsApiResponse = /** status 200 Success */ (\n  | Dog\n  | Cat\n)[];\nexport type GetApiV1AnimalsApiArg = {\n  type?: AnimalType;\n};\nexport type AnimalType = \"All\" | \"Cats\" | \"Dogs\";\nexport type AnimalBase = {\n  type: AnimalType;\n  id?: number;\n  name?: string | null;\n};\nexport type Dog = {\n  type: \"Dog\";\n} & AnimalBase & {\n    dogUniqueProp?: string | null;\n  };\nexport type Cat = {\n  type: \"Cat\";\n} & AnimalBase & {\n    catUniqueProp?: string | null;\n  };\nexport const { useGetApiV1AnimalsQuery } = injectedRtkApi;\n\"\n`;\n\nexports[`tests from issues > issue #3369: discriminated unions should use enum values, not schema names 1`] = `\n\"import { api } from \"./tmp/emptyApi\";\nconst injectedRtkApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getAllowances: build.query<GetAllowancesApiResponse, GetAllowancesApiArg>({\n      query: () => ({ url: \\`/api/allowances\\` }),\n    }),\n    createAllowance: build.mutation<\n      CreateAllowanceApiResponse,\n      CreateAllowanceApiArg\n    >({\n      query: (queryArg) => ({\n        url: \\`/api/allowances/\\${queryArg.id}\\`,\n        method: \"POST\",\n        body: queryArg.allowance,\n      }),\n    }),\n  }),\n  overrideExisting: false,\n});\nexport { injectedRtkApi as enhancedApi };\nexport type GetAllowancesApiResponse = /** status 200 Success */ Allowance[];\nexport type GetAllowancesApiArg = void;\nexport type CreateAllowanceApiResponse = /** status 201 Created */ Allowance;\nexport type CreateAllowanceApiArg = {\n  id: string;\n  allowance: Allowance;\n};\nexport type EngineeringAllowance = {\n  allowance_type?: \"engineering\";\n  distribution?: \"MARECO\" | \"LINEAR\";\n  capacity_speed_limit?: number;\n};\nexport type StandardAllowance = {\n  allowance_type?: \"standard\";\n  default_value?: number;\n  ranges?: {\n    min?: number;\n    max?: number;\n  }[];\n};\nexport type Allowance =\n  | ({\n      allowance_type: \"engineering\";\n    } & EngineeringAllowance)\n  | ({\n      allowance_type: \"standard\";\n    } & StandardAllowance);\n\"\n`;\n\nexports[`yaml parsing > should be able to use read a yaml file 1`] = `\n\"import { api } from \"./tmp/emptyApi\";\nexport const addTagTypes = [\"pet\", \"store\", \"user\"] as const;\nconst injectedRtkApi = api\n  .enhanceEndpoints({\n    addTagTypes,\n  })\n  .injectEndpoints({\n    endpoints: (build) => ({\n      updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n        query: (queryArg) => ({\n          url: \\`/pet\\`,\n          method: \"PUT\",\n          body: queryArg.pet,\n        }),\n        invalidatesTags: [\"pet\"],\n      }),\n      addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n        query: (queryArg) => ({\n          url: \\`/pet\\`,\n          method: \"POST\",\n          body: queryArg.pet,\n        }),\n        invalidatesTags: [\"pet\"],\n      }),\n      findPetsByStatus: build.query<\n        FindPetsByStatusApiResponse,\n        FindPetsByStatusApiArg\n      >({\n        query: (queryArg) => ({\n          url: \\`/pet/findByStatus\\`,\n          params: {\n            status: queryArg.status,\n          },\n        }),\n        providesTags: [\"pet\"],\n      }),\n      findPetsByTags: build.query<\n        FindPetsByTagsApiResponse,\n        FindPetsByTagsApiArg\n      >({\n        query: (queryArg) => ({\n          url: \\`/pet/findByTags\\`,\n          params: {\n            tags: queryArg.tags,\n          },\n        }),\n        providesTags: [\"pet\"],\n      }),\n      getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n        query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n        providesTags: [\"pet\"],\n      }),\n      updatePetWithForm: build.mutation<\n        UpdatePetWithFormApiResponse,\n        UpdatePetWithFormApiArg\n      >({\n        query: (queryArg) => ({\n          url: \\`/pet/\\${queryArg.petId}\\`,\n          method: \"POST\",\n          params: {\n            name: queryArg.name,\n            status: queryArg.status,\n          },\n        }),\n        invalidatesTags: [\"pet\"],\n      }),\n      deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n        query: (queryArg) => ({\n          url: \\`/pet/\\${queryArg.petId}\\`,\n          method: \"DELETE\",\n          headers: {\n            api_key: queryArg.apiKey,\n          },\n        }),\n        invalidatesTags: [\"pet\"],\n      }),\n      uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n        query: (queryArg) => ({\n          url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n          method: \"POST\",\n          body: queryArg.body,\n          params: {\n            additionalMetadata: queryArg.additionalMetadata,\n          },\n        }),\n        invalidatesTags: [\"pet\"],\n      }),\n      getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n        query: () => ({ url: \\`/store/inventory\\` }),\n        providesTags: [\"store\"],\n      }),\n      placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n        query: (queryArg) => ({\n          url: \\`/store/order\\`,\n          method: \"POST\",\n          body: queryArg.order,\n        }),\n        invalidatesTags: [\"store\"],\n      }),\n      getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n        query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n        providesTags: [\"store\"],\n      }),\n      deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n        query: (queryArg) => ({\n          url: \\`/store/order/\\${queryArg.orderId}\\`,\n          method: \"DELETE\",\n        }),\n        invalidatesTags: [\"store\"],\n      }),\n      createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n        query: (queryArg) => ({\n          url: \\`/user\\`,\n          method: \"POST\",\n          body: queryArg.user,\n        }),\n        invalidatesTags: [\"user\"],\n      }),\n      createUsersWithListInput: build.mutation<\n        CreateUsersWithListInputApiResponse,\n        CreateUsersWithListInputApiArg\n      >({\n        query: (queryArg) => ({\n          url: \\`/user/createWithList\\`,\n          method: \"POST\",\n          body: queryArg.body,\n        }),\n        invalidatesTags: [\"user\"],\n      }),\n      loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n        query: (queryArg) => ({\n          url: \\`/user/login\\`,\n          params: {\n            username: queryArg.username,\n            password: queryArg.password,\n          },\n        }),\n        providesTags: [\"user\"],\n      }),\n      logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n        query: () => ({ url: \\`/user/logout\\` }),\n        providesTags: [\"user\"],\n      }),\n      getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>(\n        {\n          query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n          providesTags: [\"user\"],\n        },\n      ),\n      updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n        query: (queryArg) => ({\n          url: \\`/user/\\${queryArg.username}\\`,\n          method: \"PUT\",\n          body: queryArg.user,\n        }),\n        invalidatesTags: [\"user\"],\n      }),\n      deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n        query: (queryArg) => ({\n          url: \\`/user/\\${queryArg.username}\\`,\n          method: \"DELETE\",\n        }),\n        invalidatesTags: [\"user\"],\n      }),\n    }),\n    overrideExisting: false,\n  });\nexport { injectedRtkApi as enhancedApi };\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: \"available\" | \"pending\" | \"sold\";\n};\nexport type FindPetsByTagsApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = {\n  /** Tags to filter by */\n  tags?: string[];\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n  /** Status of pet that needs to be updated */\n  status?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  apiKey?: string;\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse =\n  /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse =\n  /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse =\n  /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse =\n  /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse =\n  /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Tag = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Pet = {\n  id?: number | undefined;\n  name: string;\n  category?: Category | undefined;\n  photoUrls: string[];\n  tags?: Tag[] | undefined;\n  /** pet status in the store */\n  status?: (\"available\" | \"pending\" | \"sold\") | undefined;\n};\nexport type ApiResponse = {\n  code?: number | undefined;\n  type?: string | undefined;\n  message?: string | undefined;\n};\nexport type Order = {\n  id?: number | undefined;\n  petId?: number | undefined;\n  quantity?: number | undefined;\n  shipDate?: string | undefined;\n  /** Order Status */\n  status?: (\"placed\" | \"approved\" | \"delivered\") | undefined;\n  complete?: boolean | undefined;\n};\nexport type User = {\n  id?: number | undefined;\n  username?: string | undefined;\n  firstName?: string | undefined;\n  lastName?: string | undefined;\n  email?: string | undefined;\n  password?: string | undefined;\n  phone?: string | undefined;\n  website?: string | undefined;\n  /** User Status */\n  userStatus?: number | undefined;\n};\nexport const {\n  useUpdatePetMutation,\n  useAddPetMutation,\n  useFindPetsByStatusQuery,\n  useFindPetsByTagsQuery,\n  useGetPetByIdQuery,\n  useUpdatePetWithFormMutation,\n  useDeletePetMutation,\n  useUploadFileMutation,\n  useGetInventoryQuery,\n  usePlaceOrderMutation,\n  useGetOrderByIdQuery,\n  useDeleteOrderMutation,\n  useCreateUserMutation,\n  useCreateUsersWithListInputMutation,\n  useLoginUserQuery,\n  useLogoutUserQuery,\n  useGetUserByNameQuery,\n  useUpdateUserMutation,\n  useDeleteUserMutation,\n} = injectedRtkApi;\n\"\n`;\n\nexports[`yaml parsing > should generate params with non quoted keys if they don't contain special characters 1`] = `\n\"import { api } from \"./tmp/emptyApi\";\nexport const addTagTypes = [\"StructureDefinition\"] as const;\nconst injectedRtkApi = api\n  .enhanceEndpoints({\n    addTagTypes,\n  })\n  .injectEndpoints({\n    endpoints: (build) => ({\n      getStructureDefinition: build.query<\n        GetStructureDefinitionApiResponse,\n        GetStructureDefinitionApiArg\n      >({\n        query: (queryArg) => ({\n          url: \\`/StructureDefinition\\`,\n          params: {\n            foo: queryArg.foo,\n            _foo: queryArg._foo,\n            \"-bar-bar\": queryArg[\"-bar-bar\"],\n            _bar_bar: queryArg._bar_bar,\n            \"foo:bar-foo.bar/foo\": queryArg[\"foo:bar-foo.bar/foo\"],\n            foo_bar: queryArg.fooBar,\n            namingConflict: queryArg.namingConflict,\n            naming_conflict: queryArg.naming_conflict,\n          },\n        }),\n        providesTags: [\"StructureDefinition\"],\n      }),\n    }),\n    overrideExisting: false,\n  });\nexport { injectedRtkApi as enhancedApi };\nexport type GetStructureDefinitionApiResponse =\n  /** status 200 Success */ FhirJsonResource;\nexport type GetStructureDefinitionApiArg = {\n  /** Some description */\n  foo?: any;\n  /** Some description */\n  _foo?: any;\n  /** Some description */\n  \"-bar-bar\"?: any;\n  /** Some description */\n  _bar_bar?: any;\n  /** Some description */\n  \"foo:bar-foo.bar/foo\"?: any;\n  /** Some description */\n  fooBar?: any;\n  /** Some description */\n  namingConflict?: any;\n  /** Some description */\n  naming_conflict?: any;\n};\nexport type FhirJsonResource = object;\nexport const { useGetStructureDefinitionQuery } = injectedRtkApi;\n\"\n`;\n\nexports[`yaml parsing > should parse a yaml schema from a URL 1`] = `\n\"import { api } from \"./tmp/emptyApi\";\nexport const addTagTypes = [\"pet\", \"store\", \"user\"] as const;\nconst injectedRtkApi = api\n  .enhanceEndpoints({\n    addTagTypes,\n  })\n  .injectEndpoints({\n    endpoints: (build) => ({\n      updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n        query: (queryArg) => ({\n          url: \\`/pet\\`,\n          method: \"PUT\",\n          body: queryArg.pet,\n        }),\n        invalidatesTags: [\"pet\"],\n      }),\n      addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n        query: (queryArg) => ({\n          url: \\`/pet\\`,\n          method: \"POST\",\n          body: queryArg.pet,\n        }),\n        invalidatesTags: [\"pet\"],\n      }),\n      findPetsByStatus: build.query<\n        FindPetsByStatusApiResponse,\n        FindPetsByStatusApiArg\n      >({\n        query: (queryArg) => ({\n          url: \\`/pet/findByStatus\\`,\n          params: {\n            status: queryArg.status,\n          },\n        }),\n        providesTags: [\"pet\"],\n      }),\n      findPetsByTags: build.query<\n        FindPetsByTagsApiResponse,\n        FindPetsByTagsApiArg\n      >({\n        query: (queryArg) => ({\n          url: \\`/pet/findByTags\\`,\n          params: {\n            tags: queryArg.tags,\n          },\n        }),\n        providesTags: [\"pet\"],\n      }),\n      getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n        query: (queryArg) => ({ url: \\`/pet/\\${queryArg.petId}\\` }),\n        providesTags: [\"pet\"],\n      }),\n      updatePetWithForm: build.mutation<\n        UpdatePetWithFormApiResponse,\n        UpdatePetWithFormApiArg\n      >({\n        query: (queryArg) => ({\n          url: \\`/pet/\\${queryArg.petId}\\`,\n          method: \"POST\",\n          params: {\n            name: queryArg.name,\n            status: queryArg.status,\n          },\n        }),\n        invalidatesTags: [\"pet\"],\n      }),\n      deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n        query: (queryArg) => ({\n          url: \\`/pet/\\${queryArg.petId}\\`,\n          method: \"DELETE\",\n          headers: {\n            api_key: queryArg.apiKey,\n          },\n        }),\n        invalidatesTags: [\"pet\"],\n      }),\n      uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n        query: (queryArg) => ({\n          url: \\`/pet/\\${queryArg.petId}/uploadImage\\`,\n          method: \"POST\",\n          body: queryArg.body,\n          params: {\n            additionalMetadata: queryArg.additionalMetadata,\n          },\n        }),\n        invalidatesTags: [\"pet\"],\n      }),\n      getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n        query: () => ({ url: \\`/store/inventory\\` }),\n        providesTags: [\"store\"],\n      }),\n      placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n        query: (queryArg) => ({\n          url: \\`/store/order\\`,\n          method: \"POST\",\n          body: queryArg.order,\n        }),\n        invalidatesTags: [\"store\"],\n      }),\n      getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n        query: (queryArg) => ({ url: \\`/store/order/\\${queryArg.orderId}\\` }),\n        providesTags: [\"store\"],\n      }),\n      deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n        query: (queryArg) => ({\n          url: \\`/store/order/\\${queryArg.orderId}\\`,\n          method: \"DELETE\",\n        }),\n        invalidatesTags: [\"store\"],\n      }),\n      createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n        query: (queryArg) => ({\n          url: \\`/user\\`,\n          method: \"POST\",\n          body: queryArg.user,\n        }),\n        invalidatesTags: [\"user\"],\n      }),\n      createUsersWithListInput: build.mutation<\n        CreateUsersWithListInputApiResponse,\n        CreateUsersWithListInputApiArg\n      >({\n        query: (queryArg) => ({\n          url: \\`/user/createWithList\\`,\n          method: \"POST\",\n          body: queryArg.body,\n        }),\n        invalidatesTags: [\"user\"],\n      }),\n      loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n        query: (queryArg) => ({\n          url: \\`/user/login\\`,\n          params: {\n            username: queryArg.username,\n            password: queryArg.password,\n          },\n        }),\n        providesTags: [\"user\"],\n      }),\n      logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n        query: () => ({ url: \\`/user/logout\\` }),\n        providesTags: [\"user\"],\n      }),\n      getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>(\n        {\n          query: (queryArg) => ({ url: \\`/user/\\${queryArg.username}\\` }),\n          providesTags: [\"user\"],\n        },\n      ),\n      updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n        query: (queryArg) => ({\n          url: \\`/user/\\${queryArg.username}\\`,\n          method: \"PUT\",\n          body: queryArg.user,\n        }),\n        invalidatesTags: [\"user\"],\n      }),\n      deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n        query: (queryArg) => ({\n          url: \\`/user/\\${queryArg.username}\\`,\n          method: \"DELETE\",\n        }),\n        invalidatesTags: [\"user\"],\n      }),\n    }),\n    overrideExisting: false,\n  });\nexport { injectedRtkApi as enhancedApi };\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: \"available\" | \"pending\" | \"sold\";\n};\nexport type FindPetsByTagsApiResponse =\n  /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = {\n  /** Tags to filter by */\n  tags?: string[];\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n  /** Status of pet that needs to be updated */\n  status?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  apiKey?: string;\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse =\n  /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: Blob;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = void;\nexport type PlaceOrderApiResponse =\n  /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse =\n  /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse =\n  /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse =\n  /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = void;\nexport type GetUserByNameApiResponse =\n  /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Tag = {\n  id?: number | undefined;\n  name?: string | undefined;\n};\nexport type Pet = {\n  id?: number | undefined;\n  name: string;\n  category?: Category | undefined;\n  photoUrls: string[];\n  tags?: Tag[] | undefined;\n  /** pet status in the store */\n  status?: (\"available\" | \"pending\" | \"sold\") | undefined;\n};\nexport type ApiResponse = {\n  code?: number | undefined;\n  type?: string | undefined;\n  message?: string | undefined;\n};\nexport type Order = {\n  id?: number | undefined;\n  petId?: number | undefined;\n  quantity?: number | undefined;\n  shipDate?: string | undefined;\n  /** Order Status */\n  status?: (\"placed\" | \"approved\" | \"delivered\") | undefined;\n  complete?: boolean | undefined;\n};\nexport type User = {\n  id?: number | undefined;\n  username?: string | undefined;\n  firstName?: string | undefined;\n  lastName?: string | undefined;\n  email?: string | undefined;\n  password?: string | undefined;\n  phone?: string | undefined;\n  /** User Status */\n  userStatus?: number | undefined;\n};\nexport const {\n  useUpdatePetMutation,\n  useAddPetMutation,\n  useFindPetsByStatusQuery,\n  useFindPetsByTagsQuery,\n  useGetPetByIdQuery,\n  useUpdatePetWithFormMutation,\n  useDeletePetMutation,\n  useUploadFileMutation,\n  useGetInventoryQuery,\n  usePlaceOrderMutation,\n  useGetOrderByIdQuery,\n  useDeleteOrderMutation,\n  useCreateUserMutation,\n  useCreateUsersWithListInputMutation,\n  useLoginUserQuery,\n  useLogoutUserQuery,\n  useGetUserByNameQuery,\n  useUpdateUserMutation,\n  useDeleteUserMutation,\n} = injectedRtkApi;\n\"\n`;\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/cli.test.ts",
    "content": "import { exec as _exec } from 'node:child_process';\nimport fs from 'node:fs/promises';\nimport path from 'node:path';\nimport { promisify } from 'node:util';\nimport { rimraf } from 'rimraf';\n\nconst exec = promisify(_exec);\n\nconst cliPath = process.env.TEST_DIST ? 'rtk-query-codegen-openapi' : `yarn cli`;\n\nconst cli = async (args: string[]) => {\n  return await exec(`${cliPath} ${args.join(' ')}`);\n};\n\nconst tmpDir = path.resolve(__dirname, 'tmp');\n\nexport const removeTempDir = async () => {\n  await rimraf(tmpDir);\n};\n\nexport const isDir = async (filePath: string) => {\n  try {\n    const stat = await fs.lstat(filePath);\n    return stat.isDirectory();\n  } catch {\n    return false;\n  }\n};\n\ndescribe('CLI options testing', () => {\n  beforeAll(async () => {\n    if (!(await isDir(tmpDir))) {\n      await fs.mkdir(tmpDir, { recursive: true });\n    }\n  });\n\n  afterEach(async () => {\n    await rimraf(`${tmpDir}/*.ts`, { glob: true });\n  });\n\n  test('generation with `config.example.js`', { timeout: 25_000 }, async () => {\n    const out = await cli(['./test/config.example.js']);\n\n    expect(out).toEqual({\n      stdout: `Generating ./tmp/example.ts\nDone\n`,\n      stderr: '',\n    });\n\n    expect(await fs.readFile(path.resolve(tmpDir, 'example.ts'), 'utf-8')).toMatchSnapshot();\n  });\n\n  test('paths are relative to config file, not to cwd', { timeout: 25_000 }, async () => {\n    const out = await cli([`./test/config.example.js`]);\n\n    expect(out).toEqual({\n      stdout: `Generating ./tmp/example.ts\nDone\n`,\n      stderr: '',\n    });\n\n    expect(await fs.readFile(path.resolve(tmpDir, 'example.ts'), 'utf-8')).toMatchSnapshot();\n  });\n\n  test('ts, js and json all work the same', { timeout: 120_000 }, async () => {\n    await cli([`./test/config.example.js`]);\n    const fromJs = await fs.readFile(path.resolve(tmpDir, 'example.ts'), 'utf-8');\n    await cli([`./test/config.example.ts`]);\n    const fromTs = await fs.readFile(path.resolve(tmpDir, 'example.ts'), 'utf-8');\n    await cli([`./test/config.example.json`]);\n    const fromJson = await fs.readFile(path.resolve(tmpDir, 'example.ts'), 'utf-8');\n\n    expect(fromTs).toEqual(fromJs);\n    expect(fromJson).toEqual(fromJs);\n  });\n\n  test(\"missing parameters doesn't fail\", { timeout: 25_000 }, async () => {\n    await expect(() => cli([`./test/config.invalid-example.json`])).rejects.toThrowError(\n      \"Error: path parameter petId does not seem to be defined in '/pet/{petId}'!\"\n    );\n  });\n});\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/config.example.enum.ts",
    "content": "import type { ConfigFile } from '@rtk-query/codegen-openapi';\n\nconst config: ConfigFile = {\n  schemaFile: './fixtures/petstore.yaml',\n  apiFile: './fixtures/emptyApi.ts',\n  outputFile: './tmp/example.ts',\n  useEnumType: true,\n};\n\nexport default config;\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/config.example.js",
    "content": "/**\n * @type {import(\"@rtk-query/codegen-openapi\").ConfigFile}\n */\nmodule.exports = {\n  schemaFile: './fixtures/petstore.yaml',\n  apiFile: './fixtures/emptyApi.ts',\n  outputFile: './tmp/example.ts',\n};\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/config.example.json",
    "content": "{\n  \"schemaFile\": \"./fixtures/petstore.yaml\",\n  \"apiFile\": \"./fixtures/emptyApi.ts\",\n  \"outputFile\": \"./tmp/example.ts\"\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/config.example.ts",
    "content": "import type { ConfigFile } from '@rtk-query/codegen-openapi';\n\nconst config: ConfigFile = {\n  schemaFile: './fixtures/petstore.yaml',\n  apiFile: './fixtures/emptyApi.ts',\n  outputFile: './tmp/example.ts',\n};\n\nexport default config;\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/config.invalid-example.json",
    "content": "{\n  \"schemaFile\": \"./fixtures/invalid-petstore.json\",\n  \"apiFile\": \"./fixtures/emptyApi.ts\",\n  \"outputFile\": \"./tmp/example.ts\"\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/customBaseQuery.ts",
    "content": "export const namedBaseQuery = () => {};\n\nexport function anotherNamedBaseQuery() {}\n\nexport default namedBaseQuery;\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/customBaseQueryWithoutDefault.ts",
    "content": "function customBaseQuery() {}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/emptyApi.ts",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({}),\n  endpoints: () => ({}),\n});\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/fhir.yaml",
    "content": "openapi: 3.0.1\ninfo:\n  title: FHIR Server\n  contact: {}\n  version: 5.4.0-PRE10-SNAPSHOT/5db01f3139/2021-05-03\ntags:\n  - name: StructureDefinition\n    description: The StructureDefinition FHIR resource type\npaths:\n  /StructureDefinition:\n    get:\n      tags:\n        - StructureDefinition\n      summary: Some summary\n      description: This is a search type\n      parameters:\n        - name: foo\n          in: query\n          description: Some description\n          style: simple\n        - name: _foo\n          in: query\n          description: Some description\n          style: simple\n        - name: -bar-bar\n          in: query\n          description: Some description\n          style: simple\n        - name: _bar_bar\n          in: query\n          description: Some description\n          style: simple\n        - name: foo:bar-foo.bar/foo\n          in: query\n          description: Some description\n          style: simple\n        - name: foo_bar\n          in: query\n          description: Some description\n          style: simple\n        - name: namingConflict\n          in: query\n          description: Some description\n          style: simple\n        - name: naming_conflict\n          in: query\n          description: Some description\n          style: simple\n      responses:\n        '200':\n          description: Success\n          content:\n            application/fhir+json:\n              schema:\n                $ref: '#/components/schemas/FHIR-JSON-RESOURCE'\n            application/fhir+xml:\n              schema:\n                $ref: '#/components/schemas/FHIR-XML-RESOURCE'\ncomponents:\n  schemas:\n    FHIR-JSON-RESOURCE:\n      type: object\n      description: A FHIR resource\n    FHIR-XML-RESOURCE:\n      type: object\n      description: A FHIR resource\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/generated.ts",
    "content": "import { createApi } from '@reduxjs/toolkit/query/react';\nimport { fetchBaseQuery } from '@reduxjs/toolkit/query';\nexport const api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/v3' }),\n  tagTypes: [],\n  endpoints: (build) => ({\n    getHealthcheck: build.query<GetHealthcheckApiResponse, GetHealthcheckApiArg>({\n      query: () => ({ url: `/healthcheck` }),\n    }),\n    updatePet: build.mutation<UpdatePetApiResponse, UpdatePetApiArg>({\n      query: (queryArg) => ({ url: `/pet`, method: 'PUT', body: queryArg.pet }),\n    }),\n    addPet: build.mutation<AddPetApiResponse, AddPetApiArg>({\n      query: (queryArg) => ({ url: `/pet`, method: 'POST', body: queryArg.pet }),\n    }),\n    findPetsByStatus: build.query<FindPetsByStatusApiResponse, FindPetsByStatusApiArg>({\n      query: (queryArg) => ({ url: `/pet/findByStatus`, params: { status: queryArg.status } }),\n    }),\n    findPetsByTags: build.query<FindPetsByTagsApiResponse, FindPetsByTagsApiArg>({\n      query: (queryArg) => ({ url: `/pet/findByTags`, params: { tags: queryArg.tags } }),\n    }),\n    getPetById: build.query<GetPetByIdApiResponse, GetPetByIdApiArg>({\n      query: (queryArg) => ({ url: `/pet/${queryArg.petId}` }),\n    }),\n    updatePetWithForm: build.mutation<UpdatePetWithFormApiResponse, UpdatePetWithFormApiArg>({\n      query: (queryArg) => ({\n        url: `/pet/${queryArg.petId}`,\n        method: 'POST',\n        params: { name: queryArg.name, status: queryArg.status },\n      }),\n    }),\n    deletePet: build.mutation<DeletePetApiResponse, DeletePetApiArg>({\n      query: (queryArg) => ({ url: `/pet/${queryArg.petId}`, method: 'DELETE', headers: { api_key: queryArg.apiKey } }),\n    }),\n    uploadFile: build.mutation<UploadFileApiResponse, UploadFileApiArg>({\n      query: (queryArg) => ({\n        url: `/pet/${queryArg.petId}/uploadImage`,\n        method: 'POST',\n        body: queryArg.body,\n        params: { additionalMetadata: queryArg.additionalMetadata },\n      }),\n    }),\n    getInventory: build.query<GetInventoryApiResponse, GetInventoryApiArg>({\n      query: () => ({ url: `/store/inventory` }),\n    }),\n    placeOrder: build.mutation<PlaceOrderApiResponse, PlaceOrderApiArg>({\n      query: (queryArg) => ({ url: `/store/order`, method: 'POST', body: queryArg.order }),\n    }),\n    getOrderById: build.query<GetOrderByIdApiResponse, GetOrderByIdApiArg>({\n      query: (queryArg) => ({ url: `/store/order/${queryArg.orderId}` }),\n    }),\n    deleteOrder: build.mutation<DeleteOrderApiResponse, DeleteOrderApiArg>({\n      query: (queryArg) => ({ url: `/store/order/${queryArg.orderId}`, method: 'DELETE' }),\n    }),\n    createUser: build.mutation<CreateUserApiResponse, CreateUserApiArg>({\n      query: (queryArg) => ({ url: `/user`, method: 'POST', body: queryArg.user }),\n    }),\n    createUsersWithListInput: build.mutation<CreateUsersWithListInputApiResponse, CreateUsersWithListInputApiArg>({\n      query: (queryArg) => ({ url: `/user/createWithList`, method: 'POST', body: queryArg.body }),\n    }),\n    loginUser: build.query<LoginUserApiResponse, LoginUserApiArg>({\n      query: (queryArg) => ({\n        url: `/user/login`,\n        params: { username: queryArg.username, password: queryArg.password },\n      }),\n    }),\n    logoutUser: build.query<LogoutUserApiResponse, LogoutUserApiArg>({\n      query: () => ({ url: `/user/logout` }),\n    }),\n    getUserByName: build.query<GetUserByNameApiResponse, GetUserByNameApiArg>({\n      query: (queryArg) => ({ url: `/user/${queryArg.username}` }),\n    }),\n    updateUser: build.mutation<UpdateUserApiResponse, UpdateUserApiArg>({\n      query: (queryArg) => ({ url: `/user/${queryArg.username}`, method: 'PUT', body: queryArg.user }),\n    }),\n    deleteUser: build.mutation<DeleteUserApiResponse, DeleteUserApiArg>({\n      query: (queryArg) => ({ url: `/user/${queryArg.username}`, method: 'DELETE' }),\n    }),\n  }),\n});\nexport type GetHealthcheckApiResponse = /** status 200 OK */ {\n  message: string;\n};\nexport type GetHealthcheckApiArg = {};\nexport type UpdatePetApiResponse = /** status 200 Successful operation */ Pet;\nexport type UpdatePetApiArg = {\n  /** Update an existent pet in the store */\n  pet: Pet;\n};\nexport type AddPetApiResponse = /** status 200 Successful operation */ Pet;\nexport type AddPetApiArg = {\n  /** Create a new pet in the store */\n  pet: Pet;\n};\nexport type FindPetsByStatusApiResponse = /** status 200 successful operation */ Pet[];\nexport type FindPetsByStatusApiArg = {\n  /** Status values that need to be considered for filter */\n  status?: 'available' | 'pending' | 'sold';\n};\nexport type FindPetsByTagsApiResponse = /** status 200 successful operation */ Pet[];\nexport type FindPetsByTagsApiArg = {\n  /** Tags to filter by */\n  tags?: string[];\n};\nexport type GetPetByIdApiResponse = /** status 200 successful operation */ Pet;\nexport type GetPetByIdApiArg = {\n  /** ID of pet to return */\n  petId: number;\n};\nexport type UpdatePetWithFormApiResponse = unknown;\nexport type UpdatePetWithFormApiArg = {\n  /** ID of pet that needs to be updated */\n  petId: number;\n  /** Name of pet that needs to be updated */\n  name?: string;\n  /** Status of pet that needs to be updated */\n  status?: string;\n};\nexport type DeletePetApiResponse = unknown;\nexport type DeletePetApiArg = {\n  apiKey?: string;\n  /** Pet id to delete */\n  petId: number;\n};\nexport type UploadFileApiResponse = /** status 200 successful operation */ ApiResponse;\nexport type UploadFileApiArg = {\n  /** ID of pet to update */\n  petId: number;\n  /** Additional Metadata */\n  additionalMetadata?: string;\n  body: string;\n};\nexport type GetInventoryApiResponse = /** status 200 successful operation */ {\n  [key: string]: number;\n};\nexport type GetInventoryApiArg = {};\nexport type PlaceOrderApiResponse = /** status 200 successful operation */ Order;\nexport type PlaceOrderApiArg = {\n  order: Order;\n};\nexport type GetOrderByIdApiResponse = /** status 200 successful operation */ Order;\nexport type GetOrderByIdApiArg = {\n  /** ID of order that needs to be fetched */\n  orderId: number;\n};\nexport type DeleteOrderApiResponse = unknown;\nexport type DeleteOrderApiArg = {\n  /** ID of the order that needs to be deleted */\n  orderId: number;\n};\nexport type CreateUserApiResponse = unknown;\nexport type CreateUserApiArg = {\n  /** Created user object */\n  user: User;\n};\nexport type CreateUsersWithListInputApiResponse = /** status 200 Successful operation */ User;\nexport type CreateUsersWithListInputApiArg = {\n  body: User[];\n};\nexport type LoginUserApiResponse = /** status 200 successful operation */ string;\nexport type LoginUserApiArg = {\n  /** The user name for login */\n  username?: string;\n  /** The password for login in clear text */\n  password?: string;\n};\nexport type LogoutUserApiResponse = unknown;\nexport type LogoutUserApiArg = {};\nexport type GetUserByNameApiResponse = /** status 200 successful operation */ User;\nexport type GetUserByNameApiArg = {\n  /** The name that needs to be fetched. Use user1 for testing.  */\n  username: string;\n};\nexport type UpdateUserApiResponse = unknown;\nexport type UpdateUserApiArg = {\n  /** name that need to be deleted */\n  username: string;\n  /** Update an existent user in the store */\n  user: User;\n};\nexport type DeleteUserApiResponse = unknown;\nexport type DeleteUserApiArg = {\n  /** The name that needs to be deleted */\n  username: string;\n};\nexport type Category = {\n  id?: number;\n  name?: string;\n};\nexport type Tag = {\n  id?: number;\n  name?: string;\n};\nexport type Pet = {\n  id?: number;\n  name: string;\n  category?: Category;\n  photoUrls: string[];\n  tags?: Tag[];\n  status?: 'available' | 'pending' | 'sold';\n};\nexport type ApiResponse = {\n  code?: number;\n  type?: string;\n  message?: string;\n};\nexport type Order = {\n  id?: number;\n  petId?: number;\n  quantity?: number;\n  shipDate?: string;\n  status?: 'placed' | 'approved' | 'delivered';\n  complete?: boolean;\n};\nexport type User = {\n  id?: number;\n  username?: string;\n  firstName?: string;\n  lastName?: string;\n  email?: string;\n  password?: string;\n  phone?: string;\n  userStatus?: number;\n};\nexport const {\n  useGetHealthcheckQuery,\n  useUpdatePetMutation,\n  useAddPetMutation,\n  useFindPetsByStatusQuery,\n  useFindPetsByTagsQuery,\n  useGetPetByIdQuery,\n  useUpdatePetWithFormMutation,\n  useDeletePetMutation,\n  useUploadFileMutation,\n  useGetInventoryQuery,\n  usePlaceOrderMutation,\n  useGetOrderByIdQuery,\n  useDeleteOrderMutation,\n  useCreateUserMutation,\n  useCreateUsersWithListInputMutation,\n  useLoginUserQuery,\n  useLogoutUserQuery,\n  useGetUserByNameQuery,\n  useUpdateUserMutation,\n  useDeleteUserMutation,\n} = api;\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/invalid-petstore.json",
    "content": "{\n  \"openapi\": \"3.0.2\",\n  \"info\": {\n    \"title\": \"Swagger Petstore - OpenAPI 3.0\",\n    \"description\": \"This is a sample Pet Store Server based on the OpenAPI 3.0 specification.  You can find out more about\\nSwagger at [http://swagger.io](http://swagger.io). In the third iteration of the pet store, we've switched to the design first approach!\\nYou can now help us improve the API whether it's by making changes to the definition itself or to the code.\\nThat way, with time, we can improve the API in general, and expose some of the new features in OAS3.\\n\\nSome useful links:\\n- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore)\\n- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)\",\n    \"termsOfService\": \"http://swagger.io/terms/\",\n    \"contact\": {\n      \"email\": \"apiteam@swagger.io\"\n    },\n    \"license\": {\n      \"name\": \"Apache 2.0\",\n      \"url\": \"http://www.apache.org/licenses/LICENSE-2.0.html\"\n    },\n    \"version\": \"1.0.5\"\n  },\n  \"externalDocs\": {\n    \"description\": \"Find out more about Swagger\",\n    \"url\": \"http://swagger.io\"\n  },\n  \"servers\": [\n    {\n      \"url\": \"/api/v3\"\n    }\n  ],\n  \"tags\": [\n    {\n      \"name\": \"pet\",\n      \"description\": \"Everything about your Pets\",\n      \"externalDocs\": {\n        \"description\": \"Find out more\",\n        \"url\": \"http://swagger.io\"\n      }\n    },\n    {\n      \"name\": \"store\",\n      \"description\": \"Operations about user\"\n    },\n    {\n      \"name\": \"user\",\n      \"description\": \"Access to Petstore orders\",\n      \"externalDocs\": {\n        \"description\": \"Find out more about our store\",\n        \"url\": \"http://swagger.io\"\n      }\n    }\n  ],\n  \"paths\": {\n    \"/healthcheck\": {\n      \"get\": {\n        \"responses\": {\n          \"200\": {\n            \"description\": \"OK\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"properties\": {\n                    \"message\": {\n                      \"type\": \"string\",\n                      \"example\": \"I'm health\"\n                    }\n                  },\n                  \"required\": [\"message\"]\n                }\n              }\n            }\n          }\n        }\n      }\n    },\n    \"/pet\": {\n      \"put\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Update an existing pet\",\n        \"description\": \"Update an existing pet by Id\",\n        \"operationId\": \"updatePet\",\n        \"requestBody\": {\n          \"description\": \"Update an existent pet in the store\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            },\n            \"application/xml\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            }\n          },\n          \"required\": true\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid ID supplied\"\n          },\n          \"404\": {\n            \"description\": \"Pet not found\"\n          },\n          \"405\": {\n            \"description\": \"Validation exception\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      },\n      \"post\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Add a new pet to the store\",\n        \"description\": \"Add a new pet to the store\",\n        \"operationId\": \"addPet\",\n        \"requestBody\": {\n          \"description\": \"Create a new pet in the store\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            },\n            \"application/xml\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            }\n          },\n          \"required\": true\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              }\n            }\n          },\n          \"405\": {\n            \"description\": \"Invalid input\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      }\n    },\n    \"/pet/findByStatus\": {\n      \"get\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Finds Pets by status\",\n        \"description\": \"Multiple status values can be provided with comma separated strings\",\n        \"operationId\": \"findPetsByStatus\",\n        \"parameters\": [\n          {\n            \"name\": \"status\",\n            \"in\": \"query\",\n            \"description\": \"Status values that need to be considered for filter\",\n            \"required\": false,\n            \"explode\": true,\n            \"schema\": {\n              \"type\": \"string\",\n              \"default\": \"available\",\n              \"enum\": [\"available\", \"pending\", \"sold\"]\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/components/schemas/Pet\"\n                  }\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/components/schemas/Pet\"\n                  }\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid status value\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      }\n    },\n    \"/pet/findByTags\": {\n      \"get\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Finds Pets by tags\",\n        \"description\": \"Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.\",\n        \"operationId\": \"findPetsByTags\",\n        \"parameters\": [\n          {\n            \"name\": \"tags\",\n            \"in\": \"query\",\n            \"description\": \"Tags to filter by\",\n            \"required\": false,\n            \"explode\": true,\n            \"schema\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"type\": \"string\"\n              }\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/components/schemas/Pet\"\n                  }\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/components/schemas/Pet\"\n                  }\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid tag value\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      }\n    },\n    \"/pet/{petId}\": {\n      \"get\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Find pet by ID\",\n        \"description\": \"Returns a single pet\",\n        \"operationId\": \"getPetById\",\n        \"parameters\": [],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid ID supplied\"\n          },\n          \"404\": {\n            \"description\": \"Pet not found\"\n          }\n        },\n        \"security\": [\n          {\n            \"api_key\": []\n          },\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      },\n      \"post\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Updates a pet in the store with form data\",\n        \"description\": \"\",\n        \"operationId\": \"updatePetWithForm\",\n        \"parameters\": [\n          {\n            \"name\": \"petId\",\n            \"in\": \"path\",\n            \"description\": \"ID of pet that needs to be updated\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"integer\",\n              \"format\": \"int64\"\n            }\n          },\n          {\n            \"name\": \"name\",\n            \"in\": \"query\",\n            \"description\": \"Name of pet that needs to be updated\",\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          },\n          {\n            \"name\": \"status\",\n            \"in\": \"query\",\n            \"description\": \"Status of pet that needs to be updated\",\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"405\": {\n            \"description\": \"Invalid input\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      },\n      \"delete\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Deletes a pet\",\n        \"description\": \"\",\n        \"operationId\": \"deletePet\",\n        \"parameters\": [\n          {\n            \"name\": \"api_key\",\n            \"in\": \"header\",\n            \"description\": \"\",\n            \"required\": false,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          },\n          {\n            \"name\": \"petId\",\n            \"in\": \"path\",\n            \"description\": \"Pet id to delete\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"integer\",\n              \"format\": \"int64\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"400\": {\n            \"description\": \"Invalid pet value\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      }\n    },\n    \"/pet/{petId}/uploadImage\": {\n      \"post\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"uploads an image\",\n        \"description\": \"\",\n        \"operationId\": \"uploadFile\",\n        \"parameters\": [\n          {\n            \"name\": \"petId\",\n            \"in\": \"path\",\n            \"description\": \"ID of pet to update\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"integer\",\n              \"format\": \"int64\"\n            }\n          },\n          {\n            \"name\": \"additionalMetadata\",\n            \"in\": \"query\",\n            \"description\": \"Additional Metadata\",\n            \"required\": false,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"requestBody\": {\n          \"content\": {\n            \"application/octet-stream\": {\n              \"schema\": {\n                \"type\": \"string\",\n                \"format\": \"binary\"\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/ApiResponse\"\n                }\n              }\n            }\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      }\n    },\n    \"/store/inventory\": {\n      \"get\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Returns pet inventories by status\",\n        \"description\": \"Returns a map of status codes to quantities\",\n        \"operationId\": \"getInventory\",\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"object\",\n                  \"additionalProperties\": {\n                    \"type\": \"integer\",\n                    \"format\": \"int32\"\n                  }\n                }\n              }\n            }\n          }\n        },\n        \"security\": [\n          {\n            \"api_key\": []\n          }\n        ]\n      }\n    },\n    \"/store/order\": {\n      \"post\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Place an order for a pet\",\n        \"description\": \"Place a new order in the store\",\n        \"operationId\": \"placeOrder\",\n        \"requestBody\": {\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Order\"\n              }\n            },\n            \"application/xml\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Order\"\n              }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Order\"\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Order\"\n                }\n              }\n            }\n          },\n          \"405\": {\n            \"description\": \"Invalid input\"\n          }\n        }\n      }\n    },\n    \"/store/order/{orderId}\": {\n      \"get\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Find purchase order by ID\",\n        \"description\": \"For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions\",\n        \"operationId\": \"getOrderById\",\n        \"parameters\": [\n          {\n            \"name\": \"orderId\",\n            \"in\": \"path\",\n            \"description\": \"ID of order that needs to be fetched\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"integer\",\n              \"format\": \"int64\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Order\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Order\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid ID supplied\"\n          },\n          \"404\": {\n            \"description\": \"Order not found\"\n          }\n        }\n      },\n      \"delete\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Delete purchase order by ID\",\n        \"description\": \"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors\",\n        \"operationId\": \"deleteOrder\",\n        \"parameters\": [\n          {\n            \"name\": \"orderId\",\n            \"in\": \"path\",\n            \"description\": \"ID of the order that needs to be deleted\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"integer\",\n              \"format\": \"int64\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"400\": {\n            \"description\": \"Invalid ID supplied\"\n          },\n          \"404\": {\n            \"description\": \"Order not found\"\n          }\n        }\n      }\n    },\n    \"/user\": {\n      \"post\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Create user\",\n        \"description\": \"This can only be done by the logged in user.\",\n        \"operationId\": \"createUser\",\n        \"requestBody\": {\n          \"description\": \"Created user object\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            },\n            \"application/xml\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"default\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              },\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              }\n            }\n          }\n        }\n      }\n    },\n    \"/user/createWithList\": {\n      \"post\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Creates list of users with given input array\",\n        \"description\": \"Creates list of users with given input array\",\n        \"operationId\": \"createUsersWithListInput\",\n        \"requestBody\": {\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              }\n            }\n          },\n          \"default\": {\n            \"description\": \"successful operation\"\n          }\n        }\n      }\n    },\n    \"/user/login\": {\n      \"get\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Logs user into the system\",\n        \"description\": \"\",\n        \"operationId\": \"loginUser\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"query\",\n            \"description\": \"The user name for login\",\n            \"required\": false,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          },\n          {\n            \"name\": \"password\",\n            \"in\": \"query\",\n            \"description\": \"The password for login in clear text\",\n            \"required\": false,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"headers\": {\n              \"X-Rate-Limit\": {\n                \"description\": \"calls per hour allowed by the user\",\n                \"schema\": {\n                  \"type\": \"integer\",\n                  \"format\": \"int32\"\n                }\n              },\n              \"X-Expires-After\": {\n                \"description\": \"date in UTC when toekn expires\",\n                \"schema\": {\n                  \"type\": \"string\",\n                  \"format\": \"date-time\"\n                }\n              }\n            },\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid username/password supplied\"\n          }\n        }\n      }\n    },\n    \"/user/logout\": {\n      \"get\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Logs out current logged in user session\",\n        \"description\": \"\",\n        \"operationId\": \"logoutUser\",\n        \"parameters\": [],\n        \"responses\": {\n          \"default\": {\n            \"description\": \"successful operation\"\n          }\n        }\n      }\n    },\n    \"/user/{username}\": {\n      \"get\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Get user by user name\",\n        \"description\": \"\",\n        \"operationId\": \"getUserByName\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"path\",\n            \"description\": \"The name that needs to be fetched. Use user1 for testing. \",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid username supplied\"\n          },\n          \"404\": {\n            \"description\": \"User not found\"\n          }\n        }\n      },\n      \"put\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Update user\",\n        \"description\": \"This can only be done by the logged in user.\",\n        \"operationId\": \"updateUser\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"path\",\n            \"description\": \"name that need to be deleted\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"requestBody\": {\n          \"description\": \"Update an existent user in the store\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            },\n            \"application/xml\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"default\": {\n            \"description\": \"successful operation\"\n          }\n        }\n      },\n      \"delete\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Delete user\",\n        \"description\": \"This can only be done by the logged in user.\",\n        \"operationId\": \"deleteUser\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"path\",\n            \"description\": \"The name that needs to be deleted\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"400\": {\n            \"description\": \"Invalid username supplied\"\n          },\n          \"404\": {\n            \"description\": \"User not found\"\n          }\n        }\n      }\n    }\n  },\n  \"components\": {\n    \"schemas\": {\n      \"Order\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 10\n          },\n          \"petId\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 198772\n          },\n          \"quantity\": {\n            \"type\": \"integer\",\n            \"format\": \"int32\",\n            \"example\": 7\n          },\n          \"shipDate\": {\n            \"type\": \"string\",\n            \"format\": \"date-time\"\n          },\n          \"status\": {\n            \"type\": \"string\",\n            \"description\": \"Order Status\",\n            \"example\": \"approved\",\n            \"enum\": [\"placed\", \"approved\", \"delivered\"]\n          },\n          \"complete\": {\n            \"type\": \"boolean\"\n          }\n        },\n        \"xml\": {\n          \"name\": \"order\"\n        }\n      },\n      \"Customer\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 100000\n          },\n          \"username\": {\n            \"type\": \"string\",\n            \"example\": \"fehguy\"\n          },\n          \"address\": {\n            \"type\": \"array\",\n            \"xml\": {\n              \"name\": \"addresses\",\n              \"wrapped\": true\n            },\n            \"items\": {\n              \"$ref\": \"#/components/schemas/Address\"\n            }\n          }\n        },\n        \"xml\": {\n          \"name\": \"customer\"\n        }\n      },\n      \"Address\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"street\": {\n            \"type\": \"string\",\n            \"example\": \"437 Lytton\"\n          },\n          \"city\": {\n            \"type\": \"string\",\n            \"example\": \"Palo Alto\"\n          },\n          \"state\": {\n            \"type\": \"string\",\n            \"example\": \"CA\"\n          },\n          \"zip\": {\n            \"type\": \"string\",\n            \"example\": \"94301\"\n          }\n        },\n        \"xml\": {\n          \"name\": \"address\"\n        }\n      },\n      \"Category\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 1\n          },\n          \"name\": {\n            \"type\": \"string\",\n            \"example\": \"Dogs\"\n          }\n        },\n        \"xml\": {\n          \"name\": \"category\"\n        }\n      },\n      \"User\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 10\n          },\n          \"username\": {\n            \"type\": \"string\",\n            \"example\": \"theUser\"\n          },\n          \"firstName\": {\n            \"type\": \"string\",\n            \"example\": \"John\"\n          },\n          \"lastName\": {\n            \"type\": \"string\",\n            \"example\": \"James\"\n          },\n          \"email\": {\n            \"type\": \"string\",\n            \"example\": \"john@email.com\"\n          },\n          \"password\": {\n            \"type\": \"string\",\n            \"example\": \"12345\"\n          },\n          \"phone\": {\n            \"type\": \"string\",\n            \"example\": \"12345\"\n          },\n          \"userStatus\": {\n            \"type\": \"integer\",\n            \"description\": \"User Status\",\n            \"format\": \"int32\",\n            \"example\": 1\n          }\n        },\n        \"xml\": {\n          \"name\": \"user\"\n        }\n      },\n      \"Tag\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\"\n          },\n          \"name\": {\n            \"type\": \"string\"\n          }\n        },\n        \"xml\": {\n          \"name\": \"tag\"\n        }\n      },\n      \"Pet\": {\n        \"required\": [\"name\", \"photoUrls\"],\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 10\n          },\n          \"name\": {\n            \"type\": \"string\",\n            \"example\": \"doggie\"\n          },\n          \"category\": {\n            \"$ref\": \"#/components/schemas/Category\"\n          },\n          \"photoUrls\": {\n            \"type\": \"array\",\n            \"xml\": {\n              \"wrapped\": true\n            },\n            \"items\": {\n              \"type\": \"string\",\n              \"xml\": {\n                \"name\": \"photoUrl\"\n              }\n            }\n          },\n          \"tags\": {\n            \"type\": \"array\",\n            \"xml\": {\n              \"wrapped\": true\n            },\n            \"items\": {\n              \"$ref\": \"#/components/schemas/Tag\"\n            }\n          },\n          \"status\": {\n            \"type\": \"string\",\n            \"description\": \"pet status in the store\",\n            \"enum\": [\"available\", \"pending\", \"sold\"]\n          }\n        },\n        \"xml\": {\n          \"name\": \"pet\"\n        }\n      },\n      \"ApiResponse\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"code\": {\n            \"type\": \"integer\",\n            \"format\": \"int32\"\n          },\n          \"type\": {\n            \"type\": \"string\"\n          },\n          \"message\": {\n            \"type\": \"string\"\n          }\n        },\n        \"xml\": {\n          \"name\": \"##default\"\n        }\n      }\n    },\n    \"requestBodies\": {\n      \"Pet\": {\n        \"description\": \"Pet object that needs to be added to the store\",\n        \"content\": {\n          \"application/json\": {\n            \"schema\": {\n              \"$ref\": \"#/components/schemas/Pet\"\n            }\n          },\n          \"application/xml\": {\n            \"schema\": {\n              \"$ref\": \"#/components/schemas/Pet\"\n            }\n          }\n        }\n      },\n      \"UserArray\": {\n        \"description\": \"List of user object\",\n        \"content\": {\n          \"application/json\": {\n            \"schema\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            }\n          }\n        }\n      }\n    },\n    \"securitySchemes\": {\n      \"petstore_auth\": {\n        \"type\": \"oauth2\",\n        \"flows\": {\n          \"implicit\": {\n            \"authorizationUrl\": \"https://petstore3.swagger.io/oauth/authorize\",\n            \"scopes\": {\n              \"write:pets\": \"modify pets in your account\",\n              \"read:pets\": \"read your pets\"\n            }\n          }\n        }\n      },\n      \"api_key\": {\n        \"type\": \"apiKey\",\n        \"name\": \"api_key\",\n        \"in\": \"header\"\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/issue-2002.json",
    "content": "{\n  \"openapi\": \"3.0.1\",\n  \"info\": {\n    \"title\": \"Animals API\",\n    \"version\": \"1.0.0\"\n  },\n  \"servers\": [\n    {\n      \"url\": \"https://localhost:8000\"\n    }\n  ],\n  \"paths\": {\n    \"/api/v1/animals\": {\n      \"get\": {\n        \"parameters\": [\n          {\n            \"name\": \"type\",\n            \"in\": \"query\",\n            \"schema\": {\n              \"$ref\": \"#/components/schemas/AnimalType\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Success\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"oneOf\": [\n                      {\n                        \"$ref\": \"#/components/schemas/Dog\"\n                      },\n                      {\n                        \"$ref\": \"#/components/schemas/Cat\"\n                      }\n                    ],\n                    \"description\": \"Base animal type.\"\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  },\n  \"components\": {\n    \"schemas\": {\n      \"AnimalType\": {\n        \"type\": \"string\",\n        \"enum\": [\"All\", \"Cats\", \"Dogs\"]\n      },\n      \"Animal\": {\n        \"required\": [\"type\"],\n        \"type\": \"object\",\n        \"properties\": {\n          \"type\": {\n            \"type\": \"string\",\n            \"$ref\": \"#/components/schemas/AnimalType\"\n          },\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\"\n          },\n          \"name\": {\n            \"type\": \"string\",\n            \"nullable\": true\n          }\n        },\n        \"additionalProperties\": false,\n        \"description\": \"Base animal type.\",\n        \"discriminator\": {\n          \"propertyName\": \"type\",\n          \"mapping\": {\n            \"Dog\": \"#/components/schemas/Dog\",\n            \"Cat\": \"#/components/schemas/Cat\"\n          }\n        }\n      },\n      \"Dog\": {\n        \"type\": \"object\",\n        \"allOf\": [\n          {\n            \"$ref\": \"#/components/schemas/Animal\"\n          }\n        ],\n        \"properties\": {\n          \"dogUniqueProp\": {\n            \"type\": \"string\",\n            \"nullable\": true\n          }\n        },\n        \"additionalProperties\": false,\n        \"description\": \"Dog animal\"\n      },\n      \"Cat\": {\n        \"type\": \"object\",\n        \"allOf\": [\n          {\n            \"$ref\": \"#/components/schemas/Animal\"\n          }\n        ],\n        \"properties\": {\n          \"catUniqueProp\": {\n            \"type\": \"string\",\n            \"nullable\": true\n          }\n        },\n        \"additionalProperties\": false,\n        \"description\": \"Cat animal\"\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/issue-3369-discriminator-enum.json",
    "content": "{\n  \"openapi\": \"3.0.1\",\n  \"info\": {\n    \"title\": \"Discriminator Enum Test - Issue 3369\",\n    \"description\": \"Test that discriminated unions use enum values (e.g., 'standard') instead of schema names (e.g., 'StandardAllowance')\",\n    \"version\": \"1.0.0\"\n  },\n  \"servers\": [\n    {\n      \"url\": \"https://localhost:8000\"\n    }\n  ],\n  \"paths\": {\n    \"/api/allowances\": {\n      \"get\": {\n        \"operationId\": \"getAllowances\",\n        \"summary\": \"Get all allowances\",\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Success\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/components/schemas/Allowance\"\n                  }\n                }\n              }\n            }\n          }\n        }\n      }\n    },\n    \"/api/allowances/{id}\": {\n      \"post\": {\n        \"operationId\": \"createAllowance\",\n        \"summary\": \"Create an allowance\",\n        \"parameters\": [\n          {\n            \"name\": \"id\",\n            \"in\": \"path\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"requestBody\": {\n          \"required\": true,\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Allowance\"\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"201\": {\n            \"description\": \"Created\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Allowance\"\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  },\n  \"components\": {\n    \"schemas\": {\n      \"Allowance\": {\n        \"oneOf\": [\n          {\n            \"$ref\": \"#/components/schemas/EngineeringAllowance\"\n          },\n          {\n            \"$ref\": \"#/components/schemas/StandardAllowance\"\n          }\n        ],\n        \"discriminator\": {\n          \"propertyName\": \"allowance_type\"\n        }\n      },\n      \"EngineeringAllowance\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"allowance_type\": {\n            \"type\": \"string\",\n            \"enum\": [\"engineering\"]\n          },\n          \"distribution\": {\n            \"type\": \"string\",\n            \"enum\": [\"MARECO\", \"LINEAR\"]\n          },\n          \"capacity_speed_limit\": {\n            \"type\": \"number\",\n            \"format\": \"double\"\n          }\n        }\n      },\n      \"StandardAllowance\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"allowance_type\": {\n            \"type\": \"string\",\n            \"enum\": [\"standard\"]\n          },\n          \"default_value\": {\n            \"type\": \"number\"\n          },\n          \"ranges\": {\n            \"type\": \"array\",\n            \"items\": {\n              \"type\": \"object\",\n              \"properties\": {\n                \"min\": {\n                  \"type\": \"number\"\n                },\n                \"max\": {\n                  \"type\": \"number\"\n                }\n              }\n            }\n          }\n        }\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/parameterOverride.yaml",
    "content": "openapi: 3.0.2\ninfo:\n  title: parameterOverride\n  version: 1.0.0\npaths:\n  /users/{id}:\n    parameters:\n      - in: path\n        name: id\n        schema:\n          type: string\n        required: true\n    get:\n      summary: Gets one or more users by ID.\n      parameters:\n        - in: path\n          name: id\n          required: true\n          schema:\n            type: integer\n      responses:\n        '200':\n          description: OK\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/params.json",
    "content": "{\n  \"swagger\": \"2.0\",\n  \"info\": {\n    \"title\": \"Params test\",\n    \"version\": \"0.1\"\n  },\n  \"schemes\": [\"https\"],\n  \"consumes\": [\"application/json\"],\n  \"produces\": [\"application/json\"],\n  \"paths\": {\n    \"/api/v1/list/{item.id}\": {\n      \"patch\": {\n        \"responses\": {\n          \"200\": {\n            \"description\": \"A successful response.\",\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        },\n        \"parameters\": [\n          {\n            \"name\": \"item.id\",\n            \"in\": \"path\",\n            \"required\": true,\n            \"type\": \"string\"\n          }\n        ]\n      }\n    },\n    \"/api/v2/{some_name}\": {\n      \"patch\": {\n        \"responses\": {\n          \"200\": {\n            \"description\": \"A successful response.\",\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        },\n        \"parameters\": [\n          {\n            \"name\": \"some_name\",\n            \"in\": \"path\",\n            \"required\": true,\n            \"type\": \"string\"\n          },\n          {\n            \"name\": \"some_name\",\n            \"in\": \"query\",\n            \"required\": true,\n            \"type\": \"string\"\n          }\n        ]\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/petstore.json",
    "content": "{\n  \"openapi\": \"3.0.2\",\n  \"info\": {\n    \"title\": \"Swagger Petstore - OpenAPI 3.0\",\n    \"description\": \"This is a sample Pet Store Server based on the OpenAPI 3.0 specification.  You can find out more about\\nSwagger at [http://swagger.io](http://swagger.io). In the third iteration of the pet store, we've switched to the design first approach!\\nYou can now help us improve the API whether it's by making changes to the definition itself or to the code.\\nThat way, with time, we can improve the API in general, and expose some of the new features in OAS3.\\n\\nSome useful links:\\n- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore)\\n- [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)\",\n    \"termsOfService\": \"http://swagger.io/terms/\",\n    \"contact\": {\n      \"email\": \"apiteam@swagger.io\"\n    },\n    \"license\": {\n      \"name\": \"Apache 2.0\",\n      \"url\": \"http://www.apache.org/licenses/LICENSE-2.0.html\"\n    },\n    \"version\": \"1.0.5\"\n  },\n  \"externalDocs\": {\n    \"description\": \"Find out more about Swagger\",\n    \"url\": \"http://swagger.io\"\n  },\n  \"servers\": [\n    {\n      \"url\": \"/api/v3\"\n    }\n  ],\n  \"tags\": [\n    {\n      \"name\": \"pet\",\n      \"description\": \"Everything about your Pets\",\n      \"externalDocs\": {\n        \"description\": \"Find out more\",\n        \"url\": \"http://swagger.io\"\n      }\n    },\n    {\n      \"name\": \"store\",\n      \"description\": \"Operations about user\"\n    },\n    {\n      \"name\": \"user\",\n      \"description\": \"Access to Petstore orders\",\n      \"externalDocs\": {\n        \"description\": \"Find out more about our store\",\n        \"url\": \"http://swagger.io\"\n      }\n    }\n  ],\n  \"paths\": {\n    \"/healthcheck\": {\n      \"get\": {\n        \"responses\": {\n          \"200\": {\n            \"description\": \"OK\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"properties\": {\n                    \"message\": {\n                      \"type\": \"string\",\n                      \"example\": \"I'm health\"\n                    }\n                  },\n                  \"required\": [\"message\"]\n                }\n              }\n            }\n          }\n        }\n      }\n    },\n    \"/pet\": {\n      \"put\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Update an existing pet\",\n        \"description\": \"Update an existing pet by Id\",\n        \"operationId\": \"updatePet\",\n        \"requestBody\": {\n          \"description\": \"Update an existent pet in the store\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            },\n            \"application/xml\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            }\n          },\n          \"required\": true\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid ID supplied\"\n          },\n          \"404\": {\n            \"description\": \"Pet not found\"\n          },\n          \"405\": {\n            \"description\": \"Validation exception\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      },\n      \"post\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Add a new pet to the store\",\n        \"description\": \"Add a new pet to the store\",\n        \"operationId\": \"addPet\",\n        \"requestBody\": {\n          \"description\": \"Create a new pet in the store\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            },\n            \"application/xml\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Pet\"\n              }\n            }\n          },\n          \"required\": true\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              }\n            }\n          },\n          \"405\": {\n            \"description\": \"Invalid input\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      }\n    },\n    \"/pet/findByStatus\": {\n      \"get\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Finds Pets by status\",\n        \"description\": \"Multiple status values can be provided with comma separated strings\",\n        \"operationId\": \"findPetsByStatus\",\n        \"parameters\": [\n          {\n            \"name\": \"status\",\n            \"in\": \"query\",\n            \"description\": \"Status values that need to be considered for filter\",\n            \"required\": false,\n            \"explode\": true,\n            \"schema\": {\n              \"type\": \"string\",\n              \"default\": \"available\",\n              \"enum\": [\"available\", \"pending\", \"sold\"]\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/components/schemas/Pet\"\n                  }\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/components/schemas/Pet\"\n                  }\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid status value\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      }\n    },\n    \"/pet/findByTags\": {\n      \"get\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Finds Pets by tags\",\n        \"description\": \"Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.\",\n        \"operationId\": \"findPetsByTags\",\n        \"parameters\": [\n          {\n            \"name\": \"tags\",\n            \"in\": \"query\",\n            \"description\": \"Tags to filter by\",\n            \"required\": false,\n            \"explode\": true,\n            \"schema\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"type\": \"string\"\n              }\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/components/schemas/Pet\"\n                  }\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"array\",\n                  \"items\": {\n                    \"$ref\": \"#/components/schemas/Pet\"\n                  }\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid tag value\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      }\n    },\n    \"/pet/{petId}\": {\n      \"get\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Find pet by ID\",\n        \"description\": \"Returns a single pet\",\n        \"operationId\": \"getPetById\",\n        \"parameters\": [\n          {\n            \"name\": \"petId\",\n            \"in\": \"path\",\n            \"description\": \"ID of pet to return\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"integer\",\n              \"format\": \"int64\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Pet\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid ID supplied\"\n          },\n          \"404\": {\n            \"description\": \"Pet not found\"\n          }\n        },\n        \"security\": [\n          {\n            \"api_key\": []\n          },\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      },\n      \"post\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Updates a pet in the store with form data\",\n        \"description\": \"\",\n        \"operationId\": \"updatePetWithForm\",\n        \"parameters\": [\n          {\n            \"name\": \"petId\",\n            \"in\": \"path\",\n            \"description\": \"ID of pet that needs to be updated\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"integer\",\n              \"format\": \"int64\"\n            }\n          },\n          {\n            \"name\": \"name\",\n            \"in\": \"query\",\n            \"description\": \"Name of pet that needs to be updated\",\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          },\n          {\n            \"name\": \"status\",\n            \"in\": \"query\",\n            \"description\": \"Status of pet that needs to be updated\",\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"405\": {\n            \"description\": \"Invalid input\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      },\n      \"delete\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"Deletes a pet\",\n        \"description\": \"\",\n        \"operationId\": \"deletePet\",\n        \"parameters\": [\n          {\n            \"name\": \"api_key\",\n            \"in\": \"header\",\n            \"description\": \"\",\n            \"required\": false,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          },\n          {\n            \"name\": \"petId\",\n            \"in\": \"path\",\n            \"description\": \"Pet id to delete\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"integer\",\n              \"format\": \"int64\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"400\": {\n            \"description\": \"Invalid pet value\"\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      }\n    },\n    \"/pet/{petId}/uploadImage\": {\n      \"post\": {\n        \"tags\": [\"pet\"],\n        \"summary\": \"uploads an image\",\n        \"description\": \"\",\n        \"operationId\": \"uploadFile\",\n        \"parameters\": [\n          {\n            \"name\": \"petId\",\n            \"in\": \"path\",\n            \"description\": \"ID of pet to update\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"integer\",\n              \"format\": \"int64\"\n            }\n          },\n          {\n            \"name\": \"additionalMetadata\",\n            \"in\": \"query\",\n            \"description\": \"Additional Metadata\",\n            \"required\": false,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"requestBody\": {\n          \"content\": {\n            \"application/octet-stream\": {\n              \"schema\": {\n                \"type\": \"string\",\n                \"format\": \"binary\"\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/ApiResponse\"\n                }\n              }\n            }\n          }\n        },\n        \"security\": [\n          {\n            \"petstore_auth\": [\"write:pets\", \"read:pets\"]\n          }\n        ]\n      }\n    },\n    \"/store/inventory\": {\n      \"get\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Returns pet inventories by status\",\n        \"description\": \"Returns a map of status codes to quantities\",\n        \"operationId\": \"getInventory\",\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"object\",\n                  \"additionalProperties\": {\n                    \"type\": \"integer\",\n                    \"format\": \"int32\"\n                  }\n                }\n              }\n            }\n          }\n        },\n        \"security\": [\n          {\n            \"api_key\": []\n          }\n        ]\n      }\n    },\n    \"/store/order\": {\n      \"post\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Place an order for a pet\",\n        \"description\": \"Place a new order in the store\",\n        \"operationId\": \"placeOrder\",\n        \"requestBody\": {\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Order\"\n              }\n            },\n            \"application/xml\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Order\"\n              }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/Order\"\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Order\"\n                }\n              }\n            }\n          },\n          \"405\": {\n            \"description\": \"Invalid input\"\n          }\n        }\n      }\n    },\n    \"/store/order/{orderId}\": {\n      \"get\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Find purchase order by ID\",\n        \"description\": \"For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions\",\n        \"operationId\": \"getOrderById\",\n        \"parameters\": [\n          {\n            \"name\": \"orderId\",\n            \"in\": \"path\",\n            \"description\": \"ID of order that needs to be fetched\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"integer\",\n              \"format\": \"int64\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Order\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/Order\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid ID supplied\"\n          },\n          \"404\": {\n            \"description\": \"Order not found\"\n          }\n        }\n      },\n      \"delete\": {\n        \"tags\": [\"store\"],\n        \"summary\": \"Delete purchase order by ID\",\n        \"description\": \"For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors\",\n        \"operationId\": \"deleteOrder\",\n        \"parameters\": [\n          {\n            \"name\": \"orderId\",\n            \"in\": \"path\",\n            \"description\": \"ID of the order that needs to be deleted\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"integer\",\n              \"format\": \"int64\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"400\": {\n            \"description\": \"Invalid ID supplied\"\n          },\n          \"404\": {\n            \"description\": \"Order not found\"\n          }\n        }\n      }\n    },\n    \"/user\": {\n      \"post\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Create user\",\n        \"description\": \"This can only be done by the logged in user.\",\n        \"operationId\": \"createUser\",\n        \"requestBody\": {\n          \"description\": \"Created user object\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            },\n            \"application/xml\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"default\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              },\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              }\n            }\n          }\n        }\n      }\n    },\n    \"/user/createWithList\": {\n      \"post\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Creates list of users with given input array\",\n        \"description\": \"Creates list of users with given input array\",\n        \"operationId\": \"createUsersWithListInput\",\n        \"requestBody\": {\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"type\": \"array\",\n                \"items\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"Successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              }\n            }\n          },\n          \"default\": {\n            \"description\": \"successful operation\"\n          }\n        }\n      }\n    },\n    \"/user/login\": {\n      \"get\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Logs user into the system\",\n        \"description\": \"\",\n        \"operationId\": \"loginUser\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"query\",\n            \"description\": \"The user name for login\",\n            \"required\": false,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          },\n          {\n            \"name\": \"password\",\n            \"in\": \"query\",\n            \"description\": \"The password for login in clear text\",\n            \"required\": false,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"headers\": {\n              \"X-Rate-Limit\": {\n                \"description\": \"calls per hour allowed by the user\",\n                \"schema\": {\n                  \"type\": \"integer\",\n                  \"format\": \"int32\"\n                }\n              },\n              \"X-Expires-After\": {\n                \"description\": \"date in UTC when toekn expires\",\n                \"schema\": {\n                  \"type\": \"string\",\n                  \"format\": \"date-time\"\n                }\n              }\n            },\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"type\": \"string\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid username/password supplied\"\n          }\n        }\n      }\n    },\n    \"/user/logout\": {\n      \"get\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Logs out current logged in user session\",\n        \"description\": \"\",\n        \"operationId\": \"logoutUser\",\n        \"parameters\": [],\n        \"responses\": {\n          \"default\": {\n            \"description\": \"successful operation\"\n          }\n        }\n      }\n    },\n    \"/user/{username}\": {\n      \"get\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Get user by user name\",\n        \"description\": \"\",\n        \"operationId\": \"getUserByName\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"path\",\n            \"description\": \"The name that needs to be fetched. Use user1 for testing. \",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"200\": {\n            \"description\": \"successful operation\",\n            \"content\": {\n              \"application/xml\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              },\n              \"application/json\": {\n                \"schema\": {\n                  \"$ref\": \"#/components/schemas/User\"\n                }\n              }\n            }\n          },\n          \"400\": {\n            \"description\": \"Invalid username supplied\"\n          },\n          \"404\": {\n            \"description\": \"User not found\"\n          }\n        }\n      },\n      \"put\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Update user\",\n        \"description\": \"This can only be done by the logged in user.\",\n        \"operationId\": \"updateUser\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"path\",\n            \"description\": \"name that need to be deleted\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"requestBody\": {\n          \"description\": \"Update an existent user in the store\",\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            },\n            \"application/xml\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            },\n            \"application/x-www-form-urlencoded\": {\n              \"schema\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"default\": {\n            \"description\": \"successful operation\"\n          }\n        }\n      },\n      \"delete\": {\n        \"tags\": [\"user\"],\n        \"summary\": \"Delete user\",\n        \"description\": \"This can only be done by the logged in user.\",\n        \"operationId\": \"deleteUser\",\n        \"parameters\": [\n          {\n            \"name\": \"username\",\n            \"in\": \"path\",\n            \"description\": \"The name that needs to be deleted\",\n            \"required\": true,\n            \"schema\": {\n              \"type\": \"string\"\n            }\n          }\n        ],\n        \"responses\": {\n          \"400\": {\n            \"description\": \"Invalid username supplied\"\n          },\n          \"404\": {\n            \"description\": \"User not found\"\n          }\n        }\n      }\n    }\n  },\n  \"components\": {\n    \"schemas\": {\n      \"Order\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 10\n          },\n          \"petId\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 198772\n          },\n          \"quantity\": {\n            \"type\": \"integer\",\n            \"format\": \"int32\",\n            \"example\": 7\n          },\n          \"shipDate\": {\n            \"type\": \"string\",\n            \"format\": \"date-time\"\n          },\n          \"status\": {\n            \"type\": \"string\",\n            \"description\": \"Order Status\",\n            \"example\": \"approved\",\n            \"enum\": [\"placed\", \"approved\", \"delivered\"]\n          },\n          \"complete\": {\n            \"type\": \"boolean\"\n          }\n        },\n        \"xml\": {\n          \"name\": \"order\"\n        }\n      },\n      \"Customer\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 100000\n          },\n          \"username\": {\n            \"type\": \"string\",\n            \"example\": \"fehguy\"\n          },\n          \"address\": {\n            \"type\": \"array\",\n            \"xml\": {\n              \"name\": \"addresses\",\n              \"wrapped\": true\n            },\n            \"items\": {\n              \"$ref\": \"#/components/schemas/Address\"\n            }\n          }\n        },\n        \"xml\": {\n          \"name\": \"customer\"\n        }\n      },\n      \"Address\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"street\": {\n            \"type\": \"string\",\n            \"example\": \"437 Lytton\"\n          },\n          \"city\": {\n            \"type\": \"string\",\n            \"example\": \"Palo Alto\"\n          },\n          \"state\": {\n            \"type\": \"string\",\n            \"example\": \"CA\"\n          },\n          \"zip\": {\n            \"type\": \"string\",\n            \"example\": \"94301\"\n          }\n        },\n        \"xml\": {\n          \"name\": \"address\"\n        }\n      },\n      \"Category\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 1\n          },\n          \"name\": {\n            \"type\": \"string\",\n            \"example\": \"Dogs\"\n          }\n        },\n        \"xml\": {\n          \"name\": \"category\"\n        }\n      },\n      \"User\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 10\n          },\n          \"username\": {\n            \"type\": \"string\",\n            \"example\": \"theUser\"\n          },\n          \"firstName\": {\n            \"type\": \"string\",\n            \"example\": \"John\"\n          },\n          \"lastName\": {\n            \"type\": \"string\",\n            \"example\": \"James\"\n          },\n          \"email\": {\n            \"type\": \"string\",\n            \"pattern\": \"^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\\\.[a-zA-Z]{2,}$\",\n            \"example\": \"john@email.com\"\n          },\n          \"password\": {\n            \"type\": \"string\",\n            \"example\": \"12345\",\n            \"pattern\": \"\"\n          },\n          \"phone\": {\n            \"type\": \"string\",\n            \"pattern\": \"^\\\\+?[1-9]\\\\d{1,14}$\",\n            \"example\": \"12345\"\n          },\n          \"website\": {\n            \"type\": \"string\",\n            \"pattern\": \"^https?://[^\\\\s]+$\",\n            \"example\": \"https://example.com\"\n          },\n          \"userStatus\": {\n            \"type\": \"integer\",\n            \"pattern\": \"^[1-9]\\\\d{0,2}$\",\n            \"description\": \"User Status\",\n            \"format\": \"int32\",\n            \"example\": 1\n          }\n        },\n        \"xml\": {\n          \"name\": \"user\"\n        }\n      },\n      \"Tag\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\"\n          },\n          \"name\": {\n            \"type\": \"string\",\n            \"pattern\": \"^\\\\S+$\"\n          }\n        },\n        \"xml\": {\n          \"name\": \"tag\"\n        }\n      },\n      \"Pet\": {\n        \"required\": [\"name\", \"photoUrls\"],\n        \"type\": \"object\",\n        \"properties\": {\n          \"id\": {\n            \"type\": \"integer\",\n            \"format\": \"int64\",\n            \"example\": 10\n          },\n          \"name\": {\n            \"type\": \"string\",\n            \"example\": \"doggie\"\n          },\n          \"category\": {\n            \"$ref\": \"#/components/schemas/Category\"\n          },\n          \"photoUrls\": {\n            \"type\": \"array\",\n            \"xml\": {\n              \"wrapped\": true\n            },\n            \"items\": {\n              \"type\": \"string\",\n              \"xml\": {\n                \"name\": \"photoUrl\"\n              }\n            }\n          },\n          \"tags\": {\n            \"type\": \"array\",\n            \"xml\": {\n              \"wrapped\": true\n            },\n            \"items\": {\n              \"$ref\": \"#/components/schemas/Tag\"\n            }\n          },\n          \"status\": {\n            \"type\": \"string\",\n            \"description\": \"pet status in the store\",\n            \"enum\": [\"available\", \"pending\", \"sold\"]\n          }\n        },\n        \"xml\": {\n          \"name\": \"pet\"\n        }\n      },\n      \"ApiResponse\": {\n        \"type\": \"object\",\n        \"properties\": {\n          \"code\": {\n            \"type\": \"integer\",\n            \"format\": \"int32\"\n          },\n          \"type\": {\n            \"type\": \"string\"\n          },\n          \"message\": {\n            \"type\": \"string\"\n          }\n        },\n        \"xml\": {\n          \"name\": \"##default\"\n        }\n      }\n    },\n    \"requestBodies\": {\n      \"Pet\": {\n        \"description\": \"Pet object that needs to be added to the store\",\n        \"content\": {\n          \"application/json\": {\n            \"schema\": {\n              \"$ref\": \"#/components/schemas/Pet\"\n            }\n          },\n          \"application/xml\": {\n            \"schema\": {\n              \"$ref\": \"#/components/schemas/Pet\"\n            }\n          }\n        }\n      },\n      \"UserArray\": {\n        \"description\": \"List of user object\",\n        \"content\": {\n          \"application/json\": {\n            \"schema\": {\n              \"type\": \"array\",\n              \"items\": {\n                \"$ref\": \"#/components/schemas/User\"\n              }\n            }\n          }\n        }\n      }\n    },\n    \"securitySchemes\": {\n      \"petstore_auth\": {\n        \"type\": \"oauth2\",\n        \"flows\": {\n          \"implicit\": {\n            \"authorizationUrl\": \"https://petstore3.swagger.io/oauth/authorize\",\n            \"scopes\": {\n              \"write:pets\": \"modify pets in your account\",\n              \"read:pets\": \"read your pets\"\n            }\n          }\n        }\n      },\n      \"api_key\": {\n        \"type\": \"apiKey\",\n        \"name\": \"api_key\",\n        \"in\": \"header\"\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/petstore.yaml",
    "content": "openapi: 3.0.2\ninfo:\n  title: Swagger Petstore - OpenAPI 3.0\n  description: \"This is a sample Pet Store Server based on the OpenAPI 3.0 specification.\\\n    \\  You can find out more about\\nSwagger at [http://swagger.io](http://swagger.io).\\\n    \\ In the third iteration of the pet store, we've switched to the design first\\\n    \\ approach!\\nYou can now help us improve the API whether it's by making changes\\\n    \\ to the definition itself or to the code.\\nThat way, with time, we can improve\\\n    \\ the API in general, and expose some of the new features in OAS3.\\n\\nSome useful\\\n    \\ links:\\n- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore)\\n\\\n    - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)\"\n  termsOfService: http://swagger.io/terms/\n  contact:\n    email: apiteam@swagger.io\n  license:\n    name: Apache 2.0\n    url: http://www.apache.org/licenses/LICENSE-2.0.html\n  version: 1.0.5\nexternalDocs:\n  description: Find out more about Swagger\n  url: http://swagger.io\nservers:\n  - url: /api/v3\ntags:\n  - name: pet\n    description: Everything about your Pets\n    externalDocs:\n      description: Find out more\n      url: http://swagger.io\n  - name: store\n    description: Operations about user\n  - name: user\n    description: Access to Petstore orders\n    externalDocs:\n      description: Find out more about our store\n      url: http://swagger.io\npaths:\n  /pet:\n    put:\n      tags:\n        - pet\n      summary: Update an existing pet\n      description: Update an existing pet by Id\n      operationId: updatePet\n      requestBody:\n        description: Update an existent pet in the store\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/Pet'\n          application/xml:\n            schema:\n              $ref: '#/components/schemas/Pet'\n          application/x-www-form-urlencoded:\n            schema:\n              $ref: '#/components/schemas/Pet'\n        required: true\n      responses:\n        '200':\n          description: Successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/Pet'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Pet'\n        '400':\n          description: Invalid ID supplied\n        '404':\n          description: Pet not found\n        '405':\n          description: Validation exception\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n    post:\n      tags:\n        - pet\n      summary: Add a new pet to the store\n      description: Add a new pet to the store\n      operationId: addPet\n      requestBody:\n        description: Create a new pet in the store\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/Pet'\n          application/xml:\n            schema:\n              $ref: '#/components/schemas/Pet'\n          application/x-www-form-urlencoded:\n            schema:\n              $ref: '#/components/schemas/Pet'\n        required: true\n      responses:\n        '200':\n          description: Successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/Pet'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Pet'\n        '405':\n          description: Invalid input\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n  /pet/findByStatus:\n    get:\n      tags:\n        - pet\n      summary: Finds Pets by status\n      description: Multiple status values can be provided with comma separated strings\n      operationId: findPetsByStatus\n      parameters:\n        - name: status\n          in: query\n          description: Status values that need to be considered for filter\n          required: false\n          explode: true\n          schema:\n            type: string\n            default: available\n            enum:\n              - available\n              - pending\n              - sold\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/xml:\n              schema:\n                type: array\n                items:\n                  $ref: '#/components/schemas/Pet'\n            application/json:\n              schema:\n                type: array\n                items:\n                  $ref: '#/components/schemas/Pet'\n        '400':\n          description: Invalid status value\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n  /pet/findByTags:\n    get:\n      tags:\n        - pet\n      summary: Finds Pets by tags\n      description: \"Multiple tags can be provided with comma separated strings. Use\\\n        \\ tag1, tag2, tag3 for testing.\"\n      operationId: findPetsByTags\n      parameters:\n        - name: tags\n          in: query\n          description: Tags to filter by\n          required: false\n          explode: true\n          schema:\n            type: array\n            items:\n              type: string\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/xml:\n              schema:\n                type: array\n                items:\n                  $ref: '#/components/schemas/Pet'\n            application/json:\n              schema:\n                type: array\n                items:\n                  $ref: '#/components/schemas/Pet'\n        '400':\n          description: Invalid tag value\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n  /pet/{petId}:\n    get:\n      tags:\n        - pet\n      summary: Find pet by ID\n      description: Returns a single pet\n      operationId: getPetById\n      parameters:\n        - name: petId\n          in: path\n          description: ID of pet to return\n          required: true\n          schema:\n            type: integer\n            format: int64\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/Pet'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Pet'\n        '400':\n          description: Invalid ID supplied\n        '404':\n          description: Pet not found\n      security:\n        - api_key: []\n        - petstore_auth:\n            - write:pets\n            - read:pets\n    post:\n      tags:\n        - pet\n      summary: Updates a pet in the store with form data\n      description: ''\n      operationId: updatePetWithForm\n      parameters:\n        - name: petId\n          in: path\n          description: ID of pet that needs to be updated\n          required: true\n          schema:\n            type: integer\n            format: int64\n        - name: name\n          in: query\n          description: Name of pet that needs to be updated\n          schema:\n            type: string\n        - name: status\n          in: query\n          description: Status of pet that needs to be updated\n          schema:\n            type: string\n      responses:\n        '405':\n          description: Invalid input\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n    delete:\n      tags:\n        - pet\n      summary: Deletes a pet\n      description: ''\n      operationId: deletePet\n      parameters:\n        - name: api_key\n          in: header\n          description: ''\n          required: false\n          schema:\n            type: string\n        - name: petId\n          in: path\n          description: Pet id to delete\n          required: true\n          schema:\n            type: integer\n            format: int64\n      responses:\n        '400':\n          description: Invalid pet value\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n  /pet/{petId}/uploadImage:\n    post:\n      tags:\n        - pet\n      summary: uploads an image\n      description: ''\n      operationId: uploadFile\n      parameters:\n        - name: petId\n          in: path\n          description: ID of pet to update\n          required: true\n          schema:\n            type: integer\n            format: int64\n        - name: additionalMetadata\n          in: query\n          description: Additional Metadata\n          required: false\n          schema:\n            type: string\n      requestBody:\n        content:\n          application/octet-stream:\n            schema:\n              type: string\n              format: binary\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/json:\n              schema:\n                $ref: '#/components/schemas/ApiResponse'\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n  /store/inventory:\n    get:\n      tags:\n        - store\n      summary: Returns pet inventories by status\n      description: Returns a map of status codes to quantities\n      operationId: getInventory\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/json:\n              schema:\n                type: object\n                additionalProperties:\n                  type: integer\n                  format: int32\n      security:\n        - api_key: []\n  /store/order:\n    post:\n      tags:\n        - store\n      summary: Place an order for a pet\n      description: Place a new order in the store\n      operationId: placeOrder\n      requestBody:\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/Order'\n          application/xml:\n            schema:\n              $ref: '#/components/schemas/Order'\n          application/x-www-form-urlencoded:\n            schema:\n              $ref: '#/components/schemas/Order'\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Order'\n        '405':\n          description: Invalid input\n  /store/order/{orderId}:\n    get:\n      tags:\n        - store\n      summary: Find purchase order by ID\n      description: For valid response try integer IDs with value <= 5 or > 10. Other\n        values will generated exceptions\n      operationId: getOrderById\n      parameters:\n        - name: orderId\n          in: path\n          description: ID of order that needs to be fetched\n          required: true\n          schema:\n            type: integer\n            format: int64\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/Order'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Order'\n        '400':\n          description: Invalid ID supplied\n        '404':\n          description: Order not found\n    delete:\n      tags:\n        - store\n      summary: Delete purchase order by ID\n      description: For valid response try integer IDs with value < 1000. Anything\n        above 1000 or nonintegers will generate API errors\n      operationId: deleteOrder\n      parameters:\n        - name: orderId\n          in: path\n          description: ID of the order that needs to be deleted\n          required: true\n          schema:\n            type: integer\n            format: int64\n      responses:\n        '400':\n          description: Invalid ID supplied\n        '404':\n          description: Order not found\n  /user:\n    post:\n      tags:\n        - user\n      summary: Create user\n      description: This can only be done by the logged in user.\n      operationId: createUser\n      requestBody:\n        description: Created user object\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/User'\n          application/xml:\n            schema:\n              $ref: '#/components/schemas/User'\n          application/x-www-form-urlencoded:\n            schema:\n              $ref: '#/components/schemas/User'\n      responses:\n        default:\n          description: successful operation\n          content:\n            application/json:\n              schema:\n                $ref: '#/components/schemas/User'\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/User'\n  /user/createWithList:\n    post:\n      tags:\n        - user\n      summary: Creates list of users with given input array\n      description: Creates list of users with given input array\n      operationId: createUsersWithListInput\n      requestBody:\n        content:\n          application/json:\n            schema:\n              type: array\n              items:\n                $ref: '#/components/schemas/User'\n      responses:\n        '200':\n          description: Successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/User'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/User'\n        default:\n          description: successful operation\n  /user/login:\n    get:\n      tags:\n        - user\n      summary: Logs user into the system\n      description: ''\n      operationId: loginUser\n      parameters:\n        - name: username\n          in: query\n          description: The user name for login\n          required: false\n          schema:\n            type: string\n        - name: password\n          in: query\n          description: The password for login in clear text\n          required: false\n          schema:\n            type: string\n      responses:\n        '200':\n          description: successful operation\n          headers:\n            X-Rate-Limit:\n              description: calls per hour allowed by the user\n              schema:\n                type: integer\n                format: int32\n            X-Expires-After:\n              description: date in UTC when toekn expires\n              schema:\n                type: string\n                format: date-time\n          content:\n            application/xml:\n              schema:\n                type: string\n            application/json:\n              schema:\n                type: string\n        '400':\n          description: Invalid username/password supplied\n  /user/logout:\n    get:\n      tags:\n        - user\n      summary: Logs out current logged in user session\n      description: ''\n      operationId: logoutUser\n      parameters: []\n      responses:\n        default:\n          description: successful operation\n  /user/{username}:\n    get:\n      tags:\n        - user\n      summary: Get user by user name\n      description: ''\n      operationId: getUserByName\n      parameters:\n        - name: username\n          in: path\n          description: 'The name that needs to be fetched. Use user1 for testing. '\n          required: true\n          schema:\n            type: string\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/User'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/User'\n        '400':\n          description: Invalid username supplied\n        '404':\n          description: User not found\n    put:\n      tags:\n        - user\n      summary: Update user\n      description: This can only be done by the logged in user.\n      operationId: updateUser\n      parameters:\n        - name: username\n          in: path\n          description: name that need to be deleted\n          required: true\n          schema:\n            type: string\n      requestBody:\n        description: Update an existent user in the store\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/User'\n          application/xml:\n            schema:\n              $ref: '#/components/schemas/User'\n          application/x-www-form-urlencoded:\n            schema:\n              $ref: '#/components/schemas/User'\n      responses:\n        default:\n          description: successful operation\n    delete:\n      tags:\n        - user\n      summary: Delete user\n      description: This can only be done by the logged in user.\n      operationId: deleteUser\n      parameters:\n        - name: username\n          in: path\n          description: The name that needs to be deleted\n          required: true\n          schema:\n            type: string\n      responses:\n        '400':\n          description: Invalid username supplied\n        '404':\n          description: User not found\ncomponents:\n  schemas:\n    Order:\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n          example: 10\n        petId:\n          type: integer\n          format: int64\n          example: 198772\n        quantity:\n          type: integer\n          format: int32\n          example: 7\n        shipDate:\n          type: string\n          format: date-time\n        status:\n          type: string\n          description: Order Status\n          example: approved\n          enum:\n            - placed\n            - approved\n            - delivered\n        complete:\n          type: boolean\n      xml:\n        name: order\n    Customer:\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n          example: 100000\n        username:\n          type: string\n          example: fehguy\n        address:\n          type: array\n          xml:\n            name: addresses\n            wrapped: true\n          items:\n            $ref: '#/components/schemas/Address'\n      xml:\n        name: customer\n    Address:\n      type: object\n      properties:\n        street:\n          type: string\n          example: 437 Lytton\n        city:\n          type: string\n          example: Palo Alto\n        state:\n          type: string\n          example: CA\n        zip:\n          type: string\n          example: '94301'\n      xml:\n        name: address\n    Category:\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n          example: 1\n        name:\n          type: string\n          example: Dogs\n      xml:\n        name: category\n    User:\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n          example: 10\n        username:\n          type: string\n          example: theUser\n        firstName:\n          type: string\n          example: John\n        lastName:\n          type: string\n          example: James\n        email:\n          type: string\n          pattern: '^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$'\n          example: john@email.com\n        password:\n          type: string\n          pattern: ''\n          example: '12345'\n        phone:\n          type: string\n          pattern: '^\\+?[1-9]\\d{1,14}$'\n          example: '12345'\n        website:\n          type: string\n          pattern: '^https?://[^\\s]+$'\n          example: 'https://example.com'\n        userStatus:\n          type: integer\n          pattern: '^[1-9]\\d{0,2}$'\n          description: User Status\n          format: int32\n          example: 1\n      xml:\n        name: user\n    Tag:\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n        name:\n          type: string\n          pattern: '^\\S+$'\n      xml:\n        name: tag\n    Pet:\n      required:\n        - name\n        - photoUrls\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n          example: 10\n        name:\n          type: string\n          example: doggie\n        category:\n          $ref: '#/components/schemas/Category'\n        photoUrls:\n          type: array\n          xml:\n            wrapped: true\n          items:\n            type: string\n            xml:\n              name: photoUrl\n        tags:\n          type: array\n          xml:\n            wrapped: true\n          items:\n            $ref: '#/components/schemas/Tag'\n        status:\n          type: string\n          description: pet status in the store\n          enum:\n            - available\n            - pending\n            - sold\n      xml:\n        name: pet\n    ApiResponse:\n      type: object\n      properties:\n        code:\n          type: integer\n          format: int32\n        type:\n          type: string\n        message:\n          type: string\n      xml:\n        name: '##default'\n  requestBodies:\n    Pet:\n      description: Pet object that needs to be added to the store\n      content:\n        application/json:\n          schema:\n            $ref: '#/components/schemas/Pet'\n        application/xml:\n          schema:\n            $ref: '#/components/schemas/Pet'\n    UserArray:\n      description: List of user object\n      content:\n        application/json:\n          schema:\n            type: array\n            items:\n              $ref: '#/components/schemas/User'\n  securitySchemes:\n    petstore_auth:\n      type: oauth2\n      flows:\n        implicit:\n          authorizationUrl: https://petstore3.swagger.io/oauth/authorize\n          scopes:\n            write:pets: modify pets in your account\n            read:pets: read your pets\n    api_key:\n      type: apiKey\n      name: api_key\n      in: header\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/petstore.yaml.mock.ts",
    "content": "export default `\nopenapi: 3.0.2\ninfo:\n  title: Swagger Petstore - OpenAPI 3.0\n  description: \"This is a sample Pet Store Server based on the OpenAPI 3.0 specification.\\\n    \\  You can find out more about\\nSwagger at [http://swagger.io](http://swagger.io).\\\n    \\ In the third iteration of the pet store, we've switched to the design first\\\n    \\ approach!\\nYou can now help us improve the API whether it's by making changes\\\n    \\ to the definition itself or to the code.\\nThat way, with time, we can improve\\\n    \\ the API in general, and expose some of the new features in OAS3.\\n\\nSome useful\\\n    \\ links:\\n- [The Pet Store repository](https://github.com/swagger-api/swagger-petstore)\\n\\\n    - [The source API definition for the Pet Store](https://github.com/swagger-api/swagger-petstore/blob/master/src/main/resources/openapi.yaml)\"\n  termsOfService: http://swagger.io/terms/\n  contact:\n    email: apiteam@swagger.io\n  license:\n    name: Apache 2.0\n    url: http://www.apache.org/licenses/LICENSE-2.0.html\n  version: 1.0.5\nexternalDocs:\n  description: Find out more about Swagger\n  url: http://swagger.io\nservers:\n  - url: /api/v3\ntags:\n  - name: pet\n    description: Everything about your Pets\n    externalDocs:\n      description: Find out more\n      url: http://swagger.io\n  - name: store\n    description: Operations about user\n  - name: user\n    description: Access to Petstore orders\n    externalDocs:\n      description: Find out more about our store\n      url: http://swagger.io\npaths:\n  /pet:\n    put:\n      tags:\n        - pet\n      summary: Update an existing pet\n      description: Update an existing pet by Id\n      operationId: updatePet\n      requestBody:\n        description: Update an existent pet in the store\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/Pet'\n          application/xml:\n            schema:\n              $ref: '#/components/schemas/Pet'\n          application/x-www-form-urlencoded:\n            schema:\n              $ref: '#/components/schemas/Pet'\n        required: true\n      responses:\n        '200':\n          description: Successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/Pet'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Pet'\n        '400':\n          description: Invalid ID supplied\n        '404':\n          description: Pet not found\n        '405':\n          description: Validation exception\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n    post:\n      tags:\n        - pet\n      summary: Add a new pet to the store\n      description: Add a new pet to the store\n      operationId: addPet\n      requestBody:\n        description: Create a new pet in the store\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/Pet'\n          application/xml:\n            schema:\n              $ref: '#/components/schemas/Pet'\n          application/x-www-form-urlencoded:\n            schema:\n              $ref: '#/components/schemas/Pet'\n        required: true\n      responses:\n        '200':\n          description: Successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/Pet'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Pet'\n        '405':\n          description: Invalid input\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n  /pet/findByStatus:\n    get:\n      tags:\n        - pet\n      summary: Finds Pets by status\n      description: Multiple status values can be provided with comma separated strings\n      operationId: findPetsByStatus\n      parameters:\n        - name: status\n          in: query\n          description: Status values that need to be considered for filter\n          required: false\n          explode: true\n          schema:\n            type: string\n            default: available\n            enum:\n              - available\n              - pending\n              - sold\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/xml:\n              schema:\n                type: array\n                items:\n                  $ref: '#/components/schemas/Pet'\n            application/json:\n              schema:\n                type: array\n                items:\n                  $ref: '#/components/schemas/Pet'\n        '400':\n          description: Invalid status value\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n  /pet/findByTags:\n    get:\n      tags:\n        - pet\n      summary: Finds Pets by tags\n      description: \"Multiple tags can be provided with comma separated strings. Use\\\n        \\ tag1, tag2, tag3 for testing.\"\n      operationId: findPetsByTags\n      parameters:\n        - name: tags\n          in: query\n          description: Tags to filter by\n          required: false\n          explode: true\n          schema:\n            type: array\n            items:\n              type: string\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/xml:\n              schema:\n                type: array\n                items:\n                  $ref: '#/components/schemas/Pet'\n            application/json:\n              schema:\n                type: array\n                items:\n                  $ref: '#/components/schemas/Pet'\n        '400':\n          description: Invalid tag value\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n  /pet/{petId}:\n    get:\n      tags:\n        - pet\n      summary: Find pet by ID\n      description: Returns a single pet\n      operationId: getPetById\n      parameters:\n        - name: petId\n          in: path\n          description: ID of pet to return\n          required: true\n          schema:\n            type: integer\n            format: int64\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/Pet'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Pet'\n        '400':\n          description: Invalid ID supplied\n        '404':\n          description: Pet not found\n      security:\n        - api_key: []\n        - petstore_auth:\n            - write:pets\n            - read:pets\n    post:\n      tags:\n        - pet\n      summary: Updates a pet in the store with form data\n      description: ''\n      operationId: updatePetWithForm\n      parameters:\n        - name: petId\n          in: path\n          description: ID of pet that needs to be updated\n          required: true\n          schema:\n            type: integer\n            format: int64\n        - name: name\n          in: query\n          description: Name of pet that needs to be updated\n          schema:\n            type: string\n        - name: status\n          in: query\n          description: Status of pet that needs to be updated\n          schema:\n            type: string\n      responses:\n        '405':\n          description: Invalid input\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n    delete:\n      tags:\n        - pet\n      summary: Deletes a pet\n      description: ''\n      operationId: deletePet\n      parameters:\n        - name: api_key\n          in: header\n          description: ''\n          required: false\n          schema:\n            type: string\n        - name: petId\n          in: path\n          description: Pet id to delete\n          required: true\n          schema:\n            type: integer\n            format: int64\n      responses:\n        '400':\n          description: Invalid pet value\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n  /pet/{petId}/uploadImage:\n    post:\n      tags:\n        - pet\n      summary: uploads an image\n      description: ''\n      operationId: uploadFile\n      parameters:\n        - name: petId\n          in: path\n          description: ID of pet to update\n          required: true\n          schema:\n            type: integer\n            format: int64\n        - name: additionalMetadata\n          in: query\n          description: Additional Metadata\n          required: false\n          schema:\n            type: string\n      requestBody:\n        content:\n          application/octet-stream:\n            schema:\n              type: string\n              format: binary\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/json:\n              schema:\n                $ref: '#/components/schemas/ApiResponse'\n      security:\n        - petstore_auth:\n            - write:pets\n            - read:pets\n  /store/inventory:\n    get:\n      tags:\n        - store\n      summary: Returns pet inventories by status\n      description: Returns a map of status codes to quantities\n      operationId: getInventory\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/json:\n              schema:\n                type: object\n                additionalProperties:\n                  type: integer\n                  format: int32\n      security:\n        - api_key: []\n  /store/order:\n    post:\n      tags:\n        - store\n      summary: Place an order for a pet\n      description: Place a new order in the store\n      operationId: placeOrder\n      requestBody:\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/Order'\n          application/xml:\n            schema:\n              $ref: '#/components/schemas/Order'\n          application/x-www-form-urlencoded:\n            schema:\n              $ref: '#/components/schemas/Order'\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Order'\n        '405':\n          description: Invalid input\n  /store/order/{orderId}:\n    get:\n      tags:\n        - store\n      summary: Find purchase order by ID\n      description: For valid response try integer IDs with value <= 5 or > 10. Other\n        values will generated exceptions\n      operationId: getOrderById\n      parameters:\n        - name: orderId\n          in: path\n          description: ID of order that needs to be fetched\n          required: true\n          schema:\n            type: integer\n            format: int64\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/Order'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/Order'\n        '400':\n          description: Invalid ID supplied\n        '404':\n          description: Order not found\n    delete:\n      tags:\n        - store\n      summary: Delete purchase order by ID\n      description: For valid response try integer IDs with value < 1000. Anything\n        above 1000 or nonintegers will generate API errors\n      operationId: deleteOrder\n      parameters:\n        - name: orderId\n          in: path\n          description: ID of the order that needs to be deleted\n          required: true\n          schema:\n            type: integer\n            format: int64\n      responses:\n        '400':\n          description: Invalid ID supplied\n        '404':\n          description: Order not found\n  /user:\n    post:\n      tags:\n        - user\n      summary: Create user\n      description: This can only be done by the logged in user.\n      operationId: createUser\n      requestBody:\n        description: Created user object\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/User'\n          application/xml:\n            schema:\n              $ref: '#/components/schemas/User'\n          application/x-www-form-urlencoded:\n            schema:\n              $ref: '#/components/schemas/User'\n      responses:\n        default:\n          description: successful operation\n          content:\n            application/json:\n              schema:\n                $ref: '#/components/schemas/User'\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/User'\n  /user/createWithList:\n    post:\n      tags:\n        - user\n      summary: Creates list of users with given input array\n      description: Creates list of users with given input array\n      operationId: createUsersWithListInput\n      requestBody:\n        content:\n          application/json:\n            schema:\n              type: array\n              items:\n                $ref: '#/components/schemas/User'\n      responses:\n        '200':\n          description: Successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/User'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/User'\n        default:\n          description: successful operation\n  /user/login:\n    get:\n      tags:\n        - user\n      summary: Logs user into the system\n      description: ''\n      operationId: loginUser\n      parameters:\n        - name: username\n          in: query\n          description: The user name for login\n          required: false\n          schema:\n            type: string\n        - name: password\n          in: query\n          description: The password for login in clear text\n          required: false\n          schema:\n            type: string\n      responses:\n        '200':\n          description: successful operation\n          headers:\n            X-Rate-Limit:\n              description: calls per hour allowed by the user\n              schema:\n                type: integer\n                format: int32\n            X-Expires-After:\n              description: date in UTC when toekn expires\n              schema:\n                type: string\n                format: date-time\n          content:\n            application/xml:\n              schema:\n                type: string\n            application/json:\n              schema:\n                type: string\n        '400':\n          description: Invalid username/password supplied\n  /user/logout:\n    get:\n      tags:\n        - user\n      summary: Logs out current logged in user session\n      description: ''\n      operationId: logoutUser\n      parameters: []\n      responses:\n        default:\n          description: successful operation\n  /user/{username}:\n    get:\n      tags:\n        - user\n      summary: Get user by user name\n      description: ''\n      operationId: getUserByName\n      parameters:\n        - name: username\n          in: path\n          description: 'The name that needs to be fetched. Use user1 for testing. '\n          required: true\n          schema:\n            type: string\n      responses:\n        '200':\n          description: successful operation\n          content:\n            application/xml:\n              schema:\n                $ref: '#/components/schemas/User'\n            application/json:\n              schema:\n                $ref: '#/components/schemas/User'\n        '400':\n          description: Invalid username supplied\n        '404':\n          description: User not found\n    put:\n      tags:\n        - user\n      summary: Update user\n      description: This can only be done by the logged in user.\n      operationId: updateUser\n      parameters:\n        - name: username\n          in: path\n          description: name that need to be deleted\n          required: true\n          schema:\n            type: string\n      requestBody:\n        description: Update an existent user in the store\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/User'\n          application/xml:\n            schema:\n              $ref: '#/components/schemas/User'\n          application/x-www-form-urlencoded:\n            schema:\n              $ref: '#/components/schemas/User'\n      responses:\n        default:\n          description: successful operation\n    delete:\n      tags:\n        - user\n      summary: Delete user\n      description: This can only be done by the logged in user.\n      operationId: deleteUser\n      parameters:\n        - name: username\n          in: path\n          description: The name that needs to be deleted\n          required: true\n          schema:\n            type: string\n      responses:\n        '400':\n          description: Invalid username supplied\n        '404':\n          description: User not found\ncomponents:\n  schemas:\n    Order:\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n          example: 10\n        petId:\n          type: integer\n          format: int64\n          example: 198772\n        quantity:\n          type: integer\n          format: int32\n          example: 7\n        shipDate:\n          type: string\n          format: date-time\n        status:\n          type: string\n          description: Order Status\n          example: approved\n          enum:\n            - placed\n            - approved\n            - delivered\n        complete:\n          type: boolean\n      xml:\n        name: order\n    Customer:\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n          example: 100000\n        username:\n          type: string\n          example: fehguy\n        address:\n          type: array\n          xml:\n            name: addresses\n            wrapped: true\n          items:\n            $ref: '#/components/schemas/Address'\n      xml:\n        name: customer\n    Address:\n      type: object\n      properties:\n        street:\n          type: string\n          example: 437 Lytton\n        city:\n          type: string\n          example: Palo Alto\n        state:\n          type: string\n          example: CA\n        zip:\n          type: string\n          example: '94301'\n      xml:\n        name: address\n    Category:\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n          example: 1\n        name:\n          type: string\n          example: Dogs\n      xml:\n        name: category\n    User:\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n          example: 10\n        username:\n          type: string\n          example: theUser\n        firstName:\n          type: string\n          example: John\n        lastName:\n          type: string\n          example: James\n        email:\n          type: string\n          example: john@email.com\n        password:\n          type: string\n          example: '12345'\n        phone:\n          type: string\n          example: '12345'\n        userStatus:\n          type: integer\n          description: User Status\n          format: int32\n          example: 1\n      xml:\n        name: user\n    Tag:\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n        name:\n          type: string\n      xml:\n        name: tag\n    Pet:\n      required:\n        - name\n        - photoUrls\n      type: object\n      properties:\n        id:\n          type: integer\n          format: int64\n          example: 10\n        name:\n          type: string\n          example: doggie\n        category:\n          $ref: '#/components/schemas/Category'\n        photoUrls:\n          type: array\n          xml:\n            wrapped: true\n          items:\n            type: string\n            xml:\n              name: photoUrl\n        tags:\n          type: array\n          xml:\n            wrapped: true\n          items:\n            $ref: '#/components/schemas/Tag'\n        status:\n          type: string\n          description: pet status in the store\n          enum:\n            - available\n            - pending\n            - sold\n      xml:\n        name: pet\n    ApiResponse:\n      type: object\n      properties:\n        code:\n          type: integer\n          format: int32\n        type:\n          type: string\n        message:\n          type: string\n      xml:\n        name: '##default'\n  requestBodies:\n    Pet:\n      description: Pet object that needs to be added to the store\n      content:\n        application/json:\n          schema:\n            $ref: '#/components/schemas/Pet'\n        application/xml:\n          schema:\n            $ref: '#/components/schemas/Pet'\n    UserArray:\n      description: List of user object\n      content:\n        application/json:\n          schema:\n            type: array\n            items:\n              $ref: '#/components/schemas/User'\n  securitySchemes:\n    petstore_auth:\n      type: oauth2\n      flows:\n        implicit:\n          authorizationUrl: https://petstore3.swagger.io/oauth/authorize\n          scopes:\n            write:pets: modify pets in your account\n            read:pets: read your pets\n    api_key:\n      type: apiKey\n      name: api_key\n      in: header\n`;\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/readOnlyWriteOnly.yaml",
    "content": "openapi: 3.0.2\ninfo:\n  title: readOnlyWriteOnlyAPI\n  version: 1.0.0\npaths:\n  /example:\n    get:\n      responses:\n        '200':\n          content:\n            application/json:\n              schema:\n                $ref: '#/components/schemas/ExampleSchema'\n          description: OK\n      operationId: getExample\n    post:\n      requestBody:\n        content:\n          application/json:\n            schema:\n              $ref: '#/components/schemas/ExampleSchema'\n        required: true\n      responses:\n        '200':\n          content:\n            application/json:\n              schema:\n                $ref: '#/components/schemas/ExampleSchema'\n          description: OK\n      operationId: setExample\ncomponents:\n  schemas:\n    ExampleSchema:\n      description: ''\n      required:\n        - always_present\n        - read_only_prop\n        - write_only_prop\n      type: object\n      properties:\n        always_present:\n          description: ''\n          type: string\n        read_only_prop:\n          description: ''\n          type: string\n          readOnly: true\n        write_only_prop:\n          writeOnly: true\n          description: ''\n          type: string\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/fixtures/title-as-param-name.json",
    "content": "{\n  \"openapi\": \"3.0.2\",\n  \"info\": {\n    \"title\": \"Title as param name\",\n    \"version\": \"0.1\"\n  },\n  \"paths\": {\n    \"/v1/export\": {\n      \"post\": {\n        \"requestBody\": {\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"title\": \"exportedEntityIds\",\n                \"anyOf\": [\n                  {\n                    \"$ref\": \"#/components/schemas/IdList\"\n                  }\n                ]\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"OK\"\n          }\n        }\n      }\n    },\n    \"/v1/import\": {\n      \"post\": {\n        \"requestBody\": {\n          \"content\": {\n            \"application/json\": {\n              \"schema\": {\n                \"title\": \"rawData\",\n                \"type\": \"string\"\n              }\n            }\n          }\n        },\n        \"responses\": {\n          \"200\": {\n            \"description\": \"OK\"\n          }\n        }\n      }\n    }\n  },\n  \"components\": {\n    \"schemas\": {\n      \"IdList\": {\n        \"type\": \"array\",\n        \"items\": {\n          \"type\": \"number\"\n        }\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/generateEndpoints.test.ts",
    "content": "import { generateEndpoints } from '@rtk-query/codegen-openapi';\nimport fs from 'node:fs/promises';\nimport path, { resolve } from 'node:path';\nimport { rimraf } from 'rimraf';\nimport { isDir, removeTempDir } from './cli.test';\n\nconst tmpDir = path.resolve(__dirname, 'tmp');\n\nbeforeAll(async () => {\n  if (!(await isDir(tmpDir))) {\n    await fs.mkdir(tmpDir, { recursive: true });\n  }\n  return removeTempDir;\n});\n\nafterEach(async () => {\n  await rimraf(`${tmpDir}/*.ts`, { glob: true });\n});\n\ntest('calling without `outputFile` returns the generated api', async () => {\n  const api = await generateEndpoints({\n    unionUndefined: true,\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n  });\n  expect(api).toMatchSnapshot();\n});\n\ntest('should include default response type in request when includeDefault is set to true', async () => {\n  const api = await generateEndpoints({\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    includeDefault: true,\n  });\n  // eslint-disable-next-line no-template-curly-in-string\n  expect(api).toMatch(/export type CreateUserApiResponse =[\\s\\S/*]+status default successful operation[\\s/*]+User;/);\n});\n\ntest('endpoint filtering', async () => {\n  const api = await generateEndpoints({\n    unionUndefined: true,\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    filterEndpoints: ['loginUser', /Order/],\n  });\n  expect(api).toMatchSnapshot('should only have endpoints loginUser, placeOrder, getOrderById, deleteOrder');\n});\n\ntest('endpoint filtering by function', async () => {\n  const api = await generateEndpoints({\n    unionUndefined: true,\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    filterEndpoints: (name, endpoint) => name.match(/order/i) !== null && endpoint.verb === 'get',\n  });\n  expect(api).toMatch(/getOrderById:/);\n  expect(api).not.toMatch(/placeOrder:/);\n  expect(api).not.toMatch(/loginUser:/);\n});\n\ntest('negated endpoint filtering', async () => {\n  const api = await generateEndpoints({\n    unionUndefined: true,\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    filterEndpoints: (name) => !/user/i.test(name),\n  });\n  expect(api).not.toMatch(/loginUser:/);\n});\n\ndescribe('endpoint overrides', () => {\n  it('overrides endpoint type', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: 'loginUser',\n      endpointOverrides: [\n        {\n          pattern: 'loginUser',\n          type: 'mutation',\n        },\n      ],\n    });\n    expect(api).not.toMatch(/loginUser: build.query/);\n    expect(api).toMatch(/loginUser: build.mutation/);\n    expect(api).toMatchSnapshot('loginUser should be a mutation');\n  });\n\n  it('should override parameters by string', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      endpointOverrides: [\n        {\n          pattern: /.*/,\n          parameterFilter: 'status',\n        },\n      ],\n    });\n    expect(api).not.toMatch(/params: {\\n.*queryArg\\.\\w+\\b(?<!\\bstatus)/);\n    expect(api).toMatchSnapshot('should only have the \"status\" parameter from the endpoints');\n  });\n\n  it('should override parameters by regex', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      endpointOverrides: [\n        {\n          pattern: /.*/,\n          parameterFilter: /e/,\n        },\n      ],\n    });\n    expect(api).not.toMatch(/params: {\\n.*queryArg\\.[^\\We]*\\W/);\n    expect(api).toMatch(/params: {\\n.*queryArg\\.[\\we]*\\W/);\n    expect(api).toMatchSnapshot('should only have the parameters with an \"e\"');\n  });\n\n  it('should filter by array of parameter strings / regex', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      endpointOverrides: [\n        {\n          pattern: /.*/,\n          parameterFilter: [/e/, /f/],\n        },\n      ],\n    });\n    expect(api).not.toMatch(/params: {\\n.*queryArg\\.[^\\Wef]*\\W/);\n    expect(api).toMatch(/params: {\\n.*queryArg\\.[\\wef]*\\W/);\n    expect(api).toMatchSnapshot('should only have the parameters with an \"e\" or \"f\"');\n  });\n\n  it('should filter by function', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      endpointOverrides: [\n        {\n          pattern: /.*/,\n          parameterFilter: (_, param) => !(param.in === 'header'),\n        },\n      ],\n    });\n    expect(api).not.toMatch(/headers: {/);\n    expect(api).toMatchSnapshot('should remove any parameters from the header');\n  });\n\n  it('should apply first matching filter only', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      endpointOverrides: [\n        { pattern: 'findPetsByStatus', parameterFilter: () => true },\n        {\n          pattern: /.*/,\n          parameterFilter: () => false,\n        },\n      ],\n    });\n\n    const paramsMatches = (api?.match(/params:/) || []).length;\n    expect(paramsMatches).toBe(1);\n    expect(api).not.toMatch(/headers: {/);\n    expect(api).toMatchSnapshot('should remove all parameters except for findPetsByStatus');\n  });\n\n  it('should override generated tags', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      tag: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: ['getPetById', 'deletePet'],\n      endpointOverrides: [\n        {\n          pattern: 'getPetById',\n          providesTags: ['CustomQueryTag'],\n        },\n        {\n          pattern: 'deletePet',\n          invalidatesTags: [],\n        },\n      ],\n    });\n\n    expect(api).toMatch(/getPetById: build\\.query[\\s\\S]*providesTags: \\[\"CustomQueryTag\"\\]/);\n    expect(api).not.toMatch(/getPetById: build\\.query[\\s\\S]*providesTags: \\[\"pet\"\\]/);\n    expect(api).toMatch(/deletePet: build\\.mutation[\\s\\S]*invalidatesTags: \\[\\]/);\n    expect(api).not.toMatch(/deletePet: build\\.mutation[\\s\\S]*invalidatesTags: \\[\"pet\"\\]/);\n  });\n\n  it('should allow tag overrides when tag generation is disabled', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: ['getPetById', 'deletePet'],\n      endpointOverrides: [\n        {\n          pattern: 'getPetById',\n          providesTags: ['ManualProvides'],\n        },\n        {\n          pattern: 'deletePet',\n          invalidatesTags: ['ManualInvalidates'],\n        },\n      ],\n    });\n\n    expect(api).toMatch(/getPetById: build\\.query[\\s\\S]*providesTags: \\[\"ManualProvides\"\\]/);\n    expect(api).toMatch(/deletePet: build\\.mutation[\\s\\S]*invalidatesTags: \\[\"ManualInvalidates\"\\]/);\n    expect(api).not.toMatch(/providesTags: \\[\\]/);\n    expect(api).not.toMatch(/invalidatesTags: \\[\\]/);\n  });\n\n  it('allows overriding tags regardless of inferred endpoint type', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: 'loginUser',\n      endpointOverrides: [\n        {\n          pattern: 'loginUser',\n          type: 'mutation',\n          providesTags: ['LoginStatus'],\n        },\n      ],\n    });\n\n    expect(api).toMatch(/loginUser: build\\.mutation/);\n    expect(api).toMatch(/providesTags: \\[\"LoginStatus\"\\]/);\n    expect(api).not.toMatch(/invalidatesTags:/);\n  });\n\n  it('allows overriding both providesTags and invalidatesTags simultaneously', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      tag: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: 'findPetsByStatus',\n      endpointOverrides: [\n        {\n          pattern: 'findPetsByStatus',\n          providesTags: ['CustomProvide'],\n          invalidatesTags: ['CustomInvalidate'],\n        },\n      ],\n    });\n\n    expect(api).toMatch(/findPetsByStatus: build\\.query/);\n    expect(api).toMatch(/providesTags: \\[\"CustomProvide\"\\]/);\n    expect(api).toMatch(/invalidatesTags: \\[\"CustomInvalidate\"\\]/);\n    expect(api).not.toMatch(/providesTags: \\[\"pet\"\\]/);\n    expect(api).not.toMatch(/invalidatesTags: \\[\"pet\"\\]/);\n  });\n\n  it('does not add override tags to addTagTypes when tag generation is disabled', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: 'getPetById',\n      endpointOverrides: [\n        {\n          pattern: 'getPetById',\n          providesTags: ['CustomTag'],\n        },\n      ],\n    });\n\n    // The providesTags override should be present in the generated code\n    expect(api).toMatch(/providesTags: \\[\"CustomTag\"\\]/);\n    // But addTagTypes should not be generated when tag: false (default)\n    expect(api).not.toContain('addTagTypes');\n  });\n});\n\ndescribe('option encodePathParams', () => {\n  const config = {\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    encodePathParams: true,\n  };\n\n  it('should encode path parameters', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: ['getOrderById'],\n    });\n    // eslint-disable-next-line no-template-curly-in-string\n    expect(api).toContain('`/store/order/${encodeURIComponent(String(queryArg.orderId))}`');\n  });\n\n  it('should not encode query parameters', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: ['findPetsByStatus'],\n    });\n    expect(api).toContain('status: queryArg.status');\n  });\n\n  it('should not encode body parameters', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: ['addPet'],\n    });\n    expect(api).toContain('body: queryArg.pet');\n    expect(api).not.toContain('body: encodeURIComponent(String(queryArg.pet))');\n  });\n\n  it('should work correctly with flattenArg option', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      flattenArg: true,\n      filterEndpoints: ['getOrderById'],\n    });\n    // eslint-disable-next-line no-template-curly-in-string\n    expect(api).toContain('`/store/order/${encodeURIComponent(String(queryArg))}`');\n  });\n\n  it('should not encode path parameters when encodePathParams is false', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      encodePathParams: false,\n      filterEndpoints: ['findPetsByStatus', 'getOrderById'],\n    });\n    // eslint-disable-next-line no-template-curly-in-string\n    expect(api).toContain('`/store/order/${queryArg.orderId}`');\n  });\n});\n\ndescribe('option encodeQueryParams', () => {\n  const config = {\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    encodeQueryParams: true,\n  };\n\n  it('should conditionally encode query parameters', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: ['findPetsByStatus'],\n    });\n\n    expect(api).toMatch(\n      /params:\\s*{\\s*\\n\\s*status:\\s*queryArg\\.status\\s*!=\\s*null\\s*\\?\\s*encodeURIComponent\\(\\s*String\\(queryArg\\.status\\)\\s*\\)\\s*:\\s*undefined\\s*,?\\s*\\n\\s*}/s\n    );\n  });\n\n  it('should not encode path parameters', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: ['getOrderById'],\n    });\n    // eslint-disable-next-line no-template-curly-in-string\n    expect(api).toContain('`/store/order/${queryArg.orderId}`');\n  });\n\n  it('should not encode body parameters', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: ['addPet'],\n    });\n    expect(api).toContain('body: queryArg.pet');\n    expect(api).not.toContain('body: encodeURIComponent(String(queryArg.pet))');\n  });\n\n  it('should not encode query parameters when encodeQueryParams is false', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      encodeQueryParams: false,\n      filterEndpoints: ['findPetsByStatus', 'getOrderById'],\n    });\n    expect(api).toContain('status: queryArg.status');\n  });\n});\n\ndescribe('option flattenArg', () => {\n  const config = {\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    flattenArg: true,\n  };\n\n  it('should apply a queryArg directly in the path', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: ['getOrderById'],\n    });\n    // eslint-disable-next-line no-template-curly-in-string\n    expect(api).toContain('`/store/order/${queryArg}`');\n    expect(api).toMatch(/export type GetOrderByIdApiArg =[\\s/*]+ID of order that needs to be fetched[\\s/*]+number;/);\n  });\n\n  it('should apply a queryArg directly in the params', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: ['findPetsByStatus'],\n    });\n    expect(api).toContain('status: queryArg');\n    expect(api).not.toContain('export type FindPetsByStatusApiArg = {');\n  });\n\n  it('should use the queryArg as the entire body', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: ['addPet'],\n    });\n    expect(api).toMatch(/body: queryArg[^.]/);\n  });\n\n  it('should not change anything if there are 2+ arguments.', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: ['uploadFile'],\n    });\n    expect(api).toContain('queryArg.body');\n  });\n\n  it('should flatten an optional arg as an optional type', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: 'findPetsByTags',\n    });\n    expect(api).toMatch(/\\| undefined/);\n  });\n\n  it('should not flatten a non-optional arg with a superfluous union', async () => {\n    const api = await generateEndpoints({\n      ...config,\n      filterEndpoints: 'getPetById',\n    });\n    expect(api).not.toMatch(/^\\s*\\|/);\n  });\n});\n\ntest('hooks generation', async () => {\n  const api = await generateEndpoints({\n    unionUndefined: true,\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    filterEndpoints: ['getPetById', 'addPet'],\n    hooks: true,\n  });\n  expect(api).toContain('useGetPetByIdQuery');\n  expect(api).toContain('useAddPetMutation');\n  expect(api).toMatchSnapshot(\n    'should generate an `useGetPetByIdQuery` query hook and an `useAddPetMutation` mutation hook'\n  );\n});\n\ntest('hooks generation with operationNameSuffix', async () => {\n  const api = await generateEndpoints({\n    unionUndefined: true,\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    filterEndpoints: ['getPetById', 'addPet'],\n    hooks: true,\n    operationNameSuffix: 'MySuffix',\n  });\n  expect(api).toContain('useGetPetByIdMySuffixQuery');\n  expect(api).toContain('useAddPetMySuffixMutation');\n  expect(api).toMatchSnapshot(\n    'should generate an `useGetPetByIdMySuffixQuery` query hook and an `useAddPetMySuffixMutation` mutation hook'\n  );\n});\n\nit('supports granular hooks generation that includes all query types', async () => {\n  const api = await generateEndpoints({\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    filterEndpoints: ['getPetById', 'addPet'],\n    hooks: {\n      queries: true,\n      lazyQueries: true,\n      mutations: true,\n    },\n  });\n  expect(api).toContain('useGetPetByIdQuery');\n  expect(api).toContain('useLazyGetPetByIdQuery');\n  expect(api).toContain('useAddPetMutation');\n  expect(api).toMatchSnapshot();\n});\n\nit('supports granular hooks generation with only queries', async () => {\n  const api = await generateEndpoints({\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    filterEndpoints: ['getPetById', 'addPet'],\n    hooks: {\n      queries: true,\n      lazyQueries: false,\n      mutations: false,\n    },\n  });\n  expect(api).toContain('useGetPetByIdQuery');\n  expect(api).not.toContain('useLazyGetPetByIdQuery');\n  expect(api).not.toContain('useAddPetMutation');\n  expect(api).toMatchSnapshot();\n});\n\nit('supports granular hooks generation with only lazy queries', async () => {\n  const api = await generateEndpoints({\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    filterEndpoints: ['getPetById', 'addPet'],\n    hooks: {\n      queries: false,\n      lazyQueries: true,\n      mutations: false,\n    },\n  });\n  expect(api).not.toContain('useGetPetByIdQuery');\n  expect(api).toContain('useLazyGetPetByIdQuery');\n  expect(api).not.toContain('useAddPetMutation');\n  expect(api).toMatchSnapshot();\n});\n\nit('supports granular hooks generation with only mutations', async () => {\n  const api = await generateEndpoints({\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    filterEndpoints: ['getPetById', 'addPet'],\n    hooks: {\n      queries: false,\n      lazyQueries: false,\n      mutations: true,\n    },\n  });\n  expect(api).not.toContain('useGetPetByIdQuery');\n  expect(api).not.toContain('useLazyGetPetByIdQuery');\n  expect(api).toContain('useAddPetMutation');\n  expect(api).toMatchSnapshot();\n});\n\nit('falls back to the `title` parameter for the body parameter name when no other name is available', async () => {\n  const api = await generateEndpoints({\n    apiFile: 'fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/title-as-param-name.json'),\n  });\n  expect(api).not.toContain('queryArg.body');\n  expect(api).toContain('queryArg.exportedEntityIds');\n  expect(api).toContain('queryArg.rawData');\n  expect(api).toMatchSnapshot();\n});\n\ntest('hooks generation uses overrides', async () => {\n  const api = await generateEndpoints({\n    unionUndefined: true,\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    filterEndpoints: 'loginUser',\n    endpointOverrides: [\n      {\n        pattern: 'loginUser',\n        type: 'mutation',\n      },\n    ],\n    hooks: true,\n  });\n  expect(api).not.toContain('useLoginUserQuery');\n  expect(api).toContain('useLoginUserMutation');\n  expect(api).toMatchSnapshot('should generate an `useLoginMutation` mutation hook');\n});\n\ntest('should use brackets in a querystring urls arg, when the arg contains full stops', async () => {\n  const api = await generateEndpoints({\n    unionUndefined: true,\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/params.json'),\n  });\n  // eslint-disable-next-line no-template-curly-in-string\n  expect(api).toContain('`/api/v1/list/${queryArg[\"item.id\"]}`');\n  expect(api).toMatchSnapshot();\n});\n\ntest('duplicate parameter names must be prefixed with a path or query prefix', async () => {\n  const api = await generateEndpoints({\n    unionUndefined: true,\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/params.json'),\n  });\n  // eslint-disable-next-line no-template-curly-in-string\n  expect(api).toContain('pathSomeName: string');\n  expect(api).toContain('querySomeName: string');\n  expect(api).toMatchSnapshot();\n});\n\ntest('operation suffixes are applied', async () => {\n  const api = await generateEndpoints({\n    unionUndefined: true,\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n    operationNameSuffix: 'V2',\n  });\n\n  expect(api).toContain('AddPetV2');\n  expect(api).toMatchSnapshot();\n});\n\ntest('apiImport builds correct `import` statement', async () => {\n  const api = await generateEndpoints({\n    unionUndefined: true,\n    apiFile: './fixtures/emptyApi.ts',\n    schemaFile: resolve(__dirname, 'fixtures/params.json'),\n    filterEndpoints: [],\n    apiImport: 'myApi',\n  });\n  expect(api).toContain('myApi as api');\n});\n\ndescribe('import paths', () => {\n  beforeAll(async () => {\n    if (!(await isDir(tmpDir))) {\n      await fs.mkdir(tmpDir, { recursive: true });\n    }\n  });\n\n  afterEach(async () => {\n    await rimraf(`${tmpDir}/*.ts`, { glob: true });\n  });\n\n  test('should create paths relative to `outFile` when `apiFile` is relative (different folder)', async () => {\n    await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      outputFile: './test/tmp/out.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: [],\n      hooks: true,\n      tag: true,\n    });\n    expect(await fs.readFile('./test/tmp/out.ts', 'utf8')).toContain(\"import { api } from '../../fixtures/emptyApi'\");\n  });\n\n  test('should create paths relative to `outFile` when `apiFile` is relative (same folder)', async () => {\n    await fs.writeFile('./test/tmp/emptyApi.ts', await fs.readFile('./test/fixtures/emptyApi.ts', 'utf8'));\n\n    await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './test/tmp/emptyApi.ts',\n      outputFile: './test/tmp/out.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: [],\n      hooks: true,\n      tag: true,\n    });\n    expect(await fs.readFile('./test/tmp/out.ts', 'utf8')).toContain(\"import { api } from './emptyApi'\");\n  });\n});\n\ndescribe('yaml parsing', () => {\n  it('should parse a yaml schema from a URL', async () => {\n    const result = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './tmp/emptyApi.ts',\n      schemaFile: 'https://petstore3.swagger.io/api/v3/openapi.yaml',\n      hooks: true,\n      tag: true,\n    });\n    expect(result).toMatchSnapshot();\n  });\n\n  it('should be able to use read a yaml file', async () => {\n    const result = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './tmp/emptyApi.ts',\n      schemaFile: `./test/fixtures/petstore.yaml`,\n      hooks: true,\n      tag: true,\n    });\n    expect(result).toMatchSnapshot();\n  });\n\n  it(\"should generate params with non quoted keys if they don't contain special characters\", async () => {\n    const output = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './tmp/emptyApi.ts',\n      schemaFile: './test/fixtures/fhir.yaml',\n      hooks: true,\n      tag: true,\n    });\n\n    expect(output).toMatchSnapshot();\n\n    expect(output).toContain('foo: queryArg.foo,');\n    expect(output).toContain('_foo: queryArg._foo,');\n    expect(output).toContain('_bar_bar: queryArg._bar_bar,');\n    expect(output).toContain('foo_bar: queryArg.fooBar,');\n    expect(output).toContain('namingConflict: queryArg.namingConflict,');\n    expect(output).toContain('naming_conflict: queryArg.naming_conflict,');\n  });\n\n  it('should generate params with quoted keys if they contain special characters', async () => {\n    const output = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './tmp/emptyApi.ts',\n      schemaFile: './test/fixtures/fhir.yaml',\n      hooks: true,\n      tag: true,\n    });\n\n    expect(output).toContain('\"-bar-bar\": queryArg[\"-bar-bar\"],');\n    expect(output).toContain('\"foo:bar-foo.bar/foo\": queryArg[\"foo:bar-foo.bar/foo\"],');\n  });\n});\n\ndescribe('tests from issues', () => {\n  it('issue #2002: should be able to generate proper intersection types', async () => {\n    const result = await generateEndpoints({\n      apiFile: './tmp/emptyApi.ts',\n      schemaFile: './test/fixtures/issue-2002.json',\n      hooks: true,\n    });\n    expect(result).toMatchSnapshot();\n  });\n\n  it('issue #3369: discriminated unions should use enum values, not schema names', async () => {\n    const result = await generateEndpoints({\n      apiFile: './tmp/emptyApi.ts',\n      schemaFile: './test/fixtures/issue-3369-discriminator-enum.json',\n    });\n\n    // The discriminator value should be 'engineering' and 'standard' (from enum)\n    // NOT 'EngineeringAllowance' and 'StandardAllowance' (schema names)\n    expect(result).toContain('allowance_type: \"engineering\"');\n    expect(result).toContain('allowance_type: \"standard\"');\n\n    // Should NOT use schema names as discriminator values\n    expect(result).not.toContain('allowance_type: \"EngineeringAllowance\"');\n    expect(result).not.toContain('allowance_type: \"StandardAllowance\"');\n\n    expect(result).toMatchSnapshot();\n  });\n});\n\ndescribe('openapi spec', () => {\n  it('readOnly / writeOnly are respected', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      schemaFile: './test/fixtures/readOnlyWriteOnly.yaml',\n      apiFile: './fixtures/emptyApi.ts',\n    });\n    expect(api).toMatchSnapshot();\n  });\n});\n\ndescribe('openapi spec', () => {\n  it('readOnly / writeOnly are merged', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      schemaFile: './test/fixtures/readOnlyWriteOnly.yaml',\n      apiFile: './fixtures/emptyApi.ts',\n      mergeReadWriteOnly: true,\n    });\n    expect(api).toMatchSnapshot();\n  });\n});\n\ndescribe('query parameters', () => {\n  it('parameters overridden in swagger should also be overridden in the code', async () => {\n    const api = await generateEndpoints({\n      schemaFile: './test/fixtures/parameterOverride.yaml',\n      apiFile: './fixtures/emptyApi.ts',\n    });\n    expect(api).toMatchSnapshot();\n  });\n});\n\ndescribe('regex constants', () => {\n  it('should export regex constants for patterns', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      outputRegexConstants: true,\n    });\n\n    expect(api).toContain(String.raw`export const tagNamePattern = /^\\S+$/`);\n    expect(api).toContain(String.raw`export const userEmailPattern`);\n    expect(api).toContain(String.raw`/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/`);\n    expect(api).toContain(String.raw`export const userPhonePattern = /^\\+?[1-9]\\d{1,14}$/`);\n  });\n\n  it('should not export constants for invalid patterns', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      outputRegexConstants: true,\n    });\n\n    // Empty pattern should not generate a constant\n    expect(api).not.toContain('userPasswordPattern');\n    expect(api).not.toContain('passwordPattern');\n\n    // Pattern on non-string property (integer) should not generate a constant\n    expect(api).not.toContain('userUserStatusPattern');\n    expect(api).not.toContain('userStatusPattern');\n  });\n\n  it('should export regex constants for patterns from YAML file', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.yaml'),\n      outputRegexConstants: true,\n    });\n\n    expect(api).toContain(String.raw`export const tagNamePattern = /^\\S+$/`);\n    expect(api).toContain(String.raw`export const userEmailPattern`);\n    expect(api).toContain(String.raw`/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}$/`);\n    expect(api).toContain(String.raw`export const userPhonePattern = /^\\+?[1-9]\\d{1,14}$/`);\n  });\n\n  it('should not export regex constants when outputRegexConstants is false', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      outputRegexConstants: false,\n    });\n\n    expect(api).not.toContain('Pattern = /');\n    expect(api).not.toContain('tagNamePattern');\n    expect(api).not.toContain('userEmailPattern');\n    expect(api).not.toContain('userPhonePattern');\n  });\n\n  it('should properly escape forward slashes in patterns', async () => {\n    const api = await generateEndpoints({\n      unionUndefined: true,\n      apiFile: './fixtures/emptyApi.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      outputRegexConstants: true,\n    });\n\n    // The userWebsitePattern should have escaped forward slashes\n    expect(api).toContain(String.raw`export const userWebsitePattern = /^https?:\\/\\/[^\\s]+$/`);\n  });\n});\n\ndescribe('esmExtensions option', () => {\n  beforeAll(async () => {\n    if (!(await isDir(tmpDir))) {\n      await fs.mkdir(tmpDir, { recursive: true });\n    }\n  });\n\n  afterEach(async () => {\n    await rimraf(`${tmpDir}/*.ts`, { glob: true });\n  });\n\n  test('should convert .ts to .js when esmExtensions is true', async () => {\n    await generateEndpoints({\n      apiFile: './fixtures/emptyApi.ts',\n      outputFile: './test/tmp/out.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: [],\n      esmExtensions: true,\n    });\n    const content = await fs.readFile('./test/tmp/out.ts', 'utf8');\n    expect(content).toContain(\"import { api } from '../../fixtures/emptyApi.js'\");\n  });\n\n  test('should convert .mts to .mjs when esmExtensions is true', async () => {\n    await generateEndpoints({\n      apiFile: './fixtures/emptyApi.mts',\n      outputFile: './test/tmp/out.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: [],\n      esmExtensions: true,\n    });\n    const content = await fs.readFile('./test/tmp/out.ts', 'utf8');\n    expect(content).toContain(\"import { api } from '../../fixtures/emptyApi.mjs'\");\n  });\n\n  test('should preserve .jsx when esmExtensions is true', async () => {\n    await generateEndpoints({\n      apiFile: './fixtures/emptyApi.jsx',\n      outputFile: './test/tmp/out.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: [],\n      esmExtensions: true,\n    });\n    const content = await fs.readFile('./test/tmp/out.ts', 'utf8');\n    expect(content).toContain(\"import { api } from '../../fixtures/emptyApi.jsx'\");\n  });\n\n  test('should convert .tsx to .jsx when esmExtensions is true', async () => {\n    await generateEndpoints({\n      apiFile: './fixtures/emptyApi.tsx',\n      outputFile: './test/tmp/out.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: [],\n      esmExtensions: true,\n    });\n    const content = await fs.readFile('./test/tmp/out.ts', 'utf8');\n    expect(content).toContain(\"import { api } from '../../fixtures/emptyApi.jsx'\");\n  });\n\n  test('should strip extensions when esmExtensions is false', async () => {\n    await generateEndpoints({\n      apiFile: './fixtures/emptyApi.ts',\n      outputFile: './test/tmp/out.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: [],\n      esmExtensions: false,\n    });\n    const content = await fs.readFile('./test/tmp/out.ts', 'utf8');\n    expect(content).toContain(\"import { api } from '../../fixtures/emptyApi'\");\n  });\n\n  test('should strip extensions when esmExtensions is undefined (default)', async () => {\n    await generateEndpoints({\n      apiFile: './fixtures/emptyApi.ts',\n      outputFile: './test/tmp/out.ts',\n      schemaFile: resolve(__dirname, 'fixtures/petstore.json'),\n      filterEndpoints: [],\n    });\n    const content = await fs.readFile('./test/tmp/out.ts', 'utf8');\n    expect(content).toContain(\"import { api } from '../../fixtures/emptyApi'\");\n  });\n});\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/mocks/server.ts",
    "content": "import { headersToObject } from 'headers-polyfill';\nimport { http, HttpResponse } from 'msw';\nimport { setupServer } from 'msw/node';\nimport petstoreJSON from '../fixtures/petstore.json';\nimport petstoreYAML from '../fixtures/petstore.yaml.mock';\n\n// This configures a request mocking server with the given request handlers.\n\nexport const server = setupServer(\n  http.get('https://example.com/echo', async ({ request, params, cookies, requestId }) =>\n    HttpResponse.json({\n      ...request,\n      params,\n      cookies,\n      requestId,\n      url: new URL(request.url),\n      headers: headersToObject(request.headers),\n    })\n  ),\n  http.post('https://example.com/echo', async ({ request, params, cookies, requestId }) => {\n    let body;\n\n    try {\n      body =\n        headersToObject(request.headers)['content-type'] === 'text/html' ? await request.text() : await request.json();\n    } catch (err) {\n      body = request.body;\n    }\n\n    return HttpResponse.json({\n      ...request,\n      cookies,\n      params,\n      requestId,\n      body,\n      url: new URL(request.url),\n      headers: headersToObject(request.headers),\n    });\n  }),\n\n  http.get('https://petstore3.swagger.io/api/v3/openapi.json', () => HttpResponse.json(petstoreJSON)),\n  http.get('https://petstore3.swagger.io/api/v3/openapi.yaml', () => HttpResponse.text(petstoreYAML))\n);\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/test/vitest.setup.ts",
    "content": "import nodeFetch from 'node-fetch';\nimport { format } from 'prettier';\nimport { server } from './mocks/server';\n\nvi.stubGlobal('fetch', nodeFetch);\n\nbeforeAll(() => {\n  server.listen({ onUnhandledRequest: 'error' });\n});\n\nafterEach(() => {\n  server.resetHandlers();\n});\n\nafterAll(() => {\n  server.close();\n});\n\n// expect.addSnapshotSerializer({\n//   test: (val) => typeof val === 'string',\n//   print: (val) => {\n//     return val as string;\n//   },\n// });\n\n// expect.addSnapshotSerializer({\n//   // async serialize(val) {\n//   //   return await format(val, {\n//   //     parser: 'typescript',\n//   //     endOfLine: 'auto',\n//   //     printWidth: 120,\n//   //     semi: true,\n//   //     singleQuote: true,\n//   //     trailingComma: 'es5',\n//   //   });\n//   // },\n//   test: (val) => /injectEndpoints/.test(val),\n// });\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/tsconfig.build.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": {\n    \"allowJs\": false,\n    \"checkJs\": false,\n    \"noEmit\": false,\n    \"rootDir\": \"src\"\n  },\n  \"include\": [\"src\"]\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"allowJs\": true,\n    \"allowSyntheticDefaultImports\": true,\n    \"checkJs\": true,\n    \"declaration\": true,\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"isolatedModules\": true,\n    \"jsx\": \"react\",\n    \"module\": \"ESNext\",\n    \"moduleResolution\": \"Bundler\",\n    \"noEmit\": true,\n    \"noErrorTruncation\": true,\n    \"noImplicitReturns\": true,\n    \"noUnusedLocals\": false,\n    \"outDir\": \"lib\",\n    \"rootDir\": \".\",\n    \"paths\": {\n      \"@rtk-query/codegen-openapi\": [\"./src/index.ts\"] // @remap-prod-remove-line\n    },\n    \"resolveJsonModule\": true,\n    \"skipLibCheck\": true,\n    \"sourceMap\": true,\n    \"strict\": true,\n    \"target\": \"ESNext\",\n    \"types\": [\"vitest/globals\", \"vitest/importMeta\", \"node\"]\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/tsup.config.ts",
    "content": "import type { Options } from 'tsup';\nimport { defineConfig } from 'tsup';\n\nconst tsconfig = 'tsconfig.build.json' satisfies Options['tsconfig'];\n\nexport default defineConfig((options): Options[] => {\n  const commonOptions: Options = {\n    entry: { index: 'src/index.ts' },\n    sourcemap: true,\n    tsconfig,\n    clean: true,\n    target: ['esnext'],\n    outDir: 'lib',\n    splitting: false,\n    removeNodeProtocol: false,\n    shims: true,\n    ...options,\n  };\n\n  return [\n    { ...commonOptions, name: 'Modern ESM', format: ['esm'], entry: { index: 'src/index.ts' }, dts: true },\n    { ...commonOptions, name: 'CJS Development', format: ['cjs'], entry: { index: 'src/index.ts' }, dts: true },\n    {\n      ...commonOptions,\n      format: ['esm'],\n      name: 'CLI Development',\n      external: ['@rtk-query/codegen-openapi'],\n      minify: true,\n      entry: { 'bin/cli': 'src/bin/cli.ts' },\n    },\n  ];\n});\n"
  },
  {
    "path": "packages/rtk-query-codegen-openapi/vitest.config.mts",
    "content": "import path from 'node:path';\nimport { fileURLToPath } from 'node:url';\nimport tsconfigPaths from 'vite-tsconfig-paths';\nimport { defineConfig } from 'vitest/config';\n\n// No __dirname under Node ESM\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n\nexport default defineConfig({\n  plugins: [tsconfigPaths({ projects: ['./tsconfig.json'] })],\n  test: {\n    alias: process.env.TEST_DIST\n      ? {\n          '@rtk-query/codegen-openapi': path.join(__dirname, '../..', 'node_modules/@rtk-query/codegen-openapi'),\n        }\n      : undefined,\n    testTimeout: 10_000,\n    pool: 'forks',\n    globals: true,\n    setupFiles: ['./test/vitest.setup.ts'],\n  },\n});\n"
  },
  {
    "path": "packages/rtk-query-graphql-request-base-query/.gitignore",
    "content": "dist\nnode_modules\nyarn-error.log"
  },
  {
    "path": "packages/rtk-query-graphql-request-base-query/.release-it.json",
    "content": "{\n  \"hooks\": {\n    \"after:bump\": \"yarn && git add -u\"\n  },\n  \"git\": {\n    \"commitMessage\": \"Release @rtk-query/graphql-request-base-query ${version}\",\n    \"tagName\": \"@rtk-query/graphql-request-base-query@${version}\"\n  },\n  \"npm\": {\n    \"publish\": false,\n    \"versionArgs\": [\"--workspaces-update=false\"]\n  }\n}\n"
  },
  {
    "path": "packages/rtk-query-graphql-request-base-query/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2021 Lenz Weber\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/rtk-query-graphql-request-base-query/package.json",
    "content": "{\n  \"name\": \"@rtk-query/graphql-request-base-query\",\n  \"version\": \"2.3.2\",\n  \"author\": {\n    \"name\": \"Lenz Weber\",\n    \"email\": \"mail@phryneas.de\",\n    \"url\": \"https://phryneas.de/\"\n  },\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/reduxjs/redux-toolkit.git\"\n  },\n  \"type\": \"module\",\n  \"source\": \"src/index.ts\",\n  \"main\": \"./dist/index.cjs\",\n  \"module\": \"./dist/index.module.js\",\n  \"unpkg\": \"./dist/index.umd.js\",\n  \"types\": \"./dist/index.d.ts\",\n  \"scripts\": {\n    \"build\": \"microbundle\",\n    \"prepack\": \"rimraf dist/*; yarn build\",\n    \"dev\": \"microbundle watch\",\n    \"test\": \"vitest run\",\n    \"test:watch\": \"vitest\"\n  },\n  \"dependencies\": {\n    \"graphql-request\": \"^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0\"\n  },\n  \"peerDependencies\": {\n    \"@reduxjs/toolkit\": \"^1.7.1 || ^2.0.0\",\n    \"graphql\": \"^0.8.0 || ^0.9.0 || ^0.10.0 || ^0.11.0 || ^0.12.0 || ^0.13.0 || ^14.0.0 || ^15.0.0 || ^16.0.0\"\n  },\n  \"devDependencies\": {\n    \"@reduxjs/toolkit\": \"^1.6.0 || ^2.0.0\",\n    \"@types/node\": \"^25.5.0\",\n    \"graphql\": \"^16.5.0\",\n    \"microbundle\": \"^0.13.3\",\n    \"rimraf\": \"^6.1.3\",\n    \"typescript\": \"^5.9.3\",\n    \"vitest\": \"^4\"\n  },\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"files\": [\n    \"src\",\n    \"dist\"\n  ]\n}\n"
  },
  {
    "path": "packages/rtk-query-graphql-request-base-query/src/GraphqlBaseQueryTypes.ts",
    "content": "import type { BaseQueryApi } from '@reduxjs/toolkit/query'\nimport type {\n  GraphQLClient,\n  RequestOptions,\n  RequestDocument,\n  ClientError,\n} from 'graphql-request'\n\nexport type Document = RequestDocument\nexport type RequestHeaders = RequestOptions['requestHeaders']\nexport type PrepareHeaders = (\n  headers: Headers,\n  api: Pick<\n    BaseQueryApi,\n    'getState' | 'endpoint' | 'type' | 'forced' | 'extra'\n  >,\n) => MaybePromise<Headers>\n\nexport type ErrorResponse = {\n  message: string\n  stack: string\n  name: string\n}\n\nexport type GraphqlRequestBaseQueryArgs<E = ErrorResponse> = (\n  | {\n      url: string\n    }\n  | { client: GraphQLClient }\n) & {\n  requestHeaders?: RequestHeaders\n  prepareHeaders?: PrepareHeaders\n  customErrors?: (args: ClientError) => E\n}\n\nexport type QueryReturnValue<T = unknown, E = unknown, M = unknown> =\n  | {\n      error: E\n      data?: undefined\n      meta?: M\n    }\n  | {\n      error?: undefined\n      data: T\n      meta?: M\n    }\nexport type MaybePromise<T> = T | PromiseLike<T>\n"
  },
  {
    "path": "packages/rtk-query-graphql-request-base-query/src/index.test.ts",
    "content": "import { describe, it, expect, vi } from 'vitest'\nimport type { GraphQLClient } from 'graphql-request'\nimport { ClientError } from 'graphql-request'\nimport { graphqlRequestBaseQuery } from './index'\nimport type { BaseQueryApi } from '@reduxjs/toolkit/query'\n\ndescribe('graphqlRequestBaseQuery', () => {\n  const mockGetState = vi.fn()\n  const mockDispatch = vi.fn()\n  const mockAbort = vi.fn()\n  const mockExtra = {}\n  const mockSignal = new AbortController().signal\n\n  const createMockApi = (): BaseQueryApi => ({\n    signal: mockSignal,\n    abort: mockAbort,\n    dispatch: mockDispatch,\n    getState: mockGetState,\n    extra: mockExtra,\n    endpoint: 'testEndpoint',\n    type: 'query' as const,\n    forced: false,\n  })\n\n  describe('successful requests', () => {\n    it('returns data on successful request', async () => {\n      const mockData = { user: { id: '1', name: 'Test User' } }\n      const mockClient = {\n        request: vi.fn().mockResolvedValue(mockData),\n      } as unknown as GraphQLClient\n\n      const baseQuery = graphqlRequestBaseQuery({ client: mockClient })\n      const result = await baseQuery(\n        {\n          document: 'query { user { id name } }',\n          variables: {},\n        },\n        createMockApi(),\n        {},\n      )\n\n      expect(result).toEqual({\n        data: mockData,\n        meta: {},\n      })\n      expect(mockClient.request).toHaveBeenCalledTimes(1)\n    })\n\n    it('passes variables to the GraphQL client', async () => {\n      const mockData = { user: { id: '1' } }\n      const mockClient = {\n        request: vi.fn().mockResolvedValue(mockData),\n      } as unknown as GraphQLClient\n\n      const baseQuery = graphqlRequestBaseQuery({ client: mockClient })\n      const variables = { userId: '1' }\n\n      await baseQuery(\n        {\n          document: 'query($userId: ID!) { user(id: $userId) { id } }',\n          variables,\n        },\n        createMockApi(),\n        {},\n      )\n\n      expect(mockClient.request).toHaveBeenCalledWith(\n        expect.objectContaining({\n          variables,\n        }),\n      )\n    })\n\n    it('passes document to the GraphQL client', async () => {\n      const mockData = { test: 'data' }\n      const mockClient = {\n        request: vi.fn().mockResolvedValue(mockData),\n      } as unknown as GraphQLClient\n\n      const baseQuery = graphqlRequestBaseQuery({ client: mockClient })\n      const document = 'query { test }'\n\n      await baseQuery(\n        {\n          document,\n        },\n        createMockApi(),\n        {},\n      )\n\n      expect(mockClient.request).toHaveBeenCalledWith(\n        expect.objectContaining({\n          document,\n        }),\n      )\n    })\n  })\n\n  describe('error handling', () => {\n    it('returns error for ClientError (GraphQL API errors)', async () => {\n      const mockError = new ClientError(\n        {\n          errors: [{ message: 'User not found' }],\n        } as any,\n        { query: 'test query' } as any,\n      )\n\n      const mockClient = {\n        request: vi.fn().mockRejectedValue(mockError),\n      } as unknown as GraphQLClient\n\n      const baseQuery = graphqlRequestBaseQuery({ client: mockClient })\n      const result = await baseQuery(\n        {\n          document: 'query { user { id } }',\n        },\n        createMockApi(),\n        {},\n      )\n\n      expect(result).toEqual({\n        error: {\n          name: expect.any(String),\n          message: expect.any(String),\n          stack: expect.any(String),\n        },\n        meta: {\n          request: expect.any(Object),\n          response: expect.any(Object),\n        },\n      })\n    })\n\n    it('includes request and response in meta for ClientError', async () => {\n      const mockRequest = { query: 'test query' }\n      const mockResponse = { errors: [{ message: 'Error' }] }\n      const mockError = new ClientError(mockResponse as any, mockRequest as any)\n\n      const mockClient = {\n        request: vi.fn().mockRejectedValue(mockError),\n      } as unknown as GraphQLClient\n\n      const baseQuery = graphqlRequestBaseQuery({ client: mockClient })\n      const result = await baseQuery(\n        {\n          document: 'query { test }',\n        },\n        createMockApi(),\n        {},\n      )\n\n      expect(result.meta).toHaveProperty('request')\n      expect(result.meta).toHaveProperty('response')\n    })\n\n    it('returns network errors (non-ClientError) instead of throwing', async () => {\n      const networkError = new Error('Network timeout')\n      const mockClient = {\n        request: vi.fn().mockRejectedValue(networkError),\n      } as unknown as GraphQLClient\n\n      const baseQuery = graphqlRequestBaseQuery({ client: mockClient })\n\n      const result = await baseQuery(\n        {\n          document: 'query { user { id } }',\n        },\n        createMockApi(),\n        {},\n      )\n\n      // Should return error instead of throwing\n      expect(result).toEqual({\n        error: {\n          name: 'Error',\n          message: 'Network timeout',\n          stack: expect.any(String),\n        },\n        meta: {},\n      })\n    })\n\n    it('returns fetch errors instead of throwing', async () => {\n      const fetchError = new Error('Failed to fetch')\n      const mockClient = {\n        request: vi.fn().mockRejectedValue(fetchError),\n      } as unknown as GraphQLClient\n\n      const baseQuery = graphqlRequestBaseQuery({ client: mockClient })\n\n      const result = await baseQuery(\n        {\n          document: 'query { test }',\n        },\n        createMockApi(),\n        {},\n      )\n\n      // Should return error instead of throwing\n      expect(result).toEqual({\n        error: {\n          name: 'Error',\n          message: 'Failed to fetch',\n          stack: expect.any(String),\n        },\n        meta: {},\n      })\n    })\n\n    it('uses custom error handler when provided', async () => {\n      const mockError = new ClientError(\n        {\n          errors: [{ message: 'Custom error' }],\n        } as any,\n        { query: 'test query' } as any,\n      )\n\n      const mockClient = {\n        request: vi.fn().mockRejectedValue(mockError),\n      } as unknown as GraphQLClient\n\n      const customErrors = vi.fn((error: ClientError) => ({\n        customField: 'custom value',\n        originalMessage: error.message,\n      }))\n\n      const baseQuery = graphqlRequestBaseQuery({\n        client: mockClient,\n        customErrors,\n      })\n\n      const result = await baseQuery(\n        {\n          document: 'query { user { id } }',\n        },\n        createMockApi(),\n        {},\n      )\n\n      expect(customErrors).toHaveBeenCalledWith(mockError)\n      expect(result.error).toEqual({\n        customField: 'custom value',\n        originalMessage: expect.any(String),\n      })\n    })\n\n    it('uses default error format when customErrors not provided', async () => {\n      const mockError = new ClientError(\n        {\n          errors: [{ message: 'Test error' }],\n        } as any,\n        { query: 'test query' } as any,\n      )\n\n      const mockClient = {\n        request: vi.fn().mockRejectedValue(mockError),\n      } as unknown as GraphQLClient\n\n      const baseQuery = graphqlRequestBaseQuery({ client: mockClient })\n      const result = await baseQuery(\n        {\n          document: 'query { test }',\n        },\n        createMockApi(),\n        {},\n      )\n\n      expect(result).toEqual({\n        error: {\n          name: expect.any(String),\n          message: expect.any(String),\n          stack: expect.any(String),\n        },\n        meta: {\n          request: expect.any(Object),\n          response: expect.any(Object),\n        },\n      })\n    })\n  })\n\n  describe('headers', () => {\n    it('applies prepareHeaders function', async () => {\n      const mockData = { test: 'data' }\n      const mockClient = {\n        request: vi.fn().mockResolvedValue(mockData),\n      } as unknown as GraphQLClient\n\n      const prepareHeaders = vi.fn((headers: Headers) => {\n        headers.set('Authorization', 'Bearer token123')\n        return headers\n      })\n\n      const baseQuery = graphqlRequestBaseQuery({\n        client: mockClient,\n        prepareHeaders,\n      })\n\n      await baseQuery(\n        {\n          document: 'query { test }',\n        },\n        createMockApi(),\n        {},\n      )\n\n      expect(prepareHeaders).toHaveBeenCalled()\n      expect(mockClient.request).toHaveBeenCalledWith(\n        expect.objectContaining({\n          requestHeaders: expect.any(Headers),\n        }),\n      )\n    })\n\n    it('passes correct arguments to prepareHeaders', async () => {\n      const mockData = { test: 'data' }\n      const mockClient = {\n        request: vi.fn().mockResolvedValue(mockData),\n      } as unknown as GraphQLClient\n\n      const prepareHeaders = vi.fn((headers: Headers) => headers)\n\n      const baseQuery = graphqlRequestBaseQuery({\n        client: mockClient,\n        prepareHeaders,\n      })\n\n      const mockApi = createMockApi()\n      await baseQuery(\n        {\n          document: 'query { test }',\n        },\n        mockApi,\n        {},\n      )\n\n      expect(prepareHeaders).toHaveBeenCalledWith(\n        expect.any(Headers),\n        expect.objectContaining({\n          getState: mockApi.getState,\n          endpoint: mockApi.endpoint,\n          forced: mockApi.forced,\n          type: mockApi.type,\n          extra: mockApi.extra,\n        }),\n      )\n    })\n\n    it('merges requestHeaders with prepareHeaders', async () => {\n      const mockData = { test: 'data' }\n      const mockClient = {\n        request: vi.fn().mockResolvedValue(mockData),\n      } as unknown as GraphQLClient\n\n      const prepareHeaders = vi.fn((headers: Headers) => {\n        headers.set('X-Custom-Header', 'custom-value')\n        return headers\n      })\n\n      const baseQuery = graphqlRequestBaseQuery({\n        client: mockClient,\n        requestHeaders: {\n          'Content-Type': 'application/json',\n        },\n        prepareHeaders,\n      })\n\n      await baseQuery(\n        {\n          document: 'query { test }',\n        },\n        createMockApi(),\n        {},\n      )\n\n      const callArgs = (mockClient.request as any).mock.calls[0][0]\n      const headers = callArgs.requestHeaders as Headers\n\n      expect(headers.get('Content-Type')).toBe('application/json')\n      expect(headers.get('X-Custom-Header')).toBe('custom-value')\n    })\n  })\n\n  describe('client initialization', () => {\n    it('creates GraphQLClient from URL when client not provided', async () => {\n      const mockData = { test: 'data' }\n\n      // We can't easily test the actual client creation without mocking the constructor,\n      // but we can verify the baseQuery works with a URL\n      const baseQuery = graphqlRequestBaseQuery({\n        url: 'https://api.example.com/graphql',\n      })\n\n      // This will fail in the test environment since there's no actual server,\n      // but it verifies the configuration is accepted\n      expect(baseQuery).toBeDefined()\n      expect(typeof baseQuery).toBe('function')\n    })\n\n    it('uses provided client when available', async () => {\n      const mockData = { test: 'data' }\n      const mockClient = {\n        request: vi.fn().mockResolvedValue(mockData),\n      } as unknown as GraphQLClient\n\n      const baseQuery = graphqlRequestBaseQuery({ client: mockClient })\n\n      await baseQuery(\n        {\n          document: 'query { test }',\n        },\n        createMockApi(),\n        {},\n      )\n\n      expect(mockClient.request).toHaveBeenCalled()\n    })\n  })\n\n  describe('signal handling', () => {\n    it('passes abort signal to GraphQL client', async () => {\n      const mockData = { test: 'data' }\n      const mockClient = {\n        request: vi.fn().mockResolvedValue(mockData),\n      } as unknown as GraphQLClient\n\n      const baseQuery = graphqlRequestBaseQuery({ client: mockClient })\n      const controller = new AbortController()\n\n      const mockApi = {\n        ...createMockApi(),\n        signal: controller.signal,\n      }\n\n      await baseQuery(\n        {\n          document: 'query { test }',\n        },\n        mockApi,\n        {},\n      )\n\n      expect(mockClient.request).toHaveBeenCalledWith(\n        expect.objectContaining({\n          signal: controller.signal,\n        }),\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/rtk-query-graphql-request-base-query/src/index.ts",
    "content": "import { isPlainObject } from '@reduxjs/toolkit'\nimport type { BaseQueryFn } from '@reduxjs/toolkit/query'\nimport type { DocumentNode } from 'graphql'\nimport type { RequestOptions } from 'graphql-request'\nimport { GraphQLClient, ClientError } from 'graphql-request'\nimport type {\n  ErrorResponse,\n  GraphqlRequestBaseQueryArgs,\n  PrepareHeaders,\n  RequestHeaders,\n} from './GraphqlBaseQueryTypes'\n\nexport const graphqlRequestBaseQuery = <E = ErrorResponse>(\n  options: GraphqlRequestBaseQueryArgs<E>,\n): BaseQueryFn<\n  { document: string | DocumentNode; variables?: any },\n  unknown,\n  E,\n  Partial<Pick<ClientError, 'request' | 'response'>>\n> => {\n  const client =\n    'client' in options ? options.client : new GraphQLClient(options.url)\n  const requestHeaders: RequestHeaders =\n    'requestHeaders' in options ? options.requestHeaders : {}\n\n  return async (\n    { document, variables },\n    { getState, endpoint, forced, type, signal, extra },\n  ) => {\n    try {\n      const prepareHeaders: PrepareHeaders =\n        options.prepareHeaders ?? ((x) => x)\n      const headers = new Headers(stripUndefined(requestHeaders))\n\n      const preparedHeaders = await prepareHeaders(headers, {\n        getState,\n        endpoint,\n        forced,\n        type,\n        extra,\n      })\n\n      return {\n        data: await client.request({\n          document,\n          variables,\n          signal: signal as unknown as RequestOptions['signal'],\n          requestHeaders: preparedHeaders,\n        }),\n        meta: {},\n      }\n    } catch (error) {\n      if (error instanceof ClientError) {\n        const { name, message, stack, request, response } = error\n\n        const customErrors =\n          options.customErrors ?? (() => ({ name, message, stack }))\n\n        const customizedErrors = customErrors(error) as E\n\n        return { error: customizedErrors, meta: { request, response } }\n      }\n      // Base queries should never throw, but return {error}.\n      // This also ensures that retry logic works correctly.\n      const err = error as Error\n      return {\n        error: {\n          name: err?.name || 'NetworkError',\n          message: err?.message || 'An unknown network error occurred',\n          stack: err?.stack,\n        } as E,\n        meta: {},\n      }\n    }\n  }\n}\n\nfunction stripUndefined(obj: any) {\n  if (!isPlainObject(obj)) {\n    return obj\n  }\n  const copy: Record<string, any> = { ...obj }\n  for (const [k, v] of Object.entries(copy)) {\n    if (typeof v === 'undefined') delete copy[k]\n  }\n  return copy\n}\n"
  },
  {
    "path": "packages/rtk-query-graphql-request-base-query/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2020\",\n    \"module\": \"ESNext\",\n    \"lib\": [\"ES2020\"],\n    \"moduleResolution\": \"bundler\",\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"sourceMap\": true,\n    \"types\": [\"vitest/globals\", \"vitest/importMeta\", \"node\"]\n  },\n  \"include\": [\"src/**/*\"],\n  \"exclude\": [\"node_modules\", \"dist\"]\n}\n"
  },
  {
    "path": "packages/rtk-query-graphql-request-base-query/vitest.config.mts",
    "content": "import path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport { defineConfig } from 'vitest/config'\n\n// No __dirname under Node ESM\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = path.dirname(__filename)\n\nexport default defineConfig({\n  test: {\n    globals: true,\n    environment: 'node', // Node environment since this is a baseQuery, not React\n    include: ['./src/**/*.test.ts'],\n    coverage: {\n      provider: 'v8',\n      reporter: ['text', 'json', 'html'],\n      include: ['src/**/*.ts'],\n      exclude: ['src/**/*.test.ts', 'src/**/*.d.ts'],\n    },\n  },\n  resolve: {\n    alias: {\n      '@reduxjs/toolkit': path.resolve(__dirname, '../toolkit/src'),\n    },\n  },\n})\n"
  },
  {
    "path": "packages/toolkit/.release-it.json",
    "content": "{\n  \"hooks\": {\n    \"after:bump\": \"yarn && git add -u\"\n  },\n  \"git\": {\n    \"tagName\": \"v${version}\"\n  },\n  \"npm\": {\n    \"publish\": false,\n    \"versionArgs\": [\"--workspaces-update=false\"]\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/.size-limit.cjs",
    "content": "const webpack = require('webpack')\nlet { join } = require('path')\n\nconst esmSuffixes = ['modern.mjs', 'browser.mjs' /*, 'legacy-esm.js'*/]\nconst cjsSuffixes = [\n  /*'development.cjs',*/\n  /*'production.min.cjs'*/\n]\n\nfunction withRtkPath(suffix, cjs = false) {\n  /**\n   * @param {string} name\n   */\n  function alias(name) {\n    return `${cjs ? 'cjs/' : ''}${name}.${suffix}`\n  }\n  /**\n   * @param {webpack.Configuration} config\n   */\n  return (config) => {\n    config.plugins.push(\n      new webpack.NormalModuleReplacementPlugin(\n        /@reduxjs\\/toolkit\\/query\\/react/,\n        join(__dirname, 'dist/query/react/rtk-query-react.modern.mjs'),\n      ),\n      new webpack.NormalModuleReplacementPlugin(\n        /@reduxjs\\/toolkit\\/query/,\n        join(__dirname, 'dist/query/rtk-query.modern.mjs'),\n      ),\n      new webpack.NormalModuleReplacementPlugin(\n        /@reduxjs\\/toolkit\\/react/,\n        join(__dirname, 'dist/react/redux-toolkit-react.modern.mjs'),\n      ),\n      new webpack.NormalModuleReplacementPlugin(\n        /@reduxjs\\/toolkit/,\n        join(__dirname, 'dist/redux-toolkit.modern.mjs'),\n      ),\n      new webpack.NormalModuleReplacementPlugin(\n        /rtk-query-react.modern.mjs/,\n        (r) => {\n          const old = r.request\n          r.request = r.request.replace(\n            /rtk-query-react.modern.mjs$/,\n            alias('rtk-query-react'),\n          )\n          //console.log(old, '=>', r.request)\n        },\n      ),\n      new webpack.NormalModuleReplacementPlugin(/rtk-query.modern.mjs/, (r) => {\n        const old = r.request\n        r.request = r.request.replace(\n          /rtk-query.modern.mjs$/,\n          alias('rtk-query'),\n        )\n        //console.log(old, '=>', r.request)\n      }),\n      new webpack.NormalModuleReplacementPlugin(\n        /redux-toolkit-react.modern.mjs$/,\n        (r) => {\n          const old = r.request\n          r.request = r.request.replace(\n            /redux-toolkit-react.modern.mjs$/,\n            alias('redux-toolkit-react'),\n          )\n          //console.log(old, '=>', r.request)\n        },\n      ),\n      new webpack.NormalModuleReplacementPlugin(\n        /redux-toolkit.modern.mjs$/,\n        (r) => {\n          const old = r.request\n          r.request = r.request.replace(\n            /redux-toolkit.modern.mjs$/,\n            alias('redux-toolkit'),\n          )\n          //console.log(old, '=>', r.request)\n        },\n      ),\n    )\n\n    if (suffix === 'production.min.cjs') {\n      ;(config.resolve ??= {}).mainFields = ['main', 'module']\n    }\n    ;(config.optimization ??= {}).nodeEnv = 'production'\n    return config\n  }\n}\n\nconst ignoreAll = [\n  '@reduxjs/toolkit',\n  '@reduxjs/toolkit/query',\n  'immer',\n  'redux',\n  'reselect',\n  'redux-thunk',\n]\n\nconst entryPoints = [\n  {\n    name: `1. entry point: @reduxjs/toolkit`,\n    path: 'dist/redux-toolkit.modern.mjs',\n  },\n  {\n    name: `1. entry point: @reduxjs/toolkit/react`,\n    path: 'dist/react/redux-toolkit-react.modern.mjs',\n  },\n  {\n    name: `1. entry point: @reduxjs/toolkit/query`,\n    path: 'dist/query/rtk-query.modern.mjs',\n  },\n  {\n    name: `1. entry point: @reduxjs/toolkit/query/react`,\n    path: 'dist/query/react/rtk-query-react.modern.mjs',\n  },\n  {\n    name: `2. entry point: @reduxjs/toolkit (without dependencies)`,\n    path: 'dist/redux-toolkit.modern.mjs',\n    ignore: ignoreAll,\n  },\n  {\n    name: `2. entry point: @reduxjs/toolkit/react (without dependencies)`,\n    path: 'dist/react/redux-toolkit-react.modern.mjs',\n    ignore: ignoreAll,\n  },\n  {\n    name: `2. entry point: @reduxjs/toolkit/query (without dependencies)`,\n    path: 'dist/query/rtk-query.modern.mjs',\n    ignore: ignoreAll,\n  },\n  {\n    name: `2. entry point: @reduxjs/toolkit/query/react (without dependencies)`,\n    path: 'dist/query/react/rtk-query-react.modern.mjs',\n    ignore: ignoreAll,\n  },\n]\n\nmodule.exports = entryPoints\n  .flatMap((e) =>\n    esmSuffixes.map((suffix) => ({\n      ...e,\n      name: e.name + ` (${suffix})`,\n      modifyWebpackConfig: withRtkPath(suffix),\n    })),\n  )\n  .concat(\n    entryPoints.flatMap((e) =>\n      cjsSuffixes.map((suffix) => ({\n        ...e,\n        name: e.name + ` (cjs, ${suffix})`,\n        modifyWebpackConfig: withRtkPath(suffix, true),\n      })),\n    ),\n  )\n  .concat(\n    [\n      {\n        name: `3. createSlice`,\n        import: { '@reduxjs/toolkit': '{ createSlice }' },\n      },\n      {\n        name: `3. createAsyncThunk`,\n        import: { '@reduxjs/toolkit': '{ createAsyncThunk }' },\n      },\n      {\n        name: `3. buildCreateSlice and asyncThunkCreator`,\n        import: {\n          '@reduxjs/toolkit': '{ buildCreateSlice, asyncThunkCreator }',\n        },\n      },\n      {\n        name: `3. createEntityAdapter`,\n        import: { '@reduxjs/toolkit': '{ createEntityAdapter }' },\n      },\n      {\n        name: `3. configureStore`,\n        import: { '@reduxjs/toolkit': '{ configureStore }' },\n      },\n      {\n        name: `3. combineSlices`,\n        import: { '@reduxjs/toolkit': '{ combineSlices }' },\n      },\n      {\n        name: `3. createDynamicMiddleware`,\n        import: { '@reduxjs/toolkit': '{ createDynamicMiddleware }' },\n      },\n      {\n        name: `3. createDynamicMiddleware (react)`,\n        import: { '@reduxjs/toolkit/react': '{ createDynamicMiddleware }' },\n      },\n      {\n        name: `3. createListenerMiddleware`,\n        import: { '@reduxjs/toolkit': '{ createListenerMiddleware }' },\n      },\n      {\n        name: `3. createApi`,\n        import: { '@reduxjs/toolkit/query': '{ createApi }' },\n      },\n      {\n        name: `3. createApi (react)`,\n        import: { '@reduxjs/toolkit/query/react': '{ createApi }' },\n      },\n      {\n        name: `3. fetchBaseQuery`,\n        import: { '@reduxjs/toolkit/query': '{ fetchBaseQuery }' },\n      },\n    ].map((e) => ({\n      ...e,\n      name: e.name + ` (.modern.mjs)`,\n      modifyWebpackConfig: withRtkPath('modern.mjs'),\n    })),\n  )\n"
  },
  {
    "path": "packages/toolkit/LICENSE",
    "content": "MIT License\n\nCopyright (c) 2018 Mark Erikson\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/toolkit/README.md",
    "content": "# Redux Toolkit\n\n![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/reduxjs/redux-toolkit/tests.yml?style=flat-square)\n[![npm version](https://img.shields.io/npm/v/@reduxjs/toolkit.svg?style=flat-square)](https://www.npmjs.com/package/@reduxjs/toolkit)\n[![npm downloads](https://img.shields.io/npm/dm/@reduxjs/toolkit.svg?style=flat-square&label=RTK+downloads)](https://www.npmjs.com/package/@reduxjs/toolkit)\n\n**The official, opinionated, batteries-included toolset for efficient Redux development**\n\n## Installation\n\n### Create a React Redux App\n\nThe recommended way to start new apps with React and Redux Toolkit is by using [our official Redux Toolkit + TS template for Vite](https://github.com/reduxjs/redux-templates), or by creating a new Next.js project using [Next's `with-redux` template](https://github.com/vercel/next.js/tree/canary/examples/with-redux).\n\nBoth of these already have Redux Toolkit and React-Redux configured appropriately for that build tool, and come with a small example app that demonstrates how to use several of Redux Toolkit's features.\n\n```bash\n# Vite with our Redux+TS template\n# (using the `degit` tool to clone and extract the template)\nnpx degit reduxjs/redux-templates/packages/vite-template-redux my-app\n\n# Next.js using the `with-redux` template\nnpx create-next-app --example with-redux my-app\n```\n\nWe do not currently have official React Native templates, but recommend these templates for standard React Native and for Expo:\n\n- https://github.com/rahsheen/react-native-template-redux-typescript\n- https://github.com/rahsheen/expo-template-redux-typescript\n\n### An Existing App\n\nRedux Toolkit is available as a package on NPM for use with a module bundler or in a Node application:\n\n```bash\n# NPM\nnpm install @reduxjs/toolkit\n\n# Yarn\nyarn add @reduxjs/toolkit\n```\n\nIf you use an AI agent, run `npx @tanstack/intent@latest install` to install agent skills.\n\nThe package includes a precompiled ESM build that can be used as a [`<script type=\"module\">` tag](https://unpkg.com/@reduxjs/toolkit/dist/redux-toolkit.browser.mjs) directly in the browser.\n\n## Documentation\n\nThe Redux Toolkit docs are available at **https://redux-toolkit.js.org**, including API references and usage guides for all of the APIs included in Redux Toolkit.\n\nThe Redux core docs at https://redux.js.org includes the full Redux tutorials, as well usage guides on general Redux patterns.\n\n## Purpose\n\nThe **Redux Toolkit** package is intended to be the standard way to write Redux logic. It was originally created to help address three common concerns about Redux:\n\n- \"Configuring a Redux store is too complicated\"\n- \"I have to add a lot of packages to get Redux to do anything useful\"\n- \"Redux requires too much boilerplate code\"\n\nWe can't solve every use case, but in the spirit of [`create-react-app`](https://github.com/facebook/create-react-app), we can try to provide some tools that abstract over the setup process and handle the most common use cases, as well as include some useful utilities that will let the user simplify their application code.\n\nBecause of that, this package is deliberately limited in scope. It does _not_ address concepts like \"reusable encapsulated Redux modules\", folder or file structures, managing entity relationships in the store, and so on.\n\nRedux Toolkit also includes a powerful data fetching and caching capability that we've dubbed \"RTK Query\". It's included in the package as a separate set of entry points. It's optional, but can eliminate the need to hand-write data fetching logic yourself.\n\n## What's Included\n\nRedux Toolkit includes these APIs:\n\n- `configureStore()`: wraps `createStore` to provide simplified configuration options and good defaults. It can automatically combine your slice reducers, add whatever Redux middleware you supply, includes `redux-thunk` by default, and enables use of the Redux DevTools Extension.\n- `createReducer()`: lets you supply a lookup table of action types to case reducer functions, rather than writing switch statements. In addition, it automatically uses the [`immer` library](https://github.com/mweststrate/immer) to let you write simpler immutable updates with normal mutative code, like `state.todos[3].completed = true`.\n- `createAction()`: generates an action creator function for the given action type string. The function itself has `toString()` defined, so that it can be used in place of the type constant.\n- `createSlice()`: combines `createReducer()` + `createAction()`. Accepts an object of reducer functions, a slice name, and an initial state value, and automatically generates a slice reducer with corresponding action creators and action types.\n- `combineSlices()`: combines multiple slices into a single reducer, and allows \"lazy loading\" of slices after initialisation.\n- `createListenerMiddleware()`: lets you define \"listener\" entries that contain an \"effect\" callback with additional logic, and a way to specify when that callback should run based on dispatched actions or state changes. A lightweight alternative to Redux async middleware like sagas and observables.\n- `createAsyncThunk()`: accepts an action type string and a function that returns a promise, and generates a thunk that dispatches `pending/resolved/rejected` action types based on that promise\n- `createEntityAdapter()`: generates a set of reusable reducers and selectors to manage normalized data in the store\n- The `createSelector()` utility from the [Reselect](https://github.com/reduxjs/reselect) library, re-exported for ease of use.\n\nFor details, see [the Redux Toolkit API Reference section in the docs](https://redux-toolkit.js.org/api/configureStore).\n\n## RTK Query\n\n**RTK Query** is provided as an optional addon within the `@reduxjs/toolkit` package. It is purpose-built to solve the use case of data fetching and caching, supplying a compact, but powerful toolset to define an API interface layer for your app. It is intended to simplify common cases for loading data in a web application, eliminating the need to hand-write data fetching & caching logic yourself.\n\nRTK Query is built on top of the Redux Toolkit core for its implementation, using [Redux](https://redux.js.org/) internally for its architecture. Although knowledge of Redux and RTK are not required to use RTK Query, you should explore all of the additional global store management capabilities they provide, as well as installing the [Redux DevTools browser extension](https://github.com/reduxjs/redux-devtools), which works flawlessly with RTK Query to traverse and replay a timeline of your request & cache behavior.\n\nRTK Query is included within the installation of the core Redux Toolkit package. It is available via either of the two entry points below:\n\n```ts no-transpile\nimport { createApi } from '@reduxjs/toolkit/query'\n\n/* React-specific entry point that automatically generates\n   hooks corresponding to the defined endpoints */\nimport { createApi } from '@reduxjs/toolkit/query/react'\n```\n\n### What's included\n\nRTK Query includes these APIs:\n\n- `createApi()`: The core of RTK Query's functionality. It allows you to define a set of endpoints describe how to retrieve data from a series of endpoints, including configuration of how to fetch and transform that data. In most cases, you should use this once per app, with \"one API slice per base URL\" as a rule of thumb.\n- `fetchBaseQuery()`: A small wrapper around fetch that aims to simplify requests. Intended as the recommended baseQuery to be used in createApi for the majority of users.\n- `<ApiProvider />`: Can be used as a Provider if you do not already have a Redux store.\n- `setupListeners()`: A utility used to enable refetchOnMount and refetchOnReconnect behaviors.\n\nSee the [**RTK Query Overview**](https://redux-toolkit.js.org/rtk-query/overview) page for more details on what RTK Query is, what problems it solves, and how to use it.\n\n## Contributing\n\nPlease refer to our [contributing guide](/CONTRIBUTING.md) to learn about our development process, how to propose bugfixes and improvements, and how to build and test your changes to Redux Toolkit.\n"
  },
  {
    "path": "packages/toolkit/api-extractor-react.json",
    "content": "/**\n * Config file for API Extractor.  For more info, please visit: https://api-extractor.com\n */\n{\n  \"$schema\": \"https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json\",\n\n  /**\n   * Optionally specifies another JSON config file that this file extends from.  This provides a way for\n   * standard settings to be shared across multiple projects.\n   *\n   * If the path starts with \"./\" or \"../\", the path is resolved relative to the folder of the file that contains\n   * the \"extends\" field.  Otherwise, the first path segment is interpreted as an NPM package name, and will be\n   * resolved using NodeJS require().\n   *\n   * SUPPORTED TOKENS: none\n   * DEFAULT VALUE: \"\"\n   */\n  // \"extends\": \"./shared/api-extractor-base.json\"\n  // \"extends\": \"my-package/include/api-extractor-base.json\"\n\n  /**\n   * Determines the \"<projectFolder>\" token that can be used with other config file settings.  The project folder\n   * typically contains the tsconfig.json and package.json config files, but the path is user-defined.\n   *\n   * The path is resolved relative to the folder of the config file that contains the setting.\n   *\n   * The default value for \"projectFolder\" is the token \"<lookup>\", which means the folder is determined by traversing\n   * parent folders, starting from the folder containing api-extractor.json, and stopping at the first folder\n   * that contains a tsconfig.json file.  If a tsconfig.json file cannot be found in this way, then an error\n   * will be reported.\n   *\n   * SUPPORTED TOKENS: <lookup>\n   * DEFAULT VALUE: \"<lookup>\"\n   */\n  \"projectFolder\": \".\",\n\n  /**\n   * (REQUIRED) Specifies the .d.ts file to be used as the starting point for analysis.  API Extractor\n   * analyzes the symbols exported by this module.\n   *\n   * The file extension must be \".d.ts\" and not \".ts\".\n   *\n   * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n   * prepend a folder token such as \"<projectFolder>\".\n   *\n   * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n   */\n  \"mainEntryPointFilePath\": \"dist/react/index.d.ts\",\n  //\"mainEntryPointFilePath\": \"/home/weber/tmp/rtk-origin-master/dist/index.d.ts\",\n\n  /**\n   * A list of NPM package names whose exports should be treated as part of this package.\n   *\n   * For example, suppose that Webpack is used to generate a distributed bundle for the project \"library1\",\n   * and another NPM package \"library2\" is embedded in this bundle.  Some types from library2 may become part\n   * of the exported API for library1, but by default API Extractor would generate a .d.ts rollup that explicitly\n   * imports library2.  To avoid this, we can specify:\n   *\n   *   \"bundledPackages\": [ \"library2\" ],\n   *\n   * This would direct API Extractor to embed those types directly in the .d.ts rollup, as if they had been\n   * local files for library1.\n   */\n  \"bundledPackages\": [],\n\n  /**\n   * Determines how the TypeScript compiler engine will be invoked by API Extractor.\n   */\n  \"compiler\": {\n    /**\n     * Specifies the path to the tsconfig.json file to be used by API Extractor when analyzing the project.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * Note: This setting will be ignored if \"overrideTsconfig\" is used.\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/tsconfig.json\"\n     */\n    // \"tsconfigFilePath\": \"<projectFolder>/tsconfig.json\",\n    /**\n     * Provides a compiler configuration that will be used instead of reading the tsconfig.json file from disk.\n     * The object must conform to the TypeScript tsconfig schema:\n     *\n     * http://json.schemastore.org/tsconfig\n     *\n     * If omitted, then the tsconfig.json file will be read from the \"projectFolder\".\n     *\n     * DEFAULT VALUE: no overrideTsconfig section\n     */\n    // \"overrideTsconfig\": {\n    //   . . .\n    // }\n    /**\n     * This option causes the compiler to be invoked with the --skipLibCheck option. This option is not recommended\n     * and may cause API Extractor to produce incomplete or incorrect declarations, but it may be required when\n     * dependencies contain declarations that are incompatible with the TypeScript engine that API Extractor uses\n     * for its analysis.  Where possible, the underlying issue should be fixed rather than relying on skipLibCheck.\n     *\n     * DEFAULT VALUE: false\n     */\n    // \"skipLibCheck\": true,\n  },\n\n  /**\n   * Configures how the API report file (*.api.md) will be generated.\n   */\n  \"apiReport\": {\n    /**\n     * (REQUIRED) Whether to generate an API report.\n     */\n    \"enabled\": true,\n\n    /**\n     * The filename for the API report files.  It will be combined with \"reportFolder\" or \"reportTempFolder\" to produce\n     * a full file path.\n     *\n     * The file extension should be \".api.md\", and the string should not contain a path separator such as \"\\\" or \"/\".\n     *\n     * SUPPORTED TOKENS: <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<unscopedPackageName>.api.md\"\n     */\n    \"reportFileName\": \"redux-toolkit-react.api.md\",\n\n    /**\n     * Specifies the folder where the API report file is written.  The file name portion is determined by\n     * the \"reportFileName\" setting.\n     *\n     * The API report file is normally tracked by Git.  Changes to it can be used to trigger a branch policy,\n     * e.g. for an API review.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/etc/\"\n     */\n    \"reportFolder\": \"<projectFolder>/etc/\"\n\n    /**\n     * Specifies the folder where the temporary report file is written.  The file name portion is determined by\n     * the \"reportFileName\" setting.\n     *\n     * After the temporary file is written to disk, it is compared with the file in the \"reportFolder\".\n     * If they are different, a production build will fail.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/temp/\"\n     */\n    // \"reportTempFolder\": \"<projectFolder>/temp/\"\n  },\n\n  /**\n   * Configures how the doc model file (*.api.json) will be generated.\n   */\n  \"docModel\": {\n    /**\n     * (REQUIRED) Whether to generate a doc model file.\n     */\n    \"enabled\": false\n\n    /**\n     * The output path for the doc model file.  The file extension should be \".api.json\".\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/temp/<unscopedPackageName>.api.json\"\n     */\n    // \"apiJsonFilePath\": \"<projectFolder>/temp/<unscopedPackageName>.api.json\"\n  },\n\n  /**\n   * Configures how the .d.ts rollup file will be generated.\n   */\n  \"dtsRollup\": {\n    /**\n     * (REQUIRED) Whether to generate the .d.ts rollup file.\n     */\n    \"enabled\": false,\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated without any trimming.\n     * This file will include all declarations that are exported by the main entry point.\n     *\n     * If the path is an empty string, then this file will not be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/dist/<unscopedPackageName>.d.ts\"\n     */\n    \"untrimmedFilePath\": \"<projectFolder>/dist/react/typings.d.ts\"\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated with trimming for a \"beta\" release.\n     * This file will include only declarations that are marked as \"@public\" or \"@beta\".\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"\"\n     */\n    // \"betaTrimmedFilePath\": \"<projectFolder>/dist/<unscopedPackageName>-beta.d.ts\",\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated with trimming for a \"public\" release.\n     * This file will include only declarations that are marked as \"@public\".\n     *\n     * If the path is an empty string, then this file will not be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"\"\n     */\n    // \"publicTrimmedFilePath\": \"<projectFolder>/dist/<unscopedPackageName>-public.d.ts\",\n\n    /**\n     * When a declaration is trimmed, by default it will be replaced by a code comment such as\n     * \"Excluded from this release type: exampleMember\".  Set \"omitTrimmingComments\" to true to remove the\n     * declaration completely.\n     *\n     * DEFAULT VALUE: false\n     */\n    // \"omitTrimmingComments\": true\n  },\n\n  /**\n   * Configures how the tsdoc-metadata.json file will be generated.\n   */\n  \"tsdocMetadata\": {\n    /**\n     * Whether to generate the tsdoc-metadata.json file.\n     *\n     * DEFAULT VALUE: true\n     */\n    \"enabled\": false\n\n    /**\n     * Specifies where the TSDoc metadata file should be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * The default value is \"<lookup>\", which causes the path to be automatically inferred from the \"tsdocMetadata\",\n     * \"typings\" or \"main\" fields of the project's package.json.  If none of these fields are set, the lookup\n     * falls back to \"tsdoc-metadata.json\" in the package folder.\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<lookup>\"\n     */\n    // \"tsdocMetadataFilePath\": \"<projectFolder>/dist/tsdoc-metadata.json\"\n  },\n\n  /**\n   * Configures how API Extractor reports error and warning messages produced during analysis.\n   *\n   * There are three sources of messages:  compiler messages, API Extractor messages, and TSDoc messages.\n   */\n  \"messages\": {\n    /**\n     * Configures handling of diagnostic messages reported by the TypeScript compiler engine while analyzing\n     * the input .d.ts files.\n     *\n     * TypeScript message identifiers start with \"TS\" followed by an integer.  For example: \"TS2551\"\n     *\n     * DEFAULT VALUE:  A single \"default\" entry with logLevel=warning.\n     */\n    \"compilerMessageReporting\": {\n      /**\n       * Configures the default routing for messages that don't match an explicit rule in this table.\n       */\n      \"default\": {\n        /**\n         * Specifies whether the message should be written to the the tool's output log.  Note that\n         * the \"addToApiReportFile\" property may supersede this option.\n         *\n         * Possible values: \"error\", \"warning\", \"none\"\n         *\n         * Errors cause the build to fail and return a nonzero exit code.  Warnings cause a production build fail\n         * and return a nonzero exit code.  For a non-production build (e.g. when \"api-extractor run\" includes\n         * the \"--local\" option), the warning is displayed but the build will not fail.\n         *\n         * DEFAULT VALUE: \"warning\"\n         */\n        \"logLevel\": \"warning\"\n\n        /**\n         * When addToApiReportFile is true:  If API Extractor is configured to write an API report file (.api.md),\n         * then the message will be written inside that file; otherwise, the message is instead logged according to\n         * the \"logLevel\" option.\n         *\n         * DEFAULT VALUE: false\n         */\n        // \"addToApiReportFile\": false\n      }\n\n      // \"TS2551\": {\n      //   \"logLevel\": \"warning\",\n      //   \"addToApiReportFile\": true\n      // },\n      //\n      // . . .\n    },\n\n    /**\n     * Configures handling of messages reported by API Extractor during its analysis.\n     *\n     * API Extractor message identifiers start with \"ae-\".  For example: \"ae-extra-release-tag\"\n     *\n     * DEFAULT VALUE: See api-extractor-defaults.json for the complete table of extractorMessageReporting mappings\n     */\n    \"extractorMessageReporting\": {\n      \"default\": {\n        \"logLevel\": \"warning\"\n        // \"addToApiReportFile\": false\n      },\n      \"ae-forgotten-export\": {\n        \"logLevel\": \"none\",\n        \"addToApiReportFile\": false\n      }\n      //\n      // . . .\n    },\n\n    /**\n     * Configures handling of messages reported by the TSDoc parser when analyzing code comments.\n     *\n     * TSDoc message identifiers start with \"tsdoc-\".  For example: \"tsdoc-link-tag-unescaped-text\"\n     *\n     * DEFAULT VALUE:  A single \"default\" entry with logLevel=warning.\n     */\n    \"tsdocMessageReporting\": {\n      \"default\": {\n        \"logLevel\": \"none\"\n        // \"addToApiReportFile\": false\n      }\n\n      // \"tsdoc-link-tag-unescaped-text\": {\n      //   \"logLevel\": \"warning\",\n      //   \"addToApiReportFile\": true\n      // },\n      //\n      // . . .\n    }\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/api-extractor.json",
    "content": "/**\n * Config file for API Extractor.  For more info, please visit: https://api-extractor.com\n */\n{\n  \"$schema\": \"https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json\",\n\n  /**\n   * Optionally specifies another JSON config file that this file extends from.  This provides a way for\n   * standard settings to be shared across multiple projects.\n   *\n   * If the path starts with \"./\" or \"../\", the path is resolved relative to the folder of the file that contains\n   * the \"extends\" field.  Otherwise, the first path segment is interpreted as an NPM package name, and will be\n   * resolved using NodeJS require().\n   *\n   * SUPPORTED TOKENS: none\n   * DEFAULT VALUE: \"\"\n   */\n  // \"extends\": \"./shared/api-extractor-base.json\"\n  // \"extends\": \"my-package/include/api-extractor-base.json\"\n\n  /**\n   * Determines the \"<projectFolder>\" token that can be used with other config file settings.  The project folder\n   * typically contains the tsconfig.json and package.json config files, but the path is user-defined.\n   *\n   * The path is resolved relative to the folder of the config file that contains the setting.\n   *\n   * The default value for \"projectFolder\" is the token \"<lookup>\", which means the folder is determined by traversing\n   * parent folders, starting from the folder containing api-extractor.json, and stopping at the first folder\n   * that contains a tsconfig.json file.  If a tsconfig.json file cannot be found in this way, then an error\n   * will be reported.\n   *\n   * SUPPORTED TOKENS: <lookup>\n   * DEFAULT VALUE: \"<lookup>\"\n   */\n  \"projectFolder\": \".\",\n\n  /**\n   * (REQUIRED) Specifies the .d.ts file to be used as the starting point for analysis.  API Extractor\n   * analyzes the symbols exported by this module.\n   *\n   * The file extension must be \".d.ts\" and not \".ts\".\n   *\n   * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n   * prepend a folder token such as \"<projectFolder>\".\n   *\n   * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n   */\n  \"mainEntryPointFilePath\": \"dist/index.d.ts\",\n  //\"mainEntryPointFilePath\": \"/home/weber/tmp/rtk-origin-master/dist/index.d.ts\",\n\n  /**\n   * A list of NPM package names whose exports should be treated as part of this package.\n   *\n   * For example, suppose that Webpack is used to generate a distributed bundle for the project \"library1\",\n   * and another NPM package \"library2\" is embedded in this bundle.  Some types from library2 may become part\n   * of the exported API for library1, but by default API Extractor would generate a .d.ts rollup that explicitly\n   * imports library2.  To avoid this, we can specify:\n   *\n   *   \"bundledPackages\": [ \"library2\" ],\n   *\n   * This would direct API Extractor to embed those types directly in the .d.ts rollup, as if they had been\n   * local files for library1.\n   */\n  \"bundledPackages\": [],\n\n  /**\n   * Determines how the TypeScript compiler engine will be invoked by API Extractor.\n   */\n  \"compiler\": {\n    /**\n     * Specifies the path to the tsconfig.json file to be used by API Extractor when analyzing the project.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * Note: This setting will be ignored if \"overrideTsconfig\" is used.\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/tsconfig.json\"\n     */\n    // \"tsconfigFilePath\": \"<projectFolder>/tsconfig.json\",\n    /**\n     * Provides a compiler configuration that will be used instead of reading the tsconfig.json file from disk.\n     * The object must conform to the TypeScript tsconfig schema:\n     *\n     * http://json.schemastore.org/tsconfig\n     *\n     * If omitted, then the tsconfig.json file will be read from the \"projectFolder\".\n     *\n     * DEFAULT VALUE: no overrideTsconfig section\n     */\n    // \"overrideTsconfig\": {\n    //   . . .\n    // }\n    /**\n     * This option causes the compiler to be invoked with the --skipLibCheck option. This option is not recommended\n     * and may cause API Extractor to produce incomplete or incorrect declarations, but it may be required when\n     * dependencies contain declarations that are incompatible with the TypeScript engine that API Extractor uses\n     * for its analysis.  Where possible, the underlying issue should be fixed rather than relying on skipLibCheck.\n     *\n     * DEFAULT VALUE: false\n     */\n    // \"skipLibCheck\": true,\n  },\n\n  /**\n   * Configures how the API report file (*.api.md) will be generated.\n   */\n  \"apiReport\": {\n    /**\n     * (REQUIRED) Whether to generate an API report.\n     */\n    \"enabled\": true,\n\n    /**\n     * The filename for the API report files.  It will be combined with \"reportFolder\" or \"reportTempFolder\" to produce\n     * a full file path.\n     *\n     * The file extension should be \".api.md\", and the string should not contain a path separator such as \"\\\" or \"/\".\n     *\n     * SUPPORTED TOKENS: <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<unscopedPackageName>.api.md\"\n     */\n    \"reportFileName\": \"redux-toolkit.api.md\",\n\n    /**\n     * Specifies the folder where the API report file is written.  The file name portion is determined by\n     * the \"reportFileName\" setting.\n     *\n     * The API report file is normally tracked by Git.  Changes to it can be used to trigger a branch policy,\n     * e.g. for an API review.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/etc/\"\n     */\n    \"reportFolder\": \"<projectFolder>/etc/\"\n\n    /**\n     * Specifies the folder where the temporary report file is written.  The file name portion is determined by\n     * the \"reportFileName\" setting.\n     *\n     * After the temporary file is written to disk, it is compared with the file in the \"reportFolder\".\n     * If they are different, a production build will fail.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/temp/\"\n     */\n    // \"reportTempFolder\": \"<projectFolder>/temp/\"\n  },\n\n  /**\n   * Configures how the doc model file (*.api.json) will be generated.\n   */\n  \"docModel\": {\n    /**\n     * (REQUIRED) Whether to generate a doc model file.\n     */\n    \"enabled\": false\n\n    /**\n     * The output path for the doc model file.  The file extension should be \".api.json\".\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/temp/<unscopedPackageName>.api.json\"\n     */\n    // \"apiJsonFilePath\": \"<projectFolder>/temp/<unscopedPackageName>.api.json\"\n  },\n\n  /**\n   * Configures how the .d.ts rollup file will be generated.\n   */\n  \"dtsRollup\": {\n    /**\n     * (REQUIRED) Whether to generate the .d.ts rollup file.\n     */\n    \"enabled\": false,\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated without any trimming.\n     * This file will include all declarations that are exported by the main entry point.\n     *\n     * If the path is an empty string, then this file will not be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/dist/<unscopedPackageName>.d.ts\"\n     */\n    \"untrimmedFilePath\": \"<projectFolder>/dist/typings.d.ts\"\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated with trimming for a \"beta\" release.\n     * This file will include only declarations that are marked as \"@public\" or \"@beta\".\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"\"\n     */\n    // \"betaTrimmedFilePath\": \"<projectFolder>/dist/<unscopedPackageName>-beta.d.ts\",\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated with trimming for a \"public\" release.\n     * This file will include only declarations that are marked as \"@public\".\n     *\n     * If the path is an empty string, then this file will not be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"\"\n     */\n    // \"publicTrimmedFilePath\": \"<projectFolder>/dist/<unscopedPackageName>-public.d.ts\",\n\n    /**\n     * When a declaration is trimmed, by default it will be replaced by a code comment such as\n     * \"Excluded from this release type: exampleMember\".  Set \"omitTrimmingComments\" to true to remove the\n     * declaration completely.\n     *\n     * DEFAULT VALUE: false\n     */\n    // \"omitTrimmingComments\": true\n  },\n\n  /**\n   * Configures how the tsdoc-metadata.json file will be generated.\n   */\n  \"tsdocMetadata\": {\n    /**\n     * Whether to generate the tsdoc-metadata.json file.\n     *\n     * DEFAULT VALUE: true\n     */\n    \"enabled\": false\n\n    /**\n     * Specifies where the TSDoc metadata file should be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * The default value is \"<lookup>\", which causes the path to be automatically inferred from the \"tsdocMetadata\",\n     * \"typings\" or \"main\" fields of the project's package.json.  If none of these fields are set, the lookup\n     * falls back to \"tsdoc-metadata.json\" in the package folder.\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<lookup>\"\n     */\n    // \"tsdocMetadataFilePath\": \"<projectFolder>/dist/tsdoc-metadata.json\"\n  },\n\n  /**\n   * Configures how API Extractor reports error and warning messages produced during analysis.\n   *\n   * There are three sources of messages:  compiler messages, API Extractor messages, and TSDoc messages.\n   */\n  \"messages\": {\n    /**\n     * Configures handling of diagnostic messages reported by the TypeScript compiler engine while analyzing\n     * the input .d.ts files.\n     *\n     * TypeScript message identifiers start with \"TS\" followed by an integer.  For example: \"TS2551\"\n     *\n     * DEFAULT VALUE:  A single \"default\" entry with logLevel=warning.\n     */\n    \"compilerMessageReporting\": {\n      /**\n       * Configures the default routing for messages that don't match an explicit rule in this table.\n       */\n      \"default\": {\n        /**\n         * Specifies whether the message should be written to the the tool's output log.  Note that\n         * the \"addToApiReportFile\" property may supersede this option.\n         *\n         * Possible values: \"error\", \"warning\", \"none\"\n         *\n         * Errors cause the build to fail and return a nonzero exit code.  Warnings cause a production build fail\n         * and return a nonzero exit code.  For a non-production build (e.g. when \"api-extractor run\" includes\n         * the \"--local\" option), the warning is displayed but the build will not fail.\n         *\n         * DEFAULT VALUE: \"warning\"\n         */\n        \"logLevel\": \"warning\"\n\n        /**\n         * When addToApiReportFile is true:  If API Extractor is configured to write an API report file (.api.md),\n         * then the message will be written inside that file; otherwise, the message is instead logged according to\n         * the \"logLevel\" option.\n         *\n         * DEFAULT VALUE: false\n         */\n        // \"addToApiReportFile\": false\n      }\n\n      // \"TS2551\": {\n      //   \"logLevel\": \"warning\",\n      //   \"addToApiReportFile\": true\n      // },\n      //\n      // . . .\n    },\n\n    /**\n     * Configures handling of messages reported by API Extractor during its analysis.\n     *\n     * API Extractor message identifiers start with \"ae-\".  For example: \"ae-extra-release-tag\"\n     *\n     * DEFAULT VALUE: See api-extractor-defaults.json for the complete table of extractorMessageReporting mappings\n     */\n    \"extractorMessageReporting\": {\n      \"default\": {\n        \"logLevel\": \"warning\"\n        // \"addToApiReportFile\": false\n      },\n      \"ae-forgotten-export\": {\n        \"logLevel\": \"none\",\n        \"addToApiReportFile\": false\n      }\n      //\n      // . . .\n    },\n\n    /**\n     * Configures handling of messages reported by the TSDoc parser when analyzing code comments.\n     *\n     * TSDoc message identifiers start with \"tsdoc-\".  For example: \"tsdoc-link-tag-unescaped-text\"\n     *\n     * DEFAULT VALUE:  A single \"default\" entry with logLevel=warning.\n     */\n    \"tsdocMessageReporting\": {\n      \"default\": {\n        \"logLevel\": \"none\"\n        // \"addToApiReportFile\": false\n      }\n\n      // \"tsdoc-link-tag-unescaped-text\": {\n      //   \"logLevel\": \"warning\",\n      //   \"addToApiReportFile\": true\n      // },\n      //\n      // . . .\n    }\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/api-extractor.query-react.json",
    "content": "/**\n * Config file for API Extractor.  For more info, please visit: https://api-extractor.com\n */\n{\n  \"$schema\": \"https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json\",\n\n  /**\n   * Optionally specifies another JSON config file that this file extends from.  This provides a way for\n   * standard settings to be shared across multiple projects.\n   *\n   * If the path starts with \"./\" or \"../\", the path is resolved relative to the folder of the file that contains\n   * the \"extends\" field.  Otherwise, the first path segment is interpreted as an NPM package name, and will be\n   * resolved using NodeJS require().\n   *\n   * SUPPORTED TOKENS: none\n   * DEFAULT VALUE: \"\"\n   */\n  // \"extends\": \"./shared/api-extractor-base.json\"\n  // \"extends\": \"my-package/include/api-extractor-base.json\"\n\n  /**\n   * Determines the \"<projectFolder>\" token that can be used with other config file settings.  The project folder\n   * typically contains the tsconfig.json and package.json config files, but the path is user-defined.\n   *\n   * The path is resolved relative to the folder of the config file that contains the setting.\n   *\n   * The default value for \"projectFolder\" is the token \"<lookup>\", which means the folder is determined by traversing\n   * parent folders, starting from the folder containing api-extractor.json, and stopping at the first folder\n   * that contains a tsconfig.json file.  If a tsconfig.json file cannot be found in this way, then an error\n   * will be reported.\n   *\n   * SUPPORTED TOKENS: <lookup>\n   * DEFAULT VALUE: \"<lookup>\"\n   */\n  \"projectFolder\": \".\",\n\n  /**\n   * (REQUIRED) Specifies the .d.ts file to be used as the starting point for analysis.  API Extractor\n   * analyzes the symbols exported by this module.\n   *\n   * The file extension must be \".d.ts\" and not \".ts\".\n   *\n   * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n   * prepend a folder token such as \"<projectFolder>\".\n   *\n   * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n   */\n  \"mainEntryPointFilePath\": \"dist/query/react/index.d.ts\",\n  //\"mainEntryPointFilePath\": \"/home/weber/tmp/rtk-origin-master/dist/index.d.ts\",\n\n  /**\n   * A list of NPM package names whose exports should be treated as part of this package.\n   *\n   * For example, suppose that Webpack is used to generate a distributed bundle for the project \"library1\",\n   * and another NPM package \"library2\" is embedded in this bundle.  Some types from library2 may become part\n   * of the exported API for library1, but by default API Extractor would generate a .d.ts rollup that explicitly\n   * imports library2.  To avoid this, we can specify:\n   *\n   *   \"bundledPackages\": [ \"library2\" ],\n   *\n   * This would direct API Extractor to embed those types directly in the .d.ts rollup, as if they had been\n   * local files for library1.\n   */\n  \"bundledPackages\": [],\n\n  /**\n   * Determines how the TypeScript compiler engine will be invoked by API Extractor.\n   */\n  \"compiler\": {\n    /**\n     * Specifies the path to the tsconfig.json file to be used by API Extractor when analyzing the project.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * Note: This setting will be ignored if \"overrideTsconfig\" is used.\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/tsconfig.json\"\n     */\n    // \"tsconfigFilePath\": \"<projectFolder>/tsconfig.json\",\n    /**\n     * Provides a compiler configuration that will be used instead of reading the tsconfig.json file from disk.\n     * The object must conform to the TypeScript tsconfig schema:\n     *\n     * http://json.schemastore.org/tsconfig\n     *\n     * If omitted, then the tsconfig.json file will be read from the \"projectFolder\".\n     *\n     * DEFAULT VALUE: no overrideTsconfig section\n     */\n    // \"overrideTsconfig\": {\n    //   . . .\n    // }\n    /**\n     * This option causes the compiler to be invoked with the --skipLibCheck option. This option is not recommended\n     * and may cause API Extractor to produce incomplete or incorrect declarations, but it may be required when\n     * dependencies contain declarations that are incompatible with the TypeScript engine that API Extractor uses\n     * for its analysis.  Where possible, the underlying issue should be fixed rather than relying on skipLibCheck.\n     *\n     * DEFAULT VALUE: false\n     */\n    // \"skipLibCheck\": true,\n  },\n\n  /**\n   * Configures how the API report file (*.api.md) will be generated.\n   */\n  \"apiReport\": {\n    /**\n     * (REQUIRED) Whether to generate an API report.\n     */\n    \"enabled\": true,\n\n    /**\n     * The filename for the API report files.  It will be combined with \"reportFolder\" or \"reportTempFolder\" to produce\n     * a full file path.\n     *\n     * The file extension should be \".api.md\", and the string should not contain a path separator such as \"\\\" or \"/\".\n     *\n     * SUPPORTED TOKENS: <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<unscopedPackageName>.api.md\"\n     */\n    \"reportFileName\": \"rtk-query-react.api.md\",\n\n    /**\n     * Specifies the folder where the API report file is written.  The file name portion is determined by\n     * the \"reportFileName\" setting.\n     *\n     * The API report file is normally tracked by Git.  Changes to it can be used to trigger a branch policy,\n     * e.g. for an API review.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/etc/\"\n     */\n    \"reportFolder\": \"<projectFolder>/etc/\"\n\n    /**\n     * Specifies the folder where the temporary report file is written.  The file name portion is determined by\n     * the \"reportFileName\" setting.\n     *\n     * After the temporary file is written to disk, it is compared with the file in the \"reportFolder\".\n     * If they are different, a production build will fail.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/temp/\"\n     */\n    // \"reportTempFolder\": \"<projectFolder>/temp/\"\n  },\n\n  /**\n   * Configures how the doc model file (*.api.json) will be generated.\n   */\n  \"docModel\": {\n    /**\n     * (REQUIRED) Whether to generate a doc model file.\n     */\n    \"enabled\": false\n\n    /**\n     * The output path for the doc model file.  The file extension should be \".api.json\".\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/temp/<unscopedPackageName>.api.json\"\n     */\n    // \"apiJsonFilePath\": \"<projectFolder>/temp/<unscopedPackageName>.api.json\"\n  },\n\n  /**\n   * Configures how the .d.ts rollup file will be generated.\n   */\n  \"dtsRollup\": {\n    /**\n     * (REQUIRED) Whether to generate the .d.ts rollup file.\n     */\n    \"enabled\": false,\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated without any trimming.\n     * This file will include all declarations that are exported by the main entry point.\n     *\n     * If the path is an empty string, then this file will not be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/dist/<unscopedPackageName>.d.ts\"\n     */\n    \"untrimmedFilePath\": \"<projectFolder>/dist/query/react/typings.d.ts\"\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated with trimming for a \"beta\" release.\n     * This file will include only declarations that are marked as \"@public\" or \"@beta\".\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"\"\n     */\n    // \"betaTrimmedFilePath\": \"<projectFolder>/dist/<unscopedPackageName>-beta.d.ts\",\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated with trimming for a \"public\" release.\n     * This file will include only declarations that are marked as \"@public\".\n     *\n     * If the path is an empty string, then this file will not be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"\"\n     */\n    // \"publicTrimmedFilePath\": \"<projectFolder>/dist/<unscopedPackageName>-public.d.ts\",\n\n    /**\n     * When a declaration is trimmed, by default it will be replaced by a code comment such as\n     * \"Excluded from this release type: exampleMember\".  Set \"omitTrimmingComments\" to true to remove the\n     * declaration completely.\n     *\n     * DEFAULT VALUE: false\n     */\n    // \"omitTrimmingComments\": true\n  },\n\n  /**\n   * Configures how the tsdoc-metadata.json file will be generated.\n   */\n  \"tsdocMetadata\": {\n    /**\n     * Whether to generate the tsdoc-metadata.json file.\n     *\n     * DEFAULT VALUE: true\n     */\n    \"enabled\": false\n\n    /**\n     * Specifies where the TSDoc metadata file should be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * The default value is \"<lookup>\", which causes the path to be automatically inferred from the \"tsdocMetadata\",\n     * \"typings\" or \"main\" fields of the project's package.json.  If none of these fields are set, the lookup\n     * falls back to \"tsdoc-metadata.json\" in the package folder.\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<lookup>\"\n     */\n    // \"tsdocMetadataFilePath\": \"<projectFolder>/dist/tsdoc-metadata.json\"\n  },\n\n  /**\n   * Configures how API Extractor reports error and warning messages produced during analysis.\n   *\n   * There are three sources of messages:  compiler messages, API Extractor messages, and TSDoc messages.\n   */\n  \"messages\": {\n    /**\n     * Configures handling of diagnostic messages reported by the TypeScript compiler engine while analyzing\n     * the input .d.ts files.\n     *\n     * TypeScript message identifiers start with \"TS\" followed by an integer.  For example: \"TS2551\"\n     *\n     * DEFAULT VALUE:  A single \"default\" entry with logLevel=warning.\n     */\n    \"compilerMessageReporting\": {\n      /**\n       * Configures the default routing for messages that don't match an explicit rule in this table.\n       */\n      \"default\": {\n        /**\n         * Specifies whether the message should be written to the the tool's output log.  Note that\n         * the \"addToApiReportFile\" property may supersede this option.\n         *\n         * Possible values: \"error\", \"warning\", \"none\"\n         *\n         * Errors cause the build to fail and return a nonzero exit code.  Warnings cause a production build fail\n         * and return a nonzero exit code.  For a non-production build (e.g. when \"api-extractor run\" includes\n         * the \"--local\" option), the warning is displayed but the build will not fail.\n         *\n         * DEFAULT VALUE: \"warning\"\n         */\n        \"logLevel\": \"warning\"\n\n        /**\n         * When addToApiReportFile is true:  If API Extractor is configured to write an API report file (.api.md),\n         * then the message will be written inside that file; otherwise, the message is instead logged according to\n         * the \"logLevel\" option.\n         *\n         * DEFAULT VALUE: false\n         */\n        // \"addToApiReportFile\": false\n      }\n\n      // \"TS2551\": {\n      //   \"logLevel\": \"warning\",\n      //   \"addToApiReportFile\": true\n      // },\n      //\n      // . . .\n    },\n\n    /**\n     * Configures handling of messages reported by API Extractor during its analysis.\n     *\n     * API Extractor message identifiers start with \"ae-\".  For example: \"ae-extra-release-tag\"\n     *\n     * DEFAULT VALUE: See api-extractor-defaults.json for the complete table of extractorMessageReporting mappings\n     */\n    \"extractorMessageReporting\": {\n      \"default\": {\n        \"logLevel\": \"warning\"\n        // \"addToApiReportFile\": false\n      },\n      \"ae-forgotten-export\": {\n        \"logLevel\": \"none\",\n        \"addToApiReportFile\": false\n      }\n      //\n      // . . .\n    },\n\n    /**\n     * Configures handling of messages reported by the TSDoc parser when analyzing code comments.\n     *\n     * TSDoc message identifiers start with \"tsdoc-\".  For example: \"tsdoc-link-tag-unescaped-text\"\n     *\n     * DEFAULT VALUE:  A single \"default\" entry with logLevel=warning.\n     */\n    \"tsdocMessageReporting\": {\n      \"default\": {\n        \"logLevel\": \"none\"\n        // \"addToApiReportFile\": false\n      }\n\n      // \"tsdoc-link-tag-unescaped-text\": {\n      //   \"logLevel\": \"warning\",\n      //   \"addToApiReportFile\": true\n      // },\n      //\n      // . . .\n    }\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/api-extractor.query.json",
    "content": "/**\n * Config file for API Extractor.  For more info, please visit: https://api-extractor.com\n */\n{\n  \"$schema\": \"https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json\",\n\n  /**\n   * Optionally specifies another JSON config file that this file extends from.  This provides a way for\n   * standard settings to be shared across multiple projects.\n   *\n   * If the path starts with \"./\" or \"../\", the path is resolved relative to the folder of the file that contains\n   * the \"extends\" field.  Otherwise, the first path segment is interpreted as an NPM package name, and will be\n   * resolved using NodeJS require().\n   *\n   * SUPPORTED TOKENS: none\n   * DEFAULT VALUE: \"\"\n   */\n  // \"extends\": \"./shared/api-extractor-base.json\"\n  // \"extends\": \"my-package/include/api-extractor-base.json\"\n\n  /**\n   * Determines the \"<projectFolder>\" token that can be used with other config file settings.  The project folder\n   * typically contains the tsconfig.json and package.json config files, but the path is user-defined.\n   *\n   * The path is resolved relative to the folder of the config file that contains the setting.\n   *\n   * The default value for \"projectFolder\" is the token \"<lookup>\", which means the folder is determined by traversing\n   * parent folders, starting from the folder containing api-extractor.json, and stopping at the first folder\n   * that contains a tsconfig.json file.  If a tsconfig.json file cannot be found in this way, then an error\n   * will be reported.\n   *\n   * SUPPORTED TOKENS: <lookup>\n   * DEFAULT VALUE: \"<lookup>\"\n   */\n  \"projectFolder\": \".\",\n\n  /**\n   * (REQUIRED) Specifies the .d.ts file to be used as the starting point for analysis.  API Extractor\n   * analyzes the symbols exported by this module.\n   *\n   * The file extension must be \".d.ts\" and not \".ts\".\n   *\n   * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n   * prepend a folder token such as \"<projectFolder>\".\n   *\n   * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n   */\n  \"mainEntryPointFilePath\": \"dist/query/index.d.ts\",\n  //\"mainEntryPointFilePath\": \"/home/weber/tmp/rtk-origin-master/dist/index.d.ts\",\n\n  /**\n   * A list of NPM package names whose exports should be treated as part of this package.\n   *\n   * For example, suppose that Webpack is used to generate a distributed bundle for the project \"library1\",\n   * and another NPM package \"library2\" is embedded in this bundle.  Some types from library2 may become part\n   * of the exported API for library1, but by default API Extractor would generate a .d.ts rollup that explicitly\n   * imports library2.  To avoid this, we can specify:\n   *\n   *   \"bundledPackages\": [ \"library2\" ],\n   *\n   * This would direct API Extractor to embed those types directly in the .d.ts rollup, as if they had been\n   * local files for library1.\n   */\n  \"bundledPackages\": [],\n\n  /**\n   * Determines how the TypeScript compiler engine will be invoked by API Extractor.\n   */\n  \"compiler\": {\n    /**\n     * Specifies the path to the tsconfig.json file to be used by API Extractor when analyzing the project.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * Note: This setting will be ignored if \"overrideTsconfig\" is used.\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/tsconfig.json\"\n     */\n    // \"tsconfigFilePath\": \"<projectFolder>/tsconfig.json\",\n    /**\n     * Provides a compiler configuration that will be used instead of reading the tsconfig.json file from disk.\n     * The object must conform to the TypeScript tsconfig schema:\n     *\n     * http://json.schemastore.org/tsconfig\n     *\n     * If omitted, then the tsconfig.json file will be read from the \"projectFolder\".\n     *\n     * DEFAULT VALUE: no overrideTsconfig section\n     */\n    // \"overrideTsconfig\": {\n    //   . . .\n    // }\n    /**\n     * This option causes the compiler to be invoked with the --skipLibCheck option. This option is not recommended\n     * and may cause API Extractor to produce incomplete or incorrect declarations, but it may be required when\n     * dependencies contain declarations that are incompatible with the TypeScript engine that API Extractor uses\n     * for its analysis.  Where possible, the underlying issue should be fixed rather than relying on skipLibCheck.\n     *\n     * DEFAULT VALUE: false\n     */\n    // \"skipLibCheck\": true,\n  },\n\n  /**\n   * Configures how the API report file (*.api.md) will be generated.\n   */\n  \"apiReport\": {\n    /**\n     * (REQUIRED) Whether to generate an API report.\n     */\n    \"enabled\": true,\n\n    /**\n     * The filename for the API report files.  It will be combined with \"reportFolder\" or \"reportTempFolder\" to produce\n     * a full file path.\n     *\n     * The file extension should be \".api.md\", and the string should not contain a path separator such as \"\\\" or \"/\".\n     *\n     * SUPPORTED TOKENS: <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<unscopedPackageName>.api.md\"\n     */\n    \"reportFileName\": \"rtk-query.api.md\",\n\n    /**\n     * Specifies the folder where the API report file is written.  The file name portion is determined by\n     * the \"reportFileName\" setting.\n     *\n     * The API report file is normally tracked by Git.  Changes to it can be used to trigger a branch policy,\n     * e.g. for an API review.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/etc/\"\n     */\n    \"reportFolder\": \"<projectFolder>/etc/\"\n\n    /**\n     * Specifies the folder where the temporary report file is written.  The file name portion is determined by\n     * the \"reportFileName\" setting.\n     *\n     * After the temporary file is written to disk, it is compared with the file in the \"reportFolder\".\n     * If they are different, a production build will fail.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/temp/\"\n     */\n    // \"reportTempFolder\": \"<projectFolder>/temp/\"\n  },\n\n  /**\n   * Configures how the doc model file (*.api.json) will be generated.\n   */\n  \"docModel\": {\n    /**\n     * (REQUIRED) Whether to generate a doc model file.\n     */\n    \"enabled\": false\n\n    /**\n     * The output path for the doc model file.  The file extension should be \".api.json\".\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/temp/<unscopedPackageName>.api.json\"\n     */\n    // \"apiJsonFilePath\": \"<projectFolder>/temp/<unscopedPackageName>.api.json\"\n  },\n\n  /**\n   * Configures how the .d.ts rollup file will be generated.\n   */\n  \"dtsRollup\": {\n    /**\n     * (REQUIRED) Whether to generate the .d.ts rollup file.\n     */\n    \"enabled\": false,\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated without any trimming.\n     * This file will include all declarations that are exported by the main entry point.\n     *\n     * If the path is an empty string, then this file will not be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<projectFolder>/dist/<unscopedPackageName>.d.ts\"\n     */\n    \"untrimmedFilePath\": \"<projectFolder>/dist/query/typings.d.ts\"\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated with trimming for a \"beta\" release.\n     * This file will include only declarations that are marked as \"@public\" or \"@beta\".\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"\"\n     */\n    // \"betaTrimmedFilePath\": \"<projectFolder>/dist/<unscopedPackageName>-beta.d.ts\",\n\n    /**\n     * Specifies the output path for a .d.ts rollup file to be generated with trimming for a \"public\" release.\n     * This file will include only declarations that are marked as \"@public\".\n     *\n     * If the path is an empty string, then this file will not be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"\"\n     */\n    // \"publicTrimmedFilePath\": \"<projectFolder>/dist/<unscopedPackageName>-public.d.ts\",\n\n    /**\n     * When a declaration is trimmed, by default it will be replaced by a code comment such as\n     * \"Excluded from this release type: exampleMember\".  Set \"omitTrimmingComments\" to true to remove the\n     * declaration completely.\n     *\n     * DEFAULT VALUE: false\n     */\n    // \"omitTrimmingComments\": true\n  },\n\n  /**\n   * Configures how the tsdoc-metadata.json file will be generated.\n   */\n  \"tsdocMetadata\": {\n    /**\n     * Whether to generate the tsdoc-metadata.json file.\n     *\n     * DEFAULT VALUE: true\n     */\n    \"enabled\": false\n\n    /**\n     * Specifies where the TSDoc metadata file should be written.\n     *\n     * The path is resolved relative to the folder of the config file that contains the setting; to change this,\n     * prepend a folder token such as \"<projectFolder>\".\n     *\n     * The default value is \"<lookup>\", which causes the path to be automatically inferred from the \"tsdocMetadata\",\n     * \"typings\" or \"main\" fields of the project's package.json.  If none of these fields are set, the lookup\n     * falls back to \"tsdoc-metadata.json\" in the package folder.\n     *\n     * SUPPORTED TOKENS: <projectFolder>, <packageName>, <unscopedPackageName>\n     * DEFAULT VALUE: \"<lookup>\"\n     */\n    // \"tsdocMetadataFilePath\": \"<projectFolder>/dist/tsdoc-metadata.json\"\n  },\n\n  /**\n   * Configures how API Extractor reports error and warning messages produced during analysis.\n   *\n   * There are three sources of messages:  compiler messages, API Extractor messages, and TSDoc messages.\n   */\n  \"messages\": {\n    /**\n     * Configures handling of diagnostic messages reported by the TypeScript compiler engine while analyzing\n     * the input .d.ts files.\n     *\n     * TypeScript message identifiers start with \"TS\" followed by an integer.  For example: \"TS2551\"\n     *\n     * DEFAULT VALUE:  A single \"default\" entry with logLevel=warning.\n     */\n    \"compilerMessageReporting\": {\n      /**\n       * Configures the default routing for messages that don't match an explicit rule in this table.\n       */\n      \"default\": {\n        /**\n         * Specifies whether the message should be written to the the tool's output log.  Note that\n         * the \"addToApiReportFile\" property may supersede this option.\n         *\n         * Possible values: \"error\", \"warning\", \"none\"\n         *\n         * Errors cause the build to fail and return a nonzero exit code.  Warnings cause a production build fail\n         * and return a nonzero exit code.  For a non-production build (e.g. when \"api-extractor run\" includes\n         * the \"--local\" option), the warning is displayed but the build will not fail.\n         *\n         * DEFAULT VALUE: \"warning\"\n         */\n        \"logLevel\": \"warning\"\n\n        /**\n         * When addToApiReportFile is true:  If API Extractor is configured to write an API report file (.api.md),\n         * then the message will be written inside that file; otherwise, the message is instead logged according to\n         * the \"logLevel\" option.\n         *\n         * DEFAULT VALUE: false\n         */\n        // \"addToApiReportFile\": false\n      }\n\n      // \"TS2551\": {\n      //   \"logLevel\": \"warning\",\n      //   \"addToApiReportFile\": true\n      // },\n      //\n      // . . .\n    },\n\n    /**\n     * Configures handling of messages reported by API Extractor during its analysis.\n     *\n     * API Extractor message identifiers start with \"ae-\".  For example: \"ae-extra-release-tag\"\n     *\n     * DEFAULT VALUE: See api-extractor-defaults.json for the complete table of extractorMessageReporting mappings\n     */\n    \"extractorMessageReporting\": {\n      \"default\": {\n        \"logLevel\": \"warning\"\n        // \"addToApiReportFile\": false\n      },\n      \"ae-forgotten-export\": {\n        \"logLevel\": \"none\",\n        \"addToApiReportFile\": false\n      }\n      //\n      // . . .\n    },\n\n    /**\n     * Configures handling of messages reported by the TSDoc parser when analyzing code comments.\n     *\n     * TSDoc message identifiers start with \"tsdoc-\".  For example: \"tsdoc-link-tag-unescaped-text\"\n     *\n     * DEFAULT VALUE:  A single \"default\" entry with logLevel=warning.\n     */\n    \"tsdocMessageReporting\": {\n      \"default\": {\n        \"logLevel\": \"none\"\n        // \"addToApiReportFile\": false\n      }\n\n      // \"tsdoc-link-tag-unescaped-text\": {\n      //   \"logLevel\": \"warning\",\n      //   \"addToApiReportFile\": true\n      // },\n      //\n      // . . .\n    }\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/etc/redux-toolkit.api.md",
    "content": "## API Report File for \"@reduxjs/toolkit\"\r\n\r\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\r\n\r\n```ts\r\nimport type { Action } from 'redux'\r\nimport type { ActionCreator } from 'redux'\r\nimport type { UnknownAction } from 'redux'\r\nimport type { CombinedState } from 'redux'\r\nimport { default as createNextState } from 'immer'\r\nimport { createSelector } from 'reselect'\r\nimport { current } from 'immer'\r\nimport type { Dispatch } from 'redux'\r\nimport { Draft } from 'immer'\r\nimport { freeze } from 'immer'\r\nimport { isDraft } from 'immer'\r\nimport type { Middleware } from 'redux'\r\nimport { original } from 'immer'\r\nimport { OutputParametricSelector } from 'reselect'\r\nimport { OutputSelector } from 'reselect'\r\nimport { ParametricSelector } from 'reselect'\r\nimport type { PreloadedState } from 'redux'\r\nimport type { Reducer } from 'redux'\r\nimport type { ReducersMapObject } from 'redux'\r\nimport { Selector } from 'reselect'\r\nimport type { Store } from 'redux'\r\nimport type { StoreEnhancer } from 'redux'\r\nimport { ThunkAction } from 'redux-thunk'\r\nimport { ThunkDispatch } from 'redux-thunk'\r\nimport type { ThunkMiddleware } from 'redux-thunk'\r\n\r\n// @public\r\nexport interface ActionCreatorWithNonInferrablePayload<\r\n  T extends string = string,\r\n> extends BaseActionCreator<unknown, T> {\r\n  <PT extends unknown>(payload: PT): PayloadAction<PT, T>\r\n}\r\n\r\n// @public\r\nexport interface ActionCreatorWithOptionalPayload<P, T extends string = string>\r\n  extends BaseActionCreator<P, T> {\r\n  (payload?: P): PayloadAction<P, T>\r\n}\r\n\r\n// @public\r\nexport interface ActionCreatorWithoutPayload<T extends string = string>\r\n  extends BaseActionCreator<undefined, T> {\r\n  (): PayloadAction<undefined, T>\r\n}\r\n\r\n// @public\r\nexport interface ActionCreatorWithPayload<P, T extends string = string>\r\n  extends BaseActionCreator<P, T> {\r\n  (payload: P): PayloadAction<P, T>\r\n}\r\n\r\n// @public\r\nexport interface ActionCreatorWithPreparedPayload<\r\n  Args extends unknown[],\r\n  P,\r\n  T extends string = string,\r\n  E = never,\r\n  M = never,\r\n> extends BaseActionCreator<P, T, M, E> {\r\n  (...args: Args): PayloadAction<P, T, M, E>\r\n}\r\n\r\n// @public (undocumented)\r\nexport type ActionMatchingAllOf<\r\n  Matchers extends [Matcher<any>, ...Matcher<any>[]],\r\n> = UnionToIntersection<ActionMatchingAnyOf<Matchers>>\r\n\r\n// @public (undocumented)\r\nexport type ActionMatchingAnyOf<\r\n  Matchers extends [Matcher<any>, ...Matcher<any>[]],\r\n> = ActionFromMatcher<Matchers[number]>\r\n\r\n// @public\r\nexport interface ActionReducerMapBuilder<State> {\r\n  addCase<ActionCreator extends TypedActionCreator<string>>(\r\n    actionCreator: ActionCreator,\r\n    reducer: CaseReducer<State, ReturnType<ActionCreator>>,\r\n  ): ActionReducerMapBuilder<State>\r\n  addCase<Type extends string, A extends Action<Type>>(\r\n    type: Type,\r\n    reducer: CaseReducer<State, A>,\r\n  ): ActionReducerMapBuilder<State>\r\n  addDefaultCase(reducer: CaseReducer<State, UnknownAction>): {}\r\n  addMatcher<A>(\r\n    matcher: TypeGuard<A> | ((action: any) => boolean),\r\n    reducer: CaseReducer<State, A extends Action ? A : A & Action>,\r\n  ): Omit<ActionReducerMapBuilder<State>, 'addCase'>\r\n}\r\n\r\n// @public @deprecated\r\nexport type Actions<T extends keyof any = string> = Record<T, Action>\r\n\r\n// @public\r\nexport type AsyncThunk<\r\n  Returned,\r\n  ThunkArg,\r\n  ThunkApiConfig extends AsyncThunkConfig,\r\n> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {\r\n  pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>\r\n  rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>\r\n  fulfilled: AsyncThunkFulfilledActionCreator<\r\n    Returned,\r\n    ThunkArg,\r\n    ThunkApiConfig\r\n  >\r\n  typePrefix: string\r\n}\r\n\r\n// @public\r\nexport type AsyncThunkAction<\r\n  Returned,\r\n  ThunkArg,\r\n  ThunkApiConfig extends AsyncThunkConfig,\r\n> = (\r\n  dispatch: GetDispatch<ThunkApiConfig>,\r\n  getState: () => GetState<ThunkApiConfig>,\r\n  extra: GetExtra<ThunkApiConfig>,\r\n) => Promise<\r\n  | ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>>\r\n  | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>\r\n> & {\r\n  abort: (reason?: string) => void\r\n  requestId: string\r\n  arg: ThunkArg\r\n  unwrap: () => Promise<Returned>\r\n}\r\n\r\n// @public\r\nexport type AsyncThunkOptions<\r\n  ThunkArg = void,\r\n  ThunkApiConfig extends AsyncThunkConfig = {},\r\n> = {\r\n  condition?(\r\n    arg: ThunkArg,\r\n    api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,\r\n  ): MaybePromise<boolean | undefined>\r\n  dispatchConditionRejection?: boolean\r\n  serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>\r\n  idGenerator?: (arg: ThunkArg) => string\r\n} & IsUnknown<\r\n  GetPendingMeta<ThunkApiConfig>,\r\n  {\r\n    getPendingMeta?(\r\n      base: {\r\n        arg: ThunkArg\r\n        requestId: string\r\n      },\r\n      api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,\r\n    ): GetPendingMeta<ThunkApiConfig>\r\n  },\r\n  {\r\n    getPendingMeta(\r\n      base: {\r\n        arg: ThunkArg\r\n        requestId: string\r\n      },\r\n      api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,\r\n    ): GetPendingMeta<ThunkApiConfig>\r\n  }\r\n>\r\n\r\n// @public\r\nexport type AsyncThunkPayloadCreator<\r\n  Returned,\r\n  ThunkArg = void,\r\n  ThunkApiConfig extends AsyncThunkConfig = {},\r\n> = (\r\n  arg: ThunkArg,\r\n  thunkAPI: GetThunkAPI<ThunkApiConfig>,\r\n) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>\r\n\r\n// @public\r\nexport type AsyncThunkPayloadCreatorReturnValue<\r\n  Returned,\r\n  ThunkApiConfig extends AsyncThunkConfig,\r\n> = MaybePromise<\r\n  | IsUnknown<\r\n      GetFulfilledMeta<ThunkApiConfig>,\r\n      Returned,\r\n      FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>\r\n    >\r\n  | RejectWithValue<\r\n      GetRejectValue<ThunkApiConfig>,\r\n      GetRejectedMeta<ThunkApiConfig>\r\n    >\r\n>\r\n\r\n// @public\r\nexport type CaseReducer<S = any, A extends Action = UnknownAction> = (\r\n  state: Draft<S>,\r\n  action: A,\r\n) => S | void | Draft<S>\r\n\r\n// @public\r\nexport type CaseReducerActions<CaseReducers extends SliceCaseReducers<any>> = {\r\n  [Type in keyof CaseReducers]: CaseReducers[Type] extends {\r\n    prepare: any\r\n  }\r\n    ? ActionCreatorForCaseReducerWithPrepare<CaseReducers[Type]>\r\n    : ActionCreatorForCaseReducer<CaseReducers[Type]>\r\n}\r\n\r\n// @public @deprecated\r\nexport type CaseReducers<S, AS extends Actions> = {\r\n  [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void\r\n}\r\n\r\n// @public\r\nexport type CaseReducerWithPrepare<State, Action extends PayloadAction> = {\r\n  reducer: CaseReducer<State, Action>\r\n  prepare: PrepareAction<Action['payload']>\r\n}\r\n\r\n// @public (undocumented)\r\nexport type Comparer<T> = (a: T, b: T) => number\r\n\r\n// @public\r\nexport type ConfigureEnhancersCallback = (\r\n  defaultEnhancers: readonly StoreEnhancer[],\r\n) => StoreEnhancer[]\r\n\r\n// @public\r\nexport function configureStore<\r\n  S = any,\r\n  A extends Action = UnknownAction,\r\n  M extends Middlewares<S> = [ThunkMiddlewareFor<S>],\r\n>(options: ConfigureStoreOptions<S, A, M>): EnhancedStore<S, A, M>\r\n\r\n// @public\r\nexport interface ConfigureStoreOptions<\r\n  S = any,\r\n  A extends Action = UnknownAction,\r\n  M extends Middlewares<S> = Middlewares<S>,\r\n> {\r\n  devTools?: boolean | EnhancerOptions\r\n  enhancers?: StoreEnhancer[] | ConfigureEnhancersCallback\r\n  middleware?: ((getDefaultMiddleware: CurriedGetDefaultMiddleware<S>) => M) | M\r\n  preloadedState?: PreloadedState<CombinedState<NoInfer<S>>>\r\n  reducer: Reducer<S, A> | ReducersMapObject<S, A>\r\n}\r\n\r\n// @public\r\nexport function createAction<P = void, T extends string = string>(\r\n  type: T,\r\n): PayloadActionCreator<P, T>\r\n\r\n// @public\r\nexport function createAction<\r\n  PA extends PrepareAction<any>,\r\n  T extends string = string,\r\n>(\r\n  type: T,\r\n  prepareAction: PA,\r\n): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>\r\n\r\n// @public (undocumented)\r\nexport function createAsyncThunk<Returned, ThunkArg = void>(\r\n  typePrefix: string,\r\n  payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, {}>,\r\n  options?: AsyncThunkOptions<ThunkArg, {}>,\r\n): AsyncThunk<Returned, ThunkArg, {}>\r\n\r\n// @public (undocumented)\r\nexport function createAsyncThunk<\r\n  Returned,\r\n  ThunkArg,\r\n  ThunkApiConfig extends AsyncThunkConfig,\r\n>(\r\n  typePrefix: string,\r\n  payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>,\r\n  options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>,\r\n): AsyncThunk<Returned, ThunkArg, ThunkApiConfig>\r\n\r\n// @public\r\nexport const createDraftSafeSelector: typeof createSelector\r\n\r\n// @public (undocumented)\r\nexport function createEntityAdapter<T>(options?: {\r\n  selectId?: IdSelector<T>\r\n  sortComparer?: false | Comparer<T>\r\n}): EntityAdapter<T>\r\n\r\n// @public\r\nexport function createImmutableStateInvariantMiddleware(\r\n  options?: ImmutableStateInvariantMiddlewareOptions,\r\n): Middleware\r\n\r\nexport { createNextState }\r\n\r\n// @public\r\nexport function createReducer<S extends NotFunction<any>>(\r\n  initialState: S | (() => S),\r\n  builderCallback: (builder: ActionReducerMapBuilder<S>) => void,\r\n): ReducerWithInitialState<S>\r\n\r\n// @public\r\nexport function createReducer<\r\n  S extends NotFunction<any>,\r\n  CR extends CaseReducers<S, any> = CaseReducers<S, any>,\r\n>(\r\n  initialState: S | (() => S),\r\n  actionsMap: CR,\r\n  actionMatchers?: ActionMatcherDescriptionCollection<S>,\r\n  defaultCaseReducer?: CaseReducer<S>,\r\n): ReducerWithInitialState<S>\r\n\r\nexport { createSelector }\r\n\r\n// @public\r\nexport function createSerializableStateInvariantMiddleware(\r\n  options?: SerializableStateInvariantMiddlewareOptions,\r\n): Middleware\r\n\r\n// @public\r\nexport function createSlice<\r\n  State,\r\n  CaseReducers extends SliceCaseReducers<State>,\r\n  Name extends string = string,\r\n>(\r\n  options: CreateSliceOptions<State, CaseReducers, Name>,\r\n): Slice<State, CaseReducers, Name>\r\n\r\n// @public\r\nexport interface CreateSliceOptions<\r\n  State = any,\r\n  CR extends SliceCaseReducers<State> = SliceCaseReducers<State>,\r\n  Name extends string = string,\r\n> {\r\n  extraReducers?:\r\n    | CaseReducers<NoInfer<State>, any>\r\n    | ((builder: ActionReducerMapBuilder<NoInfer<State>>) => void)\r\n  initialState: State | (() => State)\r\n  name: Name\r\n  reducers: ValidateSliceCaseReducers<State, CR>\r\n}\r\n\r\nexport { current }\r\n\r\n// @public (undocumented)\r\nexport interface Dictionary<T> extends DictionaryNum<T> {\r\n  // (undocumented)\r\n  [id: string]: T | undefined\r\n}\r\n\r\nexport { Draft }\r\n\r\n// @public\r\nexport interface EnhancedStore<\r\n  S = any,\r\n  A extends Action = UnknownAction,\r\n  M extends Middlewares<S> = Middlewares<S>,\r\n> extends Store<S, A> {\r\n  dispatch: Dispatch<A> & DispatchForMiddlewares<M>\r\n}\r\n\r\n// @public (undocumented)\r\nexport interface EntityAdapter<T> extends EntityStateAdapter<T> {\r\n  // (undocumented)\r\n  getInitialState(): EntityState<T>\r\n  // (undocumented)\r\n  getInitialState<S extends object>(state: S): EntityState<T> & S\r\n  // (undocumented)\r\n  getSelectors(): EntitySelectors<T, EntityState<T>>\r\n  // (undocumented)\r\n  getSelectors<V>(\r\n    selectState: (state: V) => EntityState<T>,\r\n  ): EntitySelectors<T, V>\r\n  // (undocumented)\r\n  selectId: IdSelector<T>\r\n  // (undocumented)\r\n  sortComparer: false | Comparer<T>\r\n}\r\n\r\n// @public (undocumented)\r\nexport type EntityId = number | string\r\n\r\n// @public (undocumented)\r\nexport interface EntitySelectors<T, V> {\r\n  // (undocumented)\r\n  selectAll: (state: V) => T[]\r\n  // (undocumented)\r\n  selectById: (state: V, id: EntityId) => T | undefined\r\n  // (undocumented)\r\n  selectEntities: (state: V) => Dictionary<T>\r\n  // (undocumented)\r\n  selectIds: (state: V) => EntityId[]\r\n  // (undocumented)\r\n  selectTotal: (state: V) => number\r\n}\r\n\r\n// @public (undocumented)\r\nexport interface EntityState<T> {\r\n  // (undocumented)\r\n  entities: Dictionary<T>\r\n  // (undocumented)\r\n  ids: EntityId[]\r\n}\r\n\r\n// @public (undocumented)\r\nexport interface EntityStateAdapter<T> {\r\n  // (undocumented)\r\n  addMany<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    entities: readonly T[] | Record<EntityId, T>,\r\n  ): S\r\n  // (undocumented)\r\n  addMany<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    entities: PayloadAction<readonly T[] | Record<EntityId, T>>,\r\n  ): S\r\n  // (undocumented)\r\n  addOne<S extends EntityState<T>>(state: PreventAny<S, T>, entity: T): S\r\n  // (undocumented)\r\n  addOne<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    action: PayloadAction<T>,\r\n  ): S\r\n  // (undocumented)\r\n  removeAll<S extends EntityState<T>>(state: PreventAny<S, T>): S\r\n  // (undocumented)\r\n  removeMany<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    keys: readonly EntityId[],\r\n  ): S\r\n  // (undocumented)\r\n  removeMany<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    keys: PayloadAction<readonly EntityId[]>,\r\n  ): S\r\n  // (undocumented)\r\n  removeOne<S extends EntityState<T>>(state: PreventAny<S, T>, key: EntityId): S\r\n  // (undocumented)\r\n  removeOne<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    key: PayloadAction<EntityId>,\r\n  ): S\r\n  // (undocumented)\r\n  setAll<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    entities: readonly T[] | Record<EntityId, T>,\r\n  ): S\r\n  // (undocumented)\r\n  setAll<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    entities: PayloadAction<readonly T[] | Record<EntityId, T>>,\r\n  ): S\r\n  // (undocumented)\r\n  setMany<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    entities: readonly T[] | Record<EntityId, T>,\r\n  ): S\r\n  // (undocumented)\r\n  setMany<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    entities: PayloadAction<readonly T[] | Record<EntityId, T>>,\r\n  ): S\r\n  // (undocumented)\r\n  setOne<S extends EntityState<T>>(state: PreventAny<S, T>, entity: T): S\r\n  // (undocumented)\r\n  setOne<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    action: PayloadAction<T>,\r\n  ): S\r\n  // (undocumented)\r\n  updateMany<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    updates: ReadonlyArray<Update<T>>,\r\n  ): S\r\n  // (undocumented)\r\n  updateMany<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    updates: PayloadAction<ReadonlyArray<Update<T>>>,\r\n  ): S\r\n  // (undocumented)\r\n  updateOne<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    update: Update<T>,\r\n  ): S\r\n  // (undocumented)\r\n  updateOne<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    update: PayloadAction<Update<T>>,\r\n  ): S\r\n  // (undocumented)\r\n  upsertMany<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    entities: readonly T[] | Record<EntityId, T>,\r\n  ): S\r\n  // (undocumented)\r\n  upsertMany<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    entities: PayloadAction<readonly T[] | Record<EntityId, T>>,\r\n  ): S\r\n  // (undocumented)\r\n  upsertOne<S extends EntityState<T>>(state: PreventAny<S, T>, entity: T): S\r\n  // (undocumented)\r\n  upsertOne<S extends EntityState<T>>(\r\n    state: PreventAny<S, T>,\r\n    entity: PayloadAction<T>,\r\n  ): S\r\n}\r\n\r\n// @public (undocumented)\r\nexport function findNonSerializableValue(\r\n  value: unknown,\r\n  path?: string,\r\n  isSerializable?: (value: unknown) => boolean,\r\n  getEntries?: (value: unknown) => [string, any][],\r\n  ignoredPaths?: readonly (string | RegExp)[],\r\n): NonSerializableValue | false\r\n\r\nexport { freeze }\r\n\r\n// @public @deprecated\r\nexport function getDefaultMiddleware<\r\n  S = any,\r\n  O extends Partial<GetDefaultMiddlewareOptions> = {\r\n    thunk: true\r\n    immutableCheck: true\r\n    serializableCheck: true\r\n  },\r\n>(options?: O): MiddlewareArray<Middleware<{}, S> | ThunkMiddlewareFor<S, O>>\r\n\r\n// @public\r\nexport function getType<T extends string>(\r\n  actionCreator: PayloadActionCreator<any, T>,\r\n): T\r\n\r\n// @public (undocumented)\r\nexport type IdSelector<T> = (model: T) => EntityId\r\n\r\n// @public\r\nexport interface ImmutableStateInvariantMiddlewareOptions {\r\n  // (undocumented)\r\n  ignore?: string[]\r\n  ignoredPaths?: string[]\r\n  isImmutable?: IsImmutableFunc\r\n  warnAfter?: number\r\n}\r\n\r\n// @public\r\nexport function isAllOf<Matchers extends [Matcher<any>, ...Matcher<any>[]]>(\r\n  ...matchers: Matchers\r\n): (\r\n  action: any,\r\n) => action is UnionToIntersection<ActionFromMatcher<Matchers[number]>>\r\n\r\n// @public\r\nexport function isAnyOf<Matchers extends [Matcher<any>, ...Matcher<any>[]]>(\r\n  ...matchers: Matchers\r\n): (action: any) => action is ActionFromMatcher<Matchers[number]>\r\n\r\n// @public\r\nexport function isAsyncThunkAction(): (\r\n  action: any,\r\n) => action is UnknownAsyncThunkAction\r\n\r\n// @public\r\nexport function isAsyncThunkAction<\r\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\r\n>(\r\n  ...asyncThunks: AsyncThunks\r\n): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>\r\n\r\n// @public\r\nexport function isAsyncThunkAction(\r\n  action: any,\r\n): action is UnknownAsyncThunkAction\r\n\r\nexport { isDraft }\r\n\r\n// @public\r\nexport function isFulfilled(): (\r\n  action: any,\r\n) => action is UnknownAsyncThunkFulfilledAction\r\n\r\n// @public\r\nexport function isFulfilled<\r\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\r\n>(\r\n  ...asyncThunks: AsyncThunks\r\n): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>\r\n\r\n// @public\r\nexport function isFulfilled(\r\n  action: any,\r\n): action is UnknownAsyncThunkFulfilledAction\r\n\r\n// @public\r\nexport function isImmutableDefault(value: unknown): boolean\r\n\r\n// @public\r\nexport function isPending(): (\r\n  action: any,\r\n) => action is UnknownAsyncThunkPendingAction\r\n\r\n// @public\r\nexport function isPending<\r\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\r\n>(\r\n  ...asyncThunks: AsyncThunks\r\n): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>\r\n\r\n// @public\r\nexport function isPending(action: any): action is UnknownAsyncThunkPendingAction\r\n\r\n// @public\r\nexport function isPlain(val: any): boolean\r\n\r\n// @public\r\nexport function isPlainObject(value: unknown): value is object\r\n\r\n// @public\r\nexport function isRejected(): (\r\n  action: any,\r\n) => action is UnknownAsyncThunkRejectedAction\r\n\r\n// @public\r\nexport function isRejected<\r\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\r\n>(\r\n  ...asyncThunks: AsyncThunks\r\n): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>\r\n\r\n// @public\r\nexport function isRejected(\r\n  action: any,\r\n): action is UnknownAsyncThunkRejectedAction\r\n\r\n// @public\r\nexport function isRejectedWithValue(): (\r\n  action: any,\r\n) => action is UnknownAsyncThunkRejectedAction\r\n\r\n// @public\r\nexport function isRejectedWithValue<\r\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\r\n>(\r\n  ...asyncThunks: AsyncThunks\r\n): (\r\n  action: any,\r\n) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>\r\n\r\n// @public\r\nexport function isRejectedWithValue(\r\n  action: any,\r\n): action is UnknownAsyncThunkRejectedAction\r\n\r\n// @public (undocumented)\r\nexport class MiddlewareArray<\r\n  Middlewares extends Middleware<any, any>,\r\n> extends Array<Middlewares> {\r\n  // (undocumented)\r\n  static get [Symbol.species](): any\r\n  constructor(arrayLength?: number)\r\n  constructor(...items: Middlewares[])\r\n  // (undocumented)\r\n  concat<AdditionalMiddlewares extends ReadonlyArray<Middleware<any, any>>>(\r\n    items: AdditionalMiddlewares,\r\n  ): MiddlewareArray<Middlewares | AdditionalMiddlewares[number]>\r\n  // (undocumented)\r\n  concat<AdditionalMiddlewares extends ReadonlyArray<Middleware<any, any>>>(\r\n    ...items: AdditionalMiddlewares\r\n  ): MiddlewareArray<Middlewares | AdditionalMiddlewares[number]>\r\n  // (undocumented)\r\n  prepend<AdditionalMiddlewares extends ReadonlyArray<Middleware<any, any>>>(\r\n    items: AdditionalMiddlewares,\r\n  ): MiddlewareArray<AdditionalMiddlewares[number] | Middlewares>\r\n  // (undocumented)\r\n  prepend<AdditionalMiddlewares extends ReadonlyArray<Middleware<any, any>>>(\r\n    ...items: AdditionalMiddlewares\r\n  ): MiddlewareArray<AdditionalMiddlewares[number] | Middlewares>\r\n}\r\n\r\n// @public\r\nexport const miniSerializeError: (value: any) => SerializedError\r\n\r\n// @public (undocumented)\r\nexport let nanoid: (size?: number) => string\r\n\r\nexport { original }\r\n\r\nexport { OutputParametricSelector }\r\n\r\nexport { OutputSelector }\r\n\r\nexport { ParametricSelector }\r\n\r\n// @public\r\nexport type PayloadAction<\r\n  P = void,\r\n  T extends string = string,\r\n  M = never,\r\n  E = never,\r\n> = {\r\n  payload: P\r\n  type: T\r\n} & ([M] extends [never]\r\n  ? {}\r\n  : {\r\n      meta: M\r\n    }) &\r\n  ([E] extends [never]\r\n    ? {}\r\n    : {\r\n        error: E\r\n      })\r\n\r\n// @public\r\nexport type PayloadActionCreator<\r\n  P = void,\r\n  T extends string = string,\r\n  PA extends PrepareAction<P> | void = void,\r\n> = IfPrepareActionMethodProvided<\r\n  PA,\r\n  _ActionCreatorWithPreparedPayload<PA, T>,\r\n  IsAny<\r\n    P,\r\n    ActionCreatorWithPayload<any, T>,\r\n    IsUnknownOrNonInferrable<\r\n      P,\r\n      ActionCreatorWithNonInferrablePayload<T>,\r\n      IfVoid<\r\n        P,\r\n        ActionCreatorWithoutPayload<T>,\r\n        IfMaybeUndefined<\r\n          P,\r\n          ActionCreatorWithOptionalPayload<P, T>,\r\n          ActionCreatorWithPayload<P, T>\r\n        >\r\n      >\r\n    >\r\n  >\r\n>\r\n\r\n// @public\r\nexport type PrepareAction<P> =\r\n  | ((...args: any[]) => {\r\n      payload: P\r\n    })\r\n  | ((...args: any[]) => {\r\n      payload: P\r\n      meta: any\r\n    })\r\n  | ((...args: any[]) => {\r\n      payload: P\r\n      error: any\r\n    })\r\n  | ((...args: any[]) => {\r\n      payload: P\r\n      meta: any\r\n      error: any\r\n    })\r\n\r\nexport { Selector }\r\n\r\n// @public\r\nexport interface SerializableStateInvariantMiddlewareOptions {\r\n  getEntries?: (value: any) => [string, any][]\r\n  ignoredActionPaths?: (string | RegExp)[]\r\n  ignoredActions?: string[]\r\n  ignoredPaths?: (string | RegExp)[]\r\n  ignoreState?: boolean\r\n  isSerializable?: (value: any) => boolean\r\n  warnAfter?: number\r\n}\r\n\r\n// @public (undocumented)\r\nexport interface SerializedError {\r\n  // (undocumented)\r\n  code?: string\r\n  // (undocumented)\r\n  message?: string\r\n  // (undocumented)\r\n  name?: string\r\n  // (undocumented)\r\n  stack?: string\r\n}\r\n\r\n// @public\r\nexport interface Slice<\r\n  State = any,\r\n  CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>,\r\n  Name extends string = string,\r\n> {\r\n  actions: CaseReducerActions<CaseReducers>\r\n  caseReducers: SliceDefinedCaseReducers<CaseReducers>\r\n  getInitialState: () => State\r\n  name: Name\r\n  reducer: Reducer<State>\r\n}\r\n\r\n// @public @deprecated\r\nexport type SliceActionCreator<P> = PayloadActionCreator<P>\r\n\r\n// @public\r\nexport type SliceCaseReducers<State> = {\r\n  [K: string]:\r\n    | CaseReducer<State, PayloadAction<any>>\r\n    | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>\r\n}\r\n\r\nexport { ThunkAction }\r\n\r\nexport { ThunkDispatch }\r\n\r\n// @public (undocumented)\r\nexport function unwrapResult<R extends UnwrappableAction>(\r\n  action: R,\r\n): UnwrappedActionPayload<R>\r\n\r\n// @public (undocumented)\r\nexport type Update<T> = {\r\n  id: EntityId\r\n  changes: Partial<T>\r\n}\r\n\r\n// @public\r\nexport type ValidateSliceCaseReducers<\r\n  S,\r\n  ACR extends SliceCaseReducers<S>,\r\n> = ACR & {\r\n  [T in keyof ACR]: ACR[T] extends {\r\n    reducer(s: S, action?: infer A): any\r\n  }\r\n    ? {\r\n        prepare(...a: never[]): Omit<A, 'type'>\r\n      }\r\n    : {}\r\n}\r\n\r\nexport * from 'redux'\r\n\r\n// (No @packageDocumentation comment for this package)\r\n```\r\n"
  },
  {
    "path": "packages/toolkit/etc/rtk-query-react.api.md",
    "content": "## API Report File for \"@reduxjs/toolkit\"\r\n\r\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\r\n\r\n```ts\r\nimport { ActionCreatorWithoutPayload } from '@reduxjs/toolkit'\r\nimport { batch } from 'react-redux'\r\nimport { Context } from 'react'\r\nimport { ReactReduxContextValue } from 'react-redux'\r\nimport { ThunkDispatch } from '@reduxjs/toolkit'\r\nimport { useDispatch } from 'react-redux'\r\nimport { useSelector } from 'react-redux'\r\nimport { useStore } from 'react-redux'\r\n\r\n// @public (undocumented)\r\nexport type Api<\r\n  BaseQuery extends BaseQueryFn,\r\n  Definitions extends EndpointDefinitions,\r\n  ReducerPath extends string,\r\n  TagTypes extends string,\r\n  Enhancers extends ModuleName = CoreModule,\r\n> = Id<\r\n  Id<\r\n    UnionToIntersection<\r\n      ApiModules<BaseQuery, Definitions, ReducerPath, TagTypes>[Enhancers]\r\n    >\r\n  > & {\r\n    injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {\r\n      endpoints: (\r\n        build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,\r\n      ) => NewDefinitions\r\n      overrideExisting?: boolean\r\n    }): Api<\r\n      BaseQuery,\r\n      Definitions & NewDefinitions,\r\n      ReducerPath,\r\n      TagTypes,\r\n      Enhancers\r\n    >\r\n    enhanceEndpoints<NewTagTypes extends string = never>(_: {\r\n      addTagTypes?: readonly NewTagTypes[]\r\n      endpoints?: ReplaceTagTypes<\r\n        Definitions,\r\n        TagTypes | NoInfer<NewTagTypes>\r\n      > extends infer NewDefinitions\r\n        ? {\r\n            [K in keyof NewDefinitions]?:\r\n              | Partial<NewDefinitions[K]>\r\n              | ((definition: NewDefinitions[K]) => void)\r\n          }\r\n        : never\r\n    }): Api<\r\n      BaseQuery,\r\n      ReplaceTagTypes<Definitions, TagTypes | NewTagTypes>,\r\n      ReducerPath,\r\n      TagTypes | NewTagTypes,\r\n      Enhancers\r\n    >\r\n  }\r\n>\r\n\r\n// @public (undocumented)\r\nexport interface ApiModules<\r\n  BaseQuery extends BaseQueryFn,\r\n  Definitions extends EndpointDefinitions,\r\n  ReducerPath extends string,\r\n  TagTypes extends string,\r\n> {}\r\n\r\n// @public\r\nexport function ApiProvider<A extends Api<any, {}, any, any>>(props: {\r\n  children: any\r\n  api: A\r\n  setupListeners?: Parameters<typeof setupListeners>[1]\r\n  context?: Context<ReactReduxContextValue | null>\r\n}): JSX.Element\r\n\r\n// @public (undocumented)\r\nexport type ApiWithInjectedEndpoints<\r\n  ApiDefinition extends Api<any, any, any, any>,\r\n  Injections extends ApiDefinition extends Api<infer B, any, infer R, infer E>\r\n    ? [Api<B, any, R, E>, ...Api<B, any, R, E>[]]\r\n    : never,\r\n> = Omit<ApiDefinition, 'endpoints'> &\r\n  Omit<Injections, 'endpoints'> & {\r\n    endpoints: ApiDefinition['endpoints'] &\r\n      Partial<UnionToIntersection<Injections[number]['endpoints']>>\r\n  }\r\n\r\n// @public (undocumented)\r\nexport type BaseQueryEnhancer<\r\n  AdditionalArgs = unknown,\r\n  AdditionalDefinitionExtraOptions = unknown,\r\n  Config = void,\r\n> = <BaseQuery extends BaseQueryFn>(\r\n  baseQuery: BaseQuery,\r\n  config: Config,\r\n) => BaseQueryFn<\r\n  BaseQueryArg<BaseQuery> & AdditionalArgs,\r\n  BaseQueryResult<BaseQuery>,\r\n  BaseQueryError<BaseQuery>,\r\n  BaseQueryExtraOptions<BaseQuery> & AdditionalDefinitionExtraOptions\r\n>\r\n\r\n// @public (undocumented)\r\nexport type BaseQueryFn<\r\n  Args = any,\r\n  Result = unknown,\r\n  Error = unknown,\r\n  DefinitionExtraOptions = {},\r\n  Meta = {},\r\n> = (\r\n  args: Args,\r\n  api: BaseQueryApi,\r\n  extraOptions: DefinitionExtraOptions,\r\n) => MaybePromise<QueryReturnValue<Result, Error, Meta>>\r\n\r\n// @public\r\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(\r\n  ...modules: Modules\r\n): CreateApi<Modules[number]['name']>\r\n\r\n// @public (undocumented)\r\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T\r\n\r\n// @public\r\nexport const coreModule: () => Module<CoreModule>\r\n\r\n// @public (undocumented)\r\nexport type CreateApi<Modules extends ModuleName> = {\r\n  <\r\n    BaseQuery extends BaseQueryFn,\r\n    Definitions extends EndpointDefinitions,\r\n    ReducerPath extends string = 'api',\r\n    TagTypes extends string = never,\r\n  >(\r\n    options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,\r\n  ): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>\r\n}\r\n\r\n// @public (undocumented)\r\nexport const createApi: CreateApi<\r\n  typeof coreModuleName | typeof reactHooksModuleName\r\n>\r\n\r\n// @public (undocumented)\r\nexport interface CreateApiOptions<\r\n  BaseQuery extends BaseQueryFn,\r\n  Definitions extends EndpointDefinitions,\r\n  ReducerPath extends string = 'api',\r\n  TagTypes extends string = never,\r\n> {\r\n  baseQuery: BaseQuery\r\n  endpoints(\r\n    build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,\r\n  ): Definitions\r\n  keepUnusedDataFor?: number\r\n  reducerPath?: ReducerPath\r\n  refetchOnFocus?: boolean\r\n  refetchOnMountOrArgChange?: boolean | number\r\n  refetchOnReconnect?: boolean\r\n  serializeQueryArgs?: SerializeQueryArgs<unknown>\r\n  tagTypes?: readonly TagTypes[]\r\n}\r\n\r\n// @public (undocumented)\r\nexport type EndpointDefinition<\r\n  QueryArg,\r\n  BaseQuery extends BaseQueryFn,\r\n  TagTypes extends string,\r\n  ResultType,\r\n  ReducerPath extends string = string,\r\n> =\r\n  | QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n  | MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n\r\n// @public (undocumented)\r\nexport type EndpointDefinitions = Record<\r\n  string,\r\n  EndpointDefinition<any, any, any, any>\r\n>\r\n\r\n// @public\r\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<\r\n  void,\r\n  NEVER,\r\n  ErrorType,\r\n  {}\r\n>\r\n\r\n// @public (undocumented)\r\nexport interface FetchArgs extends CustomRequestInit {\r\n  // (undocumented)\r\n  body?: any\r\n  // (undocumented)\r\n  params?: Record<string, any>\r\n  // (undocumented)\r\n  responseHandler?: ResponseHandler\r\n  // (undocumented)\r\n  url: string\r\n  // (undocumented)\r\n  validateStatus?: (response: Response, body: any) => boolean\r\n}\r\n\r\n// @public\r\nexport function fetchBaseQuery({\r\n  baseUrl,\r\n  prepareHeaders,\r\n  fetchFn,\r\n  ...baseFetchOptions\r\n}?: FetchBaseQueryArgs): BaseQueryFn<\r\n  string | FetchArgs,\r\n  unknown,\r\n  FetchBaseQueryError,\r\n  {},\r\n  FetchBaseQueryMeta\r\n>\r\n\r\n// @public (undocumented)\r\nexport interface FetchBaseQueryError {\r\n  // (undocumented)\r\n  data: unknown\r\n  // (undocumented)\r\n  status: number\r\n}\r\n\r\n// @public (undocumented)\r\nexport type Module<Name extends ModuleName> = {\r\n  name: Name\r\n  init<\r\n    BaseQuery extends BaseQueryFn,\r\n    Definitions extends EndpointDefinitions,\r\n    ReducerPath extends string,\r\n    TagTypes extends string,\r\n  >(\r\n    api: Api<BaseQuery, EndpointDefinitions, ReducerPath, TagTypes, ModuleName>,\r\n    options: Required<\r\n      CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>\r\n    >,\r\n    context: ApiContext<Definitions>,\r\n  ): {\r\n    injectEndpoint(\r\n      endpointName: string,\r\n      definition: EndpointDefinition<any, any, any, any>,\r\n    ): void\r\n  }\r\n}\r\n\r\n// @public (undocumented)\r\nexport type MutationDefinition<\r\n  QueryArg,\r\n  BaseQuery extends BaseQueryFn,\r\n  TagTypes extends string,\r\n  ResultType,\r\n  ReducerPath extends string = string,\r\n> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> &\r\n  MutationExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>\r\n\r\n// @public (undocumented)\r\nexport type QueryDefinition<\r\n  QueryArg,\r\n  BaseQuery extends BaseQueryFn,\r\n  TagTypes extends string,\r\n  ResultType,\r\n  ReducerPath extends string = string,\r\n> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> &\r\n  QueryExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>\r\n\r\n// @public\r\nexport enum QueryStatus {\r\n  // (undocumented)\r\n  fulfilled = 'fulfilled',\r\n  // (undocumented)\r\n  pending = 'pending',\r\n  // (undocumented)\r\n  rejected = 'rejected',\r\n  // (undocumented)\r\n  uninitialized = 'uninitialized',\r\n}\r\n\r\n// @public\r\nexport const reactHooksModule: ({\r\n  batch,\r\n  useDispatch,\r\n  useSelector,\r\n  useStore,\r\n}?: ReactHooksModuleOptions) => Module<ReactHooksModule>\r\n\r\n// @public\r\nexport const retry: BaseQueryEnhancer<\r\n  unknown,\r\n  StaggerOptions,\r\n  void | StaggerOptions\r\n> & {\r\n  fail: typeof fail_2\r\n}\r\n\r\n// @public\r\nexport function setupListeners(\r\n  dispatch: ThunkDispatch<any, any, any>,\r\n  customHandler?: (\r\n    dispatch: ThunkDispatch<any, any, any>,\r\n    actions: {\r\n      onFocus: typeof onFocus\r\n      onFocusLost: typeof onFocusLost\r\n      onOnline: typeof onOnline\r\n      onOffline: typeof onOffline\r\n    },\r\n  ) => () => void,\r\n): () => void\r\n\r\n// @public (undocumented)\r\nexport const skipSelector: unique symbol\r\n\r\n// (No @packageDocumentation comment for this package)\r\n```\r\n"
  },
  {
    "path": "packages/toolkit/etc/rtk-query.api.md",
    "content": "## API Report File for \"@reduxjs/toolkit\"\r\n\r\n> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/).\r\n\r\n```ts\r\nimport type { ActionCreatorWithoutPayload } from '@reduxjs/toolkit'\r\nimport type { UnknownAction } from '@reduxjs/toolkit'\r\nimport type { SerializedError } from '@reduxjs/toolkit'\r\nimport type { ThunkDispatch } from '@reduxjs/toolkit'\r\n\r\n// @public (undocumented)\r\nexport type Api<\r\n  BaseQuery extends BaseQueryFn,\r\n  Definitions extends EndpointDefinitions,\r\n  ReducerPath extends string,\r\n  TagTypes extends string,\r\n  Enhancers extends ModuleName = CoreModule,\r\n> = UnionToIntersection<\r\n  ApiModules<BaseQuery, Definitions, ReducerPath, TagTypes>[Enhancers]\r\n> & {\r\n  injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {\r\n    endpoints: (\r\n      build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,\r\n    ) => NewDefinitions\r\n    overrideExisting?: boolean\r\n  }): Api<\r\n    BaseQuery,\r\n    Definitions & NewDefinitions,\r\n    ReducerPath,\r\n    TagTypes,\r\n    Enhancers\r\n  >\r\n  enhanceEndpoints<NewTagTypes extends string = never>(_: {\r\n    addTagTypes?: readonly NewTagTypes[]\r\n    endpoints?: ReplaceTagTypes<\r\n      Definitions,\r\n      TagTypes | NoInfer<NewTagTypes>\r\n    > extends infer NewDefinitions\r\n      ? {\r\n          [K in keyof NewDefinitions]?:\r\n            | Partial<NewDefinitions[K]>\r\n            | ((definition: NewDefinitions[K]) => void)\r\n        }\r\n      : never\r\n  }): Api<\r\n    BaseQuery,\r\n    ReplaceTagTypes<Definitions, TagTypes | NewTagTypes>,\r\n    ReducerPath,\r\n    TagTypes | NewTagTypes,\r\n    Enhancers\r\n  >\r\n}\r\n\r\n// @public (undocumented)\r\nexport interface ApiModules<\r\n  BaseQuery extends BaseQueryFn,\r\n  Definitions extends EndpointDefinitions,\r\n  ReducerPath extends string,\r\n  TagTypes extends string,\r\n> {}\r\n\r\n// @public (undocumented)\r\nexport type BaseQueryEnhancer<\r\n  AdditionalArgs = unknown,\r\n  AdditionalDefinitionExtraOptions = unknown,\r\n  Config = void,\r\n> = <BaseQuery extends BaseQueryFn>(\r\n  baseQuery: BaseQuery,\r\n  config: Config,\r\n) => BaseQueryFn<\r\n  BaseQueryArg<BaseQuery> & AdditionalArgs,\r\n  BaseQueryResult<BaseQuery>,\r\n  BaseQueryError<BaseQuery>,\r\n  BaseQueryExtraOptions<BaseQuery> & AdditionalDefinitionExtraOptions\r\n>\r\n\r\n// @public (undocumented)\r\nexport type BaseQueryFn<\r\n  Args = any,\r\n  Result = unknown,\r\n  Error = unknown,\r\n  DefinitionExtraOptions = {\r\n    copyWithStructuralSharing?: boolean\r\n  },\r\n  Meta = {},\r\n> = (\r\n  args: Args,\r\n  api: BaseQueryApi,\r\n  extraOptions: DefinitionExtraOptions,\r\n) => MaybePromise<QueryReturnValue<Result, Error, Meta>>\r\n\r\n// @public\r\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(\r\n  ...modules: Modules\r\n): CreateApi<Modules[number]['name']>\r\n\r\n// @public (undocumented)\r\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T\r\n\r\n// @public\r\nexport const coreModule: () => Module<CoreModule>\r\n\r\n// @public (undocumented)\r\nexport type CreateApi<Modules extends ModuleName> = {\r\n  <\r\n    BaseQuery extends BaseQueryFn,\r\n    Definitions extends EndpointDefinitions,\r\n    ReducerPath extends string = 'api',\r\n    TagTypes extends string = never,\r\n  >(\r\n    options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,\r\n  ): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>\r\n}\r\n\r\n// @public (undocumented)\r\nexport const createApi: CreateApi<typeof coreModuleName>\r\n\r\n// @public (undocumented)\r\nexport interface CreateApiOptions<\r\n  BaseQuery extends BaseQueryFn,\r\n  Definitions extends EndpointDefinitions,\r\n  ReducerPath extends string = 'api',\r\n  TagTypes extends string = never,\r\n> {\r\n  baseQuery: BaseQuery\r\n  endpoints(\r\n    build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,\r\n  ): Definitions\r\n  extractRehydrationInfo?: (\r\n    action: UnknownAction,\r\n    {\r\n      reducerPath,\r\n    }: {\r\n      reducerPath: ReducerPath\r\n    },\r\n  ) =>\r\n    | undefined\r\n    | CombinedState<\r\n        NoInfer<Definitions>,\r\n        NoInfer<TagTypes>,\r\n        NoInfer<ReducerPath>\r\n      >\r\n  keepUnusedDataFor?: number\r\n  reducerPath?: ReducerPath\r\n  refetchOnFocus?: boolean\r\n  refetchOnMountOrArgChange?: boolean | number\r\n  refetchOnReconnect?: boolean\r\n  serializeQueryArgs?: SerializeQueryArgs<unknown>\r\n  structuralSharing?: boolean\r\n  tagTypes?: readonly TagTypes[]\r\n}\r\n\r\n// @public (undocumented)\r\nexport type EndpointDefinition<\r\n  QueryArg,\r\n  BaseQuery extends BaseQueryFn,\r\n  TagTypes extends string,\r\n  ResultType,\r\n  ReducerPath extends string = string,\r\n> =\r\n  | QueryDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n  | MutationDefinition<QueryArg, BaseQuery, TagTypes, ResultType, ReducerPath>\r\n\r\n// @public (undocumented)\r\nexport type EndpointDefinitions = Record<\r\n  string,\r\n  EndpointDefinition<any, any, any, any>\r\n>\r\n\r\n// @public\r\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<\r\n  void,\r\n  NEVER,\r\n  ErrorType,\r\n  {}\r\n>\r\n\r\n// @public (undocumented)\r\nexport interface FetchArgs extends CustomRequestInit {\r\n  // (undocumented)\r\n  body?: any\r\n  // (undocumented)\r\n  params?: Record<string, any>\r\n  // (undocumented)\r\n  responseHandler?: ResponseHandler\r\n  // (undocumented)\r\n  url: string\r\n  // (undocumented)\r\n  validateStatus?: (response: Response, body: any) => boolean\r\n}\r\n\r\n// @public\r\nexport function fetchBaseQuery({\r\n  baseUrl,\r\n  prepareHeaders,\r\n  fetchFn,\r\n  paramsSerializer,\r\n  ...baseFetchOptions\r\n}?: FetchBaseQueryArgs): BaseQueryFn<\r\n  string | FetchArgs,\r\n  unknown,\r\n  FetchBaseQueryError,\r\n  {},\r\n  FetchBaseQueryMeta\r\n>\r\n\r\n// @public (undocumented)\r\nexport type FetchBaseQueryError =\r\n  | {\r\n      status: number\r\n      data: unknown\r\n    }\r\n  | {\r\n      status: 'FETCH_ERROR'\r\n      data?: undefined\r\n      error: string\r\n    }\r\n  | {\r\n      status: 'PARSING_ERROR'\r\n      originalStatus: number\r\n      data: string\r\n      error: string\r\n    }\r\n  | {\r\n      status: 'CUSTOM_ERROR'\r\n      data?: unknown\r\n      error: string\r\n    }\r\n\r\n// @public (undocumented)\r\nexport type FetchBaseQueryMeta = {\r\n  request: Request\r\n  response?: Response\r\n}\r\n\r\n// @public (undocumented)\r\nexport type Module<Name extends ModuleName> = {\r\n  name: Name\r\n  init<\r\n    BaseQuery extends BaseQueryFn,\r\n    Definitions extends EndpointDefinitions,\r\n    ReducerPath extends string,\r\n    TagTypes extends string,\r\n  >(\r\n    api: Api<BaseQuery, EndpointDefinitions, ReducerPath, TagTypes, ModuleName>,\r\n    options: WithRequiredProp<\r\n      CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,\r\n      | 'reducerPath'\r\n      | 'serializeQueryArgs'\r\n      | 'keepUnusedDataFor'\r\n      | 'refetchOnMountOrArgChange'\r\n      | 'refetchOnFocus'\r\n      | 'refetchOnReconnect'\r\n      | 'tagTypes'\r\n      | 'structuralSharing'\r\n    >,\r\n    context: ApiContext<Definitions>,\r\n  ): {\r\n    injectEndpoint(\r\n      endpointName: string,\r\n      definition: EndpointDefinition<any, any, any, any>,\r\n    ): void\r\n  }\r\n}\r\n\r\n// @public (undocumented)\r\nexport type MutationDefinition<\r\n  QueryArg,\r\n  BaseQuery extends BaseQueryFn,\r\n  TagTypes extends string,\r\n  ResultType,\r\n  ReducerPath extends string = string,\r\n> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> &\r\n  MutationExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>\r\n\r\n// @public (undocumented)\r\nexport type QueryDefinition<\r\n  QueryArg,\r\n  BaseQuery extends BaseQueryFn,\r\n  TagTypes extends string,\r\n  ResultType,\r\n  ReducerPath extends string = string,\r\n> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType> &\r\n  QueryExtraOptions<TagTypes, ResultType, QueryArg, BaseQuery, ReducerPath>\r\n\r\n// @public\r\nexport enum QueryStatus {\r\n  // (undocumented)\r\n  fulfilled = 'fulfilled',\r\n  // (undocumented)\r\n  pending = 'pending',\r\n  // (undocumented)\r\n  rejected = 'rejected',\r\n  // (undocumented)\r\n  uninitialized = 'uninitialized',\r\n}\r\n\r\n// @public\r\nexport const retry: BaseQueryEnhancer<\r\n  unknown,\r\n  RetryOptions,\r\n  void | RetryOptions\r\n> & {\r\n  fail: typeof fail_2\r\n}\r\n\r\n// @public\r\nexport function setupListeners(\r\n  dispatch: ThunkDispatch<any, any, any>,\r\n  customHandler?: (\r\n    dispatch: ThunkDispatch<any, any, any>,\r\n    actions: {\r\n      onFocus: typeof onFocus\r\n      onFocusLost: typeof onFocusLost\r\n      onOnline: typeof onOnline\r\n      onOffline: typeof onOffline\r\n    },\r\n  ) => () => void,\r\n): () => void\r\n\r\n// @public @deprecated (undocumented)\r\nexport const skipSelector: symbol\r\n\r\n// @public (undocumented)\r\nexport type SkipToken = typeof skipToken\r\n\r\n// @public\r\nexport const skipToken: unique symbol\r\n\r\n// (No @packageDocumentation comment for this package)\r\n```\r\n"
  },
  {
    "path": "packages/toolkit/package.json",
    "content": "{\n  \"name\": \"@reduxjs/toolkit\",\n  \"version\": \"2.11.2\",\n  \"description\": \"The official, opinionated, batteries-included toolset for efficient Redux development\",\n  \"author\": \"Mark Erikson <mark@isquaredsoftware.com>\",\n  \"license\": \"MIT\",\n  \"repository\": {\n    \"type\": \"git\",\n    \"url\": \"git+https://github.com/reduxjs/redux-toolkit.git\"\n  },\n  \"keywords\": [\n    \"redux\",\n    \"react\",\n    \"starter\",\n    \"toolkit\",\n    \"reducer\",\n    \"slice\",\n    \"immer\",\n    \"immutable\",\n    \"redux-toolkit\",\n    \"tanstack-intent\"\n  ],\n  \"publishConfig\": {\n    \"access\": \"public\"\n  },\n  \"module\": \"dist/redux-toolkit.legacy-esm.js\",\n  \"main\": \"dist/cjs/index.js\",\n  \"types\": \"dist/index.d.ts\",\n  \"react-native\": \"dist/redux-toolkit.legacy-esm.js\",\n  \"unpkg\": \"dist/redux-toolkit.browser.mjs\",\n  \"exports\": {\n    \"./package.json\": \"./package.json\",\n    \".\": {\n      \"module-sync\": {\n        \"types\": \"./dist/index.d.mts\",\n        \"default\": \"./dist/redux-toolkit.modern.mjs\"\n      },\n      \"module\": {\n        \"types\": \"./dist/index.d.mts\",\n        \"default\": \"./dist/redux-toolkit.modern.mjs\"\n      },\n      \"react-native\": {\n        \"import\": {\n          \"types\": \"./dist/index.d.mts\",\n          \"default\": \"./dist/redux-toolkit.modern.mjs\"\n        },\n        \"default\": {\n          \"types\": \"./dist/index.d.ts\",\n          \"default\": \"./dist/cjs/index.js\"\n        }\n      },\n      \"browser\": {\n        \"import\": {\n          \"types\": \"./dist/index.d.mts\",\n          \"default\": \"./dist/redux-toolkit.browser.mjs\"\n        },\n        \"default\": {\n          \"types\": \"./dist/index.d.ts\",\n          \"default\": \"./dist/cjs/index.js\"\n        }\n      },\n      \"import\": {\n        \"types\": \"./dist/index.d.mts\",\n        \"default\": \"./dist/redux-toolkit.modern.mjs\"\n      },\n      \"default\": {\n        \"types\": \"./dist/index.d.ts\",\n        \"default\": \"./dist/cjs/index.js\"\n      }\n    },\n    \"./react\": {\n      \"module-sync\": {\n        \"types\": \"./dist/react/index.d.mts\",\n        \"default\": \"./dist/react/redux-toolkit-react.modern.mjs\"\n      },\n      \"module\": {\n        \"types\": \"./dist/react/index.d.mts\",\n        \"default\": \"./dist/react/redux-toolkit-react.modern.mjs\"\n      },\n      \"react-native\": {\n        \"import\": {\n          \"types\": \"./dist/react/index.d.mts\",\n          \"default\": \"./dist/react/redux-toolkit-react.modern.mjs\"\n        },\n        \"default\": {\n          \"types\": \"./dist/react/index.d.ts\",\n          \"default\": \"./dist/react/cjs/index.js\"\n        }\n      },\n      \"browser\": {\n        \"import\": {\n          \"types\": \"./dist/react/index.d.mts\",\n          \"default\": \"./dist/react/redux-toolkit-react.browser.mjs\"\n        },\n        \"default\": {\n          \"types\": \"./dist/react/index.d.ts\",\n          \"default\": \"./dist/react/cjs/index.js\"\n        }\n      },\n      \"import\": {\n        \"types\": \"./dist/react/index.d.mts\",\n        \"default\": \"./dist/react/redux-toolkit-react.modern.mjs\"\n      },\n      \"default\": {\n        \"types\": \"./dist/react/index.d.ts\",\n        \"default\": \"./dist/react/cjs/index.js\"\n      }\n    },\n    \"./query\": {\n      \"module-sync\": {\n        \"types\": \"./dist/query/index.d.mts\",\n        \"default\": \"./dist/query/rtk-query.modern.mjs\"\n      },\n      \"module\": {\n        \"types\": \"./dist/query/index.d.mts\",\n        \"default\": \"./dist/query/rtk-query.modern.mjs\"\n      },\n      \"react-native\": {\n        \"import\": {\n          \"types\": \"./dist/query/index.d.mts\",\n          \"default\": \"./dist/query/rtk-query.modern.mjs\"\n        },\n        \"default\": {\n          \"types\": \"./dist/query/index.d.ts\",\n          \"default\": \"./dist/query/cjs/index.js\"\n        }\n      },\n      \"browser\": {\n        \"import\": {\n          \"types\": \"./dist/query/index.d.mts\",\n          \"default\": \"./dist/query/rtk-query.browser.mjs\"\n        },\n        \"default\": {\n          \"types\": \"./dist/query/index.d.ts\",\n          \"default\": \"./dist/query/cjs/index.js\"\n        }\n      },\n      \"import\": {\n        \"types\": \"./dist/query/index.d.mts\",\n        \"default\": \"./dist/query/rtk-query.modern.mjs\"\n      },\n      \"default\": {\n        \"types\": \"./dist/query/index.d.ts\",\n        \"default\": \"./dist/query/cjs/index.js\"\n      }\n    },\n    \"./query/react\": {\n      \"module-sync\": {\n        \"types\": \"./dist/query/react/index.d.mts\",\n        \"default\": \"./dist/query/react/rtk-query-react.modern.mjs\"\n      },\n      \"module\": {\n        \"types\": \"./dist/query/react/index.d.mts\",\n        \"default\": \"./dist/query/react/rtk-query-react.modern.mjs\"\n      },\n      \"react-native\": {\n        \"import\": {\n          \"types\": \"./dist/query/react/index.d.mts\",\n          \"default\": \"./dist/query/react/rtk-query-react.modern.mjs\"\n        },\n        \"default\": {\n          \"types\": \"./dist/query/react/index.d.ts\",\n          \"default\": \"./dist/query/react/cjs/index.js\"\n        }\n      },\n      \"browser\": {\n        \"import\": {\n          \"types\": \"./dist/query/react/index.d.mts\",\n          \"default\": \"./dist/query/react/rtk-query-react.browser.mjs\"\n        },\n        \"default\": {\n          \"types\": \"./dist/query/react/index.d.ts\",\n          \"default\": \"./dist/query/react/cjs/index.js\"\n        }\n      },\n      \"import\": {\n        \"types\": \"./dist/query/react/index.d.mts\",\n        \"default\": \"./dist/query/react/rtk-query-react.modern.mjs\"\n      },\n      \"default\": {\n        \"types\": \"./dist/query/react/index.d.ts\",\n        \"default\": \"./dist/query/react/cjs/index.js\"\n      }\n    }\n  },\n  \"devDependencies\": {\n    \"@arethetypeswrong/cli\": \"^0.18.2\",\n    \"@babel/core\": \"^7.24.8\",\n    \"@babel/helper-module-imports\": \"^7.24.7\",\n    \"@microsoft/api-extractor\": \"^7.13.2\",\n    \"@phryneas/ts-version\": \"^1.0.2\",\n    \"@size-limit/file\": \"^11.0.1\",\n    \"@size-limit/webpack\": \"^11.0.1\",\n    \"@tanstack/intent\": \"^0.0.19\",\n    \"@testing-library/dom\": \"^10.4.0\",\n    \"@testing-library/react\": \"^16.0.1\",\n    \"@testing-library/react-render-stream\": \"^1.0.3\",\n    \"@testing-library/user-event\": \"^14.5.2\",\n    \"@types/babel__core\": \"^7.20.5\",\n    \"@types/babel__helper-module-imports\": \"^7.18.3\",\n    \"@types/node\": \"^25.5.0\",\n    \"@types/query-string\": \"^6.3.0\",\n    \"@types/react\": \"^19.0.1\",\n    \"@types/react-dom\": \"^19.0.1\",\n    \"@typescript-eslint/eslint-plugin\": \"^6\",\n    \"@typescript-eslint/parser\": \"^6\",\n    \"axios\": \"^0.19.2\",\n    \"esbuild\": \"^0.25.1\",\n    \"esbuild-extra\": \"^0.4.0\",\n    \"eslint\": \"^7.25.0\",\n    \"eslint-config-prettier\": \"^9.1.0\",\n    \"eslint-config-react-app\": \"^7.0.1\",\n    \"eslint-plugin-flowtype\": \"^5.7.2\",\n    \"eslint-plugin-import\": \"^2.22.1\",\n    \"eslint-plugin-jsx-a11y\": \"^6.4.1\",\n    \"eslint-plugin-prettier\": \"^5.1.3\",\n    \"eslint-plugin-react\": \"^7.23.2\",\n    \"eslint-plugin-react-hooks\": \"^4.2.0\",\n    \"jsdom\": \"^25.0.1\",\n    \"msw\": \"^2.1.4\",\n    \"node-fetch\": \"^3.3.2\",\n    \"prettier\": \"^3.2.5\",\n    \"query-string\": \"^7.0.1\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-redux\": \"^9.2.0\",\n    \"rimraf\": \"^6.1.3\",\n    \"size-limit\": \"^11.0.1\",\n    \"tsup\": \"^8.4.0\",\n    \"tsx\": \"^4.19.0\",\n    \"typescript\": \"^5.9.3\",\n    \"valibot\": \"^1.0.0\",\n    \"vite-tsconfig-paths\": \"^4.3.1\",\n    \"vitest\": \"^4\"\n  },\n  \"scripts\": {\n    \"clean\": \"rimraf dist\",\n    \"run-build\": \"tsup --config=$INIT_CWD/tsup.config.mts\",\n    \"build\": \"yarn clean && yarn run-build && tsx scripts/fixUniqueSymbolExports.mts\",\n    \"build-only\": \"yarn clean && yarn run-build\",\n    \"format\": \"prettier --write \\\"(src|examples)/**/*.{ts,tsx}\\\" \\\"**/*.md\\\"\",\n    \"format:check\": \"prettier --list-different \\\"(src|examples)/**/*.{ts,tsx}\\\" \\\"docs/*/**.md\\\"\",\n    \"lint\": \"eslint src examples\",\n    \"test\": \"vitest --typecheck --run \",\n    \"test:watch\": \"vitest --watch\",\n    \"type-tests\": \"yarn tsc -p tsconfig.test.json --noEmit\",\n    \"prepack\": \"yarn build\",\n    \"size\": \"size-limit\"\n  },\n  \"files\": [\n    \"dist/\",\n    \"src/\",\n    \"query\",\n    \"react\",\n    \"skills\",\n    \"!skills/_artifacts\"\n  ],\n  \"dependencies\": {\n    \"@standard-schema/spec\": \"^1.0.0\",\n    \"@standard-schema/utils\": \"^0.3.0\",\n    \"immer\": \"^11.0.0\",\n    \"redux\": \"^5.0.1\",\n    \"redux-thunk\": \"^3.1.0\",\n    \"reselect\": \"^5.1.0\"\n  },\n  \"peerDependencies\": {\n    \"react\": \"^16.9.0 || ^17.0.0 || ^18 || ^19\",\n    \"react-redux\": \"^7.2.1 || ^8.1.3 || ^9.0.0\"\n  },\n  \"peerDependenciesMeta\": {\n    \"react\": {\n      \"optional\": true\n    },\n    \"react-redux\": {\n      \"optional\": true\n    }\n  },\n  \"sideEffects\": false,\n  \"bugs\": {\n    \"url\": \"https://github.com/reduxjs/redux-toolkit/issues\"\n  },\n  \"homepage\": \"https://redux-toolkit.js.org\"\n}\n"
  },
  {
    "path": "packages/toolkit/query/package.json",
    "content": "{\n  \"name\": \"@reduxjs/toolkit-query\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"type\": \"module\",\n  \"module\": \"../dist/query/rtk-query.legacy-esm.js\",\n  \"main\": \"../dist/query/cjs/index.js\",\n  \"types\": \"./../dist/query/index.d.ts\",\n  \"react-native\": \"./../dist/query/rtk-query.legacy-esm.js\",\n  \"author\": \"Mark Erikson <mark@isquaredsoftware.com>\",\n  \"license\": \"MIT\",\n  \"sideEffects\": false\n}\n"
  },
  {
    "path": "packages/toolkit/query/react/package.json",
    "content": "{\n  \"name\": \"@reduxjs/toolkit-query-react\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"type\": \"module\",\n  \"module\": \"../../dist/query/react/rtk-query-react.legacy-esm.js\",\n  \"main\": \"../../dist/query/react/cjs/index.js\",\n  \"types\": \"./../../dist/query/react/index.d.ts\",\n  \"react-native\": \"./../../dist/query/react/rtk-query-react.legacy-esm.js\",\n  \"author\": \"Mark Erikson <mark@isquaredsoftware.com>\",\n  \"license\": \"MIT\",\n  \"sideEffects\": false\n}\n"
  },
  {
    "path": "packages/toolkit/react/package.json",
    "content": "{\n  \"name\": \"@reduxjs/toolkit-react\",\n  \"version\": \"1.0.0\",\n  \"description\": \"\",\n  \"type\": \"module\",\n  \"module\": \"../dist/react/redux-toolkit-react.legacy-esm.js\",\n  \"main\": \"./../dist/react/redux-toolkit-react.modern.mjs\",\n  \"types\": \"./../dist/react/index.d.ts\",\n  \"react-native\": \"./../dist/react/redux-toolkit-react.modern.mjs\",\n  \"author\": \"Mark Erikson <mark@isquaredsoftware.com>\",\n  \"license\": \"MIT\",\n  \"sideEffects\": false\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/fixUniqueSymbolExports.mts",
    "content": "#!/usr/bin/env node --import=tsx\n\nimport * as fs from 'node:fs/promises'\nimport * as path from 'node:path'\n\nconst entryPointDirectories = ['', 'react', 'query', 'query/react']\n\nconst typeDefinitionEntryFiles = entryPointDirectories.flatMap(\n  (filePath) =>\n    [\n      path.join(import.meta.dirname, '..', 'dist', filePath, 'index.d.ts'),\n      path.join(import.meta.dirname, '..', 'dist', filePath, 'index.d.mts'),\n    ] as const,\n)\n\nconst filePathsToContentMap = new Map<string, string>(\n  await Promise.all(\n    typeDefinitionEntryFiles.map(\n      async (filePath) =>\n        [filePath, await fs.readFile(filePath, { encoding: 'utf-8' })] as const,\n    ),\n  ),\n)\n\nconst main = async () => {\n  filePathsToContentMap.forEach(async (content, filePath) => {\n    const exportedUniqueSymbols = new Set<string>()\n\n    console.log(`Fixing \\`unique symbol\\` exports in ${filePath}`)\n\n    const lines = content.split('\\n')\n\n    const allUniqueSymbols = lines\n      .filter((line) => /declare const (\\w+): unique symbol;/.test(line))\n      .map((line) => line.match(/declare const (\\w+): unique symbol;/)?.[1])\n\n    if (allUniqueSymbols.length === 0) {\n      console.log(`${filePath} does not have any unique symbols.`)\n\n      return\n    }\n\n    const allNamedExports = lines\n      .at(-2)\n      ?.match(/^export \\{ (.*) \\};$/)?.[1]\n      .split(', ')\n\n    allNamedExports?.forEach((namedExport) => {\n      if (allUniqueSymbols.includes(namedExport)) {\n        exportedUniqueSymbols.add(namedExport)\n      }\n    })\n\n    if (exportedUniqueSymbols.size === 0) {\n      console.log(\n        `${filePath} has unique symbols but none of them are exported.`,\n      )\n\n      return\n    }\n\n    let newContent = `${lines.slice(0, -2).join('\\n')}\\nexport { ${allNamedExports?.filter((namedExport) => !exportedUniqueSymbols.has(namedExport)).join(', ')} };\\n`\n\n    exportedUniqueSymbols.forEach((uniqueSymbol) => {\n      console.log(`Exporting \\`${uniqueSymbol}\\` from ${filePath}`)\n\n      newContent = newContent.replace(\n        `declare const ${uniqueSymbol}`,\n        `export declare const ${uniqueSymbol}`,\n      )\n    })\n\n    await fs.writeFile(filePath, newContent, { encoding: 'utf-8' })\n  })\n}\n\nvoid main()\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/.gitignore",
    "content": "# Dependencies\nnode_modules/\n\n# Build output\ndist/\n\n# Cache\ncache/\n\n# Environment variables\n.env\n.env.local\n\n# IDE\n.vscode/\n.idea/\n\n# OS\n.DS_Store\nThumbs.db"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/README-github-issue-to-markdown.md",
    "content": "# GitHub Issue to Markdown Converter\n\nA standalone TypeScript script that converts GitHub issue JSON files (with comments) into readable Markdown format.\n\n## Features\n\n- Converts GitHub issue JSON to clean Markdown\n- Includes issue metadata (author, date, comment count)\n- Formats all comments with author and date information\n- Highlights author associations (MEMBER, CONTRIBUTOR, etc.)\n- Uses only built-in Node.js modules (no dependencies)\n- Can be run with Bun, Node.js, or ts-node\n\n## Usage\n\n### With Bun (recommended)\n\n```bash\nbun run packages/toolkit/scripts/github-issue-to-markdown.ts <input-json-file> [output-md-file]\n```\n\n### With ts-node\n\n```bash\nnpx ts-node packages/toolkit/scripts/github-issue-to-markdown.ts <input-json-file> [output-md-file]\n```\n\n### With Node.js (after compilation)\n\n```bash\ntsc packages/toolkit/scripts/github-issue-to-markdown.ts\nnode packages/toolkit/scripts/github-issue-to-markdown.js <input-json-file> [output-md-file]\n```\n\n## Arguments\n\n- `<input-json-file>` (required): Path to the GitHub issue JSON file\n- `[output-md-file]` (optional): Path for the output Markdown file. If not specified, uses the input filename with `.md` extension\n\n## Examples\n\n### Basic usage (auto-generate output filename)\n\n```bash\nbun run packages/toolkit/scripts/github-issue-to-markdown.ts docs/dev-plans/issue-3692-comments.json\n# Creates: docs/dev-plans/issue-3692-comments.md\n```\n\n### Specify output filename\n\n```bash\nbun run packages/toolkit/scripts/github-issue-to-markdown.ts docs/dev-plans/issue-3692-comments.json docs/dev-plans/rtk-query-feedback.md\n```\n\n## Input Format\n\nThe script expects a JSON file with the following structure:\n\n```json\n{\n  \"number\": 3692,\n  \"title\": \"Issue title\",\n  \"user\": {\n    \"login\": \"username\",\n    \"id\": 12345\n  },\n  \"created_at\": \"2023-09-01T17:41:01Z\",\n  \"updated_at\": \"2023-09-01T17:41:01Z\",\n  \"body\": \"Issue description...\",\n  \"author_association\": \"MEMBER\",\n  \"comments\": 106,\n  \"comments_data\": [\n    {\n      \"id\": 1703237481,\n      \"user\": {\n        \"login\": \"commenter\",\n        \"id\": 67890\n      },\n      \"created_at\": \"2023-09-01T19:35:29Z\",\n      \"updated_at\": \"2023-09-01T19:35:29Z\",\n      \"body\": \"Comment text...\",\n      \"author_association\": \"NONE\"\n    }\n  ]\n}\n```\n\n## Output Format\n\nThe script generates a Markdown file with:\n\n1. Issue header with number and title\n2. Issue metadata (author, date, comment count)\n3. Issue description\n4. All comments with:\n   - Horizontal rule separator\n   - Comment author and date\n   - Author association badge (if not NONE)\n   - Comment body text\n\n## Notes\n\n- Dates are formatted as YYYY-MM-DD\n- The script preserves all Markdown formatting in issue/comment bodies\n- Author associations like MEMBER, CONTRIBUTOR are displayed as emphasized text\n- Comments are separated by horizontal rules (`---`) for readability\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/README.md",
    "content": "# GitHub Issues Triage Tool\n\nA TypeScript-based tool for automatically triaging and categorizing GitHub issues in the Redux Toolkit repository.\n\n## Features\n\n- Fetches open issues from GitHub API\n- Categorizes issues based on labels, titles, and content\n- Generates markdown reports with statistics\n- Caches data to avoid API rate limiting\n- Supports both Node.js and Bun runtimes\n\n## Setup\n\n1. Install dependencies:\n\n```bash\nnpm install\n```\n\n2. Build the TypeScript code:\n\n```bash\nnpm run build\n```\n\n## Usage\n\nRun the triage tool:\n\n```bash\nnpm start\n```\n\nOr for development (builds and runs):\n\n```bash\nnpm run dev\n```\n\n### Using Cached Data\n\nThe tool automatically saves fetched data to `cache/issues-data.json` after each run. To use cached data instead of fetching fresh data (useful for development and testing):\n\n```bash\nnpm start -- --use-cache\n```\n\nOr with the dev command:\n\n```bash\nnpm run dev -- --use-cache\n```\n\n**Note:** The `--use-cache` flag is primarily for development/testing purposes. It loads data from the cache file instantly without making API calls. If the cache file doesn't exist or is corrupted, the tool will automatically fetch fresh data.\n\n## Project Structure\n\n```\nscripts/issue-triage/\n├── src/           # TypeScript source files\n├── dist/          # Compiled JavaScript output\n├── cache/         # Cached JSON data from GitHub\n├── reports/       # Generated triage reports\n├── package.json   # Project dependencies\n└── tsconfig.json  # TypeScript configuration\n```\n\n## Requirements\n\n- Node.js 18+ or Bun 1.0+\n- TypeScript 5.0+\n\n## Development\n\nThis tool is built with TypeScript using ES modules (ESM). The configuration supports both Node.js and Bun runtimes for maximum flexibility.\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/github-issue-to-markdown.ts",
    "content": "#!/usr/bin/env node\n/**\n * Converts a GitHub issue JSON file (with comments) to a readable Markdown format.\n *\n * Usage:\n *   bun run github-issue-to-markdown.ts <input-json-file> [output-md-file]\n *\n * If output file is not specified, it will use the input filename with .md extension\n */\n\nimport { readFileSync, writeFileSync } from 'fs'\nimport { resolve, dirname, basename, extname } from 'path'\n\ninterface GitHubUser {\n  login: string\n  id: number\n}\n\ninterface GitHubComment {\n  id: number\n  user: GitHubUser\n  created_at: string\n  updated_at: string\n  body: string\n  author_association: string\n}\n\ninterface GitHubIssue {\n  number: number\n  title: string\n  user: GitHubUser\n  created_at: string\n  updated_at: string\n  body: string\n  author_association: string\n  comments: number\n  comments_data?: GitHubComment[]\n}\n\nfunction formatDate(dateString: string): string {\n  const date = new Date(dateString)\n  return date.toISOString().split('T')[0]\n}\n\nfunction convertIssueToMarkdown(issue: GitHubIssue): string {\n  let markdown = ''\n\n  // Issue header\n  markdown += `# Issue #${issue.number}: ${issue.title}\\n\\n`\n\n  // Issue metadata\n  markdown += `**Author:** ${issue.user.login}\\n`\n  markdown += `**Date:** ${formatDate(issue.created_at)}\\n`\n  markdown += `**Comments:** ${issue.comments}\\n\\n`\n\n  // Issue body\n  markdown += `## Issue Description\\n\\n`\n  markdown += `${issue.body}\\n\\n`\n\n  // Comments section\n  if (issue.comments_data && issue.comments_data.length > 0) {\n    markdown += `## Comments (${issue.comments_data.length})\\n\\n`\n\n    for (const comment of issue.comments_data) {\n      markdown += `---\\n\\n`\n      markdown += `### Comment by ${comment.user.login} on ${formatDate(comment.created_at)}\\n\\n`\n\n      if (comment.author_association && comment.author_association !== 'NONE') {\n        markdown += `_${comment.author_association}_\\n\\n`\n      }\n\n      markdown += `${comment.body}\\n\\n`\n    }\n  }\n\n  return markdown\n}\n\nfunction main() {\n  const args = process.argv.slice(2)\n\n  if (args.length === 0) {\n    console.error('Error: No input file specified')\n    console.error(\n      'Usage: bun run github-issue-to-markdown.ts <input-json-file> [output-md-file]',\n    )\n    process.exit(1)\n  }\n\n  const inputFile = resolve(args[0])\n  let outputFile: string\n\n  if (args.length > 1) {\n    outputFile = resolve(args[1])\n  } else {\n    // Generate output filename from input filename\n    const dir = dirname(inputFile)\n    const base = basename(inputFile, extname(inputFile))\n    outputFile = resolve(dir, `${base}.md`)\n  }\n\n  try {\n    // Read and parse JSON file\n    console.log(`Reading ${inputFile}...`)\n    const jsonContent = readFileSync(inputFile, 'utf-8')\n    const issue: GitHubIssue = JSON.parse(jsonContent)\n\n    // Convert to Markdown\n    console.log('Converting to Markdown...')\n    const markdown = convertIssueToMarkdown(issue)\n\n    // Write output file\n    console.log(`Writing to ${outputFile}...`)\n    writeFileSync(outputFile, markdown, 'utf-8')\n\n    console.log('✓ Conversion complete!')\n    console.log(`  Input:  ${inputFile}`)\n    console.log(`  Output: ${outputFile}`)\n    console.log(`  Comments: ${issue.comments_data?.length || 0}`)\n  } catch (error) {\n    if (error instanceof Error) {\n      console.error(`Error: ${error.message}`)\n    } else {\n      console.error('An unknown error occurred')\n    }\n    process.exit(1)\n  }\n}\n\nmain()\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/package.json",
    "content": "{\n  \"name\": \"github-issues-triage\",\n  \"version\": \"1.0.0\",\n  \"description\": \"Tool for triaging and categorizing GitHub issues\",\n  \"type\": \"module\",\n  \"scripts\": {\n    \"start\": \"bun src/index.ts\",\n    \"build\": \"tsc\"\n  },\n  \"keywords\": [\n    \"github\",\n    \"issues\",\n    \"triage\"\n  ],\n  \"author\": \"\",\n  \"license\": \"MIT\",\n  \"devDependencies\": {\n    \"@types/node\": \"^25.5.0\",\n    \"typescript\": \"^5.9.3\"\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/categorize/categorizer.ts",
    "content": "/**\n * Issue categorization logic\n */\n\nimport type { Issue } from '../github/types.js'\nimport type { Categorization } from './types.js'\nimport { CATEGORIES, type CategoryConfig } from './config.js'\n\n/**\n * Normalize text for matching (lowercase, trim)\n */\nfunction normalizeText(text: string): string {\n  return text.toLowerCase().trim()\n}\n\n/**\n * Remove stack traces from text to avoid false matches\n */\nfunction removeStackTraces(text: string): string {\n  return text\n    .split('\\n')\n    .filter((line) => {\n      const trimmed = line.trim()\n      // Skip lines starting with \"at \" (stack traces)\n      if (trimmed.startsWith('at ')) return false\n      // Skip lines with file paths (e.g., \"node_modules/\", \"src/\", \".js:\", \".ts:\")\n      if (/node_modules|\\.js:|\\.ts:|\\.tsx:|\\.jsx:/.test(trimmed)) return false\n      return true\n    })\n    .join('\\n')\n}\n\n/**\n * Detect multi-word phrases with higher confidence\n */\nfunction detectPhrases(text: string): Map<string, number> {\n  const phrases = new Map<string, number>()\n  const lowerText = text.toLowerCase()\n\n  // High-value phrases that should boost category scores\n  const phrasePatterns: Record<string, string[]> = {\n    'rtk-query': [\n      'rtk query',\n      'rtk-query',\n      'createapi',\n      'fetch base query',\n      'optimistic update',\n      'cache invalidation',\n    ],\n    codegen: [\n      'code generation',\n      'openapi',\n      'swagger',\n      'output files',\n      'codegen',\n      'rtk-query codegen',\n      '@rtk-query/codegen-openapi',\n      'generate api',\n      'generate endpoints',\n    ],\n    'build-tooling': ['webpack', 'vite', 'rollup', 'bundler'],\n    publishing: [\n      'npm publish',\n      'trusted publishing',\n      'provenance',\n      'package registry',\n    ],\n    migration: ['migration guide', 'breaking change', 'upgrade path'],\n    architecture: ['api design', 'architecture decision', 'design pattern'],\n  }\n\n  for (const [category, categoryPhrases] of Object.entries(phrasePatterns)) {\n    let score = 0\n    for (const phrase of categoryPhrases) {\n      if (lowerText.includes(phrase)) {\n        score += 3.0 // High score for phrase matches\n      }\n    }\n    if (score > 0) {\n      phrases.set(category, score)\n    }\n  }\n\n  return phrases\n}\n\n/**\n * Check if issue has any matching labels (Tier 1)\n */\nfunction checkLabels(issue: Issue): Categorization | null {\n  const issueLabels = issue.labels.map(normalizeText)\n\n  for (const category of CATEGORIES) {\n    if (category.name === 'uncategorized') continue\n\n    const hasMatchingLabel = category.labels.some((label) =>\n      issueLabels.includes(normalizeText(label)),\n    )\n\n    if (hasMatchingLabel) {\n      const type = detectIssueType(issue)\n      const subcategory = findSubcategory(issue, category)\n\n      return {\n        primary: category.name,\n        secondary: subcategory,\n        type,\n        confidence: 0.95,\n        method: 'label',\n      }\n    }\n  }\n\n  return null\n}\n\n/**\n * Calculate keyword scores for each category (Tier 2)\n * Implements context-aware matching with title prioritization\n */\nfunction calculateKeywordScores(issue: Issue): Map<string, number> {\n  const scores = new Map<string, number>()\n  const title = normalizeText(issue.title)\n  const body = normalizeText(issue.body || '')\n\n  // Remove stack traces from body for matching\n  const bodyWithoutStackTraces = removeStackTraces(body)\n\n  // Add phrase detection before keyword matching\n  const phraseScores = detectPhrases(`${title} ${bodyWithoutStackTraces}`)\n  for (const [category, phraseScore] of phraseScores) {\n    const currentScore = scores.get(category) || 0\n    scores.set(category, currentScore + phraseScore)\n  }\n\n  for (const category of CATEGORIES) {\n    if (category.name === 'uncategorized') continue\n\n    let score = 0\n\n    // Check keywords with title prioritization (2x weight for title)\n    for (const keyword of category.keywords) {\n      const normalizedKeyword = normalizeText(keyword)\n\n      // Title matches (2x weight)\n      const titleMatches = (\n        title.match(\n          new RegExp(\n            normalizedKeyword.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'),\n            'gi',\n          ),\n        ) || []\n      ).length\n      score += titleMatches * category.weight * 2.0\n\n      // Body matches (1x weight, excluding stack traces)\n      const bodyMatches = (\n        bodyWithoutStackTraces.match(\n          new RegExp(\n            normalizedKeyword.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&'),\n            'gi',\n          ),\n        ) || []\n      ).length\n      score += bodyMatches * category.weight\n    }\n\n    // Check patterns (1.5x weight for title, 1x for body)\n    for (const pattern of category.patterns) {\n      if (pattern.test(title)) {\n        score += category.weight * 1.5\n      } else if (pattern.test(bodyWithoutStackTraces)) {\n        score += category.weight\n      }\n    }\n\n    // Penalty for documentation category on bugs\n    if (category.name === 'documentation' && detectIssueType(issue) === 'bug') {\n      score *= 0.5\n    }\n\n    if (score > 0) {\n      scores.set(category.name, score)\n    }\n  }\n\n  return scores\n}\n\n/**\n * Detect patterns in issue content (Tier 3)\n */\nfunction detectPatterns(issue: Issue): Categorization | null {\n  const scores = calculateKeywordScores(issue)\n\n  if (scores.size === 0) {\n    return null\n  }\n\n  // Get the highest scoring category\n  let maxScore = 0\n  let topCategory = ''\n\n  for (const [category, score] of scores.entries()) {\n    if (score > maxScore) {\n      maxScore = score\n      topCategory = category\n    }\n  }\n\n  // Require a minimum score threshold\n  if (maxScore < 2.0) {\n    return null\n  }\n\n  const categoryConfig = CATEGORIES.find((c) => c.name === topCategory)\n  if (!categoryConfig) return null\n\n  const type = detectIssueType(issue)\n  const subcategory = findSubcategory(issue, categoryConfig)\n\n  // Calculate confidence based on score\n  const confidence = Math.min(0.85, 0.5 + maxScore * 0.1)\n\n  return {\n    primary: topCategory,\n    secondary: subcategory,\n    type,\n    confidence,\n    method: 'pattern',\n  }\n}\n\n/**\n * Find subcategory within a primary category\n */\nfunction findSubcategory(\n  issue: Issue,\n  category: CategoryConfig,\n): string | undefined {\n  if (!category.subcategories) return undefined\n\n  const text = normalizeText(`${issue.title} ${issue.body}`)\n  let maxScore = 0\n  let topSubcategory = ''\n\n  for (const subcategory of category.subcategories) {\n    let score = 0\n\n    // Check keywords\n    for (const keyword of subcategory.keywords) {\n      if (text.includes(normalizeText(keyword))) {\n        score += 1\n      }\n    }\n\n    // Check patterns\n    for (const pattern of subcategory.patterns) {\n      if (pattern.test(issue.title) || pattern.test(issue.body)) {\n        score += 2\n      }\n    }\n\n    if (score > maxScore) {\n      maxScore = score\n      topSubcategory = subcategory.name\n    }\n  }\n\n  // Require minimum score for subcategory\n  return maxScore >= 1 ? topSubcategory : undefined\n}\n\n/**\n * Detect issue type (bug, feature, question, docs)\n */\nfunction detectIssueType(\n  issue: Issue,\n): 'bug' | 'feature' | 'question' | 'docs' {\n  const labels = issue.labels.map(normalizeText)\n  const text = normalizeText(`${issue.title} ${issue.body}`)\n\n  // Check labels first\n  if (\n    labels.some((l) => ['bug', 'type: bug', 'regression', 'defect'].includes(l))\n  ) {\n    return 'bug'\n  }\n\n  if (\n    labels.some((l) =>\n      ['enhancement', 'feature', 'feature request', 'type: feature'].includes(\n        l,\n      ),\n    )\n  ) {\n    return 'feature'\n  }\n\n  if (labels.some((l) => ['documentation', 'docs', 'type: docs'].includes(l))) {\n    return 'docs'\n  }\n\n  if (\n    labels.some((l) =>\n      ['question', 'help wanted', 'type: question'].includes(l),\n    )\n  ) {\n    return 'question'\n  }\n\n  // Check content patterns\n  if (\n    /\\b(bug|error|issue|broken|not working|doesn't work|crash|fail)/i.test(text)\n  ) {\n    return 'bug'\n  }\n\n  if (\n    /\\b(feature|enhancement|add|support|would be nice|could we|suggestion)/i.test(\n      text,\n    )\n  ) {\n    return 'feature'\n  }\n\n  if (/\\b(how|what|why|when|where|question|\\?)/i.test(issue.title)) {\n    return 'question'\n  }\n\n  if (/\\b(docs|documentation|readme|guide|tutorial|example)/i.test(text)) {\n    return 'docs'\n  }\n\n  // Default to question for unclear cases\n  return 'question'\n}\n\n/**\n * Main categorization function using multi-tier approach\n * Implements confidence scoring based on match location\n */\nexport function categorizeIssue(issue: Issue): Categorization {\n  // Tier 1: Label-based (highest confidence - 95%)\n  const labelResult = checkLabels(issue)\n  if (labelResult) {\n    return labelResult\n  }\n\n  // Tier 2: Keyword matching with context-aware scoring\n  const scores = calculateKeywordScores(issue)\n  if (scores.size > 0) {\n    let maxScore = 0\n    let topCategory = ''\n\n    for (const [category, score] of scores.entries()) {\n      if (score > maxScore) {\n        maxScore = score\n        topCategory = category\n      }\n    }\n\n    if (maxScore >= 2.0) {\n      const categoryConfig = CATEGORIES.find((c) => c.name === topCategory)\n      if (categoryConfig) {\n        const type = detectIssueType(issue)\n        const subcategory = findSubcategory(issue, categoryConfig)\n\n        // Adjust confidence based on match strength and location\n        let confidence: number\n        if (maxScore > 6.0) {\n          // Strong title match (score > 3 * 2.0)\n          confidence = 0.9\n        } else if (maxScore > 4.0) {\n          // Good body match (score > 2 * 2.0)\n          confidence = 0.8\n        } else {\n          // Pattern detection level\n          confidence = 0.7\n        }\n\n        return {\n          primary: topCategory,\n          secondary: subcategory,\n          type,\n          confidence,\n          method: 'keyword',\n        }\n      }\n    }\n  }\n\n  // Tier 3: Pattern detection (70% confidence)\n  const patternResult = detectPatterns(issue)\n  if (patternResult) {\n    return patternResult\n  }\n\n  // Fallback: Uncategorized (60% confidence)\n  return {\n    primary: 'uncategorized',\n    type: detectIssueType(issue),\n    confidence: 0.6,\n    method: 'manual',\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/categorize/config.ts",
    "content": "/**\n * Category configuration for issue categorization\n */\n\nexport interface CategoryConfig {\n  name: string\n  displayName: string\n  labels: string[]\n  keywords: string[]\n  patterns: RegExp[]\n  weight: number\n  subcategories?: SubcategoryConfig[]\n}\n\nexport interface SubcategoryConfig {\n  name: string\n  displayName: string\n  keywords: string[]\n  patterns: RegExp[]\n}\n\n/**\n * Primary category configurations\n */\nexport const CATEGORIES: CategoryConfig[] = [\n  {\n    name: 'rtk-query',\n    displayName: 'RTK Query',\n    labels: ['RTK Query', 'rtk-query'],\n    keywords: [\n      'rtk query',\n      'rtkquery',\n      'createapi',\n      'endpoints',\n      'usemutation',\n      'usequery',\n      'uselazyquery',\n      'api slice',\n      'cache',\n      'invalidate',\n      'refetch',\n      'resetapistate',\n      'optimistic update',\n      'retry',\n      'abortcontroller',\n      'refetchonreconnect',\n      'keepunuseddatafor',\n      'serializequeryargs',\n    ],\n    patterns: [\n      /rtk[-\\s]?query/i,\n      /createApi/i,\n      /use\\w+Query/i,\n      /use\\w+Mutation/i,\n    ],\n    weight: 2.0,\n    subcategories: [\n      {\n        name: 'polling',\n        displayName: 'Polling',\n        keywords: ['polling', 'pollinginterval', 'refetchonmount'],\n        patterns: [/polling/i, /refetch/i],\n      },\n      {\n        name: 'cache',\n        displayName: 'Cache Management',\n        keywords: [\n          'cache',\n          'invalidate',\n          'invalidatetags',\n          'providestags',\n          'cache invalidation',\n          'resetapistate',\n          'keepunuseddatafor',\n        ],\n        patterns: [/cache/i, /invalidate/i, /tag/i],\n      },\n      {\n        name: 'hooks',\n        displayName: 'Query/Mutation Hooks',\n        keywords: ['usequery', 'usemutation', 'uselazyquery', 'hook'],\n        patterns: [/use\\w+Query/i, /use\\w+Mutation/i],\n      },\n      {\n        name: 'typescript-types',\n        displayName: 'TypeScript Types',\n        keywords: ['types', 'typing', 'inference', 'generic'],\n        patterns: [/type/i, /typing/i, /inference/i],\n      },\n      {\n        name: 'ssr',\n        displayName: 'Server-Side Rendering',\n        keywords: ['ssr', 'server side', 'nextjs', 'next.js', 'hydration'],\n        patterns: [/ssr/i, /server[-\\s]?side/i, /next\\.?js/i],\n      },\n      {\n        name: 'error-handling',\n        displayName: 'Error Handling',\n        keywords: ['error', 'error handling', 'retry', 'onerror'],\n        patterns: [/error/i, /retry/i],\n      },\n      {\n        name: 'optimistic-updates',\n        displayName: 'Optimistic Updates',\n        keywords: [\n          'optimistic',\n          'optimistic update',\n          'pessimistic',\n          'onquerystarted',\n          'updatequerydata',\n        ],\n        patterns: [/optimistic/i, /pessimistic/i, /onQueryStarted/i],\n      },\n      {\n        name: 'mutations',\n        displayName: 'Mutations',\n        keywords: ['mutation', 'usemutation', 'post', 'put', 'delete', 'patch'],\n        patterns: [/mutation/i, /useMutation/i],\n      },\n      {\n        name: 'queries',\n        displayName: 'Queries',\n        keywords: ['query', 'usequery', 'uselazyquery', 'get', 'fetch'],\n        patterns: [/\\bquery\\b/i, /useQuery/i, /useLazyQuery/i],\n      },\n    ],\n  },\n  {\n    name: 'codegen',\n    displayName: 'RTK Query Codegen',\n    labels: ['RTKQ-Codegen'],\n    keywords: [\n      'codegen',\n      'code generation',\n      'openapi',\n      'swagger',\n      '@rtk-query/codegen-openapi',\n      'rtk-query-codegen',\n      'generate',\n      'generated',\n      'api generation',\n    ],\n    patterns: [\n      /codegen/i,\n      /code[-\\s]?generation/i,\n      /openapi/i,\n      /swagger/i,\n      /@rtk-query\\/codegen/i,\n      /RTKQ-Codegen/i,\n    ],\n    weight: 2.0,\n    subcategories: [\n      {\n        name: 'type-generation',\n        displayName: 'Type Generation',\n        keywords: [\n          'type',\n          'types',\n          'typescript',\n          'nullable',\n          'readonly',\n          'writeonly',\n          'discriminator',\n          'anyOf',\n          'oneOf',\n          'allOf',\n          'circular',\n          'inference',\n          'discriminated union',\n        ],\n        patterns: [\n          /\\btype/i,\n          /nullable/i,\n          /discriminator/i,\n          /anyOf|oneOf|allOf/i,\n          /circular/i,\n        ],\n      },\n      {\n        name: 'parameter-handling',\n        displayName: 'Parameter Handling',\n        keywords: [\n          'parameter',\n          'parameters',\n          'queryArg',\n          'optional',\n          'required',\n          'collectionFormat',\n          'path parameter',\n          'query parameter',\n          'request body',\n        ],\n        patterns: [\n          /parameter/i,\n          /queryArg/i,\n          /collectionFormat/i,\n          /request\\s+body/i,\n        ],\n      },\n      {\n        name: 'configuration',\n        displayName: 'Configuration',\n        keywords: [\n          'config',\n          'configuration',\n          'outputFiles',\n          'filterEndpoints',\n          'basePath',\n          'apiFile',\n          'exportName',\n          'authorization',\n          'prefix',\n          'output files',\n        ],\n        patterns: [\n          /config/i,\n          /outputFiles/i,\n          /filterEndpoints/i,\n          /basePath/i,\n          /apiFile/i,\n        ],\n      },\n      {\n        name: 'openapi-features',\n        displayName: 'OpenAPI Features',\n        keywords: [\n          'openapi',\n          'swagger',\n          'spec',\n          'specification',\n          'content-type',\n          'response code',\n          '2XX',\n          'pattern',\n          'status code',\n        ],\n        patterns: [\n          /openapi/i,\n          /swagger/i,\n          /content[-\\s]?type/i,\n          /\\b2XX\\b/i,\n          /status\\s+code/i,\n        ],\n      },\n      {\n        name: 'hook-generation',\n        displayName: 'Hook Generation',\n        keywords: [\n          'hook',\n          'hooks',\n          'useQueryState',\n          'useQuery',\n          'useMutation',\n          'useLazyQuery',\n          'generated hooks',\n        ],\n        patterns: [\n          /hook/i,\n          /useQueryState/i,\n          /use\\w+Query/i,\n          /use\\w+Mutation/i,\n        ],\n      },\n      {\n        name: 'dependencies',\n        displayName: 'Dependencies',\n        keywords: [\n          'dependency',\n          'dependencies',\n          'oazapfts',\n          'typescript',\n          'ts 5',\n          'version',\n          'deepmerge',\n        ],\n        patterns: [\n          /dependency/i,\n          /oazapfts/i,\n          /typescript\\s+\\d/i,\n          /deepmerge/i,\n        ],\n      },\n    ],\n  },\n  {\n    name: 'core',\n    displayName: 'Core Redux Toolkit',\n    labels: ['core'],\n    keywords: [\n      'createslice',\n      'configurestore',\n      'createasyncthunk',\n      'middleware',\n      'reducer',\n      'action',\n      'dispatch',\n      'store setup',\n      'store config',\n    ],\n    patterns: [\n      /createSlice/i,\n      /configureStore/i,\n      /createAsyncThunk/i,\n      /middleware/i,\n    ],\n    weight: 1.3,\n    subcategories: [\n      {\n        name: 'createSlice',\n        displayName: 'createSlice',\n        keywords: ['createslice', 'slice', 'reducers', 'extrareducers'],\n        patterns: [/createSlice/i, /extraReducers/i],\n      },\n      {\n        name: 'configureStore',\n        displayName: 'configureStore',\n        keywords: ['configurestore', 'store', 'setup'],\n        patterns: [/configureStore/i],\n      },\n      {\n        name: 'createAsyncThunk',\n        displayName: 'createAsyncThunk',\n        keywords: [\n          'createasyncthunk',\n          'thunk',\n          'async',\n          'pending',\n          'fulfilled',\n        ],\n        patterns: [/createAsyncThunk/i, /\\.pending/i, /\\.fulfilled/i],\n      },\n      {\n        name: 'middleware',\n        displayName: 'Middleware',\n        keywords: ['middleware', 'listener', 'createlistenermiddleware'],\n        patterns: [/middleware/i, /listener/i],\n      },\n      {\n        name: 'devtools',\n        displayName: 'DevTools',\n        keywords: ['devtools', 'redux devtools', 'time travel'],\n        patterns: [/devtools/i],\n      },\n      {\n        name: 'immer',\n        displayName: 'Immer Integration',\n        keywords: ['immer', 'immutable', 'draft', 'produce'],\n        patterns: [/immer/i, /draft/i, /produce/i],\n      },\n    ],\n  },\n  {\n    name: 'typescript',\n    displayName: 'TypeScript',\n    labels: ['typescript', 'types'],\n    keywords: [\n      'typescript',\n      'types',\n      'typing',\n      'inference',\n      'generic',\n      'type error',\n      'type safety',\n    ],\n    patterns: [/typescript/i, /\\bts\\b/i, /type\\s+error/i, /inference/i],\n    weight: 1.2,\n  },\n  {\n    name: 'documentation',\n    displayName: 'Documentation',\n    labels: ['documentation', 'docs'],\n    keywords: [\n      'documentation',\n      'docs',\n      'tutorial',\n      'guide',\n      'example',\n      'readme',\n      'unclear',\n    ],\n    patterns: [/\\bdocs?\\b/i, /documentation/i, /tutorial/i, /example/i],\n    weight: 1.0,\n  },\n  {\n    name: 'build-tooling',\n    displayName: 'Build & Tooling',\n    labels: ['build', 'tooling'],\n    keywords: [\n      'build',\n      'webpack',\n      'vite',\n      'rollup',\n      'bundler',\n      'compilation',\n      'transpile',\n    ],\n    patterns: [/build/i, /webpack/i, /vite/i, /bundler/i],\n    weight: 1.0,\n    subcategories: [\n      {\n        name: 'bundling',\n        displayName: 'Bundling',\n        keywords: ['webpack', 'vite', 'rollup', 'bundler', 'build tool'],\n        patterns: [/webpack/i, /vite/i, /rollup/i],\n      },\n      {\n        name: 'dependencies',\n        displayName: 'Dependencies',\n        keywords: [\n          'dependency',\n          'dependencies',\n          'package',\n          'version conflict',\n          'peer dependency',\n        ],\n        patterns: [/dependency/i, /peer\\s+dep/i],\n      },\n    ],\n  },\n  {\n    name: 'publishing',\n    displayName: 'Publishing & Deployment',\n    labels: ['publishing', 'deployment'],\n    keywords: [\n      'npm',\n      'publishing',\n      'publish',\n      'provenance',\n      'trusted publishing',\n      'deployment',\n      'deploy',\n      'release',\n      'package',\n      'registry',\n      'npm publish',\n    ],\n    patterns: [\n      /\\bpublish(ing)?\\b/i,\n      /\\bnpm\\b/i,\n      /provenance/i,\n      /trusted\\s+publishing/i,\n    ],\n    weight: 1.5,\n  },\n  {\n    name: 'architecture',\n    displayName: 'Architecture & Design',\n    labels: ['architecture', 'design'],\n    keywords: [\n      'architecture',\n      'design',\n      'refactor',\n      'restructure',\n      'api design',\n      'breaking change',\n      'design pattern',\n    ],\n    patterns: [/architecture/i, /\\bapi\\s+design\\b/i, /design\\s+pattern/i],\n    weight: 1.3,\n  },\n  {\n    name: 'migration',\n    displayName: 'Migration & Upgrades',\n    labels: ['migration', 'upgrade'],\n    keywords: [\n      'migration',\n      'migrate',\n      'upgrade',\n      'v1 to v2',\n      'breaking change',\n      'migration guide',\n      'upgrade path',\n    ],\n    patterns: [/migrat(e|ion)/i, /upgrade/i, /v\\d+\\s+to\\s+v\\d+/i],\n    weight: 1.4,\n  },\n  {\n    name: 'future-planning',\n    displayName: 'Future Planning & Proposals',\n    labels: ['roadmap', 'proposal', 'rfc'],\n    keywords: [\n      'roadmap',\n      'future',\n      'v2',\n      'v3',\n      'next version',\n      'planning',\n      'proposal',\n      'rfc',\n    ],\n    patterns: [/roadmap/i, /\\bv\\d+\\b/i, /\\brfc\\b/i],\n    weight: 1.2,\n  },\n  {\n    name: 'uncategorized',\n    displayName: 'Uncategorized',\n    labels: [],\n    keywords: [],\n    patterns: [],\n    weight: 0,\n  },\n]\n\n/**\n * Get category by name\n */\nexport function getCategoryByName(name: string): CategoryConfig | undefined {\n  return CATEGORIES.find((cat) => cat.name === name)\n}\n\n/**\n * Get all category names\n */\nexport function getAllCategoryNames(): string[] {\n  return CATEGORIES.map((cat) => cat.name)\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/categorize/flags.ts",
    "content": "/**\n * Flag detection for special issue conditions\n */\n\nimport type { Issue } from '../github/types.js'\nimport type { Categorization, Flags, Scores } from './types.js'\n\n/**\n * Get age of issue in days\n */\nfunction getAgeInDays(date: Date): number {\n  const now = new Date()\n  const diffMs = now.getTime() - date.getTime()\n  return Math.floor(diffMs / (1000 * 60 * 60 * 24))\n}\n\n/**\n * Detect if issue is urgent\n */\nfunction isUrgent(issue: Issue, scores: Scores): boolean {\n  // High urgency score\n  if (scores.urgency >= 70) return true\n\n  // Critical labels\n  const labels = issue.labels.map((l) => l.toLowerCase())\n  if (\n    labels.includes('critical') ||\n    labels.includes('severity: critical') ||\n    labels.includes('security')\n  ) {\n    return true\n  }\n\n  // Critical keywords in title\n  const title = issue.title.toLowerCase()\n  if (\n    title.includes('crash') ||\n    title.includes('security') ||\n    title.includes('data loss')\n  ) {\n    return true\n  }\n\n  return false\n}\n\n/**\n * Detect if issue is an easy fix\n */\nfunction isEasyFix(issue: Issue, scores: Scores): boolean {\n  // Low complexity\n  if (scores.complexity < 30) return true\n\n  // Easy fix labels\n  const labels = issue.labels.map((l) => l.toLowerCase())\n  if (\n    labels.includes('good first issue') ||\n    labels.includes('easy') ||\n    labels.includes('beginner friendly')\n  ) {\n    return true\n  }\n\n  // Simple keywords\n  const text = `${issue.title} ${issue.body}`.toLowerCase()\n  const easyKeywords = ['typo', 'documentation', 'readme', 'simple fix']\n\n  for (const keyword of easyKeywords) {\n    if (text.includes(keyword)) {\n      return true\n    }\n  }\n\n  return false\n}\n\n/**\n * Detect if issue needs triage\n */\nfunction needsTriage(issue: Issue, categorization: Categorization): boolean {\n  // Uncategorized issues need triage\n  if (categorization.primary === 'uncategorized') return true\n\n  // Low confidence categorization\n  if (categorization.confidence < 0.6) return true\n\n  // No labels\n  if (issue.labels.length === 0) return true\n\n  // No type labels\n  const labels = issue.labels.map((l) => l.toLowerCase())\n  const hasTypeLabel = labels.some((l) =>\n    ['bug', 'feature', 'enhancement', 'documentation', 'question'].includes(l),\n  )\n\n  if (!hasTypeLabel) return true\n\n  return false\n}\n\n/**\n * Detect if issue is stale\n */\nfunction isStale(issue: Issue): boolean {\n  const daysSinceUpdate = getAgeInDays(issue.updated_at)\n\n  // Open issue with no activity for 90+ days\n  if (issue.state === 'open' && daysSinceUpdate > 90) {\n    return true\n  }\n\n  // Open issue with no comments for 60+ days\n  if (\n    issue.state === 'open' &&\n    issue.comment_count === 0 &&\n    daysSinceUpdate > 60\n  ) {\n    return true\n  }\n\n  return false\n}\n\n/**\n * Detect if issue mentions breaking changes\n */\nfunction hasBreakingChange(issue: Issue): boolean {\n  const text = `${issue.title} ${issue.body}`.toLowerCase()\n\n  const breakingKeywords = [\n    'breaking change',\n    'breaking',\n    'major version',\n    'backwards incompatible',\n    'breaking api',\n  ]\n\n  for (const keyword of breakingKeywords) {\n    if (text.includes(keyword)) {\n      return true\n    }\n  }\n\n  // Check labels\n  const labels = issue.labels.map((l) => l.toLowerCase())\n  if (labels.includes('breaking change') || labels.includes('breaking')) {\n    return true\n  }\n\n  return false\n}\n\n/**\n * Detect if issue needs reproduction\n */\nfunction needsRepro(issue: Issue): boolean {\n  const text = `${issue.title} ${issue.body}`.toLowerCase()\n\n  // Check for reproduction-related labels\n  const labels = issue.labels.map((l) => l.toLowerCase())\n  if (\n    labels.includes('needs reproduction') ||\n    labels.includes('needs repro') ||\n    labels.includes('cannot reproduce')\n  ) {\n    return true\n  }\n\n  // Bug reports without code examples might need repro\n  if (\n    labels.includes('bug') &&\n    !text.includes('```') &&\n    !text.includes('codesandbox') &&\n    !text.includes('stackblitz') &&\n    !text.includes('reproduction')\n  ) {\n    return true\n  }\n\n  // Keywords indicating need for reproduction\n  const needsReproKeywords = [\n    'cannot reproduce',\n    'need reproduction',\n    'needs repro',\n    'provide a reproduction',\n  ]\n\n  for (const keyword of needsReproKeywords) {\n    if (text.includes(keyword)) {\n      return true\n    }\n  }\n\n  return false\n}\n\n/**\n * Detect all flags for an issue\n */\nexport function detectFlags(\n  issue: Issue,\n  scores: Scores,\n  categorization: Categorization,\n): Flags {\n  return {\n    isUrgent: isUrgent(issue, scores),\n    isEasyFix: isEasyFix(issue, scores),\n    needsTriage: needsTriage(issue, categorization),\n    isStale: isStale(issue),\n    hasBreakingChange: hasBreakingChange(issue),\n    needsRepro: needsRepro(issue),\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/categorize/index.ts",
    "content": "/**\n * Main categorization pipeline\n */\n\nimport type { Issue } from '../github/types.js'\nimport type { CategorizedIssue } from './types.js'\nimport { categorizeIssue } from './categorizer.js'\nimport { calculateScores } from './scoring.js'\nimport { detectFlags } from './flags.js'\n\n/**\n * Categorize a single issue with scores and flags\n */\nexport function categorizeSingleIssue(issue: Issue): CategorizedIssue {\n  // Step 1: Categorize the issue\n  const categorization = categorizeIssue(issue)\n\n  // Step 2: Calculate scores\n  const scores = calculateScores(issue)\n\n  // Step 3: Detect flags\n  const flags = detectFlags(issue, scores, categorization)\n\n  // Step 4: Combine into categorized issue\n  return {\n    ...issue,\n    categorization,\n    scores,\n    flags,\n  }\n}\n\n/**\n * Categorize multiple issues\n */\nexport function categorizeIssues(issues: Issue[]): CategorizedIssue[] {\n  return issues.map((issue) => categorizeSingleIssue(issue))\n}\n\n// Re-export types for convenience\nexport type {\n  CategorizedIssue,\n  Categorization,\n  Scores,\n  Flags,\n} from './types.js'\nexport { CATEGORIES, getCategoryByName, getAllCategoryNames } from './config.js'\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/categorize/scoring.ts",
    "content": "/**\n * Scoring algorithms for issues\n */\n\nimport type { Issue } from '../github/types.js'\nimport type { Scores } from './types.js'\n\n/**\n * Get age of issue in days\n */\nfunction getAgeInDays(date: Date): number {\n  const now = new Date()\n  const diffMs = now.getTime() - date.getTime()\n  return Math.floor(diffMs / (1000 * 60 * 60 * 24))\n}\n\n/**\n * Calculate urgency score (0-100)\n * Based on: severity indicators, reactions, comments, age\n */\nexport function calculateUrgencyScore(issue: Issue): number {\n  let score = 0\n  const text = `${issue.title} ${issue.body}`.toLowerCase()\n  const age = getAgeInDays(issue.created_at)\n\n  // Severity keywords (0-40 points)\n  const criticalKeywords = [\n    'crash',\n    'critical',\n    'security',\n    'data loss',\n    'breaking',\n    'regression',\n  ]\n  const highKeywords = ['error', 'bug', 'broken', 'not working', 'fails']\n\n  for (const keyword of criticalKeywords) {\n    if (text.includes(keyword)) {\n      score += 10\n    }\n  }\n\n  for (const keyword of highKeywords) {\n    if (text.includes(keyword)) {\n      score += 5\n    }\n  }\n\n  // Labels (0-20 points)\n  const labels = issue.labels.map((l) => l.toLowerCase())\n  if (labels.includes('critical') || labels.includes('severity: critical')) {\n    score += 20\n  } else if (labels.includes('high') || labels.includes('severity: high')) {\n    score += 15\n  } else if (labels.includes('bug') || labels.includes('type: bug')) {\n    score += 10\n  }\n\n  // Community engagement (0-20 points)\n  // More comments/reactions = more people affected\n  if (issue.comment_count > 20) {\n    score += 20\n  } else if (issue.comment_count > 10) {\n    score += 15\n  } else if (issue.comment_count > 5) {\n    score += 10\n  } else if (issue.comment_count > 2) {\n    score += 5\n  }\n\n  // Age factor (0-20 points)\n  // Older issues that are still open might be more urgent\n  if (age > 90) {\n    score += 20\n  } else if (age > 60) {\n    score += 15\n  } else if (age > 30) {\n    score += 10\n  } else if (age < 7) {\n    // Very new issues get slight boost\n    score += 5\n  }\n\n  return Math.min(100, score)\n}\n\n/**\n * Calculate complexity score (0-100)\n * Based on: indicators in content, length, technical depth\n */\nexport function calculateComplexityScore(issue: Issue): number {\n  let score = 50 // Start at medium complexity\n  const text = `${issue.title} ${issue.body}`.toLowerCase()\n\n  // Simple indicators (reduce complexity)\n  const simpleKeywords = [\n    'typo',\n    'documentation',\n    'readme',\n    'example',\n    'simple',\n    'quick',\n  ]\n  for (const keyword of simpleKeywords) {\n    if (text.includes(keyword)) {\n      score -= 10\n    }\n  }\n\n  // Complex indicators (increase complexity)\n  const complexKeywords = [\n    'architecture',\n    'refactor',\n    'performance',\n    'memory leak',\n    'race condition',\n    'typescript',\n    'type inference',\n    'breaking change',\n  ]\n  for (const keyword of complexKeywords) {\n    if (text.includes(keyword)) {\n      score += 10\n    }\n  }\n\n  // Issue body length (longer = potentially more complex)\n  const bodyLength = issue.body.length\n  if (bodyLength > 2000) {\n    score += 15\n  } else if (bodyLength > 1000) {\n    score += 10\n  } else if (bodyLength < 200) {\n    score -= 10\n  }\n\n  // Code blocks indicate technical depth\n  const codeBlockCount = (issue.body.match(/```/g) || []).length / 2\n  if (codeBlockCount > 3) {\n    score += 15\n  } else if (codeBlockCount > 1) {\n    score += 10\n  }\n\n  // Multiple labels might indicate complexity\n  if (issue.labels.length > 4) {\n    score += 10\n  }\n\n  return Math.max(0, Math.min(100, score))\n}\n\n/**\n * Calculate engagement score (0-100)\n * Based on: reactions, comments, author reputation\n */\nexport function calculateEngagementScore(issue: Issue): number {\n  let score = 0\n\n  // Comment count (0-50 points)\n  if (issue.comment_count > 30) {\n    score += 50\n  } else if (issue.comment_count > 20) {\n    score += 40\n  } else if (issue.comment_count > 10) {\n    score += 30\n  } else if (issue.comment_count > 5) {\n    score += 20\n  } else if (issue.comment_count > 0) {\n    score += 10\n  }\n\n  // Recent activity (0-30 points)\n  const daysSinceUpdate = getAgeInDays(issue.updated_at)\n  if (daysSinceUpdate < 7) {\n    score += 30\n  } else if (daysSinceUpdate < 14) {\n    score += 20\n  } else if (daysSinceUpdate < 30) {\n    score += 10\n  }\n\n  // Author activity (0-20 points)\n  // If author is active in comments, it shows engagement\n  // This is a proxy - we'd need comment data to be precise\n  if (issue.comment_count > 0) {\n    score += 10\n  }\n\n  return Math.min(100, score)\n}\n\n/**\n * Calculate all scores for an issue\n */\nexport function calculateScores(issue: Issue): Scores {\n  return {\n    urgency: calculateUrgencyScore(issue),\n    complexity: calculateComplexityScore(issue),\n    engagement: calculateEngagementScore(issue),\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/categorize/types.ts",
    "content": "/**\n * Categorization types for issue analysis\n */\n\n/**\n * Categorization result for an issue\n */\nexport interface Categorization {\n  primary: string\n  secondary?: string\n  type: 'bug' | 'feature' | 'question' | 'docs'\n  confidence: number\n  method: 'label' | 'keyword' | 'pattern' | 'manual'\n}\n\n/**\n * Scoring metrics for an issue\n */\nexport interface Scores {\n  urgency: number // 0-100\n  complexity: number // 0-100\n  engagement: number // 0-100\n}\n\n/**\n * Flags for special issue conditions\n */\nexport interface Flags {\n  isUrgent: boolean\n  isEasyFix: boolean\n  needsTriage: boolean\n  isStale: boolean\n  hasBreakingChange: boolean\n  needsRepro: boolean\n}\n\n/**\n * Issue with categorization, scores, and flags\n */\nexport interface CategorizedIssue {\n  number: number\n  title: string\n  state: 'open' | 'closed'\n  type: 'issue' | 'pr'\n  created_at: Date\n  updated_at: Date\n  closed_at: Date | null\n  url: string\n  author: string\n  labels: string[]\n  comment_count: number\n  body: string\n  is_draft?: boolean\n  review_decision?: string | null\n  merged_at?: Date | null\n  categorization: Categorization\n  scores: Scores\n  flags: Flags\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/github/gh-client.ts",
    "content": "/**\n * GitHub CLI client for fetching issues and PRs\n */\n\nimport { execFile } from 'node:child_process'\nimport { promisify } from 'node:util'\nimport { promises as fs } from 'node:fs'\nimport { join, dirname } from 'node:path'\nimport type {\n  GhIssueResponse,\n  GhPullRequestResponse,\n  GhIssueDetailResponse,\n  Issue,\n  DetailedIssue,\n} from './types.js'\nimport { GhCliError, GhApiError, GhParseError } from '../utils/errors.js'\nimport { transformIssue, transformDetailedIssue } from './transformers.js'\n\nconst execFileAsync = promisify(execFile)\n\n// Configuration\nconst MAX_BUFFER = 10 * 1024 * 1024 // 10MB\nconst TIMEOUT = 30000 // 30 seconds\nconst REPO = 'reduxjs/redux-toolkit'\nconst CACHE_FILE = 'cache/issues-data.json'\n\n/**\n * Execute a gh CLI command and return stdout/stderr\n */\nexport async function executeGhCommand(\n  args: string[],\n): Promise<{ stdout: string; stderr: string }> {\n  try {\n    const result = await execFileAsync('gh', args, {\n      maxBuffer: MAX_BUFFER,\n      timeout: TIMEOUT,\n      encoding: 'utf8',\n    })\n    return result\n  } catch (error: any) {\n    // Handle specific error cases\n    if (error.code === 'ENOENT') {\n      throw new GhCliError(\n        'GitHub CLI (gh) not found. Please install it from https://cli.github.com/',\n        error,\n      )\n    }\n\n    if (error.killed && error.signal === 'SIGTERM') {\n      throw new GhApiError(\n        `Command timed out after ${TIMEOUT / 1000} seconds`,\n        undefined,\n        error,\n      )\n    }\n\n    // Check for authentication errors in stderr\n    if (error.stderr && error.stderr.includes('authentication')) {\n      throw new GhCliError(\n        'Not authenticated with GitHub CLI. Run: gh auth login',\n        error,\n      )\n    }\n\n    // Check for API rate limit errors\n    if (error.stderr && error.stderr.includes('rate limit')) {\n      throw new GhApiError('GitHub API rate limit exceeded', 429, error)\n    }\n\n    // Generic API error\n    throw new GhApiError(\n      `GitHub CLI command failed: ${error.message}`,\n      error.code,\n      error,\n    )\n  }\n}\n\n/**\n * Check if gh CLI is installed and authenticated\n */\nexport async function checkGhCli(): Promise<void> {\n  try {\n    // Check if gh is installed and authenticated\n    await executeGhCommand(['auth', 'status'])\n  } catch (error) {\n    if (error instanceof GhCliError || error instanceof GhApiError) {\n      throw error\n    }\n    throw new GhCliError('Failed to verify GitHub CLI status', error)\n  }\n}\n\n/**\n * GitHub client for fetching issues and PRs\n */\nexport class GitHubClient {\n  /**\n   * Fetch all open issues from the repository\n   */\n  async fetchOpenIssues(): Promise<Issue[]> {\n    console.log('Fetching open issues...')\n\n    const fields = [\n      'number',\n      'title',\n      'state',\n      'createdAt',\n      'updatedAt',\n      'closedAt',\n      'url',\n      'author',\n      'labels',\n      'assignees',\n      'comments',\n      'body',\n    ]\n\n    try {\n      const { stdout } = await executeGhCommand([\n        'issue',\n        'list',\n        '--repo',\n        REPO,\n        '--state',\n        'open',\n        '--limit',\n        '1000',\n        '--json',\n        fields.join(','),\n      ])\n\n      const rawIssues: GhIssueResponse[] = JSON.parse(stdout)\n      return rawIssues.map((issue) => transformIssue(issue, 'issue'))\n    } catch (error) {\n      if (error instanceof GhCliError || error instanceof GhApiError) {\n        throw error\n      }\n      if (error instanceof SyntaxError) {\n        throw new GhParseError(\n          'Failed to parse issues JSON response',\n          undefined,\n          error,\n        )\n      }\n      throw new GhApiError('Failed to fetch open issues', undefined, error)\n    }\n  }\n\n  /**\n   * Fetch all open PRs from the repository\n   */\n  async fetchOpenPRs(): Promise<Issue[]> {\n    console.log('Fetching open PRs...')\n\n    const fields = [\n      'number',\n      'title',\n      'state',\n      'createdAt',\n      'updatedAt',\n      'closedAt',\n      'mergedAt',\n      'url',\n      'author',\n      'labels',\n      'assignees',\n      'comments',\n      'body',\n      'isDraft',\n      'reviewDecision',\n    ]\n\n    try {\n      const { stdout } = await executeGhCommand([\n        'pr',\n        'list',\n        '--repo',\n        REPO,\n        '--state',\n        'open',\n        '--limit',\n        '1000',\n        '--json',\n        fields.join(','),\n      ])\n\n      const rawPRs: GhPullRequestResponse[] = JSON.parse(stdout)\n      return rawPRs.map((pr) => transformIssue(pr, 'pr'))\n    } catch (error) {\n      if (error instanceof GhCliError || error instanceof GhApiError) {\n        throw error\n      }\n      if (error instanceof SyntaxError) {\n        throw new GhParseError(\n          'Failed to parse PRs JSON response',\n          undefined,\n          error,\n        )\n      }\n      throw new GhApiError('Failed to fetch open PRs', undefined, error)\n    }\n  }\n\n  /**\n   * Fetch detailed information for a specific issue including comments\n   */\n  async fetchIssueDetail(number: number): Promise<DetailedIssue> {\n    console.log(`Fetching details for issue #${number}...`)\n\n    const fields = [\n      'number',\n      'title',\n      'state',\n      'createdAt',\n      'updatedAt',\n      'closedAt',\n      'url',\n      'author',\n      'labels',\n      'assignees',\n      'body',\n      'comments',\n    ]\n\n    try {\n      const { stdout } = await executeGhCommand([\n        'issue',\n        'view',\n        number.toString(),\n        '--repo',\n        REPO,\n        '--json',\n        fields.join(','),\n      ])\n\n      const rawIssue: GhIssueDetailResponse = JSON.parse(stdout)\n      return transformDetailedIssue(rawIssue)\n    } catch (error) {\n      if (error instanceof GhCliError || error instanceof GhApiError) {\n        throw error\n      }\n      if (error instanceof SyntaxError) {\n        throw new GhParseError(\n          `Failed to parse issue #${number} JSON response`,\n          undefined,\n          error,\n        )\n      }\n      throw new GhApiError(`Failed to fetch issue #${number}`, undefined, error)\n    }\n  }\n\n  /**\n   * Save issues and PRs to cache file\n   */\n  async saveToCache(issues: Issue[], prs: Issue[]): Promise<void> {\n    try {\n      console.log('💾 Saving data to cache...')\n\n      // Create cache directory if it doesn't exist\n      const cacheDir = dirname(CACHE_FILE)\n      await fs.mkdir(cacheDir, { recursive: true })\n\n      // Write cache file with pretty-printed JSON\n      const cacheData = { issues, prs }\n      await fs.writeFile(CACHE_FILE, JSON.stringify(cacheData, null, 2), 'utf8')\n\n      console.log(\n        `✓ Saved ${issues.length} issues and ${prs.length} PRs to cache`,\n      )\n    } catch (error) {\n      // Log warning but don't fail - caching is optional\n      console.warn(\n        '⚠️ Failed to save cache:',\n        error instanceof Error ? error.message : error,\n      )\n    }\n  }\n\n  /**\n   * Load issues and PRs from cache file\n   */\n  async loadFromCache(): Promise<{ issues: Issue[]; prs: Issue[] } | null> {\n    try {\n      const data = await fs.readFile(CACHE_FILE, 'utf8')\n      const parsed = JSON.parse(data)\n\n      // Validate cache structure\n      if (\n        !parsed.issues ||\n        !parsed.prs ||\n        !Array.isArray(parsed.issues) ||\n        !Array.isArray(parsed.prs)\n      ) {\n        console.warn('⚠️ Cache file has invalid structure, fetching fresh data')\n        return null\n      }\n\n      // Reconstruct Date objects from ISO strings\n      const reconstructDates = (item: any): Issue => ({\n        ...item,\n        created_at: new Date(item.created_at),\n        updated_at: new Date(item.updated_at),\n        closed_at: item.closed_at ? new Date(item.closed_at) : null,\n        merged_at: item.merged_at ? new Date(item.merged_at) : undefined,\n      })\n\n      return {\n        issues: parsed.issues.map(reconstructDates),\n        prs: parsed.prs.map(reconstructDates),\n      }\n    } catch (error) {\n      if ((error as NodeJS.ErrnoException).code === 'ENOENT') {\n        console.log('⚠️ Cache file not found, fetching fresh data')\n      } else if (error instanceof SyntaxError) {\n        console.warn('⚠️ Cache file corrupted, fetching fresh data')\n      } else {\n        console.warn(\n          '⚠️ Failed to load cache:',\n          error instanceof Error ? error.message : error,\n        )\n      }\n      return null\n    }\n  }\n\n  /**\n   * Fetch all open issues and PRs\n   */\n  async fetchAll(options?: { useCache?: boolean }): Promise<Issue[]> {\n    // Try to load from cache if requested\n    if (options?.useCache) {\n      console.log('📦 Attempting to use cached data...')\n      const cached = await this.loadFromCache()\n\n      if (cached) {\n        console.log('📦 Using cached data')\n        return [...cached.issues, ...cached.prs]\n      }\n    }\n\n    // Fetch fresh data\n    console.log('🔄 Fetching fresh data...')\n    console.log('Fetching all open issues and PRs...')\n\n    const [issues, prs] = await Promise.all([\n      this.fetchOpenIssues(),\n      this.fetchOpenPRs(),\n    ])\n\n    // Save to cache\n    await this.saveToCache(issues, prs)\n\n    return [...issues, ...prs]\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/github/transformers.ts",
    "content": "/**\n * Data transformation functions for GitHub API responses\n */\n\nimport type {\n  GhIssueResponse,\n  GhPullRequestResponse,\n  GhIssueDetailResponse,\n  GhComment,\n  SimplifiedComment,\n  Issue,\n  DetailedIssue,\n} from './types.js'\n\n/**\n * Simplify a comment object for caching by removing unnecessary fields\n */\nfunction simplifyComment(comment: GhComment): SimplifiedComment {\n  return {\n    author: comment.author.login,\n    authorAssociation: comment.authorAssociation,\n    body: comment.body,\n    createdAt: comment.createdAt,\n  }\n}\n\n/**\n * Transform a raw GitHub issue or PR response to our internal format\n */\nexport function transformIssue(\n  raw: GhIssueResponse | GhPullRequestResponse,\n  type: 'issue' | 'pr',\n): Issue {\n  // Handle comments - can be either a count or full array\n  const commentCount =\n    typeof raw.comments === 'number' ? raw.comments : raw.comments.length\n\n  const simplifiedComments = Array.isArray(raw.comments)\n    ? raw.comments.map(simplifyComment)\n    : undefined\n\n  const base: Issue = {\n    number: raw.number,\n    title: raw.title,\n    state: raw.state === 'OPEN' ? 'open' : 'closed',\n    type,\n    created_at: new Date(raw.createdAt),\n    updated_at: new Date(raw.updatedAt),\n    closed_at: raw.closedAt ? new Date(raw.closedAt) : null,\n    url: raw.url,\n    author: raw.author.login,\n    labels: raw.labels.map((label) => label.name),\n    comment_count: commentCount,\n    comments: simplifiedComments,\n    body: raw.body || '',\n  }\n\n  // Add PR-specific fields if this is a PR\n  if (type === 'pr' && 'isDraft' in raw) {\n    const pr = raw as GhPullRequestResponse\n    base.is_draft = pr.isDraft\n    base.review_decision = pr.reviewDecision\n    base.merged_at = pr.mergedAt ? new Date(pr.mergedAt) : null\n  }\n\n  return base\n}\n\n/**\n * Transform a detailed GitHub issue response (with comments) to our internal format\n */\nexport function transformDetailedIssue(\n  raw: GhIssueDetailResponse,\n): DetailedIssue {\n  // Transform the base issue data\n  const baseIssue: Issue = {\n    number: raw.number,\n    title: raw.title,\n    state: raw.state === 'OPEN' ? 'open' : 'closed',\n    type: 'issue',\n    created_at: new Date(raw.createdAt),\n    updated_at: new Date(raw.updatedAt),\n    closed_at: raw.closedAt ? new Date(raw.closedAt) : null,\n    url: raw.url,\n    author: raw.author.login,\n    labels: raw.labels.map((label) => label.name),\n    comment_count: raw.comments.length,\n    body: raw.body || '',\n  }\n\n  // Transform comments to simplified format\n  const comments = raw.comments.map(simplifyComment)\n\n  return {\n    ...baseIssue,\n    comments,\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/github/types.ts",
    "content": "/**\n * GitHub API response types and internal data models\n */\n\n/**\n * Comment object from GitHub API\n */\nexport interface GhComment {\n  id: string\n  author: {\n    login: string\n  }\n  authorAssociation: string\n  body: string\n  createdAt: string\n  includesCreatedEdit: boolean\n  isMinimized: boolean\n  minimizedReason: string\n  reactionGroups: Array<{\n    content: string\n    users: {\n      totalCount: number\n    }\n  }>\n  url: string\n  viewerDidAuthor: boolean\n}\n\n/**\n * Simplified comment for caching\n */\nexport interface SimplifiedComment {\n  author: string\n  authorAssociation: string\n  body: string\n  createdAt: string\n}\n\n/**\n * Raw response from `gh issue list --json` command\n */\nexport interface GhIssueResponse {\n  number: number\n  title: string\n  state: string\n  createdAt: string\n  updatedAt: string\n  closedAt: string | null\n  url: string\n  author: {\n    login: string\n  }\n  labels: Array<{\n    name: string\n    color: string\n  }>\n  assignees: Array<{\n    login: string\n  }>\n  comments: number | GhComment[] // Can be count or full array\n  body: string\n}\n\n/**\n * Raw response from `gh pr list --json` command\n */\nexport interface GhPullRequestResponse {\n  number: number\n  title: string\n  state: string\n  createdAt: string\n  updatedAt: string\n  closedAt: string | null\n  mergedAt: string | null\n  url: string\n  author: {\n    login: string\n  }\n  labels: Array<{\n    name: string\n    color: string\n  }>\n  assignees: Array<{\n    login: string\n  }>\n  comments: number\n  body: string\n  isDraft: boolean\n  reviewDecision: string | null\n}\n\n/**\n * Detailed issue response with comments from `gh issue view --json`\n */\nexport interface GhIssueDetailResponse {\n  number: number\n  title: string\n  state: string\n  createdAt: string\n  updatedAt: string\n  closedAt: string | null\n  url: string\n  author: {\n    login: string\n  }\n  labels: Array<{\n    name: string\n    color: string\n  }>\n  assignees: Array<{\n    login: string\n  }>\n  body: string\n  comments: GhComment[]\n}\n\n/**\n * Normalized internal issue format\n */\nexport interface Issue {\n  number: number\n  title: string\n  state: 'open' | 'closed'\n  type: 'issue' | 'pr'\n  created_at: Date\n  updated_at: Date\n  closed_at: Date | null\n  url: string\n  author: string\n  labels: string[]\n  comment_count: number\n  comments?: SimplifiedComment[] // Optional simplified comments for caching\n  body: string\n  // PR-specific fields\n  is_draft?: boolean\n  review_decision?: string | null\n  merged_at?: Date | null\n}\n\n/**\n * Detailed issue with comments loaded\n */\nexport interface DetailedIssue extends Issue {\n  comments: SimplifiedComment[]\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/index.ts",
    "content": "/**\n * GitHub Issues Triage Tool\n *\n * Main entry point for the issue triage automation tool.\n */\n\nimport { writeFile } from 'fs/promises'\nimport path from 'path'\nimport { GitHubClient, checkGhCli } from './github/gh-client.js'\nimport { GhCliError, GhApiError, GhParseError } from './utils/errors.js'\nimport { categorizeIssues, CATEGORIES } from './categorize/index.js'\nimport { findAllDuplicates, createWorkClusters } from './similarity/index.js'\nimport { generateReport, type ReportData } from './reports/index.js'\n\nasync function main() {\n  console.log('GitHub Issues Triage Tool v1.0.0')\n  console.log('==================================\\n')\n\n  try {\n    // Parse CLI arguments\n    const useCache = process.argv.includes('--use-cache')\n\n    // Step 1: Verify gh CLI is available and authenticated\n    console.log('Checking GitHub CLI...')\n    await checkGhCli()\n    console.log('✓ GitHub CLI is installed and authenticated\\n')\n\n    // Step 2: Create GitHub client\n    const client = new GitHubClient()\n\n    // Step 3: Fetch all open issues and PRs\n    console.log('Fetching data from reduxjs/redux-toolkit...\\n')\n    const allItems = await client.fetchAll({ useCache })\n\n    // Step 4: Categorize all items\n    console.log('Categorizing issues...\\n')\n    const categorizedItems = categorizeIssues(allItems)\n\n    // Step 5: Display summary statistics\n    const issues = categorizedItems.filter((item) => item.type === 'issue')\n    const prs = categorizedItems.filter((item) => item.type === 'pr')\n\n    console.log('\\n📊 Summary Statistics')\n    console.log('====================')\n    console.log(`Total open issues: ${issues.length}`)\n    console.log(`Total open PRs: ${prs.length}`)\n    console.log(`Total items: ${allItems.length}\\n`)\n\n    // Step 6: Display categorization statistics\n    console.log('📂 Categorization Breakdown')\n    console.log('===========================')\n\n    const categoryStats = new Map<string, number>()\n    const typeStats = new Map<string, number>()\n    let urgentCount = 0\n    let easyFixCount = 0\n    let needsTriageCount = 0\n\n    for (const item of categorizedItems) {\n      // Count by primary category\n      const category = item.categorization.primary\n      categoryStats.set(category, (categoryStats.get(category) || 0) + 1)\n\n      // Count by type\n      const type = item.categorization.type\n      typeStats.set(type, (typeStats.get(type) || 0) + 1)\n\n      // Count flags\n      if (item.flags.isUrgent) urgentCount++\n      if (item.flags.isEasyFix) easyFixCount++\n      if (item.flags.needsTriage) needsTriageCount++\n    }\n\n    // Display category breakdown\n    console.log('\\nBy Category:')\n    for (const category of CATEGORIES) {\n      const count = categoryStats.get(category.name) || 0\n      const percentage = ((count / categorizedItems.length) * 100).toFixed(1)\n      console.log(`  ${category.displayName}: ${count} (${percentage}%)`)\n    }\n\n    // Display type breakdown\n    console.log('\\nBy Type:')\n    for (const [type, count] of typeStats.entries()) {\n      const percentage = ((count / categorizedItems.length) * 100).toFixed(1)\n      console.log(`  ${type}: ${count} (${percentage}%)`)\n    }\n\n    // Display flags\n    console.log('\\nFlags:')\n    console.log(`  🚨 Urgent: ${urgentCount}`)\n    console.log(`  ✅ Easy Fix: ${easyFixCount}`)\n    console.log(`  🏷️  Needs Triage: ${needsTriageCount}`)\n\n    // Step 7: Run similarity detection\n    console.log('\\n🔍 Running Similarity Detection')\n    console.log('================================')\n\n    const startTime = Date.now()\n    const duplicateGroups = findAllDuplicates(issues)\n    const workClusters = createWorkClusters(issues)\n    const endTime = Date.now()\n\n    console.log(`✓ Similarity detection completed in ${endTime - startTime}ms`)\n    console.log(`  Found ${duplicateGroups.length} potential duplicate groups`)\n    console.log(`  Created ${workClusters.length} work clusters`)\n\n    // Step 8: Display sample categorized issues\n    if (issues.length > 0) {\n      console.log('\\n📝 Sample Categorized Issues')\n      console.log('============================\\n')\n\n      const samplesToShow = Math.min(5, issues.length)\n      for (let i = 0; i < samplesToShow; i++) {\n        const issue = issues[i]\n        const cat = issue.categorization\n        const scores = issue.scores\n        const flags = issue.flags\n\n        console.log(`Issue #${issue.number}: ${issue.title}`)\n        console.log(\n          `  Category: ${cat.primary}${cat.secondary ? ` > ${cat.secondary}` : ''}`,\n        )\n        console.log(\n          `  Type: ${cat.type} | Confidence: ${(cat.confidence * 100).toFixed(0)}% | Method: ${cat.method}`,\n        )\n        console.log(\n          `  Scores: Urgency=${scores.urgency} Complexity=${scores.complexity} Engagement=${scores.engagement}`,\n        )\n\n        const activeFlags = []\n        if (flags.isUrgent) activeFlags.push('🚨 Urgent')\n        if (flags.isEasyFix) activeFlags.push('✅ Easy Fix')\n        if (flags.needsTriage) activeFlags.push('🏷️ Needs Triage')\n        if (flags.isStale) activeFlags.push('⏰ Stale')\n        if (flags.hasBreakingChange) activeFlags.push('💥 Breaking')\n        if (flags.needsRepro) activeFlags.push('🔍 Needs Repro')\n\n        if (activeFlags.length > 0) {\n          console.log(`  Flags: ${activeFlags.join(', ')}`)\n        }\n        console.log('')\n      }\n    }\n\n    // Step 9: Display sample similarity results\n    if (duplicateGroups.length > 0) {\n      console.log('\\n🔄 Sample Duplicate Groups')\n      console.log('==========================\\n')\n\n      const samplesToShow = Math.min(3, duplicateGroups.length)\n      for (let i = 0; i < samplesToShow; i++) {\n        const group = duplicateGroups[i]\n        console.log(\n          `Primary Issue #${group.primary.number}: ${group.primary.title}`,\n        )\n        console.log(`  Potential duplicates: ${group.duplicates.length}`)\n        for (const dup of group.duplicates.slice(0, 2)) {\n          console.log(`    - #${dup.issue.number}: ${dup.issue.title}`)\n          console.log(`      Confidence: ${(dup.confidence * 100).toFixed(0)}%`)\n        }\n        console.log('')\n      }\n    }\n\n    if (workClusters.length > 0) {\n      console.log('\\n📦 Sample Work Clusters')\n      console.log('=======================\\n')\n\n      const samplesToShow = Math.min(3, workClusters.length)\n      for (let i = 0; i < samplesToShow; i++) {\n        const cluster = workClusters[i]\n        console.log(\n          `Cluster ${cluster.id}: ${cluster.category}${cluster.subcategory ? `/${cluster.subcategory}` : ''}`,\n        )\n        console.log(`  Issues: ${cluster.issues.length}`)\n        console.log(`  Priority: ${cluster.priority.toFixed(1)}`)\n        console.log(\n          `  Avg Complexity: ${cluster.metrics.avgComplexity.toFixed(0)}`,\n        )\n        console.log(\n          `  Estimated Effort: ${cluster.metrics.estimatedEffort} days`,\n        )\n        console.log(`  Reasoning: ${cluster.reasoning}`)\n        console.log('')\n      }\n    }\n\n    // Step 10: Export categorization results to JSON\n    console.log('\\n💾 Exporting categorization results...')\n    const outputPath = 'cache/categorization-results.json'\n\n    const exportData = {\n      metadata: {\n        generatedAt: new Date().toISOString(),\n        totalItems: categorizedItems.length,\n        totalIssues: issues.length,\n        totalPRs: prs.length,\n      },\n      statistics: {\n        byCategory: Object.fromEntries(categoryStats),\n        byType: Object.fromEntries(typeStats),\n        flags: {\n          urgent: urgentCount,\n          easyFix: easyFixCount,\n          needsTriage: needsTriageCount,\n        },\n      },\n      similarity: {\n        duplicateGroups: duplicateGroups.map((group) => ({\n          primary: {\n            number: group.primary.number,\n            title: group.primary.title,\n          },\n          duplicates: group.duplicates.map((dup) => ({\n            number: dup.issue.number,\n            title: dup.issue.title,\n            confidence: dup.confidence,\n            signals: dup.signals,\n          })),\n        })),\n        workClusters: workClusters.map((cluster) => ({\n          id: cluster.id,\n          category: cluster.category,\n          subcategory: cluster.subcategory,\n          issueNumbers: cluster.issues.map((i) => i.number),\n          metrics: cluster.metrics,\n          reasoning: cluster.reasoning,\n          priority: cluster.priority,\n        })),\n      },\n      items: categorizedItems.map((item) => ({\n        number: item.number,\n        title: item.title,\n        body: item.body,\n        state: item.state,\n        type: item.type,\n        url: item.url,\n        author: item.author,\n        labels: item.labels,\n        created_at: item.created_at.toISOString(),\n        updated_at: item.updated_at.toISOString(),\n        comment_count: item.comment_count,\n        categorization: item.categorization,\n        scores: item.scores,\n        flags: item.flags,\n      })),\n    }\n\n    await writeFile(outputPath, JSON.stringify(exportData, null, 2), 'utf-8')\n    console.log(`✓ Results exported to ${outputPath}`)\n\n    // Step 11: Generate Markdown reports\n    console.log('\\n📝 Generating reports...')\n\n    const reportData: ReportData = {\n      issues: categorizedItems,\n      duplicates: duplicateGroups,\n      clusters: workClusters,\n      metadata: {\n        generatedAt: new Date().toISOString(),\n        totalIssues: issues.length,\n        totalPRs: prs.length,\n        categorizedIssues: categorizedItems.filter(\n          (i) => i.categorization.primary !== 'uncategorized',\n        ).length,\n        uncategorizedIssues: categorizedItems.filter(\n          (i) => i.categorization.primary === 'uncategorized',\n        ).length,\n      },\n    }\n\n    // Generate full report\n    const fullReport = generateReport(reportData, { variant: 'full' })\n    const fullReportPath = path.join('cache', 'triage-report-full.md')\n    await writeFile(fullReportPath, fullReport, 'utf-8')\n    console.log(`✓ Full report: ${fullReportPath}`)\n\n    // Generate priority report\n    const priorityReport = generateReport(reportData, {\n      variant: 'priority',\n      maxIssuesPerSection: 30,\n    })\n    const priorityReportPath = path.join('cache', 'triage-report-priority.md')\n    await writeFile(priorityReportPath, priorityReport, 'utf-8')\n    console.log(`✓ Priority report: ${priorityReportPath}`)\n\n    console.log('\\n✓ Triage complete!')\n    console.log('\\nGenerated files:')\n    console.log(`  - ${outputPath} (JSON data)`)\n    console.log(`  - ${fullReportPath} (Full markdown report)`)\n    console.log(`  - ${priorityReportPath} (Priority issues report)`)\n    console.log('\\nNext steps:')\n    console.log('- Review the generated reports')\n    console.log('- Use reports to prioritize maintenance work')\n    console.log('- Close duplicate issues')\n    console.log('- Address urgent bugs and easy fixes')\n  } catch (error) {\n    // Handle specific error types with helpful messages\n    if (error instanceof GhCliError) {\n      console.error('\\n❌ GitHub CLI Error:')\n      console.error(error.message)\n      console.error('\\nPlease ensure:')\n      console.error('1. GitHub CLI is installed: https://cli.github.com/')\n      console.error('2. You are authenticated: gh auth login')\n      process.exit(1)\n    } else if (error instanceof GhApiError) {\n      console.error('\\n❌ GitHub API Error:')\n      console.error(error.message)\n      if (error.statusCode === 429) {\n        console.error('\\nYou have hit the GitHub API rate limit.')\n        console.error('Please wait a while before trying again.')\n      }\n      process.exit(1)\n    } else if (error instanceof GhParseError) {\n      console.error('\\n❌ Parse Error:')\n      console.error(error.message)\n      console.error('\\nThe GitHub CLI returned unexpected data.')\n      process.exit(1)\n    } else {\n      // Unknown error\n      console.error('\\n❌ Unexpected Error:')\n      console.error(error)\n      process.exit(1)\n    }\n  }\n}\n\n// Run the main function\nmain().catch((error) => {\n  console.error('Fatal error:', error)\n  process.exit(1)\n})\n\nexport { main }\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/reports/generator.ts",
    "content": "import type { ReportData, ReportOptions } from './types.js'\nimport { generateSummary } from './summary.js'\nimport {\n  generatePrioritySection,\n  generateDuplicatesSection,\n  generateClustersSection,\n  generateFlaggedSection,\n  generateCategorySection,\n  generateTopBugsSection,\n  generateQuickWinsSection,\n  generateNeedsAttentionSection,\n  generateEasyFixesSection,\n} from './sections.js'\nimport { groupByCategory } from './utils.js'\n\nexport function generateReport(\n  data: ReportData,\n  options: ReportOptions = { variant: 'full' },\n): string {\n  const sections: string[] = []\n\n  // Always include summary\n  sections.push(generateSummary(data))\n\n  switch (options.variant) {\n    case 'full':\n      return generateFullReport(data, sections)\n\n    case 'priority':\n      return generatePriorityReport(data, sections, options)\n\n    case 'category':\n      return generateCategoryReport(data, sections, options)\n\n    default:\n      return generateFullReport(data, sections)\n  }\n}\n\nfunction generateFullReport(data: ReportData, sections: string[]): string {\n  // Priority issues\n  sections.push(generatePrioritySection(data.issues, 20))\n\n  // Top bugs (NEW)\n  sections.push(generateTopBugsSection(data.issues, 20))\n\n  // Quick wins (NEW)\n  sections.push(generateQuickWinsSection(data.issues, 15))\n\n  // Urgent bugs\n  sections.push(\n    generateFlaggedSection(\n      data.issues,\n      'isUrgent',\n      '🚨 Urgent Bugs',\n      'Critical bugs that need immediate attention.',\n    ),\n  )\n\n  // Easy fixes (IMPROVED)\n  sections.push(generateEasyFixesSection(data.issues))\n\n  // Needs attention (NEW)\n  sections.push(generateNeedsAttentionSection(data.issues, 10))\n\n  // Duplicates\n  sections.push(generateDuplicatesSection(data.duplicates))\n\n  // Work clusters (with improved reasoning)\n  sections.push(generateClustersSection(data.clusters))\n\n  // Category breakdown\n  const byCategory = groupByCategory(data.issues)\n  sections.push('## 📂 All Categories')\n  sections.push('')\n\n  for (const [category, _issues] of Object.entries(byCategory).sort(\n    (a, b) => b[1].length - a[1].length,\n  )) {\n    sections.push(generateCategorySection(data.issues, category))\n  }\n\n  return sections.join('\\n')\n}\n\nfunction generatePriorityReport(\n  data: ReportData,\n  sections: string[],\n  options: ReportOptions,\n): string {\n  const maxItems = options.maxIssuesPerSection || 50\n\n  sections.push(generatePrioritySection(data.issues, maxItems))\n  sections.push(generateTopBugsSection(data.issues, 15))\n  sections.push(generateQuickWinsSection(data.issues, 10))\n  sections.push(\n    generateFlaggedSection(\n      data.issues,\n      'isUrgent',\n      '🚨 Urgent Bugs',\n      'Critical bugs.',\n    ),\n  )\n  sections.push(generateClustersSection(data.clusters.slice(0, 5)))\n\n  return sections.join('\\n')\n}\n\nfunction generateCategoryReport(\n  data: ReportData,\n  sections: string[],\n  options: ReportOptions,\n): string {\n  if (!options.category) {\n    throw new Error('Category must be specified for category report variant')\n  }\n\n  sections.push(generateCategorySection(data.issues, options.category))\n\n  // Include relevant clusters\n  const relevantClusters = data.clusters.filter(\n    (c) => c.category === options.category,\n  )\n  if (relevantClusters.length > 0) {\n    sections.push(generateClustersSection(relevantClusters))\n  }\n\n  return sections.join('\\n')\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/reports/index.ts",
    "content": "export * from './types.js'\nexport * from './generator.js'\nexport * from './summary.js'\nexport * from './sections.js'\nexport * from './utils.js'\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/reports/sections.ts",
    "content": "import type { CategorizedIssue } from '../categorize/types.js'\nimport type { DuplicateGroup, WorkCluster } from '../similarity/types.js'\nimport {\n  formatIssueLink,\n  formatRelativeDate,\n  formatConfidence,\n  formatFlags,\n  sortByPriority,\n  calculatePriority,\n} from './utils.js'\n\n/**\n * Generate priority issues section\n */\nexport function generatePrioritySection(\n  issues: CategorizedIssue[],\n  maxItems: number = 20,\n): string {\n  const sections: string[] = []\n\n  sections.push('## 🔥 Priority Issues')\n  sections.push('')\n  sections.push(\n    'Top issues ranked by urgency × engagement with time decay (recent issues prioritized).',\n  )\n  sections.push('')\n\n  const priorityIssues = sortByPriority(issues).slice(0, maxItems)\n\n  for (const issue of priorityIssues) {\n    const priority = calculatePriority(issue)\n    const flags = formatFlags(issue)\n\n    sections.push(`### ${formatIssueLink(issue)}`)\n    sections.push('')\n    sections.push(\n      `**Priority Score**: ${priority.toFixed(1)} (Urgency: ${issue.scores.urgency}, Engagement: ${issue.scores.engagement})`,\n    )\n    sections.push(\n      `**Category**: ${issue.categorization.primary}${issue.categorization.secondary ? ` / ${issue.categorization.secondary}` : ''}`,\n    )\n    sections.push(`**Age**: ${formatRelativeDate(issue.created_at)}`)\n    if (flags) sections.push(`**Flags**: ${flags}`)\n    sections.push('')\n    sections.push('---')\n    sections.push('')\n  }\n\n  return sections.join('\\n')\n}\n\n/**\n * Generate duplicates section\n */\nexport function generateDuplicatesSection(\n  duplicates: DuplicateGroup[],\n): string {\n  if (duplicates.length === 0) {\n    return '## 🔍 Potential Duplicates\\n\\nNo potential duplicates detected.\\n\\n'\n  }\n\n  const sections: string[] = []\n\n  sections.push('## 🔍 Potential Duplicates')\n  sections.push('')\n  sections.push('Issues that may be duplicates or closely related.')\n  sections.push('')\n\n  for (const group of duplicates) {\n    sections.push(`### Primary: ${formatIssueLink(group.primary)}`)\n    sections.push('')\n    sections.push('**Potential Duplicates:**')\n    sections.push('')\n\n    for (const dup of group.duplicates) {\n      const confidence = formatConfidence(\n        dup.confidence >= 0.75\n          ? 'high'\n          : dup.confidence >= 0.6\n            ? 'medium'\n            : 'low',\n      )\n      sections.push(\n        `- ${confidence} ${formatIssueLink(dup.issue)} (${Math.round(dup.confidence * 100)}% similar)`,\n      )\n      sections.push(\n        `  - Title: ${Math.round(dup.signals.titleSimilarity * 100)}% | Keywords: ${Math.round(dup.signals.keywordOverlap * 100)}% | Category: ${Math.round(dup.signals.categoryMatch * 100)}%`,\n      )\n    }\n\n    sections.push('')\n    sections.push('---')\n    sections.push('')\n  }\n\n  return sections.join('\\n')\n}\n\n/**\n * Generate work clusters section\n */\nexport function generateClustersSection(clusters: WorkCluster[]): string {\n  if (clusters.length === 0) {\n    return '## 🎯 Work Clusters\\n\\nNo work clusters identified.\\n\\n'\n  }\n\n  const sections: string[] = []\n\n  sections.push('## 🎯 Work Clusters')\n  sections.push('')\n  sections.push('Groups of related issues that could be addressed together.')\n  sections.push('')\n\n  for (const cluster of clusters) {\n    sections.push(\n      `### ${cluster.id}: ${cluster.category}${cluster.subcategory ? ` / ${cluster.subcategory}` : ''}`,\n    )\n    sections.push('')\n    sections.push(`**Priority Score**: ${cluster.priority.toFixed(1)}`)\n    sections.push(`**Issues**: ${cluster.issues.length}`)\n    sections.push(\n      `**Estimated Effort**: ${cluster.metrics.estimatedEffort} days`,\n    )\n    sections.push('')\n    sections.push(`**Metrics:**`)\n    sections.push(\n      `- Avg Complexity: ${cluster.metrics.avgComplexity.toFixed(1)}`,\n    )\n    sections.push(`- Avg Urgency: ${cluster.metrics.avgUrgency.toFixed(1)}`)\n    sections.push(`- Total Engagement: ${cluster.metrics.totalEngagement}`)\n    sections.push('')\n    sections.push(`**Reasoning**: ${cluster.reasoning}`)\n    sections.push('')\n    sections.push('**Issues in Cluster:**')\n    sections.push('')\n\n    for (const issue of cluster.issues) {\n      sections.push(`- ${formatIssueLink(issue)}`)\n    }\n\n    sections.push('')\n    sections.push('---')\n    sections.push('')\n  }\n\n  return sections.join('\\n')\n}\n\n/**\n * Generate flagged issues section grouped by category/subcategory\n */\nexport function generateFlaggedSection(\n  issues: CategorizedIssue[],\n  flagName: keyof CategorizedIssue['flags'],\n  title: string,\n  description: string,\n): string {\n  const flaggedIssues = issues.filter((issue) => issue.flags[flagName])\n\n  if (flaggedIssues.length === 0) {\n    return `## ${title}\\n\\n${description}\\n\\nNo issues found.\\n\\n`\n  }\n\n  const sections: string[] = []\n\n  sections.push(`## ${title}`)\n  sections.push('')\n  sections.push(description)\n  sections.push('')\n  sections.push(`Found ${flaggedIssues.length} issue(s).`)\n  sections.push('')\n\n  // Group by category and subcategory\n  const grouped: Record<string, Record<string, CategorizedIssue[]>> = {}\n\n  for (const issue of flaggedIssues) {\n    const category = issue.categorization.primary\n    const subcategory = issue.categorization.secondary || 'other'\n\n    if (!grouped[category]) grouped[category] = {}\n    if (!grouped[category][subcategory]) grouped[category][subcategory] = []\n    grouped[category][subcategory].push(issue)\n  }\n\n  // Sort categories by issue count\n  const sortedCategories = Object.entries(grouped).sort((a, b) => {\n    const countA = Object.values(a[1]).reduce(\n      (sum, items) => sum + items.length,\n      0,\n    )\n    const countB = Object.values(b[1]).reduce(\n      (sum, items) => sum + items.length,\n      0,\n    )\n    return countB - countA\n  })\n\n  for (const [category, subcategories] of sortedCategories) {\n    sections.push(`### ${category}`)\n    sections.push('')\n\n    // Sort subcategories by issue count\n    const sortedSubcategories = Object.entries(subcategories).sort(\n      (a, b) => b[1].length - a[1].length,\n    )\n\n    for (const [subcategory, subIssues] of sortedSubcategories) {\n      sections.push(`#### ${subcategory}`)\n      sections.push('')\n\n      for (const issue of sortByPriority(subIssues)) {\n        const age = formatRelativeDate(issue.created_at)\n        sections.push(`- ${formatIssueLink(issue)} (${age})`)\n      }\n\n      sections.push('')\n    }\n  }\n\n  return sections.join('\\n')\n}\n\n/**\n * Generate category-specific section\n */\nexport function generateCategorySection(\n  issues: CategorizedIssue[],\n  category: string,\n): string {\n  const categoryIssues = issues.filter(\n    (issue) => issue.categorization.primary === category,\n  )\n\n  if (categoryIssues.length === 0) {\n    return `## ${category}\\n\\nNo issues in this category.\\n\\n`\n  }\n\n  const sections: string[] = []\n\n  sections.push(`## ${category}`)\n  sections.push('')\n  sections.push(`${categoryIssues.length} issue(s) in this category.`)\n  sections.push('')\n\n  // Group by subcategory\n  const bySubcategory: Record<string, CategorizedIssue[]> = {}\n  for (const issue of categoryIssues) {\n    const sub = issue.categorization.secondary || 'other'\n    if (!bySubcategory[sub]) bySubcategory[sub] = []\n    bySubcategory[sub].push(issue)\n  }\n\n  for (const [subcategory, subIssues] of Object.entries(bySubcategory).sort(\n    (a, b) => b[1].length - a[1].length,\n  )) {\n    sections.push(`### ${subcategory} (${subIssues.length})`)\n    sections.push('')\n\n    for (const issue of sortByPriority(subIssues)) {\n      const flags = formatFlags(issue)\n      sections.push(`- ${formatIssueLink(issue)} ${flags ? `- ${flags}` : ''}`)\n    }\n\n    sections.push('')\n  }\n\n  return sections.join('\\n')\n}\n\n/**\n * Generate top bugs section (bugs only, not all issues)\n */\nexport function generateTopBugsSection(\n  issues: CategorizedIssue[],\n  maxItems: number = 20,\n): string {\n  const bugs = issues.filter(\n    (issue) =>\n      issue.type === 'issue' &&\n      (issue.labels.some((l) => l.toLowerCase().includes('bug')) ||\n        issue.title.toLowerCase().includes('bug') ||\n        issue.flags.isUrgent),\n  )\n\n  if (bugs.length === 0) {\n    return '## 🐛 Top Bugs\\n\\nNo bugs found.\\n\\n'\n  }\n\n  const sections: string[] = []\n\n  sections.push('## 🐛 Top Bugs')\n  sections.push('')\n  sections.push(\n    `Showing top ${Math.min(maxItems, bugs.length)} bugs by priority.`,\n  )\n  sections.push('')\n\n  const topBugs = sortByPriority(bugs).slice(0, maxItems)\n\n  for (const bug of topBugs) {\n    const priority = calculatePriority(bug)\n    const flags = formatFlags(bug)\n\n    sections.push(\n      `- ${formatIssueLink(bug)} (Priority: ${priority.toFixed(1)})`,\n    )\n    sections.push(\n      `  - **Category**: ${bug.categorization.primary}${bug.categorization.secondary ? ` / ${bug.categorization.secondary}` : ''}`,\n    )\n    sections.push(`  - **Created**: ${formatRelativeDate(bug.created_at)}`)\n    if (flags) sections.push(`  - **Flags**: ${flags}`)\n  }\n\n  sections.push('')\n\n  return sections.join('\\n')\n}\n\n/**\n * Generate quick wins section (easy + recent + engaged)\n */\nexport function generateQuickWinsSection(\n  issues: CategorizedIssue[],\n  maxItems: number = 15,\n): string {\n  const now = Date.now()\n  const thirtyDaysAgo = now - 30 * 24 * 60 * 60 * 1000\n\n  const quickWins = issues.filter((issue) => {\n    const isEasy = issue.flags.isEasyFix\n    const isRecent = new Date(issue.created_at).getTime() > thirtyDaysAgo\n    const hasEngagement = issue.scores.engagement >= 30\n\n    return isEasy && isRecent && hasEngagement\n  })\n\n  if (quickWins.length === 0) {\n    return '## ⚡ Quick Wins\\n\\nNo quick wins identified (easy + recent + engaged).\\n\\n'\n  }\n\n  const sections: string[] = []\n\n  sections.push('## ⚡ Quick Wins')\n  sections.push('')\n  sections.push(\n    'Easy fixes that are recent and have community engagement - best candidates for quick progress.',\n  )\n  sections.push('')\n\n  const sorted = sortByPriority(quickWins).slice(0, maxItems)\n\n  for (const issue of sorted) {\n    const priority = calculatePriority(issue)\n    sections.push(\n      `- ${formatIssueLink(issue)} (Priority: ${priority.toFixed(1)})`,\n    )\n    sections.push(\n      `  - **Category**: ${issue.categorization.primary}${issue.categorization.secondary ? ` / ${issue.categorization.secondary}` : ''}`,\n    )\n    sections.push(\n      `  - **Engagement**: ${issue.scores.engagement} | **Complexity**: ${issue.scores.complexity}`,\n    )\n  }\n\n  sections.push('')\n\n  return sections.join('\\n')\n}\n\n/**\n * Generate needs attention section (high engagement, no recent activity)\n */\nexport function generateNeedsAttentionSection(\n  issues: CategorizedIssue[],\n  maxItems: number = 10,\n): string {\n  const now = Date.now()\n  const thirtyDaysAgo = now - 30 * 24 * 60 * 60 * 1000\n\n  const needsAttention = issues.filter((issue) => {\n    const highEngagement = issue.scores.engagement >= 50\n    const notRecent = new Date(issue.updated_at).getTime() < thirtyDaysAgo\n    const notStale = !issue.flags.isStale\n\n    return highEngagement && notRecent && notStale\n  })\n\n  if (needsAttention.length === 0) {\n    return '## 👀 Needs Attention\\n\\nNo issues need attention.\\n\\n'\n  }\n\n  const sections: string[] = []\n\n  sections.push('## 👀 Needs Attention')\n  sections.push('')\n  sections.push(\n    'High engagement issues with no recent activity - community is waiting for response.',\n  )\n  sections.push('')\n\n  const sorted = sortByPriority(needsAttention).slice(0, maxItems)\n\n  for (const issue of sorted) {\n    const daysSinceUpdate = Math.floor(\n      (now - new Date(issue.updated_at).getTime()) / (24 * 60 * 60 * 1000),\n    )\n    sections.push(\n      `- ${formatIssueLink(issue)} (${daysSinceUpdate} days since update)`,\n    )\n    sections.push(\n      `  - **Category**: ${issue.categorization.primary}${issue.categorization.secondary ? ` / ${issue.categorization.secondary}` : ''}`,\n    )\n    sections.push(`  - **Engagement**: ${issue.scores.engagement}`)\n  }\n\n  sections.push('')\n\n  return sections.join('\\n')\n}\n\n/**\n * Generate improved easy fixes section with category grouping\n */\nexport function generateEasyFixesSection(issues: CategorizedIssue[]): string {\n  const easyFixes = issues.filter((issue) => issue.flags.isEasyFix)\n\n  if (easyFixes.length === 0) {\n    return '## ✅ Easy Fixes\\n\\nNo easy fixes identified.\\n\\n'\n  }\n\n  const sections: string[] = []\n\n  sections.push('## ✅ Easy Fixes')\n  sections.push('')\n  sections.push('Issues that should be quick to resolve, grouped by category.')\n  sections.push('')\n\n  // Group by category\n  const byCategory: Record<string, CategorizedIssue[]> = {}\n  for (const issue of easyFixes) {\n    const category = issue.categorization.primary\n    if (!byCategory[category]) byCategory[category] = []\n    byCategory[category].push(issue)\n  }\n\n  // Sort categories by count\n  const sortedCategories = Object.entries(byCategory).sort(\n    (a, b) => b[1].length - a[1].length,\n  )\n\n  for (const [category, categoryIssues] of sortedCategories) {\n    sections.push(`### ${category} (${categoryIssues.length})`)\n    sections.push('')\n\n    // Group by subcategory\n    const bySubcategory: Record<string, CategorizedIssue[]> = {}\n    for (const issue of categoryIssues) {\n      const sub = issue.categorization.secondary || 'other'\n      if (!bySubcategory[sub]) bySubcategory[sub] = []\n      bySubcategory[sub].push(issue)\n    }\n\n    for (const [subcategory, subIssues] of Object.entries(bySubcategory).sort(\n      (a, b) => b[1].length - a[1].length,\n    )) {\n      if (subcategory !== 'other') {\n        sections.push(`**${subcategory}** (${subIssues.length}):`)\n        sections.push('')\n      }\n\n      for (const issue of sortByPriority(subIssues)) {\n        sections.push(`- ${formatIssueLink(issue)}`)\n      }\n\n      sections.push('')\n    }\n  }\n\n  return sections.join('\\n')\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/reports/summary.ts",
    "content": "import type { ReportData } from './types.js'\nimport type { CategorizedIssue } from '../categorize/types.js'\nimport { groupByCategory } from './utils.js'\n\nexport function generateSummary(data: ReportData): string {\n  const { issues, duplicates, clusters, metadata } = data\n\n  const sections: string[] = []\n\n  // Header\n  sections.push('# Redux Toolkit Issues Triage Report')\n  sections.push('')\n  sections.push(`Generated: ${new Date(metadata.generatedAt).toLocaleString()}`)\n  sections.push('')\n\n  // Overview stats\n  sections.push('## 📊 Overview')\n  sections.push('')\n  sections.push(\n    `- **Total Items**: ${metadata.totalIssues + metadata.totalPRs}`,\n  )\n  sections.push(`  - Issues: ${metadata.totalIssues}`)\n  sections.push(`  - Pull Requests: ${metadata.totalPRs}`)\n  sections.push(\n    `- **Categorized**: ${metadata.categorizedIssues} (${Math.round((metadata.categorizedIssues / (metadata.totalIssues + metadata.totalPRs)) * 100)}%)`,\n  )\n  sections.push(`- **Uncategorized**: ${metadata.uncategorizedIssues}`)\n  sections.push(`- **Potential Duplicates**: ${duplicates.length} groups`)\n  sections.push(`- **Work Clusters**: ${clusters.length} clusters`)\n  sections.push('')\n\n  // Category breakdown\n  const byCategory = groupByCategory(issues)\n  sections.push('## 📁 Category Breakdown')\n  sections.push('')\n\n  // Build category > subcategory breakdown\n  const categorySubcategoryStats: Array<{\n    category: string\n    subcategory: string\n    count: number\n  }> = []\n\n  for (const [category, items] of Object.entries(byCategory)) {\n    const bySubcategory: Record<string, number> = {}\n\n    for (const item of items) {\n      const sub = item.categorization.secondary || 'other'\n      bySubcategory[sub] = (bySubcategory[sub] || 0) + 1\n    }\n\n    for (const [subcategory, count] of Object.entries(bySubcategory)) {\n      categorySubcategoryStats.push({ category, subcategory, count })\n    }\n  }\n\n  // Sort by category count (desc), then subcategory count (desc)\n  const categoryCounts = Object.entries(byCategory)\n    .map(([cat, items]) => ({ cat, count: items.length }))\n    .reduce(\n      (acc, { cat, count }) => {\n        acc[cat] = count\n        return acc\n      },\n      {} as Record<string, number>,\n    )\n\n  categorySubcategoryStats.sort((a, b) => {\n    const catDiff = categoryCounts[b.category] - categoryCounts[a.category]\n    if (catDiff !== 0) return catDiff\n    return b.count - a.count\n  })\n\n  sections.push('| Category | Subcategory | Count |')\n  sections.push('|----------|-------------|-------|')\n\n  for (const stat of categorySubcategoryStats) {\n    sections.push(`| ${stat.category} | ${stat.subcategory} | ${stat.count} |`)\n  }\n\n  sections.push('')\n\n  // Flag statistics\n  const flagCounts = countFlags(issues)\n  if (Object.keys(flagCounts).length > 0) {\n    sections.push('## 🏷️ Flag Statistics')\n    sections.push('')\n\n    for (const [flag, count] of Object.entries(flagCounts).sort(\n      (a, b) => b[1] - a[1],\n    )) {\n      sections.push(`- **${flag}**: ${count}`)\n    }\n\n    sections.push('')\n  }\n\n  return sections.join('\\n')\n}\n\nfunction countFlags(issues: CategorizedIssue[]): Record<string, number> {\n  const counts: Record<string, number> = {}\n\n  for (const issue of issues) {\n    if (issue.flags.isUrgent) counts['Urgent'] = (counts['Urgent'] || 0) + 1\n    if (issue.flags.isEasyFix)\n      counts['Easy Fix'] = (counts['Easy Fix'] || 0) + 1\n    if (issue.flags.needsRepro)\n      counts['Needs Reproduction'] = (counts['Needs Reproduction'] || 0) + 1\n    if (issue.flags.isStale) counts['Stale'] = (counts['Stale'] || 0) + 1\n    if (issue.flags.hasBreakingChange)\n      counts['Breaking Change'] = (counts['Breaking Change'] || 0) + 1\n    if (issue.flags.needsTriage)\n      counts['Needs Triage'] = (counts['Needs Triage'] || 0) + 1\n  }\n\n  return counts\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/reports/types.ts",
    "content": "import type { CategorizedIssue } from '../categorize/types.js'\nimport type { DuplicateGroup, WorkCluster } from '../similarity/types.js'\n\nexport interface ReportData {\n  issues: CategorizedIssue[]\n  duplicates: DuplicateGroup[]\n  clusters: WorkCluster[]\n  metadata: {\n    generatedAt: string\n    totalIssues: number\n    totalPRs: number\n    categorizedIssues: number\n    uncategorizedIssues: number\n  }\n}\n\nexport interface ReportOptions {\n  variant: 'full' | 'priority' | 'category'\n  category?: string\n  includeUncategorized?: boolean\n  maxIssuesPerSection?: number\n}\n\nexport interface ReportSection {\n  title: string\n  content: string\n  priority: number\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/reports/utils.ts",
    "content": "import type { CategorizedIssue } from '../categorize/types.js'\n\n/**\n * Format issue as markdown link\n */\nexport function formatIssueLink(issue: CategorizedIssue): string {\n  const type = issue.type === 'pr' ? 'PR' : 'Issue'\n  return `[${type} #${issue.number}](${issue.url}): ${issue.title}`\n}\n\n/**\n * Format date as relative time\n */\nexport function formatRelativeDate(date: Date | string): string {\n  const dateObj = typeof date === 'string' ? new Date(date) : date\n  const now = new Date()\n  const daysDiff = Math.floor(\n    (now.getTime() - dateObj.getTime()) / (1000 * 60 * 60 * 24),\n  )\n\n  if (daysDiff === 0) return 'today'\n  if (daysDiff === 1) return 'yesterday'\n  if (daysDiff < 7) return `${daysDiff} days ago`\n  if (daysDiff < 30) return `${Math.floor(daysDiff / 7)} weeks ago`\n  if (daysDiff < 365) return `${Math.floor(daysDiff / 30)} months ago`\n  return `${Math.floor(daysDiff / 365)} years ago`\n}\n\n/**\n * Format score as visual indicator\n */\nexport function formatScoreBar(score: number, maxWidth: number = 10): string {\n  // Clamp score between 0 and 100\n  const clampedScore = Math.max(0, Math.min(100, score))\n  const filled = Math.round((clampedScore / 100) * maxWidth)\n  const empty = maxWidth - filled\n  return '█'.repeat(filled) + '░'.repeat(empty)\n}\n\n/**\n * Format confidence as emoji\n */\nexport function formatConfidence(\n  confidence: 'high' | 'medium' | 'low',\n): string {\n  return {\n    high: '🔴',\n    medium: '🟡',\n    low: '🟢',\n  }[confidence]\n}\n\n/**\n * Format flags as badges\n */\nexport function formatFlags(issue: CategorizedIssue): string {\n  const flags: string[] = []\n\n  if (issue.flags.isUrgent) flags.push('🚨 urgent')\n  if (issue.flags.isEasyFix) flags.push('✅ easy-fix')\n  if (issue.flags.needsRepro) flags.push('🔍 needs-repro')\n  if (issue.flags.isStale) flags.push('⏰ stale')\n  if (issue.flags.hasBreakingChange) flags.push('⚠️ breaking-change')\n  if (issue.flags.needsTriage) flags.push('🏷️ needs-triage')\n\n  return flags.join(' ')\n}\n\n/**\n * Truncate text to max length\n */\nexport function truncate(text: string, maxLength: number): string {\n  if (text.length <= maxLength) return text\n  return text.slice(0, maxLength - 3) + '...'\n}\n\n/**\n * Group issues by category\n */\nexport function groupByCategory(\n  issues: CategorizedIssue[],\n): Record<string, CategorizedIssue[]> {\n  return issues.reduce(\n    (acc, issue) => {\n      const key = issue.categorization.primary\n      if (!acc[key]) acc[key] = []\n      acc[key].push(issue)\n      return acc\n    },\n    {} as Record<string, CategorizedIssue[]>,\n  )\n}\n\n/**\n * Calculate priority score with time decay\n * Recent issues get higher priority, older issues decay\n */\nexport function calculatePriority(issue: CategorizedIssue): number {\n  const now = new Date()\n  const ageInDays = Math.floor(\n    (now.getTime() - issue.created_at.getTime()) / (1000 * 60 * 60 * 24),\n  )\n\n  // Time decay factor: 1.0 for new issues, decays to ~0.1 after 2 years\n  // Using exponential decay with half-life of ~180 days (6 months)\n  const timeDecay = Math.exp(-ageInDays / 180)\n\n  // Base priority from urgency and engagement\n  const basePriority = issue.scores.urgency * issue.scores.engagement\n\n  // Apply time decay\n  return basePriority * timeDecay\n}\n\n/**\n * Sort issues by priority score (with time decay)\n */\nexport function sortByPriority(issues: CategorizedIssue[]): CategorizedIssue[] {\n  return [...issues].sort((a, b) => {\n    const priorityA = calculatePriority(a)\n    const priorityB = calculatePriority(b)\n    return priorityB - priorityA\n  })\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/similarity/clusters.ts",
    "content": "import type { CategorizedIssue } from '../categorize/types.js'\nimport type { WorkCluster } from './types.js'\nimport { groupBy } from './utils.js'\n\n/**\n * Create work clusters from categorized issues\n * Groups related issues that could be worked on together\n */\nexport function createWorkClusters(issues: CategorizedIssue[]): WorkCluster[] {\n  // Group by subcategory\n  const bySubcategory = groupBy(\n    issues,\n    (issue) =>\n      `${issue.categorization.primary}/${issue.categorization.secondary || 'other'}`,\n  )\n\n  const clusters: WorkCluster[] = []\n\n  for (const [category, groupIssues] of Object.entries(bySubcategory)) {\n    if (groupIssues.length < 2) continue\n\n    // Sort by priority (urgency × engagement)\n    const sorted = groupIssues\n      .map((issue) => ({\n        issue,\n        priority: issue.scores.urgency * issue.scores.engagement,\n      }))\n      .sort((a, b) => b.priority - a.priority)\n\n    // Create clusters of 3-5 issues\n    for (let i = 0; i < sorted.length; i += 4) {\n      const clusterIssues = sorted.slice(i, i + 5).map((s) => s.issue)\n      if (clusterIssues.length < 2) continue\n\n      const metrics = calculateClusterMetrics(clusterIssues)\n\n      // Skip clusters that are too easy or too hard\n      if (metrics.avgComplexity < 30 || metrics.avgComplexity > 80) continue\n\n      const [primary, secondary] = category.split('/')\n\n      const cluster: WorkCluster = {\n        id: `cluster-${clusters.length + 1}`,\n        category: primary,\n        subcategory: secondary !== 'other' ? secondary : undefined,\n        issues: clusterIssues,\n        metrics,\n        reasoning: generateClusterReasoning(clusterIssues, category),\n        priority: calculateClusterPriority(metrics),\n      }\n\n      clusters.push(cluster)\n    }\n  }\n\n  return clusters.sort((a, b) => b.priority - a.priority).slice(0, 10) // Top 10 clusters\n}\n\n/**\n * Calculate aggregate metrics for a cluster of issues\n */\nfunction calculateClusterMetrics(issues: CategorizedIssue[]) {\n  const complexities = issues.map((i) => i.scores.complexity)\n  const engagements = issues.map((i) => i.scores.engagement)\n  const urgencies = issues.map((i) => i.scores.urgency)\n\n  return {\n    avgComplexity: average(complexities),\n    totalEngagement: sum(engagements),\n    avgUrgency: average(urgencies),\n    estimatedEffort: estimateEffort(average(complexities), issues.length),\n  }\n}\n\n/**\n * Generate reasoning text for why issues are clustered together\n */\nfunction generateClusterReasoning(\n  issues: CategorizedIssue[],\n  category: string,\n): string {\n  const [primary, secondary] = category.split('/')\n\n  // Extract common keywords from titles\n  const allWords = issues.flatMap((i) =>\n    i.title\n      .toLowerCase()\n      .replace(/[^\\w\\s]/g, ' ')\n      .split(/\\s+/)\n      .filter((w) => w.length > 3),\n  )\n\n  const wordCounts: Record<string, number> = {}\n  for (const word of allWords) {\n    wordCounts[word] = (wordCounts[word] || 0) + 1\n  }\n\n  const commonWords = Object.entries(wordCounts)\n    .filter(([_, count]) => count >= 2)\n    .sort((a, b) => b[1] - a[1])\n    .slice(0, 3)\n    .map(([word]) => word)\n\n  let reasoning = `Related ${primary}${secondary !== 'other' ? `/${secondary}` : ''} issues`\n\n  if (commonWords.length > 0) {\n    reasoning += ` involving: ${commonWords.join(', ')}`\n  }\n\n  // Add specific patterns\n  const hasErrors = issues.some((i) => i.body?.toLowerCase().includes('error'))\n  const hasTypes = issues.some((i) => i.body?.toLowerCase().includes('type'))\n  const hasPerf = issues.some(\n    (i) =>\n      i.title.toLowerCase().includes('performance') ||\n      i.title.toLowerCase().includes('slow'),\n  )\n\n  const patterns: string[] = []\n  if (hasErrors) patterns.push('error handling')\n  if (hasTypes) patterns.push('TypeScript types')\n  if (hasPerf) patterns.push('performance')\n\n  if (patterns.length > 0) {\n    reasoning += `. Focus areas: ${patterns.join(', ')}`\n  }\n\n  return reasoning\n}\n\n/**\n * Calculate priority score for a cluster\n * Higher scores indicate more important clusters to work on\n */\nfunction calculateClusterPriority(metrics: {\n  totalEngagement: number\n  avgComplexity: number\n  avgUrgency: number\n}): number {\n  return (\n    (metrics.totalEngagement / 100) * 0.4 +\n    (100 - Math.abs(metrics.avgComplexity - 55)) * 0.3 +\n    metrics.avgUrgency * 0.2 +\n    10 * 0.1\n  )\n}\n\n/**\n * Calculate average of an array of numbers\n */\nfunction average(numbers: number[]): number {\n  return numbers.reduce((a, b) => a + b, 0) / numbers.length\n}\n\n/**\n * Calculate sum of an array of numbers\n */\nfunction sum(numbers: number[]): number {\n  return numbers.reduce((a, b) => a + b, 0)\n}\n\n/**\n * Estimate effort in days based on complexity and issue count\n */\nfunction estimateEffort(avgComplexity: number, issueCount: number): number {\n  // Rough estimate: 50 complexity = 1 day\n  const baseEffort = avgComplexity / 50\n  return Math.round(baseEffort * issueCount * 10) / 10\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/similarity/duplicates.ts",
    "content": "import type { CategorizedIssue } from '../categorize/types.js'\nimport type { DuplicateGroup, SimilarityResult } from './types.js'\nimport { calculateSimilarity } from './similarity.js'\n\n/**\n * Find potential duplicates for all issues\n * Returns groups where each group has a primary issue and its duplicates\n */\nexport function findAllDuplicates(\n  issues: CategorizedIssue[],\n): DuplicateGroup[] {\n  const duplicateGroups: DuplicateGroup[] = []\n  const processed = new Set<number>()\n\n  for (const issue of issues) {\n    if (processed.has(issue.number)) continue\n\n    const duplicates = findPotentialDuplicates(issue, issues).filter(\n      (result) => result.confidence !== 'low',\n    )\n\n    if (duplicates.length > 0) {\n      duplicateGroups.push({\n        primary: issue,\n        duplicates: duplicates.map((result) => ({\n          issue: issues.find((i) => i.number === result.issue2)!,\n          confidence: result.score,\n          signals: result.signals,\n        })),\n      })\n\n      // Mark all as processed\n      processed.add(issue.number)\n      duplicates.forEach((d) => processed.add(d.issue2))\n    }\n  }\n\n  return duplicateGroups.sort(\n    (a, b) => b.duplicates.length - a.duplicates.length,\n  )\n}\n\n/**\n * Find potential duplicates for a single issue\n * Returns up to 5 most similar issues with medium or high confidence\n */\nexport function findPotentialDuplicates(\n  issue: CategorizedIssue,\n  allIssues: CategorizedIssue[],\n): SimilarityResult[] {\n  return allIssues\n    .filter((other) => other.number !== issue.number)\n    .map((other) => calculateSimilarity(issue, other))\n    .filter((result) => result.score >= 0.6) // Medium confidence threshold\n    .sort((a, b) => b.score - a.score)\n    .slice(0, 5) // Top 5 potential duplicates\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/similarity/index.ts",
    "content": "export * from './types.js'\nexport * from './similarity.js'\nexport * from './duplicates.js'\nexport * from './clusters.js'\nexport * from './utils.js'\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/similarity/similarity.ts",
    "content": "import type { CategorizedIssue } from '../categorize/types.js'\nimport type { SimilarityResult, SimilaritySignals } from './types.js'\nimport {\n  tokenize,\n  extractKeywords,\n  extractErrorMessage,\n  normalizeErrorPattern,\n} from './utils.js'\n\n/**\n * Calculate Jaccard similarity between two titles\n * Returns a value between 0 (no similarity) and 1 (identical)\n */\nexport function calculateTitleSimilarity(\n  title1: string,\n  title2: string,\n): number {\n  const words1 = new Set(tokenize(title1))\n  const words2 = new Set(tokenize(title2))\n\n  if (words1.size === 0 || words2.size === 0) return 0\n\n  const intersection = new Set([...words1].filter((w) => words2.has(w)))\n  const union = new Set([...words1, ...words2])\n\n  return intersection.size / union.size\n}\n\n/**\n * Calculate keyword overlap between two issues\n * Returns a value between 0 (no overlap) and 1 (complete overlap)\n */\nexport function calculateKeywordOverlap(\n  issue1: CategorizedIssue,\n  issue2: CategorizedIssue,\n): number {\n  const text1 = `${issue1.title} ${issue1.body || ''}`\n  const text2 = `${issue2.title} ${issue2.body || ''}`\n\n  const keywords1 = new Set(extractKeywords(text1))\n  const keywords2 = new Set(extractKeywords(text2))\n\n  if (keywords1.size === 0 || keywords2.size === 0) return 0\n\n  const intersection = new Set([...keywords1].filter((k) => keywords2.has(k)))\n  const union = new Set([...keywords1, ...keywords2])\n\n  return intersection.size / union.size\n}\n\n/**\n * Calculate category match score\n * Returns 1.0 for same subcategory, 0.5 for same primary, 0 otherwise\n */\nexport function calculateCategoryMatch(\n  issue1: CategorizedIssue,\n  issue2: CategorizedIssue,\n): number {\n  if (\n    issue1.categorization.secondary === issue2.categorization.secondary &&\n    issue1.categorization.secondary !== null\n  ) {\n    return 1.0\n  }\n  if (issue1.categorization.primary === issue2.categorization.primary) {\n    return 0.5\n  }\n  return 0\n}\n\n/**\n * Calculate error pattern match score\n * Returns 1.0 for exact match, 0.8 for normalized match, 0 otherwise\n */\nexport function calculateErrorPatternMatch(\n  issue1: CategorizedIssue,\n  issue2: CategorizedIssue,\n): number {\n  const error1 = extractErrorMessage(issue1.body || '')\n  const error2 = extractErrorMessage(issue2.body || '')\n\n  if (!error1 || !error2) return 0\n  if (error1 === error2) return 1.0\n\n  const pattern1 = normalizeErrorPattern(error1)\n  const pattern2 = normalizeErrorPattern(error2)\n\n  return pattern1 === pattern2 ? 0.8 : 0\n}\n\n/**\n * Calculate temporal proximity score\n * Returns higher scores for issues created closer in time\n */\nexport function calculateTemporalProximity(\n  issue1: CategorizedIssue,\n  issue2: CategorizedIssue,\n): number {\n  const date1 = new Date(issue1.created_at).getTime()\n  const date2 = new Date(issue2.created_at).getTime()\n  const daysDiff = Math.abs(date1 - date2) / (1000 * 60 * 60 * 24)\n\n  if (daysDiff <= 1) return 1.0\n  if (daysDiff <= 7) return 0.7\n  if (daysDiff <= 30) return 0.3\n  return 0\n}\n\n/**\n * Calculate overall similarity between two issues using weighted signals\n */\nexport function calculateSimilarity(\n  issue1: CategorizedIssue,\n  issue2: CategorizedIssue,\n): SimilarityResult {\n  const signals: SimilaritySignals = {\n    titleSimilarity: calculateTitleSimilarity(issue1.title, issue2.title),\n    keywordOverlap: calculateKeywordOverlap(issue1, issue2),\n    categoryMatch: calculateCategoryMatch(issue1, issue2),\n    errorPatternMatch: calculateErrorPatternMatch(issue1, issue2),\n    temporalProximity: calculateTemporalProximity(issue1, issue2),\n  }\n\n  // Weighted score calculation\n  const score =\n    signals.titleSimilarity * 0.3 +\n    signals.keywordOverlap * 0.25 +\n    signals.categoryMatch * 0.25 +\n    signals.errorPatternMatch * 0.15 +\n    signals.temporalProximity * 0.05\n\n  const confidence: 'high' | 'medium' | 'low' =\n    score >= 0.75 ? 'high' : score >= 0.6 ? 'medium' : 'low'\n\n  const relationship = determineRelationship(score, signals)\n\n  return {\n    issue1: issue1.number,\n    issue2: issue2.number,\n    score,\n    signals,\n    confidence,\n    relationship,\n  }\n}\n\n/**\n * Determine the type of relationship between issues based on signals\n */\nfunction determineRelationship(\n  score: number,\n  signals: SimilaritySignals,\n): 'duplicate' | 'related' | 'consolidation' {\n  // High similarity + error match = likely duplicate\n  if (score >= 0.75 && signals.errorPatternMatch > 0.8) {\n    return 'duplicate'\n  }\n\n  // High similarity + same subcategory = consolidation opportunity\n  if (score >= 0.65 && signals.categoryMatch === 1.0) {\n    return 'consolidation'\n  }\n\n  // Otherwise, just related\n  return 'related'\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/similarity/types.ts",
    "content": "import type { CategorizedIssue } from '../categorize/types.js'\n\n/**\n * Individual similarity signals between two issues\n */\nexport interface SimilaritySignals {\n  /** Jaccard similarity of tokenized titles (0-1) */\n  titleSimilarity: number\n  /** Overlap of extracted technical keywords (0-1) */\n  keywordOverlap: number\n  /** Match score based on category/subcategory (0-1) */\n  categoryMatch: number\n  /** Match score for error patterns (0-1) */\n  errorPatternMatch: number\n  /** Proximity in time of creation (0-1) */\n  temporalProximity: number\n}\n\n/**\n * Result of comparing two issues for similarity\n */\nexport interface SimilarityResult {\n  /** Issue number of first issue */\n  issue1: number\n  /** Issue number of second issue */\n  issue2: number\n  /** Overall similarity score (0-1) */\n  score: number\n  /** Individual signal scores */\n  signals: SimilaritySignals\n  /** Confidence level in the similarity assessment */\n  confidence: 'high' | 'medium' | 'low'\n  /** Type of relationship between issues */\n  relationship: 'duplicate' | 'related' | 'consolidation'\n}\n\n/**\n * A cluster of related issues that could be worked on together\n */\nexport interface WorkCluster {\n  /** Unique cluster identifier */\n  id: string\n  /** Primary category */\n  category: string\n  /** Subcategory if applicable */\n  subcategory?: string\n  /** Issues in this cluster */\n  issues: CategorizedIssue[]\n  /** Aggregate metrics for the cluster */\n  metrics: {\n    /** Average complexity score */\n    avgComplexity: number\n    /** Total engagement across all issues */\n    totalEngagement: number\n    /** Average urgency score */\n    avgUrgency: number\n    /** Estimated effort in days */\n    estimatedEffort: number\n  }\n  /** Explanation of why these issues are clustered */\n  reasoning: string\n  /** Priority score for this cluster */\n  priority: number\n}\n\n/**\n * A group of duplicate issues\n */\nexport interface DuplicateGroup {\n  /** The primary/canonical issue */\n  primary: CategorizedIssue\n  /** Potential duplicates of the primary issue */\n  duplicates: Array<{\n    /** The duplicate issue */\n    issue: CategorizedIssue\n    /** Confidence that this is a duplicate (0-1) */\n    confidence: number\n    /** Similarity signals that led to this match */\n    signals: SimilaritySignals\n  }>\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/similarity/utils.ts",
    "content": "/**\n * Common English stop words to filter out during tokenization\n */\nconst STOP_WORDS = new Set([\n  'the',\n  'is',\n  'at',\n  'which',\n  'on',\n  'a',\n  'an',\n  'and',\n  'or',\n  'but',\n  'in',\n  'with',\n  'to',\n  'for',\n  'of',\n  'as',\n  'by',\n  'from',\n  'that',\n  'this',\n])\n\n/**\n * Tokenize text into words, removing stop words and short words\n */\nexport function tokenize(text: string): string[] {\n  return text\n    .toLowerCase()\n    .replace(/[^\\w\\s]/g, ' ')\n    .split(/\\s+/)\n    .filter((word) => word.length > 2)\n    .filter((word) => !STOP_WORDS.has(word))\n}\n\n/**\n * Extract technical keywords from text using pattern matching\n */\nexport function extractKeywords(text: string): string[] {\n  const patterns = {\n    // RTK Query specific patterns\n    technical: /\\b[a-z]+Query\\b|\\b[a-z]+Mutation\\b|createApi|fetchBaseQuery/gi,\n    // Error-related keywords\n    errors: /\\b(error|bug|issue|problem|fail|crash|broken)\\b/gi,\n    // Domain-specific keywords\n    domain: /\\b(polling|cache|invalidate|refetch|ssr|hydration|optimistic)\\b/gi,\n    // Function calls\n    functions: /\\b\\w+\\(\\)/g,\n  }\n\n  const keywords: string[] = []\n  for (const pattern of Object.values(patterns)) {\n    const matches = text.match(pattern) || []\n    keywords.push(...matches.map((k) => k.toLowerCase()))\n  }\n\n  return [...new Set(keywords)]\n}\n\n/**\n * Extract error message from issue body\n */\nexport function extractErrorMessage(body: string): string | null {\n  const patterns = [\n    /Error: (.+?)(?:\\n|$)/i,\n    /TypeError: (.+?)(?:\\n|$)/i,\n    /Exception: (.+?)(?:\\n|$)/i,\n    /Failed to (.+?)(?:\\n|$)/i,\n  ]\n\n  for (const pattern of patterns) {\n    const match = body.match(pattern)\n    if (match) return match[1].trim()\n  }\n\n  return null\n}\n\n/**\n * Normalize error pattern for comparison by replacing specific values\n * with placeholders\n */\nexport function normalizeErrorPattern(error: string): string {\n  return error\n    .replace(/\\d+/g, 'N') // Replace numbers with N\n    .replace(/'[^']+'/g, 'STR') // Replace single-quoted strings\n    .replace(/\"[^\"]+\"/g, 'STR') // Replace double-quoted strings\n}\n\n/**\n * Group array by key function\n */\nexport function groupBy<T>(\n  array: T[],\n  keyFn: (item: T) => string,\n): Record<string, T[]> {\n  return array.reduce(\n    (acc, item) => {\n      const key = keyFn(item)\n      if (!acc[key]) acc[key] = []\n      acc[key].push(item)\n      return acc\n    },\n    {} as Record<string, T[]>,\n  )\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/src/utils/errors.ts",
    "content": "/**\n * Custom error classes for GitHub operations\n */\n\n/**\n * Base error class for GitHub-related errors\n */\nexport class GitHubError extends Error {\n  constructor(\n    message: string,\n    public readonly cause?: unknown,\n  ) {\n    super(message)\n    this.name = 'GitHubError'\n    // Maintains proper stack trace for where our error was thrown (only available on V8)\n    if (Error.captureStackTrace) {\n      Error.captureStackTrace(this, this.constructor)\n    }\n  }\n}\n\n/**\n * Error thrown when gh CLI is not found or not authenticated\n */\nexport class GhCliError extends GitHubError {\n  constructor(message: string, cause?: unknown) {\n    super(message, cause)\n    this.name = 'GhCliError'\n  }\n}\n\n/**\n * Error thrown for network or API errors\n */\nexport class GhApiError extends GitHubError {\n  constructor(\n    message: string,\n    public readonly statusCode?: number,\n    cause?: unknown,\n  ) {\n    super(message, cause)\n    this.name = 'GhApiError'\n  }\n}\n\n/**\n * Error thrown when JSON response cannot be parsed\n */\nexport class GhParseError extends GitHubError {\n  constructor(\n    message: string,\n    public readonly rawOutput?: string,\n    cause?: unknown,\n  ) {\n    super(message, cause)\n    this.name = 'GhParseError'\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/scripts/issue-triage/tsconfig.json",
    "content": "{\n  \"compilerOptions\": {\n    \"target\": \"ES2022\",\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"lib\": [\"ES2022\"],\n    \"outDir\": \"./dist\",\n    \"rootDir\": \"./src\",\n    \"strict\": true,\n    \"esModuleInterop\": true,\n    \"skipLibCheck\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"resolveJsonModule\": true,\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"sourceMap\": true\n  },\n  \"include\": [\"src/**/*\"],\n  \"exclude\": [\"node_modules\", \"dist\"]\n}"
  },
  {
    "path": "packages/toolkit/scripts/mangleErrors.mts",
    "content": "import type { Node, PluginObj, PluginPass } from '@babel/core'\nimport * as helperModuleImports from '@babel/helper-module-imports'\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\ntype Babel = typeof import('@babel/core')\n\n/**\n * Represents the options for the {@linkcode mangleErrorsPlugin}.\n *\n * @internal\n */\nexport interface MangleErrorsPluginOptions {\n  /**\n   * Whether to minify the error messages or not.\n   * If `true`, the error messages will be replaced with an index\n   * that maps object lookup.\n   */\n  minify: boolean\n}\n\n/**\n * Converts an AST type into a JavaScript string so that it can be added to\n * the error message lookup.\n *\n * Adapted from React\n * {@linkcode https://github.com/facebook/react/blob/master/scripts/shared/evalToString.js | evalToString}\n * with some adjustments.\n */\nconst evalToString = (\n  ast: Node | { type: 'Literal'; value: string },\n): string => {\n  switch (ast.type) {\n    case 'StringLiteral':\n    case 'Literal': // ESLint\n      return ast.value\n    case 'BinaryExpression': // `+`\n      if (ast.operator !== '+') {\n        throw new Error('Unsupported binary operator ' + ast.operator)\n      }\n      return evalToString(ast.left) + evalToString(ast.right)\n    case 'TemplateLiteral':\n      return ast.quasis.reduce(\n        (concatenatedValue, templateElement) =>\n          concatenatedValue + templateElement.value.raw,\n        '',\n      )\n    case 'Identifier':\n      return ast.name\n    default:\n      console.log('Bad AST in mangleErrors -> evalToString(): ', ast)\n      throw new Error(`Unsupported AST in evalToString: ${ast.type}, ${ast}`)\n  }\n}\n\n/**\n * Transforms a `throw new Error` statement based on the\n * {@linkcode MangleErrorsPluginOptions.minify | minify} argument,\n * resulting in a smaller bundle size for consumers in production.\n *\n * If {@linkcode MangleErrorsPluginOptions.minify | minify} is enabled,\n * the error message will be replaced with an index that maps to\n * an object lookup.\n *\n * If {@linkcode MangleErrorsPluginOptions.minify | minify} is disabled,\n * a conditional statement will be added to check `process.env.NODE_ENV`,\n * which will output an error number index in production or the actual\n * error message in development. This allows consumers using Webpack or\n * another build tool to have these messages in development but only the\n * error index in production.\n *\n * @example\n * <caption>__Before:__</caption>\n *\n * ```ts\n * throw new Error('each middleware provided to configureStore must be a function');\n * throw new Error(\n *   '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers',\n * )\n * ```\n *\n * @example\n * <caption>__After (with minify):__</caption>\n *\n * ```ts\n * throw new Error(formatProdErrorMessage(0));\n * throw new Error(formatProdErrorMessage(1));\n * ```\n *\n * @example\n * <caption>__After (without minify):__</caption>\n *\n * ```ts\n * throw new Error(\n *   process.env.NODE_ENV === 'production'\n *     ? formatProdErrorMessage(4)\n *     : 'each middleware provided to configureStore must be a function',\n * )\n * ```\n */\nexport const mangleErrorsPlugin = (\n  babel: Babel,\n  options: MangleErrorsPluginOptions,\n): PluginObj<PluginPass & MangleErrorsPluginOptions> => {\n  const t = babel.types\n  // When the plugin starts up, we'll load in the existing file. This allows us to continually add to it so that the\n  // indexes do not change between builds.\n  let errorsFiles = ''\n  // Save this to the root\n  const errorsPath = path.join(__dirname, '../../../errors.json')\n  if (fs.existsSync(errorsPath)) {\n    errorsFiles = fs.readFileSync(errorsPath).toString()\n  }\n  const errors = Object.values(JSON.parse(errorsFiles || '{}'))\n  // This variable allows us to skip writing back to the file if the errors array hasn't changed\n  let changeInArray = false\n\n  return {\n    name: 'mangle-errors-plugin',\n    pre: () => {\n      changeInArray = false\n    },\n    visitor: {\n      ThrowStatement(path) {\n        if (\n          !('arguments' in path.node.argument) ||\n          !t.isNewExpression(path.node.argument)\n        ) {\n          return\n        }\n        const args = path.node.argument.arguments\n        const { minify } = options\n\n        if (args && args[0]) {\n          // Skip running this logic when certain types come up:\n          //  Identifier comes up when a variable is thrown (E.g. throw new error(message))\n          //  NumericLiteral, CallExpression, and ConditionalExpression is code we have already processed\n          if (\n            path.node.argument.arguments[0].type === 'Identifier' ||\n            path.node.argument.arguments[0].type === 'NumericLiteral' ||\n            path.node.argument.arguments[0].type === 'ConditionalExpression' ||\n            path.node.argument.arguments[0].type === 'CallExpression' ||\n            path.node.argument.arguments[0].type === 'ObjectExpression' ||\n            path.node.argument.arguments[0].type === 'MemberExpression' ||\n            !t.isExpression(path.node.argument.arguments[0]) ||\n            !t.isIdentifier(path.node.argument.callee)\n          ) {\n            return\n          }\n\n          const errorName = path.node.argument.callee.name\n\n          const errorMsgLiteral = evalToString(path.node.argument.arguments[0])\n\n          if (errorMsgLiteral.includes('Super expression')) {\n            // ignore Babel runtime error message\n            return\n          }\n\n          // Attempt to get the existing index of the error. If it is not found, add it to the array as a new error.\n          let errorIndex = errors.indexOf(errorMsgLiteral)\n          if (errorIndex === -1) {\n            errors.push(errorMsgLiteral)\n            errorIndex = errors.length - 1\n            changeInArray = true\n          }\n\n          // Import the error message function\n          const formatProdErrorMessageIdentifier = helperModuleImports.addNamed(\n            path,\n            'formatProdErrorMessage',\n            '@reduxjs/toolkit',\n            { nameHint: 'formatProdErrorMessage' },\n          )\n\n          // Creates a function call to output the message to the error code page on the website\n          const prodMessage = t.callExpression(\n            formatProdErrorMessageIdentifier,\n            [t.numericLiteral(errorIndex)],\n          )\n\n          if (minify) {\n            path.replaceWith(\n              t.throwStatement(\n                t.newExpression(t.identifier(errorName), [prodMessage]),\n              ),\n            )\n          } else {\n            path.replaceWith(\n              t.throwStatement(\n                t.newExpression(t.identifier(errorName), [\n                  t.conditionalExpression(\n                    t.binaryExpression(\n                      '===',\n                      t.identifier('process.env.NODE_ENV'),\n                      t.stringLiteral('production'),\n                    ),\n                    prodMessage,\n                    path.node.argument.arguments[0],\n                  ),\n                ]),\n              ),\n            )\n          }\n        }\n      },\n    },\n    post: () => {\n      // If there is a new error in the array, convert it to an indexed object and write it back to the file.\n      if (changeInArray) {\n        fs.writeFileSync(errorsPath, JSON.stringify({ ...errors }, null, 2))\n      }\n    },\n  }\n}\n\nexport default mangleErrorsPlugin\n"
  },
  {
    "path": "packages/toolkit/scripts/writeGitVersion.mts",
    "content": "#!/usr/bin/env node --import=tsx\n\nimport * as fs from 'node:fs'\nimport * as path from 'node:path'\n\nconst gitRev = process.argv[2]\n\nconst packagePath = path.join(import.meta.dirname, '../package.json')\nconst pkg = JSON.parse(fs.readFileSync(packagePath, 'utf-8'))\n\npkg.version = `${pkg.version}-${gitRev}`\nfs.writeFileSync(packagePath, JSON.stringify(pkg, null, 2))\n"
  },
  {
    "path": "packages/toolkit/skills/build-modern-redux-apps/modern-redux/SKILL.md",
    "content": "---\nname: build-modern-redux-apps/modern-redux\ndescription: >\n  Use this when setting up a new Redux Toolkit app or modernizing an existing\n  React + Redux codebase. Covers configureStore, Provider wiring, typed hooks,\n  hooks-first React-Redux usage, feature folders, and the correct store lifetime\n  for SPA and SSR-heavy React environments.\ntype: lifecycle\nlibrary: \"@reduxjs/toolkit\"\nlibrary_version: \"2.11.2\"\nrequires:\n  - build-modern-redux-apps/redux-dataflow\nsources:\n  - \"reduxjs/redux-toolkit:docs/tutorials/quick-start.mdx\"\n  - \"reduxjs/redux-toolkit:docs/tutorials/typescript.md\"\n  - \"reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx\"\n  - \"reduxjs/redux-toolkit:docs/usage/nextjs.mdx\"\n  - \"reduxjs/redux:docs/style-guide/style-guide.md\"\n---\n\n# Modern Redux\n\n## Setup\n\n```tsx\n// file: src/features/counter/counterSlice.ts\nimport { createSlice } from '@reduxjs/toolkit'\n\nexport const counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 },\n  reducers: {\n    increment(state) {\n      state.value += 1\n    },\n  },\n})\n\nexport const { increment } = counterSlice.actions\n\n// file: src/app/store.ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport { counterSlice } from '../features/counter/counterSlice'\n\nexport const store = configureStore({\n  reducer: {\n    counter: counterSlice.reducer,\n  },\n})\n\nexport type RootState = ReturnType<typeof store.getState>\nexport type AppDispatch = typeof store.dispatch\n\n// file: src/app/hooks.ts\nimport { useDispatch, useSelector } from 'react-redux'\nimport type { AppDispatch, RootState } from './store'\n\nexport const useAppDispatch = useDispatch.withTypes<AppDispatch>()\nexport const useAppSelector = useSelector.withTypes<RootState>()\n\n// file: src/features/counter/Counter.tsx\nimport { increment } from './counterSlice'\nimport { useAppDispatch, useAppSelector } from '../../app/hooks'\n\nexport function Counter() {\n  const value = useAppSelector((state) => state.counter.value)\n  const dispatch = useAppDispatch()\n\n  return <button onClick={() => dispatch(increment())}>{value}</button>\n}\n\n// file: src/main.tsx\nimport React from 'react'\nimport ReactDOM from 'react-dom/client'\nimport { Provider } from 'react-redux'\nimport { store } from './app/store'\nimport { Counter } from './features/counter/Counter'\n\nReactDOM.createRoot(document.getElementById('root')!).render(\n  <Provider store={store}>\n    <Counter />\n  </Provider>,\n)\n```\n\n## Core Patterns\n\n### Keep React components on hooks, not wrappers\n\n```tsx\nimport { postAdded, selectPosts } from './postsSlice'\nimport { useAppDispatch, useAppSelector } from '../../app/hooks'\n\nexport function PostsList() {\n  const posts = useAppSelector(selectPosts)\n  const dispatch = useAppDispatch()\n\n  return (\n    <button\n      onClick={() =>\n        dispatch(postAdded({ id: 'p2', title: 'Write docs' }))\n      }\n    >\n      {posts.length}\n    </button>\n  )\n}\n```\n\nHooks are the default React-Redux integration for new code.\n\n### Create the store inside the provider for SSR-heavy React apps\n\n```tsx\n// file: src/lib/store.ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport { counterSlice } from '../features/counter/counterSlice'\n\nexport const makeStore = () =>\n  configureStore({\n    reducer: {\n      counter: counterSlice.reducer,\n    },\n  })\n\nexport type AppStore = ReturnType<typeof makeStore>\nexport type RootState = ReturnType<AppStore['getState']>\nexport type AppDispatch = AppStore['dispatch']\n\n// file: src/app/StoreProvider.tsx\n'use client'\n\nimport { useState, type ReactNode } from 'react'\nimport { Provider } from 'react-redux'\nimport { makeStore } from '../lib/store'\n\nexport function StoreProvider({ children }: { children: ReactNode }) {\n  const [store] = useState(makeStore)\n\n  return <Provider store={store}>{children}</Provider>\n}\n```\n\nIn SSR-heavy React frameworks, create a store per request and keep that instance stable across renders.\n\n### Keep app wiring in `app/` and feature logic in feature folders\n\n```text\nsrc/\n  app/\n    store.ts\n    hooks.ts\n  features/\n    posts/\n      postsSlice.ts\n      PostsList.tsx\n    users/\n      usersSlice.ts\n      UsersList.tsx\n```\n\nThis keeps store wiring centralized and feature logic colocated.\n\n## Common Mistakes\n\n### HIGH Importing the store in React components\n\nWrong:\n\n```tsx\nimport { store } from '../../app/store'\n\nexport function PostsList() {\n  const posts = store.getState().posts\n  return <div>{posts.length}</div>\n}\n```\n\nCorrect:\n\n```tsx\nimport { useAppSelector } from '../../app/hooks'\n\nexport function PostsList() {\n  const posts = useAppSelector((state) => state.posts)\n  return <div>{posts.length}</div>\n}\n```\n\nReact components should read through context and hooks; direct store imports are a separate escape hatch for non-React integrations, not the default UI pattern.\n\nSource: reduxjs/redux:docs/style-guide/style-guide.md\n\n### HIGH Defaulting to `connect()` in new React code\n\nWrong:\n\n```tsx\nimport { connect } from 'react-redux'\n\nconst increment = () => ({ type: 'counter/increment' as const })\nconst mapState = (state: { counter: { value: number } }) => ({\n  value: state.counter.value,\n})\nconst mapDispatch = { increment }\n\nfunction Counter({ value, increment }: ReturnType<typeof mapState> & typeof mapDispatch) {\n  return <button onClick={() => increment()}>{value}</button>\n}\n\nexport default connect(mapState, mapDispatch)(Counter)\n```\n\nCorrect:\n\n```tsx\nimport { increment } from './counterSlice'\nimport { useAppDispatch, useAppSelector } from '../../app/hooks'\n\nexport function Counter() {\n  const value = useAppSelector((state) => state.counter.value)\n  const dispatch = useAppDispatch()\n\n  return <button onClick={() => dispatch(increment())}>{value}</button>\n}\n```\n\nHooks are the modern default, simpler to type, and the maintainers explicitly want agents to steer new code away from `connect`.\n\nSource: reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx\n\n### HIGH Recreating the store during render in SSR-heavy apps\n\nWrong:\n\n```tsx\n'use client'\n\nimport { Provider } from 'react-redux'\nimport { makeStore } from '../lib/store'\n\nexport function StoreProvider({ children }: { children: import('react').ReactNode }) {\n  const store = makeStore()\n  return <Provider store={store}>{children}</Provider>\n}\n```\n\nCorrect:\n\n```tsx\n'use client'\n\nimport { useState } from 'react'\nimport { Provider } from 'react-redux'\nimport { makeStore } from '../lib/store'\n\nexport function StoreProvider({ children }: { children: import('react').ReactNode }) {\n  const [store] = useState(makeStore)\n  return <Provider store={store}>{children}</Provider>\n}\n```\n\nA new store on every render loses client state, while a module singleton can leak across requests on the server.\n\nSource: reduxjs/redux-toolkit:docs/usage/nextjs.mdx\n\n### HIGH Keeping `createStore` boilerplate as the default\n\nWrong:\n\n```ts\nimport { applyMiddleware, combineReducers, createStore } from 'redux'\nimport thunk from 'redux-thunk'\n\nconst counterReducer = (state = { value: 0 }) => state\n\nconst rootReducer = combineReducers({\n  counter: counterReducer,\n})\n\nexport const store = createStore(rootReducer, applyMiddleware(thunk))\n```\n\nCorrect:\n\n```ts\nimport { configureStore } from '@reduxjs/toolkit'\n\nconst counterReducer = (state = { value: 0 }) => state\n\nexport const store = configureStore({\n  reducer: {\n    counter: counterReducer,\n  },\n})\n```\n\nManual store setup works, but it throws away RTK's default middleware, dev checks, and the current recommended baseline.\n\nSource: reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx\n\n## References\n\n- [Store lifetime and framework boundaries](references/store-lifetime.md)\n"
  },
  {
    "path": "packages/toolkit/skills/build-modern-redux-apps/modern-redux/references/store-lifetime.md",
    "content": "# Store Lifetime\n\n## Decision table\n\n| Environment | Default store shape | Why |\n| --- | --- | --- |\n| Client-only SPA | One module-level singleton store | There is one browser session and no cross-request leakage risk. |\n| SSR-heavy React app | `makeStore()` plus provider-local state | Each request needs its own store instance, but that instance must stay stable across client renders. |\n| Non-React integration code | Direct store access can be acceptable | This is outside the React context boundary and should stay out of UI components. |\n\n## SPA pattern\n\n```ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport { postsSlice } from '../features/posts/postsSlice'\n\nexport const store = configureStore({\n  reducer: {\n    posts: postsSlice.reducer,\n  },\n})\n```\n\nUse this for classic browser SPAs.\n\n## SSR-heavy React pattern\n\n```tsx\n// file: src/lib/store.ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport { postsSlice } from '../features/posts/postsSlice'\n\nexport const makeStore = () =>\n  configureStore({\n    reducer: {\n      posts: postsSlice.reducer,\n    },\n  })\n\n// file: src/app/StoreProvider.tsx\n'use client'\n\nimport { useState, type ReactNode } from 'react'\nimport { Provider } from 'react-redux'\nimport { makeStore } from '../lib/store'\n\nexport function StoreProvider({ children }: { children: ReactNode }) {\n  const [store] = useState(makeStore)\n  return <Provider store={store}>{children}</Provider>\n}\n```\n\nCreate the store per request, then keep it stable inside the provider component.\n"
  },
  {
    "path": "packages/toolkit/skills/build-modern-redux-apps/redux-dataflow/SKILL.md",
    "content": "---\nname: build-modern-redux-apps/redux-dataflow\ndescription: >\n  Use this when you need the Redux event -> reducer -> selector -> render loop,\n  event-style actions, reducer-owned state transitions, derived data, or a\n  debugging model for Redux Toolkit apps.\ntype: core\nlibrary: \"@reduxjs/toolkit\"\nlibrary_version: \"2.11.2\"\nsources:\n  - \"reduxjs/redux:docs/tutorials/fundamentals/part-2-concepts-data-flow.md\"\n  - \"reduxjs/redux:docs/tutorials/essentials/part-3-data-flow.md\"\n  - \"reduxjs/redux:docs/style-guide/style-guide.md\"\n---\n\n# Redux Dataflow\n\n## Setup\n\n```ts\nimport { configureStore, createSelector, createSlice } from '@reduxjs/toolkit'\n\nconst postsSlice = createSlice({\n  name: 'posts',\n  initialState: {\n    items: [] as { id: string; title: string; published: boolean }[],\n    filter: 'all' as 'all' | 'published',\n  },\n  reducers: {\n    postAdded(state, action: { payload: { id: string; title: string } }) {\n      state.items.push({ ...action.payload, published: false })\n    },\n    postPublished(state, action: { payload: { id: string } }) {\n      const post = state.items.find((item) => item.id === action.payload.id)\n      if (post) {\n        post.published = true\n      }\n    },\n    filterChanged(state, action: { payload: 'all' | 'published' }) {\n      state.filter = action.payload\n    },\n  },\n})\n\nconst store = configureStore({\n  reducer: {\n    posts: postsSlice.reducer,\n  },\n})\n\ntype RootState = ReturnType<typeof store.getState>\n\nconst selectPostsState = (state: RootState) => state.posts\nconst selectVisiblePosts = createSelector([selectPostsState], (postsState) =>\n  postsState.filter === 'all'\n    ? postsState.items\n    : postsState.items.filter((post) => post.published),\n)\n\nstore.dispatch(postsSlice.actions.postAdded({ id: 'p1', title: 'Draft' }))\nstore.dispatch(postsSlice.actions.postPublished({ id: 'p1' }))\n\nconst visiblePosts = selectVisiblePosts(store.getState())\nconsole.log(visiblePosts)\n```\n\n## Core Patterns\n\n### Dispatch events, not setters\n\n```ts\nconst postsSlice = createSlice({\n  name: 'posts',\n  initialState: [] as { id: string; title: string }[],\n  reducers: {\n    postAdded(state, action: { payload: { id: string; title: string } }) {\n      state.push(action.payload)\n    },\n    postRemoved(state, action: { payload: { id: string } }) {\n      return state.filter((post) => post.id !== action.payload.id)\n    },\n    postUpdated(\n      state,\n      action: { payload: { id: string; changes: Partial<{ title: string }> } },\n    ) {\n      const post = state.find((item) => item.id === action.payload.id)\n      if (post && action.payload.changes.title) {\n        post.title = action.payload.changes.title\n      }\n    },\n  },\n})\n\npostsSlice.actions.postAdded({ id: 'p1', title: 'Draft' })\n```\n\nEvent-style actions explain what happened in the UI instead of hiding the transition behind a generic setter.\n\n### Let reducers combine old store data with new outside data\n\n```ts\nimport { createEntityAdapter, createSlice } from '@reduxjs/toolkit'\n\nconst postsAdapter = createEntityAdapter<{ id: string; title: string }>()\n\nconst postsSlice = createSlice({\n  name: 'posts',\n  initialState: postsAdapter.getInitialState(),\n  reducers: {\n    postsReceived(state, action: { payload: { id: string; title: string }[] }) {\n      postsAdapter.upsertMany(state, action.payload)\n    },\n  },\n})\n\nconst incomingPosts = [\n  { id: 'p1', title: 'Draft' },\n  { id: 'p2', title: 'Published' },\n]\n\npostsSlice.actions.postsReceived(incomingPosts)\n```\n\nIf a transition mixes current store state with new external data, dispatch the new external data and let the reducer own the merge.\n\n### Derive values with selectors instead of storing duplicates\n\n```ts\nimport { createSelector } from '@reduxjs/toolkit'\n\nconst selectPosts = (state: RootState) => state.posts.items\nconst selectFilter = (state: RootState) => state.posts.filter\n\nexport const selectVisiblePosts = createSelector(\n  [selectPosts, selectFilter],\n  (posts, filter) =>\n    filter === 'all'\n      ? posts\n      : posts.filter((post) => post.published),\n)\n```\n\nSelectors keep a single source of truth in state while still exposing the shapes the UI needs.\n\n## Common Mistakes\n\n### CRITICAL Mutating selected state outside reducers\n\nWrong:\n\n```ts\nconst post = selectPostById(store.getState(), 'p1')\n\nif (post) {\n  post.title = 'Changed in place'\n}\n```\n\nCorrect:\n\n```ts\nstore.dispatch(postUpdated({ id: 'p1', changes: { title: 'Changed in place' } }))\n```\n\nObjects read from the store are still store state; mutating them outside reducers breaks immutability and stale-render assumptions.\n\nSource: reduxjs/redux:docs/style-guide/style-guide.md\n\n### HIGH Using setter-style actions instead of event-style actions\n\nWrong:\n\n```ts\nconst nextPosts = [...selectPosts(store.getState()), { id: 'p2', title: 'Write docs' }]\nstore.dispatch(setPosts(nextPosts))\n```\n\nCorrect:\n\n```ts\nstore.dispatch(postAdded({ id: 'p2', title: 'Write docs' }))\n```\n\nActions should describe events, not ask reducers to blindly replace state with a precomputed value.\n\nSource: reduxjs/redux:docs/style-guide/style-guide.md\n\n### HIGH Combining store state before dispatch\n\nWrong:\n\n```ts\nconst currentPosts = selectPosts(store.getState())\nconst mergedPosts = [\n  ...currentPosts.filter(\n    (currentPost) =>\n      !incomingPosts.some((incomingPost) => incomingPost.id === currentPost.id),\n  ),\n  ...incomingPosts,\n]\n\nstore.dispatch(postsReplaced(mergedPosts))\n```\n\nCorrect:\n\n```ts\nstore.dispatch(postsReceived(incomingPosts))\n```\n\nIf the next state depends on current store state, the reducer should own that combination logic; only authoritative external snapshots should replace state wholesale.\n\nSource: maintainer interview\n\n### HIGH Ignoring current state in async reducers\n\nWrong:\n\n```ts\nbuilder.addCase(fetchPosts.fulfilled, (state, action) => {\n  state.status = 'succeeded'\n  state.items = action.payload\n})\n```\n\nCorrect:\n\n```ts\nbuilder.addCase(fetchPosts.fulfilled, (state, action) => {\n  if (state.status === 'pending') {\n    state.status = 'succeeded'\n    state.items = action.payload\n  }\n})\n```\n\nReducers that treat every lifecycle action as valid can move the slice into impossible states or let stale requests win.\n\nSource: reduxjs/redux:docs/tutorials/essentials/part-5-async-logic.md\n\n### MEDIUM Storing derived values in state\n\nWrong:\n\n```ts\nconst initialState = {\n  items: [] as Post[],\n  visiblePosts: [] as Post[],\n}\n```\n\nCorrect:\n\n```ts\nconst selectVisiblePosts = createSelector(\n  [selectPosts, selectFilter],\n  (posts, filter) =>\n    filter === 'all' ? posts : posts.filter((post) => post.published),\n)\n```\n\nDerived values drift out of sync quickly; keep the raw state and derive the view shape.\n\nSource: reduxjs/redux:docs/style-guide/style-guide.md\n"
  },
  {
    "path": "packages/toolkit/skills/evolve-and-diagnose-redux-apps/debug-redux-toolkit-apps/SKILL.md",
    "content": "---\nname: evolve-and-diagnose-redux-apps/debug-redux-toolkit-apps\ndescription: >\n  Use this when debugging duplicate requests, stale cache behavior, broad\n  subscriptions, selector churn, serializability warnings, or other Redux\n  Toolkit and RTK Query bugs. Covers a practical event -> reducer -> selector ->\n  render debugging loop plus RTK Query cache interpretation.\ntype: lifecycle\nlibrary: \"@reduxjs/toolkit\"\nlibrary_version: \"2.11.2\"\nrequires:\n  - build-modern-redux-apps/redux-dataflow\nsources:\n  - \"reduxjs/redux:docs/style-guide/style-guide.md\"\n  - \"reduxjs/redux:docs/tutorials/essentials/part-5-async-logic.md\"\n  - \"reduxjs/redux:docs/tutorials/essentials/part-8-rtk-query-advanced.md\"\n  - \"reduxjs/redux-toolkit:docs/usage/usage-guide.md\"\n---\n\n# Debug Redux Toolkit Apps\n\n## Setup\n\n```ts\nimport { configureStore, createAsyncThunk, createSlice } from '@reduxjs/toolkit'\n\ntype Post = { id: string; title: string }\n\nexport const fetchPosts = createAsyncThunk(\n  'posts/fetchPosts',\n  async () => {\n    const response = await fetch('/api/posts')\n    return (await response.json()) as Post[]\n  },\n  {\n    condition(_arg, { getState }) {\n      const state = getState() as RootState\n      return state.posts.status === 'idle'\n    },\n  },\n)\n\nconst postsSlice = createSlice({\n  name: 'posts',\n  initialState: {\n    items: [] as Post[],\n    status: 'idle' as 'idle' | 'pending' | 'succeeded' | 'failed',\n  },\n  reducers: {},\n  extraReducers: (builder) => {\n    builder\n      .addCase(fetchPosts.pending, (state) => {\n        state.status = 'pending'\n      })\n      .addCase(fetchPosts.fulfilled, (state, action) => {\n        state.status = 'succeeded'\n        state.items = action.payload\n      })\n  },\n})\n\nexport const store = configureStore({\n  reducer: {\n    posts: postsSlice.reducer,\n  },\n})\n\ntype RootState = ReturnType<typeof store.getState>\n```\n\n## Core Patterns\n\n### Debug in order: action -> reducer -> selector -> render\n\n```ts\nconst selectPosts = (state: RootState) => state.posts.items\nconst selectPostsStatus = (state: RootState) => state.posts.status\n\nstore.dispatch(fetchPosts())\n\nconsole.log(selectPostsStatus(store.getState()))\nconsole.log(selectPosts(store.getState()))\n```\n\nIf a component looks wrong, first verify the action fired, then the reducer state, then the selector result, then the render boundary.\n\n### Narrow subscriptions at the usage site\n\n```tsx\nimport { useAppSelector } from '../../app/hooks'\n\nexport function PostsList() {\n  const posts = useAppSelector((state) => state.posts.items)\n  const status = useAppSelector((state) => state.posts.status)\n\n  return (\n    <div>\n      <div>{status}</div>\n      <div>{posts.length}</div>\n    </div>\n  )\n}\n```\n\nReact-Redux behaves best when components select only the values they render and do it as close to usage as possible.\n\n### Interpret RTK Query invalidation correctly\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ntype Post = { id: string; title: string }\n\nconst api = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => 'posts',\n      providesTags: ['Post'],\n    }),\n    updatePost: build.mutation<Post, Pick<Post, 'id' | 'title'>>({\n      query: ({ id, title }) => ({\n        url: `posts/${id}`,\n        method: 'PATCH',\n        body: { title },\n      }),\n      invalidatesTags: ['Post'],\n    }),\n  }),\n})\n```\n\nIf invalidation did not visibly refetch, check whether anything was still subscribed to that cache entry.\n\n## Common Mistakes\n\n### HIGH Dispatching fetch thunks from effects without a thunk-level guard\n\nWrong:\n\n```tsx\nimport { useEffect } from 'react'\nimport { useAppDispatch, useAppSelector } from '../../app/hooks'\n\nfunction PostsPage() {\n  const dispatch = useAppDispatch()\n  const postStatus = useAppSelector((state) => state.posts.status)\n\n  useEffect(() => {\n    if (postStatus === 'idle') {\n      dispatch(fetchPosts())\n    }\n  }, [dispatch, postStatus])\n\n  return null\n}\n```\n\nCorrect:\n\n```ts\nexport const fetchPosts = createAsyncThunk(\n  'posts/fetchPosts',\n  async () => {\n    const response = await fetch('/api/posts')\n    return (await response.json()) as Post[]\n  },\n  {\n    condition(_arg, { getState }) {\n      const state = getState() as RootState\n      return state.posts.status === 'idle'\n    },\n  },\n)\n```\n\nReact StrictMode can run effects twice in development, so the guard belongs in the thunk as well as the component.\n\nSource: reduxjs/redux:docs/tutorials/essentials/part-5-async-logic.md\n\n### HIGH Ignoring serializable-state warnings\n\nWrong:\n\n```ts\nconst initialState = {\n  lastSeen: new Date(),\n  pendingIds: new Set<string>(),\n}\n```\n\nCorrect:\n\n```ts\nconst initialState = {\n  lastSeenIso: new Date().toISOString(),\n  pendingIds: [] as string[],\n}\n```\n\nNon-serializable values break DevTools, replay, persistence, and equality assumptions in subtle ways.\n\nSource: reduxjs/redux:docs/style-guide/style-guide.md\n\n### HIGH Selecting broad state in parents and threading props\n\nWrong:\n\n```tsx\nimport { useAppSelector } from '../../app/hooks'\n\nfunction PostsPage() {\n  const postsState = useAppSelector((state) => state.posts)\n  return <PostsList items={postsState.items} status={postsState.status} />\n}\n```\n\nCorrect:\n\n```tsx\nimport { useAppSelector } from '../../app/hooks'\n\nfunction PostsList() {\n  const items = useAppSelector((state) => state.posts.items)\n  const status = useAppSelector((state) => state.posts.status)\n  return (\n    <div>\n      <div>{status}</div>\n      <div>{items.length}</div>\n    </div>\n  )\n}\n```\n\nSelecting whole slices high in the tree widens the subscription surface and pushes rerenders through props.\n\nSource: reduxjs/redux:docs/style-guide/style-guide.md\n\n### MEDIUM Returning unstable objects from query selection logic\n\nWrong:\n\n```tsx\nimport { api } from '../../services/api'\n\nconst result = api.useGetPostsQuery(undefined, {\n  selectFromResult: ({ data = [] }) => ({\n    posts: [...data],\n  }),\n})\n```\n\nCorrect:\n\n```tsx\nimport { api } from '../../services/api'\n\nconst result = api.useGetPostsQuery(undefined, {\n  selectFromResult: ({ data = [] }) => ({\n    posts: data,\n  }),\n})\n```\n\nNew object and array references defeat memoization and make components rerender even when the underlying cached data did not change.\n\nSource: reduxjs/redux:docs/tutorials/essentials/part-8-rtk-query-advanced.md\n"
  },
  {
    "path": "packages/toolkit/skills/evolve-and-diagnose-redux-apps/migrate-to-modern-redux/SKILL.md",
    "content": "---\nname: evolve-and-diagnose-redux-apps/migrate-to-modern-redux\ndescription: >\n  Use this when moving a legacy Redux codebase to current RTK patterns. Covers\n  replacing createStore with configureStore, migrating touched reducers to\n  createSlice, codemod-assisted RTK 2 updates, and replacing server-data stacks\n  with RTK Query instead of writing new legacy Redux code.\ntype: lifecycle\nlibrary: \"@reduxjs/toolkit\"\nlibrary_version: \"2.11.2\"\nrequires:\n  - build-modern-redux-apps/modern-redux\nsources:\n  - \"reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx\"\n  - \"reduxjs/redux-toolkit:docs/usage/migrating-rtk-2.md\"\n  - \"reduxjs/redux-toolkit:packages/rtk-codemods/README.md\"\n  - \"reduxjs/redux:docs/style-guide/style-guide.md\"\n---\n\n# Migrate To Modern Redux\n\n## Setup\n\n```ts\n// before\nimport { applyMiddleware, combineReducers, createStore } from 'redux'\nimport thunk from 'redux-thunk'\n\nconst postsReducer = (state = [] as { id: string; title: string }[]) => state\nconst usersReducer = (state = [] as { id: string; name: string }[]) => state\n\nconst rootReducer = combineReducers({\n  posts: postsReducer,\n  users: usersReducer,\n})\n\nexport const legacyStore = createStore(rootReducer, applyMiddleware(thunk))\n\n// after\nimport { configureStore } from '@reduxjs/toolkit'\n\nconst postsReducer = (state = [] as { id: string; title: string }[]) => state\nconst usersReducer = (state = [] as { id: string; name: string }[]) => state\n\nexport const store = configureStore({\n  reducer: {\n    posts: postsReducer,\n    users: usersReducer,\n  },\n})\n```\n\n## Core Patterns\n\n### Replace the store setup first\n\n```ts\nimport { configureStore } from '@reduxjs/toolkit'\n\nconst postsReducer = (state = [] as { id: string; title: string }[]) => state\nconst usersReducer = (state = [] as { id: string; name: string }[]) => state\n\nexport const store = configureStore({\n  reducer: {\n    posts: postsReducer,\n    users: usersReducer,\n  },\n})\n\nexport type RootState = ReturnType<typeof store.getState>\nexport type AppDispatch = typeof store.dispatch\n```\n\nThis is the one migration step that can happen immediately while old reducers continue to work.\n\n### Migrate reducers as you touch them\n\n```ts\nimport { createSlice } from '@reduxjs/toolkit'\n\ntype TodosState = {\n  items: { id: string; text: string; completed: boolean }[]\n}\n\nconst initialState: TodosState = {\n  items: [],\n}\n\nexport const todosSlice = createSlice({\n  name: 'todos',\n  initialState,\n  reducers: {\n    todoAdded(state, action: { payload: { id: string; text: string } }) {\n      state.items.push({ ...action.payload, completed: false })\n    },\n    todoToggled(state, action: { payload: { id: string } }) {\n      const todo = state.items.find((item) => item.id === action.payload.id)\n      if (todo) {\n        todo.completed = !todo.completed\n      }\n    },\n  },\n})\n```\n\nOnce a reducer needs editing, migrate that reducer instead of adding more legacy code to it.\n\n### Use codemods for mechanical updates\n\n```bash\nnpx @reduxjs/rtk-codemods createSliceBuilder src/features/posts/postsSlice.ts\nnpx @reduxjs/rtk-codemods createReducerBuilder src/features/posts/postsReducer.ts\n```\n\nUse codemods for repetitive RTK API migrations, then review the result and finish the semantic cleanup by hand.\n\n### Replace legacy server-data stacks with RTK Query\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ntype Todo = { id: string; text: string }\n\nexport const api = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  endpoints: (build) => ({\n    getTodos: build.query<Todo[], void>({\n      query: () => 'todos',\n    }),\n  }),\n})\n```\n\nWhen the old code is just request status plus fetched data, migrate toward RTK Query instead of carrying the thunk stack forward forever.\n\n## Common Mistakes\n\n### HIGH Attempting a big-bang rewrite\n\nWrong:\n\n```ts\n// Replace every reducer, every connected component, and every async flow\n// in one branch before shipping anything.\n```\n\nCorrect:\n\n```ts\n// 1) Switch createStore to configureStore\n// 2) Migrate one touched reducer to createSlice\n// 3) Convert touched connected components to hooks\n// 4) Repeat without introducing new legacy Redux code\n```\n\nModern Redux migration is incremental, but once the store is modernized new work should stop adding legacy patterns.\n\nSource: reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx\n\n### CRITICAL Carrying removed RTK 2 config forms forward\n\nWrong:\n\n```ts\nconfigureStore({\n  reducer,\n  middleware: [logger],\n})\n```\n\nCorrect:\n\n```ts\nconfigureStore({\n  reducer,\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(logger),\n})\n```\n\nRTK 2 removed array middleware configuration and other older builder forms that agents trained on RTK 1.x still emit.\n\nSource: reduxjs/redux-toolkit:docs/usage/migrating-rtk-2.md\n\n### HIGH Preserving hand-written fetch state by default\n\nWrong:\n\n```ts\nimport { createAsyncThunk } from '@reduxjs/toolkit'\n\ntype Todo = { id: string; text: string }\n\nconst initialState = {\n  items: [] as Todo[],\n  status: 'idle' as 'idle' | 'pending' | 'failed',\n}\n\nexport const fetchTodos = createAsyncThunk('todos/fetch', async () => {\n  const response = await fetch('/api/todos')\n  return (await response.json()) as Todo[]\n})\n```\n\nCorrect:\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ntype Todo = { id: string; text: string }\n\nconst api = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  endpoints: (build) => ({\n    getTodos: build.query<Todo[], void>({\n      query: () => 'todos',\n    }),\n  }),\n})\n```\n\nIf the feature is really server cache, keep the migration moving toward RTK Query instead of rebuilding the old loading-flag architecture in new APIs.\n\nSource: reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx\n"
  },
  {
    "path": "packages/toolkit/skills/manage-server-data/adopt-rtk-query/SKILL.md",
    "content": "---\nname: manage-server-data/adopt-rtk-query\ndescription: >\n  Use this when adding RTK Query as the default server-data and document-cache\n  layer. Covers createApi, store integration, hooks, invalidation behavior,\n  optimistic updates, and deciding when RTK Query is the right cache model.\ntype: lifecycle\nlibrary: \"@reduxjs/toolkit\"\nlibrary_version: \"2.11.2\"\nrequires:\n  - build-modern-redux-apps/modern-redux\nsources:\n  - \"reduxjs/redux-toolkit:docs/rtk-query/api/createApi.mdx\"\n  - \"reduxjs/redux-toolkit:docs/rtk-query/usage/automated-refetching.mdx\"\n  - \"reduxjs/redux-toolkit:docs/rtk-query/usage/manual-cache-updates.mdx\"\n  - \"reduxjs/redux-toolkit:docs/rtk-query/usage/persistence-and-rehydration.mdx\"\n  - \"reduxjs/redux-toolkit:docs/tutorials/rtk-query.mdx\"\n  - \"reduxjs/redux:docs/style-guide/style-guide.md\"\n---\n\n# Adopt RTK Query\n\n## Setup\n\n```tsx\n// file: src/services/api.ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ntype Post = { id: string; title: string }\n\nexport const api = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => 'posts',\n      providesTags: (result) =>\n        result\n          ? [...result.map(({ id }) => ({ type: 'Post' as const, id })), 'Post']\n          : ['Post'],\n    }),\n    addPost: build.mutation<Post, Pick<Post, 'title'>>({\n      query: (body) => ({\n        url: 'posts',\n        method: 'POST',\n        body,\n      }),\n      invalidatesTags: ['Post'],\n    }),\n  }),\n})\n\nexport const { useGetPostsQuery, useAddPostMutation } = api\n\n// file: src/app/store.ts\nimport { configureStore } from '@reduxjs/toolkit'\nimport { api } from '../services/api'\n\nexport const store = configureStore({\n  reducer: {\n    [api.reducerPath]: api.reducer,\n  },\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(api.middleware),\n})\n\n// file: src/App.tsx\nimport { Provider } from 'react-redux'\nimport { store } from './app/store'\nimport { useAddPostMutation, useGetPostsQuery } from './services/api'\n\nfunction Posts() {\n  const { data: posts = [] } = useGetPostsQuery()\n  const [addPost] = useAddPostMutation()\n\n  return (\n    <div>\n      <button onClick={() => addPost({ title: 'Write docs' })}>Add</button>\n      <ul>\n        {posts.map((post) => (\n          <li key={post.id}>{post.title}</li>\n        ))}\n      </ul>\n    </div>\n  )\n}\n\nexport function App() {\n  return (\n    <Provider store={store}>\n      <Posts />\n    </Provider>\n  )\n}\n```\n\n## Core Patterns\n\n### Keep one API slice per base URL and extend it\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nexport const api = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  endpoints: () => ({}),\n})\n\nexport const postsApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getPosts: build.query<{ id: string; title: string }[], void>({\n      query: () => 'posts',\n    }),\n  }),\n})\n```\n\nSplit files with `injectEndpoints`, not by making multiple `createApi` roots for the same backend.\n\n### Use tags for cache invalidation\n\n```ts\ntype Post = { id: string; title: string }\n\nexport const api = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => 'posts',\n      providesTags: (result) =>\n        result\n          ? [...result.map(({ id }) => ({ type: 'Post' as const, id })), 'Post']\n          : ['Post'],\n    }),\n    updatePost: build.mutation<Post, Pick<Post, 'id' | 'title'>>({\n      query: ({ id, title }) => ({\n        url: `posts/${id}`,\n        method: 'PATCH',\n        body: { title },\n      }),\n      invalidatesTags: (_result, _error, { id }) => [{ type: 'Post', id }],\n    }),\n  }),\n})\n```\n\nTreat tags as the normal invalidation path before reaching for manual cache patching.\n\n### Do optimistic updates in endpoint lifecycles\n\n```ts\ntype Post = { id: string; title: string }\n\nexport const api = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => 'posts',\n      providesTags: ['Post'],\n    }),\n    updatePostTitle: build.mutation<Post, Pick<Post, 'id' | 'title'>>({\n      query: ({ id, title }) => ({\n        url: `posts/${id}`,\n        method: 'PATCH',\n        body: { title },\n      }),\n      async onQueryStarted({ id, title }, { dispatch, queryFulfilled }) {\n        const patch = dispatch(\n          api.util.updateQueryData('getPosts', undefined, (draft) => {\n            const post = draft.find((item) => item.id === id)\n            if (post) {\n              post.title = title\n            }\n          }),\n        )\n\n        try {\n          await queryFulfilled\n        } catch {\n          patch.undo()\n        }\n      },\n    }),\n  }),\n})\n```\n\nKeep optimistic and pessimistic cache updates inside endpoint lifecycle handlers so they stay coupled to the request.\n\n## Common Mistakes\n\n### CRITICAL Creating multiple API slices for one backend\n\nWrong:\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ntype User = { id: string; name: string }\n\nconst baseQuery = fetchBaseQuery({ baseUrl: '/api/' })\n\nconst postsApi = createApi({\n  reducerPath: 'api',\n  baseQuery,\n  endpoints: () => ({}),\n})\n\nconst usersApi = createApi({\n  reducerPath: 'api',\n  baseQuery,\n  endpoints: () => ({}),\n})\n```\n\nCorrect:\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ntype User = { id: string; name: string }\n\nconst baseQuery = fetchBaseQuery({ baseUrl: '/api/' })\n\nconst api = createApi({\n  reducerPath: 'api',\n  baseQuery,\n  endpoints: () => ({}),\n})\n\nconst usersApi = api.injectEndpoints({\n  endpoints: (build) => ({\n    getUsers: build.query<User[], void>({ query: () => 'users' }),\n  }),\n})\n```\n\nOne API slice per base URL preserves invalidation behavior and avoids duplicated middleware work.\n\nSource: reduxjs/redux-toolkit:docs/rtk-query/api/createApi.mdx\n\n### HIGH Forgetting `api.reducer` or `api.middleware`\n\nWrong:\n\n```ts\nimport { configureStore } from '@reduxjs/toolkit'\n\nconst store = configureStore({\n  reducer: {},\n})\n```\n\nCorrect:\n\n```ts\nimport { configureStore } from '@reduxjs/toolkit'\n\nconst store = configureStore({\n  reducer: {\n    [api.reducerPath]: api.reducer,\n  },\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(api.middleware),\n})\n```\n\nRTK Query hooks need both the reducer and middleware to manage cache state and request lifecycles.\n\nSource: reduxjs/redux-toolkit:docs/tutorials/rtk-query.mdx\n\n### MEDIUM Persisting browser API cache by default\n\nWrong:\n\n```ts\nconst storage = window.localStorage\n\nconst persistConfig = {\n  key: 'root',\n  storage,\n}\n```\n\nCorrect:\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nconst api = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api/' }),\n  endpoints: () => ({}),\n})\n```\n\nPersisting RTK Query cache in browsers often keeps stale data around longer than users expect; treat persistence as a special case, not the default.\n\nSource: reduxjs/redux-toolkit:docs/rtk-query/usage/persistence-and-rehydration.mdx\n\n### HIGH Patching cache from components\n\nWrong:\n\n```tsx\nimport { useEffect } from 'react'\nimport { useAppDispatch } from '../../app/hooks'\n\nconst dispatch = useAppDispatch()\n\nuseEffect(() => {\n  dispatch(api.util.updateQueryData('getPosts', undefined, (draft) => {\n    draft.push({ id: 'p3', title: 'Patched from component' })\n  }))\n}, [dispatch])\n```\n\nCorrect:\n\n```ts\nupdatePostTitle: build.mutation<Post, Pick<Post, 'id' | 'title'>>({\n  query: ({ id, title }) => ({\n    url: `posts/${id}`,\n    method: 'PATCH',\n    body: { title },\n  }),\n  async onQueryStarted({ id, title }, { dispatch, queryFulfilled }) {\n    const patch = dispatch(\n      api.util.updateQueryData('getPosts', undefined, (draft) => {\n        const post = draft.find((item) => item.id === id)\n        if (post) {\n          post.title = title\n        }\n      }),\n    )\n\n    try {\n      await queryFulfilled\n    } catch {\n      patch.undo()\n    }\n  },\n})\n```\n\nComponent-level cache patches drift away from the mutation lifecycle that should own them.\n\nSource: reduxjs/redux-toolkit:docs/rtk-query/usage/manual-cache-updates.mdx\n\n### HIGH Expecting invalidation to refetch unsubscribed queries\n\nWrong:\n\n```ts\nimport { api } from './api'\nimport { store } from './store'\n\nconst subscription = store.dispatch(api.endpoints.getPosts.initiate())\nsubscription.unsubscribe()\nstore.dispatch(api.util.invalidateTags(['Post']))\n```\n\nCorrect:\n\n```ts\nimport { api } from './api'\nimport { store } from './store'\n\nstore.dispatch(api.endpoints.getPosts.initiate())\nstore.dispatch(api.util.invalidateTags(['Post']))\n```\n\nInvalidation only refetches actively subscribed queries; if no component is using that cache entry, RTK Query drops it and fetches again next time it is needed.\n\nSource: reduxjs/redux-toolkit:docs/rtk-query/usage/automated-refetching.mdx\n\n## References\n\n- [Endpoint lifecycle details and cache tradeoffs](references/endpoint-lifecycle.md)\n"
  },
  {
    "path": "packages/toolkit/skills/manage-server-data/adopt-rtk-query/references/endpoint-lifecycle.md",
    "content": "# Endpoint Lifecycle\n\n## Invalidation rule\n\nWhen a mutation invalidates tags:\n\n- active subscribers refetch\n- inactive cache entries are removed\n- removed entries fetch again only when something subscribes later\n\nThat behavior is deliberate; invalidation is not a background \"refresh everything\" switch.\n\n## Document cache tradeoff\n\nRTK Query is a document cache, not a normalized entity graph cache.\n\nUse RTK Query by default when:\n\n- the data comes from request/response APIs\n- document caching is acceptable\n- tag invalidation and endpoint lifecycles solve the problem\n\nReach for a different tool when:\n\n- the real requirement is a normalized graph cache\n- the stack already has a domain-specific normalized client that fits better\n\nIf normalized caching is mandatory and no better library is already in the stack, a slice plus thunk flow may be the fallback.\n\n## Useful endpoint options\n\n- `providesTags`: tell RTK Query what cache entries this query represents\n- `invalidatesTags`: tell RTK Query what a mutation dirties\n- `onQueryStarted`: optimistic and pessimistic updates tied to a request\n- `onCacheEntryAdded`: long-lived subscriptions such as streaming data\n- `keepUnusedDataFor`: how long inactive cache entries stay around\n"
  },
  {
    "path": "packages/toolkit/skills/model-redux-state/build-slices-and-selectors/SKILL.md",
    "content": "---\nname: model-redux-state/build-slices-and-selectors\ndescription: >\n  Use this when authoring or refactoring slices with createSlice, selectors,\n  create.asyncThunk, entity adapters, or lazy reducer injection. Covers\n  Immer-backed mutation syntax, slice selectors, getSelectors, injectInto,\n  withLazyLoadedSlices, and current RTK 2 slice patterns.\ntype: core\nlibrary: \"@reduxjs/toolkit\"\nlibrary_version: \"2.11.2\"\nrequires:\n  - model-redux-state/design-state-ownership\nsources:\n  - \"reduxjs/redux-toolkit:docs/api/createSlice.mdx\"\n  - \"reduxjs/redux-toolkit:docs/api/combineSlices.mdx\"\n  - \"reduxjs/redux-toolkit:docs/api/createEntityAdapter.mdx\"\n  - \"reduxjs/redux-toolkit:docs/usage/immer-reducers.md\"\n  - \"reduxjs/redux-toolkit:docs/usage/migrating-rtk-2.md\"\n  - \"reduxjs/redux:docs/style-guide/style-guide.md\"\n---\n\n# Build Slices And Selectors\n\n## Setup\n\n```ts\n// file: src/app/createAppSlice.ts\nimport { asyncThunkCreator, buildCreateSlice } from '@reduxjs/toolkit'\n\nexport const createAppSlice = buildCreateSlice({\n  creators: { asyncThunk: asyncThunkCreator },\n})\n\n// file: src/features/posts/postsSlice.ts\nimport { createSelector } from '@reduxjs/toolkit'\nimport { createAppSlice } from '../../app/createAppSlice'\n\ntype PostsState = {\n  items: { id: string; title: string; published: boolean }[]\n  status: 'idle' | 'pending' | 'succeeded' | 'failed'\n}\n\nconst initialState: PostsState = {\n  items: [],\n  status: 'idle',\n}\n\nexport const postsSlice = createAppSlice({\n  name: 'posts',\n  initialState,\n  reducers: (create) => ({\n    postAdded: create.reducer<{ id: string; title: string }>((state, action) => {\n      state.items.push({ ...action.payload, published: false })\n    }),\n    fetchPosts: create.asyncThunk(\n      async () => {\n        const response = await fetch('/api/posts')\n        return (await response.json()) as { id: string; title: string; published: boolean }[]\n      },\n      {\n        pending: (state) => {\n          state.status = 'pending'\n        },\n        fulfilled: (state, action) => {\n          state.status = 'succeeded'\n          state.items = action.payload\n        },\n        rejected: (state) => {\n          state.status = 'failed'\n        },\n      },\n    ),\n  }),\n  selectors: {\n    selectPosts: (state) => state.items,\n    selectPublishedPosts: createSelector(\n      [(state: PostsState) => state.items],\n      (items) => items.filter((post) => post.published),\n    ),\n  },\n})\n\nexport const { postAdded, fetchPosts } = postsSlice.actions\nexport const { selectPosts, selectPublishedPosts } = postsSlice.selectors\n```\n\n## Core Patterns\n\n### Use mutating logic inside slice reducers\n\n```ts\nimport { createSlice } from '@reduxjs/toolkit'\n\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [] as { id: string; text: string; done: boolean }[],\n  reducers: {\n    todoAdded(state, action: { payload: { id: string; text: string } }) {\n      state.push({ ...action.payload, done: false })\n    },\n    todoToggled(state, action: { payload: { id: string } }) {\n      const todo = state.find((item) => item.id === action.payload.id)\n      if (todo) {\n        todo.done = !todo.done\n      }\n    },\n  },\n})\n```\n\nImmer is the default inside `createSlice`; write the reducer logic directly instead of copying arrays and objects by hand.\n\n### Define selectors in the slice when they belong to the slice\n\n```ts\nimport { createSlice } from '@reduxjs/toolkit'\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 },\n  reducers: {\n    increment(state) {\n      state.value += 1\n    },\n  },\n  selectors: {\n    selectValue: (state) => state.value,\n    selectIsPositive: (state) => state.value > 0,\n  },\n})\n\nconst { selectValue, selectIsPositive } = counterSlice.selectors\n```\n\nSlice selectors keep state-location knowledge next to the slice.\n\n### Use `create.asyncThunk` when the async lifecycle belongs to the slice\n\n```ts\nimport { asyncThunkCreator, buildCreateSlice } from '@reduxjs/toolkit'\n\nconst createAppSlice = buildCreateSlice({\n  creators: { asyncThunk: asyncThunkCreator },\n})\n\nconst usersSlice = createAppSlice({\n  name: 'users',\n  initialState: { items: [] as { id: string; name: string }[], status: 'idle' as 'idle' | 'pending' | 'failed' },\n  reducers: (create) => ({\n    fetchUsers: create.asyncThunk(\n      async () => {\n        const response = await fetch('/api/users')\n        return (await response.json()) as { id: string; name: string }[]\n      },\n      {\n        pending: (state) => {\n          state.status = 'pending'\n        },\n        fulfilled: (state, action) => {\n          state.status = 'idle'\n          state.items = action.payload\n        },\n        rejected: (state) => {\n          state.status = 'failed'\n        },\n      },\n    ),\n  }),\n})\n```\n\nUse this when the async lifecycle handlers naturally live with the slice; otherwise regular `createAsyncThunk` is still fine.\n\n### Use entity adapters and lazy injection for scalable slices\n\n```ts\nimport {\n  combineSlices,\n  createEntityAdapter,\n  createSlice,\n} from '@reduxjs/toolkit'\n\ntype Book = { bookId: string; title: string }\n\nconst booksAdapter = createEntityAdapter<Book>({\n  selectId: (book) => book.bookId,\n})\n\nconst booksSlice = createSlice({\n  name: 'books',\n  initialState: booksAdapter.getInitialState(),\n  reducers: {\n    booksReceived: booksAdapter.setAll,\n  },\n})\n\nexport interface LazyLoadedSlices {}\n\nexport const rootReducer =\n  combineSlices().withLazyLoadedSlices<LazyLoadedSlices>()\n\ndeclare module './rootReducer' {\n  export interface LazyLoadedSlices {}\n}\n\nconst injectedBooksSlice = booksSlice.injectInto(rootReducer)\n\nconst selectors = booksAdapter.getSelectors(\n  (state: ReturnType<typeof rootReducer.selector.original>) =>\n    injectedBooksSlice.selectSlice(state),\n)\n```\n\nEntity adapters standardize normalized collections, and `injectInto` lets a slice stay aware of its injected location.\n\n## Common Mistakes\n\n### CRITICAL Using mutating logic outside slice reducers\n\nWrong:\n\n```ts\ntype Todo = { id: string; text: string }\n\nexport function addTodo(todos: Todo[], todo: Todo) {\n  todos.push(todo)\n  return todos\n}\n```\n\nCorrect:\n\n```ts\ntype Todo = { id: string; text: string }\n\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [] as Todo[],\n  reducers: {\n    todoAdded(state, action: { payload: Todo }) {\n      state.push(action.payload)\n    },\n  },\n})\n```\n\nMutation syntax is only safe inside Immer-backed reducer contexts such as `createSlice` and `createReducer`.\n\nSource: reduxjs/redux-toolkit:docs/usage/immer-reducers.md\n\n### HIGH Writing hand-written switch reducers as the default\n\nWrong:\n\n```ts\nexport default function todosReducer(state = initialState, action: { type: string; payload?: Todo }) {\n  switch (action.type) {\n    case 'todos/todoAdded':\n      return state.concat(action.payload as Todo)\n    default:\n      return state\n  }\n}\n```\n\nCorrect:\n\n```ts\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState,\n  reducers: {\n    todoAdded(state, action: { payload: Todo }) {\n      state.push(action.payload)\n    },\n  },\n})\n```\n\nHand-written reducers are an escape hatch for proven bottlenecks, not the normal thing an agent should generate in RTK code.\n\nSource: reduxjs/redux-toolkit:docs/usage/migrating-to-modern-redux.mdx\n\n### HIGH Writing RTK 1.x object syntax for `extraReducers`\n\nWrong:\n\n```ts\nimport { createAsyncThunk, createSlice } from '@reduxjs/toolkit'\n\nconst initialState = { items: [] as { id: string; title: string }[] }\n\nconst fetchPosts = createAsyncThunk('posts/fetch', async () => {\n  const response = await fetch('/api/posts')\n  return (await response.json()) as { id: string; title: string }[]\n})\n\nconst postsSlice = createSlice({\n  name: 'posts',\n  initialState,\n  reducers: {},\n  extraReducers: {\n    [fetchPosts.fulfilled.type]: (state, action) => {\n      state.items = action.payload\n    },\n  },\n})\n```\n\nCorrect:\n\n```ts\nimport { createAsyncThunk, createSlice } from '@reduxjs/toolkit'\n\nconst initialState = { items: [] as { id: string; title: string }[] }\n\nconst fetchPosts = createAsyncThunk('posts/fetch', async () => {\n  const response = await fetch('/api/posts')\n  return (await response.json()) as { id: string; title: string }[]\n})\n\nconst postsSlice = createSlice({\n  name: 'posts',\n  initialState,\n  reducers: {},\n  extraReducers: (builder) => {\n    builder.addCase(fetchPosts.fulfilled, (state, action) => {\n      state.items = action.payload\n    })\n  },\n})\n```\n\nRTK 2 removed the object form; agents trained on RTK 1.x still generate it.\n\nSource: reduxjs/redux-toolkit:docs/usage/migrating-rtk-2.md\n\n### HIGH Assuming `entity.id` exists for every collection\n\nWrong:\n\n```ts\ntype Book = { bookId: string; title: string }\n\nconst booksAdapter = createEntityAdapter<Book>()\n```\n\nCorrect:\n\n```ts\ntype Book = { bookId: string; title: string }\n\nconst booksAdapter = createEntityAdapter<Book>({\n  selectId: (book) => book.bookId,\n})\n```\n\nAdapters default to `entity.id`; collections keyed by another field must provide `selectId`.\n\nSource: reduxjs/redux-toolkit:docs/api/createEntityAdapter.mdx\n\n## References\n\n- [Slice selectors, async creators, and lazy injection details](references/slice-patterns.md)\n"
  },
  {
    "path": "packages/toolkit/skills/model-redux-state/build-slices-and-selectors/references/slice-patterns.md",
    "content": "# Slice Patterns\n\n## `getSelectors` for alternate mounting points\n\n```ts\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 },\n  reducers: {},\n  selectors: {\n    selectValue: (state) => state.value,\n  },\n})\n\nexport const { selectValue } = counterSlice.getSelectors(\n  (state: { customCounter: { value: number } }) => state.customCounter,\n)\n```\n\nUse `getSelectors` when the slice is not mounted at its default `reducerPath`.\n\n## `withLazyLoadedSlices` and `injectInto`\n\n```ts\nimport { combineSlices, createSlice, type WithSlice } from '@reduxjs/toolkit'\n\nconst staticSlice = createSlice({\n  name: 'static',\n  initialState: { ready: true },\n  reducers: {},\n})\n\nexport interface LazyLoadedSlices {}\n\nexport const rootReducer =\n  combineSlices(staticSlice).withLazyLoadedSlices<LazyLoadedSlices>()\n\nconst lazySlice = createSlice({\n  name: 'lazy',\n  initialState: { value: 0 },\n  reducers: {\n    increment(state) {\n      state.value += 1\n    },\n  },\n})\n\ndeclare module '../rootReducer' {\n  export interface LazyLoadedSlices extends WithSlice<typeof lazySlice> {}\n}\n\nexport const injectedLazySlice = lazySlice.injectInto(rootReducer)\n```\n\nThis keeps RootState types aware of reducers that will be injected later.\n\n## Selector caveat\n\nIf a selector depends on caller-specific arguments and must be memoized per caller, prefer a selector factory outside `createSlice.selectors`. `createSlice.selectors` gives you one selector instance, not a selector factory.\n"
  },
  {
    "path": "packages/toolkit/skills/model-redux-state/design-state-ownership/SKILL.md",
    "content": "---\nname: model-redux-state/design-state-ownership\ndescription: >\n  Use this when deciding whether data belongs in Redux, component state, router\n  state, or another external source. Covers state ownership, authority\n  boundaries, slice sizing, and when to move or split data as the app evolves.\ntype: core\nlibrary: \"@reduxjs/toolkit\"\nlibrary_version: \"2.11.2\"\nsources:\n  - \"reduxjs/redux:docs/style-guide/style-guide.md\"\n  - \"reduxjs/redux:docs/tutorials/essentials/part-2-app-structure.md\"\n  - \"reduxjs/redux:docs/tutorials/essentials/part-4-using-data.md\"\n---\n\n# Design State Ownership\n\n## Setup\n\n```tsx\nimport { useState } from 'react'\nimport { createSlice } from '@reduxjs/toolkit'\nimport { useAppDispatch } from '../../app/hooks'\n\nconst postsSlice = createSlice({\n  name: 'posts',\n  initialState: [] as { id: string; title: string; content: string }[],\n  reducers: {\n    postAdded(\n      state,\n      action: { payload: { id: string; title: string; content: string } },\n    ) {\n      state.push(action.payload)\n    },\n  },\n})\n\nconst { postAdded } = postsSlice.actions\n\nexport function AddPostForm() {\n  const [title, setTitle] = useState('')\n  const [content, setContent] = useState('')\n  const dispatch = useAppDispatch()\n\n  return (\n    <form\n      onSubmit={(event) => {\n        event.preventDefault()\n        dispatch(postAdded({ id: 'p1', title, content }))\n      }}\n    >\n      <input value={title} onChange={(event) => setTitle(event.target.value)} />\n      <textarea\n        value={content}\n        onChange={(event) => setContent(event.target.value)}\n      />\n      <button type=\"submit\">Save</button>\n    </form>\n  )\n}\n```\n\n## Core Patterns\n\n### Keep editable form state local until the user commits it\n\n```tsx\nimport { useState } from 'react'\nimport { useAppDispatch } from '../../app/hooks'\nimport { profileSaved } from './profileSlice'\n\nexport function ProfileForm() {\n  const [displayName, setDisplayName] = useState('Lenz')\n  const dispatch = useAppDispatch()\n\n  return (\n    <form\n      onSubmit={(event) => {\n        event.preventDefault()\n        dispatch(profileSaved({ displayName }))\n      }}\n    >\n      <input\n        value={displayName}\n        onChange={(event) => setDisplayName(event.target.value)}\n      />\n      <button type=\"submit\">Save</button>\n    </form>\n  )\n}\n```\n\nPrefer Redux for shared, durable app state, not every keystroke.\n\n### Keep URL state with the router and combine it at the edge\n\n```tsx\nimport { createSelector } from '@reduxjs/toolkit'\nimport { useSearchParams } from 'react-router-dom'\nimport { useAppSelector } from '../../app/hooks'\n\ntype RootState = {\n  posts: {\n    items: { id: string; title: string; published: boolean }[]\n  }\n}\n\nconst selectPosts = (state: RootState) => state.posts.items\n\nconst selectVisiblePosts = createSelector(\n  [selectPosts, (_state: RootState, filter: string) => filter],\n  (posts, filter) =>\n    filter === 'published'\n      ? posts.filter((post) => post.published)\n      : posts,\n)\n\nexport function PostsList() {\n  const [searchParams] = useSearchParams()\n  const filter = searchParams.get('filter') ?? 'all'\n  const posts = useAppSelector((state) => selectVisiblePosts(state, filter))\n\n  return <div>{posts.length}</div>\n}\n```\n\nIf the router already owns a piece of state, pass it into selectors or combine it in the component instead of syncing it into Redux.\n\n### Re-size slices when access patterns change\n\n```ts\nimport { combineReducers, createSlice } from '@reduxjs/toolkit'\n\nconst authSlice = createSlice({\n  name: 'auth',\n  initialState: { userId: null as string | null },\n  reducers: {},\n})\n\nconst postsSlice = createSlice({\n  name: 'posts',\n  initialState: { items: [] as { id: string; title: string }[] },\n  reducers: {},\n})\n\nexport const rootReducer = combineReducers({\n  auth: authSlice.reducer,\n  posts: postsSlice.reducer,\n})\n```\n\nRevisit slice size over time; unrelated data should split apart, and data constantly stitched together in every component may belong closer together.\n\n## Common Mistakes\n\n### MEDIUM Putting form editing state in Redux\n\nWrong:\n\n```tsx\nimport { useAppSelector } from '../../app/hooks'\n\nconst selectDraftTitle = (state: { draft: { title: string } }) => state.draft.title\n\nconst title = useAppSelector(selectDraftTitle)\n```\n\nCorrect:\n\n```tsx\nconst [title, setTitle] = useState('')\n\n<input value={title} onChange={(event) => setTitle(event.target.value)} />\n```\n\nPer-keystroke dispatching adds global complexity for data that usually lives in one component tree.\n\nSource: reduxjs/redux:docs/style-guide/style-guide.md\n\n### HIGH Synchronizing router or URL state into Redux\n\nWrong:\n\n```tsx\nimport { useEffect } from 'react'\nimport { useSearchParams } from 'react-router-dom'\nimport { useAppDispatch } from '../../app/hooks'\n\nfunction PostsPage() {\n  const [searchParams] = useSearchParams()\n  const dispatch = useAppDispatch()\n\nuseEffect(() => {\n  dispatch(filterChanged(searchParams.get('filter') ?? 'all'))\n}, [dispatch, searchParams])\n\n  return null\n}\n```\n\nCorrect:\n\n```tsx\nconst filter = searchParams.get('filter') ?? 'all'\nconst posts = useAppSelector((state) => selectVisiblePosts(state, filter))\n```\n\nURL state already has an authoritative owner; duplicating it into Redux creates two sources of truth.\n\nSource: maintainer interview\n\n### HIGH Naming state after components\n\nWrong:\n\n```ts\nimport { combineReducers } from '@reduxjs/toolkit'\n\nconst loginReducer = (state = { open: false }) => state\nconst postsReducer = (state = [] as { id: string; title: string }[]) => state\n\nconst rootReducer = combineReducers({\n  loginScreen: loginReducer,\n  postsList: postsReducer,\n})\n```\n\nCorrect:\n\n```ts\nimport { combineReducers } from '@reduxjs/toolkit'\n\nconst authReducer = (state = { userId: null as string | null }) => state\nconst postsReducer = (state = [] as { id: string; title: string }[]) => state\n\nconst rootReducer = combineReducers({\n  auth: authReducer,\n  posts: postsReducer,\n})\n```\n\nStore keys should describe data or domain concepts, not the current component tree.\n\nSource: reduxjs/redux:docs/style-guide/style-guide.md\n\n### MEDIUM Letting slice boundaries fossilize\n\nWrong:\n\n```ts\nimport { createSlice } from '@reduxjs/toolkit'\n\ntype Post = { id: string; title: string }\ntype AppNotification = { id: string; message: string }\n\nconst appSlice = createSlice({\n  name: 'app',\n  initialState: {\n    auth: { userId: null as string | null },\n    posts: [] as Post[],\n    notifications: [] as AppNotification[],\n  },\n  reducers: {},\n})\n```\n\nCorrect:\n\n```ts\nimport { createSlice } from '@reduxjs/toolkit'\n\ntype Post = { id: string; title: string }\n\nconst authSlice = createSlice({\n  name: 'auth',\n  initialState: { userId: null as string | null },\n  reducers: {},\n})\n\nconst postsSlice = createSlice({\n  name: 'posts',\n  initialState: [] as Post[],\n  reducers: {},\n})\n```\n\nWhen unrelated data is welded together, every change point gets noisier; split or merge slices as actual access patterns demand.\n\nSource: maintainer interview\n\n### HIGH Blindly spreading payloads into state\n\nWrong:\n\n```ts\nconst state = { id: '1', name: 'Lenz' }\nconst action = { payload: { id: '2', name: 'Mark', ignored: true } }\n\nuserLoggedIn(state, action) {\n  return { ...state, ...action.payload }\n}\n```\n\nCorrect:\n\n```ts\nconst state = { id: '1', name: 'Lenz' }\nconst action = { payload: { id: '2', name: 'Mark', ignored: true } }\n\nuserLoggedIn(state, action) {\n  state.id = action.payload.id\n  state.name = action.payload.name\n}\n```\n\nReducers should own the slice shape instead of treating payloads as trusted state patches.\n\nSource: reduxjs/redux:docs/style-guide/style-guide.md\n\n## References\n\n- [State ownership heuristics](references/state-ownership.md)\n"
  },
  {
    "path": "packages/toolkit/skills/model-redux-state/design-state-ownership/references/state-ownership.md",
    "content": "# State Ownership Heuristics\n\n## Choose the owner, then the tool\n\n| Kind of state | Default owner | Typical tool |\n| --- | --- | --- |\n| Editable form fields | Component | `useState` |\n| Shared mutable app data | Redux | Slice state |\n| Server cache | RTK Query | `createApi` |\n| URL, pathname, search params | Router | Router APIs plus selector inputs |\n| Browser-only authority like `localStorage` | External source | Read at boundaries, then dispatch events |\n\n## Good reasons to move data into Redux\n\n- Multiple distant parts of the UI need the same mutable data.\n- You need time-travel debugging or a stable action history.\n- The reducer should own transitions because they mix old store state with new inputs.\n\n## Reasons to keep data out of Redux\n\n- Another system already owns it, such as the router.\n- It only matters during editing inside one component tree.\n- It is server cache and RTK Query fits the use case better.\n\n## Re-evaluate slice size\n\n- If data is constantly stitched together outside reducers, it may belong closer together.\n- If unrelated updates keep touching the same slice, split the slice by domain ownership.\n"
  },
  {
    "path": "packages/toolkit/skills/orchestrate-side-effects/handle-side-effects/SKILL.md",
    "content": "---\nname: orchestrate-side-effects/handle-side-effects\ndescription: >\n  Use this when choosing between RTK Query, createAsyncThunk, handwritten\n  thunks, and createListenerMiddleware. Covers imperative versus reactive\n  workflows, listener middleware setup, and keeping side effects out of\n  reducers and UI components.\ntype: core\nlibrary: \"@reduxjs/toolkit\"\nlibrary_version: \"2.11.2\"\nrequires:\n  - build-modern-redux-apps/redux-dataflow\nsources:\n  - \"reduxjs/redux-toolkit:docs/api/createAsyncThunk.mdx\"\n  - \"reduxjs/redux-toolkit:docs/api/createListenerMiddleware.mdx\"\n  - \"reduxjs/redux:docs/style-guide/style-guide.md\"\n  - \"reduxjs/redux:docs/tutorials/essentials/part-5-async-logic.md\"\n---\n\n# Handle Side Effects\n\n## Setup\n\n```ts\nimport {\n  configureStore,\n  createListenerMiddleware,\n  createSlice,\n} from '@reduxjs/toolkit'\n\nconst docsSlice = createSlice({\n  name: 'docs',\n  initialState: { status: 'idle' as 'idle' | 'saved' },\n  reducers: {\n    saveStarted(state) {\n      state.status = 'idle'\n    },\n    saveFinished(state) {\n      state.status = 'saved'\n    },\n  },\n})\n\nconst listenerMiddleware = createListenerMiddleware()\n\nexport const store = configureStore({\n  reducer: {\n    docs: docsSlice.reducer,\n  },\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().prepend(listenerMiddleware.middleware),\n})\n\nexport type RootState = ReturnType<typeof store.getState>\nexport type AppDispatch = typeof store.dispatch\n\nexport const startAppListening =\n  listenerMiddleware.startListening.withTypes<RootState, AppDispatch>()\n```\n\n## Core Patterns\n\n### Use RTK Query for server cache by default\n\n```ts\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ntype Post = { id: string; title: string }\n\nexport const api = createApi({\n  reducerPath: 'api',\n  baseQuery: fetchBaseQuery({ baseUrl: '/api' }),\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({\n      query: () => 'posts',\n      providesTags: ['Post'],\n    }),\n  }),\n})\n```\n\nIf the problem is server data that should be cached and re-used, start with RTK Query instead of a thunk.\n\n### Use `createAsyncThunk` for imperative workflows\n\n```ts\nimport { createAsyncThunk, createSlice } from '@reduxjs/toolkit'\n\ntype Draft = { title: string }\n\nexport const draftSaved = createAsyncThunk(\n  'drafts/save',\n  async (draft: Draft) => {\n    const response = await fetch('/api/drafts', {\n      method: 'POST',\n      headers: { 'Content-Type': 'application/json' },\n      body: JSON.stringify(draft),\n    })\n\n    return (await response.json()) as { id: string; title: string }\n  },\n)\n\nconst draftsSlice = createSlice({\n  name: 'drafts',\n  initialState: { status: 'idle' as 'idle' | 'pending' | 'failed' },\n  reducers: {},\n  extraReducers: (builder) => {\n    builder\n      .addCase(draftSaved.pending, (state) => {\n        state.status = 'pending'\n      })\n      .addCase(draftSaved.fulfilled, (state) => {\n        state.status = 'idle'\n      })\n      .addCase(draftSaved.rejected, (state) => {\n        state.status = 'failed'\n      })\n  },\n})\n```\n\nUse a thunk when you need one imperative async workflow with `dispatch` and `getState`.\n\n### Use listener middleware for reactive workflows\n\n```ts\nimport { createListenerMiddleware, createSlice } from '@reduxjs/toolkit'\n\nconst docsSlice = createSlice({\n  name: 'docs',\n  initialState: { status: 'idle' as 'idle' | 'saved' },\n  reducers: {\n    saveFinished(state) {\n      state.status = 'saved'\n    },\n  },\n})\n\nconst notificationsSlice = createSlice({\n  name: 'notifications',\n  initialState: [] as string[],\n  reducers: {\n    notificationQueued(state, action: { payload: string }) {\n      state.push(action.payload)\n    },\n  },\n})\n\nconst listenerMiddleware = createListenerMiddleware()\n\nlistenerMiddleware.startListening({\n  actionCreator: docsSlice.actions.saveFinished,\n  effect: async (_action, listenerApi) => {\n    listenerApi.dispatch(\n      notificationsSlice.actions.notificationQueued('Document saved'),\n    )\n  },\n})\n```\n\nListeners fit workflows that react to future actions or state changes over time instead of driving one imperative request from a single callsite.\n\n## Common Mistakes\n\n### CRITICAL Running side effects inside reducers\n\nWrong:\n\n```ts\nconst todosSlice = createSlice({\n  name: 'todos',\n  initialState: [] as { id: string }[],\n  reducers: {\n    todoSaved(state, action: { payload: { id: string } }) {\n      fetch('/api/todos', { method: 'POST' })\n      state.push(action.payload)\n    },\n  },\n})\n```\n\nCorrect:\n\n```ts\nimport { createAsyncThunk } from '@reduxjs/toolkit'\n\nconst todoSaved = createAsyncThunk('todos/save', async (todo: { id: string }) => {\n  await fetch('/api/todos', {\n    method: 'POST',\n    headers: { 'Content-Type': 'application/json' },\n    body: JSON.stringify(todo),\n  })\n  return todo\n})\n```\n\nReducers must stay pure even when Immer is available.\n\nSource: reduxjs/redux:docs/style-guide/style-guide.md\n\n### HIGH Using thunks to watch future state changes\n\nWrong:\n\n```ts\nexport const waitForSave = () => async (\n  _dispatch: unknown,\n  getState: () => { docs: { status: string } },\n) => {\n  while (getState().docs.status !== 'saved') {\n    await new Promise((resolve) => setTimeout(resolve, 100))\n  }\n}\n```\n\nCorrect:\n\n```ts\nstartAppListening({\n  predicate: (_action, currentState) => currentState.docs.status === 'saved',\n  effect: async () => {\n    console.log('Document saved')\n  },\n})\n```\n\nPolling inside thunks fights the architecture; listener middleware is the reactive tool.\n\nSource: reduxjs/redux-toolkit:docs/api/createListenerMiddleware.mdx\n\n### HIGH Appending listener middleware after the default checks\n\nWrong:\n\n```ts\nimport { configureStore, createListenerMiddleware } from '@reduxjs/toolkit'\n\nconst reducer = (state = { ready: true }) => state\nconst listenerMiddleware = createListenerMiddleware()\n\nconst store = configureStore({\n  reducer,\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().concat(listenerMiddleware.middleware),\n})\n```\n\nCorrect:\n\n```ts\nimport { configureStore, createListenerMiddleware } from '@reduxjs/toolkit'\n\nconst reducer = (state = { ready: true }) => state\nconst listenerMiddleware = createListenerMiddleware()\n\nconst store = configureStore({\n  reducer,\n  middleware: (getDefaultMiddleware) =>\n    getDefaultMiddleware().prepend(listenerMiddleware.middleware),\n})\n```\n\nListener add and remove actions may carry functions, so the listener middleware needs to run before serializability checks.\n\nSource: reduxjs/redux-toolkit:docs/api/createListenerMiddleware.mdx\n\n## References\n\n- [Listener helpers and decision heuristics](references/listener-workflows.md)\n"
  },
  {
    "path": "packages/toolkit/skills/orchestrate-side-effects/handle-side-effects/references/listener-workflows.md",
    "content": "# Listener Workflows\n\n## Decision table\n\n| Need | Reach for |\n| --- | --- |\n| Cached server data | RTK Query |\n| One imperative async workflow with `dispatch` / `getState` | `createAsyncThunk` or a thunk |\n| React to later actions or state transitions | `createListenerMiddleware` |\n\nA good app often mixes imperative and reactive workflows. The split is by job, not by ideology.\n\n## Useful listener helpers\n\n- `predicate`: react to any action when a state condition becomes true\n- `condition`: wait until a condition becomes true before continuing\n- `take`: wait for the next matching action\n- `cancelActiveListeners`: cancel older instances of the same workflow\n- `fork`: start a child task\n\n## Example: cancel stale work\n\n```ts\nstartAppListening({\n  actionCreator: searchRequested,\n  effect: async (action, listenerApi) => {\n    listenerApi.cancelActiveListeners()\n    await listenerApi.delay(250)\n    listenerApi.dispatch(searchStarted(action.payload))\n  },\n})\n```\n\nThis is the kind of long-lived reactive behavior that does not fit a thunk well.\n"
  },
  {
    "path": "packages/toolkit/src/actionCreatorInvariantMiddleware.ts",
    "content": "import type { Middleware } from 'redux'\nimport { isActionCreator as isRTKAction } from './createAction'\n\nexport interface ActionCreatorInvariantMiddlewareOptions {\n  /**\n   * The function to identify whether a value is an action creator.\n   * The default checks for a function with a static type property and match method.\n   */\n  isActionCreator?: (action: unknown) => action is Function & { type?: unknown }\n}\n\nexport function getMessage(type?: unknown) {\n  const splitType = type ? `${type}`.split('/') : []\n  const actionName = splitType[splitType.length - 1] || 'actionCreator'\n  return `Detected an action creator with type \"${\n    type || 'unknown'\n  }\" being dispatched.\nMake sure you're calling the action creator before dispatching, i.e. \\`dispatch(${actionName}())\\` instead of \\`dispatch(${actionName})\\`. This is necessary even if the action has no payload.`\n}\n\nexport function createActionCreatorInvariantMiddleware(\n  options: ActionCreatorInvariantMiddlewareOptions = {},\n): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => (next) => (action) => next(action)\n  }\n  const { isActionCreator = isRTKAction } = options\n  return () => (next) => (action) => {\n    if (isActionCreator(action)) {\n      console.warn(getMessage(action.type))\n    }\n    return next(action)\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/autoBatchEnhancer.ts",
    "content": "import type { StoreEnhancer } from 'redux'\n\nexport const SHOULD_AUTOBATCH = 'RTK_autoBatch'\n\nexport const prepareAutoBatched =\n  <T>() =>\n  (payload: T): { payload: T; meta: unknown } => ({\n    payload,\n    meta: { [SHOULD_AUTOBATCH]: true },\n  })\n\nconst createQueueWithTimer = (timeout: number) => {\n  return (notify: () => void) => {\n    setTimeout(notify, timeout)\n  }\n}\n\nexport type AutoBatchOptions =\n  | { type: 'tick' }\n  | { type: 'timer'; timeout: number }\n  | { type: 'raf' }\n  | { type: 'callback'; queueNotification: (notify: () => void) => void }\n\n/**\n * A Redux store enhancer that watches for \"low-priority\" actions, and delays\n * notifying subscribers until either the queued callback executes or the\n * next \"standard-priority\" action is dispatched.\n *\n * This allows dispatching multiple \"low-priority\" actions in a row with only\n * a single subscriber notification to the UI after the sequence of actions\n * is finished, thus improving UI re-render performance.\n *\n * Watches for actions with the `action.meta[SHOULD_AUTOBATCH]` attribute.\n * This can be added to `action.meta` manually, or by using the\n * `prepareAutoBatched` helper.\n *\n * By default, it will queue a notification for the end of the event loop tick.\n * However, you can pass several other options to configure the behavior:\n * - `{type: 'tick'}`: queues using `queueMicrotask`\n * - `{type: 'timer', timeout: number}`: queues using `setTimeout`\n * - `{type: 'raf'}`: queues using `requestAnimationFrame` (default)\n * - `{type: 'callback', queueNotification: (notify: () => void) => void}`: lets you provide your own callback\n *\n *\n */\nexport const autoBatchEnhancer =\n  (options: AutoBatchOptions = { type: 'raf' }): StoreEnhancer =>\n  (next) =>\n  (...args) => {\n    const store = next(...args)\n\n    let notifying = true\n    let shouldNotifyAtEndOfTick = false\n    let notificationQueued = false\n\n    const listeners = new Set<() => void>()\n\n    const queueCallback =\n      options.type === 'tick'\n        ? queueMicrotask\n        : options.type === 'raf'\n          ? // requestAnimationFrame won't exist in SSR environments. Fall back to a vague approximation just to keep from erroring.\n            typeof window !== 'undefined' && window.requestAnimationFrame\n            ? window.requestAnimationFrame\n            : createQueueWithTimer(10)\n          : options.type === 'callback'\n            ? options.queueNotification\n            : createQueueWithTimer(options.timeout)\n\n    const notifyListeners = () => {\n      // We're running at the end of the event loop tick.\n      // Run the real listener callbacks to actually update the UI.\n      notificationQueued = false\n      if (shouldNotifyAtEndOfTick) {\n        shouldNotifyAtEndOfTick = false\n        listeners.forEach((l) => l())\n      }\n    }\n\n    return Object.assign({}, store, {\n      // Override the base `store.subscribe` method to keep original listeners\n      // from running if we're delaying notifications\n      subscribe(listener: () => void) {\n        // Each wrapped listener will only call the real listener if\n        // the `notifying` flag is currently active when it's called.\n        // This lets the base store work as normal, while the actual UI\n        // update becomes controlled by this enhancer.\n        const wrappedListener: typeof listener = () => notifying && listener()\n        const unsubscribe = store.subscribe(wrappedListener)\n        listeners.add(listener)\n        return () => {\n          unsubscribe()\n          listeners.delete(listener)\n        }\n      },\n      // Override the base `store.dispatch` method so that we can check actions\n      // for the `shouldAutoBatch` flag and determine if batching is active\n      dispatch(action: any) {\n        try {\n          // If the action does _not_ have the `shouldAutoBatch` flag,\n          // we resume/continue normal notify-after-each-dispatch behavior\n          notifying = !action?.meta?.[SHOULD_AUTOBATCH]\n          // If a `notifyListeners` microtask was queued, you can't cancel it.\n          // Instead, we set a flag so that it's a no-op when it does run\n          shouldNotifyAtEndOfTick = !notifying\n          if (shouldNotifyAtEndOfTick) {\n            // We've seen at least 1 action with `SHOULD_AUTOBATCH`. Try to queue\n            // a microtask to notify listeners at the end of the event loop tick.\n            // Make sure we only enqueue this _once_ per tick.\n            if (!notificationQueued) {\n              notificationQueued = true\n              queueCallback(notifyListeners)\n            }\n          }\n          // Go ahead and process the action as usual, including reducers.\n          // If normal notification behavior is enabled, the store will notify\n          // all of its own listeners, and the wrapper callbacks above will\n          // see `notifying` is true and pass on to the real listener callbacks.\n          // If we're \"batching\" behavior, then the wrapped callbacks will\n          // bail out, causing the base store notification behavior to be no-ops.\n          return store.dispatch(action)\n        } finally {\n          // Assume we're back to normal behavior after each action\n          notifying = true\n        }\n      },\n    })\n  }\n"
  },
  {
    "path": "packages/toolkit/src/combineSlices.ts",
    "content": "import type {\n  PreloadedStateShapeFromReducersMapObject,\n  Reducer,\n  StateFromReducersMapObject,\n  UnknownAction,\n} from 'redux'\nimport { combineReducers } from 'redux'\nimport { nanoid } from './nanoid'\nimport type {\n  Id,\n  NonUndefined,\n  Tail,\n  UnionToIntersection,\n  WithOptionalProp,\n} from './tsHelpers'\nimport { getOrInsertComputed } from './utils'\n\ntype SliceLike<ReducerPath extends string, State, PreloadedState = State> = {\n  reducerPath: ReducerPath\n  reducer: Reducer<State, any, PreloadedState>\n}\n\ntype AnySliceLike = SliceLike<string, any>\n\ntype SliceLikeReducerPath<A extends AnySliceLike> =\n  A extends SliceLike<infer ReducerPath, any> ? ReducerPath : never\n\ntype SliceLikeState<A extends AnySliceLike> =\n  A extends SliceLike<any, infer State, any> ? State : never\n\ntype SliceLikePreloadedState<A extends AnySliceLike> =\n  A extends SliceLike<any, any, infer PreloadedState> ? PreloadedState : never\n\nexport type WithSlice<A extends AnySliceLike> = {\n  [Path in SliceLikeReducerPath<A>]: SliceLikeState<A>\n}\n\nexport type WithSlicePreloadedState<A extends AnySliceLike> = {\n  [Path in SliceLikeReducerPath<A>]: SliceLikePreloadedState<A>\n}\n\ntype ReducerMap = Record<string, Reducer>\n\ntype ExistingSliceLike<DeclaredState, PreloadedState> = {\n  [ReducerPath in keyof DeclaredState]: SliceLike<\n    ReducerPath & string,\n    NonUndefined<DeclaredState[ReducerPath]>,\n    NonUndefined<PreloadedState[ReducerPath & keyof PreloadedState]>\n  >\n}[keyof DeclaredState]\n\nexport type InjectConfig = {\n  /**\n   * Allow replacing reducer with a different reference. Normally, an error will be thrown if a different reducer instance to the one already injected is used.\n   */\n  overrideExisting?: boolean\n}\n\n/**\n * A reducer that allows for slices/reducers to be injected after initialisation.\n */\nexport interface CombinedSliceReducer<\n  InitialState,\n  DeclaredState extends InitialState = InitialState,\n  PreloadedState extends Partial<\n    Record<keyof PreloadedState, any>\n  > = Partial<DeclaredState>,\n> extends Reducer<DeclaredState, UnknownAction, PreloadedState> {\n  /**\n   * Provide a type for slices that will be injected lazily.\n   *\n   * One way to do this would be with interface merging:\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {}\n   *\n   * export const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * // elsewhere\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBoolean = rootReducer.inject(booleanSlice);\n   *\n   * // elsewhere again\n   *\n   * declare module './reducer' {\n   *   export interface LazyLoadedSlices {\n   *     customName: CustomState\n   *   }\n   * }\n   *\n   * const withCustom = rootReducer.inject({ reducerPath: \"customName\", reducer: customSlice.reducer })\n   * ```\n   */\n  withLazyLoadedSlices<Lazy = {}, LazyPreloaded = Lazy>(): CombinedSliceReducer<\n    InitialState,\n    Id<DeclaredState & Partial<Lazy>>,\n    Id<PreloadedState & Partial<LazyPreloaded>>\n  >\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<Sl extends Id<ExistingSliceLike<DeclaredState, PreloadedState>>>(\n    slice: Sl,\n    config?: InjectConfig,\n  ): CombinedSliceReducer<\n    InitialState,\n    Id<DeclaredState & WithSlice<Sl>>,\n    Id<PreloadedState & Partial<WithSlicePreloadedState<Sl>>>\n  >\n\n  /**\n   * Inject a slice.\n   *\n   * Accepts an individual slice, RTKQ API instance, or a \"slice-like\" { reducerPath, reducer } object.\n   *\n   * ```ts\n   * rootReducer.inject(booleanSlice)\n   * rootReducer.inject(baseApi)\n   * rootReducer.inject({ reducerPath: 'boolean' as const, reducer: newReducer }, { overrideExisting: true })\n   * ```\n   *\n   */\n  inject<ReducerPath extends string, State, PreloadedState = State>(\n    slice: SliceLike<\n      ReducerPath,\n      State & (ReducerPath extends keyof DeclaredState ? never : State),\n      PreloadedState &\n        (ReducerPath extends keyof PreloadedState ? never : PreloadedState)\n    >,\n    config?: InjectConfig,\n  ): CombinedSliceReducer<\n    InitialState,\n    Id<DeclaredState & WithSlice<SliceLike<ReducerPath, State>>>,\n    Id<\n      PreloadedState &\n        WithSlicePreloadedState<SliceLike<ReducerPath, State, PreloadedState>>\n    >\n  >\n\n  /**\n   * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n   *\n   * ```ts\n   * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n   * //                                                                ^? boolean | undefined\n   *\n   * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n   *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n   *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n   *   return state.boolean;\n   *   //           ^? boolean\n   * })\n   * ```\n   *\n   * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n   *\n   * ```ts\n   *\n   * export interface LazyLoadedSlices {};\n   *\n   * export const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n   *\n   * export const rootReducer = combineSlices({ inner: innerReducer });\n   *\n   * export type RootState = ReturnType<typeof rootReducer>;\n   *\n   * // elsewhere\n   *\n   * declare module \"./reducer.ts\" {\n   *  export interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n   * }\n   *\n   * const withBool = innerReducer.inject(booleanSlice);\n   *\n   * const selectBoolean = withBool.selector(\n   *   (state) => state.boolean,\n   *   (rootState: RootState) => state.inner\n   * );\n   * //    now expects to be passed RootState instead of innerReducer state\n   *\n   * ```\n   *\n   * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n   *\n   * ```ts\n   * const injectedReducer = rootReducer.inject(booleanSlice);\n   * const selectBoolean = injectedReducer.selector((state) => {\n   *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n   *   return state.boolean\n   * })\n   * ```\n   */\n  selector: {\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <Selector extends (state: DeclaredState, ...args: any[]) => unknown>(\n      selectorFn: Selector,\n    ): (\n      state: WithOptionalProp<\n        Parameters<Selector>[0],\n        Exclude<keyof DeclaredState, keyof InitialState>\n      >,\n      ...args: Tail<Parameters<Selector>>\n    ) => ReturnType<Selector>\n\n    /**\n     * Create a selector that guarantees that the slices injected will have a defined value when selector is run.\n     *\n     * ```ts\n     * const selectBooleanWithoutInjection = (state: RootState) => state.boolean;\n     * //                                                                ^? boolean | undefined\n     *\n     * const selectBoolean = rootReducer.inject(booleanSlice).selector((state) => {\n     *   // if action hasn't been dispatched since slice was injected, this would usually be undefined\n     *   // however selector() uses a Proxy around the first parameter to ensure that it evaluates to the initial state instead, if undefined\n     *   return state.boolean;\n     *   //           ^? boolean\n     * })\n     * ```\n     *\n     * If the reducer is nested inside the root state, a selectState callback can be passed to retrieve the reducer's state.\n     *\n     * ```ts\n     *\n     * interface LazyLoadedSlices {};\n     *\n     * const innerReducer = combineSlices(stringSlice).withLazyLoadedSlices<LazyLoadedSlices>();\n     *\n     * const rootReducer = combineSlices({ inner: innerReducer });\n     *\n     * type RootState = ReturnType<typeof rootReducer>;\n     *\n     * // elsewhere\n     *\n     * declare module \"./reducer.ts\" {\n     *  interface LazyLoadedSlices extends WithSlice<typeof booleanSlice> {}\n     * }\n     *\n     * const withBool = innerReducer.inject(booleanSlice);\n     *\n     * const selectBoolean = withBool.selector(\n     *   (state) => state.boolean,\n     *   (rootState: RootState) => state.inner\n     * );\n     * //    now expects to be passed RootState instead of innerReducer state\n     *\n     * ```\n     *\n     * Value passed to selectorFn will be a Proxy - use selector.original(proxy) to get original state value (useful for debugging)\n     *\n     * ```ts\n     * const injectedReducer = rootReducer.inject(booleanSlice);\n     * const selectBoolean = injectedReducer.selector((state) => {\n     *   console.log(injectedReducer.selector.original(state).boolean) // possibly undefined\n     *   return state.boolean\n     * })\n     * ```\n     */\n    <\n      Selector extends (state: DeclaredState, ...args: any[]) => unknown,\n      RootState,\n    >(\n      selectorFn: Selector,\n      selectState: (\n        rootState: RootState,\n        ...args: Tail<Parameters<Selector>>\n      ) => WithOptionalProp<\n        Parameters<Selector>[0],\n        Exclude<keyof DeclaredState, keyof InitialState>\n      >,\n    ): (\n      state: RootState,\n      ...args: Tail<Parameters<Selector>>\n    ) => ReturnType<Selector>\n    /**\n     * Returns the unproxied state. Useful for debugging.\n     * @param state state Proxy, that ensures injected reducers have value\n     * @returns original, unproxied state\n     * @throws if value passed is not a state Proxy\n     */\n    original: (state: DeclaredState) => InitialState & Partial<DeclaredState>\n  }\n}\n\ntype InitialState<Slices extends Array<AnySliceLike | ReducerMap>> =\n  UnionToIntersection<\n    Slices[number] extends infer Slice\n      ? Slice extends AnySliceLike\n        ? WithSlice<Slice>\n        : StateFromReducersMapObject<Slice>\n      : never\n  >\n\ntype InitialPreloadedState<Slices extends Array<AnySliceLike | ReducerMap>> =\n  UnionToIntersection<\n    Slices[number] extends infer Slice\n      ? Slice extends AnySliceLike\n        ? WithSlicePreloadedState<Slice>\n        : PreloadedStateShapeFromReducersMapObject<Slice>\n      : never\n  >\n\nconst isSliceLike = (\n  maybeSliceLike: AnySliceLike | ReducerMap,\n): maybeSliceLike is AnySliceLike =>\n  'reducerPath' in maybeSliceLike &&\n  typeof maybeSliceLike.reducerPath === 'string'\n\nconst getReducers = (slices: Array<AnySliceLike | ReducerMap>) =>\n  slices.flatMap<[string, Reducer]>((sliceOrMap) =>\n    isSliceLike(sliceOrMap)\n      ? [[sliceOrMap.reducerPath, sliceOrMap.reducer]]\n      : Object.entries(sliceOrMap),\n  )\n\nconst ORIGINAL_STATE = Symbol.for('rtk-state-proxy-original')\n\nconst isStateProxy = (value: any) => !!value && !!value[ORIGINAL_STATE]\n\nconst stateProxyMap = new WeakMap<object, object>()\n\nconst createStateProxy = <State extends object>(\n  state: State,\n  reducerMap: Partial<Record<PropertyKey, Reducer>>,\n  initialStateCache: Record<PropertyKey, unknown>,\n) =>\n  getOrInsertComputed(\n    stateProxyMap,\n    state,\n    () =>\n      new Proxy(state, {\n        get: (target, prop, receiver) => {\n          if (prop === ORIGINAL_STATE) return target\n          const result = Reflect.get(target, prop, receiver)\n          if (typeof result === 'undefined') {\n            const cached = initialStateCache[prop]\n            if (typeof cached !== 'undefined') return cached\n            const reducer = reducerMap[prop]\n            if (reducer) {\n              // ensure action type is random, to prevent reducer treating it differently\n              const reducerResult = reducer(undefined, { type: nanoid() })\n              if (typeof reducerResult === 'undefined') {\n                throw new Error(\n                  `The slice reducer for key \"${prop.toString()}\" returned undefined when called for selector(). ` +\n                    `If the state passed to the reducer is undefined, you must ` +\n                    `explicitly return the initial state. The initial state may ` +\n                    `not be undefined. If you don't want to set a value for this reducer, ` +\n                    `you can use null instead of undefined.`,\n                )\n              }\n              initialStateCache[prop] = reducerResult\n              return reducerResult\n            }\n          }\n          return result\n        },\n      }),\n  ) as State\n\nconst original = (state: any) => {\n  if (!isStateProxy(state)) {\n    throw new Error('original must be used on state Proxy')\n  }\n  return state[ORIGINAL_STATE]\n}\n\nconst emptyObject = {}\nconst noopReducer: Reducer<Record<string, any>> = (state = emptyObject) => state\n\nexport function combineSlices<Slices extends Array<AnySliceLike | ReducerMap>>(\n  ...slices: Slices\n): CombinedSliceReducer<\n  Id<InitialState<Slices>>,\n  Id<InitialState<Slices>>,\n  Partial<Id<InitialPreloadedState<Slices>>>\n> {\n  const reducerMap = Object.fromEntries(getReducers(slices))\n\n  const getReducer = () =>\n    Object.keys(reducerMap).length ? combineReducers(reducerMap) : noopReducer\n\n  let reducer = getReducer()\n\n  function combinedReducer(\n    state: Record<string, unknown>,\n    action: UnknownAction,\n  ) {\n    return reducer(state, action)\n  }\n\n  combinedReducer.withLazyLoadedSlices = () => combinedReducer\n\n  const initialStateCache: Record<PropertyKey, unknown> = {}\n\n  const inject = (\n    slice: AnySliceLike,\n    config: InjectConfig = {},\n  ): typeof combinedReducer => {\n    const { reducerPath, reducer: reducerToInject } = slice\n\n    const currentReducer = reducerMap[reducerPath]\n    if (\n      !config.overrideExisting &&\n      currentReducer &&\n      currentReducer !== reducerToInject\n    ) {\n      if (\n        typeof process !== 'undefined' &&\n        process.env.NODE_ENV === 'development'\n      ) {\n        console.error(\n          `called \\`inject\\` to override already-existing reducer ${reducerPath} without specifying \\`overrideExisting: true\\``,\n        )\n      }\n\n      return combinedReducer\n    }\n\n    if (config.overrideExisting && currentReducer !== reducerToInject) {\n      delete initialStateCache[reducerPath]\n    }\n\n    reducerMap[reducerPath] = reducerToInject\n\n    reducer = getReducer()\n\n    return combinedReducer\n  }\n\n  const selector = Object.assign(\n    function makeSelector<State extends object, RootState, Args extends any[]>(\n      selectorFn: (state: State, ...args: Args) => any,\n      selectState?: (rootState: RootState, ...args: Args) => State,\n    ) {\n      return function selector(state: State, ...args: Args) {\n        return selectorFn(\n          createStateProxy(\n            selectState ? selectState(state as any, ...args) : state,\n            reducerMap,\n            initialStateCache,\n          ),\n          ...args,\n        )\n      }\n    },\n    { original },\n  )\n\n  return Object.assign(combinedReducer, { inject, selector }) as any\n}\n"
  },
  {
    "path": "packages/toolkit/src/configureStore.ts",
    "content": "import type {\n  Reducer,\n  ReducersMapObject,\n  Middleware,\n  Action,\n  StoreEnhancer,\n  Store,\n  UnknownAction,\n} from 'redux'\nimport {\n  applyMiddleware,\n  createStore,\n  compose,\n  combineReducers,\n  isPlainObject,\n} from './reduxImports'\nimport type { DevToolsEnhancerOptions as DevToolsOptions } from './devtoolsExtension'\nimport { composeWithDevTools } from './devtoolsExtension'\n\nimport type {\n  ThunkMiddlewareFor,\n  GetDefaultMiddleware,\n} from './getDefaultMiddleware'\nimport { buildGetDefaultMiddleware } from './getDefaultMiddleware'\nimport type {\n  ExtractDispatchExtensions,\n  ExtractStoreExtensions,\n  ExtractStateExtensions,\n  UnknownIfNonSpecific,\n} from './tsHelpers'\nimport type { Tuple } from './utils'\nimport type { GetDefaultEnhancers } from './getDefaultEnhancers'\nimport { buildGetDefaultEnhancers } from './getDefaultEnhancers'\n\n/**\n * Options for `configureStore()`.\n *\n * @public\n */\nexport interface ConfigureStoreOptions<\n  S = any,\n  A extends Action = UnknownAction,\n  M extends Tuple<Middlewares<S>> = Tuple<Middlewares<S>>,\n  E extends Tuple<Enhancers> = Tuple<Enhancers>,\n  P = S,\n> {\n  /**\n   * A single reducer function that will be used as the root reducer, or an\n   * object of slice reducers that will be passed to `combineReducers()`.\n   */\n  reducer: Reducer<S, A, P> | ReducersMapObject<S, A, P>\n\n  /**\n   * An array of Redux middleware to install, or a callback receiving `getDefaultMiddleware` and returning a Tuple of middleware.\n   * If not supplied, defaults to the set of middleware returned by `getDefaultMiddleware()`.\n   *\n   * @example `middleware: (gDM) => gDM().concat(logger, apiMiddleware, yourCustomMiddleware)`\n   * @see https://redux-toolkit.js.org/api/getDefaultMiddleware#intended-usage\n   */\n  middleware?: (getDefaultMiddleware: GetDefaultMiddleware<S>) => M\n\n  /**\n   * Whether to enable Redux DevTools integration. Defaults to `true`.\n   *\n   * Additional configuration can be done by passing Redux DevTools options\n   */\n  devTools?: boolean | DevToolsOptions\n\n  /**\n   * Whether to check for duplicate middleware instances. Defaults to `true`.\n   */\n  duplicateMiddlewareCheck?: boolean\n\n  /**\n   * The initial state, same as Redux's createStore.\n   * You may optionally specify it to hydrate the state\n   * from the server in universal apps, or to restore a previously serialized\n   * user session. If you use `combineReducers()` to produce the root reducer\n   * function (either directly or indirectly by passing an object as `reducer`),\n   * this must be an object with the same shape as the reducer map keys.\n   */\n  // we infer here, and instead complain if the reducer doesn't match\n  preloadedState?: P\n\n  /**\n   * The store enhancers to apply. See Redux's `createStore()`.\n   * All enhancers will be included before the DevTools Extension enhancer.\n   * If you need to customize the order of enhancers, supply a callback\n   * function that will receive a `getDefaultEnhancers` function that returns a Tuple,\n   * and should return a Tuple of enhancers (such as `getDefaultEnhancers().concat(offline)`).\n   * If you only need to add middleware, you can use the `middleware` parameter instead.\n   */\n  enhancers?: (getDefaultEnhancers: GetDefaultEnhancers<M>) => E\n}\n\nexport type Middlewares<S> = ReadonlyArray<Middleware<{}, S>>\n\ntype Enhancers = ReadonlyArray<StoreEnhancer>\n\n/**\n * A Redux store returned by `configureStore()`. Supports dispatching\n * side-effectful _thunks_ in addition to plain actions.\n *\n * @public\n */\nexport type EnhancedStore<\n  S = any,\n  A extends Action = UnknownAction,\n  E extends Enhancers = Enhancers,\n> = ExtractStoreExtensions<E> &\n  Store<S, A, UnknownIfNonSpecific<ExtractStateExtensions<E>>>\n\n/**\n * A friendly abstraction over the standard Redux `createStore()` function.\n *\n * @param options The store configuration.\n * @returns A configured Redux store.\n *\n * @public\n */\nexport function configureStore<\n  S = any,\n  A extends Action = UnknownAction,\n  M extends Tuple<Middlewares<S>> = Tuple<[ThunkMiddlewareFor<S>]>,\n  E extends Tuple<Enhancers> = Tuple<\n    [StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>, StoreEnhancer]\n  >,\n  P = S,\n>(options: ConfigureStoreOptions<S, A, M, E, P>): EnhancedStore<S, A, E> {\n  const getDefaultMiddleware = buildGetDefaultMiddleware<S>()\n\n  const {\n    reducer = undefined,\n    middleware,\n    devTools = true,\n    duplicateMiddlewareCheck = true,\n    preloadedState = undefined,\n    enhancers = undefined,\n  } = options || {}\n\n  let rootReducer: Reducer<S, A, P>\n\n  if (typeof reducer === 'function') {\n    rootReducer = reducer\n  } else if (isPlainObject(reducer)) {\n    rootReducer = combineReducers(reducer) as unknown as Reducer<S, A, P>\n  } else {\n    throw new Error(\n      '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers',\n    )\n  }\n\n  if (\n    process.env.NODE_ENV !== 'production' &&\n    middleware &&\n    typeof middleware !== 'function'\n  ) {\n    throw new Error('`middleware` field must be a callback')\n  }\n\n  let finalMiddleware: Tuple<Middlewares<S>>\n  if (typeof middleware === 'function') {\n    finalMiddleware = middleware(getDefaultMiddleware)\n\n    if (\n      process.env.NODE_ENV !== 'production' &&\n      !Array.isArray(finalMiddleware)\n    ) {\n      throw new Error(\n        'when using a middleware builder function, an array of middleware must be returned',\n      )\n    }\n  } else {\n    finalMiddleware = getDefaultMiddleware()\n  }\n  if (\n    process.env.NODE_ENV !== 'production' &&\n    finalMiddleware.some((item: any) => typeof item !== 'function')\n  ) {\n    throw new Error(\n      'each middleware provided to configureStore must be a function',\n    )\n  }\n\n  if (process.env.NODE_ENV !== 'production' && duplicateMiddlewareCheck) {\n    let middlewareReferences = new Set<Middleware<any, S>>()\n    finalMiddleware.forEach((middleware) => {\n      if (middlewareReferences.has(middleware)) {\n        throw new Error(\n          'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',\n        )\n      }\n      middlewareReferences.add(middleware)\n    })\n  }\n\n  let finalCompose = compose\n\n  if (devTools) {\n    finalCompose = composeWithDevTools({\n      // Enable capture of stack traces for dispatched Redux actions\n      trace: process.env.NODE_ENV !== 'production',\n      ...(typeof devTools === 'object' && devTools),\n    })\n  }\n\n  const middlewareEnhancer = applyMiddleware(...finalMiddleware)\n\n  const getDefaultEnhancers = buildGetDefaultEnhancers<M>(middlewareEnhancer)\n\n  if (\n    process.env.NODE_ENV !== 'production' &&\n    enhancers &&\n    typeof enhancers !== 'function'\n  ) {\n    throw new Error('`enhancers` field must be a callback')\n  }\n\n  let storeEnhancers =\n    typeof enhancers === 'function'\n      ? enhancers(getDefaultEnhancers)\n      : getDefaultEnhancers()\n\n  if (process.env.NODE_ENV !== 'production' && !Array.isArray(storeEnhancers)) {\n    throw new Error('`enhancers` callback must return an array')\n  }\n  if (\n    process.env.NODE_ENV !== 'production' &&\n    storeEnhancers.some((item: any) => typeof item !== 'function')\n  ) {\n    throw new Error(\n      'each enhancer provided to configureStore must be a function',\n    )\n  }\n  if (\n    process.env.NODE_ENV !== 'production' &&\n    finalMiddleware.length &&\n    !storeEnhancers.includes(middlewareEnhancer)\n  ) {\n    console.error(\n      'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`',\n    )\n  }\n\n  const composedEnhancer: StoreEnhancer<any> = finalCompose(...storeEnhancers)\n\n  return createStore(rootReducer, preloadedState as P, composedEnhancer)\n}\n"
  },
  {
    "path": "packages/toolkit/src/createAction.ts",
    "content": "import { isAction } from './reduxImports'\nimport type {\n  IsUnknownOrNonInferrable,\n  IfMaybeUndefined,\n  IfVoid,\n  IsAny,\n} from './tsHelpers'\nimport { hasMatchFunction } from './tsHelpers'\n\n/**\n * An action with a string type and an associated payload. This is the\n * type of action returned by `createAction()` action creators.\n *\n * @template P The type of the action's payload.\n * @template T the type used for the action type.\n * @template M The type of the action's meta (optional)\n * @template E The type of the action's error (optional)\n *\n * @public\n */\nexport type PayloadAction<\n  P = void,\n  T extends string = string,\n  M = never,\n  E = never,\n> = {\n  payload: P\n  type: T\n} & ([M] extends [never]\n  ? {}\n  : {\n      meta: M\n    }) &\n  ([E] extends [never]\n    ? {}\n    : {\n        error: E\n      })\n\n/**\n * A \"prepare\" method to be used as the second parameter of `createAction`.\n * Takes any number of arguments and returns a Flux Standard Action without\n * type (will be added later) that *must* contain a payload (might be undefined).\n *\n * @public\n */\nexport type PrepareAction<P> =\n  | ((...args: any[]) => { payload: P })\n  | ((...args: any[]) => { payload: P; meta: any })\n  | ((...args: any[]) => { payload: P; error: any })\n  | ((...args: any[]) => { payload: P; meta: any; error: any })\n\n/**\n * Internal version of `ActionCreatorWithPreparedPayload`. Not to be used externally.\n *\n * @internal\n */\nexport type _ActionCreatorWithPreparedPayload<\n  PA extends PrepareAction<any> | void,\n  T extends string = string,\n> =\n  PA extends PrepareAction<infer P>\n    ? ActionCreatorWithPreparedPayload<\n        Parameters<PA>,\n        P,\n        T,\n        ReturnType<PA> extends {\n          error: infer E\n        }\n          ? E\n          : never,\n        ReturnType<PA> extends {\n          meta: infer M\n        }\n          ? M\n          : never\n      >\n    : void\n\n/**\n * Basic type for all action creators.\n *\n * @inheritdoc {redux#ActionCreator}\n */\nexport type BaseActionCreator<P, T extends string, M = never, E = never> = {\n  type: T\n  match: (action: unknown) => action is PayloadAction<P, T, M, E>\n}\n\n/**\n * An action creator that takes multiple arguments that are passed\n * to a `PrepareAction` method to create the final Action.\n * @typeParam Args arguments for the action creator function\n * @typeParam P `payload` type\n * @typeParam T `type` name\n * @typeParam E optional `error` type\n * @typeParam M optional `meta` type\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPreparedPayload<\n  Args extends unknown[],\n  P,\n  T extends string = string,\n  E = never,\n  M = never,\n> extends BaseActionCreator<P, T, M, E> {\n  /**\n   * Calling this {@link redux#ActionCreator} with `Args` will return\n   * an Action with a payload of type `P` and (depending on the `PrepareAction`\n   * method used) a `meta`- and `error` property of types `M` and `E` respectively.\n   */\n  (...args: Args): PayloadAction<P, T, M, E>\n}\n\n/**\n * An action creator of type `T` that takes an optional payload of type `P`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithOptionalPayload<P, T extends string = string>\n  extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`.\n   * Calling it without an argument will return a PayloadAction with a payload of `undefined`.\n   */\n  (payload?: P): PayloadAction<P, T>\n}\n\n/**\n * An action creator of type `T` that takes no payload.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithoutPayload<T extends string = string>\n  extends BaseActionCreator<undefined, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} will\n   * return a {@link PayloadAction} of type `T` with a payload of `undefined`\n   */\n  (noArgument: void): PayloadAction<undefined, T>\n}\n\n/**\n * An action creator of type `T` that requires a payload of type P.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithPayload<P, T extends string = string>\n  extends BaseActionCreator<P, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload of `P`\n   */\n  (payload: P): PayloadAction<P, T>\n}\n\n/**\n * An action creator of type `T` whose `payload` type could not be inferred. Accepts everything as `payload`.\n *\n * @inheritdoc {redux#ActionCreator}\n *\n * @public\n */\nexport interface ActionCreatorWithNonInferrablePayload<\n  T extends string = string,\n> extends BaseActionCreator<unknown, T> {\n  /**\n   * Calling this {@link redux#ActionCreator} with an argument will\n   * return a {@link PayloadAction} of type `T` with a payload\n   * of exactly the type of the argument.\n   */\n  <PT extends unknown>(payload: PT): PayloadAction<PT, T>\n}\n\n/**\n * An action creator that produces actions with a `payload` attribute.\n *\n * @typeParam P the `payload` type\n * @typeParam T the `type` of the resulting action\n * @typeParam PA if the resulting action is preprocessed by a `prepare` method, the signature of said method.\n *\n * @public\n */\nexport type PayloadActionCreator<\n  P = void,\n  T extends string = string,\n  PA extends PrepareAction<P> | void = void,\n> = IfPrepareActionMethodProvided<\n  PA,\n  _ActionCreatorWithPreparedPayload<PA, T>,\n  // else\n  IsAny<\n    P,\n    ActionCreatorWithPayload<any, T>,\n    IsUnknownOrNonInferrable<\n      P,\n      ActionCreatorWithNonInferrablePayload<T>,\n      // else\n      IfVoid<\n        P,\n        ActionCreatorWithoutPayload<T>,\n        // else\n        IfMaybeUndefined<\n          P,\n          ActionCreatorWithOptionalPayload<P, T>,\n          // else\n          ActionCreatorWithPayload<P, T>\n        >\n      >\n    >\n  >\n>\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<P = void, T extends string = string>(\n  type: T,\n): PayloadActionCreator<P, T>\n\n/**\n * A utility function to create an action creator for the given action type\n * string. The action creator accepts a single argument, which will be included\n * in the action object as a field called payload. The action creator function\n * will also have its toString() overridden so that it returns the action type.\n *\n * @param type The action type to use for created actions.\n * @param prepare (optional) a method that takes any number of arguments and returns { payload } or { payload, meta }.\n *                If this is given, the resulting action creator will pass its arguments to this method to calculate payload & meta.\n *\n * @public\n */\nexport function createAction<\n  PA extends PrepareAction<any>,\n  T extends string = string,\n>(\n  type: T,\n  prepareAction: PA,\n): PayloadActionCreator<ReturnType<PA>['payload'], T, PA>\n\nexport function createAction(type: string, prepareAction?: Function): any {\n  function actionCreator(...args: any[]) {\n    if (prepareAction) {\n      let prepared = prepareAction(...args)\n      if (!prepared) {\n        throw new Error('prepareAction did not return an object')\n      }\n\n      return {\n        type,\n        payload: prepared.payload,\n        ...('meta' in prepared && { meta: prepared.meta }),\n        ...('error' in prepared && { error: prepared.error }),\n      }\n    }\n    return { type, payload: args[0] }\n  }\n\n  actionCreator.toString = () => `${type}`\n\n  actionCreator.type = type\n\n  actionCreator.match = (action: unknown): action is PayloadAction =>\n    isAction(action) && action.type === type\n\n  return actionCreator\n}\n\n/**\n * Returns true if value is an RTK-like action creator, with a static type property and match method.\n */\nexport function isActionCreator(\n  action: unknown,\n): action is BaseActionCreator<unknown, string> & Function {\n  return (\n    typeof action === 'function' &&\n    'type' in action &&\n    // hasMatchFunction only wants Matchers but I don't see the point in rewriting it\n    hasMatchFunction(action as any)\n  )\n}\n\n/**\n * Returns true if value is an action with a string type and valid Flux Standard Action keys.\n */\nexport function isFSA(action: unknown): action is {\n  type: string\n  payload?: unknown\n  error?: unknown\n  meta?: unknown\n} {\n  return isAction(action) && Object.keys(action).every(isValidKey)\n}\n\nfunction isValidKey(key: string) {\n  return ['type', 'payload', 'error', 'meta'].indexOf(key) > -1\n}\n\n// helper types for more readable typings\n\ntype IfPrepareActionMethodProvided<\n  PA extends PrepareAction<any> | void,\n  True,\n  False,\n> = PA extends (...args: any[]) => any ? True : False\n"
  },
  {
    "path": "packages/toolkit/src/createAsyncThunk.ts",
    "content": "import type { Dispatch, UnknownAction } from 'redux'\nimport type { ThunkDispatch } from 'redux-thunk'\nimport type { ActionCreatorWithPreparedPayload } from './createAction'\nimport { createAction } from './createAction'\nimport { isAnyOf } from './matchers'\nimport { nanoid } from './nanoid'\nimport type {\n  FallbackIfUnknown,\n  Id,\n  IsAny,\n  IsUnknown,\n  SafePromise,\n} from './tsHelpers'\n\nexport type BaseThunkAPI<\n  S,\n  E,\n  D extends Dispatch = Dispatch,\n  RejectedValue = unknown,\n  RejectedMeta = unknown,\n  FulfilledMeta = unknown,\n> = {\n  dispatch: D\n  getState: () => S\n  extra: E\n  requestId: string\n  signal: AbortSignal\n  abort: (reason?: string) => void\n  rejectWithValue: IsUnknown<\n    RejectedMeta,\n    (value: RejectedValue) => RejectWithValue<RejectedValue, RejectedMeta>,\n    (\n      value: RejectedValue,\n      meta: RejectedMeta,\n    ) => RejectWithValue<RejectedValue, RejectedMeta>\n  >\n  fulfillWithValue: IsUnknown<\n    FulfilledMeta,\n    <FulfilledValue>(value: FulfilledValue) => FulfilledValue,\n    <FulfilledValue>(\n      value: FulfilledValue,\n      meta: FulfilledMeta,\n    ) => FulfillWithMeta<FulfilledValue, FulfilledMeta>\n  >\n}\n\n/**\n * @public\n */\nexport interface SerializedError {\n  name?: string\n  message?: string\n  stack?: string\n  code?: string\n}\n\nconst commonProperties: Array<keyof SerializedError> = [\n  'name',\n  'message',\n  'stack',\n  'code',\n]\n\nclass RejectWithValue<Payload, RejectedMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'RejectWithValue'\n  constructor(\n    public readonly payload: Payload,\n    public readonly meta: RejectedMeta,\n  ) {}\n}\n\nclass FulfillWithMeta<Payload, FulfilledMeta> {\n  /*\n  type-only property to distinguish between RejectWithValue and FulfillWithMeta\n  does not exist at runtime\n  */\n  private readonly _type!: 'FulfillWithMeta'\n  constructor(\n    public readonly payload: Payload,\n    public readonly meta: FulfilledMeta,\n  ) {}\n}\n\n/**\n * Serializes an error into a plain object.\n * Reworked from https://github.com/sindresorhus/serialize-error\n *\n * @public\n */\nexport const miniSerializeError = (value: any): SerializedError => {\n  if (typeof value === 'object' && value !== null) {\n    const simpleError: SerializedError = {}\n    for (const property of commonProperties) {\n      if (typeof value[property] === 'string') {\n        simpleError[property] = value[property]\n      }\n    }\n\n    return simpleError\n  }\n\n  return { message: String(value) }\n}\n\nexport type AsyncThunkConfig = {\n  state?: unknown\n  dispatch?: ThunkDispatch<unknown, unknown, UnknownAction>\n  extra?: unknown\n  rejectValue?: unknown\n  serializedErrorType?: unknown\n  pendingMeta?: unknown\n  fulfilledMeta?: unknown\n  rejectedMeta?: unknown\n}\n\nexport type GetState<ThunkApiConfig> = ThunkApiConfig extends {\n  state: infer State\n}\n  ? State\n  : unknown\n\ntype GetExtra<ThunkApiConfig> = ThunkApiConfig extends { extra: infer Extra }\n  ? Extra\n  : unknown\ntype GetDispatch<ThunkApiConfig> = ThunkApiConfig extends {\n  dispatch: infer Dispatch\n}\n  ? FallbackIfUnknown<\n      Dispatch,\n      ThunkDispatch<\n        GetState<ThunkApiConfig>,\n        GetExtra<ThunkApiConfig>,\n        UnknownAction\n      >\n    >\n  : ThunkDispatch<\n      GetState<ThunkApiConfig>,\n      GetExtra<ThunkApiConfig>,\n      UnknownAction\n    >\n\nexport type GetThunkAPI<ThunkApiConfig> = BaseThunkAPI<\n  GetState<ThunkApiConfig>,\n  GetExtra<ThunkApiConfig>,\n  GetDispatch<ThunkApiConfig>,\n  GetRejectValue<ThunkApiConfig>,\n  GetRejectedMeta<ThunkApiConfig>,\n  GetFulfilledMeta<ThunkApiConfig>\n>\n\ntype GetRejectValue<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectValue: infer RejectValue\n}\n  ? RejectValue\n  : unknown\n\ntype GetPendingMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  pendingMeta: infer PendingMeta\n}\n  ? PendingMeta\n  : unknown\n\ntype GetFulfilledMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  fulfilledMeta: infer FulfilledMeta\n}\n  ? FulfilledMeta\n  : unknown\n\ntype GetRejectedMeta<ThunkApiConfig> = ThunkApiConfig extends {\n  rejectedMeta: infer RejectedMeta\n}\n  ? RejectedMeta\n  : unknown\n\ntype GetSerializedErrorType<ThunkApiConfig> = ThunkApiConfig extends {\n  serializedErrorType: infer GetSerializedErrorType\n}\n  ? GetSerializedErrorType\n  : SerializedError\n\ntype MaybePromise<T> = T | Promise<T> | (T extends any ? Promise<T> : never)\n\n/**\n * A type describing the return value of the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreatorReturnValue<\n  Returned,\n  ThunkApiConfig extends AsyncThunkConfig,\n> = MaybePromise<\n  | IsUnknown<\n      GetFulfilledMeta<ThunkApiConfig>,\n      Returned,\n      FulfillWithMeta<Returned, GetFulfilledMeta<ThunkApiConfig>>\n    >\n  | RejectWithValue<\n      GetRejectValue<ThunkApiConfig>,\n      GetRejectedMeta<ThunkApiConfig>\n    >\n>\n/**\n * A type describing the `payloadCreator` argument to `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunkPayloadCreator<\n  Returned,\n  ThunkArg = void,\n  ThunkApiConfig extends AsyncThunkConfig = {},\n> = (\n  arg: ThunkArg,\n  thunkAPI: GetThunkAPI<ThunkApiConfig>,\n) => AsyncThunkPayloadCreatorReturnValue<Returned, ThunkApiConfig>\n\n/**\n * A ThunkAction created by `createAsyncThunk`.\n * Dispatching it returns a Promise for either a\n * fulfilled or rejected action.\n * Also, the returned value contains an `abort()` method\n * that allows the asyncAction to be cancelled from the outside.\n *\n * @public\n */\nexport type AsyncThunkAction<\n  Returned,\n  ThunkArg,\n  ThunkApiConfig extends AsyncThunkConfig,\n> = (\n  dispatch: NonNullable<GetDispatch<ThunkApiConfig>>,\n  getState: () => GetState<ThunkApiConfig>,\n  extra: GetExtra<ThunkApiConfig>,\n) => SafePromise<\n  | ReturnType<AsyncThunkFulfilledActionCreator<Returned, ThunkArg>>\n  | ReturnType<AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>>\n> & {\n  abort: (reason?: string) => void\n  requestId: string\n  arg: ThunkArg\n  unwrap: () => Promise<Returned>\n}\n\n/**\n * Config provided when calling the async thunk action creator.\n */\nexport interface AsyncThunkDispatchConfig {\n  /**\n   * An external `AbortSignal` that will be tracked by the internal `AbortSignal`.\n   */\n  signal?: AbortSignal\n}\n\ntype AsyncThunkActionCreator<\n  Returned,\n  ThunkArg,\n  ThunkApiConfig extends AsyncThunkConfig,\n> = IsAny<\n  ThunkArg,\n  // any handling\n  (\n    arg: ThunkArg,\n    config?: AsyncThunkDispatchConfig,\n  ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n  // unknown handling\n  unknown extends ThunkArg\n    ? (\n        arg: ThunkArg,\n        config?: AsyncThunkDispatchConfig,\n      ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument not specified or specified as void or undefined\n    : [ThunkArg] extends [void] | [undefined]\n      ? (\n          arg?: undefined,\n          config?: AsyncThunkDispatchConfig,\n        ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains void\n      : [void] extends [ThunkArg] // make optional\n        ? (\n            arg?: ThunkArg,\n            config?: AsyncThunkDispatchConfig,\n          ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig> // argument contains undefined\n        : [undefined] extends [ThunkArg]\n          ? WithStrictNullChecks<\n              // with strict nullChecks: make optional\n              (\n                arg?: ThunkArg,\n                config?: AsyncThunkDispatchConfig,\n              ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>,\n              // without strict null checks this will match everything, so don't make it optional\n              (\n                arg: ThunkArg,\n                config?: AsyncThunkDispatchConfig,\n              ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>\n            > // default case: normal argument\n          : (\n              arg: ThunkArg,\n              config?: AsyncThunkDispatchConfig,\n            ) => AsyncThunkAction<Returned, ThunkArg, ThunkApiConfig>\n>\n\n/**\n * Options object for `createAsyncThunk`.\n *\n * @public\n */\nexport type AsyncThunkOptions<\n  ThunkArg = void,\n  ThunkApiConfig extends AsyncThunkConfig = {},\n> = {\n  /**\n   * A method to control whether the asyncThunk should be executed. Has access to the\n   * `arg`, `api.getState()` and `api.extra` arguments.\n   *\n   * @returns `false` if it should be skipped\n   */\n  condition?(\n    arg: ThunkArg,\n    api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,\n  ): MaybePromise<boolean | undefined>\n  /**\n   * If `condition` returns `false`, the asyncThunk will be skipped.\n   * This option allows you to control whether a `rejected` action with `meta.condition == false`\n   * will be dispatched or not.\n   *\n   * @default `false`\n   */\n  dispatchConditionRejection?: boolean\n\n  serializeError?: (x: unknown) => GetSerializedErrorType<ThunkApiConfig>\n\n  /**\n   * A function to use when generating the `requestId` for the request sequence.\n   *\n   * @default `nanoid`\n   */\n  idGenerator?: (arg: ThunkArg) => string\n} & IsUnknown<\n  GetPendingMeta<ThunkApiConfig>,\n  {\n    /**\n     * A method to generate additional properties to be added to `meta` of the pending action.\n     *\n     * Using this optional overload will not modify the types correctly, this overload is only in place to support JavaScript users.\n     * Please use the `ThunkApiConfig` parameter `pendingMeta` to get access to a correctly typed overload\n     */\n    getPendingMeta?(\n      base: {\n        arg: ThunkArg\n        requestId: string\n      },\n      api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,\n    ): GetPendingMeta<ThunkApiConfig>\n  },\n  {\n    /**\n     * A method to generate additional properties to be added to `meta` of the pending action.\n     */\n    getPendingMeta(\n      base: {\n        arg: ThunkArg\n        requestId: string\n      },\n      api: Pick<GetThunkAPI<ThunkApiConfig>, 'getState' | 'extra'>,\n    ): GetPendingMeta<ThunkApiConfig>\n  }\n>\n\nexport type AsyncThunkPendingActionCreator<\n  ThunkArg,\n  ThunkApiConfig = {},\n> = ActionCreatorWithPreparedPayload<\n  [string, ThunkArg, GetPendingMeta<ThunkApiConfig>?],\n  undefined,\n  string,\n  never,\n  {\n    arg: ThunkArg\n    requestId: string\n    requestStatus: 'pending'\n  } & GetPendingMeta<ThunkApiConfig>\n>\n\nexport type AsyncThunkRejectedActionCreator<\n  ThunkArg,\n  ThunkApiConfig = {},\n> = ActionCreatorWithPreparedPayload<\n  [\n    Error | null,\n    string,\n    ThunkArg,\n    GetRejectValue<ThunkApiConfig>?,\n    GetRejectedMeta<ThunkApiConfig>?,\n  ],\n  GetRejectValue<ThunkApiConfig> | undefined,\n  string,\n  GetSerializedErrorType<ThunkApiConfig>,\n  {\n    arg: ThunkArg\n    requestId: string\n    requestStatus: 'rejected'\n    aborted: boolean\n    condition: boolean\n  } & (\n    | ({ rejectedWithValue: false } & {\n        [K in keyof GetRejectedMeta<ThunkApiConfig>]?: undefined\n      })\n    | ({ rejectedWithValue: true } & GetRejectedMeta<ThunkApiConfig>)\n  )\n>\n\nexport type AsyncThunkFulfilledActionCreator<\n  Returned,\n  ThunkArg,\n  ThunkApiConfig = {},\n> = ActionCreatorWithPreparedPayload<\n  [Returned, string, ThunkArg, GetFulfilledMeta<ThunkApiConfig>?],\n  Returned,\n  string,\n  never,\n  {\n    arg: ThunkArg\n    requestId: string\n    requestStatus: 'fulfilled'\n  } & GetFulfilledMeta<ThunkApiConfig>\n>\n\n/**\n * A type describing the return value of `createAsyncThunk`.\n * Might be useful for wrapping `createAsyncThunk` in custom abstractions.\n *\n * @public\n */\nexport type AsyncThunk<\n  Returned,\n  ThunkArg,\n  ThunkApiConfig extends AsyncThunkConfig,\n> = AsyncThunkActionCreator<Returned, ThunkArg, ThunkApiConfig> & {\n  pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig>\n  rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>\n  fulfilled: AsyncThunkFulfilledActionCreator<\n    Returned,\n    ThunkArg,\n    ThunkApiConfig\n  >\n  // matchSettled?\n  settled: (\n    action: any,\n  ) => action is ReturnType<\n    | AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig>\n    | AsyncThunkFulfilledActionCreator<Returned, ThunkArg, ThunkApiConfig>\n  >\n  typePrefix: string\n}\n\nexport type OverrideThunkApiConfigs<OldConfig, NewConfig> = Id<\n  NewConfig & Omit<OldConfig, keyof NewConfig>\n>\n\nexport type CreateAsyncThunkFunction<\n  CurriedThunkApiConfig extends AsyncThunkConfig,\n> = {\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  // separate signature without `AsyncThunkConfig` for better inference\n  <Returned, ThunkArg = void>(\n    typePrefix: string,\n    payloadCreator: AsyncThunkPayloadCreator<\n      Returned,\n      ThunkArg,\n      CurriedThunkApiConfig\n    >,\n    options?: AsyncThunkOptions<ThunkArg, CurriedThunkApiConfig>,\n  ): AsyncThunk<Returned, ThunkArg, CurriedThunkApiConfig>\n\n  /**\n   *\n   * @param typePrefix\n   * @param payloadCreator\n   * @param options\n   *\n   * @public\n   */\n  <Returned, ThunkArg, ThunkApiConfig extends AsyncThunkConfig>(\n    typePrefix: string,\n    payloadCreator: AsyncThunkPayloadCreator<\n      Returned,\n      ThunkArg,\n      OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>\n    >,\n    options?: AsyncThunkOptions<\n      ThunkArg,\n      OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>\n    >,\n  ): AsyncThunk<\n    Returned,\n    ThunkArg,\n    OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>\n  >\n}\n\ntype CreateAsyncThunk<CurriedThunkApiConfig extends AsyncThunkConfig> =\n  CreateAsyncThunkFunction<CurriedThunkApiConfig> & {\n    withTypes<ThunkApiConfig extends AsyncThunkConfig>(): CreateAsyncThunk<\n      OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>\n    >\n  }\n\nconst externalAbortMessage = 'External signal was aborted'\n\nexport const createAsyncThunk = /* @__PURE__ */ (() => {\n  function createAsyncThunk<\n    Returned,\n    ThunkArg,\n    ThunkApiConfig extends AsyncThunkConfig,\n  >(\n    typePrefix: string,\n    payloadCreator: AsyncThunkPayloadCreator<\n      Returned,\n      ThunkArg,\n      ThunkApiConfig\n    >,\n    options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>,\n  ): AsyncThunk<Returned, ThunkArg, ThunkApiConfig> {\n    type RejectedValue = GetRejectValue<ThunkApiConfig>\n    type PendingMeta = GetPendingMeta<ThunkApiConfig>\n    type FulfilledMeta = GetFulfilledMeta<ThunkApiConfig>\n    type RejectedMeta = GetRejectedMeta<ThunkApiConfig>\n\n    const fulfilled: AsyncThunkFulfilledActionCreator<\n      Returned,\n      ThunkArg,\n      ThunkApiConfig\n    > = createAction(\n      typePrefix + '/fulfilled',\n      (\n        payload: Returned,\n        requestId: string,\n        arg: ThunkArg,\n        meta?: FulfilledMeta,\n      ) => ({\n        payload,\n        meta: {\n          ...((meta as any) || {}),\n          arg,\n          requestId,\n          requestStatus: 'fulfilled' as const,\n        },\n      }),\n    )\n\n    const pending: AsyncThunkPendingActionCreator<ThunkArg, ThunkApiConfig> =\n      createAction(\n        typePrefix + '/pending',\n        (requestId: string, arg: ThunkArg, meta?: PendingMeta) => ({\n          payload: undefined,\n          meta: {\n            ...((meta as any) || {}),\n            arg,\n            requestId,\n            requestStatus: 'pending' as const,\n          },\n        }),\n      )\n\n    const rejected: AsyncThunkRejectedActionCreator<ThunkArg, ThunkApiConfig> =\n      createAction(\n        typePrefix + '/rejected',\n        (\n          error: Error | null,\n          requestId: string,\n          arg: ThunkArg,\n          payload?: RejectedValue,\n          meta?: RejectedMeta,\n        ) => ({\n          payload,\n          error: ((options && options.serializeError) || miniSerializeError)(\n            error || 'Rejected',\n          ) as GetSerializedErrorType<ThunkApiConfig>,\n          meta: {\n            ...((meta as any) || {}),\n            arg,\n            requestId,\n            rejectedWithValue: !!payload,\n            requestStatus: 'rejected' as const,\n            aborted: error?.name === 'AbortError',\n            condition: error?.name === 'ConditionError',\n          },\n        }),\n      )\n\n    function actionCreator(\n      arg: ThunkArg,\n      { signal }: AsyncThunkDispatchConfig = {},\n    ): AsyncThunkAction<Returned, ThunkArg, Required<ThunkApiConfig>> {\n      return (dispatch, getState, extra) => {\n        const requestId = options?.idGenerator\n          ? options.idGenerator(arg)\n          : nanoid()\n\n        const abortController = new AbortController()\n        let abortHandler: (() => void) | undefined\n        let abortReason: string | undefined\n\n        function abort(reason?: string) {\n          abortReason = reason\n          abortController.abort()\n        }\n\n        if (signal) {\n          if (signal.aborted) {\n            abort(externalAbortMessage)\n          } else {\n            signal.addEventListener(\n              'abort',\n              () => abort(externalAbortMessage),\n              { once: true },\n            )\n          }\n        }\n\n        const promise = (async function () {\n          let finalAction: ReturnType<typeof fulfilled | typeof rejected>\n          try {\n            let conditionResult = options?.condition?.(arg, { getState, extra })\n            if (isThenable(conditionResult)) {\n              conditionResult = await conditionResult\n            }\n\n            if (conditionResult === false || abortController.signal.aborted) {\n              // eslint-disable-next-line no-throw-literal\n              throw {\n                name: 'ConditionError',\n                message: 'Aborted due to condition callback returning false.',\n              }\n            }\n\n            const abortedPromise = new Promise<never>((_, reject) => {\n              abortHandler = () => {\n                reject({\n                  name: 'AbortError',\n                  message: abortReason || 'Aborted',\n                })\n              }\n              abortController.signal.addEventListener('abort', abortHandler, {\n                once: true,\n              })\n            })\n            dispatch(\n              pending(\n                requestId,\n                arg,\n                options?.getPendingMeta?.(\n                  { requestId, arg },\n                  { getState, extra },\n                ),\n              ) as any,\n            )\n            finalAction = await Promise.race([\n              abortedPromise,\n              Promise.resolve(\n                payloadCreator(arg, {\n                  dispatch,\n                  getState,\n                  extra,\n                  requestId,\n                  signal: abortController.signal,\n                  abort,\n                  rejectWithValue: ((\n                    value: RejectedValue,\n                    meta?: RejectedMeta,\n                  ) => {\n                    return new RejectWithValue(value, meta)\n                  }) as any,\n                  fulfillWithValue: ((value: unknown, meta?: FulfilledMeta) => {\n                    return new FulfillWithMeta(value, meta)\n                  }) as any,\n                }),\n              ).then((result) => {\n                if (result instanceof RejectWithValue) {\n                  throw result\n                }\n                if (result instanceof FulfillWithMeta) {\n                  return fulfilled(result.payload, requestId, arg, result.meta)\n                }\n                return fulfilled(result as any, requestId, arg)\n              }),\n            ])\n          } catch (err) {\n            finalAction =\n              err instanceof RejectWithValue\n                ? rejected(null, requestId, arg, err.payload, err.meta)\n                : rejected(err as any, requestId, arg)\n          } finally {\n            if (abortHandler) {\n              abortController.signal.removeEventListener('abort', abortHandler)\n            }\n          }\n          // We dispatch the result action _after_ the catch, to avoid having any errors\n          // here get swallowed by the try/catch block,\n          // per https://twitter.com/dan_abramov/status/770914221638942720\n          // and https://github.com/reduxjs/redux-toolkit/blob/e85eb17b39a2118d859f7b7746e0f3fee523e089/docs/tutorials/advanced-tutorial.md#async-error-handling-logic-in-thunks\n\n          const skipDispatch =\n            options &&\n            !options.dispatchConditionRejection &&\n            rejected.match(finalAction) &&\n            (finalAction as any).meta.condition\n\n          if (!skipDispatch) {\n            dispatch(finalAction as any)\n          }\n          return finalAction\n        })()\n        return Object.assign(promise as SafePromise<any>, {\n          abort,\n          requestId,\n          arg,\n          unwrap() {\n            return promise.then<any>(unwrapResult)\n          },\n        })\n      }\n    }\n\n    return Object.assign(\n      actionCreator as AsyncThunkActionCreator<\n        Returned,\n        ThunkArg,\n        ThunkApiConfig\n      >,\n      {\n        pending,\n        rejected,\n        fulfilled,\n        settled: isAnyOf(rejected, fulfilled),\n        typePrefix,\n      },\n    )\n  }\n  createAsyncThunk.withTypes = () => createAsyncThunk\n\n  return createAsyncThunk as CreateAsyncThunk<AsyncThunkConfig>\n})()\n\ninterface UnwrappableAction {\n  payload: any\n  meta?: any\n  error?: any\n}\n\ntype UnwrappedActionPayload<T extends UnwrappableAction> = Exclude<\n  T,\n  { error: any }\n>['payload']\n\n/**\n * @public\n */\nexport function unwrapResult<R extends UnwrappableAction>(\n  action: R,\n): UnwrappedActionPayload<R> {\n  if (action.meta && action.meta.rejectedWithValue) {\n    throw action.payload\n  }\n  if (action.error) {\n    throw action.error\n  }\n  return action.payload\n}\n\ntype WithStrictNullChecks<True, False> = undefined extends boolean\n  ? False\n  : True\n\nfunction isThenable(value: any): value is PromiseLike<any> {\n  return (\n    value !== null &&\n    typeof value === 'object' &&\n    typeof value.then === 'function'\n  )\n}\n"
  },
  {
    "path": "packages/toolkit/src/createDraftSafeSelector.ts",
    "content": "import { current, isDraft } from './immerImports'\nimport { createSelectorCreator, weakMapMemoize } from './reselectImports'\n\nexport const createDraftSafeSelectorCreator: typeof createSelectorCreator = (\n  ...args: unknown[]\n) => {\n  const createSelector = (createSelectorCreator as any)(...args)\n  const createDraftSafeSelector = Object.assign(\n    (...args: unknown[]) => {\n      const selector = createSelector(...args)\n      const wrappedSelector = (value: unknown, ...rest: unknown[]) =>\n        selector(isDraft(value) ? current(value) : value, ...rest)\n      Object.assign(wrappedSelector, selector)\n      return wrappedSelector as any\n    },\n    { withTypes: () => createDraftSafeSelector },\n  )\n  return createDraftSafeSelector\n}\n\n/**\n * \"Draft-Safe\" version of `reselect`'s `createSelector`:\n * If an `immer`-drafted object is passed into the resulting selector's first argument,\n * the selector will act on the current draft value, instead of returning a cached value\n * that might be possibly outdated if the draft has been modified since.\n * @public\n */\nexport const createDraftSafeSelector =\n  /* @__PURE__ */\n  createDraftSafeSelectorCreator(weakMapMemoize)\n"
  },
  {
    "path": "packages/toolkit/src/createReducer.ts",
    "content": "import type { Draft } from 'immer'\nimport {\n  createNextState,\n  isDraft,\n  isDraftable,\n  setUseStrictIteration,\n} from './immerImports'\nimport type { Action, Reducer, UnknownAction } from 'redux'\nimport type { ActionReducerMapBuilder } from './mapBuilders'\nimport { executeReducerBuilderCallback } from './mapBuilders'\nimport type { NoInfer, TypeGuard } from './tsHelpers'\nimport { freezeDraftable } from './utils'\n\n/**\n * Defines a mapping from action types to corresponding action object shapes.\n *\n * @deprecated This should not be used manually - it is only used for internal\n *             inference purposes and should not have any further value.\n *             It might be removed in the future.\n * @public\n */\nexport type Actions<T extends keyof any = string> = Record<T, Action>\n\nexport type ActionMatcherDescription<S, A extends Action> = {\n  matcher: TypeGuard<A>\n  reducer: CaseReducer<S, NoInfer<A>>\n}\n\nexport type ReadonlyActionMatcherDescriptionCollection<S> = ReadonlyArray<\n  ActionMatcherDescription<S, any>\n>\n\nexport type ActionMatcherDescriptionCollection<S> = Array<\n  ActionMatcherDescription<S, any>\n>\n\n/**\n * A *case reducer* is a reducer function for a specific action type. Case\n * reducers can be composed to full reducers using `createReducer()`.\n *\n * Unlike a normal Redux reducer, a case reducer is never called with an\n * `undefined` state to determine the initial state. Instead, the initial\n * state is explicitly specified as an argument to `createReducer()`.\n *\n * In addition, a case reducer can choose to mutate the passed-in `state`\n * value directly instead of returning a new state. This does not actually\n * cause the store state to be mutated directly; instead, thanks to\n * [immer](https://github.com/mweststrate/immer), the mutations are\n * translated to copy operations that result in a new state.\n *\n * @public\n */\nexport type CaseReducer<S = any, A extends Action = UnknownAction> = (\n  state: Draft<S>,\n  action: A,\n) => NoInfer<S> | void | Draft<NoInfer<S>>\n\n/**\n * A mapping from action types to case reducers for `createReducer()`.\n *\n * @deprecated This should not be used manually - it is only used\n *             for internal inference purposes and using it manually\n *             would lead to type erasure.\n *             It might be removed in the future.\n * @public\n */\nexport type CaseReducers<S, AS extends Actions> = {\n  [T in keyof AS]: AS[T] extends Action ? CaseReducer<S, AS[T]> : void\n}\n\nexport type NotFunction<T> = T extends Function ? never : T\n\nfunction isStateFunction<S>(x: unknown): x is () => S {\n  return typeof x === 'function'\n}\n\nexport type ReducerWithInitialState<S extends NotFunction<any>> = Reducer<S> & {\n  getInitialState: () => S\n}\n\n/**\n * A utility function that allows defining a reducer as a mapping from action\n * type to *case reducer* functions that handle these action types. The\n * reducer's initial state is passed as the first argument.\n *\n * @remarks\n * The body of every case reducer is implicitly wrapped with a call to\n * `produce()` from the [immer](https://github.com/mweststrate/immer) library.\n * This means that rather than returning a new state object, you can also\n * mutate the passed-in state object directly; these mutations will then be\n * automatically and efficiently translated into copies, giving you both\n * convenience and immutability.\n *\n * @overloadSummary\n * This function accepts a callback that receives a `builder` object as its argument.\n * That builder provides `addCase`, `addMatcher` and `addDefaultCase` functions that may be\n * called to define what actions this reducer will handle.\n *\n * @param initialState - `State | (() => State)`: The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n * @param builderCallback - `(builder: Builder) => void` A callback that receives a *builder* object to define\n *   case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n * @example\n * ```ts\n * import type { PayloadAction, UnknownAction } from '@reduxjs/toolkit';\n * import { createAction, createReducer } from '@reduxjs/toolkit';\n *\n * const increment = createAction<number>('increment');\n * const decrement = createAction<number>('decrement');\n *\n * function isActionWithNumberPayload(\n *   action: UnknownAction,\n * ): action is PayloadAction<number> {\n *   return typeof action.payload === 'number';\n * }\n *\n * const reducer = createReducer(\n *   {\n *     counter: 0,\n *     sumOfNumberPayloads: 0,\n *     unhandledActions: 0,\n *   },\n *   (builder) => {\n *     builder\n *       .addCase(increment, (state, action) => {\n *         // action is inferred correctly here\n *         state.counter += action.payload;\n *       })\n *       // You can chain calls, or have separate `builder.addCase()` lines each time\n *       .addCase(decrement, (state, action) => {\n *         state.counter -= action.payload;\n *       })\n *       // You can apply a \"matcher function\" to incoming actions\n *       .addMatcher(isActionWithNumberPayload, (state, action) => {})\n *       // and provide a default case if no other handlers matched\n *       .addDefaultCase((state, action) => {});\n *   },\n * );\n * ```\n * @public\n */\nexport function createReducer<S extends NotFunction<any>>(\n  initialState: S | (() => S),\n  mapOrBuilderCallback: (builder: ActionReducerMapBuilder<S>) => void,\n): ReducerWithInitialState<S> {\n  if (process.env.NODE_ENV !== 'production') {\n    if (typeof mapOrBuilderCallback === 'object') {\n      throw new Error(\n        \"The object notation for `createReducer` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createReducer\",\n      )\n    }\n  }\n\n  let [actionsMap, finalActionMatchers, finalDefaultCaseReducer] =\n    executeReducerBuilderCallback(mapOrBuilderCallback)\n\n  // Ensure the initial state gets frozen either way (if draftable)\n  let getInitialState: () => S\n  if (isStateFunction(initialState)) {\n    getInitialState = () => freezeDraftable(initialState())\n  } else {\n    const frozenInitialState = freezeDraftable(initialState)\n    getInitialState = () => frozenInitialState\n  }\n\n  function reducer(state = getInitialState(), action: any): S {\n    let caseReducers = [\n      actionsMap[action.type],\n      ...finalActionMatchers\n        .filter(({ matcher }) => matcher(action))\n        .map(({ reducer }) => reducer),\n    ]\n    if (caseReducers.filter((cr) => !!cr).length === 0) {\n      caseReducers = [finalDefaultCaseReducer]\n    }\n\n    return caseReducers.reduce((previousState, caseReducer): S => {\n      if (caseReducer) {\n        if (isDraft(previousState)) {\n          // If it's already a draft, we must already be inside a `createNextState` call,\n          // likely because this is being wrapped in `createReducer`, `createSlice`, or nested\n          // inside an existing draft. It's safe to just pass the draft to the mutator.\n          const draft = previousState as Draft<S> // We can assume this is already a draft\n          const result = caseReducer(draft, action)\n\n          if (result === undefined) {\n            return previousState\n          }\n\n          return result as S\n        } else if (!isDraftable(previousState)) {\n          // If state is not draftable (ex: a primitive, such as 0), we want to directly\n          // return the caseReducer func and not wrap it with produce.\n          const result = caseReducer(previousState as any, action)\n\n          if (result === undefined) {\n            if (previousState === null) {\n              return previousState\n            }\n            throw Error(\n              'A case reducer on a non-draftable value must not return undefined',\n            )\n          }\n\n          return result as S\n        } else {\n          // @ts-ignore createNextState() produces an Immutable<Draft<S>> rather\n          // than an Immutable<S>, and TypeScript cannot find out how to reconcile\n          // these two types.\n          return createNextState(previousState, (draft: Draft<S>) => {\n            return caseReducer(draft, action)\n          })\n        }\n      }\n\n      return previousState\n    }, state)\n  }\n\n  reducer.getInitialState = getInitialState\n\n  return reducer as ReducerWithInitialState<S>\n}\n"
  },
  {
    "path": "packages/toolkit/src/createSlice.ts",
    "content": "import type { Action, Reducer, UnknownAction } from 'redux'\nimport type { Selector } from 'reselect'\nimport type { InjectConfig } from './combineSlices'\nimport type {\n  ActionCreatorWithoutPayload,\n  PayloadAction,\n  PayloadActionCreator,\n  PrepareAction,\n  _ActionCreatorWithPreparedPayload,\n} from './createAction'\nimport { createAction } from './createAction'\nimport type {\n  AsyncThunk,\n  AsyncThunkConfig,\n  AsyncThunkOptions,\n  AsyncThunkPayloadCreator,\n  OverrideThunkApiConfigs,\n} from './createAsyncThunk'\nimport { createAsyncThunk as _createAsyncThunk } from './createAsyncThunk'\nimport type {\n  ActionMatcherDescriptionCollection,\n  CaseReducer,\n  ReducerWithInitialState,\n} from './createReducer'\nimport { createReducer } from './createReducer'\nimport type {\n  ActionReducerMapBuilder,\n  AsyncThunkReducers,\n  TypedActionCreator,\n} from './mapBuilders'\nimport { executeReducerBuilderCallback } from './mapBuilders'\nimport type { Id, TypeGuard } from './tsHelpers'\nimport { getOrInsertComputed } from './utils'\n\nconst asyncThunkSymbol = /* @__PURE__ */ Symbol.for(\n  'rtk-slice-createasyncthunk',\n)\n// type is annotated because it's too long to infer\nexport const asyncThunkCreator: {\n  [asyncThunkSymbol]: typeof _createAsyncThunk\n} = {\n  [asyncThunkSymbol]: _createAsyncThunk,\n}\n\ntype InjectIntoConfig<NewReducerPath extends string> = InjectConfig & {\n  reducerPath?: NewReducerPath\n}\n\n/**\n * The return value of `createSlice`\n *\n * @public\n */\nexport interface Slice<\n  State = any,\n  CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>,\n  Name extends string = string,\n  ReducerPath extends string = Name,\n  Selectors extends SliceSelectors<State> = SliceSelectors<State>,\n> {\n  /**\n   * The slice name.\n   */\n  name: Name\n\n  /**\n   *  The slice reducer path.\n   */\n  reducerPath: ReducerPath\n\n  /**\n   * The slice's reducer.\n   */\n  reducer: Reducer<State>\n\n  /**\n   * Action creators for the types of actions that are handled by the slice\n   * reducer.\n   */\n  actions: CaseReducerActions<CaseReducers, Name>\n\n  /**\n   * The individual case reducer functions that were passed in the `reducers` parameter.\n   * This enables reuse and testing if they were defined inline when calling `createSlice`.\n   */\n  caseReducers: SliceDefinedCaseReducers<CaseReducers>\n\n  /**\n   * Provides access to the initial state value given to the slice.\n   * If a lazy state initializer was provided, it will be called and a fresh value returned.\n   */\n  getInitialState: () => State\n\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State>>\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(\n    selectState: (rootState: RootState) => State,\n  ): Id<SliceDefinedSelectors<State, Selectors, RootState>>\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.reducerPath]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.reducerPath])`.\n   */\n  get selectors(): Id<\n    SliceDefinedSelectors<State, Selectors, { [K in ReducerPath]: State }>\n  >\n\n  /**\n   * Inject slice into provided reducer (return value from `combineSlices`), and return injected slice.\n   */\n  injectInto<NewReducerPath extends string = ReducerPath>(\n    this: this,\n    injectable: {\n      inject: (\n        slice: { reducerPath: string; reducer: Reducer },\n        config?: InjectConfig,\n      ) => void\n    },\n    config?: InjectIntoConfig<NewReducerPath>,\n  ): InjectedSlice<State, CaseReducers, Name, NewReducerPath, Selectors>\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Will throw an error if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]: State }): State\n}\n\n/**\n * A slice after being called with `injectInto(reducer)`.\n *\n * Selectors can now be called with an `undefined` value, in which case they use the slice's initial state.\n */\ntype InjectedSlice<\n  State = any,\n  CaseReducers extends SliceCaseReducers<State> = SliceCaseReducers<State>,\n  Name extends string = string,\n  ReducerPath extends string = Name,\n  Selectors extends SliceSelectors<State> = SliceSelectors<State>,\n> = Omit<\n  Slice<State, CaseReducers, Name, ReducerPath, Selectors>,\n  'getSelectors' | 'selectors'\n> & {\n  /**\n   * Get localised slice selectors (expects to be called with *just* the slice's state as the first parameter)\n   */\n  getSelectors(): Id<SliceDefinedSelectors<State, Selectors, State | undefined>>\n\n  /**\n   * Get globalised slice selectors (`selectState` callback is expected to receive first parameter and return slice state)\n   */\n  getSelectors<RootState>(\n    selectState: (rootState: RootState) => State | undefined,\n  ): Id<SliceDefinedSelectors<State, Selectors, RootState>>\n\n  /**\n   * Selectors that assume the slice's state is `rootState[slice.name]` (which is usually the case)\n   *\n   * Equivalent to `slice.getSelectors((state: RootState) => state[slice.name])`.\n   */\n  get selectors(): Id<\n    SliceDefinedSelectors<\n      State,\n      Selectors,\n      { [K in ReducerPath]?: State | undefined }\n    >\n  >\n\n  /**\n   * Select the slice state, using the slice's current reducerPath.\n   *\n   * Returns initial state if slice is not found.\n   */\n  selectSlice(state: { [K in ReducerPath]?: State | undefined }): State\n}\n\n/**\n * Options for `createSlice()`.\n *\n * @public\n */\nexport interface CreateSliceOptions<\n  State = any,\n  CR extends SliceCaseReducers<State> = SliceCaseReducers<State>,\n  Name extends string = string,\n  ReducerPath extends string = Name,\n  Selectors extends SliceSelectors<State> = SliceSelectors<State>,\n> {\n  /**\n   * The slice's name. Used to namespace the generated action types.\n   */\n  name: Name\n\n  /**\n   * The slice's reducer path. Used when injecting into a combined slice reducer.\n   */\n  reducerPath?: ReducerPath\n\n  /**\n   * The initial state that should be used when the reducer is called the first time. This may also be a \"lazy initializer\" function, which should return an initial state value when called. This will be used whenever the reducer is called with `undefined` as its state value, and is primarily useful for cases like reading initial state from `localStorage`.\n   */\n  initialState: State | (() => State)\n\n  /**\n   * A mapping from action types to action-type-specific *case reducer*\n   * functions. For every action type, a matching action creator will be\n   * generated using `createAction()`.\n   */\n  reducers:\n    | ValidateSliceCaseReducers<State, CR>\n    | ((creators: ReducerCreators<State>) => CR)\n\n  /**\n   * A callback that receives a *builder* object to define\n   * case reducers via calls to `builder.addCase(actionCreatorOrType, reducer)`.\n   *\n   *\n   * @example\n   * ```ts\n   * import type { Action } from '@reduxjs/toolkit';\n   * import { createAction, createSlice } from '@reduxjs/toolkit';\n   *\n   * const incrementBy = createAction<number>('incrementBy');\n   * const decrement = createAction('decrement');\n   *\n   * interface RejectedAction extends Action {\n   *   error: Error;\n   * }\n   *\n   * function isRejectedAction(action: Action): action is RejectedAction {\n   *   return action.type.endsWith('rejected');\n   * }\n   *\n   * createSlice({\n   *   name: 'counter',\n   *   initialState: 0,\n   *   reducers: {},\n   *   extraReducers: (builder) => {\n   *     builder\n   *       .addCase(incrementBy, (state, action) => {\n   *         // action is inferred correctly here if using TS\n   *       })\n   *       // You can chain calls, or have separate `builder.addCase()` lines each time\n   *       .addCase(decrement, (state, action) => {})\n   *       // You can match a range of action types\n   *       .addMatcher(\n   *         isRejectedAction,\n   *         // `action` will be inferred as a RejectedAction due to isRejectedAction being defined as a type guard\n   *         (state, action) => {},\n   *       )\n   *       // and provide a default case if no other handlers matched\n   *       .addDefaultCase((state, action) => {});\n   *   },\n   * });\n   * ```\n   */\n  extraReducers?: (builder: ActionReducerMapBuilder<State>) => void\n\n  /**\n   * A map of selectors that receive the slice's state and any additional arguments, and return a result.\n   */\n  selectors?: Selectors\n}\n\nexport enum ReducerType {\n  reducer = 'reducer',\n  reducerWithPrepare = 'reducerWithPrepare',\n  asyncThunk = 'asyncThunk',\n}\n\ntype ReducerDefinition<T extends ReducerType = ReducerType> = {\n  _reducerDefinitionType: T\n}\n\nexport type CaseReducerDefinition<\n  S = any,\n  A extends Action = UnknownAction,\n> = CaseReducer<S, A> & ReducerDefinition<ReducerType.reducer>\n\n/**\n * A CaseReducer with a `prepare` method.\n *\n * @public\n */\nexport type CaseReducerWithPrepare<State, Action extends PayloadAction> = {\n  reducer: CaseReducer<State, Action>\n  prepare: PrepareAction<Action['payload']>\n}\n\nexport interface CaseReducerWithPrepareDefinition<\n  State,\n  Action extends PayloadAction,\n> extends CaseReducerWithPrepare<State, Action>,\n    ReducerDefinition<ReducerType.reducerWithPrepare> {}\n\ntype AsyncThunkSliceReducerConfig<\n  State,\n  ThunkArg extends any,\n  Returned = unknown,\n  ThunkApiConfig extends AsyncThunkConfig = {},\n> = AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig> & {\n  options?: AsyncThunkOptions<ThunkArg, ThunkApiConfig>\n}\n\ntype AsyncThunkSliceReducerDefinition<\n  State,\n  ThunkArg extends any,\n  Returned = unknown,\n  ThunkApiConfig extends AsyncThunkConfig = {},\n> = AsyncThunkSliceReducerConfig<State, ThunkArg, Returned, ThunkApiConfig> &\n  ReducerDefinition<ReducerType.asyncThunk> & {\n    payloadCreator: AsyncThunkPayloadCreator<Returned, ThunkArg, ThunkApiConfig>\n  }\n\n/**\n * Providing these as part of the config would cause circular types, so we disallow passing them\n */\ntype PreventCircular<ThunkApiConfig> = {\n  [K in keyof ThunkApiConfig]: K extends 'state' | 'dispatch'\n    ? never\n    : ThunkApiConfig[K]\n}\n\ninterface AsyncThunkCreator<\n  State,\n  CurriedThunkApiConfig extends\n    PreventCircular<AsyncThunkConfig> = PreventCircular<AsyncThunkConfig>,\n> {\n  <Returned, ThunkArg = void>(\n    payloadCreator: AsyncThunkPayloadCreator<\n      Returned,\n      ThunkArg,\n      CurriedThunkApiConfig\n    >,\n    config?: AsyncThunkSliceReducerConfig<\n      State,\n      ThunkArg,\n      Returned,\n      CurriedThunkApiConfig\n    >,\n  ): AsyncThunkSliceReducerDefinition<\n    State,\n    ThunkArg,\n    Returned,\n    CurriedThunkApiConfig\n  >\n  <\n    Returned,\n    ThunkArg,\n    ThunkApiConfig extends PreventCircular<AsyncThunkConfig> = {},\n  >(\n    payloadCreator: AsyncThunkPayloadCreator<\n      Returned,\n      ThunkArg,\n      ThunkApiConfig\n    >,\n    config?: AsyncThunkSliceReducerConfig<\n      State,\n      ThunkArg,\n      Returned,\n      ThunkApiConfig\n    >,\n  ): AsyncThunkSliceReducerDefinition<State, ThunkArg, Returned, ThunkApiConfig>\n  withTypes<\n    ThunkApiConfig extends PreventCircular<AsyncThunkConfig>,\n  >(): AsyncThunkCreator<\n    State,\n    OverrideThunkApiConfigs<CurriedThunkApiConfig, ThunkApiConfig>\n  >\n}\n\nexport interface ReducerCreators<State> {\n  reducer(\n    caseReducer: CaseReducer<State, PayloadAction>,\n  ): CaseReducerDefinition<State, PayloadAction>\n  reducer<Payload>(\n    caseReducer: CaseReducer<State, PayloadAction<Payload>>,\n  ): CaseReducerDefinition<State, PayloadAction<Payload>>\n\n  asyncThunk: AsyncThunkCreator<State>\n\n  preparedReducer<Prepare extends PrepareAction<any>>(\n    prepare: Prepare,\n    reducer: CaseReducer<\n      State,\n      ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>\n    >,\n  ): {\n    _reducerDefinitionType: ReducerType.reducerWithPrepare\n    prepare: Prepare\n    reducer: CaseReducer<\n      State,\n      ReturnType<_ActionCreatorWithPreparedPayload<Prepare>>\n    >\n  }\n}\n\n/**\n * The type describing a slice's `reducers` option.\n *\n * @public\n */\nexport type SliceCaseReducers<State> =\n  | Record<string, ReducerDefinition>\n  | Record<\n      string,\n      | CaseReducer<State, PayloadAction<any>>\n      | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>\n    >\n\n/**\n * The type describing a slice's `selectors` option.\n */\nexport type SliceSelectors<State> = {\n  [K: string]: (sliceState: State, ...args: any[]) => any\n}\n\ntype SliceActionType<\n  SliceName extends string,\n  ActionName extends keyof any,\n> = ActionName extends string | number ? `${SliceName}/${ActionName}` : string\n\n/**\n * Derives the slice's `actions` property from the `reducers` options\n *\n * @public\n */\nexport type CaseReducerActions<\n  CaseReducers extends SliceCaseReducers<any>,\n  SliceName extends string,\n> = {\n  [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition\n    ? Definition extends { prepare: any }\n      ? ActionCreatorForCaseReducerWithPrepare<\n          Definition,\n          SliceActionType<SliceName, Type>\n        >\n      : Definition extends AsyncThunkSliceReducerDefinition<\n            any,\n            infer ThunkArg,\n            infer Returned,\n            infer ThunkApiConfig\n          >\n        ? AsyncThunk<Returned, ThunkArg, ThunkApiConfig>\n        : Definition extends { reducer: any }\n          ? ActionCreatorForCaseReducer<\n              Definition['reducer'],\n              SliceActionType<SliceName, Type>\n            >\n          : ActionCreatorForCaseReducer<\n              Definition,\n              SliceActionType<SliceName, Type>\n            >\n    : never\n}\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducerWithPrepare`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducerWithPrepare<\n  CR extends { prepare: any },\n  Type extends string,\n> = _ActionCreatorWithPreparedPayload<CR['prepare'], Type>\n\n/**\n * Get a `PayloadActionCreator` type for a passed `CaseReducer`\n *\n * @internal\n */\ntype ActionCreatorForCaseReducer<CR, Type extends string> = CR extends (\n  state: any,\n  action: infer Action,\n) => any\n  ? Action extends { payload: infer P }\n    ? PayloadActionCreator<P, Type>\n    : ActionCreatorWithoutPayload<Type>\n  : ActionCreatorWithoutPayload<Type>\n\n/**\n * Extracts the CaseReducers out of a `reducers` object, even if they are\n * tested into a `CaseReducerWithPrepare`.\n *\n * @internal\n */\ntype SliceDefinedCaseReducers<CaseReducers extends SliceCaseReducers<any>> = {\n  [Type in keyof CaseReducers]: CaseReducers[Type] extends infer Definition\n    ? Definition extends AsyncThunkSliceReducerDefinition<any, any, any>\n      ? Id<\n          Pick<\n            Required<Definition>,\n            'fulfilled' | 'rejected' | 'pending' | 'settled'\n          >\n        >\n      : Definition extends {\n            reducer: infer Reducer\n          }\n        ? Reducer\n        : Definition\n    : never\n}\n\ntype RemappedSelector<S extends Selector, NewState> =\n  S extends Selector<any, infer R, infer P>\n    ? Selector<NewState, R, P> & { unwrapped: S }\n    : never\n\n/**\n * Extracts the final selector type from the `selectors` object.\n *\n * Removes the `string` index signature from the default value.\n */\ntype SliceDefinedSelectors<\n  State,\n  Selectors extends SliceSelectors<State>,\n  RootState,\n> = {\n  [K in keyof Selectors as string extends K ? never : K]: RemappedSelector<\n    Selectors[K],\n    RootState\n  >\n}\n\n/**\n * Used on a SliceCaseReducers object.\n * Ensures that if a CaseReducer is a `CaseReducerWithPrepare`, that\n * the `reducer` and the `prepare` function use the same type of `payload`.\n *\n * Might do additional such checks in the future.\n *\n * This type is only ever useful if you want to write your own wrapper around\n * `createSlice`. Please don't use it otherwise!\n *\n * @public\n */\nexport type ValidateSliceCaseReducers<\n  S,\n  ACR extends SliceCaseReducers<S>,\n> = ACR & {\n  [T in keyof ACR]: ACR[T] extends {\n    reducer(s: S, action?: infer A): any\n  }\n    ? {\n        prepare(...a: never[]): Omit<A, 'type'>\n      }\n    : {}\n}\n\nfunction getType(slice: string, actionKey: string): string {\n  return `${slice}/${actionKey}`\n}\n\ninterface BuildCreateSliceConfig {\n  creators?: {\n    asyncThunk?: typeof asyncThunkCreator\n  }\n}\n\nexport function buildCreateSlice({ creators }: BuildCreateSliceConfig = {}) {\n  const cAT = creators?.asyncThunk?.[asyncThunkSymbol]\n  return function createSlice<\n    State,\n    CaseReducers extends SliceCaseReducers<State>,\n    Name extends string,\n    Selectors extends SliceSelectors<State>,\n    ReducerPath extends string = Name,\n  >(\n    options: CreateSliceOptions<\n      State,\n      CaseReducers,\n      Name,\n      ReducerPath,\n      Selectors\n    >,\n  ): Slice<State, CaseReducers, Name, ReducerPath, Selectors> {\n    const { name, reducerPath = name as unknown as ReducerPath } = options\n    if (!name) {\n      throw new Error('`name` is a required option for createSlice')\n    }\n\n    if (\n      typeof process !== 'undefined' &&\n      process.env.NODE_ENV === 'development'\n    ) {\n      if (options.initialState === undefined) {\n        console.error(\n          'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`',\n        )\n      }\n    }\n\n    const reducers =\n      (typeof options.reducers === 'function'\n        ? options.reducers(buildReducerCreators<State>())\n        : options.reducers) || {}\n\n    const reducerNames = Object.keys(reducers)\n\n    const context: ReducerHandlingContext<State> = {\n      sliceCaseReducersByName: {},\n      sliceCaseReducersByType: {},\n      actionCreators: {},\n      sliceMatchers: [],\n    }\n\n    const contextMethods: ReducerHandlingContextMethods<State> = {\n      addCase(\n        typeOrActionCreator: string | TypedActionCreator<any>,\n        reducer: CaseReducer<State>,\n      ) {\n        const type =\n          typeof typeOrActionCreator === 'string'\n            ? typeOrActionCreator\n            : typeOrActionCreator.type\n        if (!type) {\n          throw new Error(\n            '`context.addCase` cannot be called with an empty action type',\n          )\n        }\n        if (type in context.sliceCaseReducersByType) {\n          throw new Error(\n            '`context.addCase` cannot be called with two reducers for the same action type: ' +\n              type,\n          )\n        }\n        context.sliceCaseReducersByType[type] = reducer\n        return contextMethods\n      },\n      addMatcher(matcher, reducer) {\n        context.sliceMatchers.push({ matcher, reducer })\n        return contextMethods\n      },\n      exposeAction(name, actionCreator) {\n        context.actionCreators[name] = actionCreator\n        return contextMethods\n      },\n      exposeCaseReducer(name, reducer) {\n        context.sliceCaseReducersByName[name] = reducer\n        return contextMethods\n      },\n    }\n\n    reducerNames.forEach((reducerName) => {\n      const reducerDefinition = reducers[reducerName]\n      const reducerDetails: ReducerDetails = {\n        reducerName,\n        type: getType(name, reducerName),\n        createNotation: typeof options.reducers === 'function',\n      }\n      if (isAsyncThunkSliceReducerDefinition<State>(reducerDefinition)) {\n        handleThunkCaseReducerDefinition(\n          reducerDetails,\n          reducerDefinition,\n          contextMethods,\n          cAT,\n        )\n      } else {\n        handleNormalReducerDefinition<State>(\n          reducerDetails,\n          reducerDefinition as any,\n          contextMethods,\n        )\n      }\n    })\n\n    function buildReducer() {\n      if (process.env.NODE_ENV !== 'production') {\n        if (typeof options.extraReducers === 'object') {\n          throw new Error(\n            \"The object notation for `createSlice.extraReducers` has been removed. Please use the 'builder callback' notation instead: https://redux-toolkit.js.org/api/createSlice\",\n          )\n        }\n      }\n      const [\n        extraReducers = {},\n        actionMatchers = [],\n        defaultCaseReducer = undefined,\n      ] =\n        typeof options.extraReducers === 'function'\n          ? executeReducerBuilderCallback(options.extraReducers)\n          : [options.extraReducers]\n\n      const finalCaseReducers = {\n        ...extraReducers,\n        ...context.sliceCaseReducersByType,\n      }\n\n      return createReducer(options.initialState, (builder) => {\n        for (let key in finalCaseReducers) {\n          builder.addCase(key, finalCaseReducers[key] as CaseReducer<any>)\n        }\n        for (let sM of context.sliceMatchers) {\n          builder.addMatcher(sM.matcher, sM.reducer)\n        }\n        for (let m of actionMatchers) {\n          builder.addMatcher(m.matcher, m.reducer)\n        }\n        if (defaultCaseReducer) {\n          builder.addDefaultCase(defaultCaseReducer)\n        }\n      })\n    }\n\n    const selectSelf = (state: State) => state\n\n    const injectedSelectorCache = new Map<\n      boolean,\n      WeakMap<\n        (rootState: any) => State | undefined,\n        Record<string, (rootState: any) => any>\n      >\n    >()\n\n    const injectedStateCache = new WeakMap<(rootState: any) => State, State>()\n\n    let _reducer: ReducerWithInitialState<State>\n\n    function reducer(state: State | undefined, action: UnknownAction) {\n      if (!_reducer) _reducer = buildReducer()\n\n      return _reducer(state, action)\n    }\n\n    function getInitialState() {\n      if (!_reducer) _reducer = buildReducer()\n\n      return _reducer.getInitialState()\n    }\n\n    function makeSelectorProps<CurrentReducerPath extends string = ReducerPath>(\n      reducerPath: CurrentReducerPath,\n      injected = false,\n    ): Pick<\n      Slice<State, CaseReducers, Name, CurrentReducerPath, Selectors>,\n      'getSelectors' | 'selectors' | 'selectSlice' | 'reducerPath'\n    > {\n      function selectSlice(state: { [K in CurrentReducerPath]: State }) {\n        let sliceState = state[reducerPath]\n        if (typeof sliceState === 'undefined') {\n          if (injected) {\n            sliceState = getOrInsertComputed(\n              injectedStateCache,\n              selectSlice,\n              getInitialState,\n            )\n          } else if (process.env.NODE_ENV !== 'production') {\n            throw new Error(\n              'selectSlice returned undefined for an uninjected slice reducer',\n            )\n          }\n        }\n        return sliceState\n      }\n\n      function getSelectors(\n        selectState: (rootState: any) => State = selectSelf,\n      ) {\n        const selectorCache = getOrInsertComputed(\n          injectedSelectorCache,\n          injected,\n          () => new WeakMap(),\n        )\n\n        return getOrInsertComputed(selectorCache, selectState, () => {\n          const map: Record<string, Selector<any, any>> = {}\n          for (const [name, selector] of Object.entries(\n            options.selectors ?? {},\n          )) {\n            map[name] = wrapSelector(\n              selector,\n              selectState,\n              () =>\n                getOrInsertComputed(\n                  injectedStateCache,\n                  selectState,\n                  getInitialState,\n                ),\n              injected,\n            )\n          }\n          return map\n        }) as any\n      }\n      return {\n        reducerPath,\n        getSelectors,\n        get selectors() {\n          return getSelectors(selectSlice)\n        },\n        selectSlice,\n      }\n    }\n\n    const slice: Slice<State, CaseReducers, Name, ReducerPath, Selectors> = {\n      name,\n      reducer,\n      actions: context.actionCreators as any,\n      caseReducers: context.sliceCaseReducersByName as any,\n      getInitialState,\n      ...makeSelectorProps(reducerPath),\n      injectInto(injectable, { reducerPath: pathOpt, ...config } = {}) {\n        const newReducerPath = pathOpt ?? reducerPath\n        injectable.inject({ reducerPath: newReducerPath, reducer }, config)\n        return {\n          ...slice,\n          ...makeSelectorProps(newReducerPath, true),\n        } as any\n      },\n    }\n    return slice\n  }\n}\n\nfunction wrapSelector<State, NewState, S extends Selector<State>>(\n  selector: S,\n  selectState: Selector<NewState, State>,\n  getInitialState: () => State,\n  injected?: boolean,\n) {\n  function wrapper(rootState: NewState, ...args: any[]) {\n    let sliceState = selectState(rootState)\n    if (typeof sliceState === 'undefined') {\n      if (injected) {\n        sliceState = getInitialState()\n      } else if (process.env.NODE_ENV !== 'production') {\n        throw new Error(\n          'selectState returned undefined for an uninjected slice reducer',\n        )\n      }\n    }\n    return selector(sliceState, ...args)\n  }\n  wrapper.unwrapped = selector\n  return wrapper as RemappedSelector<S, NewState>\n}\n\n/**\n * A function that accepts an initial state, an object full of reducer\n * functions, and a \"slice name\", and automatically generates\n * action creators and action types that correspond to the\n * reducers and state.\n *\n * @public\n */\nexport const createSlice = /* @__PURE__ */ buildCreateSlice()\n\ninterface ReducerHandlingContext<State> {\n  sliceCaseReducersByName: Record<\n    string,\n    | CaseReducer<State, any>\n    | Pick<\n        AsyncThunkSliceReducerDefinition<State, any, any, any>,\n        'fulfilled' | 'rejected' | 'pending' | 'settled'\n      >\n  >\n  sliceCaseReducersByType: Record<string, CaseReducer<State, any>>\n  sliceMatchers: ActionMatcherDescriptionCollection<State>\n  actionCreators: Record<string, Function>\n}\n\ninterface ReducerHandlingContextMethods<State> {\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(\n    actionCreator: ActionCreator,\n    reducer: CaseReducer<State, ReturnType<ActionCreator>>,\n  ): ReducerHandlingContextMethods<State>\n  /**\n   * Adds a case reducer to handle a single action type.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(\n    type: Type,\n    reducer: CaseReducer<State, A>,\n  ): ReducerHandlingContextMethods<State>\n\n  /**\n   * Allows you to match incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   */\n  addMatcher<A>(\n    matcher: TypeGuard<A>,\n    reducer: CaseReducer<State, A extends Action ? A : A & Action>,\n  ): ReducerHandlingContextMethods<State>\n  /**\n   * Add an action to be exposed under the final `slice.actions` key.\n   * @param name The key to be exposed as.\n   * @param actionCreator The action to expose.\n   * @example\n   * ```ts\n   * context.exposeAction('addPost', createAction<Post>('addPost'));\n   *\n   * export const { addPost } = slice.actions;\n   *\n   * dispatch(addPost(post));\n   * ```\n   */\n  exposeAction(\n    name: string,\n    actionCreator: Function,\n  ): ReducerHandlingContextMethods<State>\n  /**\n   * Add a case reducer to be exposed under the final `slice.caseReducers` key.\n   * @param name The key to be exposed as.\n   * @param reducer The reducer to expose.\n   * @example\n   * ```ts\n   * context.exposeCaseReducer('addPost', (state, action: PayloadAction<Post>) => {\n   *   state.push(action.payload);\n   * });\n   *\n   * slice.caseReducers.addPost([], addPost(post));\n   * ```\n   */\n  exposeCaseReducer(\n    name: string,\n    reducer:\n      | CaseReducer<State, any>\n      | Pick<\n          AsyncThunkSliceReducerDefinition<State, any, any, any>,\n          'fulfilled' | 'rejected' | 'pending' | 'settled'\n        >,\n  ): ReducerHandlingContextMethods<State>\n}\n\ninterface ReducerDetails {\n  /** The key the reducer was defined under */\n  reducerName: string\n  /** The predefined action type, i.e. `${slice.name}/${reducerName}` */\n  type: string\n  /** Whether create. notation was used when defining reducers */\n  createNotation: boolean\n}\n\nfunction buildReducerCreators<State>(): ReducerCreators<State> {\n  function asyncThunk(\n    payloadCreator: AsyncThunkPayloadCreator<any, any>,\n    config: AsyncThunkSliceReducerConfig<State, any>,\n  ): AsyncThunkSliceReducerDefinition<State, any> {\n    return {\n      _reducerDefinitionType: ReducerType.asyncThunk,\n      payloadCreator,\n      ...config,\n    }\n  }\n  asyncThunk.withTypes = () => asyncThunk\n  return {\n    reducer(caseReducer: CaseReducer<State, any>) {\n      return Object.assign(\n        {\n          // hack so the wrapping function has the same name as the original\n          // we need to create a wrapper so the `reducerDefinitionType` is not assigned to the original\n          [caseReducer.name](...args: Parameters<typeof caseReducer>) {\n            return caseReducer(...args)\n          },\n        }[caseReducer.name],\n        {\n          _reducerDefinitionType: ReducerType.reducer,\n        } as const,\n      )\n    },\n    preparedReducer(prepare, reducer) {\n      return {\n        _reducerDefinitionType: ReducerType.reducerWithPrepare,\n        prepare,\n        reducer,\n      }\n    },\n    asyncThunk: asyncThunk as any,\n  }\n}\n\nfunction handleNormalReducerDefinition<State>(\n  { type, reducerName, createNotation }: ReducerDetails,\n  maybeReducerWithPrepare:\n    | CaseReducer<State, { payload: any; type: string }>\n    | CaseReducerWithPrepare<State, PayloadAction<any, string, any, any>>,\n  context: ReducerHandlingContextMethods<State>,\n) {\n  let caseReducer: CaseReducer<State, any>\n  let prepareCallback: PrepareAction<any> | undefined\n  if ('reducer' in maybeReducerWithPrepare) {\n    if (\n      createNotation &&\n      !isCaseReducerWithPrepareDefinition(maybeReducerWithPrepare)\n    ) {\n      throw new Error(\n        'Please use the `create.preparedReducer` notation for prepared action creators with the `create` notation.',\n      )\n    }\n    caseReducer = maybeReducerWithPrepare.reducer\n    prepareCallback = maybeReducerWithPrepare.prepare\n  } else {\n    caseReducer = maybeReducerWithPrepare\n  }\n  context\n    .addCase(type, caseReducer)\n    .exposeCaseReducer(reducerName, caseReducer)\n    .exposeAction(\n      reducerName,\n      prepareCallback\n        ? createAction(type, prepareCallback)\n        : createAction(type),\n    )\n}\n\nfunction isAsyncThunkSliceReducerDefinition<State>(\n  reducerDefinition: any,\n): reducerDefinition is AsyncThunkSliceReducerDefinition<State, any, any, any> {\n  return reducerDefinition._reducerDefinitionType === ReducerType.asyncThunk\n}\n\nfunction isCaseReducerWithPrepareDefinition<State>(\n  reducerDefinition: any,\n): reducerDefinition is CaseReducerWithPrepareDefinition<State, any> {\n  return (\n    reducerDefinition._reducerDefinitionType === ReducerType.reducerWithPrepare\n  )\n}\n\nfunction handleThunkCaseReducerDefinition<State>(\n  { type, reducerName }: ReducerDetails,\n  reducerDefinition: AsyncThunkSliceReducerDefinition<State, any, any, any>,\n  context: ReducerHandlingContextMethods<State>,\n  cAT: typeof _createAsyncThunk | undefined,\n) {\n  if (!cAT) {\n    throw new Error(\n      'Cannot use `create.asyncThunk` in the built-in `createSlice`. ' +\n        'Use `buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })` to create a customised version of `createSlice`.',\n    )\n  }\n  const { payloadCreator, fulfilled, pending, rejected, settled, options } =\n    reducerDefinition\n  const thunk = cAT(type, payloadCreator, options as any)\n  context.exposeAction(reducerName, thunk)\n\n  if (fulfilled) {\n    context.addCase(thunk.fulfilled, fulfilled)\n  }\n  if (pending) {\n    context.addCase(thunk.pending, pending)\n  }\n  if (rejected) {\n    context.addCase(thunk.rejected, rejected)\n  }\n  if (settled) {\n    context.addMatcher(thunk.settled, settled)\n  }\n\n  context.exposeCaseReducer(reducerName, {\n    fulfilled: fulfilled || noop,\n    pending: pending || noop,\n    rejected: rejected || noop,\n    settled: settled || noop,\n  })\n}\n\nfunction noop() {}\n"
  },
  {
    "path": "packages/toolkit/src/devtoolsExtension.ts",
    "content": "import type { Action, ActionCreator, StoreEnhancer } from 'redux'\nimport { compose } from './reduxImports'\n\n/**\n * @public\n */\nexport interface DevToolsEnhancerOptions {\n  /**\n   * the instance name to be showed on the monitor page. Default value is `document.title`.\n   * If not specified and there's no document title, it will consist of `tabId` and `instanceId`.\n   */\n  name?: string\n  /**\n   * action creators functions to be available in the Dispatcher.\n   */\n  actionCreators?: ActionCreator<any>[] | { [key: string]: ActionCreator<any> }\n  /**\n   * if more than one action is dispatched in the indicated interval, all new actions will be collected and sent at once.\n   * It is the joint between performance and speed. When set to `0`, all actions will be sent instantly.\n   * Set it to a higher value when experiencing perf issues (also `maxAge` to a lower value).\n   *\n   * @default 500 ms.\n   */\n  latency?: number\n  /**\n   * (> 1) - maximum allowed actions to be stored in the history tree. The oldest actions are removed once maxAge is reached. It's critical for performance.\n   *\n   * @default 50\n   */\n  maxAge?: number\n  /**\n   * Customizes how actions and state are serialized and deserialized. Can be a boolean or object. If given a boolean, the behavior is the same as if you\n   * were to pass an object and specify `options` as a boolean. Giving an object allows fine-grained customization using the `replacer` and `reviver`\n   * functions.\n   */\n  serialize?:\n    | boolean\n    | {\n        /**\n         * - `undefined` - will use regular `JSON.stringify` to send data (it's the fast mode).\n         * - `false` - will handle also circular references.\n         * - `true` - will handle also date, regex, undefined, error objects, symbols, maps, sets and functions.\n         * - object, which contains `date`, `regex`, `undefined`, `error`, `symbol`, `map`, `set` and `function` keys.\n         *   For each of them you can indicate if to include (by setting as `true`).\n         *   For `function` key you can also specify a custom function which handles serialization.\n         *   See [`jsan`](https://github.com/kolodny/jsan) for more details.\n         */\n        options?:\n          | undefined\n          | boolean\n          | {\n              date?: true\n              regex?: true\n              undefined?: true\n              error?: true\n              symbol?: true\n              map?: true\n              set?: true\n              function?: true | ((fn: (...args: any[]) => any) => string)\n            }\n        /**\n         * [JSON replacer function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify#The_replacer_parameter) used for both actions and states stringify.\n         * In addition, you can specify a data type by adding a [`__serializedType__`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/helpers/index.js#L4)\n         * key. So you can deserialize it back while importing or persisting data.\n         * Moreover, it will also [show a nice preview showing the provided custom type](https://cloud.githubusercontent.com/assets/7957859/21814330/a17d556a-d761-11e6-85ef-159dd12f36c5.png):\n         */\n        replacer?: (key: string, value: unknown) => any\n        /**\n         * [JSON `reviver` function](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse#Using_the_reviver_parameter)\n         * used for parsing the imported actions and states. See [`remotedev-serialize`](https://github.com/zalmoxisus/remotedev-serialize/blob/master/immutable/serialize.js#L8-L41)\n         * as an example on how to serialize special data types and get them back.\n         */\n        reviver?: (key: string, value: unknown) => any\n        /**\n         * Automatically serialize/deserialize immutablejs via [remotedev-serialize](https://github.com/zalmoxisus/remotedev-serialize).\n         * Just pass the Immutable library. It will support all ImmutableJS structures. You can even export them into a file and get them back.\n         * The only exception is `Record` class, for which you should pass this in addition the references to your classes in `refs`.\n         */\n        immutable?: any\n        /**\n         * ImmutableJS `Record` classes used to make possible restore its instances back when importing, persisting...\n         */\n        refs?: any\n      }\n  /**\n   * function which takes `action` object and id number as arguments, and should return `action` object back.\n   */\n  actionSanitizer?: <A extends Action>(action: A, id: number) => A\n  /**\n   * function which takes `state` object and index as arguments, and should return `state` object back.\n   */\n  stateSanitizer?: <S>(state: S, index: number) => S\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsDenylist?: string | string[]\n  /**\n   * *string or array of strings as regex* - actions types to be hidden / shown in the monitors (while passed to the reducers).\n   * If `actionsAllowlist` specified, `actionsDenylist` is ignored.\n   */\n  actionsAllowlist?: string | string[]\n  /**\n   * called for every action before sending, takes `state` and `action` object, and returns `true` in case it allows sending the current data to the monitor.\n   * Use it as a more advanced version of `actionsDenylist`/`actionsAllowlist` parameters.\n   */\n  predicate?: <S, A extends Action>(state: S, action: A) => boolean\n  /**\n   * if specified as `false`, it will not record the changes till clicking on `Start recording` button.\n   * Available only for Redux enhancer, for others use `autoPause`.\n   *\n   * @default true\n   */\n  shouldRecordChanges?: boolean\n  /**\n   * if specified, whenever clicking on `Pause recording` button and there are actions in the history log, will add this action type.\n   * If not specified, will commit when paused. Available only for Redux enhancer.\n   *\n   * @default \"@@PAUSED\"\"\n   */\n  pauseActionType?: string\n  /**\n   * auto pauses when the extension’s window is not opened, and so has zero impact on your app when not in use.\n   * Not available for Redux enhancer (as it already does it but storing the data to be sent).\n   *\n   * @default false\n   */\n  autoPause?: boolean\n  /**\n   * if specified as `true`, it will not allow any non-monitor actions to be dispatched till clicking on `Unlock changes` button.\n   * Available only for Redux enhancer.\n   *\n   * @default false\n   */\n  shouldStartLocked?: boolean\n  /**\n   * if set to `false`, will not recompute the states on hot reloading (or on replacing the reducers). Available only for Redux enhancer.\n   *\n   * @default true\n   */\n  shouldHotReload?: boolean\n  /**\n   * if specified as `true`, whenever there's an exception in reducers, the monitors will show the error message, and next actions will not be dispatched.\n   *\n   * @default false\n   */\n  shouldCatchErrors?: boolean\n  /**\n   * If you want to restrict the extension, specify the features you allow.\n   * If not specified, all of the features are enabled. When set as an object, only those included as `true` will be allowed.\n   * Note that except `true`/`false`, `import` and `export` can be set as `custom` (which is by default for Redux enhancer), meaning that the importing/exporting occurs on the client side.\n   * Otherwise, you'll get/set the data right from the monitor part.\n   */\n  features?: {\n    /**\n     * start/pause recording of dispatched actions\n     */\n    pause?: boolean\n    /**\n     * lock/unlock dispatching actions and side effects\n     */\n    lock?: boolean\n    /**\n     * persist states on page reloading\n     */\n    persist?: boolean\n    /**\n     * export history of actions in a file\n     */\n    export?: boolean | 'custom'\n    /**\n     * import history of actions from a file\n     */\n    import?: boolean | 'custom'\n    /**\n     * jump back and forth (time travelling)\n     */\n    jump?: boolean\n    /**\n     * skip (cancel) actions\n     */\n    skip?: boolean\n    /**\n     * drag and drop actions in the history list\n     */\n    reorder?: boolean\n    /**\n     * dispatch custom actions or action creators\n     */\n    dispatch?: boolean\n    /**\n     * generate tests for the selected actions\n     */\n    test?: boolean\n  }\n  /**\n   * Set to true or a stacktrace-returning function to record call stack traces for dispatched actions.\n   * Defaults to false.\n   */\n  trace?: boolean | (<A extends Action>(action: A) => string)\n  /**\n   * The maximum number of stack trace entries to record per action. Defaults to 10.\n   */\n  traceLimit?: number\n}\n\ntype Compose = typeof compose\n\ninterface ComposeWithDevTools {\n  (options: DevToolsEnhancerOptions): Compose\n  <StoreExt extends {}>(\n    ...funcs: StoreEnhancer<StoreExt>[]\n  ): StoreEnhancer<StoreExt>\n}\n\n/**\n * @public\n */\nexport const composeWithDevTools: ComposeWithDevTools =\n  typeof window !== 'undefined' &&\n  (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__\n    ? (window as any).__REDUX_DEVTOOLS_EXTENSION_COMPOSE__\n    : function () {\n        if (arguments.length === 0) return undefined\n        if (typeof arguments[0] === 'object') return compose\n        return compose.apply(null, arguments as any as Function[])\n      }\n\n/**\n * @public\n */\nexport const devToolsEnhancer: {\n  (options: DevToolsEnhancerOptions): StoreEnhancer<any>\n} =\n  typeof window !== 'undefined' && (window as any).__REDUX_DEVTOOLS_EXTENSION__\n    ? (window as any).__REDUX_DEVTOOLS_EXTENSION__\n    : function () {\n        return function (noop) {\n          return noop\n        }\n      }\n"
  },
  {
    "path": "packages/toolkit/src/dynamicMiddleware/index.ts",
    "content": "import type { Dispatch, Middleware, UnknownAction } from 'redux'\nimport { compose } from '../reduxImports'\nimport { createAction } from '../createAction'\nimport { isAllOf } from '../matchers'\nimport { nanoid } from '../nanoid'\nimport { getOrInsertComputed } from '../utils'\nimport type {\n  AddMiddleware,\n  DynamicMiddleware,\n  DynamicMiddlewareInstance,\n  MiddlewareEntry,\n  WithMiddleware,\n} from './types'\nexport type {\n  DynamicMiddlewareInstance,\n  GetDispatchType as GetDispatch,\n  MiddlewareApiConfig,\n} from './types'\n\nconst createMiddlewareEntry = <\n  State = any,\n  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,\n>(\n  middleware: Middleware<any, State, DispatchType>,\n): MiddlewareEntry<State, DispatchType> => ({\n  middleware,\n  applied: new Map(),\n})\n\nconst matchInstance =\n  (instanceId: string) =>\n  (action: any): action is { meta: { instanceId: string } } =>\n    action?.meta?.instanceId === instanceId\n\nexport const createDynamicMiddleware = <\n  State = any,\n  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,\n>(): DynamicMiddlewareInstance<State, DispatchType> => {\n  const instanceId = nanoid()\n  const middlewareMap = new Map<\n    Middleware<any, State, DispatchType>,\n    MiddlewareEntry<State, DispatchType>\n  >()\n\n  const withMiddleware = Object.assign(\n    createAction(\n      'dynamicMiddleware/add',\n      (...middlewares: Middleware<any, State, DispatchType>[]) => ({\n        payload: middlewares,\n        meta: {\n          instanceId,\n        },\n      }),\n    ),\n    { withTypes: () => withMiddleware },\n  ) as WithMiddleware<State, DispatchType>\n\n  const addMiddleware = Object.assign(\n    function addMiddleware(\n      ...middlewares: Middleware<any, State, DispatchType>[]\n    ) {\n      middlewares.forEach((middleware) => {\n        getOrInsertComputed(middlewareMap, middleware, createMiddlewareEntry)\n      })\n    },\n    { withTypes: () => addMiddleware },\n  ) as AddMiddleware<State, DispatchType>\n\n  const getFinalMiddleware: Middleware<{}, State, DispatchType> = (api) => {\n    const appliedMiddleware = Array.from(middlewareMap.values()).map((entry) =>\n      getOrInsertComputed(entry.applied, api, entry.middleware),\n    )\n    return compose(...appliedMiddleware)\n  }\n\n  const isWithMiddleware = isAllOf(withMiddleware, matchInstance(instanceId))\n\n  const middleware: DynamicMiddleware<State, DispatchType> =\n    (api) => (next) => (action) => {\n      if (isWithMiddleware(action)) {\n        addMiddleware(...action.payload)\n        return api.dispatch\n      }\n      return getFinalMiddleware(api)(next)(action)\n    }\n\n  return {\n    middleware,\n    addMiddleware,\n    withMiddleware,\n    instanceId,\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/dynamicMiddleware/react/index.ts",
    "content": "import type {\n  DynamicMiddlewareInstance,\n  GetDispatch,\n  GetState,\n  MiddlewareApiConfig,\n  TSHelpersExtractDispatchExtensions,\n} from '@reduxjs/toolkit'\nimport { createDynamicMiddleware as cDM } from '@reduxjs/toolkit'\nimport type { Context } from 'react'\nimport type { ReactReduxContextValue } from 'react-redux'\nimport {\n  createDispatchHook,\n  ReactReduxContext,\n  useDispatch as useDefaultDispatch,\n} from 'react-redux'\nimport type { Action, Dispatch, Middleware, UnknownAction } from 'redux'\n\nexport type UseDispatchWithMiddlewareHook<\n  Middlewares extends Middleware<any, State, DispatchType>[] = [],\n  State = any,\n  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,\n> = () => TSHelpersExtractDispatchExtensions<Middlewares> & DispatchType\n\nexport type CreateDispatchWithMiddlewareHook<\n  State = any,\n  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,\n> = {\n  <\n    Middlewares extends [\n      Middleware<any, State, DispatchType>,\n      ...Middleware<any, State, DispatchType>[],\n    ],\n  >(\n    ...middlewares: Middlewares\n  ): UseDispatchWithMiddlewareHook<Middlewares, State, DispatchType>\n  withTypes<\n    MiddlewareConfig extends MiddlewareApiConfig,\n  >(): CreateDispatchWithMiddlewareHook<\n    GetState<MiddlewareConfig>,\n    GetDispatch<MiddlewareConfig>\n  >\n}\n\ntype ActionFromDispatch<DispatchType extends Dispatch<Action>> =\n  DispatchType extends Dispatch<infer Action> ? Action : never\n\ntype ReactDynamicMiddlewareInstance<\n  State = any,\n  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,\n> = DynamicMiddlewareInstance<State, DispatchType> & {\n  createDispatchWithMiddlewareHookFactory: (\n    context?: Context<ReactReduxContextValue<\n      State,\n      ActionFromDispatch<DispatchType>\n    > | null>,\n  ) => CreateDispatchWithMiddlewareHook<State, DispatchType>\n  createDispatchWithMiddlewareHook: CreateDispatchWithMiddlewareHook<\n    State,\n    DispatchType\n  >\n}\n\nexport const createDynamicMiddleware = <\n  State = any,\n  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,\n>(): ReactDynamicMiddlewareInstance<State, DispatchType> => {\n  const instance = cDM<State, DispatchType>()\n  const createDispatchWithMiddlewareHookFactory = (\n    // @ts-ignore\n    context: Context<ReactReduxContextValue<\n      State,\n      ActionFromDispatch<DispatchType>\n    > | null> = ReactReduxContext,\n  ) => {\n    const useDispatch =\n      context === ReactReduxContext\n        ? useDefaultDispatch\n        : createDispatchHook(context)\n    function createDispatchWithMiddlewareHook<\n      Middlewares extends Middleware<any, State, DispatchType>[],\n    >(...middlewares: Middlewares) {\n      instance.addMiddleware(...middlewares)\n      return useDispatch\n    }\n    createDispatchWithMiddlewareHook.withTypes = () =>\n      createDispatchWithMiddlewareHook\n    return createDispatchWithMiddlewareHook as CreateDispatchWithMiddlewareHook<\n      State,\n      DispatchType\n    >\n  }\n\n  const createDispatchWithMiddlewareHook =\n    createDispatchWithMiddlewareHookFactory()\n\n  return {\n    ...instance,\n    createDispatchWithMiddlewareHookFactory,\n    createDispatchWithMiddlewareHook,\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/dynamicMiddleware/tests/index.test-d.ts",
    "content": "import type {\n  Action,\n  Middleware,\n  ThunkDispatch,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport { configureStore, createDynamicMiddleware } from '@reduxjs/toolkit'\n\nconst untypedInstance = createDynamicMiddleware()\n\ninterface AppDispatch extends ThunkDispatch<number, undefined, UnknownAction> {\n  (n: 1): 1\n}\n\nconst typedInstance = createDynamicMiddleware<number, AppDispatch>()\n\ndeclare const staticMiddleware: Middleware<(n: 1) => 1>\n\nconst store = configureStore({\n  reducer: () => 0,\n  middleware: (gDM) =>\n    gDM().prepend(typedInstance.middleware).concat(staticMiddleware),\n})\n\ndeclare const compatibleMiddleware: Middleware<{}, number, AppDispatch>\ndeclare const incompatibleMiddleware: Middleware<{}, string, AppDispatch>\n\ndeclare const addedMiddleware: Middleware<(n: 2) => 2>\n\ndescribe('type tests', () => {\n  test('instance typed at creation ensures middleware compatibility with store', () => {\n    const store = configureStore({\n      reducer: () => '',\n      // @ts-expect-error\n      middleware: (gDM) => gDM().prepend(typedInstance.middleware),\n    })\n  })\n\n  test('instance typed at creation enforces correct middleware type', () => {\n    typedInstance.addMiddleware(\n      compatibleMiddleware,\n      // @ts-expect-error\n      incompatibleMiddleware,\n    )\n\n    const dispatch = store.dispatch(\n      typedInstance.withMiddleware(\n        compatibleMiddleware,\n        // @ts-expect-error\n        incompatibleMiddleware,\n      ),\n    )\n  })\n\n  test('withTypes() enforces correct middleware type', () => {\n    const addMiddleware = untypedInstance.addMiddleware.withTypes<{\n      state: number\n      dispatch: AppDispatch\n    }>()\n\n    addMiddleware(\n      compatibleMiddleware,\n      // @ts-expect-error\n      incompatibleMiddleware,\n    )\n\n    const withMiddleware = untypedInstance.withMiddleware.withTypes<{\n      state: number\n      dispatch: AppDispatch\n    }>()\n\n    const dispatch = store.dispatch(\n      withMiddleware(\n        compatibleMiddleware,\n        // @ts-expect-error\n        incompatibleMiddleware,\n      ),\n    )\n  })\n\n  test('withMiddleware returns typed dispatch, with any applicable extensions', () => {\n    const dispatch = store.dispatch(\n      typedInstance.withMiddleware(addedMiddleware),\n    )\n\n    // standard\n    expectTypeOf(dispatch({ type: 'foo' })).toEqualTypeOf<Action<string>>()\n\n    // thunk\n    expectTypeOf(dispatch(() => 'foo')).toBeString()\n\n    // static\n    expectTypeOf(dispatch(1)).toEqualTypeOf<1>()\n\n    // added\n    expectTypeOf(dispatch(2)).toEqualTypeOf<2>()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/dynamicMiddleware/tests/index.test.ts",
    "content": "import type { Middleware, PayloadAction } from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createAction,\n  createDynamicMiddleware,\n  isAllOf,\n} from '@reduxjs/toolkit'\nimport type { BaseActionCreator } from '../../createAction'\n\nconst probeType = 'probeableMW/probe'\n\nexport interface ProbeMiddleware extends BaseActionCreator<\n  number,\n  typeof probeType\n> {\n  <Id extends number>(id: Id): PayloadAction<Id, typeof probeType>\n}\n\nexport const probeMiddleware = createAction(probeType) as ProbeMiddleware\n\nconst matchId =\n  <Id extends number>(id: Id) =>\n  (action: any): action is PayloadAction<Id> =>\n    action.payload === id\n\nexport const makeProbeableMiddleware = <Id extends number>(\n  id: Id,\n): Middleware<{\n  (action: PayloadAction<Id, typeof probeType>): Id\n}> => {\n  const isMiddlewareAction = isAllOf(probeMiddleware, matchId(id))\n  return (api) => (next) => (action) => {\n    if (isMiddlewareAction(action)) {\n      return id\n    }\n    return next(action)\n  }\n}\n\nconst staticMiddleware = makeProbeableMiddleware(1)\n\ndescribe('createDynamicMiddleware', () => {\n  it('allows injecting middleware after store instantiation', () => {\n    const dynamicInstance = createDynamicMiddleware()\n    const store = configureStore({\n      reducer: () => 0,\n      middleware: (gDM) =>\n        gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),\n    })\n    // normal, pre-inject\n    expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))\n    // static\n    expect(store.dispatch(probeMiddleware(1))).toBe(1)\n\n    // inject\n    dynamicInstance.addMiddleware(makeProbeableMiddleware(2))\n\n    // injected\n    expect(store.dispatch(probeMiddleware(2))).toBe(2)\n  })\n  it('returns dispatch when withMiddleware is dispatched', () => {\n    const dynamicInstance = createDynamicMiddleware()\n    const store = configureStore({\n      reducer: () => 0,\n      middleware: (gDM) => gDM().prepend(dynamicInstance.middleware),\n    })\n\n    // normal, pre-inject\n    expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))\n\n    const dispatch = store.dispatch(\n      dynamicInstance.withMiddleware(makeProbeableMiddleware(2)),\n    )\n    expect(dispatch).toEqual(expect.any(Function))\n\n    expect(dispatch(probeMiddleware(2))).toBe(2)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/dynamicMiddleware/tests/react.test-d.ts",
    "content": "import type {\n  Action,\n  Middleware,\n  ThunkDispatch,\n  UnknownAction,\n} from '@reduxjs/toolkit/react'\nimport { createDynamicMiddleware } from '@reduxjs/toolkit/react'\nimport type { Context } from 'react'\nimport type { ReactReduxContextValue } from 'react-redux'\n\ninterface AppDispatch extends ThunkDispatch<number, undefined, UnknownAction> {\n  (n: 1): 1\n}\n\nconst untypedInstance = createDynamicMiddleware()\n\nconst typedInstance = createDynamicMiddleware<number, AppDispatch>()\n\ndeclare const compatibleMiddleware: Middleware<{}, number, AppDispatch>\ndeclare const incompatibleMiddleware: Middleware<{}, string, AppDispatch>\n\ndeclare const customContext: Context<ReactReduxContextValue | null>\n\ndeclare const addedMiddleware: Middleware<(n: 2) => 2>\n\ndescribe('type tests', () => {\n  test('instance typed at creation enforces correct middleware type', () => {\n    const useDispatch = typedInstance.createDispatchWithMiddlewareHook(\n      compatibleMiddleware,\n      // @ts-expect-error\n      incompatibleMiddleware,\n    )\n\n    const createDispatchWithMiddlewareHook =\n      typedInstance.createDispatchWithMiddlewareHookFactory(customContext)\n    const useDispatchWithContext = createDispatchWithMiddlewareHook(\n      compatibleMiddleware,\n      // @ts-expect-error\n      incompatibleMiddleware,\n    )\n  })\n\n  test('withTypes() enforces correct middleware type', () => {\n    const createDispatchWithMiddlewareHook =\n      untypedInstance.createDispatchWithMiddlewareHook.withTypes<{\n        state: number\n        dispatch: AppDispatch\n      }>()\n    const useDispatch = createDispatchWithMiddlewareHook(\n      compatibleMiddleware,\n      // @ts-expect-error\n      incompatibleMiddleware,\n    )\n\n    const createCustomDispatchWithMiddlewareHook = untypedInstance\n      .createDispatchWithMiddlewareHookFactory(customContext)\n      .withTypes<{\n        state: number\n        dispatch: AppDispatch\n      }>()\n    const useCustomDispatch = createCustomDispatchWithMiddlewareHook(\n      compatibleMiddleware,\n      // @ts-expect-error\n      incompatibleMiddleware,\n    )\n  })\n\n  test('useDispatchWithMW returns typed dispatch, with any applicable extensions', () => {\n    const useDispatchWithMW =\n      typedInstance.createDispatchWithMiddlewareHook(addedMiddleware)\n    const dispatch = useDispatchWithMW()\n\n    // standard\n    expectTypeOf(dispatch({ type: 'foo' })).toEqualTypeOf<Action<string>>()\n\n    // thunk\n    expectTypeOf(dispatch(() => 'foo')).toBeString()\n\n    // static\n    expectTypeOf(dispatch(1)).toEqualTypeOf<1>()\n\n    // added\n    expectTypeOf(dispatch(2)).toEqualTypeOf<2>()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/dynamicMiddleware/tests/react.test.tsx",
    "content": "import type { Dispatch } from '@reduxjs/toolkit/react'\nimport { configureStore, createDynamicMiddleware } from '@reduxjs/toolkit/react'\nimport { render } from '@testing-library/react'\nimport * as React from 'react'\nimport type { ReactReduxContextValue } from 'react-redux'\nimport { Provider } from 'react-redux'\nimport { makeProbeableMiddleware, probeMiddleware } from './index.test'\n\nconst staticMiddleware = makeProbeableMiddleware(1)\n\ndescribe('createReactDynamicMiddleware', () => {\n  describe('createDispatchWithMiddlewareHook', () => {\n    it('injects middleware upon creation', () => {\n      const dynamicInstance = createDynamicMiddleware()\n      const store = configureStore({\n        reducer: () => 0,\n        middleware: (gDM) =>\n          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),\n      })\n      // normal, pre-inject\n      expect(store.dispatch(probeMiddleware(2))).toEqual(probeMiddleware(2))\n      // static\n      expect(store.dispatch(probeMiddleware(1))).toBe(1)\n\n      const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook(\n        makeProbeableMiddleware(2),\n      )\n\n      // injected\n      expect(store.dispatch(probeMiddleware(2))).toBe(2)\n    })\n\n    it('returns dispatch', () => {\n      const dynamicInstance = createDynamicMiddleware()\n      const store = configureStore({\n        reducer: () => 0,\n        middleware: (gDM) =>\n          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),\n      })\n\n      const useDispatch = dynamicInstance.createDispatchWithMiddlewareHook(\n        makeProbeableMiddleware(2),\n      )\n\n      let dispatch: Dispatch | undefined\n      function Component() {\n        dispatch = useDispatch()\n\n        return null\n      }\n      render(<Component />, {\n        wrapper: ({ children }) => (\n          <Provider store={store}>{children}</Provider>\n        ),\n      })\n      expect(dispatch).toBe(store.dispatch)\n    })\n  })\n  describe('createDispatchWithMiddlewareHookFactory', () => {\n    it('returns the correct store dispatch', () => {\n      const dynamicInstance = createDynamicMiddleware()\n      const store = configureStore({\n        reducer: () => 0,\n        middleware: (gDM) =>\n          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),\n      })\n      const store2 = configureStore({\n        reducer: () => '',\n        middleware: (gDM) =>\n          gDM().prepend(dynamicInstance.middleware).concat(staticMiddleware),\n      })\n\n      const context = React.createContext<ReactReduxContextValue | null>(null)\n\n      const createDispatchWithMiddlewareHook =\n        dynamicInstance.createDispatchWithMiddlewareHookFactory(context)\n\n      const useDispatch = createDispatchWithMiddlewareHook(\n        makeProbeableMiddleware(2),\n      )\n\n      let dispatch: Dispatch | undefined\n      function Component() {\n        dispatch = useDispatch()\n\n        return null\n      }\n      render(<Component />, {\n        wrapper: ({ children }) => (\n          <Provider store={store}>\n            <Provider context={context} store={store2}>\n              {children}\n            </Provider>\n          </Provider>\n        ),\n      })\n      expect(dispatch).toBe(store2.dispatch)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/dynamicMiddleware/types.ts",
    "content": "import type { Dispatch, Middleware, MiddlewareAPI, UnknownAction } from 'redux'\nimport type { BaseActionCreator, PayloadAction } from '../createAction'\nimport type { GetState } from '../createAsyncThunk'\nimport type { ExtractDispatchExtensions, FallbackIfUnknown } from '../tsHelpers'\n\nexport type GetMiddlewareApi<MiddlewareApiConfig> = MiddlewareAPI<\n  GetDispatchType<MiddlewareApiConfig>,\n  GetState<MiddlewareApiConfig>\n>\n\nexport type MiddlewareApiConfig = {\n  state?: unknown\n  dispatch?: Dispatch\n}\n\n// TODO: consolidate with cAT helpers?\nexport type GetDispatchType<MiddlewareApiConfig> = MiddlewareApiConfig extends {\n  dispatch: infer DispatchType\n}\n  ? FallbackIfUnknown<DispatchType, Dispatch>\n  : Dispatch\n\nexport type AddMiddleware<\n  State = any,\n  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,\n> = {\n  (...middlewares: Middleware<any, State, DispatchType>[]): void\n  withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): AddMiddleware<\n    GetState<MiddlewareConfig>,\n    GetDispatchType<MiddlewareConfig>\n  >\n}\n\nexport type WithMiddleware<\n  State = any,\n  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,\n> = BaseActionCreator<\n  Middleware<any, State, DispatchType>[],\n  'dynamicMiddleware/add',\n  { instanceId: string }\n> & {\n  <Middlewares extends Middleware<any, State, DispatchType>[]>(\n    ...middlewares: Middlewares\n  ): PayloadAction<Middlewares, 'dynamicMiddleware/add', { instanceId: string }>\n  withTypes<MiddlewareConfig extends MiddlewareApiConfig>(): WithMiddleware<\n    GetState<MiddlewareConfig>,\n    GetDispatchType<MiddlewareConfig>\n  >\n}\n\nexport interface DynamicDispatch {\n  // return a version of dispatch that knows about middleware\n  <Middlewares extends Middleware<any>[]>(\n    action: PayloadAction<Middlewares, 'dynamicMiddleware/add'>,\n  ): ExtractDispatchExtensions<Middlewares> & this\n}\n\nexport type MiddlewareEntry<\n  State = unknown,\n  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,\n> = {\n  middleware: Middleware<any, State, DispatchType>\n  applied: Map<\n    MiddlewareAPI<DispatchType, State>,\n    ReturnType<Middleware<any, State, DispatchType>>\n  >\n}\n\nexport type DynamicMiddleware<\n  State = unknown,\n  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,\n> = Middleware<DynamicDispatch, State, DispatchType>\n\nexport type DynamicMiddlewareInstance<\n  State = unknown,\n  DispatchType extends Dispatch<UnknownAction> = Dispatch<UnknownAction>,\n> = {\n  middleware: DynamicMiddleware<State, DispatchType>\n  addMiddleware: AddMiddleware<State, DispatchType>\n  withMiddleware: WithMiddleware<State, DispatchType>\n  instanceId: string\n}\n"
  },
  {
    "path": "packages/toolkit/src/entities/create_adapter.ts",
    "content": "import type { EntityAdapter, EntityId, EntityAdapterOptions } from './models'\nimport { createInitialStateFactory } from './entity_state'\nimport { createSelectorsFactory } from './state_selectors'\nimport { createSortedStateAdapter } from './sorted_state_adapter'\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter'\nimport type { WithRequiredProp } from '../tsHelpers'\n\nexport function createEntityAdapter<T, Id extends EntityId>(\n  options: WithRequiredProp<EntityAdapterOptions<T, Id>, 'selectId'>,\n): EntityAdapter<T, Id>\n\nexport function createEntityAdapter<T extends { id: EntityId }>(\n  options?: Omit<EntityAdapterOptions<T, T['id']>, 'selectId'>,\n): EntityAdapter<T, T['id']>\n\n/**\n *\n * @param options\n *\n * @public\n */\nexport function createEntityAdapter<T>(\n  options: EntityAdapterOptions<T, EntityId> = {},\n): EntityAdapter<T, EntityId> {\n  const {\n    selectId,\n    sortComparer,\n  }: Required<EntityAdapterOptions<T, EntityId>> = {\n    sortComparer: false,\n    selectId: (instance: any) => instance.id,\n    ...options,\n  }\n\n  const stateAdapter = sortComparer\n    ? createSortedStateAdapter(selectId, sortComparer)\n    : createUnsortedStateAdapter(selectId)\n  const stateFactory = createInitialStateFactory(stateAdapter)\n  const selectorsFactory = createSelectorsFactory<T, EntityId>()\n\n  return {\n    selectId,\n    sortComparer,\n    ...stateFactory,\n    ...selectorsFactory,\n    ...stateAdapter,\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/entities/entity_state.ts",
    "content": "import type {\n  EntityId,\n  EntityState,\n  EntityStateAdapter,\n  EntityStateFactory,\n} from './models'\n\nexport function getInitialEntityState<T, Id extends EntityId>(): EntityState<\n  T,\n  Id\n> {\n  return {\n    ids: [],\n    entities: {} as Record<Id, T>,\n  }\n}\n\nexport function createInitialStateFactory<T, Id extends EntityId>(\n  stateAdapter: EntityStateAdapter<T, Id>,\n): EntityStateFactory<T, Id> {\n  function getInitialState(\n    state?: undefined,\n    entities?: readonly T[] | Record<Id, T>,\n  ): EntityState<T, Id>\n  function getInitialState<S extends object>(\n    additionalState: S,\n    entities?: readonly T[] | Record<Id, T>,\n  ): EntityState<T, Id> & S\n  function getInitialState(\n    additionalState: any = {},\n    entities?: readonly T[] | Record<Id, T>,\n  ): any {\n    const state = Object.assign(getInitialEntityState(), additionalState)\n    return entities ? stateAdapter.setAll(state, entities) : state\n  }\n\n  return { getInitialState }\n}\n"
  },
  {
    "path": "packages/toolkit/src/entities/index.ts",
    "content": "export { createEntityAdapter } from './create_adapter'\nexport type {\n  EntityState,\n  EntityAdapter,\n  Update,\n  IdSelector,\n  Comparer,\n} from './models'\n"
  },
  {
    "path": "packages/toolkit/src/entities/models.ts",
    "content": "import type { Draft } from 'immer'\nimport type { PayloadAction } from '../createAction'\nimport type { CastAny, Id } from '../tsHelpers'\nimport type { UncheckedIndexedAccess } from '../uncheckedindexed.js'\nimport type { GetSelectorsOptions } from './state_selectors'\n\n/**\n * @public\n */\nexport type EntityId = number | string\n\n/**\n * @public\n */\nexport type Comparer<T> = (a: T, b: T) => number\n\n/**\n * @public\n */\nexport type IdSelector<T, Id extends EntityId> = (model: T) => Id\n\n/**\n * @public\n */\nexport type Update<T, Id extends EntityId> = { id: Id; changes: Partial<T> }\n\n/**\n * @public\n */\nexport interface EntityState<T, Id extends EntityId> {\n  ids: Id[]\n  entities: Record<Id, T>\n}\n\n/**\n * @public\n */\nexport interface EntityAdapterOptions<T, Id extends EntityId> {\n  selectId?: IdSelector<T, Id>\n  sortComparer?: false | Comparer<T>\n}\n\nexport type PreventAny<S, T, Id extends EntityId> = CastAny<\n  S,\n  EntityState<T, Id>\n>\n\nexport type DraftableEntityState<T, Id extends EntityId> =\n  | EntityState<T, Id>\n  | Draft<EntityState<T, Id>>\n\n/**\n * @public\n */\nexport interface EntityStateAdapter<T, Id extends EntityId> {\n  addOne<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entity: T,\n  ): S\n  addOne<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    action: PayloadAction<T>,\n  ): S\n\n  addMany<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entities: readonly T[] | Record<Id, T>,\n  ): S\n  addMany<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entities: PayloadAction<readonly T[] | Record<Id, T>>,\n  ): S\n\n  setOne<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entity: T,\n  ): S\n  setOne<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    action: PayloadAction<T>,\n  ): S\n  setMany<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entities: readonly T[] | Record<Id, T>,\n  ): S\n  setMany<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entities: PayloadAction<readonly T[] | Record<Id, T>>,\n  ): S\n  setAll<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entities: readonly T[] | Record<Id, T>,\n  ): S\n  setAll<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entities: PayloadAction<readonly T[] | Record<Id, T>>,\n  ): S\n\n  removeOne<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    key: Id,\n  ): S\n  removeOne<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    key: PayloadAction<Id>,\n  ): S\n\n  removeMany<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    keys: readonly Id[],\n  ): S\n  removeMany<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    keys: PayloadAction<readonly Id[]>,\n  ): S\n\n  removeAll<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n  ): S\n\n  updateOne<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    update: Update<T, Id>,\n  ): S\n  updateOne<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    update: PayloadAction<Update<T, Id>>,\n  ): S\n\n  updateMany<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    updates: ReadonlyArray<Update<T, Id>>,\n  ): S\n  updateMany<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    updates: PayloadAction<ReadonlyArray<Update<T, Id>>>,\n  ): S\n\n  upsertOne<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entity: T,\n  ): S\n  upsertOne<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entity: PayloadAction<T>,\n  ): S\n\n  upsertMany<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entities: readonly T[] | Record<Id, T>,\n  ): S\n  upsertMany<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n    entities: PayloadAction<readonly T[] | Record<Id, T>>,\n  ): S\n}\n\n/**\n * @public\n */\nexport interface EntitySelectors<T, V, IdType extends EntityId> {\n  selectIds: (state: V) => IdType[]\n  selectEntities: (state: V) => Record<IdType, T>\n  selectAll: (state: V) => T[]\n  selectTotal: (state: V) => number\n  selectById: (state: V, id: IdType) => Id<UncheckedIndexedAccess<T>>\n}\n\n/**\n * @public\n */\nexport interface EntityStateFactory<T, Id extends EntityId> {\n  getInitialState(\n    state?: undefined,\n    entities?: Record<Id, T> | readonly T[],\n  ): EntityState<T, Id>\n  getInitialState<S extends object>(\n    state: S,\n    entities?: Record<Id, T> | readonly T[],\n  ): EntityState<T, Id> & S\n}\n\n/**\n * @public\n */\nexport interface EntityAdapter<T, Id extends EntityId>\n  extends EntityStateAdapter<T, Id>,\n    EntityStateFactory<T, Id>,\n    Required<EntityAdapterOptions<T, Id>> {\n  getSelectors(\n    selectState?: undefined,\n    options?: GetSelectorsOptions,\n  ): EntitySelectors<T, EntityState<T, Id>, Id>\n  getSelectors<V>(\n    selectState: (state: V) => EntityState<T, Id>,\n    options?: GetSelectorsOptions,\n  ): EntitySelectors<T, V, Id>\n}\n"
  },
  {
    "path": "packages/toolkit/src/entities/sorted_state_adapter.ts",
    "content": "import type {\n  IdSelector,\n  Comparer,\n  EntityStateAdapter,\n  Update,\n  EntityId,\n  DraftableEntityState,\n} from './models'\nimport { createStateOperator } from './state_adapter'\nimport { createUnsortedStateAdapter } from './unsorted_state_adapter'\nimport {\n  selectIdValue,\n  ensureEntitiesArray,\n  splitAddedUpdatedEntities,\n  getCurrent,\n} from './utils'\n\n// Borrowed from Replay\nexport function findInsertIndex<T>(\n  sortedItems: T[],\n  item: T,\n  comparisonFunction: Comparer<T>,\n): number {\n  let lowIndex = 0\n  let highIndex = sortedItems.length\n  while (lowIndex < highIndex) {\n    let middleIndex = (lowIndex + highIndex) >>> 1\n    const currentItem = sortedItems[middleIndex]\n    const res = comparisonFunction(item, currentItem)\n    if (res >= 0) {\n      lowIndex = middleIndex + 1\n    } else {\n      highIndex = middleIndex\n    }\n  }\n\n  return lowIndex\n}\n\nexport function insert<T>(\n  sortedItems: T[],\n  item: T,\n  comparisonFunction: Comparer<T>,\n): T[] {\n  const insertAtIndex = findInsertIndex(sortedItems, item, comparisonFunction)\n\n  sortedItems.splice(insertAtIndex, 0, item)\n\n  return sortedItems\n}\n\nexport function createSortedStateAdapter<T, Id extends EntityId>(\n  selectId: IdSelector<T, Id>,\n  comparer: Comparer<T>,\n): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>\n\n  const { removeOne, removeMany, removeAll } =\n    createUnsortedStateAdapter(selectId)\n\n  function addOneMutably(entity: T, state: R): void {\n    return addManyMutably([entity], state)\n  }\n\n  function addManyMutably(\n    newEntities: readonly T[] | Record<Id, T>,\n    state: R,\n    existingIds?: Id[],\n  ): void {\n    newEntities = ensureEntitiesArray(newEntities)\n\n    const existingKeys = new Set<Id>(existingIds ?? getCurrent(state.ids))\n    const addedKeys = new Set<Id>();\n    const models = newEntities.filter(\n      (model) => {\n          const modelId = selectIdValue(model, selectId);\n          const notAdded = !addedKeys.has(modelId);\n          if (notAdded) addedKeys.add(modelId);\n          return !existingKeys.has(modelId) && notAdded;\n      }\n    )\n\n    if (models.length !== 0) {\n      mergeFunction(state, models)\n    }\n  }\n\n  function setOneMutably(entity: T, state: R): void {\n    return setManyMutably([entity], state)\n  }\n\n  function setManyMutably(\n    newEntities: readonly T[] | Record<Id, T>,\n    state: R,\n  ): void {\n    let deduplicatedEntities = {} as Record<Id, T>;\n    newEntities = ensureEntitiesArray(newEntities)\n    if (newEntities.length !== 0) {\n      for (const item of newEntities) {\n        const entityId = selectId(item);\n        // For multiple items with the same ID, we should keep the last one.\n        deduplicatedEntities[entityId] = item;\n        delete (state.entities as Record<Id, T>)[entityId]\n      }\n      newEntities = ensureEntitiesArray(deduplicatedEntities);\n      mergeFunction(state, newEntities)\n    }\n  }\n\n  function setAllMutably(\n    newEntities: readonly T[] | Record<Id, T>,\n    state: R,\n  ): void {\n    newEntities = ensureEntitiesArray(newEntities)\n    state.entities = {} as Record<Id, T>\n    state.ids = []\n\n    addManyMutably(newEntities, state, [])\n  }\n\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state)\n  }\n\n  function updateManyMutably(\n    updates: ReadonlyArray<Update<T, Id>>,\n    state: R,\n  ): void {\n    let appliedUpdates = false\n    let replacedIds = false\n\n    for (let update of updates) {\n      const entity: T | undefined = (state.entities as Record<Id, T>)[update.id]\n      if (!entity) {\n        continue\n      }\n\n      appliedUpdates = true\n\n      Object.assign(entity, update.changes)\n      const newId = selectId(entity)\n\n      if (update.id !== newId) {\n        // We do support the case where updates can change an item's ID.\n        // This makes things trickier - go ahead and swap the IDs in state now.\n        replacedIds = true\n        delete (state.entities as Record<Id, T>)[update.id]\n        const oldIndex = (state.ids as Id[]).indexOf(update.id)\n        state.ids[oldIndex] = newId\n        ;(state.entities as Record<Id, T>)[newId] = entity\n      }\n    }\n\n    if (appliedUpdates) {\n      mergeFunction(state, [], appliedUpdates, replacedIds)\n    }\n  }\n\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state)\n  }\n\n  function upsertManyMutably(\n    newEntities: readonly T[] | Record<Id, T>,\n    state: R,\n  ): void {\n    const [added, updated, existingIdsArray] = splitAddedUpdatedEntities<T, Id>(\n      newEntities,\n      selectId,\n      state,\n    )\n\n    if (added.length) {\n      addManyMutably(added, state, existingIdsArray)\n    }\n    if (updated.length) {\n      updateManyMutably(updated, state)\n    }\n  }\n\n  function areArraysEqual(a: readonly unknown[], b: readonly unknown[]) {\n    if (a.length !== b.length) {\n      return false\n    }\n\n    for (let i = 0; i < a.length; i++) {\n      if (a[i] === b[i]) {\n        continue\n      }\n      return false\n    }\n    return true\n  }\n\n  type MergeFunction = (\n    state: R,\n    addedItems: readonly T[],\n    appliedUpdates?: boolean,\n    replacedIds?: boolean,\n  ) => void\n\n  const mergeFunction: MergeFunction = (\n    state,\n    addedItems,\n    appliedUpdates,\n    replacedIds,\n  ) => {\n    const currentEntities = getCurrent(state.entities)\n    const currentIds = getCurrent(state.ids)\n\n    const stateEntities = state.entities as Record<Id, T>\n\n    let ids: Iterable<Id> = currentIds\n    if (replacedIds) {\n      ids = new Set(currentIds)\n    }\n\n    let sortedEntities: T[] = []\n    for (const id of ids) {\n      const entity = currentEntities[id]\n      if (entity) {\n        sortedEntities.push(entity)\n      }\n    }\n    const wasPreviouslyEmpty = sortedEntities.length === 0\n\n    // Insert/overwrite all new/updated\n    for (const item of addedItems) {\n      stateEntities[selectId(item)] = item\n\n      if (!wasPreviouslyEmpty) {\n        // Binary search insertion generally requires fewer comparisons\n        insert(sortedEntities, item, comparer)\n      }\n    }\n\n    if (wasPreviouslyEmpty) {\n      // All we have is the incoming values, sort them\n      sortedEntities = addedItems.slice().sort(comparer)\n    } else if (appliedUpdates) {\n      // We should have a _mostly_-sorted array already\n      sortedEntities.sort(comparer)\n    }\n\n    const newSortedIds = sortedEntities.map(selectId)\n\n    if (!areArraysEqual(currentIds, newSortedIds)) {\n      state.ids = newSortedIds\n    }\n  }\n\n  return {\n    removeOne,\n    removeMany,\n    removeAll,\n    addOne: createStateOperator(addOneMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    addMany: createStateOperator(addManyMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertMany: createStateOperator(upsertManyMutably),\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/entities/state_adapter.ts",
    "content": "import { createNextState, isDraft } from '../immerImports'\nimport type { Draft } from 'immer'\nimport type { EntityId, DraftableEntityState, PreventAny } from './models'\nimport type { PayloadAction } from '../createAction'\nimport { isFSA } from '../createAction'\n\nexport const isDraftTyped = isDraft as <T>(\n  value: T | Draft<T>,\n) => value is Draft<T>\n\nexport function createSingleArgumentStateOperator<T, Id extends EntityId>(\n  mutator: (state: DraftableEntityState<T, Id>) => void,\n) {\n  const operator = createStateOperator(\n    (_: undefined, state: DraftableEntityState<T, Id>) => mutator(state),\n  )\n\n  return function operation<S extends DraftableEntityState<T, Id>>(\n    state: PreventAny<S, T, Id>,\n  ): S {\n    return operator(state as S, undefined)\n  }\n}\n\nexport function createStateOperator<T, Id extends EntityId, R>(\n  mutator: (arg: R, state: DraftableEntityState<T, Id>) => void,\n) {\n  return function operation<S extends DraftableEntityState<T, Id>>(\n    state: S,\n    arg: R | PayloadAction<R>,\n  ): S {\n    function isPayloadActionArgument(\n      arg: R | PayloadAction<R>,\n    ): arg is PayloadAction<R> {\n      return isFSA(arg)\n    }\n\n    const runMutator = (draft: DraftableEntityState<T, Id>) => {\n      if (isPayloadActionArgument(arg)) {\n        mutator(arg.payload, draft)\n      } else {\n        mutator(arg, draft)\n      }\n    }\n\n    if (isDraftTyped<DraftableEntityState<T, Id>>(state)) {\n      // we must already be inside a `createNextState` call, likely because\n      // this is being wrapped in `createReducer` or `createSlice`.\n      // It's safe to just pass the draft to the mutator.\n      runMutator(state)\n\n      // since it's a draft, we'll just return it\n      return state\n    }\n\n    return createNextState(state, runMutator)\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/entities/state_selectors.ts",
    "content": "import type { CreateSelectorFunction, Selector } from 'reselect'\nimport { createDraftSafeSelector } from '../createDraftSafeSelector'\nimport type { EntityId, EntitySelectors, EntityState } from './models'\n\ntype AnyCreateSelectorFunction = CreateSelectorFunction<any, any, any>\n\nexport type GetSelectorsOptions = {\n  createSelector?: AnyCreateSelectorFunction\n}\n\nexport function createSelectorsFactory<T, Id extends EntityId>() {\n  function getSelectors(\n    selectState?: undefined,\n    options?: GetSelectorsOptions,\n  ): EntitySelectors<T, EntityState<T, Id>, Id>\n  function getSelectors<V>(\n    selectState: (state: V) => EntityState<T, Id>,\n    options?: GetSelectorsOptions,\n  ): EntitySelectors<T, V, Id>\n  function getSelectors<V>(\n    selectState?: (state: V) => EntityState<T, Id>,\n    options: GetSelectorsOptions = {},\n  ): EntitySelectors<T, any, Id> {\n    const {\n      createSelector = createDraftSafeSelector as AnyCreateSelectorFunction,\n    } = options\n\n    const selectIds = (state: EntityState<T, Id>) => state.ids\n\n    const selectEntities = (state: EntityState<T, Id>) => state.entities\n\n    const selectAll = createSelector(\n      selectIds,\n      selectEntities,\n      (ids, entities): T[] => ids.map((id) => entities[id]!),\n    )\n\n    const selectId = (_: unknown, id: Id) => id\n\n    const selectById = (entities: Record<Id, T>, id: Id) => entities[id]\n\n    const selectTotal = createSelector(selectIds, (ids) => ids.length)\n\n    if (!selectState) {\n      return {\n        selectIds,\n        selectEntities,\n        selectAll,\n        selectTotal,\n        selectById: createSelector(selectEntities, selectId, selectById),\n      }\n    }\n\n    const selectGlobalizedEntities = createSelector(\n      selectState as Selector<V, EntityState<T, Id>>,\n      selectEntities,\n    )\n\n    return {\n      selectIds: createSelector(selectState, selectIds),\n      selectEntities: selectGlobalizedEntities,\n      selectAll: createSelector(selectState, selectAll),\n      selectTotal: createSelector(selectState, selectTotal),\n      selectById: createSelector(\n        selectGlobalizedEntities,\n        selectId,\n        selectById,\n      ),\n    }\n  }\n\n  return { getSelectors }\n}\n"
  },
  {
    "path": "packages/toolkit/src/entities/tests/entity_slice_enhancer.test.ts",
    "content": "import type {\n  EntityId,\n  EntityState,\n  IdSelector,\n  PayloadAction,\n  Slice,\n  SliceCaseReducers,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport { createEntityAdapter, createSlice } from '@reduxjs/toolkit'\nimport type { BookModel } from './fixtures/book'\n\ndescribe('Entity Slice Enhancer', () => {\n  let slice: Slice<EntityState<BookModel, BookModel['id']>>\n\n  beforeEach(() => {\n    const indieSlice = entitySliceEnhancer({\n      name: 'book',\n      selectId: (book: BookModel) => book.id,\n    })\n    slice = indieSlice\n  })\n\n  it('exposes oneAdded', () => {\n    const book = {\n      id: '0',\n      title: 'Der Steppenwolf',\n      author: 'Herman Hesse',\n    }\n    const action = slice.actions.oneAdded(book)\n    const oneAdded = slice.reducer(undefined, action as UnknownAction)\n    expect(oneAdded.entities['0']).toBe(book)\n  })\n})\n\ninterface EntitySliceArgs<T, Id extends EntityId> {\n  name: string\n  selectId: IdSelector<T, Id>\n  modelReducer?: SliceCaseReducers<T>\n}\n\nfunction entitySliceEnhancer<T, Id extends EntityId>({\n  name,\n  selectId,\n  modelReducer,\n}: EntitySliceArgs<T, Id>) {\n  const modelAdapter = createEntityAdapter({\n    selectId,\n  })\n\n  return createSlice({\n    name,\n    initialState: modelAdapter.getInitialState(),\n    reducers: {\n      oneAdded(state, action: PayloadAction<T>) {\n        modelAdapter.addOne(state, action.payload)\n      },\n      ...modelReducer,\n    },\n  })\n}\n"
  },
  {
    "path": "packages/toolkit/src/entities/tests/entity_state.test.ts",
    "content": "import type { EntityAdapter, PayloadAction } from '@reduxjs/toolkit'\nimport {\n  createAction,\n  createEntityAdapter,\n  createSlice,\n} from '@reduxjs/toolkit'\nimport type { BookModel } from './fixtures/book'\n\ndescribe('Entity State', () => {\n  let adapter: EntityAdapter<BookModel, string>\n\n  beforeEach(() => {\n    adapter = createEntityAdapter({\n      selectId: (book: BookModel) => book.id,\n    })\n  })\n\n  it('should let you get the initial state', () => {\n    const initialState = adapter.getInitialState()\n\n    expect(initialState).toEqual({\n      ids: [],\n      entities: {},\n    })\n  })\n\n  it('should let you provide additional initial state properties', () => {\n    const additionalProperties = { isHydrated: true }\n\n    const initialState = adapter.getInitialState(additionalProperties)\n\n    expect(initialState).toEqual({\n      ...additionalProperties,\n      ids: [],\n      entities: {},\n    })\n  })\n\n  it('should let you provide initial entities', () => {\n    const book1: BookModel = { id: 'a', title: 'First' }\n\n    const initialState = adapter.getInitialState(undefined, [book1])\n\n    expect(initialState).toEqual({\n      ids: [book1.id],\n      entities: { [book1.id]: book1 },\n    })\n\n    const additionalProperties = { isHydrated: true }\n\n    const initialState2 = adapter.getInitialState(additionalProperties, [book1])\n\n    expect(initialState2).toEqual({\n      ...additionalProperties,\n      ids: [book1.id],\n      entities: { [book1.id]: book1 },\n    })\n  })\n\n  it('should allow methods to be passed as reducers', () => {\n    const upsertBook = createAction<BookModel>('otherBooks/upsert')\n\n    const booksSlice = createSlice({\n      name: 'books',\n      initialState: adapter.getInitialState(),\n      reducers: {\n        addOne: adapter.addOne,\n        removeOne(state, action: PayloadAction<string>) {\n          // TODO The nested `produce` calls don't mutate `state` here as I would have expected.\n          // TODO (note that `state` here is actually an Immer Draft<S>, from `createReducer`)\n          // TODO However, this works if we _return_ the new plain result value instead\n          // TODO See https://github.com/immerjs/immer/issues/533\n          const result = adapter.removeOne(state, action)\n          return result\n        },\n      },\n      extraReducers: (builder) => {\n        builder.addCase(upsertBook, (state, action) => {\n          return adapter.upsertOne(state, action)\n        })\n      },\n    })\n\n    const { addOne, removeOne } = booksSlice.actions\n    const { reducer } = booksSlice\n\n    const selectors = adapter.getSelectors()\n\n    const book1: BookModel = { id: 'a', title: 'First' }\n    const book1a: BookModel = { id: 'a', title: 'Second' }\n\n    const afterAddOne = reducer(undefined, addOne(book1))\n    expect(afterAddOne.entities[book1.id]).toBe(book1)\n\n    const afterRemoveOne = reducer(afterAddOne, removeOne(book1.id))\n    expect(afterRemoveOne.entities[book1.id]).toBeUndefined()\n    expect(selectors.selectTotal(afterRemoveOne)).toBe(0)\n\n    const afterUpsertFirst = reducer(afterRemoveOne, upsertBook(book1))\n    const afterUpsertSecond = reducer(afterUpsertFirst, upsertBook(book1a))\n\n    expect(afterUpsertSecond.entities[book1.id]).toEqual(book1a)\n    expect(selectors.selectTotal(afterUpsertSecond)).toBe(1)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/entities/tests/fixtures/book.ts",
    "content": "export interface BookModel {\n  id: string\n  title: string\n  author?: string\n}\n\nexport const AClockworkOrange: BookModel = Object.freeze({\n  id: 'aco',\n  title: 'A Clockwork Orange',\n})\n\nexport const AnimalFarm: BookModel = Object.freeze({\n  id: 'af',\n  title: 'Animal Farm',\n})\n\nexport const TheGreatGatsby: BookModel = Object.freeze({\n  id: 'tgg',\n  title: 'The Great Gatsby',\n})\n\nexport const TheHobbit: BookModel = Object.freeze({\n  id: 'th',\n  title: 'The Hobbit',\n  author: 'J. R. R. Tolkien',\n})\n"
  },
  {
    "path": "packages/toolkit/src/entities/tests/sorted_state_adapter.test.ts",
    "content": "import type {\n  EntityAdapter,\n  EntityState,\n  PayloadAction,\n} from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createAction,\n  createEntityAdapter,\n  createNextState,\n  createSlice,\n  nanoid,\n} from '@reduxjs/toolkit'\nimport type { BookModel } from './fixtures/book'\nimport {\n  AClockworkOrange,\n  AnimalFarm,\n  TheGreatGatsby,\n  TheHobbit,\n} from './fixtures/book'\n\ndescribe('Sorted State Adapter', () => {\n  let adapter: EntityAdapter<BookModel, string>\n  let state: EntityState<BookModel, string>\n\n  beforeAll(() => {\n    //eslint-disable-next-line\n    Object.defineProperty(Array.prototype, 'unwantedField', {\n      enumerable: true,\n      configurable: true,\n      value: 'This should not appear anywhere',\n    })\n  })\n\n  afterAll(() => {\n    delete (Array.prototype as any).unwantedField\n  })\n\n  beforeEach(() => {\n    adapter = createEntityAdapter({\n      selectId: (book: BookModel) => book.id,\n      sortComparer: (a, b) => {\n        return a.title.localeCompare(b.title)\n      },\n    })\n\n    state = { ids: [], entities: {} }\n  })\n\n  it('should let you add one entity to the state', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    expect(withOneEntity).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n      },\n    })\n  })\n\n  it('should let you add one entity to the state as an FSA', () => {\n    const bookAction = createAction<BookModel>('books/add')\n    const withOneEntity = adapter.addOne(state, bookAction(TheGreatGatsby))\n\n    expect(withOneEntity).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n      },\n    })\n  })\n\n  it('should not change state if you attempt to re-add an entity', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const readded = adapter.addOne(withOneEntity, TheGreatGatsby)\n\n    expect(readded).toBe(withOneEntity)\n  })\n\n  it('should let you add many entities to the state', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const withManyMore = adapter.addMany(withOneEntity, [\n      AClockworkOrange,\n      AnimalFarm,\n    ])\n\n    expect(withManyMore).toEqual({\n      ids: [AClockworkOrange.id, AnimalFarm.id, TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n        [AClockworkOrange.id]: AClockworkOrange,\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should let you add many entities to the state from a dictionary', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const withManyMore = adapter.addMany(withOneEntity, {\n      [AClockworkOrange.id]: AClockworkOrange,\n      [AnimalFarm.id]: AnimalFarm,\n    })\n\n    expect(withManyMore).toEqual({\n      ids: [AClockworkOrange.id, AnimalFarm.id, TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n        [AClockworkOrange.id]: AClockworkOrange,\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should remove existing and add new ones on setAll', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const withAll = adapter.setAll(withOneEntity, [\n      AClockworkOrange,\n      AnimalFarm,\n    ])\n\n    expect(withAll).toEqual({\n      ids: [AClockworkOrange.id, AnimalFarm.id],\n      entities: {\n        [AClockworkOrange.id]: AClockworkOrange,\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should remove existing and add new ones on setAll when passing in a dictionary', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const withAll = adapter.setAll(withOneEntity, {\n      [AClockworkOrange.id]: AClockworkOrange,\n      [AnimalFarm.id]: AnimalFarm,\n    })\n\n    expect(withAll).toEqual({\n      ids: [AClockworkOrange.id, AnimalFarm.id],\n      entities: {\n        [AClockworkOrange.id]: AClockworkOrange,\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should remove existing and add new ones on addAll (deprecated)', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const withAll = adapter.setAll(withOneEntity, [\n      AClockworkOrange,\n      AnimalFarm,\n    ])\n\n    expect(withAll).toEqual({\n      ids: [AClockworkOrange.id, AnimalFarm.id],\n      entities: {\n        [AClockworkOrange.id]: AClockworkOrange,\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should let you add remove an entity from the state', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const withoutOne = adapter.removeOne(withOneEntity, TheGreatGatsby.id)\n\n    expect(withoutOne).toEqual({\n      ids: [],\n      entities: {},\n    })\n  })\n\n  it('should let you remove many entities by id from the state', () => {\n    const withAll = adapter.setAll(state, [\n      TheGreatGatsby,\n      AClockworkOrange,\n      AnimalFarm,\n    ])\n\n    const withoutMany = adapter.removeMany(withAll, [\n      TheGreatGatsby.id,\n      AClockworkOrange.id,\n    ])\n\n    expect(withoutMany).toEqual({\n      ids: [AnimalFarm.id],\n      entities: {\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should let you remove all entities from the state', () => {\n    const withAll = adapter.setAll(state, [\n      TheGreatGatsby,\n      AClockworkOrange,\n      AnimalFarm,\n    ])\n\n    const withoutAll = adapter.removeAll(withAll)\n\n    expect(withoutAll).toEqual({\n      ids: [],\n      entities: {},\n    })\n  })\n\n  it('should let you update an entity in the state', () => {\n    const withOne = adapter.addOne(state, TheGreatGatsby)\n    const changes = { title: 'A New Hope' }\n\n    const withUpdates = adapter.updateOne(withOne, {\n      id: TheGreatGatsby.id,\n      changes,\n    })\n\n    expect(withUpdates).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...changes,\n        },\n      },\n    })\n  })\n\n  it('should not change state if you attempt to update an entity that has not been added', () => {\n    const withUpdates = adapter.updateOne(state, {\n      id: TheGreatGatsby.id,\n      changes: { title: 'A New Title' },\n    })\n\n    expect(withUpdates).toBe(state)\n  })\n\n  it('Replaces an existing entity if you change the ID while updating', () => {\n    const a = { id: 'a', title: 'First' }\n    const b = { id: 'b', title: 'Second' }\n    const c = { id: 'c', title: 'Third' }\n    const d = { id: 'd', title: 'Fourth' }\n    const withAdded = adapter.setAll(state, [a, b, c])\n\n    const withUpdated = adapter.updateOne(withAdded, {\n      id: 'b',\n      changes: {\n        id: 'c',\n      },\n    })\n\n    const { ids, entities } = withUpdated\n\n    expect(ids).toEqual(['a', 'c'])\n    expect(entities.a).toBeTruthy()\n    expect(entities.b).not.toBeTruthy()\n    expect(entities.c).toBeTruthy()\n    expect(entities.c!.id).toBe('c')\n    expect(entities.c!.title).toBe('Second')\n  })\n\n  it('should not change ids state if you attempt to update an entity that does not impact sorting', () => {\n    const withAll = adapter.setAll(state, [\n      TheGreatGatsby,\n      AClockworkOrange,\n      AnimalFarm,\n    ])\n    const changes = { title: 'The Great Gatsby II' }\n\n    const withUpdates = adapter.updateOne(withAll, {\n      id: TheGreatGatsby.id,\n      changes,\n    })\n\n    expect(withAll.ids).toBe(withUpdates.ids)\n  })\n\n  it('should let you update the id of entity', () => {\n    const withOne = adapter.addOne(state, TheGreatGatsby)\n    const changes = { id: 'A New Id' }\n\n    const withUpdates = adapter.updateOne(withOne, {\n      id: TheGreatGatsby.id,\n      changes,\n    })\n\n    expect(withUpdates).toEqual({\n      ids: [changes.id],\n      entities: {\n        [changes.id]: {\n          ...TheGreatGatsby,\n          ...changes,\n        },\n      },\n    })\n  })\n\n  it('should resort correctly if same id but sort key update', () => {\n    const withAll = adapter.setAll(state, [\n      TheGreatGatsby,\n      AnimalFarm,\n      AClockworkOrange,\n    ])\n    const changes = { title: 'A New Hope' }\n\n    const withUpdates = adapter.updateOne(withAll, {\n      id: TheGreatGatsby.id,\n      changes,\n    })\n\n    expect(withUpdates).toEqual({\n      ids: [AClockworkOrange.id, TheGreatGatsby.id, AnimalFarm.id],\n      entities: {\n        [AClockworkOrange.id]: AClockworkOrange,\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...changes,\n        },\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should resort correctly if the id and sort key update', () => {\n    const withOne = adapter.setAll(state, [\n      TheGreatGatsby,\n      AnimalFarm,\n      AClockworkOrange,\n    ])\n    const changes = { id: 'A New Id', title: 'A New Hope' }\n\n    const withUpdates = adapter.updateOne(withOne, {\n      id: TheGreatGatsby.id,\n      changes,\n    })\n\n    expect(withUpdates).toEqual({\n      ids: [AClockworkOrange.id, changes.id, AnimalFarm.id],\n      entities: {\n        [AClockworkOrange.id]: AClockworkOrange,\n        [changes.id]: {\n          ...TheGreatGatsby,\n          ...changes,\n        },\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should maintain a stable sorting order when updating items', () => {\n    interface OrderedEntity {\n      id: string\n      order: number\n      ts: number\n    }\n    const sortedItemsAdapter = createEntityAdapter<OrderedEntity>({\n      sortComparer: (a, b) => a.order - b.order,\n    })\n    const withInitialItems = sortedItemsAdapter.setAll(\n      sortedItemsAdapter.getInitialState(),\n      [\n        { id: 'C', order: 3, ts: 0 },\n        { id: 'A', order: 1, ts: 0 },\n        { id: 'F', order: 4, ts: 0 },\n        { id: 'B', order: 2, ts: 0 },\n        { id: 'D', order: 3, ts: 0 },\n        { id: 'E', order: 3, ts: 0 },\n      ],\n    )\n\n    expect(withInitialItems.ids).toEqual(['A', 'B', 'C', 'D', 'E', 'F'])\n\n    const updated = sortedItemsAdapter.updateOne(withInitialItems, {\n      id: 'C',\n      changes: { ts: 5 },\n    })\n\n    expect(updated.ids).toEqual(['A', 'B', 'C', 'D', 'E', 'F'])\n\n    const updated2 = sortedItemsAdapter.updateOne(withInitialItems, {\n      id: 'D',\n      changes: { ts: 6 },\n    })\n\n    expect(updated2.ids).toEqual(['A', 'B', 'C', 'D', 'E', 'F'])\n  })\n\n  it('should let you update many entities by id in the state', () => {\n    const firstChange = { title: 'Zack' }\n    const secondChange = { title: 'Aaron' }\n    const withMany = adapter.setAll(state, [TheGreatGatsby, AClockworkOrange])\n\n    const withUpdates = adapter.updateMany(withMany, [\n      { id: TheGreatGatsby.id, changes: firstChange },\n      { id: AClockworkOrange.id, changes: secondChange },\n    ])\n\n    expect(withUpdates).toEqual({\n      ids: [AClockworkOrange.id, TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...firstChange,\n        },\n        [AClockworkOrange.id]: {\n          ...AClockworkOrange,\n          ...secondChange,\n        },\n      },\n    })\n  })\n\n  it('should let you add one entity to the state with upsert()', () => {\n    const withOneEntity = adapter.upsertOne(state, TheGreatGatsby)\n    expect(withOneEntity).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n      },\n    })\n  })\n\n  it('should let you update an entity in the state with upsert()', () => {\n    const withOne = adapter.addOne(state, TheGreatGatsby)\n    const changes = { title: 'A New Hope' }\n\n    const withUpdates = adapter.upsertOne(withOne, {\n      ...TheGreatGatsby,\n      ...changes,\n    })\n    expect(withUpdates).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...changes,\n        },\n      },\n    })\n  })\n\n  it('should let you upsert many entities in the state', () => {\n    const firstChange = { title: 'Zack' }\n    const withMany = adapter.setAll(state, [TheGreatGatsby])\n\n    const withUpserts = adapter.upsertMany(withMany, [\n      { ...TheGreatGatsby, ...firstChange },\n      AClockworkOrange,\n    ])\n\n    expect(withUpserts).toEqual({\n      ids: [AClockworkOrange.id, TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...firstChange,\n        },\n        [AClockworkOrange.id]: AClockworkOrange,\n      },\n    })\n  })\n\n  it('should do nothing when upsertMany is given an empty array', () => {\n    const withMany = adapter.setAll(state, [TheGreatGatsby])\n\n    const withUpserts = adapter.upsertMany(withMany, [])\n\n    expect(withUpserts).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n      },\n    })\n  })\n\n  it('should throw when upsertMany is passed undefined or null', async () => {\n    const withMany = adapter.setAll(state, [TheGreatGatsby])\n\n    const fakeRequest = (response: null | undefined) =>\n      new Promise((resolve) => setTimeout(() => resolve(response), 50))\n\n    const undefinedBooks = (await fakeRequest(undefined)) as BookModel[]\n    expect(() => adapter.upsertMany(withMany, undefinedBooks)).toThrow()\n\n    const nullBooks = (await fakeRequest(null)) as BookModel[]\n    expect(() => adapter.upsertMany(withMany, nullBooks)).toThrow()\n  })\n\n  it('should let you upsert many entities in the state when passing in a dictionary', () => {\n    const firstChange = { title: 'Zack' }\n    const withMany = adapter.setAll(state, [TheGreatGatsby])\n\n    const withUpserts = adapter.upsertMany(withMany, {\n      [TheGreatGatsby.id]: { ...TheGreatGatsby, ...firstChange },\n      [AClockworkOrange.id]: AClockworkOrange,\n    })\n\n    expect(withUpserts).toEqual({\n      ids: [AClockworkOrange.id, TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...firstChange,\n        },\n        [AClockworkOrange.id]: AClockworkOrange,\n      },\n    })\n  })\n\n  it('should let you add a new entity then apply changes to it', () => {\n    const firstChange = { author: TheHobbit.author }\n    const secondChange = { title: 'Zack' }\n    const withMany = adapter.setAll(state, [AClockworkOrange])\n\n    const withUpserts = adapter.upsertMany(withMany, [\n      { ...TheGreatGatsby },\n      { ...TheGreatGatsby, ...firstChange },\n      { ...TheGreatGatsby, ...secondChange },\n    ])\n\n    expect(withUpserts).toEqual({\n      ids: [AClockworkOrange.id, TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...firstChange,\n          ...secondChange,\n        },\n        [AClockworkOrange.id]: AClockworkOrange,\n      },\n    })\n  })\n\n  it('should let you add a new entity in the state with setOne() and keep the sorting', () => {\n    const withMany = adapter.setAll(state, [AnimalFarm, TheHobbit])\n    const withOneMore = adapter.setOne(withMany, TheGreatGatsby)\n    expect(withOneMore).toEqual({\n      ids: [AnimalFarm.id, TheGreatGatsby.id, TheHobbit.id],\n      entities: {\n        [AnimalFarm.id]: AnimalFarm,\n        [TheHobbit.id]: TheHobbit,\n        [TheGreatGatsby.id]: TheGreatGatsby,\n      },\n    })\n  })\n\n  it('should let you replace an entity in the state with setOne()', () => {\n    let withOne = adapter.setOne(state, TheHobbit)\n    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }\n    withOne = adapter.setOne(withOne, changeWithoutAuthor)\n\n    expect(withOne).toEqual({\n      ids: [TheHobbit.id],\n      entities: {\n        [TheHobbit.id]: changeWithoutAuthor,\n      },\n    })\n  })\n\n  it('should do nothing when setMany is given an empty array', () => {\n    const withMany = adapter.setAll(state, [TheGreatGatsby])\n\n    const withUpserts = adapter.setMany(withMany, [])\n\n    expect(withUpserts).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n      },\n    })\n  })\n\n  it('should let you set many entities in the state', () => {\n    const firstChange = { id: TheHobbit.id, title: 'Silmarillion' }\n    const withMany = adapter.setAll(state, [TheHobbit])\n\n    const withSetMany = adapter.setMany(withMany, [\n      firstChange,\n      AClockworkOrange,\n    ])\n\n    expect(withSetMany).toEqual({\n      ids: [AClockworkOrange.id, TheHobbit.id],\n      entities: {\n        [TheHobbit.id]: firstChange,\n        [AClockworkOrange.id]: AClockworkOrange,\n      },\n    })\n  })\n\n  it('should work consistent with Unsorted State Adapter adding duplicate ids', () => {\n    const unsortedAdaptor = createEntityAdapter({\n      selectId: (book: BookModel) => book.id,\n    })\n\n    const firstEntry = { id: AClockworkOrange.id, author: TheHobbit.author }\n    const secondEntry = { id: AClockworkOrange.id, title: 'Zack' }\n    const withNothingSorted = adapter.setAll(state, [])\n    const withNothingUnsorted = unsortedAdaptor.setAll(state, [])\n    const withOneSorted = adapter.addMany(withNothingSorted, [\n      { ...AClockworkOrange, ...firstEntry },\n      { ...AClockworkOrange, ...secondEntry },\n    ])\n    const withOneUnsorted = adapter.addMany(withNothingUnsorted, [\n      { ...AClockworkOrange, ...firstEntry },\n      { ...AClockworkOrange, ...secondEntry },\n    ])\n\n    expect(withOneSorted).toEqual(withOneUnsorted)\n  })\n\n  it('should work consistent with Unsorted State Adapter adding duplicate ids', () => {\n    const unsortedAdaptor = createEntityAdapter({\n      selectId: (book: BookModel) => book.id,\n    })\n\n    const firstEntry = { id: AClockworkOrange.id, author: TheHobbit.author }\n    const secondEntry = { id: AClockworkOrange.id, title: 'Zack' }\n    const withNothingSorted = adapter.setAll(state, [TheHobbit])\n    const withNothingUnsorted = unsortedAdaptor.setAll(state, [TheHobbit])\n    const withOneSorted = adapter.setMany(withNothingSorted, [\n      { ...AClockworkOrange, ...firstEntry, id: 'th' },\n      { ...AClockworkOrange, ...secondEntry, id: 'th' },\n    ])\n    const withOneUnsorted = unsortedAdaptor.setMany(withNothingUnsorted, [\n      { ...AClockworkOrange, ...firstEntry, id: 'th' },\n      { ...AClockworkOrange, ...secondEntry, id: 'th' },\n    ])\n\n    expect(withOneSorted).toEqual(withOneUnsorted)\n  })\n\n  it('should let you set many entities in the state when passing in a dictionary', () => {\n    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }\n    const withMany = adapter.setAll(state, [TheHobbit])\n\n    const withSetMany = adapter.setMany(withMany, {\n      [TheHobbit.id]: changeWithoutAuthor,\n      [AClockworkOrange.id]: AClockworkOrange,\n    })\n\n    expect(withSetMany).toEqual({\n      ids: [AClockworkOrange.id, TheHobbit.id],\n      entities: {\n        [TheHobbit.id]: changeWithoutAuthor,\n        [AClockworkOrange.id]: AClockworkOrange,\n      },\n    })\n  })\n\n  it(\"only returns one entry for that id in the id's array\", () => {\n    const book1: BookModel = { id: 'a', title: 'First' }\n    const book2: BookModel = { id: 'b', title: 'Second' }\n    const initialState = adapter.getInitialState()\n    const withItems = adapter.addMany(initialState, [book1, book2])\n\n    expect(withItems.ids).toEqual(['a', 'b'])\n    const withUpdate = adapter.updateOne(withItems, {\n      id: 'a',\n      changes: { id: 'b' },\n    })\n\n    expect(withUpdate.ids).toEqual(['b'])\n    expect(withUpdate.entities['b']!.title).toBe(book1.title)\n  })\n\n  it('should minimize the amount of sorting work needed', () => {\n    const INITIAL_ITEMS = 10_000\n    const ADDED_ITEMS = 1_000\n\n    type Entity = { id: string; name: string; position: number }\n\n    let numSorts = 0\n\n    const adaptor = createEntityAdapter({\n      selectId: (entity: Entity) => entity.id,\n      sortComparer: (a, b) => {\n        numSorts++\n        if (a.position < b.position) return -1\n        else if (a.position > b.position) return 1\n        return 0\n      },\n    })\n\n    function generateItems(count: number) {\n      const items: readonly Entity[] = new Array(count)\n        .fill(undefined)\n        .map((x, i) => ({\n          name: `${i}`,\n          position: Math.random(),\n          id: nanoid(),\n        }))\n      return items\n    }\n\n    const entitySlice = createSlice({\n      name: 'entity',\n      initialState: adaptor.getInitialState(),\n      reducers: {\n        updateOne: adaptor.updateOne,\n        upsertOne: adaptor.upsertOne,\n        upsertMany: adaptor.upsertMany,\n        addMany: adaptor.addMany,\n      },\n    })\n\n    const store = configureStore({\n      reducer: {\n        entity: entitySlice.reducer,\n      },\n      middleware: (getDefaultMiddleware) => {\n        return getDefaultMiddleware({\n          serializableCheck: false,\n          immutableCheck: false,\n        })\n      },\n    })\n\n    numSorts = 0\n\n    const logComparisons = false\n\n    function measureComparisons(name: string, cb: () => void) {\n      numSorts = 0\n      const start = new Date().getTime()\n      cb()\n      const end = new Date().getTime()\n      const duration = end - start\n\n      if (logComparisons) {\n        console.log(\n          `${name}: sortComparer called ${numSorts.toLocaleString()} times in ${duration.toLocaleString()}ms`,\n        )\n      }\n    }\n\n    const initialItems = generateItems(INITIAL_ITEMS)\n\n    measureComparisons('Original Setup', () => {\n      store.dispatch(entitySlice.actions.upsertMany(initialItems))\n    })\n\n    expect(numSorts).toBeLessThan(INITIAL_ITEMS * 20)\n\n    measureComparisons('Insert One (random)', () => {\n      store.dispatch(\n        entitySlice.actions.upsertOne({\n          id: nanoid(),\n          position: Math.random(),\n          name: 'test',\n        }),\n      )\n    })\n\n    expect(numSorts).toBeLessThan(50)\n\n    measureComparisons('Insert One (middle)', () => {\n      store.dispatch(\n        entitySlice.actions.upsertOne({\n          id: nanoid(),\n          position: 0.5,\n          name: 'test',\n        }),\n      )\n    })\n\n    expect(numSorts).toBeLessThan(50)\n\n    measureComparisons('Insert One (end)', () => {\n      store.dispatch(\n        entitySlice.actions.upsertOne({\n          id: nanoid(),\n          position: 0.9998,\n          name: 'test',\n        }),\n      )\n    })\n\n    expect(numSorts).toBeLessThan(50)\n\n    const addedItems = generateItems(ADDED_ITEMS)\n    measureComparisons('Add Many', () => {\n      store.dispatch(entitySlice.actions.addMany(addedItems))\n    })\n\n    expect(numSorts).toBeLessThan(ADDED_ITEMS * 20)\n\n    // These numbers will vary because of the randomness, but generally\n    // with 10K items the old code had 200K+ sort calls, while the new code\n    // is around 13K sort calls.\n    expect(numSorts).toBeLessThan(20_000)\n\n    const { ids } = store.getState().entity\n    const middleItemId = ids[(ids.length / 2) | 0]\n\n    measureComparisons('Update One (end)', () => {\n      store.dispatch(\n        // Move this middle item near the end\n        entitySlice.actions.updateOne({\n          id: middleItemId,\n          changes: {\n            position: 0.99999,\n          },\n        }),\n      )\n    })\n\n    const SORTING_COUNT_BUFFER = 100\n\n    expect(numSorts).toBeLessThan(\n      INITIAL_ITEMS + ADDED_ITEMS + SORTING_COUNT_BUFFER,\n    )\n\n    measureComparisons('Update One (middle)', () => {\n      store.dispatch(\n        // Move this middle item near the end\n        entitySlice.actions.updateOne({\n          id: middleItemId,\n          changes: {\n            position: 0.42,\n          },\n        }),\n      )\n    })\n\n    expect(numSorts).toBeLessThan(\n      INITIAL_ITEMS + ADDED_ITEMS + SORTING_COUNT_BUFFER,\n    )\n\n    measureComparisons('Update One (replace)', () => {\n      store.dispatch(\n        // Move this middle item near the end\n        entitySlice.actions.updateOne({\n          id: middleItemId,\n          changes: {\n            id: nanoid(),\n            position: 0.98,\n          },\n        }),\n      )\n    })\n\n    expect(numSorts).toBeLessThan(\n      INITIAL_ITEMS + ADDED_ITEMS + SORTING_COUNT_BUFFER,\n    )\n\n    // The old code was around 120K, the new code is around 10K.\n    //expect(numSorts).toBeLessThan(25_000)\n  })\n\n  it('should not throw an Immer `current` error when `state.ids` is a plain array', () => {\n    const book1: BookModel = { id: 'a', title: 'First' }\n    const initialState = adapter.getInitialState()\n    const withItems = adapter.addMany(initialState, [book1])\n    const booksSlice = createSlice({\n      name: 'books',\n      initialState,\n      reducers: {\n        testCurrentBehavior(state, action: PayloadAction<BookModel>) {\n          // Will overwrite `state.ids` with a plain array\n          adapter.removeAll(state)\n\n          // will call `splitAddedUpdatedEntities` and call `current(state.ids)`\n          adapter.upsertMany(state, [book1])\n        },\n      },\n    })\n\n    booksSlice.reducer(\n      initialState,\n      booksSlice.actions.testCurrentBehavior(book1),\n    )\n  })\n\n  it('should not throw an Immer `current` error when the adapter is called twice', () => {\n    const book1: BookModel = { id: 'a', title: 'First' }\n    const book2: BookModel = { id: 'b', title: 'Second' }\n    const initialState = adapter.getInitialState()\n    const booksSlice = createSlice({\n      name: 'books',\n      initialState,\n      reducers: {\n        testCurrentBehavior(state, action: PayloadAction<BookModel>) {\n          // Will overwrite `state.ids` with a plain array\n          adapter.removeAll(state)\n\n          // will call `splitAddedUpdatedEntities` and call `current(state.ids)`\n          adapter.addOne(state, book1)\n          adapter.addOne(state, book2)\n        },\n      },\n    })\n\n    booksSlice.reducer(\n      initialState,\n      booksSlice.actions.testCurrentBehavior(book1),\n    )\n  })\n\n  describe('can be used mutably when wrapped in createNextState', () => {\n    test('removeAll', () => {\n      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])\n      const result = createNextState(withTwo, (draft) => {\n        adapter.removeAll(draft)\n      })\n      expect(result).toEqual({\n        entities: {},\n        ids: [],\n      })\n    })\n\n    test('addOne', () => {\n      const result = createNextState(state, (draft) => {\n        adapter.addOne(draft, TheGreatGatsby)\n      })\n\n      expect(result).toEqual({\n        entities: {\n          tgg: {\n            id: 'tgg',\n            title: 'The Great Gatsby',\n          },\n        },\n        ids: ['tgg'],\n      })\n    })\n\n    test('addMany', () => {\n      const result = createNextState(state, (draft) => {\n        adapter.addMany(draft, [TheGreatGatsby, AnimalFarm])\n      })\n\n      expect(result).toEqual({\n        entities: {\n          af: {\n            id: 'af',\n            title: 'Animal Farm',\n          },\n          tgg: {\n            id: 'tgg',\n            title: 'The Great Gatsby',\n          },\n        },\n        ids: ['af', 'tgg'],\n      })\n    })\n\n    test('setAll', () => {\n      const result = createNextState(state, (draft) => {\n        adapter.setAll(draft, [TheGreatGatsby, AnimalFarm])\n      })\n\n      expect(result).toEqual({\n        entities: {\n          af: {\n            id: 'af',\n            title: 'Animal Farm',\n          },\n          tgg: {\n            id: 'tgg',\n            title: 'The Great Gatsby',\n          },\n        },\n        ids: ['af', 'tgg'],\n      })\n    })\n\n    test('updateOne', () => {\n      const withOne = adapter.addOne(state, TheGreatGatsby)\n      const changes = { title: 'A New Hope' }\n      const result = createNextState(withOne, (draft) => {\n        adapter.updateOne(draft, {\n          id: TheGreatGatsby.id,\n          changes,\n        })\n      })\n\n      expect(result).toEqual({\n        entities: {\n          tgg: {\n            id: 'tgg',\n            title: 'A New Hope',\n          },\n        },\n        ids: ['tgg'],\n      })\n    })\n\n    test('updateMany', () => {\n      const firstChange = { title: 'First Change' }\n      const secondChange = { title: 'Second Change' }\n      const thirdChange = { title: 'Third Change' }\n      const fourthChange = { author: 'Fourth Change' }\n      const withMany = adapter.setAll(state, [\n        TheGreatGatsby,\n        AClockworkOrange,\n        TheHobbit,\n      ])\n\n      const result = createNextState(withMany, (draft) => {\n        adapter.updateMany(draft, [\n          { id: TheHobbit.id, changes: firstChange },\n          { id: TheGreatGatsby.id, changes: secondChange },\n          { id: AClockworkOrange.id, changes: thirdChange },\n          { id: TheHobbit.id, changes: fourthChange },\n        ])\n      })\n\n      expect(result).toEqual({\n        entities: {\n          aco: {\n            id: 'aco',\n            title: 'Third Change',\n          },\n          tgg: {\n            id: 'tgg',\n            title: 'Second Change',\n          },\n          th: {\n            author: 'Fourth Change',\n            id: 'th',\n            title: 'First Change',\n          },\n        },\n        ids: ['th', 'tgg', 'aco'],\n      })\n    })\n\n    test('upsertOne (insert)', () => {\n      const result = createNextState(state, (draft) => {\n        adapter.upsertOne(draft, TheGreatGatsby)\n      })\n      expect(result).toEqual({\n        entities: {\n          tgg: {\n            id: 'tgg',\n            title: 'The Great Gatsby',\n          },\n        },\n        ids: ['tgg'],\n      })\n    })\n\n    test('upsertOne (update)', () => {\n      const withOne = adapter.upsertOne(state, TheGreatGatsby)\n      const result = createNextState(withOne, (draft) => {\n        adapter.upsertOne(draft, {\n          id: TheGreatGatsby.id,\n          title: 'A New Hope',\n        })\n      })\n      expect(result).toEqual({\n        entities: {\n          tgg: {\n            id: 'tgg',\n            title: 'A New Hope',\n          },\n        },\n        ids: ['tgg'],\n      })\n    })\n\n    test('upsertMany', () => {\n      const withOne = adapter.upsertOne(state, TheGreatGatsby)\n      const result = createNextState(withOne, (draft) => {\n        adapter.upsertMany(draft, [\n          {\n            id: TheGreatGatsby.id,\n            title: 'A New Hope',\n          },\n          AnimalFarm,\n        ])\n      })\n      expect(result).toEqual({\n        entities: {\n          af: {\n            id: 'af',\n            title: 'Animal Farm',\n          },\n          tgg: {\n            id: 'tgg',\n            title: 'A New Hope',\n          },\n        },\n        ids: ['tgg', 'af'],\n      })\n    })\n\n    test('setOne (insert)', () => {\n      const result = createNextState(state, (draft) => {\n        adapter.setOne(draft, TheGreatGatsby)\n      })\n      expect(result).toEqual({\n        entities: {\n          tgg: {\n            id: 'tgg',\n            title: 'The Great Gatsby',\n          },\n        },\n        ids: ['tgg'],\n      })\n    })\n\n    test('setOne (update)', () => {\n      const withOne = adapter.setOne(state, TheHobbit)\n      const result = createNextState(withOne, (draft) => {\n        adapter.setOne(draft, {\n          id: TheHobbit.id,\n          title: 'Silmarillion',\n        })\n      })\n      expect(result).toEqual({\n        entities: {\n          th: {\n            id: 'th',\n            title: 'Silmarillion',\n          },\n        },\n        ids: ['th'],\n      })\n    })\n\n    test('setMany', () => {\n      const withOne = adapter.setOne(state, TheHobbit)\n      const result = createNextState(withOne, (draft) => {\n        adapter.setMany(draft, [\n          {\n            id: TheHobbit.id,\n            title: 'Silmarillion',\n          },\n          AnimalFarm,\n        ])\n      })\n      expect(result).toEqual({\n        entities: {\n          af: {\n            id: 'af',\n            title: 'Animal Farm',\n          },\n          th: {\n            id: 'th',\n            title: 'Silmarillion',\n          },\n        },\n        ids: ['af', 'th'],\n      })\n    })\n\n    test('removeOne', () => {\n      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])\n      const result = createNextState(withTwo, (draft) => {\n        adapter.removeOne(draft, TheGreatGatsby.id)\n      })\n      expect(result).toEqual({\n        entities: {\n          af: {\n            id: 'af',\n            title: 'Animal Farm',\n          },\n        },\n        ids: ['af'],\n      })\n    })\n\n    test('removeMany', () => {\n      const withThree = adapter.addMany(state, [\n        TheGreatGatsby,\n        AnimalFarm,\n        AClockworkOrange,\n      ])\n      const result = createNextState(withThree, (draft) => {\n        adapter.removeMany(draft, [TheGreatGatsby.id, AnimalFarm.id])\n      })\n      expect(result).toEqual({\n        entities: {\n          aco: {\n            id: 'aco',\n            title: 'A Clockwork Orange',\n          },\n        },\n        ids: ['aco'],\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/entities/tests/state_adapter.test.ts",
    "content": "import type { EntityAdapter, PayloadAction } from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createEntityAdapter,\n  createSlice,\n} from '@reduxjs/toolkit'\nimport type { BookModel } from './fixtures/book'\n\ndescribe('createStateOperator', () => {\n  let adapter: EntityAdapter<BookModel, string>\n\n  beforeEach(() => {\n    adapter = createEntityAdapter({\n      selectId: (book: BookModel) => book.id,\n    })\n  })\n  it('Correctly mutates a draft state when inside `createNextState', () => {\n    const booksSlice = createSlice({\n      name: 'books',\n      initialState: adapter.getInitialState(),\n      reducers: {\n        // We should be able to call an adapter method as a mutating helper in a larger reducer\n        addOne(state, action: PayloadAction<BookModel>) {\n          // Originally, having nested `produce` calls don't mutate `state` here as I would have expected.\n          // (note that `state` here is actually an Immer Draft<S>, from `createReducer`)\n          // One woarkound was to return the new plain result value instead\n          // See https://github.com/immerjs/immer/issues/533\n          // However, after tweaking `createStateOperator` to check if the argument is a draft,\n          // we can just treat the operator as strictly mutating, without returning a result,\n          // and the result should be correct.\n          const result = adapter.addOne(state, action)\n          expect(result.ids.length).toBe(1)\n          //Deliberately _don't_ return result\n        },\n        // We should also be able to pass them individually as case reducers\n        addAnother: adapter.addOne,\n      },\n    })\n\n    const { addOne, addAnother } = booksSlice.actions\n\n    const store = configureStore({\n      reducer: {\n        books: booksSlice.reducer,\n      },\n    })\n\n    const book1: BookModel = { id: 'a', title: 'First' }\n    store.dispatch(addOne(book1))\n\n    const state1 = store.getState()\n    expect(state1.books.ids.length).toBe(1)\n    expect(state1.books.entities['a']).toBe(book1)\n\n    const book2: BookModel = { id: 'b', title: 'Second' }\n    store.dispatch(addAnother(book2))\n\n    const state2 = store.getState()\n    expect(state2.books.ids.length).toBe(2)\n    expect(state2.books.entities['b']).toBe(book2)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/entities/tests/state_selectors.test.ts",
    "content": "import type {\n  EntityAdapter,\n  EntitySelectors,\n  EntityState,\n} from '@reduxjs/toolkit'\nimport {\n  createDraftSafeSelectorCreator,\n  createEntityAdapter,\n} from '@reduxjs/toolkit'\nimport type { BookModel } from './fixtures/book'\nimport { AClockworkOrange, AnimalFarm, TheGreatGatsby } from './fixtures/book'\n\ndescribe('Entity State Selectors', () => {\n  describe('Composed Selectors', () => {\n    interface State {\n      books: EntityState<BookModel, string>\n    }\n\n    let adapter: EntityAdapter<BookModel, string>\n    let selectors: EntitySelectors<BookModel, State, string>\n    let state: State\n\n    beforeEach(() => {\n      adapter = createEntityAdapter({\n        selectId: (book: BookModel) => book.id,\n      })\n\n      state = {\n        books: adapter.setAll(adapter.getInitialState(), [\n          AClockworkOrange,\n          AnimalFarm,\n          TheGreatGatsby,\n        ]),\n      }\n\n      selectors = adapter.getSelectors((state: State) => state.books)\n    })\n\n    it('should create a selector for selecting the ids', () => {\n      const ids = selectors.selectIds(state)\n\n      expect(ids).toEqual(state.books.ids)\n    })\n\n    it('should create a selector for selecting the entities', () => {\n      const entities = selectors.selectEntities(state)\n\n      expect(entities).toEqual(state.books.entities)\n    })\n\n    it('should create a selector for selecting the list of models', () => {\n      const models = selectors.selectAll(state)\n\n      expect(models).toEqual([AClockworkOrange, AnimalFarm, TheGreatGatsby])\n    })\n\n    it('should create a selector for selecting the count of models', () => {\n      const total = selectors.selectTotal(state)\n\n      expect(total).toEqual(3)\n    })\n\n    it('should create a selector for selecting a single item by ID', () => {\n      const first = selectors.selectById(state, AClockworkOrange.id)\n      expect(first).toBe(AClockworkOrange)\n      const second = selectors.selectById(state, AnimalFarm.id)\n      expect(second).toBe(AnimalFarm)\n    })\n  })\n\n  describe('Uncomposed Selectors', () => {\n    type State = EntityState<BookModel, string>\n\n    let adapter: EntityAdapter<BookModel, string>\n    let selectors: EntitySelectors<\n      BookModel,\n      EntityState<BookModel, string>,\n      string\n    >\n    let state: State\n\n    beforeEach(() => {\n      adapter = createEntityAdapter({\n        selectId: (book: BookModel) => book.id,\n      })\n\n      state = adapter.setAll(adapter.getInitialState(), [\n        AClockworkOrange,\n        AnimalFarm,\n        TheGreatGatsby,\n      ])\n\n      selectors = adapter.getSelectors()\n    })\n\n    it('should create a selector for selecting the ids', () => {\n      const ids = selectors.selectIds(state)\n\n      expect(ids).toEqual(state.ids)\n    })\n\n    it('should create a selector for selecting the entities', () => {\n      const entities = selectors.selectEntities(state)\n\n      expect(entities).toEqual(state.entities)\n    })\n\n    it('should create a selector for selecting the list of models', () => {\n      const models = selectors.selectAll(state)\n\n      expect(models).toEqual([AClockworkOrange, AnimalFarm, TheGreatGatsby])\n    })\n\n    it('should create a selector for selecting the count of models', () => {\n      const total = selectors.selectTotal(state)\n\n      expect(total).toEqual(3)\n    })\n\n    it('should create a selector for selecting a single item by ID', () => {\n      const first = selectors.selectById(state, AClockworkOrange.id)\n      expect(first).toBe(AClockworkOrange)\n      const second = selectors.selectById(state, AnimalFarm.id)\n      expect(second).toBe(AnimalFarm)\n    })\n  })\n  describe('custom createSelector instance', () => {\n    it('should use the custom createSelector function if provided', () => {\n      const memoizeSpy = vi.fn(\n        // test that we're allowed to pass memoizers with different options, as long as they're optional\n        <F extends (...args: any[]) => any>(fn: F, param?: boolean) => fn,\n      )\n      const createCustomSelector = createDraftSafeSelectorCreator(memoizeSpy)\n\n      const adapter = createEntityAdapter({\n        selectId: (book: BookModel) => book.id,\n      })\n\n      adapter.getSelectors(undefined, { createSelector: createCustomSelector })\n\n      expect(memoizeSpy).toHaveBeenCalled()\n\n      memoizeSpy.mockClear()\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/entities/tests/unsorted_state_adapter.test.ts",
    "content": "import type { EntityAdapter, EntityState } from '@reduxjs/toolkit'\nimport { createEntityAdapter, createNextState } from '@reduxjs/toolkit'\nimport type { BookModel } from './fixtures/book'\nimport {\n  AClockworkOrange,\n  AnimalFarm,\n  TheGreatGatsby,\n  TheHobbit,\n} from './fixtures/book'\n\ndescribe('Unsorted State Adapter', () => {\n  let adapter: EntityAdapter<BookModel, string>\n  let state: EntityState<BookModel, string>\n\n  beforeAll(() => {\n    //eslint-disable-next-line\n    Object.defineProperty(Array.prototype, 'unwantedField', {\n      enumerable: true,\n      configurable: true,\n      value: 'This should not appear anywhere',\n    })\n  })\n\n  afterAll(() => {\n    delete (Array.prototype as any).unwantedField\n  })\n\n  beforeEach(() => {\n    adapter = createEntityAdapter({\n      selectId: (book: BookModel) => book.id,\n    })\n\n    state = { ids: [], entities: {} }\n  })\n\n  it('should let you add one entity to the state', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    expect(withOneEntity).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n      },\n    })\n  })\n\n  it('should not change state if you attempt to re-add an entity', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const readded = adapter.addOne(withOneEntity, TheGreatGatsby)\n\n    expect(readded).toBe(withOneEntity)\n  })\n\n  it('should let you add many entities to the state', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const withManyMore = adapter.addMany(withOneEntity, [\n      AClockworkOrange,\n      AnimalFarm,\n    ])\n\n    expect(withManyMore).toEqual({\n      ids: [TheGreatGatsby.id, AClockworkOrange.id, AnimalFarm.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n        [AClockworkOrange.id]: AClockworkOrange,\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should let you add many entities to the state from a dictionary', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const withManyMore = adapter.addMany(withOneEntity, {\n      [AClockworkOrange.id]: AClockworkOrange,\n      [AnimalFarm.id]: AnimalFarm,\n    })\n\n    expect(withManyMore).toEqual({\n      ids: [TheGreatGatsby.id, AClockworkOrange.id, AnimalFarm.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n        [AClockworkOrange.id]: AClockworkOrange,\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should let you add the only first occurrence for duplicate ids', () => {\n    const firstEntry = { id: AClockworkOrange.id, author: TheHobbit.author }\n    const secondEntry = { id: AClockworkOrange.id, title: 'Zack' }\n    const withOne = adapter.setAll(state, [TheGreatGatsby])\n    const withMany = adapter.addMany(withOne, [\n      { ...AClockworkOrange, ...firstEntry },\n      { ...AClockworkOrange, ...secondEntry },\n    ])\n\n    expect(withMany).toEqual({\n      ids: [TheGreatGatsby.id, AClockworkOrange.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n        [AClockworkOrange.id]: {\n          ...AClockworkOrange,\n          ...firstEntry,\n        },\n      },\n    })\n  })\n\n  it('should remove existing and add new ones on setAll', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const withAll = adapter.setAll(withOneEntity, [\n      AClockworkOrange,\n      AnimalFarm,\n    ])\n\n    expect(withAll).toEqual({\n      ids: [AClockworkOrange.id, AnimalFarm.id],\n      entities: {\n        [AClockworkOrange.id]: AClockworkOrange,\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should remove existing and add new ones on setAll when passing in a dictionary', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const withAll = adapter.setAll(withOneEntity, {\n      [AClockworkOrange.id]: AClockworkOrange,\n      [AnimalFarm.id]: AnimalFarm,\n    })\n\n    expect(withAll).toEqual({\n      ids: [AClockworkOrange.id, AnimalFarm.id],\n      entities: {\n        [AClockworkOrange.id]: AClockworkOrange,\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should let you add remove an entity from the state', () => {\n    const withOneEntity = adapter.addOne(state, TheGreatGatsby)\n\n    const withoutOne = adapter.removeOne(withOneEntity, TheGreatGatsby.id)\n\n    expect(withoutOne).toEqual({\n      ids: [],\n      entities: {},\n    })\n  })\n\n  it('should let you remove many entities by id from the state', () => {\n    const withAll = adapter.setAll(state, [\n      TheGreatGatsby,\n      AClockworkOrange,\n      AnimalFarm,\n    ])\n\n    const withoutMany = adapter.removeMany(withAll, [\n      TheGreatGatsby.id,\n      AClockworkOrange.id,\n    ])\n\n    expect(withoutMany).toEqual({\n      ids: [AnimalFarm.id],\n      entities: {\n        [AnimalFarm.id]: AnimalFarm,\n      },\n    })\n  })\n\n  it('should let you remove all entities from the state', () => {\n    const withAll = adapter.setAll(state, [\n      TheGreatGatsby,\n      AClockworkOrange,\n      AnimalFarm,\n    ])\n\n    const withoutAll = adapter.removeAll(withAll)\n\n    expect(withoutAll).toEqual({\n      ids: [],\n      entities: {},\n    })\n  })\n\n  it('should let you update an entity in the state', () => {\n    const withOne = adapter.addOne(state, TheGreatGatsby)\n    const changes = { title: 'A New Hope' }\n\n    const withUpdates = adapter.updateOne(withOne, {\n      id: TheGreatGatsby.id,\n      changes,\n    })\n\n    expect(withUpdates).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...changes,\n        },\n      },\n    })\n  })\n\n  it('should not change state if you attempt to update an entity that has not been added', () => {\n    const withUpdates = adapter.updateOne(state, {\n      id: TheGreatGatsby.id,\n      changes: { title: 'A New Title' },\n    })\n\n    expect(withUpdates).toBe(state)\n  })\n\n  it('should not change ids state if you attempt to update an entity that has already been added', () => {\n    const withOne = adapter.addOne(state, TheGreatGatsby)\n    const changes = { title: 'A New Hope' }\n\n    const withUpdates = adapter.updateOne(withOne, {\n      id: TheGreatGatsby.id,\n      changes,\n    })\n\n    expect(withOne.ids).toBe(withUpdates.ids)\n  })\n\n  it('should let you update the id of entity', () => {\n    const withOne = adapter.addOne(state, TheGreatGatsby)\n    const changes = { id: 'A New Id' }\n\n    const withUpdates = adapter.updateOne(withOne, {\n      id: TheGreatGatsby.id,\n      changes,\n    })\n\n    expect(withUpdates).toEqual({\n      ids: [changes.id],\n      entities: {\n        [changes.id]: {\n          ...TheGreatGatsby,\n          ...changes,\n        },\n      },\n    })\n  })\n\n  it('should let you update many entities by id in the state', () => {\n    const firstChange = { title: 'First Change' }\n    const secondChange = { title: 'Second Change' }\n    const withMany = adapter.setAll(state, [TheGreatGatsby, AClockworkOrange])\n\n    const withUpdates = adapter.updateMany(withMany, [\n      { id: TheGreatGatsby.id, changes: firstChange },\n      { id: AClockworkOrange.id, changes: secondChange },\n    ])\n\n    expect(withUpdates).toEqual({\n      ids: [TheGreatGatsby.id, AClockworkOrange.id],\n      entities: {\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...firstChange,\n        },\n        [AClockworkOrange.id]: {\n          ...AClockworkOrange,\n          ...secondChange,\n        },\n      },\n    })\n  })\n\n  it(\"doesn't break when multiple renames of one item occur\", () => {\n    const withA = adapter.addOne(state, { id: 'a', title: 'First' })\n\n    const withUpdates = adapter.updateMany(withA, [\n      { id: 'a', changes: { id: 'b' } },\n      { id: 'a', changes: { id: 'c' } },\n    ])\n\n    const { ids, entities } = withUpdates\n\n    /*\n      Original code failed with a mish-mash of values, like:\n      {\n        ids: [ 'c' ],\n        entities: { b: { id: 'b', title: 'First' }, c: { id: 'c' } }\n      }\n      We now expect that only 'c' will be left:\n      {\n        ids: [ 'c' ],\n        entities: { c: { id: 'c', title: 'First' } }\n      }\n    */\n    expect(ids.length).toBe(1)\n    expect(ids).toEqual(['c'])\n    expect(entities.a).toBeFalsy()\n    expect(entities.b).toBeFalsy()\n    expect(entities.c).toBeTruthy()\n  })\n\n  it('should let you add one entity to the state with upsert()', () => {\n    const withOneEntity = adapter.upsertOne(state, TheGreatGatsby)\n    expect(withOneEntity).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n      },\n    })\n  })\n\n  it('should let you update an entity in the state with upsert()', () => {\n    const withOne = adapter.addOne(state, TheGreatGatsby)\n    const changes = { title: 'A New Hope' }\n\n    const withUpdates = adapter.upsertOne(withOne, {\n      ...TheGreatGatsby,\n      ...changes,\n    })\n    expect(withUpdates).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...changes,\n        },\n      },\n    })\n  })\n\n  it('should let you upsert many entities in the state', () => {\n    const firstChange = { title: 'First Change' }\n    const withMany = adapter.setAll(state, [TheGreatGatsby])\n\n    const withUpserts = adapter.upsertMany(withMany, [\n      { ...TheGreatGatsby, ...firstChange },\n      AClockworkOrange,\n    ])\n\n    expect(withUpserts).toEqual({\n      ids: [TheGreatGatsby.id, AClockworkOrange.id],\n      entities: {\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...firstChange,\n        },\n        [AClockworkOrange.id]: AClockworkOrange,\n      },\n    })\n  })\n\n  it('should let you upsert many entities in the state when passing in a dictionary', () => {\n    const firstChange = { title: 'Zack' }\n    const withMany = adapter.setAll(state, [TheGreatGatsby])\n\n    const withUpserts = adapter.upsertMany(withMany, {\n      [TheGreatGatsby.id]: { ...TheGreatGatsby, ...firstChange },\n      [AClockworkOrange.id]: AClockworkOrange,\n    })\n\n    expect(withUpserts).toEqual({\n      ids: [TheGreatGatsby.id, AClockworkOrange.id],\n      entities: {\n        [TheGreatGatsby.id]: {\n          ...TheGreatGatsby,\n          ...firstChange,\n        },\n        [AClockworkOrange.id]: AClockworkOrange,\n      },\n    })\n  })\n\n  it('should let you add a new entity then apply changes to it', () => {\n    const firstChange = { author: TheHobbit.author }\n    const secondChange = { title: 'Zack' }\n    const withMany = adapter.setAll(state, [TheGreatGatsby])\n\n    const withUpserts = adapter.upsertMany(withMany, [\n      { ...AClockworkOrange },\n      { ...AClockworkOrange, ...firstChange },\n      { ...AClockworkOrange, ...secondChange },\n    ])\n\n    expect(withUpserts).toEqual({\n      ids: [TheGreatGatsby.id, AClockworkOrange.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n        [AClockworkOrange.id]: {\n          ...AClockworkOrange,\n          ...firstChange,\n          ...secondChange,\n        },\n      },\n    })\n  })\n\n  it('should let you add a new entity in the state with setOne()', () => {\n    const withOne = adapter.setOne(state, TheGreatGatsby)\n    expect(withOne).toEqual({\n      ids: [TheGreatGatsby.id],\n      entities: {\n        [TheGreatGatsby.id]: TheGreatGatsby,\n      },\n    })\n  })\n\n  it('should let you replace an entity in the state with setOne()', () => {\n    let withOne = adapter.setOne(state, TheHobbit)\n    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }\n    withOne = adapter.setOne(withOne, changeWithoutAuthor)\n\n    expect(withOne).toEqual({\n      ids: [TheHobbit.id],\n      entities: {\n        [TheHobbit.id]: changeWithoutAuthor,\n      },\n    })\n  })\n\n  it('should let you set many entities in the state', () => {\n    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }\n    const withMany = adapter.setAll(state, [TheHobbit])\n\n    const withSetMany = adapter.setMany(withMany, [\n      changeWithoutAuthor,\n      AClockworkOrange,\n    ])\n\n    expect(withSetMany).toEqual({\n      ids: [TheHobbit.id, AClockworkOrange.id],\n      entities: {\n        [TheHobbit.id]: changeWithoutAuthor,\n        [AClockworkOrange.id]: AClockworkOrange,\n      },\n    })\n  })\n\n  it('should let you set many entities in the state when passing in a dictionary', () => {\n    const changeWithoutAuthor = { id: TheHobbit.id, title: 'Silmarillion' }\n    const withMany = adapter.setAll(state, [TheHobbit])\n\n    const withSetMany = adapter.setMany(withMany, {\n      [TheHobbit.id]: changeWithoutAuthor,\n      [AClockworkOrange.id]: AClockworkOrange,\n    })\n\n    expect(withSetMany).toEqual({\n      ids: [TheHobbit.id, AClockworkOrange.id],\n      entities: {\n        [TheHobbit.id]: changeWithoutAuthor,\n        [AClockworkOrange.id]: AClockworkOrange,\n      },\n    })\n  })\n  it(\"only returns one entry for that id in the id's array\", () => {\n    const book1: BookModel = { id: 'a', title: 'First' }\n    const book2: BookModel = { id: 'b', title: 'Second' }\n    const initialState = adapter.getInitialState()\n    const withItems = adapter.addMany(initialState, [book1, book2])\n\n    expect(withItems.ids).toEqual(['a', 'b'])\n    const withUpdate = adapter.updateOne(withItems, {\n      id: 'a',\n      changes: { id: 'b' },\n    })\n\n    expect(withUpdate.ids).toEqual(['b'])\n    expect(withUpdate.entities['b']!.title).toBe(book1.title)\n  })\n\n  describe('can be used mutably when wrapped in createNextState', () => {\n    test('removeAll', () => {\n      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])\n      const result = createNextState(withTwo, (draft) => {\n        adapter.removeAll(draft)\n      })\n      expect(result).toEqual({\n        entities: {},\n        ids: [],\n      })\n    })\n\n    test('addOne', () => {\n      const result = createNextState(state, (draft) => {\n        adapter.addOne(draft, TheGreatGatsby)\n      })\n\n      expect(result).toEqual({\n        entities: {\n          tgg: {\n            id: 'tgg',\n            title: 'The Great Gatsby',\n          },\n        },\n        ids: ['tgg'],\n      })\n    })\n\n    test('addMany', () => {\n      const result = createNextState(state, (draft) => {\n        adapter.addMany(draft, [TheGreatGatsby, AnimalFarm])\n      })\n\n      expect(result).toEqual({\n        entities: {\n          af: {\n            id: 'af',\n            title: 'Animal Farm',\n          },\n          tgg: {\n            id: 'tgg',\n            title: 'The Great Gatsby',\n          },\n        },\n        ids: ['tgg', 'af'],\n      })\n    })\n\n    test('setAll', () => {\n      const result = createNextState(state, (draft) => {\n        adapter.setAll(draft, [TheGreatGatsby, AnimalFarm])\n      })\n\n      expect(result).toEqual({\n        entities: {\n          af: {\n            id: 'af',\n            title: 'Animal Farm',\n          },\n          tgg: {\n            id: 'tgg',\n            title: 'The Great Gatsby',\n          },\n        },\n        ids: ['tgg', 'af'],\n      })\n    })\n\n    test('updateOne', () => {\n      const withOne = adapter.addOne(state, TheGreatGatsby)\n      const changes = { title: 'A New Hope' }\n      const result = createNextState(withOne, (draft) => {\n        adapter.updateOne(draft, {\n          id: TheGreatGatsby.id,\n          changes,\n        })\n      })\n\n      expect(result).toEqual({\n        entities: {\n          tgg: {\n            id: 'tgg',\n            title: 'A New Hope',\n          },\n        },\n        ids: ['tgg'],\n      })\n    })\n\n    test('updateMany', () => {\n      const firstChange = { title: 'First Change' }\n      const secondChange = { title: 'Second Change' }\n      const thirdChange = { title: 'Third Change' }\n      const fourthChange = { author: 'Fourth Change' }\n      const withMany = adapter.setAll(state, [\n        TheGreatGatsby,\n        AClockworkOrange,\n        TheHobbit,\n      ])\n\n      const result = createNextState(withMany, (draft) => {\n        adapter.updateMany(draft, [\n          { id: TheHobbit.id, changes: firstChange },\n          { id: TheGreatGatsby.id, changes: secondChange },\n          { id: AClockworkOrange.id, changes: thirdChange },\n          { id: TheHobbit.id, changes: fourthChange },\n        ])\n      })\n\n      expect(result).toEqual({\n        entities: {\n          aco: {\n            id: 'aco',\n            title: 'Third Change',\n          },\n          tgg: {\n            id: 'tgg',\n            title: 'Second Change',\n          },\n          th: {\n            author: 'Fourth Change',\n            id: 'th',\n            title: 'First Change',\n          },\n        },\n        ids: ['tgg', 'aco', 'th'],\n      })\n    })\n\n    test('upsertOne (insert)', () => {\n      const result = createNextState(state, (draft) => {\n        adapter.upsertOne(draft, TheGreatGatsby)\n      })\n      expect(result).toEqual({\n        entities: {\n          tgg: {\n            id: 'tgg',\n            title: 'The Great Gatsby',\n          },\n        },\n        ids: ['tgg'],\n      })\n    })\n\n    test('upsertOne (update)', () => {\n      const withOne = adapter.upsertOne(state, TheGreatGatsby)\n      const result = createNextState(withOne, (draft) => {\n        adapter.upsertOne(draft, {\n          id: TheGreatGatsby.id,\n          title: 'A New Hope',\n        })\n      })\n      expect(result).toEqual({\n        entities: {\n          tgg: {\n            id: 'tgg',\n            title: 'A New Hope',\n          },\n        },\n        ids: ['tgg'],\n      })\n    })\n\n    test('upsertMany', () => {\n      const withOne = adapter.upsertOne(state, TheGreatGatsby)\n      const result = createNextState(withOne, (draft) => {\n        adapter.upsertMany(draft, [\n          {\n            id: TheGreatGatsby.id,\n            title: 'A New Hope',\n          },\n          AnimalFarm,\n        ])\n      })\n      expect(result).toEqual({\n        entities: {\n          af: {\n            id: 'af',\n            title: 'Animal Farm',\n          },\n          tgg: {\n            id: 'tgg',\n            title: 'A New Hope',\n          },\n        },\n        ids: ['tgg', 'af'],\n      })\n    })\n\n    test('setOne (insert)', () => {\n      const result = createNextState(state, (draft) => {\n        adapter.setOne(draft, TheGreatGatsby)\n      })\n      expect(result).toEqual({\n        entities: {\n          tgg: {\n            id: 'tgg',\n            title: 'The Great Gatsby',\n          },\n        },\n        ids: ['tgg'],\n      })\n    })\n\n    test('setOne (update)', () => {\n      const withOne = adapter.setOne(state, TheHobbit)\n      const result = createNextState(withOne, (draft) => {\n        adapter.setOne(draft, {\n          id: TheHobbit.id,\n          title: 'Silmarillion',\n        })\n      })\n      expect(result).toEqual({\n        entities: {\n          th: {\n            id: 'th',\n            title: 'Silmarillion',\n          },\n        },\n        ids: ['th'],\n      })\n    })\n\n    test('setMany', () => {\n      const withOne = adapter.setOne(state, TheHobbit)\n      const result = createNextState(withOne, (draft) => {\n        adapter.setMany(draft, [\n          {\n            id: TheHobbit.id,\n            title: 'Silmarillion',\n          },\n          AnimalFarm,\n        ])\n      })\n      expect(result).toEqual({\n        entities: {\n          af: {\n            id: 'af',\n            title: 'Animal Farm',\n          },\n          th: {\n            id: 'th',\n            title: 'Silmarillion',\n          },\n        },\n        ids: ['th', 'af'],\n      })\n    })\n\n    test('removeOne', () => {\n      const withTwo = adapter.addMany(state, [TheGreatGatsby, AnimalFarm])\n      const result = createNextState(withTwo, (draft) => {\n        adapter.removeOne(draft, TheGreatGatsby.id)\n      })\n      expect(result).toEqual({\n        entities: {\n          af: {\n            id: 'af',\n            title: 'Animal Farm',\n          },\n        },\n        ids: ['af'],\n      })\n    })\n\n    test('removeMany', () => {\n      const withThree = adapter.addMany(state, [\n        TheGreatGatsby,\n        AnimalFarm,\n        AClockworkOrange,\n      ])\n      const result = createNextState(withThree, (draft) => {\n        adapter.removeMany(draft, [TheGreatGatsby.id, AnimalFarm.id])\n      })\n      expect(result).toEqual({\n        entities: {\n          aco: {\n            id: 'aco',\n            title: 'A Clockwork Orange',\n          },\n        },\n        ids: ['aco'],\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/entities/tests/utils.spec.ts",
    "content": "import { noop } from '@internal/listenerMiddleware/utils'\nimport { AClockworkOrange } from './fixtures/book'\n\ndescribe('Entity utils', () => {\n  describe(`selectIdValue()`, () => {\n    const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)\n\n    beforeEach(() => {\n      vi.resetModules() // this is important - it clears the cache\n      vi.stubEnv('NODE_ENV', 'development')\n    })\n\n    afterEach(() => {\n      vi.unstubAllEnvs()\n      vi.clearAllMocks()\n    })\n\n    afterAll(() => {\n      vi.restoreAllMocks()\n    })\n\n    it('should not warn when key does exist', async () => {\n      const { selectIdValue } = await import('../utils')\n\n      selectIdValue(AClockworkOrange, (book: any) => book.id)\n      expect(consoleWarnSpy).not.toHaveBeenCalled()\n    })\n\n    it('should warn when key does not exist in dev mode', async () => {\n      const { selectIdValue } = await import('../utils')\n\n      expect(process.env.NODE_ENV).toBe('development')\n\n      selectIdValue(AClockworkOrange, (book: any) => book.foo)\n\n      expect(consoleWarnSpy).toHaveBeenCalledOnce()\n    })\n\n    it('should warn when key is undefined in dev mode', async () => {\n      const { selectIdValue } = await import('../utils')\n\n      expect(process.env.NODE_ENV).toBe('development')\n\n      const undefinedAClockworkOrange = { ...AClockworkOrange, id: undefined }\n      selectIdValue(undefinedAClockworkOrange, (book: any) => book.id)\n\n      expect(consoleWarnSpy).toHaveBeenCalledOnce()\n    })\n\n    it('should not warn when key does not exist in prod mode', async () => {\n      vi.stubEnv('NODE_ENV', 'production')\n\n      const { selectIdValue } = await import('../utils')\n\n      selectIdValue(AClockworkOrange, (book: any) => book.foo)\n\n      expect(consoleWarnSpy).not.toHaveBeenCalled()\n    })\n\n    it('should not warn when key is undefined in prod mode', async () => {\n      vi.stubEnv('NODE_ENV', 'production')\n\n      const { selectIdValue } = await import('../utils')\n\n      const undefinedAClockworkOrange = { ...AClockworkOrange, id: undefined }\n      selectIdValue(undefinedAClockworkOrange, (book: any) => book.id)\n\n      expect(consoleWarnSpy).not.toHaveBeenCalled()\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/entities/unsorted_state_adapter.ts",
    "content": "import type { Draft } from 'immer'\nimport type {\n  EntityStateAdapter,\n  IdSelector,\n  Update,\n  EntityId,\n  DraftableEntityState,\n} from './models'\nimport {\n  createStateOperator,\n  createSingleArgumentStateOperator,\n} from './state_adapter'\nimport {\n  selectIdValue,\n  ensureEntitiesArray,\n  splitAddedUpdatedEntities,\n} from './utils'\n\nexport function createUnsortedStateAdapter<T, Id extends EntityId>(\n  selectId: IdSelector<T, Id>,\n): EntityStateAdapter<T, Id> {\n  type R = DraftableEntityState<T, Id>\n\n  function addOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId)\n\n    if (key in state.entities) {\n      return\n    }\n\n    state.ids.push(key as Id & Draft<Id>)\n    ;(state.entities as Record<Id, T>)[key] = entity\n  }\n\n  function addManyMutably(\n    newEntities: readonly T[] | Record<Id, T>,\n    state: R,\n  ): void {\n    newEntities = ensureEntitiesArray(newEntities)\n\n    for (const entity of newEntities) {\n      addOneMutably(entity, state)\n    }\n  }\n\n  function setOneMutably(entity: T, state: R): void {\n    const key = selectIdValue(entity, selectId)\n    if (!(key in state.entities)) {\n      state.ids.push(key as Id & Draft<Id>)\n    }\n    ;(state.entities as Record<Id, T>)[key] = entity\n  }\n\n  function setManyMutably(\n    newEntities: readonly T[] | Record<Id, T>,\n    state: R,\n  ): void {\n    newEntities = ensureEntitiesArray(newEntities)\n    for (const entity of newEntities) {\n      setOneMutably(entity, state)\n    }\n  }\n\n  function setAllMutably(\n    newEntities: readonly T[] | Record<Id, T>,\n    state: R,\n  ): void {\n    newEntities = ensureEntitiesArray(newEntities)\n\n    state.ids = []\n    state.entities = {} as Record<Id, T>\n\n    addManyMutably(newEntities, state)\n  }\n\n  function removeOneMutably(key: Id, state: R): void {\n    return removeManyMutably([key], state)\n  }\n\n  function removeManyMutably(keys: readonly Id[], state: R): void {\n    let didMutate = false\n\n    keys.forEach((key) => {\n      if (key in state.entities) {\n        delete (state.entities as Record<Id, T>)[key]\n        didMutate = true\n      }\n    })\n\n    if (didMutate) {\n      state.ids = (state.ids as Id[]).filter((id) => id in state.entities) as\n        | Id[]\n        | Draft<Id[]>\n    }\n  }\n\n  function removeAllMutably(state: R): void {\n    Object.assign(state, {\n      ids: [],\n      entities: {},\n    })\n  }\n\n  function takeNewKey(\n    keys: { [id: string]: Id },\n    update: Update<T, Id>,\n    state: R,\n  ): boolean {\n    const original: T | undefined = (state.entities as Record<Id, T>)[update.id]\n    if (original === undefined) {\n      return false\n    }\n    const updated: T = Object.assign({}, original, update.changes)\n    const newKey = selectIdValue(updated, selectId)\n    const hasNewKey = newKey !== update.id\n\n    if (hasNewKey) {\n      keys[update.id] = newKey\n      delete (state.entities as Record<Id, T>)[update.id]\n    }\n\n    ;(state.entities as Record<Id, T>)[newKey] = updated\n\n    return hasNewKey\n  }\n\n  function updateOneMutably(update: Update<T, Id>, state: R): void {\n    return updateManyMutably([update], state)\n  }\n\n  function updateManyMutably(\n    updates: ReadonlyArray<Update<T, Id>>,\n    state: R,\n  ): void {\n    const newKeys: { [id: string]: Id } = {}\n\n    const updatesPerEntity: { [id: string]: Update<T, Id> } = {}\n\n    updates.forEach((update) => {\n      // Only apply updates to entities that currently exist\n      if (update.id in state.entities) {\n        // If there are multiple updates to one entity, merge them together\n        updatesPerEntity[update.id] = {\n          id: update.id,\n          // Spreads ignore falsy values, so this works even if there isn't\n          // an existing update already at this key\n          changes: {\n            ...updatesPerEntity[update.id]?.changes,\n            ...update.changes,\n          },\n        }\n      }\n    })\n\n    updates = Object.values(updatesPerEntity)\n\n    const didMutateEntities = updates.length > 0\n\n    if (didMutateEntities) {\n      const didMutateIds =\n        updates.filter((update) => takeNewKey(newKeys, update, state)).length >\n        0\n\n      if (didMutateIds) {\n        state.ids = Object.values(state.entities).map((e) =>\n          selectIdValue(e as T, selectId),\n        )\n      }\n    }\n  }\n\n  function upsertOneMutably(entity: T, state: R): void {\n    return upsertManyMutably([entity], state)\n  }\n\n  function upsertManyMutably(\n    newEntities: readonly T[] | Record<Id, T>,\n    state: R,\n  ): void {\n    const [added, updated] = splitAddedUpdatedEntities<T, Id>(\n      newEntities,\n      selectId,\n      state,\n    )\n\n    addManyMutably(added, state)\n    updateManyMutably(updated, state)\n  }\n\n  return {\n    removeAll: createSingleArgumentStateOperator(removeAllMutably),\n    addOne: createStateOperator(addOneMutably),\n    addMany: createStateOperator(addManyMutably),\n    setOne: createStateOperator(setOneMutably),\n    setMany: createStateOperator(setManyMutably),\n    setAll: createStateOperator(setAllMutably),\n    updateOne: createStateOperator(updateOneMutably),\n    updateMany: createStateOperator(updateManyMutably),\n    upsertOne: createStateOperator(upsertOneMutably),\n    upsertMany: createStateOperator(upsertManyMutably),\n    removeOne: createStateOperator(removeOneMutably),\n    removeMany: createStateOperator(removeManyMutably),\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/entities/utils.ts",
    "content": "import type { Draft } from 'immer'\nimport { current, isDraft } from '../immerImports'\nimport type {\n  DraftableEntityState,\n  EntityId,\n  IdSelector,\n  Update,\n} from './models'\n\nexport function selectIdValue<T, Id extends EntityId>(\n  entity: T,\n  selectId: IdSelector<T, Id>,\n) {\n  const key = selectId(entity)\n\n  if (process.env.NODE_ENV !== 'production' && key === undefined) {\n    console.warn(\n      'The entity passed to the `selectId` implementation returned undefined.',\n      'You should probably provide your own `selectId` implementation.',\n      'The entity that was passed:',\n      entity,\n      'The `selectId` implementation:',\n      selectId.toString(),\n    )\n  }\n\n  return key\n}\n\nexport function ensureEntitiesArray<T, Id extends EntityId>(\n  entities: readonly T[] | Record<Id, T>,\n): readonly T[] {\n  if (!Array.isArray(entities)) {\n    entities = Object.values(entities)\n  }\n\n  return entities\n}\n\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T\n}\n\nexport function splitAddedUpdatedEntities<T, Id extends EntityId>(\n  newEntities: readonly T[] | Record<Id, T>,\n  selectId: IdSelector<T, Id>,\n  state: DraftableEntityState<T, Id>,\n): [T[], Update<T, Id>[], Id[]] {\n  newEntities = ensureEntitiesArray(newEntities)\n\n  const existingIdsArray = getCurrent(state.ids)\n  const existingIds = new Set<Id>(existingIdsArray)\n\n  const added: T[] = []\n  const addedIds = new Set<Id>([])\n  const updated: Update<T, Id>[] = []\n\n  for (const entity of newEntities) {\n    const id = selectIdValue(entity, selectId)\n    if (existingIds.has(id) || addedIds.has(id)) {\n      updated.push({ id, changes: entity })\n    } else {\n      addedIds.add(id)\n      added.push(entity)\n    }\n  }\n  return [added, updated, existingIdsArray]\n}\n"
  },
  {
    "path": "packages/toolkit/src/formatProdErrorMessage.ts",
    "content": "/**\n * Adapted from React: https://github.com/facebook/react/blob/master/packages/shared/formatProdErrorMessage.js\n *\n * Do not require this module directly! Use normal throw error calls. These messages will be replaced with error codes\n * during build.\n * @param {number} code\n */\nexport function formatProdErrorMessage(code: number) {\n  return (\n    `Minified Redux Toolkit error #${code}; visit https://redux-toolkit.js.org/Errors?code=${code} for the full message or ` +\n    'use the non-minified dev environment for full errors. '\n  )\n}\n"
  },
  {
    "path": "packages/toolkit/src/getDefaultEnhancers.ts",
    "content": "import type { StoreEnhancer } from 'redux'\nimport type { AutoBatchOptions } from './autoBatchEnhancer'\nimport { autoBatchEnhancer } from './autoBatchEnhancer'\nimport { Tuple } from './utils'\nimport type { Middlewares } from './configureStore'\nimport type { ExtractDispatchExtensions } from './tsHelpers'\n\ntype GetDefaultEnhancersOptions = {\n  autoBatch?: boolean | AutoBatchOptions\n}\n\nexport type GetDefaultEnhancers<M extends Middlewares<any>> = (\n  options?: GetDefaultEnhancersOptions,\n) => Tuple<[StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>]>\n\nexport const buildGetDefaultEnhancers = <M extends Middlewares<any>>(\n  middlewareEnhancer: StoreEnhancer<{ dispatch: ExtractDispatchExtensions<M> }>,\n): GetDefaultEnhancers<M> =>\n  function getDefaultEnhancers(options) {\n    const { autoBatch = true } = options ?? {}\n\n    let enhancerArray = new Tuple<StoreEnhancer[]>(middlewareEnhancer)\n    if (autoBatch) {\n      enhancerArray.push(\n        autoBatchEnhancer(\n          typeof autoBatch === 'object' ? autoBatch : undefined,\n        ),\n      )\n    }\n    return enhancerArray as any\n  }\n"
  },
  {
    "path": "packages/toolkit/src/getDefaultMiddleware.ts",
    "content": "import type { Middleware, UnknownAction } from 'redux'\nimport type { ThunkMiddleware } from 'redux-thunk'\nimport { thunk as thunkMiddleware, withExtraArgument } from 'redux-thunk'\nimport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'\nimport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'\nimport type { ImmutableStateInvariantMiddlewareOptions } from './immutableStateInvariantMiddleware'\n/* PROD_START_REMOVE_UMD */\nimport { createImmutableStateInvariantMiddleware } from './immutableStateInvariantMiddleware'\n/* PROD_STOP_REMOVE_UMD */\n\nimport type { SerializableStateInvariantMiddlewareOptions } from './serializableStateInvariantMiddleware'\nimport { createSerializableStateInvariantMiddleware } from './serializableStateInvariantMiddleware'\nimport type { ExcludeFromTuple } from './tsHelpers'\nimport { Tuple } from './utils'\n\nfunction isBoolean(x: any): x is boolean {\n  return typeof x === 'boolean'\n}\n\ninterface ThunkOptions<E = any> {\n  extraArgument: E\n}\n\ninterface GetDefaultMiddlewareOptions {\n  thunk?: boolean | ThunkOptions\n  immutableCheck?: boolean | ImmutableStateInvariantMiddlewareOptions\n  serializableCheck?: boolean | SerializableStateInvariantMiddlewareOptions\n  actionCreatorCheck?: boolean | ActionCreatorInvariantMiddlewareOptions\n}\n\nexport type ThunkMiddlewareFor<\n  S,\n  O extends GetDefaultMiddlewareOptions = {},\n> = O extends {\n  thunk: false\n}\n  ? never\n  : O extends { thunk: { extraArgument: infer E } }\n    ? ThunkMiddleware<S, UnknownAction, E>\n    : ThunkMiddleware<S, UnknownAction>\n\nexport type GetDefaultMiddleware<S = any> = <\n  O extends GetDefaultMiddlewareOptions = {\n    thunk: true\n    immutableCheck: true\n    serializableCheck: true\n    actionCreatorCheck: true\n  },\n>(\n  options?: O,\n) => Tuple<ExcludeFromTuple<[ThunkMiddlewareFor<S, O>], never>>\n\nexport const buildGetDefaultMiddleware = <S = any>(): GetDefaultMiddleware<S> =>\n  function getDefaultMiddleware(options) {\n    const {\n      thunk = true,\n      immutableCheck = true,\n      serializableCheck = true,\n      actionCreatorCheck = true,\n    } = options ?? {}\n\n    let middlewareArray = new Tuple<Middleware[]>()\n\n    if (thunk) {\n      if (isBoolean(thunk)) {\n        middlewareArray.push(thunkMiddleware)\n      } else {\n        middlewareArray.push(withExtraArgument(thunk.extraArgument))\n      }\n    }\n\n    if (process.env.NODE_ENV !== 'production') {\n      if (immutableCheck) {\n        /* PROD_START_REMOVE_UMD */\n        let immutableOptions: ImmutableStateInvariantMiddlewareOptions = {}\n\n        if (!isBoolean(immutableCheck)) {\n          immutableOptions = immutableCheck\n        }\n\n        middlewareArray.unshift(\n          createImmutableStateInvariantMiddleware(immutableOptions),\n        )\n        /* PROD_STOP_REMOVE_UMD */\n      }\n\n      if (serializableCheck) {\n        let serializableOptions: SerializableStateInvariantMiddlewareOptions =\n          {}\n\n        if (!isBoolean(serializableCheck)) {\n          serializableOptions = serializableCheck\n        }\n\n        middlewareArray.push(\n          createSerializableStateInvariantMiddleware(serializableOptions),\n        )\n      }\n      if (actionCreatorCheck) {\n        let actionCreatorOptions: ActionCreatorInvariantMiddlewareOptions = {}\n\n        if (!isBoolean(actionCreatorCheck)) {\n          actionCreatorOptions = actionCreatorCheck\n        }\n\n        middlewareArray.unshift(\n          createActionCreatorInvariantMiddleware(actionCreatorOptions),\n        )\n      }\n    }\n\n    return middlewareArray as any\n  }\n"
  },
  {
    "path": "packages/toolkit/src/immerImports.ts",
    "content": "export {\n  current,\n  isDraft,\n  produce as createNextState,\n  isDraftable,\n  setUseStrictIteration,\n} from 'immer'\n"
  },
  {
    "path": "packages/toolkit/src/immutableStateInvariantMiddleware.ts",
    "content": "import type { Middleware } from 'redux'\nimport type { IgnorePaths } from './serializableStateInvariantMiddleware'\nimport { getTimeMeasureUtils } from './utils'\n\ntype EntryProcessor = (key: string, value: any) => any\n\n/**\n * The default `isImmutable` function.\n *\n * @public\n */\nexport function isImmutableDefault(value: unknown): boolean {\n  return typeof value !== 'object' || value == null || Object.isFrozen(value)\n}\n\nexport function trackForMutations(\n  isImmutable: IsImmutableFunc,\n  ignoredPaths: IgnorePaths | undefined,\n  obj: any,\n) {\n  const trackedProperties = trackProperties(isImmutable, ignoredPaths, obj)\n  return {\n    detectMutations() {\n      return detectMutations(isImmutable, ignoredPaths, trackedProperties, obj)\n    },\n  }\n}\n\ninterface TrackedProperty {\n  value: any\n  children: Record<string, any>\n}\n\nfunction trackProperties(\n  isImmutable: IsImmutableFunc,\n  ignoredPaths: IgnorePaths = [],\n  obj: Record<string, any>,\n  path: string = '',\n  checkedObjects: Set<Record<string, any>> = new Set(),\n) {\n  const tracked: Partial<TrackedProperty> = { value: obj }\n\n  if (!isImmutable(obj) && !checkedObjects.has(obj)) {\n    checkedObjects.add(obj)\n    tracked.children = {}\n\n    const hasIgnoredPaths = ignoredPaths.length > 0\n\n    for (const key in obj) {\n      const nestedPath = path ? path + '.' + key : key\n\n      if (hasIgnoredPaths) {\n        const hasMatches = ignoredPaths.some((ignored) => {\n          if (ignored instanceof RegExp) {\n            return ignored.test(nestedPath)\n          }\n          return nestedPath === ignored\n        })\n        if (hasMatches) {\n          continue\n        }\n      }\n\n      tracked.children[key] = trackProperties(\n        isImmutable,\n        ignoredPaths,\n        obj[key],\n        nestedPath,\n      )\n    }\n  }\n  return tracked as TrackedProperty\n}\n\nfunction detectMutations(\n  isImmutable: IsImmutableFunc,\n  ignoredPaths: IgnorePaths = [],\n  trackedProperty: TrackedProperty,\n  obj: any,\n  sameParentRef: boolean = false,\n  path: string = '',\n): { wasMutated: boolean; path?: string } {\n  const prevObj = trackedProperty ? trackedProperty.value : undefined\n\n  const sameRef = prevObj === obj\n\n  if (sameParentRef && !sameRef && !Number.isNaN(obj)) {\n    return { wasMutated: true, path }\n  }\n\n  if (isImmutable(prevObj) || isImmutable(obj)) {\n    return { wasMutated: false }\n  }\n\n  // Gather all keys from prev (tracked) and after objs\n  const keysToDetect: Record<string, boolean> = {}\n  for (let key in trackedProperty.children) {\n    keysToDetect[key] = true\n  }\n  for (let key in obj) {\n    keysToDetect[key] = true\n  }\n\n  const hasIgnoredPaths = ignoredPaths.length > 0\n\n  for (let key in keysToDetect) {\n    const nestedPath = path ? path + '.' + key : key\n\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some((ignored) => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath)\n        }\n        return nestedPath === ignored\n      })\n      if (hasMatches) {\n        continue\n      }\n    }\n\n    const result = detectMutations(\n      isImmutable,\n      ignoredPaths,\n      trackedProperty.children[key],\n      obj[key],\n      sameRef,\n      nestedPath,\n    )\n\n    if (result.wasMutated) {\n      return result\n    }\n  }\n  return { wasMutated: false }\n}\n\ntype IsImmutableFunc = (value: any) => boolean\n\n/**\n * Options for `createImmutableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface ImmutableStateInvariantMiddlewareOptions {\n  /**\n    Callback function to check if a value is considered to be immutable.\n    This function is applied recursively to every value contained in the state.\n    The default implementation will return true for primitive types\n    (like numbers, strings, booleans, null and undefined).\n   */\n  isImmutable?: IsImmutableFunc\n  /**\n    An array of dot-separated path strings that match named nodes from\n    the root state to ignore when checking for immutability.\n    Defaults to undefined\n   */\n  ignoredPaths?: IgnorePaths\n  /** Print a warning if checks take longer than N ms. Default: 32ms */\n  warnAfter?: number\n}\n\n/**\n * Creates a middleware that checks whether any state was mutated in between\n * dispatches or during a dispatch. If any mutations are detected, an error is\n * thrown.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createImmutableStateInvariantMiddleware(\n  options: ImmutableStateInvariantMiddlewareOptions = {},\n): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => (next) => (action) => next(action)\n  } else {\n    function stringify(\n      obj: any,\n      serializer?: EntryProcessor,\n      indent?: string | number,\n      decycler?: EntryProcessor,\n    ): string {\n      return JSON.stringify(obj, getSerialize(serializer, decycler), indent)\n    }\n\n    function getSerialize(\n      serializer?: EntryProcessor,\n      decycler?: EntryProcessor,\n    ): EntryProcessor {\n      let stack: any[] = [],\n        keys: any[] = []\n\n      if (!decycler)\n        decycler = function (_: string, value: any) {\n          if (stack[0] === value) return '[Circular ~]'\n          return (\n            '[Circular ~.' + keys.slice(0, stack.indexOf(value)).join('.') + ']'\n          )\n        }\n\n      return function (this: any, key: string, value: any) {\n        if (stack.length > 0) {\n          var thisPos = stack.indexOf(this)\n          ~thisPos ? stack.splice(thisPos + 1) : stack.push(this)\n          ~thisPos ? keys.splice(thisPos, Infinity, key) : keys.push(key)\n          if (~stack.indexOf(value)) value = decycler!.call(this, key, value)\n        } else stack.push(value)\n\n        return serializer == null ? value : serializer.call(this, key, value)\n      }\n    }\n\n    let {\n      isImmutable = isImmutableDefault,\n      ignoredPaths,\n      warnAfter = 32,\n    } = options\n\n    const track = trackForMutations.bind(null, isImmutable, ignoredPaths)\n\n    return ({ getState }) => {\n      let state = getState()\n      let tracker = track(state)\n\n      let result\n      return (next) => (action) => {\n        const measureUtils = getTimeMeasureUtils(\n          warnAfter,\n          'ImmutableStateInvariantMiddleware',\n        )\n\n        measureUtils.measureTime(() => {\n          state = getState()\n\n          result = tracker.detectMutations()\n          // Track before potentially not meeting the invariant\n          tracker = track(state)\n\n          if (result.wasMutated) {\n            throw new Error(\n              `A state mutation was detected between dispatches, in the path '${\n                result.path || ''\n              }'.  This may cause incorrect behavior. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`,\n            )\n          }\n        })\n\n        const dispatchedAction = next(action)\n\n        measureUtils.measureTime(() => {\n          state = getState()\n\n          result = tracker.detectMutations()\n          // Track before potentially not meeting the invariant\n          tracker = track(state)\n\n          if (result.wasMutated) {\n            throw new Error(\n              `A state mutation was detected inside a dispatch, in the path: ${\n                result.path || ''\n              }. Take a look at the reducer(s) handling the action ${stringify(\n                action,\n              )}. (https://redux.js.org/style-guide/style-guide#do-not-mutate-state)`,\n            )\n          }\n        })\n\n        measureUtils.warnIfExceeded()\n\n        return dispatchedAction\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/index.ts",
    "content": "// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from './formatProdErrorMessage'\n\nexport * from 'redux'\nexport { freeze, original } from 'immer'\nexport { createNextState, current, isDraft } from './immerImports'\nexport type { Draft, WritableDraft } from 'immer'\nexport { createSelector, lruMemoize } from 'reselect'\nexport { createSelectorCreator, weakMapMemoize } from './reselectImports'\nexport type { Selector, OutputSelector } from 'reselect'\nexport {\n  createDraftSafeSelector,\n  createDraftSafeSelectorCreator,\n} from './createDraftSafeSelector'\nexport type { ThunkAction, ThunkDispatch, ThunkMiddleware } from 'redux-thunk'\n\nexport {\n  // js\n  configureStore,\n} from './configureStore'\nexport type {\n  // types\n  ConfigureStoreOptions,\n  EnhancedStore,\n} from './configureStore'\nexport type { DevToolsEnhancerOptions } from './devtoolsExtension'\nexport {\n  // js\n  createAction,\n  isActionCreator,\n  isFSA as isFluxStandardAction,\n} from './createAction'\nexport type {\n  // types\n  PayloadAction,\n  PayloadActionCreator,\n  ActionCreatorWithNonInferrablePayload,\n  ActionCreatorWithOptionalPayload,\n  ActionCreatorWithPayload,\n  ActionCreatorWithoutPayload,\n  ActionCreatorWithPreparedPayload,\n  PrepareAction,\n} from './createAction'\nexport {\n  // js\n  createReducer,\n} from './createReducer'\nexport type {\n  // types\n  Actions,\n  CaseReducer,\n  CaseReducers,\n} from './createReducer'\nexport {\n  // js\n  createSlice,\n  buildCreateSlice,\n  asyncThunkCreator,\n  ReducerType,\n} from './createSlice'\n\nexport type {\n  // types\n  CreateSliceOptions,\n  Slice,\n  CaseReducerActions,\n  SliceCaseReducers,\n  ValidateSliceCaseReducers,\n  CaseReducerWithPrepare,\n  ReducerCreators,\n  SliceSelectors,\n} from './createSlice'\nexport type { ActionCreatorInvariantMiddlewareOptions } from './actionCreatorInvariantMiddleware'\nexport { createActionCreatorInvariantMiddleware } from './actionCreatorInvariantMiddleware'\nexport {\n  // js\n  createImmutableStateInvariantMiddleware,\n  isImmutableDefault,\n} from './immutableStateInvariantMiddleware'\nexport type {\n  // types\n  ImmutableStateInvariantMiddlewareOptions,\n} from './immutableStateInvariantMiddleware'\nexport {\n  // js\n  createSerializableStateInvariantMiddleware,\n  findNonSerializableValue,\n  isPlain,\n} from './serializableStateInvariantMiddleware'\nexport type {\n  // types\n  SerializableStateInvariantMiddlewareOptions,\n} from './serializableStateInvariantMiddleware'\nexport type {\n  // types\n  ActionReducerMapBuilder,\n  AsyncThunkReducers,\n} from './mapBuilders'\nexport { Tuple } from './utils'\n\nexport { createEntityAdapter } from './entities/create_adapter'\nexport type {\n  EntityState,\n  EntityAdapter,\n  EntitySelectors,\n  EntityStateAdapter,\n  EntityId,\n  Update,\n  IdSelector,\n  Comparer,\n} from './entities/models'\n\nexport {\n  createAsyncThunk,\n  unwrapResult,\n  miniSerializeError,\n} from './createAsyncThunk'\nexport type {\n  AsyncThunk,\n  AsyncThunkConfig,\n  AsyncThunkDispatchConfig,\n  AsyncThunkOptions,\n  AsyncThunkAction,\n  AsyncThunkPayloadCreatorReturnValue,\n  AsyncThunkPayloadCreator,\n  GetState,\n  GetThunkAPI,\n  SerializedError,\n  CreateAsyncThunkFunction,\n} from './createAsyncThunk'\n\nexport {\n  // js\n  isAllOf,\n  isAnyOf,\n  isPending,\n  isRejected,\n  isFulfilled,\n  isAsyncThunkAction,\n  isRejectedWithValue,\n} from './matchers'\nexport type {\n  // types\n  ActionMatchingAllOf,\n  ActionMatchingAnyOf,\n} from './matchers'\n\nexport { nanoid } from './nanoid'\n\nexport type {\n  ListenerEffect,\n  ListenerMiddleware,\n  ListenerEffectAPI,\n  ListenerMiddlewareInstance,\n  CreateListenerMiddlewareOptions,\n  ListenerErrorHandler,\n  TypedStartListening,\n  TypedAddListener,\n  TypedStopListening,\n  TypedRemoveListener,\n  UnsubscribeListener,\n  UnsubscribeListenerOptions,\n  ForkedTaskExecutor,\n  ForkedTask,\n  ForkedTaskAPI,\n  AsyncTaskExecutor,\n  SyncTaskExecutor,\n  TaskCancelled,\n  TaskRejected,\n  TaskResolved,\n  TaskResult,\n} from './listenerMiddleware/index'\nexport type { AnyListenerPredicate } from './listenerMiddleware/types'\n\nexport {\n  createListenerMiddleware,\n  addListener,\n  removeListener,\n  clearAllListeners,\n  TaskAbortError,\n} from './listenerMiddleware/index'\n\nexport type {\n  AddMiddleware,\n  DynamicDispatch,\n  DynamicMiddlewareInstance,\n  GetDispatchType as GetDispatch,\n  MiddlewareApiConfig,\n} from './dynamicMiddleware/types'\nexport { createDynamicMiddleware } from './dynamicMiddleware/index'\n\nexport {\n  SHOULD_AUTOBATCH,\n  prepareAutoBatched,\n  autoBatchEnhancer,\n} from './autoBatchEnhancer'\nexport type { AutoBatchOptions } from './autoBatchEnhancer'\n\nexport { combineSlices } from './combineSlices'\n\nexport type {\n  CombinedSliceReducer,\n  WithSlice,\n  WithSlicePreloadedState,\n} from './combineSlices'\n\nexport type {\n  ExtractDispatchExtensions as TSHelpersExtractDispatchExtensions,\n  SafePromise,\n} from './tsHelpers'\n\nexport { formatProdErrorMessage } from './formatProdErrorMessage'\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/exceptions.ts",
    "content": "import type { SerializedError } from '@reduxjs/toolkit'\n\nconst task = 'task'\nconst listener = 'listener'\nconst completed = 'completed'\nconst cancelled = 'cancelled'\n\n/* TaskAbortError error codes  */\nexport const taskCancelled = `task-${cancelled}` as const\nexport const taskCompleted = `task-${completed}` as const\nexport const listenerCancelled = `${listener}-${cancelled}` as const\nexport const listenerCompleted = `${listener}-${completed}` as const\n\nexport class TaskAbortError implements SerializedError {\n  name = 'TaskAbortError'\n  message: string\n  constructor(public code: string | undefined) {\n    this.message = `${task} ${cancelled} (reason: ${code})`\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/index.ts",
    "content": "import type { Action, Dispatch, MiddlewareAPI, UnknownAction } from 'redux'\nimport { isAction } from '../reduxImports'\nimport type { ThunkDispatch } from 'redux-thunk'\nimport { createAction } from '../createAction'\nimport { nanoid } from '../nanoid'\n\nimport {\n  TaskAbortError,\n  listenerCancelled,\n  listenerCompleted,\n  taskCancelled,\n  taskCompleted,\n} from './exceptions'\nimport {\n  createDelay,\n  createPause,\n  raceWithSignal,\n  runTask,\n  validateActive,\n} from './task'\nimport type {\n  AddListenerOverloads,\n  AnyListenerPredicate,\n  CreateListenerMiddlewareOptions,\n  FallbackAddListenerOptions,\n  ForkOptions,\n  ForkedTask,\n  ForkedTaskExecutor,\n  ListenerEntry,\n  ListenerErrorHandler,\n  ListenerErrorInfo,\n  ListenerMiddleware,\n  ListenerMiddlewareInstance,\n  TakePattern,\n  TaskResult,\n  TypedAddListener,\n  TypedCreateListenerEntry,\n  TypedRemoveListener,\n  UnsubscribeListener,\n  UnsubscribeListenerOptions,\n} from './types'\nimport {\n  addAbortSignalListener,\n  assertFunction,\n  catchRejection,\n  noop,\n} from './utils'\nexport { TaskAbortError } from './exceptions'\nexport type {\n  AsyncTaskExecutor,\n  CreateListenerMiddlewareOptions,\n  ForkedTask,\n  ForkedTaskAPI,\n  ForkedTaskExecutor,\n  ListenerEffect,\n  ListenerEffectAPI,\n  ListenerErrorHandler,\n  ListenerMiddleware,\n  ListenerMiddlewareInstance,\n  SyncTaskExecutor,\n  TaskCancelled,\n  TaskRejected,\n  TaskResolved,\n  TaskResult,\n  TypedAddListener,\n  TypedRemoveListener,\n  TypedStartListening,\n  TypedStopListening,\n  UnsubscribeListener,\n  UnsubscribeListenerOptions,\n} from './types'\n\n//Overly-aggressive byte-shaving\nconst { assign } = Object\n/**\n * @internal\n */\nconst INTERNAL_NIL_TOKEN = {} as const\n\nconst alm = 'listenerMiddleware' as const\n\nconst createFork = (\n  parentAbortSignal: AbortSignal,\n  parentBlockingPromises: Promise<any>[],\n) => {\n  const linkControllers = (controller: AbortController) =>\n    addAbortSignalListener(parentAbortSignal, () =>\n      controller.abort(parentAbortSignal.reason),\n    )\n\n  return <T>(\n    taskExecutor: ForkedTaskExecutor<T>,\n    opts?: ForkOptions,\n  ): ForkedTask<T> => {\n    assertFunction(taskExecutor, 'taskExecutor')\n    const childAbortController = new AbortController()\n\n    linkControllers(childAbortController)\n\n    const result = runTask<T>(\n      async (): Promise<T> => {\n        validateActive(parentAbortSignal)\n        validateActive(childAbortController.signal)\n        const result = (await taskExecutor({\n          pause: createPause(childAbortController.signal),\n          delay: createDelay(childAbortController.signal),\n          signal: childAbortController.signal,\n        })) as T\n        validateActive(childAbortController.signal)\n        return result\n      },\n      () => childAbortController.abort(taskCompleted),\n    )\n\n    if (opts?.autoJoin) {\n      parentBlockingPromises.push(result.catch(noop))\n    }\n\n    return {\n      result: createPause<TaskResult<T>>(parentAbortSignal)(result),\n      cancel() {\n        childAbortController.abort(taskCancelled)\n      },\n    }\n  }\n}\n\nconst createTakePattern = <S>(\n  startListening: AddListenerOverloads<UnsubscribeListener, S, Dispatch>,\n  signal: AbortSignal,\n): TakePattern<S> => {\n  /**\n   * A function that takes a ListenerPredicate and an optional timeout,\n   * and resolves when either the predicate returns `true` based on an action\n   * state combination or when the timeout expires.\n   * If the parent listener is canceled while waiting, this will throw a\n   * TaskAbortError.\n   */\n  const take = async <P extends AnyListenerPredicate<S>>(\n    predicate: P,\n    timeout: number | undefined,\n  ) => {\n    validateActive(signal)\n\n    // Placeholder unsubscribe function until the listener is added\n    let unsubscribe: UnsubscribeListener = () => {}\n\n    const tuplePromise = new Promise<[Action, S, S]>((resolve, reject) => {\n      // Inside the Promise, we synchronously add the listener.\n      let stopListening = startListening({\n        predicate: predicate as any,\n        effect: (action, listenerApi): void => {\n          // One-shot listener that cleans up as soon as the predicate passes\n          listenerApi.unsubscribe()\n          // Resolve the promise with the same arguments the predicate saw\n          resolve([\n            action,\n            listenerApi.getState(),\n            listenerApi.getOriginalState(),\n          ])\n        },\n      })\n      unsubscribe = () => {\n        stopListening()\n        reject()\n      }\n    })\n\n    const promises: (Promise<null> | Promise<[Action, S, S]>)[] = [tuplePromise]\n\n    if (timeout != null) {\n      promises.push(\n        new Promise<null>((resolve) => setTimeout(resolve, timeout, null)),\n      )\n    }\n\n    try {\n      const output = await raceWithSignal(signal, Promise.race(promises))\n\n      validateActive(signal)\n      return output\n    } finally {\n      // Always clean up the listener\n      unsubscribe()\n    }\n  }\n\n  return ((predicate: AnyListenerPredicate<S>, timeout: number | undefined) =>\n    catchRejection(take(predicate, timeout))) as TakePattern<S>\n}\n\nconst getListenerEntryPropsFrom = (options: FallbackAddListenerOptions) => {\n  let { type, actionCreator, matcher, predicate, effect } = options\n\n  if (type) {\n    predicate = createAction(type).match\n  } else if (actionCreator) {\n    type = actionCreator!.type\n    predicate = actionCreator.match\n  } else if (matcher) {\n    predicate = matcher\n  } else if (predicate) {\n    // pass\n  } else {\n    throw new Error(\n      'Creating or removing a listener requires one of the known fields for matching an action',\n    )\n  }\n\n  assertFunction(effect, 'options.listener')\n\n  return { predicate, type, effect }\n}\n\n/** Accepts the possible options for creating a listener, and returns a formatted listener entry */\nexport const createListenerEntry: TypedCreateListenerEntry<unknown> =\n  /* @__PURE__ */ assign(\n    (options: FallbackAddListenerOptions) => {\n      const { type, predicate, effect } = getListenerEntryPropsFrom(options)\n\n      const entry: ListenerEntry<unknown> = {\n        id: nanoid(),\n        effect,\n        type,\n        predicate,\n        pending: new Set<AbortController>(),\n        unsubscribe: () => {\n          throw new Error('Unsubscribe not initialized')\n        },\n      }\n\n      return entry\n    },\n    { withTypes: () => createListenerEntry },\n  ) as unknown as TypedCreateListenerEntry<unknown>\n\nconst findListenerEntry = (\n  listenerMap: Map<string, ListenerEntry>,\n  options: FallbackAddListenerOptions,\n) => {\n  const { type, effect, predicate } = getListenerEntryPropsFrom(options)\n\n  return Array.from(listenerMap.values()).find((entry) => {\n    const matchPredicateOrType =\n      typeof type === 'string'\n        ? entry.type === type\n        : entry.predicate === predicate\n\n    return matchPredicateOrType && entry.effect === effect\n  })\n}\n\nconst cancelActiveListeners = (\n  entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,\n) => {\n  entry.pending.forEach((controller) => {\n    controller.abort(listenerCancelled)\n  })\n}\n\nconst createClearListenerMiddleware = (\n  listenerMap: Map<string, ListenerEntry>,\n  executingListeners: Map<ListenerEntry, number>,\n) => {\n  return () => {\n    for (const listener of executingListeners.keys()) {\n      cancelActiveListeners(listener)\n    }\n    listenerMap.clear()\n  }\n}\n\n/**\n * Safely reports errors to the `errorHandler` provided.\n * Errors that occur inside `errorHandler` are notified in a new task.\n * Inspired by [rxjs reportUnhandledError](https://github.com/ReactiveX/rxjs/blob/6fafcf53dc9e557439b25debaeadfd224b245a66/src/internal/util/reportUnhandledError.ts)\n * @param errorHandler\n * @param errorToNotify\n */\nconst safelyNotifyError = (\n  errorHandler: ListenerErrorHandler,\n  errorToNotify: unknown,\n  errorInfo: ListenerErrorInfo,\n): void => {\n  try {\n    errorHandler(errorToNotify, errorInfo)\n  } catch (errorHandlerError) {\n    // We cannot let an error raised here block the listener queue.\n    // The error raised here will be picked up by `window.onerror`, `process.on('error')` etc...\n    setTimeout(() => {\n      throw errorHandlerError\n    }, 0)\n  }\n}\n\n/**\n * @public\n */\nexport const addListener = /* @__PURE__ */ assign(\n  /* @__PURE__ */ createAction(`${alm}/add`),\n  {\n    withTypes: () => addListener,\n  },\n) as unknown as TypedAddListener<unknown>\n\n/**\n * @public\n */\nexport const clearAllListeners = /* @__PURE__ */ createAction(\n  `${alm}/removeAll`,\n)\n\n/**\n * @public\n */\nexport const removeListener = /* @__PURE__ */ assign(\n  /* @__PURE__ */ createAction(`${alm}/remove`),\n  {\n    withTypes: () => removeListener,\n  },\n) as unknown as TypedRemoveListener<unknown>\n\nconst defaultErrorHandler: ListenerErrorHandler = (...args: unknown[]) => {\n  console.error(`${alm}/error`, ...args)\n}\n\n/**\n * @public\n */\nexport const createListenerMiddleware = <\n  StateType = unknown,\n  DispatchType extends Dispatch<Action> = ThunkDispatch<\n    StateType,\n    unknown,\n    UnknownAction\n  >,\n  ExtraArgument = unknown,\n>(\n  middlewareOptions: CreateListenerMiddlewareOptions<ExtraArgument> = {},\n) => {\n  const listenerMap = new Map<string, ListenerEntry>()\n\n  // Track listeners whose effect is currently executing so clearListeners can\n  // abort even listeners that have become unsubscribed while executing.\n  const executingListeners = new Map<ListenerEntry, number>()\n  const trackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 0\n    executingListeners.set(entry, count + 1)\n  }\n  const untrackExecutingListener = (entry: ListenerEntry) => {\n    const count = executingListeners.get(entry) ?? 1\n    if (count === 1) {\n      executingListeners.delete(entry)\n    } else {\n      executingListeners.set(entry, count - 1)\n    }\n  }\n\n  const { extra, onError = defaultErrorHandler } = middlewareOptions\n\n  assertFunction(onError, 'onError')\n\n  const insertEntry = (entry: ListenerEntry) => {\n    entry.unsubscribe = () => listenerMap.delete(entry.id)\n\n    listenerMap.set(entry.id, entry)\n    return (cancelOptions?: UnsubscribeListenerOptions) => {\n      entry.unsubscribe()\n      if (cancelOptions?.cancelActive) {\n        cancelActiveListeners(entry)\n      }\n    }\n  }\n\n  const startListening = ((options: FallbackAddListenerOptions) => {\n    const entry =\n      findListenerEntry(listenerMap, options) ??\n      createListenerEntry(options as any)\n\n    return insertEntry(entry)\n  }) as AddListenerOverloads<any>\n\n  assign(startListening, {\n    withTypes: () => startListening,\n  })\n\n  const stopListening = (\n    options: FallbackAddListenerOptions & UnsubscribeListenerOptions,\n  ): boolean => {\n    const entry = findListenerEntry(listenerMap, options)\n\n    if (entry) {\n      entry.unsubscribe()\n      if (options.cancelActive) {\n        cancelActiveListeners(entry)\n      }\n    }\n\n    return !!entry\n  }\n\n  assign(stopListening, {\n    withTypes: () => stopListening,\n  })\n\n  const notifyListener = async (\n    entry: ListenerEntry<unknown, Dispatch<UnknownAction>>,\n    action: unknown,\n    api: MiddlewareAPI,\n    getOriginalState: () => StateType,\n  ) => {\n    const internalTaskController = new AbortController()\n    const take = createTakePattern(\n      startListening as AddListenerOverloads<any>,\n      internalTaskController.signal,\n    )\n    const autoJoinPromises: Promise<any>[] = []\n\n    try {\n      entry.pending.add(internalTaskController)\n      trackExecutingListener(entry)\n      await Promise.resolve(\n        entry.effect(\n          action,\n          // Use assign() rather than ... to avoid extra helper functions added to bundle\n          assign({}, api, {\n            getOriginalState,\n            condition: (\n              predicate: AnyListenerPredicate<any>,\n              timeout?: number,\n            ) => take(predicate, timeout).then(Boolean),\n            take,\n            delay: createDelay(internalTaskController.signal),\n            pause: createPause<any>(internalTaskController.signal),\n            extra,\n            signal: internalTaskController.signal,\n            fork: createFork(internalTaskController.signal, autoJoinPromises),\n            unsubscribe: entry.unsubscribe,\n            subscribe: () => {\n              listenerMap.set(entry.id, entry)\n            },\n            cancelActiveListeners: () => {\n              entry.pending.forEach((controller, _, set) => {\n                if (controller !== internalTaskController) {\n                  controller.abort(listenerCancelled)\n                  set.delete(controller)\n                }\n              })\n            },\n            cancel: () => {\n              internalTaskController.abort(listenerCancelled)\n              entry.pending.delete(internalTaskController)\n            },\n            throwIfCancelled: () => {\n              validateActive(internalTaskController.signal)\n            },\n          }),\n        ),\n      )\n    } catch (listenerError) {\n      if (!(listenerError instanceof TaskAbortError)) {\n        safelyNotifyError(onError, listenerError, {\n          raisedBy: 'effect',\n        })\n      }\n    } finally {\n      await Promise.all(autoJoinPromises)\n\n      internalTaskController.abort(listenerCompleted) // Notify that the task has completed\n      untrackExecutingListener(entry)\n      entry.pending.delete(internalTaskController)\n    }\n  }\n\n  const clearListenerMiddleware = createClearListenerMiddleware(\n    listenerMap,\n    executingListeners,\n  )\n\n  const middleware: ListenerMiddleware<\n    StateType,\n    DispatchType,\n    ExtraArgument\n  > = (api) => (next) => (action) => {\n    if (!isAction(action)) {\n      // we only want to notify listeners for action objects\n      return next(action)\n    }\n\n    if (addListener.match(action)) {\n      return startListening(action.payload as any)\n    }\n\n    if (clearAllListeners.match(action)) {\n      clearListenerMiddleware()\n      return\n    }\n\n    if (removeListener.match(action)) {\n      return stopListening(action.payload)\n    }\n\n    // Need to get this state _before_ the reducer processes the action\n    let originalState: StateType | typeof INTERNAL_NIL_TOKEN = api.getState()\n\n    // `getOriginalState` can only be called synchronously.\n    // @see https://github.com/reduxjs/redux-toolkit/discussions/1648#discussioncomment-1932820\n    const getOriginalState = (): StateType => {\n      if (originalState === INTERNAL_NIL_TOKEN) {\n        throw new Error(\n          `${alm}: getOriginalState can only be called synchronously`,\n        )\n      }\n\n      return originalState as StateType\n    }\n\n    let result: unknown\n\n    try {\n      // Actually forward the action to the reducer before we handle listeners\n      result = next(action)\n\n      if (listenerMap.size > 0) {\n        const currentState = api.getState()\n        // Work around ESBuild+TS transpilation issue\n        const listenerEntries = Array.from(listenerMap.values())\n        for (const entry of listenerEntries) {\n          let runListener = false\n\n          try {\n            runListener = entry.predicate(action, currentState, originalState)\n          } catch (predicateError) {\n            runListener = false\n\n            safelyNotifyError(onError, predicateError, {\n              raisedBy: 'predicate',\n            })\n          }\n\n          if (!runListener) {\n            continue\n          }\n\n          notifyListener(entry, action, api, getOriginalState)\n        }\n      }\n    } finally {\n      // Remove `originalState` store from this scope.\n      originalState = INTERNAL_NIL_TOKEN\n    }\n\n    return result\n  }\n\n  return {\n    middleware,\n    startListening,\n    stopListening,\n    clearListeners: clearListenerMiddleware,\n  } as ListenerMiddlewareInstance<StateType, DispatchType, ExtraArgument>\n}\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/task.ts",
    "content": "import { TaskAbortError } from './exceptions'\nimport type { TaskResult } from './types'\nimport { addAbortSignalListener, catchRejection, noop } from './utils'\n\n/**\n * Synchronously raises {@link TaskAbortError} if the task tied to the input `signal` has been cancelled.\n * @param signal\n * @see {TaskAbortError}\n * @throws {TaskAbortError} if the task tied to the input `signal` has been cancelled.\n */\nexport const validateActive = (signal: AbortSignal): void => {\n  if (signal.aborted) {\n    throw new TaskAbortError(signal.reason)\n  }\n}\n\n/**\n * Generates a race between the promise(s) and the AbortSignal\n * This avoids `Promise.race()`-related memory leaks:\n * https://github.com/nodejs/node/issues/17469#issuecomment-349794909\n */\nexport function raceWithSignal<T>(\n  signal: AbortSignal,\n  promise: Promise<T>,\n): Promise<T> {\n  let cleanup = noop\n  return new Promise<T>((resolve, reject) => {\n    const notifyRejection = () => reject(new TaskAbortError(signal.reason))\n\n    if (signal.aborted) {\n      notifyRejection()\n      return\n    }\n\n    cleanup = addAbortSignalListener(signal, notifyRejection)\n    promise.finally(() => cleanup()).then(resolve, reject)\n  }).finally(() => {\n    // after this point, replace `cleanup` with a noop, so there is no reference to `signal` any more\n    cleanup = noop\n  })\n}\n\n/**\n * Runs a task and returns promise that resolves to {@link TaskResult}.\n * Second argument is an optional `cleanUp` function that always runs after task.\n *\n * **Note:** `runTask` runs the executor in the next microtask.\n * @returns\n */\nexport const runTask = async <T>(\n  task: () => Promise<T>,\n  cleanUp?: () => void,\n): Promise<TaskResult<T>> => {\n  try {\n    await Promise.resolve()\n    const value = await task()\n    return {\n      status: 'ok',\n      value,\n    }\n  } catch (error: any) {\n    return {\n      status: error instanceof TaskAbortError ? 'cancelled' : 'rejected',\n      error,\n    }\n  } finally {\n    cleanUp?.()\n  }\n}\n\n/**\n * Given an input `AbortSignal` and a promise returns another promise that resolves\n * as soon the input promise is provided or rejects as soon as\n * `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createPause = <T>(signal: AbortSignal) => {\n  return (promise: Promise<T>): Promise<T> => {\n    return catchRejection(\n      raceWithSignal(signal, promise).then((output) => {\n        validateActive(signal)\n        return output\n      }),\n    )\n  }\n}\n\n/**\n * Given an input `AbortSignal` and `timeoutMs` returns a promise that resolves\n * after `timeoutMs` or rejects as soon as `AbortSignal.abort` is `true`.\n * @param signal\n * @returns\n */\nexport const createDelay = (signal: AbortSignal) => {\n  const pause = createPause<void>(signal)\n  return (timeoutMs: number): Promise<void> => {\n    return pause(new Promise<void>((resolve) => setTimeout(resolve, timeoutMs)))\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/tests/effectScenarios.test.ts",
    "content": "import { noop } from '@internal/listenerMiddleware/utils'\nimport type { PayloadAction } from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createAction,\n  createListenerMiddleware,\n  createSlice,\n  isAnyOf,\n  TaskAbortError,\n} from '@reduxjs/toolkit'\n\ndescribe('Saga-style Effects Scenarios', () => {\n  interface CounterState {\n    value: number\n  }\n\n  const counterSlice = createSlice({\n    name: 'counter',\n    initialState: { value: 0 } as CounterState,\n    reducers: {\n      increment(state) {\n        state.value += 1\n      },\n      decrement(state) {\n        state.value -= 1\n      },\n      // Use the PayloadAction type to declare the contents of `action.payload`\n      incrementByAmount: (state, action: PayloadAction<number>) => {\n        state.value += action.payload\n      },\n    },\n  })\n  const { increment, decrement, incrementByAmount } = counterSlice.actions\n\n  let { reducer } = counterSlice\n  let listenerMiddleware = createListenerMiddleware<CounterState>()\n  let { middleware, startListening, stopListening } = listenerMiddleware\n\n  let store = configureStore({\n    reducer,\n    middleware: (gDM) => gDM().prepend(middleware),\n  })\n\n  const testAction1 = createAction<string>('testAction1')\n  type TestAction1 = ReturnType<typeof testAction1>\n  const testAction2 = createAction<string>('testAction2')\n  type TestAction2 = ReturnType<typeof testAction2>\n  const testAction3 = createAction<string>('testAction3')\n  type TestAction3 = ReturnType<typeof testAction3>\n\n  type RootState = ReturnType<typeof store.getState>\n\n  function delay(ms: number) {\n    return new Promise((resolve) => setTimeout(resolve, ms))\n  }\n\n  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n\n  beforeEach(() => {\n    listenerMiddleware = createListenerMiddleware<CounterState>()\n    middleware = listenerMiddleware.middleware\n    startListening = listenerMiddleware.startListening\n    store = configureStore({\n      reducer,\n      middleware: (gDM) => gDM().prepend(middleware),\n    })\n  })\n\n  afterEach(() => {\n    vi.clearAllMocks()\n  })\n\n  afterAll(() => {\n    vi.restoreAllMocks()\n  })\n\n  test('throttle', async () => {\n    // Ignore incoming actions for a given period of time while processing a task.\n    // Ref: https://redux-saga.js.org/docs/api#throttlems-pattern-saga-args\n\n    let listenerCalls = 0\n    let workPerformed = 0\n\n    startListening({\n      actionCreator: increment,\n      effect: (action, listenerApi) => {\n        listenerCalls++\n\n        // Stop listening until further notice\n        listenerApi.unsubscribe()\n\n        // Queue to start listening again after a delay\n        setTimeout(listenerApi.subscribe, 15)\n        workPerformed++\n      },\n    })\n\n    // Dispatch 3 actions. First triggers listener, next two ignored.\n    store.dispatch(increment())\n    store.dispatch(increment())\n    store.dispatch(increment())\n\n    // Wait for resubscription\n    await delay(25)\n\n    // Dispatch 2 more actions, first triggers, second ignored\n    store.dispatch(increment())\n    store.dispatch(increment())\n\n    // Wait for work\n    await delay(5)\n\n    // Both listener calls completed\n    expect(listenerCalls).toBe(2)\n    expect(workPerformed).toBe(2)\n  })\n\n  test('debounce / takeLatest', async () => {\n    // Repeated calls cancel previous ones, no work performed\n    // until the specified delay elapses without another call\n    // NOTE: This is also basically identical to `takeLatest`.\n    // Ref: https://redux-saga.js.org/docs/api#debouncems-pattern-saga-args\n    // Ref: https://redux-saga.js.org/docs/api#takelatestpattern-saga-args\n\n    let listenerCalls = 0\n    let workPerformed = 0\n\n    startListening({\n      actionCreator: increment,\n      effect: async (action, listenerApi) => {\n        listenerCalls++\n\n        // Cancel any in-progress instances of this listener\n        listenerApi.cancelActiveListeners()\n\n        // Delay before starting actual work\n        await listenerApi.delay(15)\n\n        workPerformed++\n      },\n    })\n\n    // First action, listener 1 starts, nothing to cancel\n    store.dispatch(increment())\n    // Second action, listener 2 starts, cancels 1\n    store.dispatch(increment())\n    // Third action, listener 3 starts, cancels 2\n    store.dispatch(increment())\n\n    // 3 listeners started, third is still paused\n    expect(listenerCalls).toBe(3)\n    expect(workPerformed).toBe(0)\n\n    await delay(25)\n\n    // All 3 started\n    expect(listenerCalls).toBe(3)\n    // First two canceled, `delay()` threw JobCanceled and skipped work.\n    // Third actually completed.\n    expect(workPerformed).toBe(1)\n  })\n\n  test('takeEvery', async () => {\n    // Runs the listener on every action match\n    // Ref: https://redux-saga.js.org/docs/api#takeeverypattern-saga-args\n\n    // NOTE: This is already the default behavior - nothing special here!\n\n    let listenerCalls = 0\n    startListening({\n      actionCreator: increment,\n      effect: (action, listenerApi) => {\n        listenerCalls++\n      },\n    })\n\n    store.dispatch(increment())\n    expect(listenerCalls).toBe(1)\n\n    store.dispatch(increment())\n    expect(listenerCalls).toBe(2)\n  })\n\n  test('takeLeading', async () => {\n    // Starts listener on first action, ignores others until task completes\n    // Ref: https://redux-saga.js.org/docs/api#takeleadingpattern-saga-args\n\n    let listenerCalls = 0\n    let workPerformed = 0\n\n    startListening({\n      actionCreator: increment,\n      effect: async (action, listenerApi) => {\n        listenerCalls++\n\n        // Stop listening for this action\n        listenerApi.unsubscribe()\n\n        // Pretend we're doing expensive work\n        await listenerApi.delay(25)\n\n        workPerformed++\n\n        // Re-enable the listener\n        listenerApi.subscribe()\n      },\n    })\n\n    // First action starts the listener, which unsubscribes\n    store.dispatch(increment())\n    // Second action is ignored\n    store.dispatch(increment())\n\n    // One instance in progress, but not complete\n    expect(listenerCalls).toBe(1)\n    expect(workPerformed).toBe(0)\n\n    await delay(5)\n\n    // In-progress listener not done yet\n    store.dispatch(increment())\n\n    // No changes in status\n    expect(listenerCalls).toBe(1)\n    expect(workPerformed).toBe(0)\n\n    await delay(50)\n\n    // Work finished, should have resubscribed\n    expect(workPerformed).toBe(1)\n\n    // Listener is re-subscribed, will trigger again\n    store.dispatch(increment())\n\n    expect(listenerCalls).toBe(2)\n    expect(workPerformed).toBe(1)\n\n    await delay(50)\n\n    expect(workPerformed).toBe(2)\n  })\n\n  test('fork + join', async () => {\n    // fork starts a child job, join waits for the child to complete and return a value\n    // Ref: https://redux-saga.js.org/docs/api#forkfn-args\n    // Ref: https://redux-saga.js.org/docs/api#jointask\n\n    let childResult = 0\n\n    startListening({\n      actionCreator: increment,\n      effect: async (_, listenerApi) => {\n        const childOutput = 42\n        // Spawn a child job and start it immediately\n        const result = await listenerApi.fork(async () => {\n          // Artificially wait a bit inside the child\n          await listenerApi.delay(5)\n          // Complete the child by returning an Outcome-wrapped value\n          return childOutput\n        }).result\n\n        // Unwrap the child result in the listener\n        if (result.status === 'ok') {\n          childResult = result.value\n        }\n      },\n    })\n\n    store.dispatch(increment())\n\n    await delay(10)\n    expect(childResult).toBe(42)\n  })\n\n  test('fork + cancel', async () => {\n    // fork starts a child job, cancel will raise an exception if the\n    // child is paused in the middle of an effect\n    // Ref: https://redux-saga.js.org/docs/api#forkfn-args\n\n    let childResult = 0\n    let listenerCompleted = false\n\n    startListening({\n      actionCreator: increment,\n      effect: async (action, listenerApi) => {\n        // Spawn a child job and start it immediately\n        const forkedTask = listenerApi.fork(async () => {\n          // Artificially wait a bit inside the child\n          await listenerApi.delay(15)\n          // Complete the child by returning an Outcome-wrapped value\n          childResult = 42\n\n          return 0\n        })\n\n        await listenerApi.delay(5)\n        forkedTask.cancel()\n        listenerCompleted = true\n      },\n    })\n\n    // Starts listener, which starts child\n    store.dispatch(increment())\n\n    // Wait for child to have maybe completed\n    await delay(20)\n\n    // Listener finished, but the child was canceled and threw an exception, so it never finished\n    expect(listenerCompleted).toBe(true)\n    expect(childResult).toBe(0)\n  })\n\n  test('canceled', async () => {\n    // canceled allows checking if the current task was canceled\n    // Ref: https://redux-saga.js.org/docs/api#cancelled\n\n    let canceledAndCaught = false\n    let canceledCheck = false\n\n    startListening({\n      matcher: isAnyOf(increment, decrement, incrementByAmount),\n      effect: async (action, listenerApi) => {\n        if (increment.match(action)) {\n          // Have this branch wait around to be canceled by the other\n          try {\n            await listenerApi.delay(10)\n          } catch (err) {\n            // Can check cancelation based on the exception and its reason\n            if (err instanceof TaskAbortError) {\n              canceledAndCaught = true\n            }\n          }\n        } else if (incrementByAmount.match(action)) {\n          // do a non-cancelation-aware wait\n          await delay(15)\n          if (listenerApi.signal.aborted) {\n            canceledCheck = true\n          }\n        } else if (decrement.match(action)) {\n          listenerApi.cancelActiveListeners()\n        }\n      },\n    })\n\n    // Start first branch\n    store.dispatch(increment())\n    // Cancel first listener\n    store.dispatch(decrement())\n\n    // Have to wait for the delay to resolve\n    // TODO Can we make ``Job.delay()` be a race?\n    await delay(15)\n\n    expect(canceledAndCaught).toBe(true)\n\n    // Start second branch\n    store.dispatch(incrementByAmount(42))\n    // Cancel second listener, although it won't know about that until later\n    store.dispatch(decrement())\n\n    expect(canceledCheck).toBe(false)\n\n    await delay(20)\n\n    expect(canceledCheck).toBe(true)\n  })\n\n  test('long-running listener with immediate unsubscribe is cancelable', async () => {\n    let runCount = 0\n    let abortCount = 0\n\n    startListening({\n      actionCreator: increment,\n      effect: async (action, listenerApi) => {\n        runCount++\n\n        // Stop listening for this action\n        listenerApi.unsubscribe()\n\n        try {\n          // Wait indefinitely\n          await listenerApi.condition(() => false)\n        } catch (err) {\n          if (err instanceof TaskAbortError) {\n            abortCount++\n          }\n        }\n      },\n    })\n\n    // First action starts the listener, which unsubscribes\n    store.dispatch(increment())\n    expect(runCount).toBe(1)\n\n    // Verify that the first action unsubscribed the listener\n    store.dispatch(increment())\n    expect(runCount).toBe(1)\n\n    // Now call clearListeners, which should abort the running effect, even\n    // though the listener is no longer subscribed\n    listenerMiddleware.clearListeners()\n    await delay(0)\n\n    expect(abortCount).toBe(1)\n  })\n\n  test('long-running listener with unsubscribe race is cancelable', async () => {\n    let runCount = 0\n    let abortCount = 0\n\n    startListening({\n      actionCreator: increment,\n      effect: async (action, listenerApi) => {\n        runCount++\n\n        if (runCount === 2) {\n          // On the second run, stop listening for this action\n          listenerApi.unsubscribe()\n          return\n        }\n\n        try {\n          // Wait indefinitely\n          await listenerApi.condition(() => false)\n        } catch (err) {\n          if (err instanceof TaskAbortError) {\n            abortCount++\n          }\n        }\n      },\n    })\n\n    // First action starts the hanging effect\n    store.dispatch(increment())\n    expect(runCount).toBe(1)\n\n    // Second action starts the fast effect, which unsubscribes\n    store.dispatch(increment())\n    expect(runCount).toBe(2)\n\n    // Third action should be a noop\n    store.dispatch(increment())\n    expect(runCount).toBe(2)\n\n    // The hanging effect should still be hanging\n    expect(abortCount).toBe(0)\n\n    // Now call clearListeners, which should abort the hanging effect, even\n    // though the listener is no longer subscribed\n    listenerMiddleware.clearListeners()\n    await delay(0)\n\n    expect(abortCount).toBe(1)\n  })\n\n  test('long-running listener with immediate unsubscribe and forked child is cancelable', async () => {\n    let outerAborted = false\n    let innerAborted = false\n\n    startListening({\n      actionCreator: increment,\n      effect: async (action, listenerApi) => {\n        // Stop listening for this action\n        listenerApi.unsubscribe()\n\n        const pollingTask = listenerApi.fork(async (forkApi) => {\n          try {\n            // Cancellation-aware indefinite pause\n            await forkApi.pause(new Promise(() => {}))\n          } catch (err) {\n            if (err instanceof TaskAbortError) {\n              innerAborted = true\n            }\n          }\n        })\n\n        try {\n          // Wait indefinitely\n          await listenerApi.condition(() => false)\n          pollingTask.cancel()\n        } catch (err) {\n          if (err instanceof TaskAbortError) {\n            outerAborted = true\n          }\n        }\n      },\n    })\n\n    store.dispatch(increment())\n    await delay(0)\n\n    listenerMiddleware.clearListeners()\n    await delay(0)\n\n    expect(outerAborted).toBe(true)\n    expect(innerAborted).toBe(true)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/tests/fork.test.ts",
    "content": "import type {\n  ForkedTaskExecutor,\n  PayloadAction,\n  TaskResult,\n} from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createAction,\n  createListenerMiddleware,\n  createSlice,\n  TaskAbortError,\n} from '@reduxjs/toolkit'\nimport {\n  listenerCancelled,\n  listenerCompleted,\n  taskCancelled,\n  taskCompleted,\n} from '../exceptions'\n\nfunction delay(ms: number) {\n  return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n// @see https://deno.land/std@0.95.0/async/deferred.ts (MIT)\nexport interface Deferred<T> extends Promise<T> {\n  resolve(value?: T | PromiseLike<T>): void\n  reject(reason?: any): void\n}\n\n/** Creates a Promise with the `reject` and `resolve` functions\n * placed as methods on the promise object itself. It allows you to do:\n *\n *     const p = deferred<number>();\n *     // ...\n *     p.resolve(42);\n */\nexport function deferred<T>(): Deferred<T> {\n  let methods\n  const promise = new Promise<T>((resolve, reject): void => {\n    methods = { resolve, reject }\n  })\n  return Object.assign(promise, methods) as Deferred<T>\n}\n\ninterface CounterSlice {\n  value: number\n}\n\ndescribe('fork', () => {\n  const counterSlice = createSlice({\n    name: 'counter',\n    initialState: { value: 0 } as CounterSlice,\n    reducers: {\n      increment(state) {\n        state.value += 1\n      },\n      decrement(state) {\n        state.value -= 1\n      },\n      // Use the PayloadAction type to declare the contents of `action.payload`\n      incrementByAmount: (state, action: PayloadAction<number>) => {\n        state.value += action.payload\n      },\n    },\n  })\n  const { increment, decrement, incrementByAmount } = counterSlice.actions\n  let listenerMiddleware = createListenerMiddleware()\n  let { middleware, startListening, stopListening } = listenerMiddleware\n  let store = configureStore({\n    reducer: counterSlice.reducer,\n    middleware: (gDM) => gDM().prepend(middleware),\n  })\n\n  beforeEach(() => {\n    listenerMiddleware = createListenerMiddleware()\n    middleware = listenerMiddleware.middleware\n    startListening = listenerMiddleware.startListening\n    stopListening = listenerMiddleware.stopListening\n    store = configureStore({\n      reducer: counterSlice.reducer,\n      middleware: (gDM) => gDM().prepend(middleware),\n    })\n  })\n\n  it('runs executors in the next microtask', async () => {\n    let hasRunSyncExector = false\n    let hasRunAsyncExecutor = false\n\n    startListening({\n      actionCreator: increment,\n      effect: async (_, listenerApi) => {\n        listenerApi.fork(() => {\n          hasRunSyncExector = true\n        })\n\n        listenerApi.fork(async () => {\n          hasRunAsyncExecutor = true\n        })\n      },\n    })\n\n    store.dispatch(increment())\n\n    expect(hasRunSyncExector).toBe(false)\n    expect(hasRunAsyncExecutor).toBe(false)\n\n    await Promise.resolve()\n\n    expect(hasRunSyncExector).toBe(true)\n    expect(hasRunAsyncExecutor).toBe(true)\n  })\n\n  test('forkedTask.result rejects TaskAbortError if listener is cancelled', async () => {\n    const deferredForkedTaskError = deferred()\n\n    startListening({\n      actionCreator: increment,\n      async effect(_, listenerApi) {\n        listenerApi.cancelActiveListeners()\n        listenerApi\n          .fork(async () => {\n            await delay(10)\n\n            throw new Error('unreachable code')\n          })\n          .result.then(\n            deferredForkedTaskError.resolve,\n            deferredForkedTaskError.resolve,\n          )\n      },\n    })\n\n    store.dispatch(increment())\n    store.dispatch(increment())\n\n    expect(await deferredForkedTaskError).toEqual(\n      new TaskAbortError(listenerCancelled),\n    )\n  })\n\n  it('synchronously throws TypeError error if the provided executor is not a function', () => {\n    const invalidExecutors = [null, {}, undefined, 1]\n\n    startListening({\n      predicate: () => true,\n      effect: async (_, listenerApi) => {\n        invalidExecutors.forEach((invalidExecutor) => {\n          let caughtError\n          try {\n            listenerApi.fork(invalidExecutor as any)\n          } catch (err) {\n            caughtError = err\n          }\n\n          expect(caughtError).toBeInstanceOf(TypeError)\n        })\n      },\n    })\n\n    store.dispatch(increment())\n\n    expect.assertions(invalidExecutors.length)\n  })\n\n  it('does not run an executor if the task is synchronously cancelled', async () => {\n    const storeStateAfter = deferred()\n\n    startListening({\n      actionCreator: increment,\n      effect: async (action, listenerApi) => {\n        const forkedTask = listenerApi.fork(() => {\n          listenerApi.dispatch(decrement())\n          listenerApi.dispatch(decrement())\n          listenerApi.dispatch(decrement())\n        })\n        forkedTask.cancel()\n\n        const result = await forkedTask.result\n        storeStateAfter.resolve(listenerApi.getState())\n      },\n    })\n    store.dispatch(increment())\n\n    await expect(storeStateAfter).resolves.toEqual({ value: 1 })\n  })\n\n  it.each<{\n    desc: string\n    executor: ForkedTaskExecutor<any>\n    cancelAfterMs?: number\n    expected: TaskResult<any>\n  }>([\n    {\n      desc: 'sync exec - success',\n      executor: () => 42,\n      expected: { status: 'ok', value: 42 },\n    },\n    {\n      desc: 'sync exec - error',\n      executor: () => {\n        throw new Error('2020')\n      },\n      expected: { status: 'rejected', error: new Error('2020') },\n    },\n    {\n      desc: 'sync exec - sync cancel',\n      executor: () => 42,\n      cancelAfterMs: -1,\n      expected: {\n        status: 'cancelled',\n        error: new TaskAbortError(taskCancelled),\n      },\n    },\n    {\n      desc: 'sync exec - async cancel',\n      executor: () => 42,\n      cancelAfterMs: 0,\n      expected: { status: 'ok', value: 42 },\n    },\n    {\n      desc: 'async exec - async cancel',\n      executor: async (forkApi) => {\n        await forkApi.delay(100)\n        throw new Error('2020')\n      },\n      cancelAfterMs: 10,\n      expected: {\n        status: 'cancelled',\n        error: new TaskAbortError(taskCancelled),\n      },\n    },\n    {\n      desc: 'async exec - success',\n      executor: async () => {\n        await delay(20)\n        return Promise.resolve(21)\n      },\n      expected: { status: 'ok', value: 21 },\n    },\n    {\n      desc: 'async exec - error',\n      executor: async () => {\n        await Promise.resolve()\n        throw new Error('2020')\n      },\n      expected: { status: 'rejected', error: new Error('2020') },\n    },\n    {\n      desc: 'async exec - success with forkApi.pause',\n      executor: async (forkApi) => {\n        return forkApi.pause(Promise.resolve(2))\n      },\n      expected: { status: 'ok', value: 2 },\n    },\n    {\n      desc: 'async exec - error with forkApi.pause',\n      executor: async (forkApi) => {\n        return forkApi.pause(Promise.reject(22))\n      },\n      expected: { status: 'rejected', error: 22 },\n    },\n    {\n      desc: 'async exec - success with forkApi.delay',\n      executor: async (forkApi) => {\n        await forkApi.delay(10)\n        return 5\n      },\n      expected: { status: 'ok', value: 5 },\n    },\n  ])('$desc', async ({ executor, expected, cancelAfterMs }) => {\n    let deferredResult = deferred()\n    let forkedTask: any = {}\n\n    startListening({\n      predicate: () => true,\n      effect: async (_, listenerApi) => {\n        forkedTask = listenerApi.fork(executor)\n\n        deferredResult.resolve(await forkedTask.result)\n      },\n    })\n\n    store.dispatch({ type: '' })\n\n    if (typeof cancelAfterMs === 'number') {\n      if (cancelAfterMs < 0) {\n        forkedTask.cancel()\n      } else {\n        await delay(cancelAfterMs)\n        forkedTask.cancel()\n      }\n    }\n\n    const result = await deferredResult\n\n    expect(result).toEqual(expected)\n  })\n\n  describe('forkAPI', () => {\n    test('forkApi.delay rejects as soon as the task is cancelled', async () => {\n      let deferredResult = deferred()\n\n      startListening({\n        actionCreator: increment,\n        effect: async (_, listenerApi) => {\n          const forkedTask = listenerApi.fork(async (forkApi) => {\n            await forkApi.delay(100)\n\n            return 4\n          })\n\n          await listenerApi.delay(10)\n          forkedTask.cancel()\n          deferredResult.resolve(await forkedTask.result)\n        },\n      })\n\n      store.dispatch(increment())\n\n      expect(await deferredResult).toEqual({\n        status: 'cancelled',\n        error: new TaskAbortError(taskCancelled),\n      })\n    })\n\n    test('forkApi.delay rejects as soon as the parent listener is cancelled', async () => {\n      let deferredResult = deferred()\n\n      startListening({\n        actionCreator: increment,\n        effect: async (_, listenerApi) => {\n          listenerApi.cancelActiveListeners()\n          await listenerApi.fork(async (forkApi) => {\n            await forkApi\n              .delay(100)\n              .then(deferredResult.resolve, deferredResult.resolve)\n\n            return 4\n          }).result\n\n          deferredResult.resolve(new Error('unreachable'))\n        },\n      })\n\n      store.dispatch(increment())\n\n      await Promise.resolve()\n\n      store.dispatch(increment())\n      expect(await deferredResult).toEqual(\n        new TaskAbortError(listenerCancelled),\n      )\n    })\n\n    it.each([\n      {\n        autoJoin: true,\n        expectedAbortReason: taskCompleted,\n        cancelListener: false,\n      },\n      {\n        autoJoin: false,\n        expectedAbortReason: listenerCompleted,\n        cancelListener: false,\n      },\n      {\n        autoJoin: true,\n        expectedAbortReason: listenerCancelled,\n        cancelListener: true,\n      },\n      {\n        autoJoin: false,\n        expectedAbortReason: listenerCancelled,\n        cancelListener: true,\n      },\n    ])(\n      'signal is $expectedAbortReason when autoJoin: $autoJoin, cancelListener: $cancelListener',\n      async ({ autoJoin, cancelListener, expectedAbortReason }) => {\n        let deferredResult = deferred()\n\n        const unsubscribe = startListening({\n          actionCreator: increment,\n          async effect(_, listenerApi) {\n            listenerApi.fork(\n              async (forkApi) => {\n                forkApi.signal.addEventListener('abort', () => {\n                  deferredResult.resolve(forkApi.signal.reason)\n                })\n\n                await forkApi.delay(10)\n              },\n              { autoJoin },\n            )\n          },\n        })\n\n        store.dispatch(increment())\n\n        // let task start\n        await Promise.resolve()\n\n        if (cancelListener) unsubscribe({ cancelActive: true })\n\n        expect(await deferredResult).toBe(expectedAbortReason)\n      },\n    )\n\n    test('fork.delay does not trigger unhandledRejections for completed or cancelled tasks', async () => {\n      let deferredCompletedEvt = deferred()\n      let deferredCancelledEvt = deferred()\n\n      // Unfortunately we cannot test declaratively unhandleRejections in jest: https://github.com/facebook/jest/issues/5620\n      // This test just fails if an `unhandledRejection` occurs.\n      startListening({\n        actionCreator: increment,\n        effect: async (_, listenerApi) => {\n          const completedTask = listenerApi.fork(async (forkApi) => {\n            forkApi.signal.addEventListener(\n              'abort',\n              deferredCompletedEvt.resolve,\n              { once: true },\n            )\n            forkApi.delay(100) // missing await\n\n            return 4\n          })\n\n          deferredCompletedEvt.resolve(await completedTask.result)\n\n          const godotPauseTrigger = deferred()\n\n          const cancelledTask = listenerApi.fork(async (forkApi) => {\n            forkApi.signal.addEventListener(\n              'abort',\n              deferredCompletedEvt.resolve,\n              { once: true },\n            )\n            forkApi.delay(1_000) // missing await\n            await forkApi.pause(godotPauseTrigger)\n            return 4\n          })\n\n          await Promise.resolve()\n          cancelledTask.cancel()\n          deferredCancelledEvt.resolve(await cancelledTask.result)\n        },\n      })\n\n      store.dispatch(increment())\n      expect(await deferredCompletedEvt).toBeDefined()\n      expect(await deferredCancelledEvt).toBeDefined()\n    })\n  })\n\n  test('forkApi.pause rejects if task is cancelled', async () => {\n    let deferredResult = deferred()\n    startListening({\n      actionCreator: increment,\n      effect: async (_, listenerApi) => {\n        const forkedTask = listenerApi.fork(async (forkApi) => {\n          await forkApi.pause(delay(1_000))\n\n          return 4\n        })\n\n        await Promise.resolve()\n        forkedTask.cancel()\n        deferredResult.resolve(await forkedTask.result)\n      },\n    })\n\n    store.dispatch(increment())\n\n    expect(await deferredResult).toEqual({\n      status: 'cancelled',\n      error: new TaskAbortError(taskCancelled),\n    })\n  })\n\n  test('forkApi.pause rejects as soon as the parent listener is cancelled', async () => {\n    let deferredResult = deferred()\n\n    startListening({\n      actionCreator: increment,\n      effect: async (_, listenerApi) => {\n        listenerApi.cancelActiveListeners()\n        const forkedTask = listenerApi.fork(async (forkApi) => {\n          await forkApi\n            .pause(delay(100))\n            .then(deferredResult.resolve, deferredResult.resolve)\n\n          return 4\n        })\n\n        await forkedTask.result\n        deferredResult.resolve(new Error('unreachable'))\n      },\n    })\n\n    store.dispatch(increment())\n\n    await Promise.resolve()\n\n    store.dispatch(increment())\n    expect(await deferredResult).toEqual(new TaskAbortError(listenerCancelled))\n  })\n\n  test('forkApi.pause rejects if listener is cancelled', async () => {\n    const incrementByInListener = createAction<number>('incrementByInListener')\n\n    startListening({\n      actionCreator: incrementByInListener,\n      async effect({ payload: amountToIncrement }, listenerApi) {\n        listenerApi.cancelActiveListeners()\n        await listenerApi.fork(async (forkApi) => {\n          await forkApi.pause(delay(10))\n          listenerApi.dispatch(incrementByAmount(amountToIncrement))\n        }).result\n        listenerApi.dispatch(incrementByAmount(2 * amountToIncrement))\n      },\n    })\n\n    store.dispatch(incrementByInListener(10))\n    store.dispatch(incrementByInListener(100))\n\n    await delay(50)\n\n    expect(store.getState().value).toEqual(300)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test-d.ts",
    "content": "import { createListenerEntry } from '@internal/listenerMiddleware'\nimport type {\n  Action,\n  PayloadAction,\n  TypedAddListener,\n  TypedStartListening,\n  UnknownAction,\n  UnsubscribeListener,\n} from '@reduxjs/toolkit'\nimport {\n  addListener,\n  configureStore,\n  createAction,\n  createListenerMiddleware,\n  createSlice,\n  isFluxStandardAction,\n} from '@reduxjs/toolkit'\n\nconst listenerMiddleware = createListenerMiddleware()\nconst { startListening } = listenerMiddleware\n\nconst addTypedListenerAction = addListener as TypedAddListener<CounterState>\n\ninterface CounterState {\n  value: number\n}\n\nconst testAction1 = createAction<string>('testAction1')\nconst testAction2 = createAction<string>('testAction2')\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 } as CounterState,\n  reducers: {\n    increment(state) {\n      state.value += 1\n    },\n    decrement(state) {\n      state.value -= 1\n    },\n    // Use the PayloadAction type to declare the contents of `action.payload`\n    incrementByAmount: (state, action: PayloadAction<number>) => {\n      state.value += action.payload\n    },\n  },\n})\n\nconst { increment, decrement, incrementByAmount } = counterSlice.actions\n\ndescribe('type tests', () => {\n  const store = configureStore({\n    reducer: () => 42,\n    middleware: (gDM) => gDM().prepend(createListenerMiddleware().middleware),\n  })\n\n  test('Allows passing an extra argument on middleware creation', () => {\n    const originalExtra = 42\n    const listenerMiddleware = createListenerMiddleware({\n      extra: originalExtra,\n    })\n    const store = configureStore({\n      reducer: counterSlice.reducer,\n      middleware: (gDM) => gDM().prepend(listenerMiddleware.middleware),\n    })\n\n    let foundExtra: number | null = null\n\n    const typedAddListener =\n      listenerMiddleware.startListening as TypedStartListening<\n        CounterState,\n        typeof store.dispatch,\n        typeof originalExtra\n      >\n\n    typedAddListener({\n      matcher: (action): action is Action => true,\n      effect: (action, listenerApi) => {\n        foundExtra = listenerApi.extra\n\n        expectTypeOf(listenerApi.extra).toExtend<typeof originalExtra>()\n      },\n    })\n\n    store.dispatch(testAction1('a'))\n    expect(foundExtra).toBe(originalExtra)\n  })\n\n  test('unsubscribing via callback from dispatch', () => {\n    const unsubscribe = store.dispatch(\n      addListener({\n        actionCreator: testAction1,\n        effect: () => {},\n      }),\n    )\n\n    expectTypeOf(unsubscribe).toEqualTypeOf<UnsubscribeListener>()\n\n    store.dispatch(testAction1('a'))\n\n    unsubscribe()\n    store.dispatch(testAction2('b'))\n    store.dispatch(testAction1('c'))\n  })\n\n  test('take resolves to `[A, CurrentState, PreviousState] | null` if a possibly undefined timeout parameter is provided', () => {\n    type ExpectedTakeResultType =\n      | readonly [ReturnType<typeof increment>, CounterState, CounterState]\n      | null\n\n    let timeout: number | undefined = undefined\n    let done = false\n\n    const startAppListening =\n      startListening as TypedStartListening<CounterState>\n    startAppListening({\n      predicate: incrementByAmount.match,\n      effect: async (_, listenerApi) => {\n        let takeResult = await listenerApi.take(increment.match, timeout)\n\n        timeout = 1\n        takeResult = await listenerApi.take(increment.match, timeout)\n        expect(takeResult).toBeNull()\n\n        expectTypeOf(takeResult).toExtend<ExpectedTakeResultType>()\n\n        done = true\n      },\n    })\n\n    expect(done).toBe(true)\n  })\n\n  test('State args default to unknown', () => {\n    createListenerEntry({\n      predicate: (\n        action,\n        currentState,\n        previousState,\n      ): action is UnknownAction => {\n        expectTypeOf(currentState).toBeUnknown()\n\n        expectTypeOf(previousState).toBeUnknown()\n\n        return true\n      },\n      effect: (action, listenerApi) => {\n        const listenerState = listenerApi.getState()\n\n        expectTypeOf(listenerState).toBeUnknown()\n\n        listenerApi.dispatch((dispatch, getState) => {\n          const thunkState = getState()\n\n          expectTypeOf(thunkState).toBeUnknown()\n        })\n      },\n    })\n\n    startListening({\n      predicate: (\n        action,\n        currentState,\n        previousState,\n      ): action is UnknownAction => {\n        expectTypeOf(currentState).toBeUnknown()\n\n        expectTypeOf(previousState).toBeUnknown()\n\n        return true\n      },\n      effect: (action, listenerApi) => {},\n    })\n\n    startListening({\n      matcher: increment.match,\n      effect: (action, listenerApi) => {\n        const listenerState = listenerApi.getState()\n\n        expectTypeOf(listenerState).toBeUnknown()\n\n        listenerApi.dispatch((dispatch, getState) => {\n          const thunkState = getState()\n\n          expectTypeOf(thunkState).toBeUnknown()\n        })\n      },\n    })\n\n    store.dispatch(\n      addListener({\n        predicate: (\n          action,\n          currentState,\n          previousState,\n        ): action is UnknownAction => {\n          expectTypeOf(currentState).toBeUnknown()\n\n          expectTypeOf(previousState).toBeUnknown()\n\n          return true\n        },\n        effect: (action, listenerApi) => {\n          const listenerState = listenerApi.getState()\n\n          expectTypeOf(listenerState).toBeUnknown()\n\n          listenerApi.dispatch((dispatch, getState) => {\n            const thunkState = getState()\n\n            expectTypeOf(thunkState).toBeUnknown()\n          })\n        },\n      }),\n    )\n\n    store.dispatch(\n      addListener({\n        matcher: increment.match,\n        effect: (action, listenerApi) => {\n          const listenerState = listenerApi.getState()\n\n          expectTypeOf(listenerState).toBeUnknown()\n\n          listenerApi.dispatch((dispatch, getState) => {\n            const thunkState = getState()\n\n            expectTypeOf(thunkState).toBeUnknown()\n          })\n        },\n      }),\n    )\n  })\n\n  test('Action type is inferred from args', () => {\n    startListening({\n      type: 'abcd',\n      effect: (action, listenerApi) => {\n        expectTypeOf(action).toEqualTypeOf<{ type: 'abcd' }>()\n      },\n    })\n\n    startListening({\n      actionCreator: incrementByAmount,\n      effect: (action, listenerApi) => {\n        expectTypeOf(action).toExtend<PayloadAction<number>>()\n      },\n    })\n\n    startListening({\n      matcher: incrementByAmount.match,\n      effect: (action, listenerApi) => {\n        expectTypeOf(action).toExtend<PayloadAction<number>>()\n      },\n    })\n\n    startListening({\n      predicate: (\n        action,\n        currentState,\n        previousState,\n      ): action is PayloadAction<number> => {\n        return (\n          isFluxStandardAction(action) && typeof action.payload === 'boolean'\n        )\n      },\n      effect: (action, listenerApi) => {\n        expectTypeOf(action).toEqualTypeOf<PayloadAction<number>>()\n      },\n    })\n\n    startListening({\n      predicate: (action, currentState) => {\n        return (\n          isFluxStandardAction(action) && typeof action.payload === 'number'\n        )\n      },\n      effect: (action, listenerApi) => {\n        expectTypeOf(action).toEqualTypeOf<UnknownAction>()\n      },\n    })\n\n    store.dispatch(\n      addListener({\n        type: 'abcd',\n        effect: (action, listenerApi) => {\n          expectTypeOf(action).toEqualTypeOf<{ type: 'abcd' }>()\n        },\n      }),\n    )\n\n    store.dispatch(\n      addListener({\n        actionCreator: incrementByAmount,\n        effect: (action, listenerApi) => {\n          expectTypeOf(action).toExtend<PayloadAction<number>>()\n        },\n      }),\n    )\n\n    store.dispatch(\n      addListener({\n        matcher: incrementByAmount.match,\n        effect: (action, listenerApi) => {\n          expectTypeOf(action).toExtend<PayloadAction<number>>()\n        },\n      }),\n    )\n  })\n\n  test('Can create a pre-typed middleware', () => {\n    const typedMiddleware = createListenerMiddleware<CounterState>()\n\n    typedMiddleware.startListening({\n      predicate: (\n        action,\n        currentState,\n        previousState,\n      ): action is UnknownAction => {\n        expectTypeOf(currentState).not.toBeAny()\n\n        expectTypeOf(previousState).not.toBeAny()\n\n        expectTypeOf(currentState).toEqualTypeOf<CounterState>()\n\n        expectTypeOf(previousState).toEqualTypeOf<CounterState>()\n\n        return true\n      },\n      effect: (action, listenerApi) => {\n        const listenerState = listenerApi.getState()\n\n        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()\n\n        listenerApi.dispatch((dispatch, getState) => {\n          const thunkState = listenerApi.getState()\n\n          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()\n        })\n      },\n    })\n\n    // Can pass a predicate function with fewer args\n    typedMiddleware.startListening({\n      predicate: (action, currentState): action is PayloadAction<number> => {\n        expectTypeOf(currentState).not.toBeAny()\n\n        expectTypeOf(currentState).toEqualTypeOf<CounterState>()\n\n        return true\n      },\n      effect: (action, listenerApi) => {\n        expectTypeOf(action).toEqualTypeOf<PayloadAction<number>>()\n\n        const listenerState = listenerApi.getState()\n\n        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()\n\n        listenerApi.dispatch((dispatch, getState) => {\n          const thunkState = listenerApi.getState()\n\n          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()\n        })\n      },\n    })\n\n    typedMiddleware.startListening({\n      actionCreator: incrementByAmount,\n      effect: (action, listenerApi) => {\n        const listenerState = listenerApi.getState()\n\n        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()\n\n        listenerApi.dispatch((dispatch, getState) => {\n          const thunkState = listenerApi.getState()\n\n          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()\n        })\n      },\n    })\n\n    store.dispatch(\n      addTypedListenerAction({\n        predicate: (\n          action,\n          currentState,\n          previousState,\n        ): action is ReturnType<typeof incrementByAmount> => {\n          expectTypeOf(currentState).not.toBeAny()\n\n          expectTypeOf(previousState).not.toBeAny()\n\n          expectTypeOf(currentState).toEqualTypeOf<CounterState>()\n\n          expectTypeOf(previousState).toEqualTypeOf<CounterState>()\n\n          return true\n        },\n        effect: (action, listenerApi) => {\n          const listenerState = listenerApi.getState()\n\n          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()\n\n          listenerApi.dispatch((dispatch, getState) => {\n            const thunkState = listenerApi.getState()\n\n            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()\n          })\n        },\n      }),\n    )\n\n    store.dispatch(\n      addTypedListenerAction({\n        predicate: (\n          action,\n          currentState,\n          previousState,\n        ): action is UnknownAction => {\n          expectTypeOf(currentState).not.toBeAny()\n\n          expectTypeOf(previousState).not.toBeAny()\n\n          expectTypeOf(currentState).toEqualTypeOf<CounterState>()\n\n          expectTypeOf(previousState).toEqualTypeOf<CounterState>()\n\n          return true\n        },\n        effect: (action, listenerApi) => {\n          const listenerState = listenerApi.getState()\n\n          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()\n\n          listenerApi.dispatch((dispatch, getState) => {\n            const thunkState = listenerApi.getState()\n\n            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()\n          })\n        },\n      }),\n    )\n  })\n\n  test('Can create pre-typed versions of startListening and addListener', () => {\n    const typedAddListener = startListening as TypedStartListening<CounterState>\n    const typedAddListenerAction = addListener as TypedAddListener<CounterState>\n\n    typedAddListener({\n      predicate: (\n        action,\n        currentState,\n        previousState,\n      ): action is UnknownAction => {\n        expectTypeOf(currentState).not.toBeAny()\n\n        expectTypeOf(previousState).not.toBeAny()\n\n        expectTypeOf(currentState).toEqualTypeOf<CounterState>()\n\n        expectTypeOf(previousState).toEqualTypeOf<CounterState>()\n\n        return true\n      },\n      effect: (action, listenerApi) => {\n        const listenerState = listenerApi.getState()\n\n        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()\n\n        listenerApi.dispatch((dispatch, getState) => {\n          const thunkState = listenerApi.getState()\n\n          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()\n        })\n      },\n    })\n\n    typedAddListener({\n      matcher: incrementByAmount.match,\n      effect: (action, listenerApi) => {\n        const listenerState = listenerApi.getState()\n\n        expectTypeOf(listenerState).toEqualTypeOf<CounterState>()\n\n        listenerApi.dispatch((dispatch, getState) => {\n          const thunkState = listenerApi.getState()\n\n          expectTypeOf(thunkState).toEqualTypeOf<CounterState>()\n        })\n      },\n    })\n\n    store.dispatch(\n      typedAddListenerAction({\n        predicate: (\n          action,\n          currentState,\n          previousState,\n        ): action is UnknownAction => {\n          expectTypeOf(currentState).not.toBeAny()\n\n          expectTypeOf(previousState).not.toBeAny()\n\n          expectTypeOf(currentState).toEqualTypeOf<CounterState>()\n\n          expectTypeOf(previousState).toEqualTypeOf<CounterState>()\n\n          return true\n        },\n        effect: (action, listenerApi) => {\n          const listenerState = listenerApi.getState()\n\n          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()\n\n          listenerApi.dispatch((dispatch, getState) => {\n            const thunkState = listenerApi.getState()\n\n            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()\n          })\n        },\n      }),\n    )\n\n    store.dispatch(\n      typedAddListenerAction({\n        matcher: incrementByAmount.match,\n        effect: (action, listenerApi) => {\n          const listenerState = listenerApi.getState()\n\n          expectTypeOf(listenerState).toEqualTypeOf<CounterState>()\n\n          listenerApi.dispatch((dispatch, getState) => {\n            const thunkState = listenerApi.getState()\n\n            expectTypeOf(thunkState).toEqualTypeOf<CounterState>()\n          })\n        },\n      }),\n    )\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.test.ts",
    "content": "import {\n  listenerCancelled,\n  listenerCompleted,\n} from '@internal/listenerMiddleware/exceptions'\nimport type { AddListenerOverloads } from '@internal/listenerMiddleware/types'\nimport { noop } from '@internal/listenerMiddleware/utils'\nimport type {\n  Action,\n  ListenerEffect,\n  ListenerEffectAPI,\n  PayloadAction,\n  TypedRemoveListener,\n  TypedStartListening,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport {\n  TaskAbortError,\n  addListener,\n  clearAllListeners,\n  configureStore,\n  createAction,\n  createListenerMiddleware,\n  createSlice,\n  isAnyOf,\n  removeListener,\n} from '@reduxjs/toolkit'\nimport type { Mock } from 'vitest'\n\nconst middlewareApi = {\n  getState: expect.any(Function),\n  getOriginalState: expect.any(Function),\n  condition: expect.any(Function),\n  extra: undefined,\n  take: expect.any(Function),\n  signal: expect.any(Object),\n  fork: expect.any(Function),\n  delay: expect.any(Function),\n  pause: expect.any(Function),\n  dispatch: expect.any(Function),\n  unsubscribe: expect.any(Function),\n  subscribe: expect.any(Function),\n  cancelActiveListeners: expect.any(Function),\n  cancel: expect.any(Function),\n  throwIfCancelled: expect.any(Function),\n}\n\n// Copyright 2018-2021 the Deno authors. All rights reserved. MIT license.\nexport interface Deferred<T> extends Promise<T> {\n  resolve(value?: T | PromiseLike<T>): void\n  // deno-lint-ignore no-explicit-any\n  reject(reason?: any): void\n}\n\n/** Creates a Promise with the `reject` and `resolve` functions\n * placed as methods on the promise object itself. It allows you to do:\n *\n *     const p = deferred<number>();\n *     // ...\n *     p.resolve(42);\n */\nexport function deferred<T>(): Deferred<T> {\n  let methods\n  const promise = new Promise<T>((resolve, reject): void => {\n    methods = { resolve, reject }\n  })\n  return Object.assign(promise, methods) as Deferred<T>\n}\n\ndescribe('createListenerMiddleware', () => {\n  let store = configureStore({\n    reducer: () => 42,\n    middleware: (gDM) => gDM().prepend(createListenerMiddleware().middleware),\n  })\n\n  interface CounterState {\n    value: number\n  }\n\n  const counterSlice = createSlice({\n    name: 'counter',\n    initialState: { value: 0 } as CounterState,\n    reducers: {\n      increment(state) {\n        state.value += 1\n      },\n      decrement(state) {\n        state.value -= 1\n      },\n      // Use the PayloadAction type to declare the contents of `action.payload`\n      incrementByAmount: (state, action: PayloadAction<number>) => {\n        state.value += action.payload\n      },\n    },\n  })\n  const { increment, decrement, incrementByAmount } = counterSlice.actions\n\n  function delay(ms: number) {\n    return new Promise((resolve) => setTimeout(resolve, ms))\n  }\n\n  let reducer: Mock\n  let listenerMiddleware = createListenerMiddleware()\n  let { middleware, startListening, stopListening, clearListeners } =\n    listenerMiddleware\n  const removeTypedListenerAction =\n    removeListener as TypedRemoveListener<CounterState>\n\n  const testAction1 = createAction<string>('testAction1')\n  type TestAction1 = ReturnType<typeof testAction1>\n  const testAction2 = createAction<string>('testAction2')\n  type TestAction2 = ReturnType<typeof testAction2>\n  const testAction3 = createAction<string>('testAction3')\n\n  vi.spyOn(console, 'error').mockImplementation(noop)\n\n  beforeEach(() => {\n    listenerMiddleware = createListenerMiddleware()\n    middleware = listenerMiddleware.middleware\n    startListening = listenerMiddleware.startListening\n    stopListening = listenerMiddleware.stopListening\n    clearListeners = listenerMiddleware.clearListeners\n    reducer = vi.fn(() => ({}))\n    store = configureStore({\n      reducer,\n      middleware: (gDM) => gDM().prepend(middleware),\n    })\n  })\n\n  afterEach(() => {\n    vi.clearAllMocks()\n  })\n\n  afterAll(() => {\n    vi.restoreAllMocks()\n  })\n\n  describe('Middleware setup', () => {\n    test('Allows passing an extra argument on middleware creation', () => {\n      const originalExtra = 42\n      const listenerMiddleware = createListenerMiddleware({\n        extra: originalExtra,\n      })\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(listenerMiddleware.middleware),\n      })\n\n      let foundExtra: number | null = null\n\n      const typedAddListener =\n        listenerMiddleware.startListening as TypedStartListening<\n          CounterState,\n          typeof store.dispatch,\n          typeof originalExtra\n        >\n\n      typedAddListener({\n        matcher: (action): action is Action => true,\n        effect: (action, listenerApi) => {\n          foundExtra = listenerApi.extra\n        },\n      })\n\n      store.dispatch(testAction1('a'))\n      expect(foundExtra).toBe(originalExtra)\n    })\n\n    test('Passes through if there are no listeners', () => {\n      const originalAction = testAction1('a')\n      const resultAction = store.dispatch(originalAction)\n      expect(resultAction).toBe(originalAction)\n    })\n  })\n\n  describe('Subscription and unsubscription', () => {\n    test('directly subscribing', () => {\n      const effect = vi.fn((_: TestAction1) => {})\n\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      store.dispatch(testAction1('a'))\n      store.dispatch(testAction2('b'))\n      store.dispatch(testAction1('c'))\n\n      expect(effect.mock.calls).toEqual([\n        [testAction1('a'), middlewareApi],\n        [testAction1('c'), middlewareApi],\n      ])\n    })\n\n    test('stopListening returns true if an entry has been unsubscribed, false otherwise', () => {\n      const effect = vi.fn((_: TestAction1) => {})\n\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      expect(stopListening({ actionCreator: testAction2, effect })).toBe(false)\n      expect(stopListening({ actionCreator: testAction1, effect })).toBe(true)\n    })\n\n    test('dispatch(removeListener({...})) returns true if an entry has been unsubscribed, false otherwise', () => {\n      const effect = vi.fn((_: TestAction1) => {})\n\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      expect(\n        store.dispatch(\n          removeTypedListenerAction({\n            actionCreator: testAction2,\n            effect,\n          }),\n        ),\n      ).toBe(false)\n      expect(\n        store.dispatch(\n          removeTypedListenerAction({\n            actionCreator: testAction1,\n            effect,\n          }),\n        ),\n      ).toBe(true)\n    })\n\n    test('can subscribe with a string action type', () => {\n      const effect = vi.fn((_: UnknownAction) => {})\n\n      store.dispatch(\n        addListener({\n          type: testAction2.type,\n          effect,\n        }),\n      )\n\n      store.dispatch(testAction2('b'))\n      expect(effect.mock.calls).toEqual([[testAction2('b'), middlewareApi]])\n\n      store.dispatch(removeListener({ type: testAction2.type, effect }))\n\n      store.dispatch(testAction2('b'))\n      expect(effect.mock.calls).toEqual([[testAction2('b'), middlewareApi]])\n    })\n\n    test('can subscribe with a matcher function', () => {\n      const effect = vi.fn((_: UnknownAction) => {})\n\n      const isAction1Or2 = isAnyOf(testAction1, testAction2)\n\n      const unsubscribe = startListening({\n        matcher: isAction1Or2,\n        effect,\n      })\n\n      store.dispatch(testAction1('a'))\n      store.dispatch(testAction2('b'))\n      store.dispatch(testAction3('c'))\n      expect(effect.mock.calls).toEqual([\n        [testAction1('a'), middlewareApi],\n        [testAction2('b'), middlewareApi],\n      ])\n\n      unsubscribe()\n\n      store.dispatch(testAction2('b'))\n      expect(effect.mock.calls).toEqual([\n        [testAction1('a'), middlewareApi],\n        [testAction2('b'), middlewareApi],\n      ])\n    })\n\n    test('Can subscribe with an action predicate function', () => {\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n\n      let listener1Calls = 0\n\n      startListening({\n        predicate: (action, state) => {\n          return (state as CounterState).value > 1\n        },\n        effect: () => {\n          listener1Calls++\n        },\n      })\n\n      let listener2Calls = 0\n\n      startListening({\n        predicate: (action, state, prevState) => {\n          return (\n            (state as CounterState).value > 1 &&\n            (prevState as CounterState).value % 2 === 0\n          )\n        },\n        effect: () => {\n          listener2Calls++\n        },\n      })\n\n      store.dispatch(increment())\n      store.dispatch(increment())\n      store.dispatch(increment())\n      store.dispatch(increment())\n\n      expect(listener1Calls).toBe(3)\n      expect(listener2Calls).toBe(1)\n    })\n\n    test('subscribing with the same listener will not make it trigger twice (like EventTarget.addEventListener())', () => {\n      const effect = vi.fn((_: TestAction1) => {})\n\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      store.dispatch(testAction1('a'))\n      store.dispatch(testAction2('b'))\n      store.dispatch(testAction1('c'))\n\n      expect(effect.mock.calls).toEqual([\n        [testAction1('a'), middlewareApi],\n        [testAction1('c'), middlewareApi],\n      ])\n    })\n\n    test('subscribing with the same effect but different predicate is allowed', () => {\n      const effect = vi.fn((_: TestAction1 | TestAction2) => {})\n\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n      startListening({\n        actionCreator: testAction2,\n        effect,\n      })\n\n      store.dispatch(testAction1('a'))\n      store.dispatch(testAction2('b'))\n\n      expect(effect.mock.calls).toEqual([\n        [testAction1('a'), middlewareApi],\n        [testAction2('b'), middlewareApi],\n      ])\n    })\n\n    test('unsubscribing via callback', () => {\n      const effect = vi.fn((_: TestAction1) => {})\n\n      const unsubscribe = startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      store.dispatch(testAction1('a'))\n      unsubscribe()\n      store.dispatch(testAction2('b'))\n      store.dispatch(testAction1('c'))\n\n      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])\n    })\n\n    test('directly unsubscribing', () => {\n      const effect = vi.fn((_: TestAction1) => {})\n\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      store.dispatch(testAction1('a'))\n\n      stopListening({ actionCreator: testAction1, effect })\n      store.dispatch(testAction2('b'))\n      store.dispatch(testAction1('c'))\n\n      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])\n    })\n\n    test('unsubscribing without any subscriptions does not trigger an error', () => {\n      stopListening({ matcher: testAction1.match, effect: noop })\n    })\n\n    test('subscribing via action', () => {\n      const effect = vi.fn((_: TestAction1) => {})\n\n      store.dispatch(\n        addListener({\n          actionCreator: testAction1,\n          effect,\n        }),\n      )\n\n      store.dispatch(testAction1('a'))\n      store.dispatch(testAction2('b'))\n      store.dispatch(testAction1('c'))\n\n      expect(effect.mock.calls).toEqual([\n        [testAction1('a'), middlewareApi],\n        [testAction1('c'), middlewareApi],\n      ])\n    })\n\n    test('unsubscribing via callback from dispatch', () => {\n      const effect = vi.fn((_: TestAction1) => {})\n\n      const unsubscribe = store.dispatch(\n        addListener({\n          actionCreator: testAction1,\n          effect,\n        }),\n      )\n\n      store.dispatch(testAction1('a'))\n\n      unsubscribe()\n      store.dispatch(testAction2('b'))\n      store.dispatch(testAction1('c'))\n\n      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])\n    })\n\n    test('unsubscribing via action', () => {\n      const effect = vi.fn((_: TestAction1) => {})\n\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      store.dispatch(testAction1('a'))\n\n      store.dispatch(removeListener({ actionCreator: testAction1, effect }))\n      store.dispatch(testAction2('b'))\n      store.dispatch(testAction1('c'))\n\n      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])\n    })\n\n    test('can cancel an active listener when unsubscribing directly', async () => {\n      let wasCancelled = false\n      const unsubscribe = startListening({\n        actionCreator: testAction1,\n        effect: async (action, listenerApi) => {\n          try {\n            await listenerApi.condition(testAction2.match)\n          } catch (err) {\n            if (err instanceof TaskAbortError) {\n              wasCancelled = true\n            }\n          }\n        },\n      })\n\n      store.dispatch(testAction1('a'))\n      unsubscribe({ cancelActive: true })\n      expect(wasCancelled).toBe(false)\n      await delay(10)\n      expect(wasCancelled).toBe(true)\n    })\n\n    test('can cancel an active listener when unsubscribing via stopListening', async () => {\n      let wasCancelled = false\n      const effect = async (action: any, listenerApi: any) => {\n        try {\n          await listenerApi.condition(testAction2.match)\n        } catch (err) {\n          if (err instanceof TaskAbortError) {\n            wasCancelled = true\n          }\n        }\n      }\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      store.dispatch(testAction1('a'))\n      stopListening({ actionCreator: testAction1, effect, cancelActive: true })\n      expect(wasCancelled).toBe(false)\n      await delay(10)\n      expect(wasCancelled).toBe(true)\n    })\n\n    test('can cancel an active listener when unsubscribing via removeListener', async () => {\n      let wasCancelled = false\n      const effect = async (action: any, listenerApi: any) => {\n        try {\n          await listenerApi.condition(testAction2.match)\n        } catch (err) {\n          if (err instanceof TaskAbortError) {\n            wasCancelled = true\n          }\n        }\n      }\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      store.dispatch(testAction1('a'))\n      store.dispatch(\n        removeListener({\n          actionCreator: testAction1,\n          effect,\n          cancelActive: true,\n        }),\n      )\n      expect(wasCancelled).toBe(false)\n      await delay(10)\n      expect(wasCancelled).toBe(true)\n    })\n\n    const addListenerOptions: [\n      string,\n      Omit<\n        AddListenerOverloads<\n          () => void,\n          typeof store.getState,\n          typeof store.dispatch\n        >,\n        'effect' | 'withTypes'\n      >,\n    ][] = [\n      ['predicate', { predicate: () => true }],\n      ['actionCreator', { actionCreator: testAction1 }],\n      ['matcher', { matcher: isAnyOf(testAction1, testAction2) }],\n      ['type', { type: testAction1.type }],\n    ]\n\n    test.each(addListenerOptions)(\n      'add and remove listener with \"%s\" param correctly',\n      (_, params) => {\n        const effect: ListenerEffect<\n          UnknownAction,\n          typeof store.getState,\n          typeof store.dispatch\n        > = vi.fn()\n\n        startListening({ ...params, effect } as any)\n\n        store.dispatch(testAction1('a'))\n        expect(effect).toBeCalledTimes(1)\n\n        stopListening({ ...params, effect } as any)\n\n        store.dispatch(testAction1('b'))\n        expect(effect).toBeCalledTimes(1)\n      },\n    )\n\n    const unforwardedActions: [string, UnknownAction][] = [\n      [\n        'addListener',\n        addListener({ actionCreator: testAction1, effect: noop }),\n      ],\n      [\n        'removeListener',\n        removeListener({ actionCreator: testAction1, effect: noop }),\n      ],\n    ]\n    test.each(unforwardedActions)(\n      '\"%s\" is not forwarded to the reducer',\n      (_, action) => {\n        reducer.mockClear()\n\n        store.dispatch(testAction1('a'))\n        store.dispatch(action)\n        store.dispatch(testAction2('b'))\n\n        expect(reducer.mock.calls).toEqual([\n          [{}, testAction1('a')],\n          [{}, testAction2('b')],\n        ])\n      },\n    )\n\n    test('listenerApi.signal has correct reason when listener is cancelled or completes', async () => {\n      const notifyDeferred = createAction<Deferred<string>>('notify-deferred')\n\n      startListening({\n        actionCreator: notifyDeferred,\n        async effect({ payload }, { signal, cancelActiveListeners, delay }) {\n          signal.addEventListener(\n            'abort',\n            () => {\n              payload.resolve(signal.reason)\n            },\n            { once: true },\n          )\n\n          cancelActiveListeners()\n          delay(10)\n        },\n      })\n\n      const deferredCancelledSignalReason = store.dispatch(\n        notifyDeferred(deferred<string>()),\n      ).payload\n      const deferredCompletedSignalReason = store.dispatch(\n        notifyDeferred(deferred<string>()),\n      ).payload\n\n      expect(await deferredCancelledSignalReason).toBe(listenerCancelled)\n      expect(await deferredCompletedSignalReason).toBe(listenerCompleted)\n    })\n\n    test('can self-cancel via middleware api', async () => {\n      const notifyDeferred = createAction<Deferred<string>>('notify-deferred')\n\n      startListening({\n        actionCreator: notifyDeferred,\n        effect: async ({ payload }, { signal, cancel, delay }) => {\n          signal.addEventListener(\n            'abort',\n            () => {\n              payload.resolve(signal.reason)\n            },\n            { once: true },\n          )\n\n          cancel()\n        },\n      })\n\n      const deferredCancelledSignalReason = store.dispatch(\n        notifyDeferred(deferred<string>()),\n      ).payload\n\n      expect(await deferredCancelledSignalReason).toBe(listenerCancelled)\n    })\n\n    test('Can easily check if the listener has been cancelled', async () => {\n      const pauseDeferred = deferred<void>()\n\n      let listenerCancelled = false\n      let listenerStarted = false\n      let listenerCompleted = false\n      let cancelListener: () => void = () => {}\n      let error: TaskAbortError | undefined = undefined\n\n      startListening({\n        actionCreator: testAction1,\n        effect: async ({ payload }, { throwIfCancelled, cancel }) => {\n          cancelListener = cancel\n          try {\n            listenerStarted = true\n            throwIfCancelled()\n            await pauseDeferred\n\n            throwIfCancelled()\n            listenerCompleted = true\n          } catch (err) {\n            if (err instanceof TaskAbortError) {\n              listenerCancelled = true\n              error = err\n            }\n          }\n        },\n      })\n\n      store.dispatch(testAction1('a'))\n      expect(listenerStarted).toBe(true)\n      expect(listenerCompleted).toBe(false)\n      expect(listenerCancelled).toBe(false)\n\n      // Cancel it while the listener is paused at a non-cancel-aware promise\n      cancelListener()\n      pauseDeferred.resolve()\n\n      await delay(10)\n      expect(listenerCompleted).toBe(false)\n      expect(listenerCancelled).toBe(true)\n      expect((error as any)?.message).toBe(\n        'task cancelled (reason: listener-cancelled)',\n      )\n    })\n\n    test('can unsubscribe via middleware api', () => {\n      const effect = vi.fn(\n        (action: TestAction1, api: ListenerEffectAPI<any, any>) => {\n          if (action.payload === 'b') {\n            api.unsubscribe()\n          }\n        },\n      )\n\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      store.dispatch(testAction1('a'))\n      store.dispatch(testAction1('b'))\n      store.dispatch(testAction1('c'))\n\n      expect(effect.mock.calls).toEqual([\n        [testAction1('a'), middlewareApi],\n        [testAction1('b'), middlewareApi],\n      ])\n    })\n\n    test('Can re-subscribe via middleware api', async () => {\n      let numListenerRuns = 0\n      startListening({\n        actionCreator: testAction1,\n        effect: async (action, listenerApi) => {\n          numListenerRuns++\n\n          listenerApi.unsubscribe()\n\n          await listenerApi.condition(testAction2.match)\n\n          listenerApi.subscribe()\n        },\n      })\n\n      store.dispatch(testAction1('a'))\n      expect(numListenerRuns).toBe(1)\n\n      store.dispatch(testAction1('a'))\n      expect(numListenerRuns).toBe(1)\n\n      store.dispatch(testAction2('b'))\n      expect(numListenerRuns).toBe(1)\n\n      await delay(5)\n\n      store.dispatch(testAction1('b'))\n      expect(numListenerRuns).toBe(2)\n    })\n  })\n\n  describe('clear listeners', () => {\n    test('dispatch(clearListenerAction()) cancels running listeners and removes all subscriptions', async () => {\n      const listener1Test = deferred()\n      let listener1Calls = 0\n      let listener2Calls = 0\n      let listener3Calls = 0\n\n      startListening({\n        actionCreator: testAction1,\n        async effect(_, listenerApi) {\n          listener1Calls++\n          listenerApi.signal.addEventListener(\n            'abort',\n            () => listener1Test.resolve(listener1Calls),\n            { once: true },\n          )\n          await listenerApi.condition(() => true)\n          listener1Test.reject(new Error('unreachable: listener1Test'))\n        },\n      })\n\n      startListening({\n        actionCreator: clearAllListeners,\n        effect() {\n          listener2Calls++\n        },\n      })\n\n      startListening({\n        predicate: () => true,\n        effect() {\n          listener3Calls++\n        },\n      })\n\n      store.dispatch(testAction1('a'))\n      store.dispatch(clearAllListeners())\n      store.dispatch(testAction1('b'))\n      expect(await listener1Test).toBe(1)\n      expect(listener1Calls).toBe(1)\n      expect(listener3Calls).toBe(1)\n      expect(listener2Calls).toBe(0)\n    })\n\n    test('clear() cancels running listeners and removes all subscriptions', async () => {\n      const listener1Test = deferred()\n\n      let listener1Calls = 0\n      let listener2Calls = 0\n\n      startListening({\n        actionCreator: testAction1,\n        async effect(_, listenerApi) {\n          listener1Calls++\n          listenerApi.signal.addEventListener(\n            'abort',\n            () => listener1Test.resolve(listener1Calls),\n            { once: true },\n          )\n          await listenerApi.condition(() => true)\n          listener1Test.reject(new Error('unreachable: listener1Test'))\n        },\n      })\n\n      startListening({\n        actionCreator: testAction2,\n        effect() {\n          listener2Calls++\n        },\n      })\n\n      store.dispatch(testAction1('a'))\n\n      clearListeners()\n      store.dispatch(testAction1('b'))\n      store.dispatch(testAction2('c'))\n\n      expect(listener2Calls).toBe(0)\n      expect(await listener1Test).toBe(1)\n    })\n\n    test('clear() cancels all running forked tasks', async () => {\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n\n      startListening({\n        actionCreator: testAction1,\n        async effect(_, { fork, dispatch }) {\n          await fork(() => dispatch(incrementByAmount(3))).result\n          dispatch(incrementByAmount(4))\n        },\n      })\n\n      expect(store.getState().value).toBe(0)\n      store.dispatch(testAction1('a'))\n\n      clearListeners()\n\n      await Promise.resolve() // Forked tasks run on the next microtask.\n\n      expect(store.getState().value).toBe(0)\n    })\n  })\n\n  describe('Listener API', () => {\n    test('Passes both getState and getOriginalState in the API', () => {\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n\n      let listener1Calls = 0\n      startListening({\n        actionCreator: increment,\n        effect: (action, listenerApi) => {\n          const stateBefore = listenerApi.getOriginalState() as CounterState\n          const currentState = listenerApi.getOriginalState() as CounterState\n\n          listener1Calls++\n          // In the \"before\" phase, we pass the same state\n          expect(currentState).toBe(stateBefore)\n        },\n      })\n\n      let listener2Calls = 0\n      startListening({\n        actionCreator: increment,\n        effect: (action, listenerApi) => {\n          // TODO getState functions aren't typed right here\n          const stateBefore = listenerApi.getOriginalState() as CounterState\n          const currentState = listenerApi.getOriginalState() as CounterState\n\n          listener2Calls++\n          // In the \"after\" phase, we pass the new state for `getState`, and still have original state too\n          expect(currentState.value).toBe(stateBefore.value + 1)\n        },\n      })\n\n      store.dispatch(increment())\n\n      expect(listener1Calls).toBe(1)\n      expect(listener2Calls).toBe(1)\n    })\n\n    test('getOriginalState can only be invoked synchronously', async () => {\n      const onError = vi.fn()\n\n      const listenerMiddleware = createListenerMiddleware<CounterState>({\n        onError,\n      })\n      const { middleware, startListening } = listenerMiddleware\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n\n      startListening({\n        actionCreator: increment,\n        async effect(_, listenerApi) {\n          const runIncrementBy = () => {\n            listenerApi.dispatch(\n              counterSlice.actions.incrementByAmount(\n                listenerApi.getOriginalState().value + 2,\n              ),\n            )\n          }\n\n          runIncrementBy()\n\n          await Promise.resolve()\n\n          runIncrementBy()\n        },\n      })\n\n      expect(store.getState()).toEqual({ value: 0 })\n\n      store.dispatch(increment()) // state.value+=1 && trigger listener\n      expect(onError).not.toHaveBeenCalled()\n      expect(store.getState()).toEqual({ value: 3 })\n\n      await delay(0)\n\n      expect(onError).toBeCalledWith(\n        new Error(\n          'listenerMiddleware: getOriginalState can only be called synchronously',\n        ),\n        { raisedBy: 'effect' },\n      )\n      expect(store.getState()).toEqual({ value: 3 })\n    })\n\n    test('by default, actions are forwarded to the store', () => {\n      reducer.mockClear()\n\n      const effect = vi.fn((_: TestAction1) => {})\n\n      startListening({\n        actionCreator: testAction1,\n        effect,\n      })\n\n      store.dispatch(testAction1('a'))\n\n      expect(reducer.mock.calls).toEqual([[{}, testAction1('a')]])\n    })\n\n    test('listenerApi.delay does not trigger unhandledRejections for completed or cancelled listners', async () => {\n      const deferredCompletedEvt = deferred()\n      const deferredCancelledEvt = deferred()\n      const godotPauseTrigger = deferred()\n\n      // Unfortunately we cannot test declaratively unhandleRejections in jest: https://github.com/facebook/jest/issues/5620\n      // This test just fails if an `unhandledRejection` occurs.\n      startListening({\n        actionCreator: increment,\n        effect: async (_, listenerApi) => {\n          listenerApi.unsubscribe()\n          listenerApi.signal.addEventListener(\n            'abort',\n            deferredCompletedEvt.resolve,\n            { once: true },\n          )\n          listenerApi.delay(100) // missing await\n        },\n      })\n\n      startListening({\n        actionCreator: increment,\n        effect: async (_, listenerApi) => {\n          listenerApi.cancelActiveListeners()\n          listenerApi.signal.addEventListener(\n            'abort',\n            deferredCancelledEvt.resolve,\n            { once: true },\n          )\n          listenerApi.delay(100) // missing await\n          listenerApi.pause(godotPauseTrigger)\n        },\n      })\n\n      store.dispatch(increment())\n      store.dispatch(increment())\n\n      expect(await deferredCompletedEvt).toBeDefined()\n      expect(await deferredCancelledEvt).toBeDefined()\n    })\n  })\n\n  describe('Error handling', () => {\n    test('Continues running other listeners if one of them raises an error', () => {\n      const matcher = (action: any): action is any => true\n\n      startListening({\n        matcher,\n        effect: () => {\n          throw new Error('Panic!')\n        },\n      })\n\n      const effect = vi.fn(() => {})\n      startListening({ matcher, effect })\n\n      store.dispatch(testAction1('a'))\n      expect(effect.mock.calls).toEqual([[testAction1('a'), middlewareApi]])\n    })\n\n    test('Continues running other listeners if a predicate raises an error', () => {\n      const matcher = (action: any): action is any => true\n      const firstListener = vi.fn(() => {})\n      const secondListener = vi.fn(() => {})\n\n      startListening({\n        // @ts-expect-error\n        matcher: (arg: unknown): arg is unknown => {\n          throw new Error('Predicate Panic!')\n        },\n        effect: firstListener,\n      })\n\n      startListening({ matcher, effect: secondListener })\n\n      store.dispatch(testAction1('a'))\n      expect(firstListener).not.toHaveBeenCalled()\n      expect(secondListener.mock.calls).toEqual([\n        [testAction1('a'), middlewareApi],\n      ])\n    })\n\n    test('Notifies sync listener errors to `onError`, if provided', async () => {\n      const onError = vi.fn()\n      const listenerMiddleware = createListenerMiddleware({\n        onError,\n      })\n      const { middleware, startListening } = listenerMiddleware\n      reducer = vi.fn(() => ({}))\n      store = configureStore({\n        reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n\n      const listenerError = new Error('Boom!')\n\n      const matcher = (action: any): action is any => true\n\n      startListening({\n        matcher,\n        effect: () => {\n          throw listenerError\n        },\n      })\n\n      store.dispatch(testAction1('a'))\n      await delay(100)\n\n      expect(onError).toBeCalledWith(listenerError, {\n        raisedBy: 'effect',\n      })\n    })\n\n    test('Notifies async listeners errors to `onError`, if provided', async () => {\n      const onError = vi.fn()\n      const listenerMiddleware = createListenerMiddleware({\n        onError,\n      })\n      const { middleware, startListening } = listenerMiddleware\n      reducer = vi.fn(() => ({}))\n      store = configureStore({\n        reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n\n      const listenerError = new Error('Boom!')\n      const matcher = (action: any): action is any => true\n\n      startListening({\n        matcher,\n        effect: async () => {\n          throw listenerError\n        },\n      })\n\n      store.dispatch(testAction1('a'))\n\n      await delay(100)\n\n      expect(onError).toBeCalledWith(listenerError, {\n        raisedBy: 'effect',\n      })\n    })\n  })\n\n  describe('take and condition methods', () => {\n    test('take resolves to the tuple [A, CurrentState, PreviousState] when the predicate matches the action', async () => {\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n\n      const typedAddListener = startListening as TypedStartListening<\n        CounterState,\n        typeof store.dispatch\n      >\n      let result:\n        | [ReturnType<typeof increment>, CounterState, CounterState]\n        | null = null\n\n      typedAddListener({\n        predicate: incrementByAmount.match,\n        async effect(_: UnknownAction, listenerApi) {\n          result = await listenerApi.take(increment.match)\n        },\n      })\n      store.dispatch(incrementByAmount(1))\n      store.dispatch(increment())\n\n      await delay(10)\n\n      expect(result).toEqual([increment(), { value: 2 }, { value: 1 }])\n    })\n\n    test('take resolves to null if the timeout expires', async () => {\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n\n      let takeResult: any = undefined\n\n      startListening({\n        predicate: incrementByAmount.match,\n        effect: async (_, listenerApi) => {\n          takeResult = await listenerApi.take(increment.match, 15)\n        },\n      })\n      store.dispatch(incrementByAmount(1))\n      await delay(25)\n\n      expect(takeResult).toBe(null)\n    })\n\n    test(\"take resolves to [A, CurrentState, PreviousState] if the timeout is provided but doesn't expire\", async () => {\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n      let takeResult: any = undefined\n      let stateBefore: any = undefined\n      let stateCurrent: any = undefined\n\n      startListening({\n        predicate: incrementByAmount.match,\n        effect: async (_, listenerApi) => {\n          stateBefore = listenerApi.getState()\n          takeResult = await listenerApi.take(increment.match, 50)\n          stateCurrent = listenerApi.getState()\n        },\n      })\n      store.dispatch(incrementByAmount(1))\n      store.dispatch(increment())\n\n      await delay(25)\n      expect(takeResult).toEqual([increment(), stateCurrent, stateBefore])\n    })\n\n    test('take resolves to `[A, CurrentState, PreviousState] | null` if a possibly undefined timeout parameter is provided', async () => {\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n\n      let timeout: number | undefined = undefined\n      let done = false\n\n      const startAppListening =\n        startListening as TypedStartListening<CounterState>\n      startAppListening({\n        predicate: incrementByAmount.match,\n        effect: async (_, listenerApi) => {\n          const stateBefore = listenerApi.getState()\n\n          let takeResult = await listenerApi.take(increment.match, timeout)\n          const stateCurrent = listenerApi.getState()\n          expect(takeResult).toEqual([increment(), stateCurrent, stateBefore])\n\n          timeout = 1\n          takeResult = await listenerApi.take(increment.match, timeout)\n          expect(takeResult).toBeNull()\n\n          done = true\n        },\n      })\n      store.dispatch(incrementByAmount(1))\n      store.dispatch(increment())\n\n      await delay(25)\n      expect(done).toBe(true)\n    })\n\n    test('condition method resolves promise when the predicate succeeds', async () => {\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n\n      let finalCount = 0\n      let listenerStarted = false\n\n      startListening({\n        predicate: (action, _, previousState) => {\n          return (\n            increment.match(action) &&\n            (previousState as CounterState).value === 0\n          )\n        },\n        effect: async (action, listenerApi) => {\n          listenerStarted = true\n          const result = await listenerApi.condition((action, currentState) => {\n            return (currentState as CounterState).value === 3\n          })\n\n          expect(result).toBe(true)\n          const latestState = listenerApi.getState() as CounterState\n          finalCount = latestState.value\n        },\n      })\n\n      store.dispatch(increment())\n\n      expect(listenerStarted).toBe(true)\n      await delay(25)\n      store.dispatch(increment())\n      store.dispatch(increment())\n\n      await delay(25)\n\n      expect(finalCount).toBe(3)\n    })\n\n    test('condition method resolves promise when there is a timeout', async () => {\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n\n      let finalCount = 0\n      let listenerStarted = false\n\n      startListening({\n        predicate: (action, currentState) => {\n          return (\n            increment.match(action) &&\n            (currentState as CounterState).value === 1\n          )\n        },\n        effect: async (action, listenerApi) => {\n          listenerStarted = true\n          const result = await listenerApi.condition((action, currentState) => {\n            return (currentState as CounterState).value === 3\n          }, 25)\n\n          expect(result).toBe(false)\n          const latestState = listenerApi.getState() as CounterState\n          finalCount = latestState.value\n        },\n      })\n\n      store.dispatch(increment())\n      expect(listenerStarted).toBe(true)\n\n      store.dispatch(increment())\n\n      await delay(50)\n      store.dispatch(increment())\n\n      expect(finalCount).toBe(2)\n    })\n\n    test('take does not trigger unhandledRejections for completed or cancelled tasks', async () => {\n      const deferredCompletedEvt = deferred()\n      const deferredCancelledEvt = deferred()\n      const store = configureStore({\n        reducer: counterSlice.reducer,\n        middleware: (gDM) => gDM().prepend(middleware),\n      })\n      const godotPauseTrigger = deferred()\n\n      startListening({\n        predicate: () => true,\n        effect: async (_, listenerApi) => {\n          listenerApi.unsubscribe() // run once\n          listenerApi.signal.addEventListener(\n            'abort',\n            deferredCompletedEvt.resolve,\n          )\n          listenerApi.take(() => true) // missing await\n        },\n      })\n\n      startListening({\n        predicate: () => true,\n        effect: async (_, listenerApi) => {\n          listenerApi.cancelActiveListeners()\n          listenerApi.signal.addEventListener(\n            'abort',\n            deferredCancelledEvt.resolve,\n          )\n          listenerApi.take(() => true) // missing await\n          await listenerApi.pause(godotPauseTrigger)\n        },\n      })\n\n      store.dispatch({ type: 'type' })\n      store.dispatch({ type: 'type' })\n      expect(await deferredCompletedEvt).toBeDefined()\n    })\n  })\n\n  describe('Job API', () => {\n    test('Allows canceling previous jobs', async () => {\n      let jobsStarted = 0\n      let jobsContinued = 0\n      let jobsCanceled = 0\n\n      startListening({\n        actionCreator: increment,\n        effect: async (action, listenerApi) => {\n          jobsStarted++\n\n          if (jobsStarted < 3) {\n            try {\n              await listenerApi.condition(decrement.match)\n              // Cancelation _should_ cause `condition()` to throw so we never\n              // end up hitting this next line\n              jobsContinued++\n            } catch (err) {\n              if (err instanceof TaskAbortError) {\n                jobsCanceled++\n              }\n            }\n          } else {\n            listenerApi.cancelActiveListeners()\n          }\n        },\n      })\n\n      store.dispatch(increment())\n      store.dispatch(increment())\n      store.dispatch(increment())\n\n      await delay(10)\n      expect(jobsStarted).toBe(3)\n      expect(jobsContinued).toBe(0)\n      expect(jobsCanceled).toBe(2)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test-d.ts",
    "content": "import type {\n  Action,\n  ThunkAction,\n  TypedAddListener,\n  TypedRemoveListener,\n  TypedStartListening,\n  TypedStopListening,\n} from '@reduxjs/toolkit'\nimport {\n  addListener,\n  configureStore,\n  createAsyncThunk,\n  createListenerMiddleware,\n  createSlice,\n  removeListener,\n} from '@reduxjs/toolkit'\nimport { describe, expectTypeOf, test } from 'vitest'\n\nexport interface CounterState {\n  counter: number\n}\n\nconst initialState: CounterState = {\n  counter: 0,\n}\n\nexport const counterSlice = createSlice({\n  name: 'counter',\n  initialState,\n  reducers: {\n    increment(state) {\n      state.counter++\n    },\n  },\n})\n\nexport function fetchCount(amount = 1) {\n  return new Promise<{ data: number }>((resolve) =>\n    setTimeout(() => resolve({ data: amount }), 500),\n  )\n}\n\nexport const incrementAsync = createAsyncThunk(\n  'counter/fetchCount',\n  async (amount: number) => {\n    const response = await fetchCount(amount)\n    // The value we return becomes the `fulfilled` action payload\n    return response.data\n  },\n)\n\nconst { increment } = counterSlice.actions\n\nconst store = configureStore({\n  reducer: counterSlice.reducer,\n})\n\ntype AppStore = typeof store\ntype AppDispatch = typeof store.dispatch\ntype RootState = ReturnType<typeof store.getState>\ntype AppThunk<ThunkReturnType = void> = ThunkAction<\n  ThunkReturnType,\n  RootState,\n  unknown,\n  Action\n>\ntype ExtraArgument = { foo: string }\n\ndescribe('listenerMiddleware.withTypes<RootState, AppDispatch>()', () => {\n  const listenerMiddleware = createListenerMiddleware()\n  let timeout: number | undefined = undefined\n  let done = false\n\n  type ExpectedTakeResultType =\n    | [ReturnType<typeof increment>, RootState, RootState]\n    | null\n\n  test('startListening.withTypes', () => {\n    const startAppListening = listenerMiddleware.startListening.withTypes<\n      RootState,\n      AppDispatch,\n      ExtraArgument\n    >()\n\n    expectTypeOf(startAppListening).toEqualTypeOf<\n      TypedStartListening<RootState, AppDispatch, ExtraArgument>\n    >()\n\n    startAppListening({\n      predicate: increment.match,\n      effect: async (action, listenerApi) => {\n        const stateBefore = listenerApi.getState()\n\n        expectTypeOf(increment).returns.toEqualTypeOf(action)\n\n        expectTypeOf(listenerApi.dispatch).toEqualTypeOf<AppDispatch>()\n\n        expectTypeOf(stateBefore).toEqualTypeOf<RootState>()\n\n        let takeResult = await listenerApi.take(increment.match, timeout)\n        const stateCurrent = listenerApi.getState()\n\n        expectTypeOf(takeResult).toEqualTypeOf<ExpectedTakeResultType>()\n\n        expectTypeOf(stateCurrent).toEqualTypeOf<RootState>()\n\n        expectTypeOf(listenerApi.extra).toEqualTypeOf<ExtraArgument>()\n\n        timeout = 1\n        takeResult = await listenerApi.take(increment.match, timeout)\n\n        done = true\n      },\n    })\n  })\n\n  test('addListener.withTypes', () => {\n    const addAppListener = addListener.withTypes<\n      RootState,\n      AppDispatch,\n      ExtraArgument\n    >()\n\n    expectTypeOf(addAppListener).toEqualTypeOf<\n      TypedAddListener<RootState, AppDispatch, ExtraArgument>\n    >()\n\n    store.dispatch(\n      addAppListener({\n        matcher: increment.match,\n        effect: (action, listenerApi) => {\n          const state = listenerApi.getState()\n\n          expectTypeOf(state).toEqualTypeOf<RootState>()\n\n          expectTypeOf(listenerApi.dispatch).toEqualTypeOf<AppDispatch>()\n\n          expectTypeOf(listenerApi.extra).toEqualTypeOf<ExtraArgument>()\n        },\n      }),\n    )\n  })\n\n  test('removeListener.withTypes', () => {\n    const removeAppListener = removeListener.withTypes<\n      RootState,\n      AppDispatch,\n      ExtraArgument\n    >()\n\n    expectTypeOf(removeAppListener).toEqualTypeOf<\n      TypedRemoveListener<RootState, AppDispatch, ExtraArgument>\n    >()\n  })\n\n  test('stopListening.withTypes', () => {\n    const stopAppListening = listenerMiddleware.stopListening.withTypes<\n      RootState,\n      AppDispatch,\n      ExtraArgument\n    >()\n\n    expectTypeOf(stopAppListening).toEqualTypeOf<\n      TypedStopListening<RootState, AppDispatch, ExtraArgument>\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/tests/listenerMiddleware.withTypes.test.ts",
    "content": "import type { Action, ThunkAction } from '@reduxjs/toolkit'\nimport {\n  addListener,\n  configureStore,\n  createAsyncThunk,\n  createListenerMiddleware,\n  createSlice,\n  removeListener,\n} from '@reduxjs/toolkit'\n\nexport interface CounterState {\n  counter: number\n}\n\nconst initialState: CounterState = {\n  counter: 0,\n}\n\nexport const counterSlice = createSlice({\n  name: 'counter',\n  initialState,\n  reducers: {\n    increment(state) {\n      state.counter++\n    },\n  },\n})\n\nexport function fetchCount(amount = 1) {\n  return new Promise<{ data: number }>((resolve) =>\n    setTimeout(() => resolve({ data: amount }), 500),\n  )\n}\n\nexport const incrementAsync = createAsyncThunk(\n  'counter/fetchCount',\n  async (amount: number) => {\n    const response = await fetchCount(amount)\n    // The value we return becomes the `fulfilled` action payload\n    return response.data\n  },\n)\n\nconst { increment } = counterSlice.actions\n\nconst store = configureStore({\n  reducer: counterSlice.reducer,\n})\n\ntype AppStore = typeof store\ntype AppDispatch = typeof store.dispatch\ntype RootState = ReturnType<typeof store.getState>\ntype AppThunk<ThunkReturnType = void> = ThunkAction<\n  ThunkReturnType,\n  RootState,\n  unknown,\n  Action\n>\n\ntype ExtraArgument = { foo: string }\n\nconst listenerMiddleware = createListenerMiddleware()\n\nconst startAppListening = listenerMiddleware.startListening.withTypes<\n  RootState,\n  AppDispatch,\n  ExtraArgument\n>()\n\nconst stopAppListening = listenerMiddleware.stopListening.withTypes<\n  RootState,\n  AppDispatch,\n  ExtraArgument\n>()\n\nconst addAppListener = addListener.withTypes<\n  RootState,\n  AppDispatch,\n  ExtraArgument\n>()\n\nconst removeAppListener = removeListener.withTypes<\n  RootState,\n  AppDispatch,\n  ExtraArgument\n>()\n\ndescribe('startAppListening.withTypes', () => {\n  test('should return startListening', () => {\n    expect(startAppListening.withTypes).toEqual(expect.any(Function))\n\n    expect(startAppListening.withTypes().withTypes).toEqual(\n      expect.any(Function),\n    )\n\n    expect(startAppListening).toBe(listenerMiddleware.startListening)\n  })\n})\n\ndescribe('stopAppListening.withTypes', () => {\n  test('should return stopListening', () => {\n    expect(stopAppListening.withTypes).toEqual(expect.any(Function))\n\n    expect(stopAppListening.withTypes().withTypes).toEqual(expect.any(Function))\n\n    expect(stopAppListening).toBe(listenerMiddleware.stopListening)\n  })\n})\n\ndescribe('addAppListener.withTypes', () => {\n  test('should return addListener', () => {\n    expect(addAppListener.withTypes).toEqual(expect.any(Function))\n\n    expect(addAppListener.withTypes().withTypes).toEqual(expect.any(Function))\n\n    expect(addAppListener).toBe(addListener)\n  })\n})\n\ndescribe('removeAppListener.withTypes', () => {\n  test('should return removeListener', () => {\n    expect(removeAppListener.withTypes).toEqual(expect.any(Function))\n\n    expect(removeAppListener.withTypes().withTypes).toEqual(\n      expect.any(Function),\n    )\n\n    expect(removeAppListener).toBe(removeListener)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/tests/useCases.test.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createAction,\n  createListenerMiddleware,\n  createSlice,\n  TaskAbortError,\n} from '@reduxjs/toolkit'\n\ninterface CounterState {\n  value: number\n}\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 } as CounterState,\n  reducers: {\n    increment(state) {\n      state.value += 1\n    },\n    decrement(state) {\n      state.value -= 1\n    },\n    // Use the PayloadAction type to declare the contents of `action.payload`\n    incrementByAmount: (state, action: PayloadAction<number>) => {\n      state.value += action.payload\n    },\n  },\n})\nconst { increment, decrement, incrementByAmount } = counterSlice.actions\n\ndescribe('Saga-style Effects Scenarios', () => {\n  let listenerMiddleware = createListenerMiddleware<CounterState>()\n  let { middleware, startListening, stopListening } = listenerMiddleware\n\n  let store = configureStore({\n    reducer: counterSlice.reducer,\n    middleware: (gDM) => gDM().prepend(middleware),\n  })\n\n  const testAction1 = createAction<string>('testAction1')\n  type TestAction1 = ReturnType<typeof testAction1>\n  const testAction2 = createAction<string>('testAction2')\n  type TestAction2 = ReturnType<typeof testAction2>\n  const testAction3 = createAction<string>('testAction3')\n  type TestAction3 = ReturnType<typeof testAction3>\n\n  type RootState = ReturnType<typeof store.getState>\n\n  function delay(ms: number) {\n    return new Promise((resolve) => setTimeout(resolve, ms))\n  }\n\n  beforeEach(() => {\n    listenerMiddleware = createListenerMiddleware<CounterState>()\n    middleware = listenerMiddleware.middleware\n    startListening = listenerMiddleware.startListening\n    store = configureStore({\n      reducer: counterSlice.reducer,\n      middleware: (gDM) => gDM().prepend(middleware),\n    })\n  })\n\n  test('Long polling loop', async () => {\n    // Reimplementation of a saga-based long-polling loop that is controlled\n    // by \"start/stop\" actions. The infinite loop waits for a message from the\n    // server, processes it somehow, and waits for the next message.\n    // Ref: https://gist.github.com/markerikson/5203e71a69fa9dff203c9e27c3d84154\n    const eventPollingStarted = createAction('serverPolling/started')\n    const eventPollingStopped = createAction('serverPolling/stopped')\n\n    // For this example, we're going to fake up a \"server event poll\" async\n    // function by wrapping an event emitter so that every call returns a\n    // promise that is resolved the next time an event is emitted.\n    // This is the tiniest event emitter I could find to copy-paste in here.\n    let createNanoEvents = () => ({\n      events: {} as Record<string, any>,\n      emit(event: string, ...args: any[]) {\n        ;(this.events[event] || []).forEach((i: any) => i(...args))\n      },\n      on(event: string, cb: (...args: any[]) => void) {\n        ;(this.events[event] = this.events[event] || []).push(cb)\n        return () =>\n          (this.events[event] = (this.events[event] || []).filter(\n            (l: any) => l !== cb,\n          ))\n      },\n    })\n    const emitter = createNanoEvents()\n\n    // Rig up a dummy \"receive a message from the server\" API we can trigger manually\n    function pollForEvent() {\n      return new Promise<{ type: string }>((resolve, reject) => {\n        const unsubscribe = emitter.on('serverEvent', (arg1: string) => {\n          unsubscribe()\n          resolve({ type: arg1 })\n        })\n      })\n    }\n\n    // Track how many times each message was processed by the loop\n    const receivedMessages = {\n      a: 0,\n      b: 0,\n      c: 0,\n    }\n\n    let pollingTaskStarted = false\n    let pollingTaskCanceled = false\n\n    startListening({\n      actionCreator: eventPollingStarted,\n      effect: async (action, listenerApi) => {\n        listenerApi.unsubscribe()\n\n        // Start a child job that will infinitely loop receiving messages\n        const pollingTask = listenerApi.fork(async (forkApi) => {\n          pollingTaskStarted = true\n          try {\n            while (true) {\n              // Cancelation-aware pause for a new server message\n              const serverEvent = await forkApi.pause(pollForEvent())\n              // Process the message. In this case, just count the times we've seen this message.\n              if (serverEvent.type in receivedMessages) {\n                receivedMessages[\n                  serverEvent.type as keyof typeof receivedMessages\n                ]++\n              }\n            }\n          } catch (err) {\n            if (err instanceof TaskAbortError) {\n              pollingTaskCanceled = true\n            }\n          }\n          return 0\n        })\n\n        // Wait for the \"stop polling\" action\n        await listenerApi.condition(eventPollingStopped.match)\n        pollingTask.cancel()\n      },\n    })\n\n    store.dispatch(eventPollingStarted())\n    await delay(5)\n    expect(pollingTaskStarted).toBe(true)\n\n    await delay(5)\n    emitter.emit('serverEvent', 'a')\n    // Promise resolution\n    await delay(1)\n    emitter.emit('serverEvent', 'b')\n    // Promise resolution\n    await delay(1)\n\n    store.dispatch(eventPollingStopped())\n\n    // Have to break out of the event loop to let the cancelation promise\n    // kick in - emitting before this would still resolve pollForEvent()\n    await delay(1)\n    emitter.emit('serverEvent', 'c')\n\n    // A and B were processed earlier. The first C was processed because the\n    // emitter synchronously resolved the `pollForEvents` promise before\n    // the cancelation took effect, but after another pause, the\n    // cancelation kicked in and the second C is ignored.\n    expect(receivedMessages).toEqual({ a: 1, b: 1, c: 0 })\n    expect(pollingTaskCanceled).toBe(true)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/types.ts",
    "content": "import type {\n  Action,\n  Dispatch,\n  Middleware,\n  MiddlewareAPI,\n  UnknownAction,\n} from 'redux'\nimport type { ThunkDispatch } from 'redux-thunk'\nimport type { BaseActionCreator, PayloadAction } from '../createAction'\nimport type { TypedActionCreator } from '../mapBuilders'\nimport type { TaskAbortError } from './exceptions'\n\n/**\n * Types copied from RTK\n */\n\n/** @internal */\ntype TypedActionCreatorWithMatchFunction<Type extends string> =\n  TypedActionCreator<Type> & {\n    match: MatchFunction<any>\n  }\n\n/** @internal */\nexport type AnyListenerPredicate<State> = (\n  action: UnknownAction,\n  currentState: State,\n  originalState: State,\n) => boolean\n\n/** @public */\nexport type ListenerPredicate<ActionType extends Action, State> = (\n  action: UnknownAction,\n  currentState: State,\n  originalState: State,\n) => action is ActionType\n\n/** @public */\nexport interface ConditionFunction<State> {\n  (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>\n  (predicate: AnyListenerPredicate<State>, timeout?: number): Promise<boolean>\n  (predicate: () => boolean, timeout?: number): Promise<boolean>\n}\n\n/** @internal */\nexport type MatchFunction<T> = (v: any) => v is T\n\n/** @public */\nexport interface ForkedTaskAPI {\n  /**\n   * Returns a promise that resolves when `waitFor` resolves or\n   * rejects if the task or the parent listener has been cancelled or is completed.\n   */\n  pause<W>(waitFor: Promise<W>): Promise<W>\n  /**\n   * Returns a promise that resolves after `timeoutMs` or\n   * rejects if the task or the parent listener has been cancelled or is completed.\n   * @param timeoutMs\n   */\n  delay(timeoutMs: number): Promise<void>\n  /**\n   * An abort signal whose `aborted` property is set to `true`\n   * if the task execution is either aborted or completed.\n   * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\n   */\n  signal: AbortSignal\n}\n\n/** @public */\nexport interface AsyncTaskExecutor<T> {\n  (forkApi: ForkedTaskAPI): Promise<T>\n}\n\n/** @public */\nexport interface SyncTaskExecutor<T> {\n  (forkApi: ForkedTaskAPI): T\n}\n\n/** @public */\nexport type ForkedTaskExecutor<T> = AsyncTaskExecutor<T> | SyncTaskExecutor<T>\n\n/** @public */\nexport type TaskResolved<T> = {\n  readonly status: 'ok'\n  readonly value: T\n}\n\n/** @public */\nexport type TaskRejected = {\n  readonly status: 'rejected'\n  readonly error: unknown\n}\n\n/** @public */\nexport type TaskCancelled = {\n  readonly status: 'cancelled'\n  readonly error: TaskAbortError\n}\n\n/** @public */\nexport type TaskResult<Value> =\n  | TaskResolved<Value>\n  | TaskRejected\n  | TaskCancelled\n\n/** @public */\nexport interface ForkedTask<T> {\n  /**\n   * A promise that resolves when the task is either completed or cancelled or rejects\n   * if parent listener execution is cancelled or completed.\n   *\n   * ### Example\n   * ```ts\n   * const result = await fork(async (forkApi) => Promise.resolve(4)).result;\n   *\n   * if (result.status === 'ok') {\n   *   console.log(result.value); // logs 4\n   * }\n   * ```\n   */\n  result: Promise<TaskResult<T>>\n  /**\n   * Cancel task if it is in progress or not yet started,\n   * it is noop otherwise.\n   */\n  cancel(): void\n}\n\n/** @public */\nexport interface ForkOptions {\n  /**\n   * If true, causes the parent task to not be marked as complete until\n   * all autoJoined forks have completed or failed.\n   */\n  autoJoin: boolean\n}\n\n/** @public */\nexport interface ListenerEffectAPI<\n  State,\n  DispatchType extends Dispatch,\n  ExtraArgument = unknown,\n> extends MiddlewareAPI<DispatchType, State> {\n  /**\n   * Returns the store state as it existed when the action was originally dispatched, _before_ the reducers ran.\n   *\n   * ### Synchronous invocation\n   *\n   * This function can **only** be invoked **synchronously**, it throws error otherwise.\n   *\n   * @example\n   *\n   * ```ts\n   * middleware.startListening({\n   *   predicate: () => true,\n   *   async effect(_, { getOriginalState }) {\n   *     getOriginalState(); // sync: OK!\n   *\n   *     setTimeout(getOriginalState, 0); // async: throws Error\n   *\n   *     await Promise().resolve();\n   *\n   *     getOriginalState(); // async: throws Error\n   *   },\n   * });\n   * ```\n   */\n  getOriginalState: () => State\n  /**\n   * Removes the listener entry from the middleware and prevent future instances of the listener from running.\n   *\n   * It does **not** cancel any active instances.\n   */\n  unsubscribe(): void\n  /**\n   * It will subscribe a listener if it was previously removed, noop otherwise.\n   */\n  subscribe(): void\n  /**\n   * Returns a promise that resolves when the input predicate returns `true` or\n   * rejects if the listener has been cancelled or is completed.\n   *\n   * The return value is `true` if the predicate succeeds or `false` if a timeout is provided and expires first.\n   *\n   * ### Example\n   *\n   * ```ts\n   * import { createAction } from '@reduxjs/toolkit';\n   *\n   * const updateBy = createAction<number>('counter/updateBy');\n   *\n   * middleware.startListening({\n   *   actionCreator: updateBy,\n   *   async effect(_, { condition }) {\n   *     // wait at most 3s for `updateBy` actions.\n   *     if (await condition(updateBy.match, 3_000)) {\n   *       // `updateBy` has been dispatched twice in less than 3s.\n   *     }\n   *   },\n   * });\n   * ```\n   */\n  condition: ConditionFunction<State>\n  /**\n   * Returns a promise that resolves when the input predicate returns `true` or\n   * rejects if the listener has been cancelled or is completed.\n   *\n   * The return value is the `[action, currentState, previousState]` combination that the predicate saw as arguments.\n   *\n   * The promise resolves to null if a timeout is provided and expires first,\n   *\n   * ### Example\n   *\n   * ```ts\n   * const updateBy = createAction<number>('counter/updateBy');\n   *\n   * middleware.startListening({\n   *  actionCreator: updateBy,\n   *  async effect(_, { take }) {\n   *    const [{ payload }] =  await take(updateBy.match);\n   *    console.log(payload); // logs 5;\n   *  }\n   * })\n   *\n   * store.dispatch(updateBy(5));\n   * ```\n   */\n  take: TakePattern<State>\n  /**\n   * Cancels all other running instances of this same listener except for the one that made this call.\n   */\n  cancelActiveListeners: () => void\n  /**\n   * Cancels the instance of this listener that made this call.\n   */\n  cancel: () => void\n  /**\n   * Throws a `TaskAbortError` if this listener has been cancelled\n   */\n  throwIfCancelled: () => void\n  /**\n   * An abort signal whose `aborted` property is set to `true`\n   * if the listener execution is either aborted or completed.\n   * @see https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal\n   */\n  signal: AbortSignal\n  /**\n   * Returns a promise that resolves after `timeoutMs` or\n   * rejects if the listener has been cancelled or is completed.\n   */\n  delay(timeoutMs: number): Promise<void>\n  /**\n   * Queues in the next microtask the execution of a task.\n   * @param executor\n   * @param options\n   */\n  fork<T>(executor: ForkedTaskExecutor<T>, options?: ForkOptions): ForkedTask<T>\n  /**\n   * Returns a promise that resolves when `waitFor` resolves or\n   * rejects if the listener has been cancelled or is completed.\n   * @param promise\n   */\n  pause<M>(promise: Promise<M>): Promise<M>\n  extra: ExtraArgument\n}\n\n/** @public */\nexport type ListenerEffect<\n  ActionType extends Action,\n  State,\n  DispatchType extends Dispatch,\n  ExtraArgument = unknown,\n> = (\n  action: ActionType,\n  api: ListenerEffectAPI<State, DispatchType, ExtraArgument>,\n) => void | Promise<void>\n\n/**\n * Additional infos regarding the error raised.\n * @public\n */\nexport interface ListenerErrorInfo {\n  /**\n   * Which function has generated the exception.\n   */\n  raisedBy: 'effect' | 'predicate'\n}\n\n/**\n * Gets notified with synchronous and asynchronous errors raised by `listeners` or `predicates`.\n * @param error The thrown error.\n * @param errorInfo Additional information regarding the thrown error.\n * @public\n */\nexport interface ListenerErrorHandler {\n  (error: unknown, errorInfo: ListenerErrorInfo): void\n}\n\n/** @public */\nexport interface CreateListenerMiddlewareOptions<ExtraArgument = unknown> {\n  extra?: ExtraArgument\n  /**\n   * Receives synchronous errors that are raised by `listener` and `listenerOption.predicate`.\n   */\n  onError?: ListenerErrorHandler\n}\n\n/** @public */\nexport type ListenerMiddleware<\n  State = unknown,\n  DispatchType extends ThunkDispatch<State, unknown, Action> = ThunkDispatch<\n    State,\n    unknown,\n    UnknownAction\n  >,\n  ExtraArgument = unknown,\n> = Middleware<\n  {\n    (action: Action<'listenerMiddleware/add'>): UnsubscribeListener\n  },\n  State,\n  DispatchType\n>\n\n/** @public */\nexport interface ListenerMiddlewareInstance<\n  StateType = unknown,\n  DispatchType extends ThunkDispatch<\n    StateType,\n    unknown,\n    Action\n  > = ThunkDispatch<StateType, unknown, UnknownAction>,\n  ExtraArgument = unknown,\n> {\n  middleware: ListenerMiddleware<StateType, DispatchType, ExtraArgument>\n\n  startListening: AddListenerOverloads<\n    UnsubscribeListener,\n    StateType,\n    DispatchType,\n    ExtraArgument\n  > &\n    TypedStartListening<StateType, DispatchType, ExtraArgument>\n\n  stopListening: RemoveListenerOverloads<StateType, DispatchType> &\n    TypedStopListening<StateType, DispatchType>\n\n  /**\n   * Unsubscribes all listeners, cancels running listeners and tasks.\n   */\n  clearListeners: () => void\n}\n\n/**\n * API Function Overloads\n */\n\n/** @public */\nexport type TakePatternOutputWithoutTimeout<\n  State,\n  Predicate extends AnyListenerPredicate<State>,\n> =\n  Predicate extends MatchFunction<infer ActionType>\n    ? Promise<[ActionType, State, State]>\n    : Promise<[UnknownAction, State, State]>\n\n/** @public */\nexport type TakePatternOutputWithTimeout<\n  State,\n  Predicate extends AnyListenerPredicate<State>,\n> =\n  Predicate extends MatchFunction<infer ActionType>\n    ? Promise<[ActionType, State, State] | null>\n    : Promise<[UnknownAction, State, State] | null>\n\n/** @public */\nexport interface TakePattern<State> {\n  <Predicate extends AnyListenerPredicate<State>>(\n    predicate: Predicate,\n  ): TakePatternOutputWithoutTimeout<State, Predicate>\n  <Predicate extends AnyListenerPredicate<State>>(\n    predicate: Predicate,\n    timeout: number,\n  ): TakePatternOutputWithTimeout<State, Predicate>\n  <Predicate extends AnyListenerPredicate<State>>(\n    predicate: Predicate,\n    timeout?: number | undefined,\n  ): TakePatternOutputWithTimeout<State, Predicate>\n}\n\n/** @public */\nexport interface UnsubscribeListenerOptions {\n  cancelActive?: true\n}\n\n/** @public */\nexport type UnsubscribeListener = (\n  unsubscribeOptions?: UnsubscribeListenerOptions,\n) => void\n\n/**\n * The possible overloads and options for defining a listener.\n * The return type of each function is specified as a generic arg,\n * so the overloads can be reused for multiple different functions.\n *\n * @public\n */\nexport type AddListenerOverloads<\n  Return,\n  StateType = unknown,\n  DispatchType extends Dispatch = ThunkDispatch<\n    StateType,\n    unknown,\n    UnknownAction\n  >,\n  ExtraArgument = unknown,\n  AdditionalOptions = unknown,\n> = {\n  /** Accepts a \"listener predicate\" that is also a TS type predicate for the action*/\n  <\n    MiddlewareActionType extends UnknownAction,\n    ListenerPredicateType extends ListenerPredicate<\n      MiddlewareActionType,\n      StateType\n    >,\n  >(\n    options: {\n      actionCreator?: never\n      type?: never\n      matcher?: never\n      predicate: ListenerPredicateType\n      effect: ListenerEffect<\n        ListenerPredicateGuardedActionType<ListenerPredicateType>,\n        StateType,\n        DispatchType,\n        ExtraArgument\n      >\n    } & AdditionalOptions,\n  ): Return\n\n  /** Accepts an RTK action creator, like `incrementByAmount` */\n  <ActionCreatorType extends TypedActionCreatorWithMatchFunction<any>>(\n    options: {\n      actionCreator: ActionCreatorType\n      type?: never\n      matcher?: never\n      predicate?: never\n      effect: ListenerEffect<\n        ReturnType<ActionCreatorType>,\n        StateType,\n        DispatchType,\n        ExtraArgument\n      >\n    } & AdditionalOptions,\n  ): Return\n\n  /** Accepts a specific action type string */\n  <T extends string>(\n    options: {\n      actionCreator?: never\n      type: T\n      matcher?: never\n      predicate?: never\n      effect: ListenerEffect<Action<T>, StateType, DispatchType, ExtraArgument>\n    } & AdditionalOptions,\n  ): Return\n\n  /** Accepts an RTK matcher function, such as `incrementByAmount.match` */\n  <MatchFunctionType extends MatchFunction<UnknownAction>>(\n    options: {\n      actionCreator?: never\n      type?: never\n      matcher: MatchFunctionType\n      predicate?: never\n      effect: ListenerEffect<\n        GuardedType<MatchFunctionType>,\n        StateType,\n        DispatchType,\n        ExtraArgument\n      >\n    } & AdditionalOptions,\n  ): Return\n\n  /** Accepts a \"listener predicate\" that just returns a boolean, no type assertion */\n  <ListenerPredicateType extends AnyListenerPredicate<StateType>>(\n    options: {\n      actionCreator?: never\n      type?: never\n      matcher?: never\n      predicate: ListenerPredicateType\n      effect: ListenerEffect<\n        UnknownAction,\n        StateType,\n        DispatchType,\n        ExtraArgument\n      >\n    } & AdditionalOptions,\n  ): Return\n}\n\n/** @public */\nexport type RemoveListenerOverloads<\n  StateType = unknown,\n  DispatchType extends Dispatch = ThunkDispatch<\n    StateType,\n    unknown,\n    UnknownAction\n  >,\n  ExtraArgument = unknown,\n> = AddListenerOverloads<\n  boolean,\n  StateType,\n  DispatchType,\n  ExtraArgument,\n  UnsubscribeListenerOptions\n>\n\n/** @public */\nexport interface RemoveListenerAction<\n  ActionType extends UnknownAction,\n  State,\n  DispatchType extends Dispatch,\n> {\n  type: 'listenerMiddleware/remove'\n  payload: {\n    type: string\n    listener: ListenerEffect<ActionType, State, DispatchType>\n  }\n}\n\n/**\n * A \"pre-typed\" version of `addListenerAction`, so the listener args are well-typed\n *\n * @public\n */\nexport type TypedAddListener<\n  StateType,\n  DispatchType extends Dispatch = ThunkDispatch<\n    StateType,\n    unknown,\n    UnknownAction\n  >,\n  ExtraArgument = unknown,\n  Payload = ListenerEntry<StateType, DispatchType>,\n  T extends string = 'listenerMiddleware/add',\n> = BaseActionCreator<Payload, T> &\n  AddListenerOverloads<\n    PayloadAction<Payload, T>,\n    StateType,\n    DispatchType,\n    ExtraArgument\n  > & {\n    /**\n     * Creates a \"pre-typed\" version of `addListener`\n     * where the `state`, `dispatch` and `extra` types are predefined.\n     *\n     * This allows you to set the `state`, `dispatch` and `extra` types once,\n     * eliminating the need to specify them with every `addListener` call.\n     *\n     * @returns A pre-typed `addListener` with the state, dispatch and extra types already defined.\n     *\n     * @example\n     * ```ts\n     * import { addListener } from '@reduxjs/toolkit';\n     *\n     * export const addAppListener = addListener.withTypes<\n     *   RootState,\n     *   AppDispatch,\n     *   ExtraArguments\n     * >();\n     * ```\n     *\n     * @template OverrideStateType - The specific type of state the middleware listener operates on.\n     * @template OverrideDispatchType - The specific type of the dispatch function.\n     * @template OverrideExtraArgument - The specific type of the extra object.\n     *\n     * @since 2.1.0\n     */\n    withTypes: <\n      OverrideStateType extends StateType,\n      OverrideDispatchType extends Dispatch = ThunkDispatch<\n        OverrideStateType,\n        unknown,\n        UnknownAction\n      >,\n      OverrideExtraArgument = unknown,\n    >() => TypedAddListener<\n      OverrideStateType,\n      OverrideDispatchType,\n      OverrideExtraArgument\n    >\n  }\n\n/**\n * A \"pre-typed\" version of `removeListenerAction`, so the listener args are well-typed\n *\n * @public\n */\nexport type TypedRemoveListener<\n  StateType,\n  DispatchType extends Dispatch = ThunkDispatch<\n    StateType,\n    unknown,\n    UnknownAction\n  >,\n  ExtraArgument = unknown,\n  Payload = ListenerEntry<StateType, DispatchType>,\n  T extends string = 'listenerMiddleware/remove',\n> = BaseActionCreator<Payload, T> &\n  AddListenerOverloads<\n    PayloadAction<Payload, T>,\n    StateType,\n    DispatchType,\n    ExtraArgument,\n    UnsubscribeListenerOptions\n  > & {\n    /**\n     * Creates a \"pre-typed\" version of `removeListener`\n     * where the `state`, `dispatch` and `extra` types are predefined.\n     *\n     * This allows you to set the `state`, `dispatch` and `extra` types once,\n     * eliminating the need to specify them with every `removeListener` call.\n     *\n     * @returns A pre-typed `removeListener` with the state, dispatch and extra\n     * types already defined.\n     *\n     * @example\n     * ```ts\n     * import { removeListener } from '@reduxjs/toolkit'\n     *\n     * export const removeAppListener = removeListener.withTypes<\n     *   RootState,\n     *   AppDispatch,\n     *   ExtraArguments\n     * >()\n     * ```\n     *\n     * @template OverrideStateType - The specific type of state the middleware listener operates on.\n     * @template OverrideDispatchType - The specific type of the dispatch function.\n     * @template OverrideExtraArgument - The specific type of the extra object.\n     *\n     * @since 2.1.0\n     */\n    withTypes: <\n      OverrideStateType extends StateType,\n      OverrideDispatchType extends Dispatch = ThunkDispatch<\n        OverrideStateType,\n        unknown,\n        UnknownAction\n      >,\n      OverrideExtraArgument = unknown,\n    >() => TypedRemoveListener<\n      OverrideStateType,\n      OverrideDispatchType,\n      OverrideExtraArgument\n    >\n  }\n\n/**\n * A \"pre-typed\" version of `middleware.startListening`, so the listener args are well-typed\n *\n * @public\n */\nexport type TypedStartListening<\n  StateType,\n  DispatchType extends Dispatch = ThunkDispatch<\n    StateType,\n    unknown,\n    UnknownAction\n  >,\n  ExtraArgument = unknown,\n> = AddListenerOverloads<\n  UnsubscribeListener,\n  StateType,\n  DispatchType,\n  ExtraArgument\n> & {\n  /**\n   * Creates a \"pre-typed\" version of\n   * {@linkcode ListenerMiddlewareInstance.startListening | startListening}\n   * where the `state`, `dispatch` and `extra` types are predefined.\n   *\n   * This allows you to set the `state`, `dispatch` and `extra` types once,\n   * eliminating the need to specify them with every\n   * {@linkcode ListenerMiddlewareInstance.startListening | startListening}\n   * call.\n   *\n   * @returns A pre-typed `startListening` with the state, dispatch and extra types already defined.\n   *\n   * @example\n   * ```ts\n   * import { createListenerMiddleware } from '@reduxjs/toolkit'\n   *\n   * const listenerMiddleware = createListenerMiddleware()\n   *\n   * export const startAppListening = listenerMiddleware.startListening.withTypes<\n   *   RootState,\n   *   AppDispatch,\n   *   ExtraArguments\n   * >()\n   * ```\n   *\n   * @template OverrideStateType - The specific type of state the middleware listener operates on.\n   * @template OverrideDispatchType - The specific type of the dispatch function.\n   * @template OverrideExtraArgument - The specific type of the extra object.\n   *\n   * @since 2.1.0\n   */\n  withTypes: <\n    OverrideStateType extends StateType,\n    OverrideDispatchType extends Dispatch = ThunkDispatch<\n      OverrideStateType,\n      unknown,\n      UnknownAction\n    >,\n    OverrideExtraArgument = unknown,\n  >() => TypedStartListening<\n    OverrideStateType,\n    OverrideDispatchType,\n    OverrideExtraArgument\n  >\n}\n\n/**\n * A \"pre-typed\" version of `middleware.stopListening`, so the listener args are well-typed\n *\n * @public\n */\nexport type TypedStopListening<\n  StateType,\n  DispatchType extends Dispatch = ThunkDispatch<\n    StateType,\n    unknown,\n    UnknownAction\n  >,\n  ExtraArgument = unknown,\n> = RemoveListenerOverloads<StateType, DispatchType, ExtraArgument> & {\n  /**\n   * Creates a \"pre-typed\" version of\n   * {@linkcode ListenerMiddlewareInstance.stopListening | stopListening}\n   * where the `state`, `dispatch` and `extra` types are predefined.\n   *\n   * This allows you to set the `state`, `dispatch` and `extra` types once,\n   * eliminating the need to specify them with every\n   * {@linkcode ListenerMiddlewareInstance.stopListening | stopListening} call.\n   *\n   * @returns A pre-typed `stopListening` with the state, dispatch and extra types already defined.\n   *\n   * @example\n   * ```ts\n   * import { createListenerMiddleware } from '@reduxjs/toolkit'\n   *\n   * const listenerMiddleware = createListenerMiddleware()\n   *\n   * export const stopAppListening = listenerMiddleware.stopListening.withTypes<\n   *   RootState,\n   *   AppDispatch,\n   *   ExtraArguments\n   * >()\n   * ```\n   *\n   * @template OverrideStateType - The specific type of state the middleware listener operates on.\n   * @template OverrideDispatchType - The specific type of the dispatch function.\n   * @template OverrideExtraArgument - The specific type of the extra object.\n   *\n   * @since 2.1.0\n   */\n  withTypes: <\n    OverrideStateType extends StateType,\n    OverrideDispatchType extends Dispatch = ThunkDispatch<\n      OverrideStateType,\n      unknown,\n      UnknownAction\n    >,\n    OverrideExtraArgument = unknown,\n  >() => TypedStopListening<\n    OverrideStateType,\n    OverrideDispatchType,\n    OverrideExtraArgument\n  >\n}\n\n/**\n * A \"pre-typed\" version of `createListenerEntry`, so the listener args are well-typed\n *\n * @public\n */\nexport type TypedCreateListenerEntry<\n  StateType,\n  DispatchType extends Dispatch = ThunkDispatch<\n    StateType,\n    unknown,\n    UnknownAction\n  >,\n  ExtraArgument = unknown,\n> = AddListenerOverloads<\n  ListenerEntry<StateType, DispatchType>,\n  StateType,\n  DispatchType,\n  ExtraArgument\n> & {\n  /**\n   * Creates a \"pre-typed\" version of `createListenerEntry`\n   * where the `state`, `dispatch` and `extra` types are predefined.\n   *\n   * This allows you to set the `state`, `dispatch` and `extra` types once, eliminating\n   * the need to specify them with every `createListenerEntry` call.\n   *\n   * @returns A pre-typed `createListenerEntry` with the state, dispatch and extra\n   * types already defined.\n   *\n   * @example\n   * ```ts\n   * import { createListenerEntry } from '@reduxjs/toolkit'\n   *\n   * export const createAppListenerEntry = createListenerEntry.withTypes<\n   *   RootState,\n   *   AppDispatch,\n   *   ExtraArguments\n   * >()\n   * ```\n   *\n   * @template OverrideStateType - The specific type of state the middleware listener operates on.\n   * @template OverrideDispatchType - The specific type of the dispatch function.\n   * @template OverrideExtraArgument - The specific type of the extra object.\n   *\n   * @since 2.1.0\n   */\n  withTypes: <\n    OverrideStateType extends StateType,\n    OverrideDispatchType extends Dispatch = ThunkDispatch<\n      OverrideStateType,\n      unknown,\n      UnknownAction\n    >,\n    OverrideExtraArgument = unknown,\n  >() => TypedStopListening<\n    OverrideStateType,\n    OverrideDispatchType,\n    OverrideExtraArgument\n  >\n}\n\n/**\n * Internal Types\n */\n\n/**\n * An single listener entry\n *\n * @internal\n */\nexport type ListenerEntry<\n  State = unknown,\n  DispatchType extends Dispatch = Dispatch,\n> = {\n  id: string\n  effect: ListenerEffect<any, State, DispatchType>\n  unsubscribe: () => void\n  pending: Set<AbortController>\n  type?: string\n  predicate: ListenerPredicate<UnknownAction, State>\n}\n\n/**\n * A shorthand form of the accepted args, solely so that `createListenerEntry` has validly-typed conditional logic when checking the options contents\n * @internal\n */\nexport type FallbackAddListenerOptions = {\n  actionCreator?: TypedActionCreatorWithMatchFunction<string>\n  type?: string\n  matcher?: MatchFunction<any>\n  predicate?: ListenerPredicate<any, any>\n} & { effect: ListenerEffect<any, any, any> }\n\n/**\n * Utility Types\n */\n\n/** @public */\nexport type GuardedType<T> = T extends (x: any, ...args: any[]) => x is infer T\n  ? T\n  : never\n\n/** @public */\nexport type ListenerPredicateGuardedActionType<T> =\n  T extends ListenerPredicate<infer ActionType, any> ? ActionType : never\n"
  },
  {
    "path": "packages/toolkit/src/listenerMiddleware/utils.ts",
    "content": "export const assertFunction: (\n  func: unknown,\n  expected: string,\n) => asserts func is (...args: unknown[]) => unknown = (\n  func: unknown,\n  expected: string,\n) => {\n  if (typeof func !== 'function') {\n    throw new TypeError(`${expected} is not a function`)\n  }\n}\n\nexport const noop = () => {}\n\nexport const catchRejection = <T>(\n  promise: Promise<T>,\n  onError = noop,\n): Promise<T> => {\n  promise.catch(onError)\n\n  return promise\n}\n\nexport const addAbortSignalListener = (\n  abortSignal: AbortSignal,\n  callback: (evt: Event) => void,\n) => {\n  abortSignal.addEventListener('abort', callback, { once: true })\n  return () => abortSignal.removeEventListener('abort', callback)\n}\n"
  },
  {
    "path": "packages/toolkit/src/mapBuilders.ts",
    "content": "import type { Action } from 'redux'\nimport type {\n  CaseReducer,\n  CaseReducers,\n  ActionMatcherDescriptionCollection,\n} from './createReducer'\nimport type { TypeGuard } from './tsHelpers'\nimport type { AsyncThunk, AsyncThunkConfig } from './createAsyncThunk'\n\nexport type AsyncThunkReducers<\n  State,\n  ThunkArg extends any,\n  Returned = unknown,\n  ThunkApiConfig extends AsyncThunkConfig = {},\n> = {\n  pending?: CaseReducer<\n    State,\n    ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['pending']>\n  >\n  rejected?: CaseReducer<\n    State,\n    ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected']>\n  >\n  fulfilled?: CaseReducer<\n    State,\n    ReturnType<AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['fulfilled']>\n  >\n  settled?: CaseReducer<\n    State,\n    ReturnType<\n      AsyncThunk<Returned, ThunkArg, ThunkApiConfig>['rejected' | 'fulfilled']\n    >\n  >\n}\n\nexport type TypedActionCreator<Type extends string> = {\n  (...args: any[]): Action<Type>\n  type: Type\n}\n\n/**\n * A builder for an action <-> reducer map.\n *\n * @public\n */\nexport interface ActionReducerMapBuilder<State> {\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<ActionCreator extends TypedActionCreator<string>>(\n    actionCreator: ActionCreator,\n    reducer: CaseReducer<State, ReturnType<ActionCreator>>,\n  ): ActionReducerMapBuilder<State>\n  /**\n   * Adds a case reducer to handle a single exact action type.\n   * @remarks\n   * All calls to `builder.addCase` must come before any calls to `builder.addAsyncThunk`, `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param actionCreator - Either a plain action type string, or an action creator generated by [`createAction`](./createAction) that can be used to determine the action type.\n   * @param reducer - The actual case reducer function.\n   */\n  addCase<Type extends string, A extends Action<Type>>(\n    type: Type,\n    reducer: CaseReducer<State, A>,\n  ): ActionReducerMapBuilder<State>\n\n  /**\n   * Adds case reducers to handle actions based on a `AsyncThunk` action creator.\n   * @remarks\n   * All calls to `builder.addAsyncThunk` must come before after any calls to `builder.addCase` and before any calls to `builder.addMatcher` or `builder.addDefaultCase`.\n   * @param asyncThunk - The async thunk action creator itself.\n   * @param reducers - A mapping from each of the `AsyncThunk` action types to the case reducer that should handle those actions.\n   * @example\n   * ```ts no-transpile\n   * import { createAsyncThunk, createReducer } from '@reduxjs/toolkit';\n   *\n   * const fetchUserById = createAsyncThunk('users/fetchUser', async (id) => {\n   *   const response = await fetch(`https://reqres.in/api/users/${id}`);\n   *   return (await response.json()).data;\n   * });\n   *\n   * const reducer = createReducer(initialState, (builder) => {\n   *   builder.addAsyncThunk(fetchUserById, {\n   *     pending: (state, action) => {\n   *       state.fetchUserById.loading = 'pending';\n   *     },\n   *     fulfilled: (state, action) => {\n   *       state.fetchUserById.data = action.payload;\n   *     },\n   *     rejected: (state, action) => {\n   *       state.fetchUserById.error = action.error;\n   *     },\n   *     settled: (state, action) => {\n   *       state.fetchUserById.loading = action.meta.requestStatus;\n   *     },\n   *   });\n   * });\n   * ```\n   */\n  addAsyncThunk<\n    Returned,\n    ThunkArg,\n    ThunkApiConfig extends AsyncThunkConfig = {},\n  >(\n    asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>,\n    reducers: AsyncThunkReducers<State, ThunkArg, Returned, ThunkApiConfig>,\n  ): Omit<ActionReducerMapBuilder<State>, 'addCase'>\n\n  /**\n   * Allows you to match your incoming actions against your own filter function instead of only the `action.type` property.\n   * @remarks\n   * If multiple matcher reducers match, all of them will be executed in the order\n   * they were defined in - even if a case reducer already matched.\n   * All calls to `builder.addMatcher` must come after any calls to `builder.addCase` and `builder.addAsyncThunk` and before any calls to `builder.addDefaultCase`.\n   * @param matcher - A matcher function. In TypeScript, this should be a [type predicate](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates)\n   *   function\n   * @param reducer - The actual case reducer function.\n   *\n   * @example\n   * ```ts\n   * import type { AsyncThunk, UnknownAction } from '@reduxjs/toolkit';\n   * import { createAction, createReducer } from '@reduxjs/toolkit';\n   *\n   * type GenericAsyncThunk = AsyncThunk<unknown, unknown, any>;\n   *\n   * type PendingAction = ReturnType<GenericAsyncThunk['pending']>;\n   * type RejectedAction = ReturnType<GenericAsyncThunk['rejected']>;\n   * type FulfilledAction = ReturnType<GenericAsyncThunk['fulfilled']>;\n   *\n   * const initialState: Record<string, string> = {};\n   * const resetAction = createAction('reset-tracked-loading-state');\n   *\n   * function isPendingAction(action: UnknownAction): action is PendingAction {\n   *   return typeof action.type === 'string' && action.type.endsWith('/pending');\n   * }\n   *\n   * const reducer = createReducer(initialState, (builder) => {\n   *   builder\n   *     .addCase(resetAction, () => initialState)\n   *     // matcher can be defined outside as a type predicate function\n   *     .addMatcher(isPendingAction, (state, action) => {\n   *       state[action.meta.requestId] = 'pending';\n   *     })\n   *     .addMatcher(\n   *       // matcher can be defined inline as a type predicate function\n   *       (action): action is RejectedAction => action.type.endsWith('/rejected'),\n   *       (state, action) => {\n   *         state[action.meta.requestId] = 'rejected';\n   *       },\n   *     )\n   *     // matcher can just return boolean and the matcher can receive a generic argument\n   *     .addMatcher<FulfilledAction>(\n   *       (action) => action.type.endsWith('/fulfilled'),\n   *       (state, action) => {\n   *         state[action.meta.requestId] = 'fulfilled';\n   *       },\n   *     );\n   * });\n   * ```\n   */\n  addMatcher<A>(\n    matcher: TypeGuard<A> | ((action: any) => boolean),\n    reducer: CaseReducer<State, A extends Action ? A : A & Action>,\n  ): Omit<ActionReducerMapBuilder<State>, 'addCase' | 'addAsyncThunk'>\n\n  /**\n   * Adds a \"default case\" reducer that is executed if no case reducer and no matcher\n   * reducer was executed for this action.\n   * @param reducer - The fallback \"default case\" reducer function.\n   *\n   * @example\n   * ```ts\n   * import { createReducer } from '@reduxjs/toolkit';\n   *\n   * const initialState = { otherActions: 0 };\n   *\n   * const reducer = createReducer(initialState, (builder) => {\n   *   builder\n   *     // .addCase(...)\n   *     // .addMatcher(...)\n   *     .addDefaultCase((state, action) => {\n   *       state.otherActions++;\n   *     });\n   * });\n   * ```\n   */\n  addDefaultCase(reducer: CaseReducer<State, Action>): {}\n}\n\nexport function executeReducerBuilderCallback<S>(\n  builderCallback: (builder: ActionReducerMapBuilder<S>) => void,\n): [\n  CaseReducers<S, any>,\n  ActionMatcherDescriptionCollection<S>,\n  CaseReducer<S, Action> | undefined,\n] {\n  const actionsMap: CaseReducers<S, any> = {}\n  const actionMatchers: ActionMatcherDescriptionCollection<S> = []\n  let defaultCaseReducer: CaseReducer<S, Action> | undefined\n  const builder = {\n    addCase(\n      typeOrActionCreator: string | TypedActionCreator<any>,\n      reducer: CaseReducer<S>,\n    ) {\n      if (process.env.NODE_ENV !== 'production') {\n        /*\n         to keep the definition by the user in line with actual behavior,\n         we enforce `addCase` to always be called before calling `addMatcher`\n         as matching cases take precedence over matchers\n         */\n        if (actionMatchers.length > 0) {\n          throw new Error(\n            '`builder.addCase` should only be called before calling `builder.addMatcher`',\n          )\n        }\n        if (defaultCaseReducer) {\n          throw new Error(\n            '`builder.addCase` should only be called before calling `builder.addDefaultCase`',\n          )\n        }\n      }\n      const type =\n        typeof typeOrActionCreator === 'string'\n          ? typeOrActionCreator\n          : typeOrActionCreator.type\n      if (!type) {\n        throw new Error(\n          '`builder.addCase` cannot be called with an empty action type',\n        )\n      }\n      if (type in actionsMap) {\n        throw new Error(\n          '`builder.addCase` cannot be called with two reducers for the same action type ' +\n            `'${type}'`,\n        )\n      }\n      actionsMap[type] = reducer\n      return builder\n    },\n    addAsyncThunk<\n      Returned,\n      ThunkArg,\n      ThunkApiConfig extends AsyncThunkConfig = {},\n    >(\n      asyncThunk: AsyncThunk<Returned, ThunkArg, ThunkApiConfig>,\n      reducers: AsyncThunkReducers<S, ThunkArg, Returned, ThunkApiConfig>,\n    ) {\n      if (process.env.NODE_ENV !== 'production') {\n        // since this uses both action cases and matchers, we can't enforce the order in runtime other than checking for default case\n        if (defaultCaseReducer) {\n          throw new Error(\n            '`builder.addAsyncThunk` should only be called before calling `builder.addDefaultCase`',\n          )\n        }\n      }\n      if (reducers.pending)\n        actionsMap[asyncThunk.pending.type] = reducers.pending\n      if (reducers.rejected)\n        actionsMap[asyncThunk.rejected.type] = reducers.rejected\n      if (reducers.fulfilled)\n        actionsMap[asyncThunk.fulfilled.type] = reducers.fulfilled\n      if (reducers.settled)\n        actionMatchers.push({\n          matcher: asyncThunk.settled,\n          reducer: reducers.settled,\n        })\n      return builder\n    },\n    addMatcher<A>(\n      matcher: TypeGuard<A>,\n      reducer: CaseReducer<S, A extends Action ? A : A & Action>,\n    ) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error(\n            '`builder.addMatcher` should only be called before calling `builder.addDefaultCase`',\n          )\n        }\n      }\n      actionMatchers.push({ matcher, reducer })\n      return builder\n    },\n    addDefaultCase(reducer: CaseReducer<S, Action>) {\n      if (process.env.NODE_ENV !== 'production') {\n        if (defaultCaseReducer) {\n          throw new Error('`builder.addDefaultCase` can only be called once')\n        }\n      }\n      defaultCaseReducer = reducer\n      return builder\n    },\n  }\n  builderCallback(builder)\n  return [actionsMap, actionMatchers, defaultCaseReducer]\n}\n"
  },
  {
    "path": "packages/toolkit/src/matchers.ts",
    "content": "import type {\n  ActionFromMatcher,\n  Matcher,\n  UnionToIntersection,\n} from './tsHelpers'\nimport { hasMatchFunction } from './tsHelpers'\nimport type {\n  AsyncThunk,\n  AsyncThunkFulfilledActionCreator,\n  AsyncThunkPendingActionCreator,\n  AsyncThunkRejectedActionCreator,\n} from './createAsyncThunk'\n\n/** @public */\nexport type ActionMatchingAnyOf<Matchers extends Matcher<any>[]> =\n  ActionFromMatcher<Matchers[number]>\n\n/** @public */\nexport type ActionMatchingAllOf<Matchers extends Matcher<any>[]> =\n  UnionToIntersection<ActionMatchingAnyOf<Matchers>>\n\nconst matches = (matcher: Matcher<any>, action: any) => {\n  if (hasMatchFunction(matcher)) {\n    return matcher.match(action)\n  } else {\n    return matcher(action)\n  }\n}\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches any one of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAnyOf<Matchers extends Matcher<any>[]>(\n  ...matchers: Matchers\n) {\n  return (action: any): action is ActionMatchingAnyOf<Matchers> => {\n    return matchers.some((matcher) => matches(matcher, action))\n  }\n}\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action matches all of the supplied type guards or action\n * creators.\n *\n * @param matchers The type guards or action creators to match against.\n *\n * @public\n */\nexport function isAllOf<Matchers extends Matcher<any>[]>(\n  ...matchers: Matchers\n) {\n  return (action: any): action is ActionMatchingAllOf<Matchers> => {\n    return matchers.every((matcher) => matches(matcher, action))\n  }\n}\n\n/**\n * @param action A redux action\n * @param validStatus An array of valid meta.requestStatus values\n *\n * @internal\n */\nexport function hasExpectedRequestMetadata(\n  action: any,\n  validStatus: readonly string[],\n) {\n  if (!action || !action.meta) return false\n\n  const hasValidRequestId = typeof action.meta.requestId === 'string'\n  const hasValidRequestStatus =\n    validStatus.indexOf(action.meta.requestStatus) > -1\n\n  return hasValidRequestId && hasValidRequestStatus\n}\n\nfunction isAsyncThunkArray(a: [any] | AnyAsyncThunk[]): a is AnyAsyncThunk[] {\n  return (\n    typeof a[0] === 'function' &&\n    'pending' in a[0] &&\n    'fulfilled' in a[0] &&\n    'rejected' in a[0]\n  )\n}\n\nexport type UnknownAsyncThunkPendingAction = ReturnType<\n  AsyncThunkPendingActionCreator<unknown>\n>\n\nexport type PendingActionFromAsyncThunk<T extends AnyAsyncThunk> =\n  ActionFromMatcher<T['pending']>\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is pending.\n *\n * @public\n */\nexport function isPending(): (\n  action: any,\n) => action is UnknownAsyncThunkPendingAction\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is pending.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isPending<\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\n>(\n  ...asyncThunks: AsyncThunks\n): (action: any) => action is PendingActionFromAsyncThunk<AsyncThunks[number]>\n/**\n * Tests if `action` is a pending thunk action\n * @public\n */\nexport function isPending(action: any): action is UnknownAsyncThunkPendingAction\nexport function isPending<\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\n>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['pending'])\n  }\n\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isPending()(asyncThunks[0])\n  }\n\n  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.pending))\n}\n\nexport type UnknownAsyncThunkRejectedAction = ReturnType<\n  AsyncThunkRejectedActionCreator<unknown, unknown>\n>\n\nexport type RejectedActionFromAsyncThunk<T extends AnyAsyncThunk> =\n  ActionFromMatcher<T['rejected']>\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected.\n *\n * @public\n */\nexport function isRejected(): (\n  action: any,\n) => action is UnknownAsyncThunkRejectedAction\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejected<\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\n>(\n  ...asyncThunks: AsyncThunks\n): (action: any) => action is RejectedActionFromAsyncThunk<AsyncThunks[number]>\n/**\n * Tests if `action` is a rejected thunk action\n * @public\n */\nexport function isRejected(\n  action: any,\n): action is UnknownAsyncThunkRejectedAction\nexport function isRejected<\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\n>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['rejected'])\n  }\n\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejected()(asyncThunks[0])\n  }\n\n  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.rejected))\n}\n\nexport type UnknownAsyncThunkRejectedWithValueAction = ReturnType<\n  AsyncThunkRejectedActionCreator<unknown, unknown>\n>\n\nexport type RejectedWithValueActionFromAsyncThunk<T extends AnyAsyncThunk> =\n  ActionFromMatcher<T['rejected']> &\n    (T extends AsyncThunk<any, any, { rejectValue: infer RejectedValue }>\n      ? { payload: RejectedValue }\n      : unknown)\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is rejected with value.\n *\n * @public\n */\nexport function isRejectedWithValue(): (\n  action: any,\n) => action is UnknownAsyncThunkRejectedAction\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is rejected with value.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isRejectedWithValue<\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\n>(\n  ...asyncThunks: AsyncThunks\n): (\n  action: any,\n) => action is RejectedWithValueActionFromAsyncThunk<AsyncThunks[number]>\n/**\n * Tests if `action` is a rejected thunk action with value\n * @public\n */\nexport function isRejectedWithValue(\n  action: any,\n): action is UnknownAsyncThunkRejectedAction\nexport function isRejectedWithValue<\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\n>(...asyncThunks: AsyncThunks | [any]) {\n  const hasFlag = (action: any): action is any => {\n    return action && action.meta && action.meta.rejectedWithValue\n  }\n\n  if (asyncThunks.length === 0) {\n    return isAllOf(isRejected(...asyncThunks), hasFlag)\n  }\n\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isRejectedWithValue()(asyncThunks[0])\n  }\n\n  return isAllOf(isRejected(...asyncThunks), hasFlag)\n}\n\nexport type UnknownAsyncThunkFulfilledAction = ReturnType<\n  AsyncThunkFulfilledActionCreator<unknown, unknown>\n>\n\nexport type FulfilledActionFromAsyncThunk<T extends AnyAsyncThunk> =\n  ActionFromMatcher<T['fulfilled']>\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator, and that\n * the action is fulfilled.\n *\n * @public\n */\nexport function isFulfilled(): (\n  action: any,\n) => action is UnknownAsyncThunkFulfilledAction\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators,\n * and that the action is fulfilled.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isFulfilled<\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\n>(\n  ...asyncThunks: AsyncThunks\n): (action: any) => action is FulfilledActionFromAsyncThunk<AsyncThunks[number]>\n/**\n * Tests if `action` is a fulfilled thunk action\n * @public\n */\nexport function isFulfilled(\n  action: any,\n): action is UnknownAsyncThunkFulfilledAction\nexport function isFulfilled<\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\n>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) => hasExpectedRequestMetadata(action, ['fulfilled'])\n  }\n\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isFulfilled()(asyncThunks[0])\n  }\n\n  return isAnyOf(...asyncThunks.map((asyncThunk) => asyncThunk.fulfilled))\n}\n\nexport type UnknownAsyncThunkAction =\n  | UnknownAsyncThunkPendingAction\n  | UnknownAsyncThunkRejectedAction\n  | UnknownAsyncThunkFulfilledAction\n\nexport type AnyAsyncThunk = {\n  pending: { match: (action: any) => action is any }\n  fulfilled: { match: (action: any) => action is any }\n  rejected: { match: (action: any) => action is any }\n}\n\nexport type ActionsFromAsyncThunk<T extends AnyAsyncThunk> =\n  | ActionFromMatcher<T['pending']>\n  | ActionFromMatcher<T['fulfilled']>\n  | ActionFromMatcher<T['rejected']>\n\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action was created by an async thunk action creator.\n *\n * @public\n */\nexport function isAsyncThunkAction(): (\n  action: any,\n) => action is UnknownAsyncThunkAction\n/**\n * A higher-order function that returns a function that may be used to check\n * whether an action belongs to one of the provided async thunk action creators.\n *\n * @param asyncThunks (optional) The async thunk action creators to match against.\n *\n * @public\n */\nexport function isAsyncThunkAction<\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\n>(\n  ...asyncThunks: AsyncThunks\n): (action: any) => action is ActionsFromAsyncThunk<AsyncThunks[number]>\n/**\n * Tests if `action` is a thunk action\n * @public\n */\nexport function isAsyncThunkAction(\n  action: any,\n): action is UnknownAsyncThunkAction\nexport function isAsyncThunkAction<\n  AsyncThunks extends [AnyAsyncThunk, ...AnyAsyncThunk[]],\n>(...asyncThunks: AsyncThunks | [any]) {\n  if (asyncThunks.length === 0) {\n    return (action: any) =>\n      hasExpectedRequestMetadata(action, ['pending', 'fulfilled', 'rejected'])\n  }\n\n  if (!isAsyncThunkArray(asyncThunks)) {\n    return isAsyncThunkAction()(asyncThunks[0])\n  }\n\n  return isAnyOf(...asyncThunks.flatMap(asyncThunk => [asyncThunk.pending, asyncThunk.rejected, asyncThunk.fulfilled]))\n}\n"
  },
  {
    "path": "packages/toolkit/src/nanoid.ts",
    "content": "// Borrowed from https://github.com/ai/nanoid/blob/3.0.2/non-secure/index.js\n// This alphabet uses `A-Za-z0-9_-` symbols. A genetic algorithm helped\n// optimize the gzip compression for this alphabet.\nlet urlAlphabet =\n  'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'\n\n/**\n *\n * @public\n */\nexport let nanoid = (size = 21) => {\n  let id = ''\n  // A compact alternative for `for (var i = 0; i < step; i++)`.\n  let i = size\n  while (i--) {\n    // `| 0` is more compact and faster than `Math.floor()`.\n    id += urlAlphabet[(Math.random() * 64) | 0]\n  }\n  return id\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/HandledError.ts",
    "content": "export class HandledError {\n  constructor(\n    public readonly value: any,\n    public readonly meta: any = undefined,\n  ) {}\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/apiTypes.ts",
    "content": "import type { UnknownAction } from '@reduxjs/toolkit'\nimport type { BaseQueryFn } from './baseQueryTypes'\nimport type { CombinedState, CoreModule, QueryKeys } from './core'\nimport type { ApiModules } from './core/module'\nimport type { CreateApiOptions } from './createApi'\nimport type {\n  EndpointBuilder,\n  EndpointDefinition,\n  EndpointDefinitions,\n  UpdateDefinitions,\n} from './endpointDefinitions'\nimport type {\n  NoInfer,\n  UnionToIntersection,\n  WithRequiredProp,\n} from './tsHelpers'\n\nexport type ModuleName = keyof ApiModules<any, any, any, any>\n\nexport type Module<Name extends ModuleName> = {\n  name: Name\n  init<\n    BaseQuery extends BaseQueryFn,\n    Definitions extends EndpointDefinitions,\n    ReducerPath extends string,\n    TagTypes extends string,\n  >(\n    api: Api<BaseQuery, EndpointDefinitions, ReducerPath, TagTypes, ModuleName>,\n    options: WithRequiredProp<\n      CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,\n      | 'reducerPath'\n      | 'serializeQueryArgs'\n      | 'keepUnusedDataFor'\n      | 'refetchOnMountOrArgChange'\n      | 'refetchOnFocus'\n      | 'refetchOnReconnect'\n      | 'invalidationBehavior'\n      | 'tagTypes'\n    >,\n    context: ApiContext<Definitions>,\n  ): {\n    injectEndpoint(\n      endpointName: string,\n      definition: EndpointDefinition<any, any, any, any>,\n    ): void\n  }\n}\n\nexport interface ApiContext<Definitions extends EndpointDefinitions> {\n  apiUid: string\n  endpointDefinitions: Definitions\n  batch(cb: () => void): void\n  extractRehydrationInfo: (\n    action: UnknownAction,\n  ) => CombinedState<any, any, any> | undefined\n  hasRehydrationInfo: (action: UnknownAction) => boolean\n}\n\nexport const getEndpointDefinition = <\n  Definitions extends EndpointDefinitions,\n  EndpointName extends keyof Definitions,\n>(\n  context: ApiContext<Definitions>,\n  endpointName: EndpointName,\n) => context.endpointDefinitions[endpointName]\n\nexport type Api<\n  BaseQuery extends BaseQueryFn,\n  Definitions extends EndpointDefinitions,\n  ReducerPath extends string,\n  TagTypes extends string,\n  Enhancers extends ModuleName = CoreModule,\n> = UnionToIntersection<\n  ApiModules<BaseQuery, Definitions, ReducerPath, TagTypes>[Enhancers]\n> & {\n  /**\n   * A function to inject the endpoints into the original API, but also give you that same API with correct types for these endpoints back. Useful with code-splitting.\n   */\n  injectEndpoints<NewDefinitions extends EndpointDefinitions>(_: {\n    endpoints: (\n      build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,\n    ) => NewDefinitions\n    /**\n     * Optionally allows endpoints to be overridden if defined by multiple `injectEndpoints` calls.\n     *\n     * If set to `true`, will override existing endpoints with the new definition.\n     * If set to `'throw'`, will throw an error if an endpoint is redefined with a different definition.\n     * If set to `false` (or unset), will not override existing endpoints with the new definition, and log a warning in development.\n     */\n    overrideExisting?: boolean | 'throw'\n  }): Api<\n    BaseQuery,\n    Definitions & NewDefinitions,\n    ReducerPath,\n    TagTypes,\n    Enhancers\n  >\n  /**\n   *A function to enhance a generated API with additional information. Useful with code-generation.\n   */\n  enhanceEndpoints<\n    NewTagTypes extends string = never,\n    NewDefinitions extends EndpointDefinitions = never,\n  >(_: {\n    addTagTypes?: readonly NewTagTypes[]\n    endpoints?: UpdateDefinitions<\n      Definitions,\n      TagTypes | NoInfer<NewTagTypes>,\n      NewDefinitions\n    > extends infer NewDefinitions\n      ? {\n          [K in keyof NewDefinitions]?:\n            | Partial<NewDefinitions[K]>\n            | ((definition: NewDefinitions[K]) => void)\n        }\n      : never\n  }): Api<\n    BaseQuery,\n    UpdateDefinitions<Definitions, TagTypes | NewTagTypes, NewDefinitions>,\n    ReducerPath,\n    TagTypes | NewTagTypes,\n    Enhancers\n  >\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/baseQueryTypes.ts",
    "content": "import type { ThunkDispatch } from '@reduxjs/toolkit'\nimport type { MaybePromise, UnwrapPromise } from './tsHelpers'\n\nexport interface BaseQueryApi {\n  signal: AbortSignal\n  abort: (reason?: string) => void\n  dispatch: ThunkDispatch<any, any, any>\n  getState: () => unknown\n  extra: unknown\n  endpoint: string\n  type: 'query' | 'mutation'\n  /**\n   * Only available for queries: indicates if a query has been forced,\n   * i.e. it would have been fetched even if there would already be a cache entry\n   * (this does not mean that there is already a cache entry though!)\n   *\n   * This can be used to for example add a `Cache-Control: no-cache` header for\n   * invalidated queries.\n   */\n  forced?: boolean\n  /**\n   * Only available for queries: the cache key that was used to store the query result\n   */\n  queryCacheKey?: string\n}\n\nexport type QueryReturnValue<T = unknown, E = unknown, M = unknown> =\n  | {\n      error: E\n      data?: undefined\n      meta?: M\n    }\n  | {\n      error?: undefined\n      data: T\n      meta?: M\n    }\n\nexport type BaseQueryFn<\n  Args = any,\n  Result = unknown,\n  Error = unknown,\n  DefinitionExtraOptions = {},\n  Meta = {},\n> = (\n  args: Args,\n  api: BaseQueryApi,\n  extraOptions: DefinitionExtraOptions,\n) => MaybePromise<QueryReturnValue<Result, Error, Meta>>\n\nexport type BaseQueryEnhancer<\n  AdditionalArgs = unknown,\n  AdditionalDefinitionExtraOptions = unknown,\n  Config = void,\n> = <BaseQuery extends BaseQueryFn>(\n  baseQuery: BaseQuery,\n  config: Config,\n) => BaseQueryFn<\n  BaseQueryArg<BaseQuery> & AdditionalArgs,\n  BaseQueryResult<BaseQuery>,\n  BaseQueryError<BaseQuery>,\n  BaseQueryExtraOptions<BaseQuery> & AdditionalDefinitionExtraOptions,\n  NonNullable<BaseQueryMeta<BaseQuery>>\n>\n\n/**\n * @public\n */\nexport type BaseQueryResult<BaseQuery extends BaseQueryFn> =\n  UnwrapPromise<ReturnType<BaseQuery>> extends infer Unwrapped\n    ? Unwrapped extends { data: any }\n      ? Unwrapped['data']\n      : never\n    : never\n\n/**\n * @public\n */\nexport type BaseQueryMeta<BaseQuery extends BaseQueryFn> = UnwrapPromise<\n  ReturnType<BaseQuery>\n>['meta']\n\n/**\n * @public\n */\nexport type BaseQueryError<BaseQuery extends BaseQueryFn> = Exclude<\n  UnwrapPromise<ReturnType<BaseQuery>>,\n  { error?: undefined }\n>['error']\n\n/**\n * @public\n */\nexport type BaseQueryArg<T extends (arg: any, ...args: any[]) => any> =\n  T extends (arg: infer A, ...args: any[]) => any ? A : any\n\n/**\n * @public\n */\nexport type BaseQueryExtraOptions<BaseQuery extends BaseQueryFn> =\n  Parameters<BaseQuery>[2]\n"
  },
  {
    "path": "packages/toolkit/src/query/core/apiState.ts",
    "content": "import type { SerializedError } from '@reduxjs/toolkit'\nimport type { BaseQueryError } from '../baseQueryTypes'\nimport type {\n  BaseEndpointDefinition,\n  EndpointDefinitions,\n  FullTagDescription,\n  InfiniteQueryDefinition,\n  MutationDefinition,\n  PageParamFrom,\n  QueryArgFromAnyQuery,\n  QueryDefinition,\n  ResultTypeFrom,\n} from '../endpointDefinitions'\nimport type { Id, WithRequiredProp } from '../tsHelpers'\n\nexport type QueryCacheKey = string & { _type: 'queryCacheKey' }\nexport type QuerySubstateIdentifier = { queryCacheKey: QueryCacheKey }\nexport type MutationSubstateIdentifier =\n  | { requestId: string; fixedCacheKey?: string }\n  | { requestId?: string; fixedCacheKey: string }\n\nexport type RefetchConfigOptions = {\n  refetchOnMountOrArgChange: boolean | number\n  refetchOnReconnect: boolean\n  refetchOnFocus: boolean\n}\n\nexport type InfiniteQueryConfigOptions<DataType, PageParam, QueryArg> = {\n  /**\n   * The initial page parameter to use for the first page fetch.\n   */\n  initialPageParam: PageParam\n  /**\n   * This function is required to automatically get the next cursor for infinite queries.\n   * The result will also be used to determine the value of `hasNextPage`.\n   */\n  getNextPageParam: (\n    lastPage: DataType,\n    allPages: Array<DataType>,\n    lastPageParam: PageParam,\n    allPageParams: Array<PageParam>,\n    queryArg: QueryArg,\n  ) => PageParam | undefined | null\n  /**\n   * This function can be set to automatically get the previous cursor for infinite queries.\n   * The result will also be used to determine the value of `hasPreviousPage`.\n   */\n  getPreviousPageParam?: (\n    firstPage: DataType,\n    allPages: Array<DataType>,\n    firstPageParam: PageParam,\n    allPageParams: Array<PageParam>,\n    queryArg: QueryArg,\n  ) => PageParam | undefined | null\n  /**\n   * If specified, only keep this many pages in cache at once.\n   * If additional pages are fetched, older pages in the other\n   * direction will be dropped from the cache.\n   */\n  maxPages?: number\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   */\n  refetchCachedPages?: boolean\n}\n\nexport type InfiniteData<DataType, PageParam> = {\n  pages: Array<DataType>\n  pageParams: Array<PageParam>\n}\n\n// NOTE: DO NOT import and use this for runtime comparisons internally,\n// except in the RTKQ React package. Use the string versions just below this.\n// ESBuild auto-inlines TS enums, which bloats our bundle with many repeated\n// constants like \"initialized\":\n// https://github.com/evanw/esbuild/releases/tag/v0.14.7\n// We still have to use this in the React package since we don't publicly export\n// the string constants below.\n/**\n * Strings describing the query state at any given time.\n */\nexport enum QueryStatus {\n  uninitialized = 'uninitialized',\n  pending = 'pending',\n  fulfilled = 'fulfilled',\n  rejected = 'rejected',\n}\n\n// Use these string constants for runtime comparisons internally\nexport const STATUS_UNINITIALIZED = QueryStatus.uninitialized\nexport const STATUS_PENDING = QueryStatus.pending\nexport const STATUS_FULFILLED = QueryStatus.fulfilled\nexport const STATUS_REJECTED = QueryStatus.rejected\n\nexport type RequestStatusFlags =\n  | {\n      status: QueryStatus.uninitialized\n      isUninitialized: true\n      isLoading: false\n      isSuccess: false\n      isError: false\n    }\n  | {\n      status: QueryStatus.pending\n      isUninitialized: false\n      isLoading: true\n      isSuccess: false\n      isError: false\n    }\n  | {\n      status: QueryStatus.fulfilled\n      isUninitialized: false\n      isLoading: false\n      isSuccess: true\n      isError: false\n    }\n  | {\n      status: QueryStatus.rejected\n      isUninitialized: false\n      isLoading: false\n      isSuccess: false\n      isError: true\n    }\n\nexport function getRequestStatusFlags(status: QueryStatus): RequestStatusFlags {\n  return {\n    status,\n    isUninitialized: status === STATUS_UNINITIALIZED,\n    isLoading: status === STATUS_PENDING,\n    isSuccess: status === STATUS_FULFILLED,\n    isError: status === STATUS_REJECTED,\n  } as any\n}\n\n/**\n * @public\n */\nexport type SubscriptionOptions = {\n  /**\n   * How frequently to automatically re-fetch data (in milliseconds). Defaults to `0` (off).\n   */\n  pollingInterval?: number\n  /**\n   *  Defaults to 'false'. This setting allows you to control whether RTK Query will continue polling if the window is not focused.\n   *\n   *  If pollingInterval is not set or set to 0, this **will not be evaluated** until pollingInterval is greater than 0.\n   *\n   *  Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  skipPollingIfUnfocused?: boolean\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean\n}\nexport type SubscribersInternal = Map<string, SubscriptionOptions>\nexport type Subscribers = { [requestId: string]: SubscriptionOptions }\nexport type QueryKeys<Definitions extends EndpointDefinitions> = {\n  [K in keyof Definitions]: Definitions[K] extends QueryDefinition<\n    any,\n    any,\n    any,\n    any\n  >\n    ? K\n    : never\n}[keyof Definitions]\n\nexport type InfiniteQueryKeys<Definitions extends EndpointDefinitions> = {\n  [K in keyof Definitions]: Definitions[K] extends InfiniteQueryDefinition<\n    any,\n    any,\n    any,\n    any,\n    any\n  >\n    ? K\n    : never\n}[keyof Definitions]\n\nexport type MutationKeys<Definitions extends EndpointDefinitions> = {\n  [K in keyof Definitions]: Definitions[K] extends MutationDefinition<\n    any,\n    any,\n    any,\n    any\n  >\n    ? K\n    : never\n}[keyof Definitions]\n\ntype BaseQuerySubState<\n  D extends BaseEndpointDefinition<any, any, any, any>,\n  DataType = ResultTypeFrom<D>,\n> = {\n  /**\n   * The argument originally passed into the hook or `initiate` action call\n   */\n  originalArgs: QueryArgFromAnyQuery<D>\n  /**\n   * A unique ID associated with the request\n   */\n  requestId: string\n  /**\n   * The received data from the query\n   */\n  data?: DataType\n  /**\n   * The received error if applicable\n   */\n  error?:\n    | SerializedError\n    | (D extends QueryDefinition<any, infer BaseQuery, any, any>\n        ? BaseQueryError<BaseQuery>\n        : never)\n  /**\n   * The name of the endpoint associated with the query\n   */\n  endpointName: string\n  /**\n   * Time that the latest query started\n   */\n  startedTimeStamp: number\n  /**\n   * Time that the latest query was fulfilled\n   */\n  fulfilledTimeStamp?: number\n}\n\nexport type QuerySubState<\n  D extends BaseEndpointDefinition<any, any, any, any>,\n  DataType = ResultTypeFrom<D>,\n> = Id<\n  | ({ status: QueryStatus.fulfilled } & WithRequiredProp<\n      BaseQuerySubState<D, DataType>,\n      'data' | 'fulfilledTimeStamp'\n    > & { error: undefined })\n  | ({ status: QueryStatus.pending } & BaseQuerySubState<D, DataType>)\n  | ({ status: QueryStatus.rejected } & WithRequiredProp<\n      BaseQuerySubState<D, DataType>,\n      'error'\n    >)\n  | {\n      status: QueryStatus.uninitialized\n      originalArgs?: undefined\n      data?: undefined\n      error?: undefined\n      requestId?: undefined\n      endpointName?: string\n      startedTimeStamp?: undefined\n      fulfilledTimeStamp?: undefined\n    }\n>\n\nexport type InfiniteQueryDirection = 'forward' | 'backward'\n\nexport type InfiniteQuerySubState<\n  D extends BaseEndpointDefinition<any, any, any, any>,\n> =\n  D extends InfiniteQueryDefinition<any, any, any, any, any>\n    ? QuerySubState<D, InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>> & {\n        direction?: InfiniteQueryDirection\n      }\n    : never\n\ntype BaseMutationSubState<\n  D extends BaseEndpointDefinition<any, any, any, any>,\n> = {\n  requestId: string\n  data?: ResultTypeFrom<D>\n  error?:\n    | SerializedError\n    | (D extends MutationDefinition<any, infer BaseQuery, any, any>\n        ? BaseQueryError<BaseQuery>\n        : never)\n  endpointName: string\n  startedTimeStamp: number\n  fulfilledTimeStamp?: number\n}\n\nexport type MutationSubState<\n  D extends BaseEndpointDefinition<any, any, any, any>,\n> =\n  | (({\n      status: QueryStatus.fulfilled\n    } & WithRequiredProp<\n      BaseMutationSubState<D>,\n      'data' | 'fulfilledTimeStamp'\n    >) & { error: undefined })\n  | (({ status: QueryStatus.pending } & BaseMutationSubState<D>) & {\n      data?: undefined\n    })\n  | ({ status: QueryStatus.rejected } & WithRequiredProp<\n      BaseMutationSubState<D>,\n      'error'\n    >)\n  | {\n      requestId?: undefined\n      status: QueryStatus.uninitialized\n      data?: undefined\n      error?: undefined\n      endpointName?: string\n      startedTimeStamp?: undefined\n      fulfilledTimeStamp?: undefined\n    }\n\nexport type CombinedState<\n  D extends EndpointDefinitions,\n  E extends string,\n  ReducerPath extends string,\n> = {\n  queries: QueryState<D>\n  mutations: MutationState<D>\n  provided: InvalidationState<E>\n  subscriptions: SubscriptionState\n  config: ConfigState<ReducerPath>\n}\n\nexport type InvalidationState<TagTypes extends string> = {\n  tags: {\n    [_ in TagTypes]: {\n      [id: string]: Array<QueryCacheKey>\n      [id: number]: Array<QueryCacheKey>\n    }\n  }\n  keys: Record<QueryCacheKey, Array<FullTagDescription<any>>>\n}\n\nexport type QueryState<D extends EndpointDefinitions> = {\n  [queryCacheKey: string]:\n    | QuerySubState<D[string]>\n    | InfiniteQuerySubState<D[string]>\n    | undefined\n}\n\nexport type SubscriptionInternalState = Map<string, SubscribersInternal>\n\nexport type SubscriptionState = {\n  [queryCacheKey: string]: Subscribers | undefined\n}\n\nexport type ConfigState<ReducerPath> = RefetchConfigOptions & {\n  reducerPath: ReducerPath\n  online: boolean\n  focused: boolean\n  middlewareRegistered: boolean | 'conflict'\n} & ModifiableConfigState\n\nexport type ModifiableConfigState = {\n  keepUnusedDataFor: number\n  invalidationBehavior: 'delayed' | 'immediately'\n} & RefetchConfigOptions\n\nexport type MutationState<D extends EndpointDefinitions> = {\n  [requestId: string]: MutationSubState<D[string]> | undefined\n}\n\nexport type RootState<\n  Definitions extends EndpointDefinitions,\n  TagTypes extends string,\n  ReducerPath extends string,\n> = { [P in ReducerPath]: CombinedState<Definitions, TagTypes, P> }\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildInitiate.ts",
    "content": "import type {\n  AsyncThunkAction,\n  SafePromise,\n  SerializedError,\n  ThunkAction,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport type { Dispatch } from 'redux'\nimport { asSafePromise } from '../../tsHelpers'\nimport { getEndpointDefinition, type Api, type ApiContext } from '../apiTypes'\nimport type { BaseQueryError, QueryReturnValue } from '../baseQueryTypes'\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\nimport {\n  ENDPOINT_QUERY,\n  isQueryDefinition,\n  type EndpointDefinition,\n  type EndpointDefinitions,\n  type InfiniteQueryArgFrom,\n  type InfiniteQueryDefinition,\n  type MutationDefinition,\n  type PageParamFrom,\n  type QueryArgFrom,\n  type QueryDefinition,\n  type ResultTypeFrom,\n} from '../endpointDefinitions'\nimport { filterNullishValues } from '../utils'\nimport type {\n  InfiniteData,\n  InfiniteQueryConfigOptions,\n  InfiniteQueryDirection,\n  SubscriptionOptions,\n} from './apiState'\nimport type {\n  InfiniteQueryResultSelectorResult,\n  QueryResultSelectorResult,\n} from './buildSelectors'\nimport type {\n  InfiniteQueryThunk,\n  InfiniteQueryThunkArg,\n  MutationThunk,\n  QueryThunk,\n  QueryThunkArg,\n  ThunkApiMetaConfig,\n} from './buildThunks'\nimport type { ApiEndpointQuery } from './module'\nimport type { InternalMiddlewareState } from './buildMiddleware/types'\n\nexport type BuildInitiateApiEndpointQuery<\n  Definition extends QueryDefinition<any, any, any, any, any>,\n> = {\n  initiate: StartQueryActionCreator<Definition>\n}\n\nexport type BuildInitiateApiEndpointInfiniteQuery<\n  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = {\n  initiate: StartInfiniteQueryActionCreator<Definition>\n}\n\nexport type BuildInitiateApiEndpointMutation<\n  Definition extends MutationDefinition<any, any, any, any, any>,\n> = {\n  initiate: StartMutationActionCreator<Definition>\n}\n\nexport const forceQueryFnSymbol = Symbol('forceQueryFn')\nexport const isUpsertQuery = (arg: QueryThunkArg) =>\n  typeof arg[forceQueryFnSymbol] === 'function'\n\nexport type StartQueryActionCreatorOptions = {\n  subscribe?: boolean\n  forceRefetch?: boolean | number\n  subscriptionOptions?: SubscriptionOptions\n  [forceQueryFnSymbol]?: () => QueryReturnValue\n}\n\ntype RefetchOptions = {\n  refetchCachedPages?: boolean\n}\n\nexport type StartInfiniteQueryActionCreatorOptions<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = StartQueryActionCreatorOptions & {\n  direction?: InfiniteQueryDirection\n  param?: unknown\n} & Partial<\n    Pick<\n      Partial<\n        InfiniteQueryConfigOptions<\n          ResultTypeFrom<D>,\n          PageParamFrom<D>,\n          InfiniteQueryArgFrom<D>\n        >\n      >,\n      'initialPageParam' | 'refetchCachedPages'\n    >\n  >\n\ntype AnyQueryActionCreator<D extends EndpointDefinition<any, any, any, any>> = (\n  arg: any,\n  options?: StartQueryActionCreatorOptions,\n) => ThunkAction<AnyActionCreatorResult, any, any, UnknownAction>\n\ntype StartQueryActionCreator<\n  D extends QueryDefinition<any, any, any, any, any>,\n> = (\n  arg: QueryArgFrom<D>,\n  options?: StartQueryActionCreatorOptions,\n) => ThunkAction<QueryActionCreatorResult<D>, any, any, UnknownAction>\n\nexport type StartInfiniteQueryActionCreator<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = (\n  arg: InfiniteQueryArgFrom<D>,\n  options?: StartInfiniteQueryActionCreatorOptions<D>,\n) => ThunkAction<InfiniteQueryActionCreatorResult<D>, any, any, UnknownAction>\n\ntype QueryActionCreatorFields = {\n  requestId: string\n  subscriptionOptions: SubscriptionOptions | undefined\n  abort(): void\n  unsubscribe(): void\n  updateSubscriptionOptions(options: SubscriptionOptions): void\n  queryCacheKey: string\n}\n\ntype AnyActionCreatorResult = SafePromise<any> &\n  QueryActionCreatorFields & {\n    arg: any\n    unwrap(): Promise<any>\n    refetch(options?: RefetchOptions): AnyActionCreatorResult\n  }\n\nexport type QueryActionCreatorResult<\n  D extends QueryDefinition<any, any, any, any>,\n> = SafePromise<QueryResultSelectorResult<D>> &\n  QueryActionCreatorFields & {\n    arg: QueryArgFrom<D>\n    unwrap(): Promise<ResultTypeFrom<D>>\n    refetch(): QueryActionCreatorResult<D>\n  }\n\nexport type InfiniteQueryActionCreatorResult<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = SafePromise<InfiniteQueryResultSelectorResult<D>> &\n  QueryActionCreatorFields & {\n    arg: InfiniteQueryArgFrom<D>\n    unwrap(): Promise<InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>>\n    refetch(\n      options?: Pick<\n        StartInfiniteQueryActionCreatorOptions<D>,\n        'refetchCachedPages'\n      >,\n    ): InfiniteQueryActionCreatorResult<D>\n  }\n\ntype StartMutationActionCreator<\n  D extends MutationDefinition<any, any, any, any>,\n> = (\n  arg: QueryArgFrom<D>,\n  options?: {\n    /**\n     * If this mutation should be tracked in the store.\n     * If you just want to manually trigger this mutation using `dispatch` and don't care about the\n     * result, state & potential errors being held in store, you can set this to false.\n     * (defaults to `true`)\n     */\n    track?: boolean\n    fixedCacheKey?: string\n  },\n) => ThunkAction<MutationActionCreatorResult<D>, any, any, UnknownAction>\n\nexport type MutationActionCreatorResult<\n  D extends MutationDefinition<any, any, any, any>,\n> = SafePromise<\n  | {\n      data: ResultTypeFrom<D>\n      error?: undefined\n    }\n  | {\n      data?: undefined\n      error:\n        | Exclude<\n            BaseQueryError<\n              D extends MutationDefinition<any, infer BaseQuery, any, any>\n                ? BaseQuery\n                : never\n            >,\n            undefined\n          >\n        | SerializedError\n    }\n> & {\n  /** @internal */\n  arg: {\n    /**\n     * The name of the given endpoint for the mutation\n     */\n    endpointName: string\n    /**\n     * The original arguments supplied to the mutation call\n     */\n    originalArgs: QueryArgFrom<D>\n    /**\n     * Whether the mutation is being tracked in the store.\n     */\n    track?: boolean\n    fixedCacheKey?: string\n  }\n  /**\n   * A unique string generated for the request sequence\n   */\n  requestId: string\n\n  /**\n   * A method to cancel the mutation promise. Note that this is not intended to prevent the mutation\n   * that was fired off from reaching the server, but only to assist in handling the response.\n   *\n   * Calling `abort()` prior to the promise resolving will force it to reach the error state with\n   * the serialized error:\n   * `{ name: 'AbortError', message: 'Aborted' }`\n   *\n   * @example\n   * ```ts\n   * const [updateUser] = useUpdateUserMutation();\n   *\n   * useEffect(() => {\n   *   const promise = updateUser(id);\n   *   promise\n   *     .unwrap()\n   *     .catch((err) => {\n   *       if (err.name === 'AbortError') return;\n   *       // else handle the unexpected error\n   *     })\n   *\n   *   return () => {\n   *     promise.abort();\n   *   }\n   * }, [id, updateUser])\n   * ```\n   */\n  abort(): void\n  /**\n   * Unwraps a mutation call to provide the raw response/error.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap\"\n   * addPost({ id: 1, name: 'Example' })\n   *   .unwrap()\n   *   .then((payload) => console.log('fulfilled', payload))\n   *   .catch((error) => console.error('rejected', error));\n   * ```\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n   *   console.log('fulfilled', payload)\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  unwrap(): Promise<ResultTypeFrom<D>>\n  /**\n   * A method to manually unsubscribe from the mutation call, meaning it will be removed from cache after the usual caching grace period.\n   The value returned by the hook will reset to `isUninitialized` afterwards.\n   */\n  reset(): void\n}\n\nexport function buildInitiate({\n  serializeQueryArgs,\n  queryThunk,\n  infiniteQueryThunk,\n  mutationThunk,\n  api,\n  context,\n  getInternalState,\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs\n  queryThunk: QueryThunk\n  infiniteQueryThunk: InfiniteQueryThunk<any>\n  mutationThunk: MutationThunk\n  api: Api<any, EndpointDefinitions, any, any>\n  context: ApiContext<EndpointDefinitions>\n  getInternalState: (dispatch: Dispatch) => InternalMiddlewareState\n}) {\n  const getRunningQueries = (dispatch: Dispatch) =>\n    getInternalState(dispatch)?.runningQueries\n  const getRunningMutations = (dispatch: Dispatch) =>\n    getInternalState(dispatch)?.runningMutations\n\n  const {\n    unsubscribeQueryResult,\n    removeMutationResult,\n    updateSubscriptionOptions,\n  } = api.internalActions\n  return {\n    buildInitiateQuery,\n    buildInitiateInfiniteQuery,\n    buildInitiateMutation,\n    getRunningQueryThunk,\n    getRunningMutationThunk,\n    getRunningQueriesThunk,\n    getRunningMutationsThunk,\n  }\n\n  function getRunningQueryThunk(endpointName: string, queryArgs: any) {\n    return (dispatch: Dispatch) => {\n      const endpointDefinition = getEndpointDefinition(context, endpointName)\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName,\n      })\n      return getRunningQueries(dispatch)?.get(queryCacheKey) as\n        | QueryActionCreatorResult<never>\n        | InfiniteQueryActionCreatorResult<never>\n        | undefined\n    }\n  }\n\n  function getRunningMutationThunk(\n    /**\n     * this is only here to allow TS to infer the result type by input value\n     * we could use it to validate the result, but it's probably not necessary\n     */\n    _endpointName: string,\n    fixedCacheKeyOrRequestId: string,\n  ) {\n    return (dispatch: Dispatch) => {\n      return getRunningMutations(dispatch)?.get(fixedCacheKeyOrRequestId) as\n        | MutationActionCreatorResult<never>\n        | undefined\n    }\n  }\n\n  function getRunningQueriesThunk() {\n    return (dispatch: Dispatch) =>\n      filterNullishValues(getRunningQueries(dispatch))\n  }\n\n  function getRunningMutationsThunk() {\n    return (dispatch: Dispatch) =>\n      filterNullishValues(getRunningMutations(dispatch))\n  }\n\n  function middlewareWarning(dispatch: Dispatch) {\n    if (process.env.NODE_ENV !== 'production') {\n      if ((middlewareWarning as any).triggered) return\n      const returnedValue = dispatch(\n        api.internalActions.internal_getRTKQSubscriptions(),\n      )\n\n      ;(middlewareWarning as any).triggered = true\n\n      // The RTKQ middleware should return the internal state object,\n      // but it should _not_ be the action object.\n      if (\n        typeof returnedValue !== 'object' ||\n        typeof returnedValue?.type === 'string'\n      ) {\n        // Otherwise, must not have been added\n        throw new Error(\n          `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\nYou must add the middleware for RTK-Query to function correctly!`,\n        )\n      }\n    }\n  }\n\n  function buildInitiateAnyQuery<T extends 'query' | 'infiniteQuery'>(\n    endpointName: string,\n    endpointDefinition:\n      | QueryDefinition<any, any, any, any>\n      | InfiniteQueryDefinition<any, any, any, any, any>,\n  ) {\n    const queryAction: AnyQueryActionCreator<any> =\n      (\n        arg,\n        {\n          subscribe = true,\n          forceRefetch,\n          subscriptionOptions,\n          [forceQueryFnSymbol]: forceQueryFn,\n          ...rest\n        } = {},\n      ) =>\n      (dispatch, getState) => {\n        const queryCacheKey = serializeQueryArgs({\n          queryArgs: arg,\n          endpointDefinition,\n          endpointName,\n        })\n\n        let thunk: AsyncThunkAction<unknown, QueryThunkArg, ThunkApiMetaConfig>\n\n        const commonThunkArgs = {\n          ...rest,\n          type: ENDPOINT_QUERY as 'query',\n          subscribe,\n          forceRefetch: forceRefetch,\n          subscriptionOptions,\n          endpointName,\n          originalArgs: arg,\n          queryCacheKey,\n          [forceQueryFnSymbol]: forceQueryFn,\n        }\n\n        if (isQueryDefinition(endpointDefinition)) {\n          thunk = queryThunk(commonThunkArgs)\n        } else {\n          const { direction, initialPageParam, refetchCachedPages } =\n            rest as Pick<\n              InfiniteQueryThunkArg<any>,\n              'direction' | 'initialPageParam' | 'refetchCachedPages'\n            >\n          thunk = infiniteQueryThunk({\n            ...(commonThunkArgs as InfiniteQueryThunkArg<any>),\n            // Supply these even if undefined. This helps with a field existence\n            // check over in `buildSlice.ts`\n            direction,\n            initialPageParam,\n            refetchCachedPages,\n          })\n        }\n\n        const selector = (\n          api.endpoints[endpointName] as ApiEndpointQuery<any, any>\n        ).select(arg)\n\n        const thunkResult = dispatch(thunk)\n        const stateAfter = selector(getState())\n\n        middlewareWarning(dispatch)\n\n        const { requestId, abort } = thunkResult\n\n        const skippedSynchronously = stateAfter.requestId !== requestId\n\n        const runningQuery = getRunningQueries(dispatch)?.get(queryCacheKey)\n        const selectFromState = () => selector(getState())\n\n        const statePromise: AnyActionCreatorResult = Object.assign(\n          (forceQueryFn\n            ? // a query has been forced (upsertQueryData)\n              // -> we want to resolve it once data has been written with the data that will be written\n              thunkResult.then(selectFromState)\n            : skippedSynchronously && !runningQuery\n              ? // a query has been skipped due to a condition and we do not have any currently running query\n                // -> we want to resolve it immediately with the current data\n                Promise.resolve(stateAfter)\n              : // query just started or one is already in flight\n                // -> wait for the running query, then resolve with data from after that\n                Promise.all([runningQuery, thunkResult]).then(\n                  selectFromState,\n                )) as SafePromise<any>,\n          {\n            arg,\n            requestId,\n            subscriptionOptions,\n            queryCacheKey,\n            abort,\n            async unwrap() {\n              const result = await statePromise\n\n              if (result.isError) {\n                throw result.error\n              }\n\n              return result.data\n            },\n            refetch: (options?: RefetchOptions) =>\n              dispatch(\n                queryAction(arg, {\n                  subscribe: false,\n                  forceRefetch: true,\n                  ...options,\n                }),\n              ),\n            unsubscribe() {\n              if (subscribe)\n                dispatch(\n                  unsubscribeQueryResult({\n                    queryCacheKey,\n                    requestId,\n                  }),\n                )\n            },\n            updateSubscriptionOptions(options: SubscriptionOptions) {\n              statePromise.subscriptionOptions = options\n              dispatch(\n                updateSubscriptionOptions({\n                  endpointName,\n                  requestId,\n                  queryCacheKey,\n                  options,\n                }),\n              )\n            },\n          },\n        )\n\n        if (!runningQuery && !skippedSynchronously && !forceQueryFn) {\n          const runningQueries = getRunningQueries(dispatch)!\n          runningQueries.set(queryCacheKey, statePromise)\n\n          statePromise.then(() => {\n            runningQueries.delete(queryCacheKey)\n          })\n        }\n\n        return statePromise\n      }\n    return queryAction\n  }\n\n  function buildInitiateQuery(\n    endpointName: string,\n    endpointDefinition: QueryDefinition<any, any, any, any>,\n  ) {\n    const queryAction: StartQueryActionCreator<any> = buildInitiateAnyQuery(\n      endpointName,\n      endpointDefinition,\n    )\n\n    return queryAction\n  }\n\n  function buildInitiateInfiniteQuery(\n    endpointName: string,\n    endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>,\n  ) {\n    const infiniteQueryAction: StartInfiniteQueryActionCreator<any> =\n      buildInitiateAnyQuery(endpointName, endpointDefinition)\n\n    return infiniteQueryAction\n  }\n\n  function buildInitiateMutation(\n    endpointName: string,\n  ): StartMutationActionCreator<any> {\n    return (arg, { track = true, fixedCacheKey } = {}) =>\n      (dispatch, getState) => {\n        const thunk = mutationThunk({\n          type: 'mutation',\n          endpointName,\n          originalArgs: arg,\n          track,\n          fixedCacheKey,\n        })\n        const thunkResult = dispatch(thunk)\n        middlewareWarning(dispatch)\n        const { requestId, abort, unwrap } = thunkResult\n        const returnValuePromise = asSafePromise(\n          thunkResult.unwrap().then((data) => ({ data })),\n          (error) => ({ error }),\n        )\n\n        const reset = () => {\n          dispatch(removeMutationResult({ requestId, fixedCacheKey }))\n        }\n\n        const ret = Object.assign(returnValuePromise, {\n          arg: thunkResult.arg,\n          requestId,\n          abort,\n          unwrap,\n          reset,\n        })\n\n        const runningMutations = getRunningMutations(dispatch)!\n\n        runningMutations.set(requestId, ret)\n        ret.then(() => {\n          runningMutations.delete(requestId)\n        })\n        if (fixedCacheKey) {\n          runningMutations.set(fixedCacheKey, ret)\n          ret.then(() => {\n            if (runningMutations.get(fixedCacheKey) === ret) {\n              runningMutations.delete(fixedCacheKey)\n            }\n          })\n        }\n\n        return ret\n      }\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildMiddleware/batchActions.ts",
    "content": "import type { InternalHandlerBuilder, SubscriptionSelectors } from './types'\nimport type { SubscriptionInternalState, SubscriptionState } from '../apiState'\nimport { produceWithPatches } from '../../utils/immerImports'\nimport type { Action } from '@reduxjs/toolkit'\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert'\n\nexport const buildBatchedActionsHandler: InternalHandlerBuilder<\n  [actionShouldContinue: boolean, returnValue: SubscriptionSelectors | boolean]\n> = ({ api, queryThunk, internalState, mwApi }) => {\n  const subscriptionsPrefix = `${api.reducerPath}/subscriptions`\n\n  let previousSubscriptions: SubscriptionState =\n    null as unknown as SubscriptionState\n\n  let updateSyncTimer: ReturnType<typeof window.setTimeout> | null = null\n\n  const { updateSubscriptionOptions, unsubscribeQueryResult } =\n    api.internalActions\n\n  // Actually intentionally mutate the subscriptions state used in the middleware\n  // This is done to speed up perf when loading many components\n  const actuallyMutateSubscriptions = (\n    currentSubscriptions: SubscriptionInternalState,\n    action: Action,\n  ) => {\n    if (updateSubscriptionOptions.match(action)) {\n      const { queryCacheKey, requestId, options } = action.payload\n\n      const sub = currentSubscriptions.get(queryCacheKey)\n      if (sub?.has(requestId)) {\n        sub.set(requestId, options)\n      }\n      return true\n    }\n    if (unsubscribeQueryResult.match(action)) {\n      const { queryCacheKey, requestId } = action.payload\n      const sub = currentSubscriptions.get(queryCacheKey)\n      if (sub) {\n        sub.delete(requestId)\n      }\n      return true\n    }\n    if (api.internalActions.removeQueryResult.match(action)) {\n      currentSubscriptions.delete(action.payload.queryCacheKey)\n      return true\n    }\n    if (queryThunk.pending.match(action)) {\n      const {\n        meta: { arg, requestId },\n      } = action\n      const substate = getOrInsertComputed(\n        currentSubscriptions,\n        arg.queryCacheKey,\n        createNewMap,\n      )\n      if (arg.subscribe) {\n        substate.set(\n          requestId,\n          arg.subscriptionOptions ?? substate.get(requestId) ?? {},\n        )\n      }\n      return true\n    }\n    let mutated = false\n\n    if (queryThunk.rejected.match(action)) {\n      const {\n        meta: { condition, arg, requestId },\n      } = action\n      if (condition && arg.subscribe) {\n        const substate = getOrInsertComputed(\n          currentSubscriptions,\n          arg.queryCacheKey,\n          createNewMap,\n        )\n        substate.set(\n          requestId,\n          arg.subscriptionOptions ?? substate.get(requestId) ?? {},\n        )\n\n        mutated = true\n      }\n    }\n\n    return mutated\n  }\n\n  const getSubscriptions = () => internalState.currentSubscriptions\n  const getSubscriptionCount = (queryCacheKey: string) => {\n    const subscriptions = getSubscriptions()\n    const subscriptionsForQueryArg = subscriptions.get(queryCacheKey)\n    return subscriptionsForQueryArg?.size ?? 0\n  }\n  const isRequestSubscribed = (queryCacheKey: string, requestId: string) => {\n    const subscriptions = getSubscriptions()\n    return !!subscriptions?.get(queryCacheKey)?.get(requestId)\n  }\n\n  const subscriptionSelectors: SubscriptionSelectors = {\n    getSubscriptions,\n    getSubscriptionCount,\n    isRequestSubscribed,\n  }\n\n  function serializeSubscriptions(\n    currentSubscriptions: SubscriptionInternalState,\n  ): SubscriptionState {\n    // We now use nested Maps for subscriptions, instead of\n    // plain Records. Stringify this accordingly so we can\n    // convert it to the shape we need for the store.\n    return JSON.parse(\n      JSON.stringify(\n        Object.fromEntries(\n          [...currentSubscriptions].map(([k, v]) => [k, Object.fromEntries(v)]),\n        ),\n      ),\n    )\n  }\n\n  return (\n    action,\n    mwApi,\n  ): [\n    actionShouldContinue: boolean,\n    result: SubscriptionSelectors | boolean,\n  ] => {\n    if (!previousSubscriptions) {\n      // Initialize it the first time this handler runs\n      previousSubscriptions = serializeSubscriptions(\n        internalState.currentSubscriptions,\n      )\n    }\n\n    if (api.util.resetApiState.match(action)) {\n      previousSubscriptions = {}\n      internalState.currentSubscriptions.clear()\n      updateSyncTimer = null\n      return [true, false]\n    }\n\n    // Intercept requests by hooks to see if they're subscribed\n    // We return the internal state reference so that hooks\n    // can do their own checks to see if they're still active.\n    // It's stupid and hacky, but it does cut down on some dispatch calls.\n    if (api.internalActions.internal_getRTKQSubscriptions.match(action)) {\n      return [false, subscriptionSelectors]\n    }\n\n    // Update subscription data based on this action\n    const didMutate = actuallyMutateSubscriptions(\n      internalState.currentSubscriptions,\n      action,\n    )\n\n    let actionShouldContinue = true\n\n    // HACK Sneak the test-only polling state back out\n    if (\n      process.env.NODE_ENV === 'test' &&\n      typeof action.type === 'string' &&\n      action.type === `${api.reducerPath}/getPolling`\n    ) {\n      return [false, internalState.currentPolls] as any\n    }\n\n    if (didMutate) {\n      if (!updateSyncTimer) {\n        // We only use the subscription state for the Redux DevTools at this point,\n        // as the real data is kept here in the middleware.\n        // Given that, we can throttle synchronizing this state significantly to\n        // save on overall perf.\n        // In 1.9, it was updated in a microtask, but now we do it at most every 500ms.\n        updateSyncTimer = setTimeout(() => {\n          // Deep clone the current subscription data\n          const newSubscriptions: SubscriptionState = serializeSubscriptions(\n            internalState.currentSubscriptions,\n          )\n          // Figure out a smaller diff between original and current\n          const [, patches] = produceWithPatches(\n            previousSubscriptions,\n            () => newSubscriptions,\n          )\n\n          // Sync the store state for visibility\n          mwApi.next(api.internalActions.subscriptionsUpdated(patches))\n          // Save the cloned state for later reference\n          previousSubscriptions = newSubscriptions\n          updateSyncTimer = null\n        }, 500)\n      }\n\n      const isSubscriptionSliceAction =\n        typeof action.type == 'string' &&\n        !!action.type.startsWith(subscriptionsPrefix)\n\n      const isAdditionalSubscriptionAction =\n        queryThunk.rejected.match(action) &&\n        action.meta.condition &&\n        !!action.meta.arg.subscribe\n\n      actionShouldContinue =\n        !isSubscriptionSliceAction && !isAdditionalSubscriptionAction\n    }\n\n    return [actionShouldContinue, false]\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildMiddleware/cacheCollection.ts",
    "content": "import { getEndpointDefinition } from '@internal/query/apiTypes'\nimport type { QueryDefinition } from '../../endpointDefinitions'\nimport type { ConfigState, QueryCacheKey, QuerySubState } from '../apiState'\nimport { isAnyOf } from '../rtkImports'\nimport type {\n  ApiMiddlewareInternalHandler,\n  InternalHandlerBuilder,\n  QueryStateMeta,\n  SubMiddlewareApi,\n  TimeoutId,\n} from './types'\n\nexport type ReferenceCacheCollection = never\n\n/**\n * @example\n * ```ts\n * // codeblock-meta title=\"keepUnusedDataFor example\"\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => 'posts',\n *       // highlight-start\n *       keepUnusedDataFor: 5\n *       // highlight-end\n *     })\n *   })\n * })\n * ```\n */\nexport type CacheCollectionQueryExtraOptions = {\n  /**\n   * Overrides the api-wide definition of `keepUnusedDataFor` for this endpoint only. _(This value is in seconds.)_\n   *\n   * This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   */\n  keepUnusedDataFor?: number\n}\n\n// Per https://developer.mozilla.org/en-US/docs/Web/API/setTimeout#maximum_delay_value , browsers store\n// `setTimeout()` timer values in a 32-bit int. If we pass a value in that's larger than that,\n// it wraps and ends up executing immediately.\n// Our `keepUnusedDataFor` values are in seconds, so adjust the numbers here accordingly.\nexport const THIRTY_TWO_BIT_MAX_INT = 2_147_483_647\nexport const THIRTY_TWO_BIT_MAX_TIMER_SECONDS = 2_147_483_647 / 1_000 - 1\n\nexport const buildCacheCollectionHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  api,\n  queryThunk,\n  context,\n  internalState,\n  selectors: { selectQueryEntry, selectConfig },\n  getRunningQueryThunk,\n  mwApi,\n}) => {\n  const { removeQueryResult, unsubscribeQueryResult, cacheEntriesUpserted } =\n    api.internalActions\n\n  const canTriggerUnsubscribe = isAnyOf(\n    unsubscribeQueryResult.match,\n    queryThunk.fulfilled,\n    queryThunk.rejected,\n    cacheEntriesUpserted.match,\n  )\n\n  function anySubscriptionsRemainingForKey(queryCacheKey: string) {\n    const subscriptions = internalState.currentSubscriptions.get(queryCacheKey)\n    if (!subscriptions) {\n      return false\n    }\n\n    const hasSubscriptions = subscriptions.size > 0\n    return hasSubscriptions\n  }\n\n  const currentRemovalTimeouts: QueryStateMeta<TimeoutId> = {}\n\n  function abortAllPromises<T extends { abort?: () => void }>(\n    promiseMap: Map<string, T | undefined>,\n  ): void {\n    for (const promise of promiseMap.values()) {\n      promise?.abort?.()\n    }\n  }\n\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    const state = mwApi.getState()\n    const config = selectConfig(state)\n\n    if (canTriggerUnsubscribe(action)) {\n      let queryCacheKeys: QueryCacheKey[]\n\n      if (cacheEntriesUpserted.match(action)) {\n        queryCacheKeys = action.payload.map(\n          (entry) => entry.queryDescription.queryCacheKey,\n        )\n      } else {\n        const { queryCacheKey } = unsubscribeQueryResult.match(action)\n          ? action.payload\n          : action.meta.arg\n        queryCacheKeys = [queryCacheKey]\n      }\n\n      handleUnsubscribeMany(queryCacheKeys, mwApi, config)\n    }\n\n    if (api.util.resetApiState.match(action)) {\n      for (const [key, timeout] of Object.entries(currentRemovalTimeouts)) {\n        if (timeout) clearTimeout(timeout)\n        delete currentRemovalTimeouts[key]\n      }\n\n      abortAllPromises(internalState.runningQueries)\n      abortAllPromises(internalState.runningMutations)\n    }\n\n    if (context.hasRehydrationInfo(action)) {\n      const { queries } = context.extractRehydrationInfo(action)!\n      // Gotcha:\n      // If rehydrating before the endpoint has been injected,the global `keepUnusedDataFor`\n      // will be used instead of the endpoint-specific one.\n      handleUnsubscribeMany(\n        Object.keys(queries) as QueryCacheKey[],\n        mwApi,\n        config,\n      )\n    }\n  }\n\n  function handleUnsubscribeMany(\n    cacheKeys: QueryCacheKey[],\n    api: SubMiddlewareApi,\n    config: ConfigState<string>,\n  ) {\n    const state = api.getState()\n    for (const queryCacheKey of cacheKeys) {\n      const entry = selectQueryEntry(state, queryCacheKey)\n      if (entry?.endpointName) {\n        handleUnsubscribe(queryCacheKey, entry.endpointName, api, config)\n      }\n    }\n  }\n\n  function handleUnsubscribe(\n    queryCacheKey: QueryCacheKey,\n    endpointName: string,\n    api: SubMiddlewareApi,\n    config: ConfigState<string>,\n  ) {\n    const endpointDefinition = getEndpointDefinition(\n      context,\n      endpointName,\n    ) as QueryDefinition<any, any, any, any>\n    const keepUnusedDataFor =\n      endpointDefinition?.keepUnusedDataFor ?? config.keepUnusedDataFor\n\n    if (keepUnusedDataFor === Infinity) {\n      // Hey, user said keep this forever!\n      return\n    }\n    // Prevent `setTimeout` timers from overflowing a 32-bit internal int, by\n    // clamping the max value to be at most 1000ms less than the 32-bit max.\n    // Look, a 24.8-day keepalive ought to be enough for anybody, right? :)\n    // Also avoid negative values too.\n    const finalKeepUnusedDataFor = Math.max(\n      0,\n      Math.min(keepUnusedDataFor, THIRTY_TWO_BIT_MAX_TIMER_SECONDS),\n    )\n\n    if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n      const currentTimeout = currentRemovalTimeouts[queryCacheKey]\n      if (currentTimeout) {\n        clearTimeout(currentTimeout)\n      }\n\n      currentRemovalTimeouts[queryCacheKey] = setTimeout(() => {\n        if (!anySubscriptionsRemainingForKey(queryCacheKey)) {\n          // Try to abort any running query for this cache key\n          const entry = selectQueryEntry(api.getState(), queryCacheKey)\n\n          if (entry?.endpointName) {\n            const runningQuery = api.dispatch(\n              getRunningQueryThunk(entry.endpointName, entry.originalArgs),\n            )\n            runningQuery?.abort()\n          }\n          api.dispatch(removeQueryResult({ queryCacheKey }))\n        }\n        delete currentRemovalTimeouts![queryCacheKey]\n      }, finalKeepUnusedDataFor * 1000)\n    }\n  }\n\n  return handler\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildMiddleware/cacheLifecycle.ts",
    "content": "import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'\nimport type {\n  BaseQueryFn,\n  BaseQueryMeta,\n  BaseQueryResult,\n} from '../../baseQueryTypes'\nimport type {\n  BaseEndpointDefinition,\n  DefinitionType,\n} from '../../endpointDefinitions'\nimport { isAnyQueryDefinition } from '../../endpointDefinitions'\nimport type { QueryCacheKey, RootState } from '../apiState'\nimport type {\n  MutationResultSelectorResult,\n  QueryResultSelectorResult,\n} from '../buildSelectors'\nimport { getMutationCacheKey } from '../buildSlice'\nimport type { PatchCollection, Recipe } from '../buildThunks'\nimport { isAsyncThunkAction, isFulfilled } from '../rtkImports'\nimport type {\n  ApiMiddlewareInternalHandler,\n  InternalHandlerBuilder,\n  PromiseWithKnownReason,\n  SubMiddlewareApi,\n} from './types'\nimport { getEndpointDefinition } from '@internal/query/apiTypes'\n\nexport type ReferenceCacheLifecycle = never\n\nexport interface QueryBaseLifecycleApi<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ResultType,\n  ReducerPath extends string = string,\n> extends LifecycleApi<ReducerPath> {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): QueryResultSelectorResult<\n    { type: DefinitionType.query } & BaseEndpointDefinition<\n      QueryArg,\n      BaseQuery,\n      ResultType,\n      BaseQueryResult<BaseQuery>\n    >\n  >\n  /**\n   * Updates the current cache entry value.\n   * For documentation see `api.util.updateQueryData`.\n   */\n  updateCachedData(updateRecipe: Recipe<ResultType>): PatchCollection\n}\n\nexport type MutationBaseLifecycleApi<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ResultType,\n  ReducerPath extends string = string,\n> = LifecycleApi<ReducerPath> & {\n  /**\n   * Gets the current value of this cache entry.\n   */\n  getCacheEntry(): MutationResultSelectorResult<\n    { type: DefinitionType.mutation } & BaseEndpointDefinition<\n      QueryArg,\n      BaseQuery,\n      ResultType,\n      BaseQueryResult<BaseQuery>\n    >\n  >\n}\n\ntype LifecycleApi<ReducerPath extends string = string> = {\n  /**\n   * The dispatch method for the store\n   */\n  dispatch: ThunkDispatch<any, any, UnknownAction>\n  /**\n   * A method to get the current state\n   */\n  getState(): RootState<any, any, ReducerPath>\n  /**\n   * `extra` as provided as `thunk.extraArgument` to the `configureStore` `getDefaultMiddleware` option.\n   */\n  extra: unknown\n  /**\n   * A unique ID generated for the mutation\n   */\n  requestId: string\n}\n\ntype CacheLifecyclePromises<ResultType = unknown, MetaType = unknown> = {\n  /**\n   * Promise that will resolve with the first value for this cache key.\n   * This allows you to `await` until an actual value is in cache.\n   *\n   * If the cache entry is removed from the cache before any value has ever\n   * been resolved, this Promise will reject with\n   * `new Error('Promise never resolved before cacheEntryRemoved.')`\n   * to prevent memory leaks.\n   * You can just re-throw that error (or not handle it at all) -\n   * it will be caught outside of `cacheEntryAdded`.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  cacheDataLoaded: PromiseWithKnownReason<\n    {\n      /**\n       * The (transformed) query result.\n       */\n      data: ResultType\n      /**\n       * The `meta` returned by the `baseQuery`\n       */\n      meta: MetaType\n    },\n    typeof neverResolvedError\n  >\n  /**\n   * Promise that allows you to wait for the point in time when the cache entry\n   * has been removed from the cache, by not being used/subscribed to any more\n   * in the application for too long or by dispatching `api.util.resetApiState`.\n   */\n  cacheEntryRemoved: Promise<void>\n}\n\nexport interface QueryCacheLifecycleApi<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ResultType,\n  ReducerPath extends string = string,\n> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,\n    CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>> {}\n\nexport type MutationCacheLifecycleApi<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ResultType,\n  ReducerPath extends string = string,\n> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> &\n  CacheLifecyclePromises<ResultType, BaseQueryMeta<BaseQuery>>\n\nexport type CacheLifecycleQueryExtraOptions<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ReducerPath extends string = string,\n> = {\n  onCacheEntryAdded?(\n    arg: QueryArg,\n    api: QueryCacheLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,\n  ): Promise<void> | void\n}\n\nexport type CacheLifecycleInfiniteQueryExtraOptions<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ReducerPath extends string = string,\n> = CacheLifecycleQueryExtraOptions<\n  ResultType,\n  QueryArg,\n  BaseQuery,\n  ReducerPath\n>\n\nexport type CacheLifecycleMutationExtraOptions<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ReducerPath extends string = string,\n> = {\n  onCacheEntryAdded?(\n    arg: QueryArg,\n    api: MutationCacheLifecycleApi<\n      QueryArg,\n      BaseQuery,\n      ResultType,\n      ReducerPath\n    >,\n  ): Promise<void> | void\n}\n\nconst neverResolvedError = new Error(\n  'Promise never resolved before cacheEntryRemoved.',\n) as Error & {\n  message: 'Promise never resolved before cacheEntryRemoved.'\n}\n\nexport const buildCacheLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  reducerPath,\n  context,\n  queryThunk,\n  mutationThunk,\n  internalState,\n  selectors: { selectQueryEntry, selectApiState },\n}) => {\n  const isQueryThunk = isAsyncThunkAction(queryThunk)\n  const isMutationThunk = isAsyncThunkAction(mutationThunk)\n  const isFulfilledThunk = isFulfilled(queryThunk, mutationThunk)\n\n  type CacheLifecycle = {\n    valueResolved?(value: { data: unknown; meta: unknown }): unknown\n    cacheEntryRemoved(): void\n  }\n  const lifecycleMap: Record<string, CacheLifecycle> = {}\n\n  const { removeQueryResult, removeMutationResult, cacheEntriesUpserted } =\n    api.internalActions\n\n  function resolveLifecycleEntry(\n    cacheKey: string,\n    data: unknown,\n    meta: unknown,\n  ) {\n    const lifecycle = lifecycleMap[cacheKey]\n\n    if (lifecycle?.valueResolved) {\n      lifecycle.valueResolved({\n        data,\n        meta,\n      })\n      delete lifecycle.valueResolved\n    }\n  }\n\n  function removeLifecycleEntry(cacheKey: string) {\n    const lifecycle = lifecycleMap[cacheKey]\n    if (lifecycle) {\n      delete lifecycleMap[cacheKey]\n      lifecycle.cacheEntryRemoved()\n    }\n  }\n\n  function getActionMetaFields(\n    action:\n      | ReturnType<typeof queryThunk.pending>\n      | ReturnType<typeof mutationThunk.pending>,\n  ) {\n    const { arg, requestId } = action.meta\n    const { endpointName, originalArgs } = arg\n    return [endpointName, originalArgs, requestId] as const\n  }\n\n  const handler: ApiMiddlewareInternalHandler = (\n    action,\n    mwApi,\n    stateBefore,\n  ) => {\n    const cacheKey = getCacheKey(action) as QueryCacheKey\n\n    function checkForNewCacheKey(\n      endpointName: string,\n      cacheKey: QueryCacheKey,\n      requestId: string,\n      originalArgs: unknown,\n    ) {\n      const oldEntry = selectQueryEntry(stateBefore, cacheKey)\n      const newEntry = selectQueryEntry(mwApi.getState(), cacheKey)\n      if (!oldEntry && newEntry) {\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId)\n      }\n    }\n\n    if (queryThunk.pending.match(action)) {\n      const [endpointName, originalArgs, requestId] =\n        getActionMetaFields(action)\n      checkForNewCacheKey(endpointName, cacheKey, requestId, originalArgs)\n    } else if (cacheEntriesUpserted.match(action)) {\n      for (const { queryDescription, value } of action.payload) {\n        const { endpointName, originalArgs, queryCacheKey } = queryDescription\n        checkForNewCacheKey(\n          endpointName,\n          queryCacheKey,\n          action.meta.requestId,\n          originalArgs,\n        )\n\n        resolveLifecycleEntry(queryCacheKey, value, {})\n      }\n    } else if (mutationThunk.pending.match(action)) {\n      const state = mwApi.getState()[reducerPath].mutations[cacheKey]\n      if (state) {\n        const [endpointName, originalArgs, requestId] =\n          getActionMetaFields(action)\n        handleNewKey(endpointName, originalArgs, cacheKey, mwApi, requestId)\n      }\n    } else if (isFulfilledThunk(action)) {\n      resolveLifecycleEntry(cacheKey, action.payload, action.meta.baseQueryMeta)\n    } else if (\n      removeQueryResult.match(action) ||\n      removeMutationResult.match(action)\n    ) {\n      removeLifecycleEntry(cacheKey)\n    } else if (api.util.resetApiState.match(action)) {\n      for (const cacheKey of Object.keys(lifecycleMap)) {\n        removeLifecycleEntry(cacheKey)\n      }\n    }\n  }\n\n  function getCacheKey(action: any) {\n    if (isQueryThunk(action)) return action.meta.arg.queryCacheKey\n    if (isMutationThunk(action)) {\n      return action.meta.arg.fixedCacheKey ?? action.meta.requestId\n    }\n    if (removeQueryResult.match(action)) return action.payload.queryCacheKey\n    if (removeMutationResult.match(action))\n      return getMutationCacheKey(action.payload)\n    return ''\n  }\n\n  function handleNewKey(\n    endpointName: string,\n    originalArgs: any,\n    queryCacheKey: string,\n    mwApi: SubMiddlewareApi,\n    requestId: string,\n  ) {\n    const endpointDefinition = getEndpointDefinition(context, endpointName)\n    const onCacheEntryAdded = endpointDefinition?.onCacheEntryAdded\n    if (!onCacheEntryAdded) return\n\n    const lifecycle = {} as CacheLifecycle\n\n    const cacheEntryRemoved = new Promise<void>((resolve) => {\n      lifecycle.cacheEntryRemoved = resolve\n    })\n    const cacheDataLoaded: PromiseWithKnownReason<\n      { data: unknown; meta: unknown },\n      typeof neverResolvedError\n    > = Promise.race([\n      new Promise<{ data: unknown; meta: unknown }>((resolve) => {\n        lifecycle.valueResolved = resolve\n      }),\n      cacheEntryRemoved.then(() => {\n        throw neverResolvedError\n      }),\n    ])\n    // prevent uncaught promise rejections from happening.\n    // if the original promise is used in any way, that will create a new promise that will throw again\n    cacheDataLoaded.catch(() => {})\n    lifecycleMap[queryCacheKey] = lifecycle\n    const selector = (api.endpoints[endpointName] as any).select(\n      isAnyQueryDefinition(endpointDefinition) ? originalArgs : queryCacheKey,\n    )\n\n    const extra = mwApi.dispatch((_, __, extra) => extra)\n    const lifecycleApi = {\n      ...mwApi,\n      getCacheEntry: () => selector(mwApi.getState()),\n      requestId,\n      extra,\n      updateCachedData: (isAnyQueryDefinition(endpointDefinition)\n        ? (updateRecipe: Recipe<any>) =>\n            mwApi.dispatch(\n              api.util.updateQueryData(\n                endpointName as never,\n                originalArgs as never,\n                updateRecipe,\n              ),\n            )\n        : undefined) as any,\n\n      cacheDataLoaded,\n      cacheEntryRemoved,\n    }\n\n    const runningHandler = onCacheEntryAdded(originalArgs, lifecycleApi as any)\n    // if a `neverResolvedError` was thrown, but not handled in the running handler, do not let it leak out further\n    Promise.resolve(runningHandler).catch((e) => {\n      if (e === neverResolvedError) return\n      throw e\n    })\n  }\n\n  return handler\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildMiddleware/devMiddleware.ts",
    "content": "import type { InternalHandlerBuilder } from './types'\n\nexport const buildDevCheckHandler: InternalHandlerBuilder = ({\n  api,\n  context: { apiUid },\n  reducerPath,\n}) => {\n  return (action, mwApi) => {\n    if (api.util.resetApiState.match(action)) {\n      // dispatch after api reset\n      mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))\n    }\n\n    if (\n      typeof process !== 'undefined' &&\n      process.env.NODE_ENV === 'development'\n    ) {\n      if (\n        api.internalActions.middlewareRegistered.match(action) &&\n        action.payload === apiUid &&\n        mwApi.getState()[reducerPath]?.config?.middlewareRegistered ===\n          'conflict'\n      ) {\n        console.warn(`There is a mismatch between slice and middleware for the reducerPath \"${reducerPath}\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!${\n          reducerPath === 'api'\n            ? `\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!`\n            : ''\n        }`)\n      }\n    }\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildMiddleware/index.ts",
    "content": "import type {\n  Action,\n  Middleware,\n  ThunkDispatch,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport type {\n  EndpointDefinitions,\n  FullTagDescription,\n} from '../../endpointDefinitions'\nimport type { QueryStatus, QuerySubState, RootState } from '../apiState'\nimport type { QueryThunkArg } from '../buildThunks'\nimport { createAction, isAction } from '../rtkImports'\nimport { buildBatchedActionsHandler } from './batchActions'\nimport { buildCacheCollectionHandler } from './cacheCollection'\nimport { buildCacheLifecycleHandler } from './cacheLifecycle'\nimport { buildDevCheckHandler } from './devMiddleware'\nimport { buildInvalidationByTagsHandler } from './invalidationByTags'\nimport { buildPollingHandler } from './polling'\nimport { buildQueryLifecycleHandler } from './queryLifecycle'\nimport type {\n  BuildMiddlewareInput,\n  InternalHandlerBuilder,\n  InternalMiddlewareState,\n} from './types'\nimport { buildWindowEventHandler } from './windowEventHandling'\nimport type { ApiEndpointQuery } from '../module'\nexport type { ReferenceCacheCollection } from './cacheCollection'\nexport type {\n  MutationCacheLifecycleApi,\n  QueryCacheLifecycleApi,\n  ReferenceCacheLifecycle,\n} from './cacheLifecycle'\nexport type {\n  MutationLifecycleApi,\n  QueryLifecycleApi,\n  ReferenceQueryLifecycle,\n  TypedMutationOnQueryStarted,\n  TypedQueryOnQueryStarted,\n} from './queryLifecycle'\nexport type { SubscriptionSelectors } from './types'\n\nexport function buildMiddleware<\n  Definitions extends EndpointDefinitions,\n  ReducerPath extends string,\n  TagTypes extends string,\n>(input: BuildMiddlewareInput<Definitions, ReducerPath, TagTypes>) {\n  const { reducerPath, queryThunk, api, context, getInternalState } = input\n  const { apiUid } = context\n\n  const actions = {\n    invalidateTags: createAction<\n      Array<TagTypes | FullTagDescription<TagTypes> | null | undefined>\n    >(`${reducerPath}/invalidateTags`),\n  }\n\n  const isThisApiSliceAction = (action: Action) =>\n    action.type.startsWith(`${reducerPath}/`)\n\n  const handlerBuilders: InternalHandlerBuilder[] = [\n    buildDevCheckHandler,\n    buildCacheCollectionHandler,\n    buildInvalidationByTagsHandler,\n    buildPollingHandler,\n    buildCacheLifecycleHandler,\n    buildQueryLifecycleHandler,\n  ]\n\n  const middleware: Middleware<\n    {},\n    RootState<Definitions, string, ReducerPath>,\n    ThunkDispatch<any, any, UnknownAction>\n  > = (mwApi) => {\n    let initialized = false\n\n    const internalState = getInternalState(mwApi.dispatch)\n\n    const builderArgs = {\n      ...(input as any as BuildMiddlewareInput<\n        EndpointDefinitions,\n        string,\n        string\n      >),\n      internalState,\n      refetchQuery,\n      isThisApiSliceAction,\n      mwApi,\n    }\n\n    const handlers = handlerBuilders.map((build) => build(builderArgs))\n\n    const batchedActionsHandler = buildBatchedActionsHandler(builderArgs)\n    const windowEventsHandler = buildWindowEventHandler(builderArgs)\n\n    return (next) => {\n      return (action) => {\n        if (!isAction(action)) {\n          return next(action)\n        }\n        if (!initialized) {\n          initialized = true\n          // dispatch before any other action\n          mwApi.dispatch(api.internalActions.middlewareRegistered(apiUid))\n        }\n\n        const mwApiWithNext = { ...mwApi, next }\n\n        const stateBefore = mwApi.getState()\n\n        const [actionShouldContinue, internalProbeResult] =\n          batchedActionsHandler(action, mwApiWithNext, stateBefore)\n\n        let res: any\n\n        if (actionShouldContinue) {\n          res = next(action)\n        } else {\n          res = internalProbeResult\n        }\n\n        if (!!mwApi.getState()[reducerPath]) {\n          // Only run these checks if the middleware is registered okay\n\n          // This looks for actions that aren't specific to the API slice\n          windowEventsHandler(action, mwApiWithNext, stateBefore)\n\n          if (\n            isThisApiSliceAction(action) ||\n            context.hasRehydrationInfo(action)\n          ) {\n            // Only run these additional checks if the actions are part of the API slice,\n            // or the action has hydration-related data\n            for (const handler of handlers) {\n              handler(action, mwApiWithNext, stateBefore)\n            }\n          }\n        }\n\n        return res\n      }\n    }\n  }\n\n  return { middleware, actions }\n\n  function refetchQuery(\n    querySubState: Exclude<\n      QuerySubState<any>,\n      { status: QueryStatus.uninitialized }\n    >,\n  ) {\n    return (\n      input.api.endpoints[querySubState.endpointName] as ApiEndpointQuery<\n        any,\n        any\n      >\n    ).initiate(querySubState.originalArgs as any, {\n      subscribe: false,\n      forceRefetch: true,\n    })\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildMiddleware/invalidationByTags.ts",
    "content": "import {\n  isAnyOf,\n  isFulfilled,\n  isRejected,\n  isRejectedWithValue,\n} from '../rtkImports'\n\nimport type {\n  EndpointDefinitions,\n  FullTagDescription,\n} from '../../endpointDefinitions'\nimport { calculateProvidedBy } from '../../endpointDefinitions'\nimport type { CombinedState, QueryCacheKey } from '../apiState'\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'\nimport { calculateProvidedByThunk } from '../buildThunks'\nimport type {\n  SubMiddlewareApi,\n  InternalHandlerBuilder,\n  ApiMiddlewareInternalHandler,\n} from './types'\nimport { getOrInsertComputed, createNewMap } from '../../utils/getOrInsert'\n\nexport const buildInvalidationByTagsHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  context: { endpointDefinitions },\n  mutationThunk,\n  queryThunk,\n  api,\n  assertTagType,\n  refetchQuery,\n  internalState,\n}) => {\n  const { removeQueryResult } = api.internalActions\n  const isThunkActionWithTags = isAnyOf(\n    isFulfilled(mutationThunk),\n    isRejectedWithValue(mutationThunk),\n  )\n\n  const isQueryEnd = isAnyOf(\n    isFulfilled(queryThunk, mutationThunk),\n    isRejected(queryThunk, mutationThunk),\n  )\n  let pendingTagInvalidations: FullTagDescription<string>[] = []\n  // Track via counter so we can avoid iterating over state every time\n  let pendingRequestCount = 0\n\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (\n      queryThunk.pending.match(action) ||\n      mutationThunk.pending.match(action)\n    ) {\n      pendingRequestCount++\n    }\n\n    if (isQueryEnd(action)) {\n      pendingRequestCount = Math.max(0, pendingRequestCount - 1)\n    }\n\n    if (isThunkActionWithTags(action)) {\n      invalidateTags(\n        calculateProvidedByThunk(\n          action,\n          'invalidatesTags',\n          endpointDefinitions,\n          assertTagType,\n        ),\n        mwApi,\n      )\n    } else if (isQueryEnd(action)) {\n      invalidateTags([], mwApi)\n    } else if (api.util.invalidateTags.match(action)) {\n      invalidateTags(\n        calculateProvidedBy(\n          action.payload,\n          undefined,\n          undefined,\n          undefined,\n          undefined,\n          assertTagType,\n        ),\n        mwApi,\n      )\n    }\n  }\n\n  function hasPendingRequests() {\n    return pendingRequestCount > 0\n  }\n\n  function invalidateTags(\n    newTags: readonly FullTagDescription<string>[],\n    mwApi: SubMiddlewareApi,\n  ) {\n    const rootState = mwApi.getState()\n    const state = rootState[reducerPath]\n\n    pendingTagInvalidations.push(...newTags)\n\n    if (\n      state.config.invalidationBehavior === 'delayed' &&\n      hasPendingRequests()\n    ) {\n      return\n    }\n\n    const tags = pendingTagInvalidations\n    pendingTagInvalidations = []\n    if (tags.length === 0) return\n\n    const toInvalidate = api.util.selectInvalidatedBy(rootState, tags)\n\n    context.batch(() => {\n      const valuesArray = Array.from(toInvalidate.values())\n      for (const { queryCacheKey } of valuesArray) {\n        const querySubState = state.queries[queryCacheKey]\n        const subscriptionSubState = getOrInsertComputed(\n          internalState.currentSubscriptions,\n          queryCacheKey,\n          createNewMap,\n        )\n\n        if (querySubState) {\n          if (subscriptionSubState.size === 0) {\n            mwApi.dispatch(\n              removeQueryResult({\n                queryCacheKey: queryCacheKey as QueryCacheKey,\n              }),\n            )\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            mwApi.dispatch(refetchQuery(querySubState))\n          }\n        }\n      }\n    })\n  }\n\n  return handler\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildMiddleware/polling.ts",
    "content": "import type {\n  QueryCacheKey,\n  QuerySubstateIdentifier,\n  Subscribers,\n  SubscribersInternal,\n} from '../apiState'\nimport { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'\nimport type {\n  QueryStateMeta,\n  SubMiddlewareApi,\n  TimeoutId,\n  InternalHandlerBuilder,\n  ApiMiddlewareInternalHandler,\n  InternalMiddlewareState,\n} from './types'\n\nexport const buildPollingHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  queryThunk,\n  api,\n  refetchQuery,\n  internalState,\n}) => {\n  const { currentPolls, currentSubscriptions } = internalState\n\n  // Batching state for polling updates\n  const pendingPollingUpdates = new Set<string>()\n  let pollingUpdateTimer: ReturnType<typeof setTimeout> | null = null\n\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (\n      api.internalActions.updateSubscriptionOptions.match(action) ||\n      api.internalActions.unsubscribeQueryResult.match(action)\n    ) {\n      schedulePollingUpdate(action.payload.queryCacheKey, mwApi)\n    }\n\n    if (\n      queryThunk.pending.match(action) ||\n      (queryThunk.rejected.match(action) && action.meta.condition)\n    ) {\n      schedulePollingUpdate(action.meta.arg.queryCacheKey, mwApi)\n    }\n\n    if (\n      queryThunk.fulfilled.match(action) ||\n      (queryThunk.rejected.match(action) && !action.meta.condition)\n    ) {\n      startNextPoll(action.meta.arg, mwApi)\n    }\n\n    if (api.util.resetApiState.match(action)) {\n      clearPolls()\n      // Clear any pending updates\n      if (pollingUpdateTimer) {\n        clearTimeout(pollingUpdateTimer)\n        pollingUpdateTimer = null\n      }\n      pendingPollingUpdates.clear()\n    }\n  }\n\n  function schedulePollingUpdate(queryCacheKey: string, api: SubMiddlewareApi) {\n    pendingPollingUpdates.add(queryCacheKey)\n\n    if (!pollingUpdateTimer) {\n      pollingUpdateTimer = setTimeout(() => {\n        // Process all pending updates in a single batch\n        for (const key of pendingPollingUpdates) {\n          updatePollingInterval({ queryCacheKey: key as any }, api)\n        }\n        pendingPollingUpdates.clear()\n        pollingUpdateTimer = null\n      }, 0)\n    }\n  }\n\n  function startNextPoll(\n    { queryCacheKey }: QuerySubstateIdentifier,\n    api: SubMiddlewareApi,\n  ) {\n    const state = api.getState()[reducerPath]\n    const querySubState = state.queries[queryCacheKey]\n    const subscriptions = currentSubscriptions.get(queryCacheKey)\n\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) return\n\n    const { lowestPollingInterval, skipPollingIfUnfocused } =\n      findLowestPollingInterval(subscriptions)\n    if (!Number.isFinite(lowestPollingInterval)) return\n\n    const currentPoll = currentPolls.get(queryCacheKey)\n\n    if (currentPoll?.timeout) {\n      clearTimeout(currentPoll.timeout)\n      currentPoll.timeout = undefined\n    }\n\n    const nextPollTimestamp = Date.now() + lowestPollingInterval\n\n    currentPolls.set(queryCacheKey, {\n      nextPollTimestamp,\n      pollingInterval: lowestPollingInterval,\n      timeout: setTimeout(() => {\n        if (state.config.focused || !skipPollingIfUnfocused) {\n          api.dispatch(refetchQuery(querySubState))\n        }\n        startNextPoll({ queryCacheKey }, api)\n      }, lowestPollingInterval),\n    })\n  }\n\n  function updatePollingInterval(\n    { queryCacheKey }: QuerySubstateIdentifier,\n    api: SubMiddlewareApi,\n  ) {\n    const state = api.getState()[reducerPath]\n    const querySubState = state.queries[queryCacheKey]\n    const subscriptions = currentSubscriptions.get(queryCacheKey)\n\n    if (!querySubState || querySubState.status === STATUS_UNINITIALIZED) {\n      return\n    }\n\n    const { lowestPollingInterval } = findLowestPollingInterval(subscriptions)\n\n    // HACK add extra data to track how many times this has been called in tests\n    // yes we're mutating a nonexistent field on a Map here\n    if (process.env.NODE_ENV === 'test') {\n      const updateCounters = ((currentPolls as any).pollUpdateCounters ??= {})\n      updateCounters[queryCacheKey] ??= 0\n      updateCounters[queryCacheKey]++\n    }\n\n    if (!Number.isFinite(lowestPollingInterval)) {\n      cleanupPollForKey(queryCacheKey)\n      return\n    }\n\n    const currentPoll = currentPolls.get(queryCacheKey)\n\n    const nextPollTimestamp = Date.now() + lowestPollingInterval\n\n    if (!currentPoll || nextPollTimestamp < currentPoll.nextPollTimestamp) {\n      startNextPoll({ queryCacheKey }, api)\n    }\n  }\n\n  function cleanupPollForKey(key: string) {\n    const existingPoll = currentPolls.get(key)\n    if (existingPoll?.timeout) {\n      clearTimeout(existingPoll.timeout)\n    }\n    currentPolls.delete(key)\n  }\n\n  function clearPolls() {\n    for (const key of currentPolls.keys()) {\n      cleanupPollForKey(key)\n    }\n  }\n\n  function findLowestPollingInterval(\n    subscribers: SubscribersInternal = new Map(),\n  ) {\n    let skipPollingIfUnfocused: boolean | undefined = false\n    let lowestPollingInterval = Number.POSITIVE_INFINITY\n\n    for (const entry of subscribers.values()) {\n      if (!!entry.pollingInterval) {\n        lowestPollingInterval = Math.min(\n          entry.pollingInterval!,\n          lowestPollingInterval,\n        )\n        skipPollingIfUnfocused =\n          entry.skipPollingIfUnfocused || skipPollingIfUnfocused\n      }\n    }\n\n    return {\n      lowestPollingInterval,\n      skipPollingIfUnfocused,\n    }\n  }\n\n  return handler\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildMiddleware/queryLifecycle.ts",
    "content": "import { getEndpointDefinition } from '@internal/query/apiTypes'\nimport type {\n  BaseQueryError,\n  BaseQueryFn,\n  BaseQueryMeta,\n} from '../../baseQueryTypes'\nimport { isAnyQueryDefinition } from '../../endpointDefinitions'\nimport type { Recipe } from '../buildThunks'\nimport { isFulfilled, isPending, isRejected } from '../rtkImports'\nimport type {\n  MutationBaseLifecycleApi,\n  QueryBaseLifecycleApi,\n} from './cacheLifecycle'\nimport type {\n  ApiMiddlewareInternalHandler,\n  InternalHandlerBuilder,\n  PromiseConstructorWithKnownReason,\n  PromiseWithKnownReason,\n} from './types'\n\nexport type ReferenceQueryLifecycle = never\n\ntype QueryLifecyclePromises<ResultType, BaseQuery extends BaseQueryFn> = {\n  /**\n   * Promise that will resolve with the (transformed) query result.\n   *\n   * If the query fails, this promise will reject with the error.\n   *\n   * This allows you to `await` for the query to finish.\n   *\n   * If you don't interact with this promise, it will not throw.\n   */\n  queryFulfilled: PromiseWithKnownReason<\n    {\n      /**\n       * The (transformed) query result.\n       */\n      data: ResultType\n      /**\n       * The `meta` returned by the `baseQuery`\n       */\n      meta: BaseQueryMeta<BaseQuery>\n    },\n    QueryFulfilledRejectionReason<BaseQuery>\n  >\n}\n\ntype QueryFulfilledRejectionReason<BaseQuery extends BaseQueryFn> =\n  | {\n      error: BaseQueryError<BaseQuery>\n      /**\n       * If this is `false`, that means this error was returned from the `baseQuery` or `queryFn` in a controlled manner.\n       */\n      isUnhandledError: false\n      /**\n       * The `meta` returned by the `baseQuery`\n       */\n      meta: BaseQueryMeta<BaseQuery>\n    }\n  | {\n      error: unknown\n      meta?: undefined\n      /**\n       * If this is `true`, that means that this error is the result of `baseQueryFn`, `queryFn`, `transformResponse` or `transformErrorResponse` throwing an error instead of handling it properly.\n       * There can not be made any assumption about the shape of `error`.\n       */\n      isUnhandledError: true\n    }\n\nexport type QueryLifecycleQueryExtraOptions<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ReducerPath extends string = string,\n> = {\n  /**\n   * A function that is called when the individual query is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used to perform side-effects throughout the lifecycle of the query.\n   *\n   * @example\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';\n   * import { messageCreated } from './notificationsSlice';\n   *\n   * export interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       async onQueryStarted(id, { dispatch, queryFulfilled }) {\n   *         // `onStart` side-effect\n   *         dispatch(messageCreated('Fetching posts...'));\n   *         try {\n   *           const { data } = await queryFulfilled;\n   *           // `onSuccess` side-effect\n   *           dispatch(messageCreated('Posts received!'));\n   *         } catch (err) {\n   *           // `onError` side-effect\n   *           dispatch(messageCreated('Error fetching posts!'));\n   *         }\n   *       },\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  onQueryStarted?(\n    queryArgument: QueryArg,\n    queryLifeCycleApi: QueryLifecycleApi<\n      QueryArg,\n      BaseQuery,\n      ResultType,\n      ReducerPath\n    >,\n  ): Promise<void> | void\n}\n\nexport type QueryLifecycleInfiniteQueryExtraOptions<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ReducerPath extends string = string,\n> = QueryLifecycleQueryExtraOptions<\n  ResultType,\n  QueryArg,\n  BaseQuery,\n  ReducerPath\n>\n\nexport type QueryLifecycleMutationExtraOptions<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ReducerPath extends string = string,\n> = {\n  /**\n   * A function that is called when the individual mutation is started. The function is called with a lifecycle api object containing properties such as `queryFulfilled`, allowing code to be run when a query is started, when it succeeds, and when it fails (i.e. throughout the lifecycle of an individual query/mutation call).\n   *\n   * Can be used for `optimistic updates`.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   * export interface Post {\n   *   id: number\n   *   name: string\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({\n   *     baseUrl: '/',\n   *   }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, number>({\n   *       query: (id) => `post/${id}`,\n   *       providesTags: ['Post'],\n   *     }),\n   *     updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n   *       query: ({ id, ...patch }) => ({\n   *         url: `post/${id}`,\n   *         method: 'PATCH',\n   *         body: patch,\n   *       }),\n   *       invalidatesTags: ['Post'],\n   *       async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n   *         const patchResult = dispatch(\n   *           api.util.updateQueryData('getPost', id, (draft) => {\n   *             Object.assign(draft, patch)\n   *           })\n   *         )\n   *         try {\n   *           await queryFulfilled\n   *         } catch {\n   *           patchResult.undo()\n   *         }\n   *       },\n   *     }),\n   *   }),\n   * })\n   * ```\n   */\n  onQueryStarted?(\n    queryArgument: QueryArg,\n    mutationLifeCycleApi: MutationLifecycleApi<\n      QueryArg,\n      BaseQuery,\n      ResultType,\n      ReducerPath\n    >,\n  ): Promise<void> | void\n}\n\nexport interface QueryLifecycleApi<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ResultType,\n  ReducerPath extends string = string,\n> extends QueryBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath>,\n    QueryLifecyclePromises<ResultType, BaseQuery> {}\n\nexport type MutationLifecycleApi<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ResultType,\n  ReducerPath extends string = string,\n> = MutationBaseLifecycleApi<QueryArg, BaseQuery, ResultType, ReducerPath> &\n  QueryLifecyclePromises<ResultType, BaseQuery>\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleQueryExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific query.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedQueryOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = number | undefined\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, QueryArgument>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedQueryOnQueryStarted<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async (queryArgument, { dispatch, queryFulfilled }) => {\n *   const result = await queryFulfilled\n *\n *   const { posts } = result.data\n *\n *   // Pre-fill the individual post entries with the results\n *   // from the list endpoint query\n *   dispatch(\n *     baseApiSlice.util.upsertQueryEntries(\n *       posts.map((post) => ({\n *         endpointName: 'getPostById',\n *         arg: post.id,\n *         value: post,\n *       })),\n *     ),\n *   )\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     getPostsByUserId: build.query<PostsApiResponse, QueryArgument>({\n *       query: (userId) => `/posts/user/${userId}`,\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedQueryOnQueryStarted<\n  ResultType,\n  QueryArgumentType,\n  BaseQueryFunctionType extends BaseQueryFn,\n  ReducerPath extends string = string,\n> = QueryLifecycleQueryExtraOptions<\n  ResultType,\n  QueryArgumentType,\n  BaseQueryFunctionType,\n  ReducerPath\n>['onQueryStarted']\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryLifecycleMutationExtraOptions.onQueryStarted | onQueryStarted}\n * for a specific mutation.\n *\n * @example\n * <caption>#### __Create and reuse a strongly-typed `onQueryStarted` function__</caption>\n *\n * ```ts\n * import type { TypedMutationOnQueryStarted } from '@reduxjs/toolkit/query'\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n *\n * type Post = {\n *   id: number\n *   title: string\n *   userId: number\n * }\n *\n * type PostsApiResponse = {\n *   posts: Post[]\n *   total: number\n *   skip: number\n *   limit: number\n * }\n *\n * type QueryArgument = Pick<Post, 'id'> & Partial<Post>\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n *\n * const baseApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, void>({\n *       query: () => `/posts`,\n *     }),\n *\n *     getPostById: build.query<Post, number>({\n *       query: (postId) => `/posts/${postId}`,\n *     }),\n *   }),\n * })\n *\n * const updatePostOnFulfilled: TypedMutationOnQueryStarted<\n *   Post,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   'postsApi'\n * > = async ({ id, ...patch }, { dispatch, queryFulfilled }) => {\n *   const patchCollection = dispatch(\n *     baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {\n *       Object.assign(draftPost, patch)\n *     }),\n *   )\n *\n *   try {\n *     await queryFulfilled\n *   } catch {\n *     patchCollection.undo()\n *   }\n * }\n *\n * export const extendedApiSlice = baseApiSlice.injectEndpoints({\n *   endpoints: (build) => ({\n *     addPost: build.mutation<Post, Omit<QueryArgument, 'id'>>({\n *       query: (body) => ({\n *         url: `posts/add`,\n *         method: 'POST',\n *         body,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *\n *     updatePost: build.mutation<Post, QueryArgument>({\n *       query: ({ id, ...patch }) => ({\n *         url: `post/${id}`,\n *         method: 'PATCH',\n *         body: patch,\n *       }),\n *\n *       onQueryStarted: updatePostOnFulfilled,\n *     }),\n *   }),\n * })\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template ReducerPath - The type representing the `reducerPath` for the API slice.\n *\n * @since 2.4.0\n * @public\n */\nexport type TypedMutationOnQueryStarted<\n  ResultType,\n  QueryArgumentType,\n  BaseQueryFunctionType extends BaseQueryFn,\n  ReducerPath extends string = string,\n> = QueryLifecycleMutationExtraOptions<\n  ResultType,\n  QueryArgumentType,\n  BaseQueryFunctionType,\n  ReducerPath\n>['onQueryStarted']\n\nexport const buildQueryLifecycleHandler: InternalHandlerBuilder = ({\n  api,\n  context,\n  queryThunk,\n  mutationThunk,\n}) => {\n  const isPendingThunk = isPending(queryThunk, mutationThunk)\n  const isRejectedThunk = isRejected(queryThunk, mutationThunk)\n  const isFullfilledThunk = isFulfilled(queryThunk, mutationThunk)\n\n  type CacheLifecycle = {\n    resolve(value: { data: unknown; meta: unknown }): unknown\n    reject(value: QueryFulfilledRejectionReason<any>): unknown\n  }\n  const lifecycleMap: Record<string, CacheLifecycle> = {}\n\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (isPendingThunk(action)) {\n      const {\n        requestId,\n        arg: { endpointName, originalArgs },\n      } = action.meta\n      const endpointDefinition = getEndpointDefinition(context, endpointName)\n      const onQueryStarted = endpointDefinition?.onQueryStarted\n      if (onQueryStarted) {\n        const lifecycle = {} as CacheLifecycle\n        const queryFulfilled =\n          new (Promise as PromiseConstructorWithKnownReason)<\n            { data: unknown; meta: unknown },\n            QueryFulfilledRejectionReason<any>\n          >((resolve, reject) => {\n            lifecycle.resolve = resolve\n            lifecycle.reject = reject\n          })\n        // prevent uncaught promise rejections from happening.\n        // if the original promise is used in any way, that will create a new promise that will throw again\n        queryFulfilled.catch(() => {})\n        lifecycleMap[requestId] = lifecycle\n        const selector = (api.endpoints[endpointName] as any).select(\n          isAnyQueryDefinition(endpointDefinition) ? originalArgs : requestId,\n        )\n\n        const extra = mwApi.dispatch((_, __, extra) => extra)\n        const lifecycleApi = {\n          ...mwApi,\n          getCacheEntry: () => selector(mwApi.getState()),\n          requestId,\n          extra,\n          updateCachedData: (isAnyQueryDefinition(endpointDefinition)\n            ? (updateRecipe: Recipe<any>) =>\n                mwApi.dispatch(\n                  api.util.updateQueryData(\n                    endpointName as never,\n                    originalArgs as never,\n                    updateRecipe,\n                  ),\n                )\n            : undefined) as any,\n          queryFulfilled,\n        }\n        onQueryStarted(originalArgs, lifecycleApi as any)\n      }\n    } else if (isFullfilledThunk(action)) {\n      const { requestId, baseQueryMeta } = action.meta\n      lifecycleMap[requestId]?.resolve({\n        data: action.payload,\n        meta: baseQueryMeta,\n      })\n      delete lifecycleMap[requestId]\n    } else if (isRejectedThunk(action)) {\n      const { requestId, rejectedWithValue, baseQueryMeta } = action.meta\n      lifecycleMap[requestId]?.reject({\n        error: action.payload ?? action.error,\n        isUnhandledError: !rejectedWithValue,\n        meta: baseQueryMeta as any,\n      })\n      delete lifecycleMap[requestId]\n    }\n  }\n\n  return handler\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildMiddleware/types.ts",
    "content": "import type {\n  Action,\n  AsyncThunkAction,\n  Dispatch,\n  Middleware,\n  MiddlewareAPI,\n  ThunkAction,\n  ThunkDispatch,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport type { Api, ApiContext } from '../../apiTypes'\nimport type {\n  AssertTagTypes,\n  EndpointDefinitions,\n} from '../../endpointDefinitions'\nimport type {\n  QueryStatus,\n  QuerySubState,\n  RootState,\n  SubscriptionInternalState,\n  SubscriptionState,\n} from '../apiState'\nimport type {\n  InfiniteQueryThunk,\n  MutationThunk,\n  QueryThunk,\n  QueryThunkArg,\n  ThunkResult,\n} from '../buildThunks'\nimport type {\n  InfiniteQueryActionCreatorResult,\n  MutationActionCreatorResult,\n  QueryActionCreatorResult,\n} from '../buildInitiate'\nimport type { AllSelectors } from '../buildSelectors'\n\nexport type QueryStateMeta<T> = Record<string, undefined | T>\nexport type TimeoutId = ReturnType<typeof setTimeout>\n\ntype QueryPollState = {\n  nextPollTimestamp: number\n  timeout?: TimeoutId\n  pollingInterval: number\n}\n\nexport interface InternalMiddlewareState {\n  currentSubscriptions: SubscriptionInternalState\n  currentPolls: Map<string, QueryPollState>\n  runningQueries: Map<\n    string,\n    | QueryActionCreatorResult<any>\n    | InfiniteQueryActionCreatorResult<any>\n    | undefined\n  >\n  runningMutations: Map<string, MutationActionCreatorResult<any> | undefined>\n}\n\nexport interface SubscriptionSelectors {\n  getSubscriptions: () => SubscriptionInternalState\n  getSubscriptionCount: (queryCacheKey: string) => number\n  isRequestSubscribed: (queryCacheKey: string, requestId: string) => boolean\n}\n\nexport interface BuildMiddlewareInput<\n  Definitions extends EndpointDefinitions,\n  ReducerPath extends string,\n  TagTypes extends string,\n> {\n  reducerPath: ReducerPath\n  context: ApiContext<Definitions>\n  queryThunk: QueryThunk\n  mutationThunk: MutationThunk\n  infiniteQueryThunk: InfiniteQueryThunk<any>\n  api: Api<any, Definitions, ReducerPath, TagTypes>\n  assertTagType: AssertTagTypes\n  selectors: AllSelectors\n  getRunningQueryThunk: (\n    endpointName: string,\n    queryArgs: any,\n  ) => (dispatch: Dispatch) => QueryActionCreatorResult<any> | undefined\n  getInternalState: (dispatch: Dispatch) => InternalMiddlewareState\n}\n\nexport type SubMiddlewareApi = MiddlewareAPI<\n  ThunkDispatch<any, any, UnknownAction>,\n  RootState<EndpointDefinitions, string, string>\n>\n\nexport interface BuildSubMiddlewareInput\n  extends BuildMiddlewareInput<EndpointDefinitions, string, string> {\n  internalState: InternalMiddlewareState\n  refetchQuery(\n    querySubState: Exclude<\n      QuerySubState<any>,\n      { status: QueryStatus.uninitialized }\n    >,\n  ): ThunkAction<QueryActionCreatorResult<any>, any, any, UnknownAction>\n  isThisApiSliceAction: (action: Action) => boolean\n  selectors: AllSelectors\n  mwApi: MiddlewareAPI<\n    ThunkDispatch<any, any, UnknownAction>,\n    RootState<EndpointDefinitions, string, string>\n  >\n}\n\nexport type SubMiddlewareBuilder = (\n  input: BuildSubMiddlewareInput,\n) => Middleware<\n  {},\n  RootState<EndpointDefinitions, string, string>,\n  ThunkDispatch<any, any, UnknownAction>\n>\n\ntype MwNext = Parameters<ReturnType<Middleware>>[0]\n\nexport type ApiMiddlewareInternalHandler<Return = void> = (\n  action: Action,\n  mwApi: SubMiddlewareApi & { next: MwNext },\n  prevState: RootState<EndpointDefinitions, string, string>,\n) => Return\n\nexport type InternalHandlerBuilder<ReturnType = void> = (\n  input: BuildSubMiddlewareInput,\n) => ApiMiddlewareInternalHandler<ReturnType>\n\nexport interface PromiseConstructorWithKnownReason {\n  /**\n   * Creates a new Promise with a known rejection reason.\n   * @param executor A callback used to initialize the promise. This callback is passed two arguments:\n   * a resolve callback used to resolve the promise with a value or the result of another promise,\n   * and a reject callback used to reject the promise with a provided reason or error.\n   */\n  new <T, R>(\n    executor: (\n      resolve: (value: T | PromiseLike<T>) => void,\n      reject: (reason?: R) => void,\n    ) => void,\n  ): PromiseWithKnownReason<T, R>\n}\n\nexport type PromiseWithKnownReason<T, R> = Omit<\n  Promise<T>,\n  'then' | 'catch'\n> & {\n  /**\n   * Attaches callbacks for the resolution and/or rejection of the Promise.\n   * @param onfulfilled The callback to execute when the Promise is resolved.\n   * @param onrejected The callback to execute when the Promise is rejected.\n   * @returns A Promise for the completion of which ever callback is executed.\n   */\n  then<TResult1 = T, TResult2 = never>(\n    onfulfilled?:\n      | ((value: T) => TResult1 | PromiseLike<TResult1>)\n      | undefined\n      | null,\n    onrejected?:\n      | ((reason: R) => TResult2 | PromiseLike<TResult2>)\n      | undefined\n      | null,\n  ): Promise<TResult1 | TResult2>\n\n  /**\n   * Attaches a callback for only the rejection of the Promise.\n   * @param onrejected The callback to execute when the Promise is rejected.\n   * @returns A Promise for the completion of the callback.\n   */\n  catch<TResult = never>(\n    onrejected?:\n      | ((reason: R) => TResult | PromiseLike<TResult>)\n      | undefined\n      | null,\n  ): Promise<T | TResult>\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildMiddleware/windowEventHandling.ts",
    "content": "import { QueryStatus, STATUS_UNINITIALIZED } from '../apiState'\nimport type { QueryCacheKey } from '../apiState'\nimport { onFocus, onOnline } from '../setupListeners'\nimport type {\n  ApiMiddlewareInternalHandler,\n  InternalHandlerBuilder,\n  SubMiddlewareApi,\n} from './types'\n\nexport const buildWindowEventHandler: InternalHandlerBuilder = ({\n  reducerPath,\n  context,\n  api,\n  refetchQuery,\n  internalState,\n}) => {\n  const { removeQueryResult } = api.internalActions\n\n  const handler: ApiMiddlewareInternalHandler = (action, mwApi) => {\n    if (onFocus.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnFocus')\n    }\n    if (onOnline.match(action)) {\n      refetchValidQueries(mwApi, 'refetchOnReconnect')\n    }\n  }\n\n  function refetchValidQueries(\n    api: SubMiddlewareApi,\n    type: 'refetchOnFocus' | 'refetchOnReconnect',\n  ) {\n    const state = api.getState()[reducerPath]\n    const queries = state.queries\n    const subscriptions = internalState.currentSubscriptions\n\n    context.batch(() => {\n      for (const queryCacheKey of subscriptions.keys()) {\n        const querySubState = queries[queryCacheKey]\n        const subscriptionSubState = subscriptions.get(queryCacheKey)\n\n        if (!subscriptionSubState || !querySubState) continue\n\n        const values = [...subscriptionSubState.values()]\n        const shouldRefetch =\n          values.some((sub) => sub[type] === true) ||\n          (values.every((sub) => sub[type] === undefined) && state.config[type])\n\n        if (shouldRefetch) {\n          if (subscriptionSubState.size === 0) {\n            api.dispatch(\n              removeQueryResult({\n                queryCacheKey: queryCacheKey as QueryCacheKey,\n              }),\n            )\n          } else if (querySubState.status !== STATUS_UNINITIALIZED) {\n            api.dispatch(refetchQuery(querySubState))\n          }\n        }\n      }\n    })\n  }\n\n  return handler\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildSelectors.ts",
    "content": "import type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\nimport type {\n  EndpointDefinition,\n  EndpointDefinitions,\n  InfiniteQueryArgFrom,\n  InfiniteQueryDefinition,\n  MutationDefinition,\n  QueryArgFrom,\n  QueryArgFromAnyQuery,\n  QueryDefinition,\n  ReducerPathFrom,\n  TagDescription,\n  TagTypesFrom,\n} from '../endpointDefinitions'\nimport { expandTagDescription } from '../endpointDefinitions'\nimport { filterMap, isNotNullish } from '../utils'\nimport type {\n  InfiniteData,\n  InfiniteQueryConfigOptions,\n  InfiniteQuerySubState,\n  MutationSubState,\n  QueryCacheKey,\n  QueryState,\n  QuerySubState,\n  RequestStatusFlags,\n  RootState as _RootState,\n  QueryStatus,\n} from './apiState'\nimport { STATUS_UNINITIALIZED, getRequestStatusFlags } from './apiState'\nimport { getMutationCacheKey } from './buildSlice'\nimport type { createSelector as _createSelector } from './rtkImports'\nimport { createNextState } from './rtkImports'\nimport {\n  type AllQueryKeys,\n  getNextPageParam,\n  getPreviousPageParam,\n} from './buildThunks'\n\nexport type SkipToken = typeof skipToken\n/**\n * Can be passed into `useQuery`, `useQueryState` or `useQuerySubscription`\n * instead of the query argument to get the same effect as if setting\n * `skip: true` in the query options.\n *\n * Useful for scenarios where a query should be skipped when `arg` is `undefined`\n * and TypeScript complains about it because `arg` is not allowed to be passed\n * in as `undefined`, such as\n *\n * ```ts\n * // codeblock-meta title=\"will error if the query argument is not allowed to be undefined\" no-transpile\n * useSomeQuery(arg, { skip: !!arg })\n * ```\n *\n * ```ts\n * // codeblock-meta title=\"using skipToken instead\" no-transpile\n * useSomeQuery(arg ?? skipToken)\n * ```\n *\n * If passed directly into a query or mutation selector, that selector will always\n * return an uninitialized state.\n */\nexport const skipToken = /* @__PURE__ */ Symbol.for('RTKQ/skipToken')\n\nexport type BuildSelectorsApiEndpointQuery<\n  Definition extends QueryDefinition<any, any, any, any, any>,\n  Definitions extends EndpointDefinitions,\n> = {\n  select: QueryResultSelectorFactory<\n    Definition,\n    _RootState<\n      Definitions,\n      TagTypesFrom<Definition>,\n      ReducerPathFrom<Definition>\n    >\n  >\n}\n\nexport type BuildSelectorsApiEndpointInfiniteQuery<\n  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,\n  Definitions extends EndpointDefinitions,\n> = {\n  select: InfiniteQueryResultSelectorFactory<\n    Definition,\n    _RootState<\n      Definitions,\n      TagTypesFrom<Definition>,\n      ReducerPathFrom<Definition>\n    >\n  >\n}\n\nexport type BuildSelectorsApiEndpointMutation<\n  Definition extends MutationDefinition<any, any, any, any, any>,\n  Definitions extends EndpointDefinitions,\n> = {\n  select: MutationResultSelectorFactory<\n    Definition,\n    _RootState<\n      Definitions,\n      TagTypesFrom<Definition>,\n      ReducerPathFrom<Definition>\n    >\n  >\n}\n\ntype QueryResultSelectorFactory<\n  Definition extends QueryDefinition<any, any, any, any>,\n  RootState,\n> = (\n  queryArg: QueryArgFrom<Definition> | SkipToken,\n) => (state: RootState) => QueryResultSelectorResult<Definition>\n\nexport type QueryResultSelectorResult<\n  Definition extends QueryDefinition<any, any, any, any>,\n> = QuerySubState<Definition> & RequestStatusFlags\n\ntype InfiniteQueryResultSelectorFactory<\n  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,\n  RootState,\n> = (\n  queryArg: InfiniteQueryArgFrom<Definition> | SkipToken,\n) => (state: RootState) => InfiniteQueryResultSelectorResult<Definition>\n\nexport type InfiniteQueryResultFlags = {\n  hasNextPage: boolean\n  hasPreviousPage: boolean\n  isFetchingNextPage: boolean\n  isFetchingPreviousPage: boolean\n  isFetchNextPageError: boolean\n  isFetchPreviousPageError: boolean\n}\n\nexport type InfiniteQueryResultSelectorResult<\n  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = InfiniteQuerySubState<Definition> &\n  RequestStatusFlags &\n  InfiniteQueryResultFlags\n\ntype MutationResultSelectorFactory<\n  Definition extends MutationDefinition<any, any, any, any>,\n  RootState,\n> = (\n  requestId:\n    | string\n    | { requestId: string | undefined; fixedCacheKey: string | undefined }\n    | SkipToken,\n) => (state: RootState) => MutationResultSelectorResult<Definition>\n\nexport type MutationResultSelectorResult<\n  Definition extends MutationDefinition<any, any, any, any>,\n> = MutationSubState<Definition> & RequestStatusFlags\n\nconst initialSubState: QuerySubState<any> = {\n  status: STATUS_UNINITIALIZED,\n}\n\n// abuse immer to freeze default states\nconst defaultQuerySubState = /* @__PURE__ */ createNextState(\n  initialSubState,\n  () => {},\n)\nconst defaultMutationSubState = /* @__PURE__ */ createNextState(\n  initialSubState as MutationSubState<any>,\n  () => {},\n)\n\nexport type AllSelectors = ReturnType<typeof buildSelectors>\n\nexport function buildSelectors<\n  Definitions extends EndpointDefinitions,\n  ReducerPath extends string,\n>({\n  serializeQueryArgs,\n  reducerPath,\n  createSelector,\n}: {\n  serializeQueryArgs: InternalSerializeQueryArgs\n  reducerPath: ReducerPath\n  createSelector: typeof _createSelector\n}) {\n  type RootState = _RootState<Definitions, string, string>\n\n  const selectSkippedQuery = (state: RootState) => defaultQuerySubState\n  const selectSkippedMutation = (state: RootState) => defaultMutationSubState\n\n  return {\n    buildQuerySelector,\n    buildInfiniteQuerySelector,\n    buildMutationSelector,\n    selectInvalidatedBy,\n    selectCachedArgsForQuery,\n    selectApiState,\n    selectQueries,\n    selectMutations,\n    selectQueryEntry,\n    selectConfig,\n  }\n\n  function withRequestFlags<T extends { status: QueryStatus }>(\n    substate: T,\n  ): T & RequestStatusFlags {\n    return { ...substate, ...getRequestStatusFlags(substate.status) }\n  }\n\n  function selectApiState(rootState: RootState) {\n    const state = rootState[reducerPath]\n    if (process.env.NODE_ENV !== 'production') {\n      if (!state) {\n        if ((selectApiState as any).triggered) return state\n        ;(selectApiState as any).triggered = true\n        console.error(\n          `Error: No data found at \\`state.${reducerPath}\\`. Did you forget to add the reducer to the store?`,\n        )\n      }\n    }\n    return state\n  }\n\n  function selectQueries(rootState: RootState) {\n    return selectApiState(rootState)?.queries\n  }\n\n  function selectQueryEntry(rootState: RootState, cacheKey: QueryCacheKey) {\n    return selectQueries(rootState)?.[cacheKey]\n  }\n\n  function selectMutations(rootState: RootState) {\n    return selectApiState(rootState)?.mutations\n  }\n\n  function selectConfig(rootState: RootState) {\n    return selectApiState(rootState)?.config\n  }\n\n  function buildAnyQuerySelector(\n    endpointName: string,\n    endpointDefinition: EndpointDefinition<any, any, any, any>,\n    combiner: <T extends { status: QueryStatus }>(\n      substate: T,\n    ) => T & RequestStatusFlags,\n  ) {\n    return (queryArgs: any) => {\n      // Avoid calling serializeQueryArgs if the arg is skipToken\n      if (queryArgs === skipToken) {\n        return createSelector(selectSkippedQuery, combiner)\n      }\n\n      const serializedArgs = serializeQueryArgs({\n        queryArgs,\n        endpointDefinition,\n        endpointName,\n      })\n      const selectQuerySubstate = (state: RootState) =>\n        selectQueryEntry(state, serializedArgs) ?? defaultQuerySubState\n\n      return createSelector(selectQuerySubstate, combiner)\n    }\n  }\n\n  function buildQuerySelector(\n    endpointName: string,\n    endpointDefinition: QueryDefinition<any, any, any, any>,\n  ) {\n    return buildAnyQuerySelector(\n      endpointName,\n      endpointDefinition,\n      withRequestFlags,\n    ) as QueryResultSelectorFactory<any, RootState>\n  }\n\n  function buildInfiniteQuerySelector(\n    endpointName: string,\n    endpointDefinition: InfiniteQueryDefinition<any, any, any, any, any>,\n  ) {\n    const { infiniteQueryOptions } = endpointDefinition\n\n    function withInfiniteQueryResultFlags<T extends { status: QueryStatus }>(\n      substate: T,\n    ): T & RequestStatusFlags & InfiniteQueryResultFlags {\n      const stateWithRequestFlags = {\n        ...(substate as InfiniteQuerySubState<any>),\n        ...getRequestStatusFlags(substate.status),\n      }\n\n      const { isLoading, isError, direction } = stateWithRequestFlags\n      const isForward = direction === 'forward'\n      const isBackward = direction === 'backward'\n\n      return {\n        ...stateWithRequestFlags,\n        hasNextPage: getHasNextPage(\n          infiniteQueryOptions,\n          stateWithRequestFlags.data,\n          stateWithRequestFlags.originalArgs,\n        ),\n        hasPreviousPage: getHasPreviousPage(\n          infiniteQueryOptions,\n          stateWithRequestFlags.data,\n          stateWithRequestFlags.originalArgs,\n        ),\n        isFetchingNextPage: isLoading && isForward,\n        isFetchingPreviousPage: isLoading && isBackward,\n        isFetchNextPageError: isError && isForward,\n        isFetchPreviousPageError: isError && isBackward,\n      }\n    }\n\n    return buildAnyQuerySelector(\n      endpointName,\n      endpointDefinition,\n      withInfiniteQueryResultFlags,\n    ) as unknown as InfiniteQueryResultSelectorFactory<any, RootState>\n  }\n\n  function buildMutationSelector() {\n    return ((id) => {\n      let mutationId: string | typeof skipToken\n      if (typeof id === 'object') {\n        mutationId = getMutationCacheKey(id) ?? skipToken\n      } else {\n        mutationId = id\n      }\n      const selectMutationSubstate = (state: RootState) =>\n        selectApiState(state)?.mutations?.[mutationId as string] ??\n        defaultMutationSubState\n      const finalSelectMutationSubstate =\n        mutationId === skipToken\n          ? selectSkippedMutation\n          : selectMutationSubstate\n\n      return createSelector(finalSelectMutationSubstate, withRequestFlags)\n    }) as MutationResultSelectorFactory<any, RootState>\n  }\n\n  function selectInvalidatedBy(\n    state: RootState,\n    tags: ReadonlyArray<TagDescription<string> | null | undefined>,\n  ): Array<{\n    endpointName: string\n    originalArgs: any\n    queryCacheKey: QueryCacheKey\n  }> {\n    const apiState = state[reducerPath]\n    const toInvalidate = new Set<QueryCacheKey>()\n    const finalTags = filterMap(tags, isNotNullish, expandTagDescription)\n    for (const tag of finalTags) {\n      const provided = apiState.provided.tags[tag.type]\n      if (!provided) {\n        continue\n      }\n\n      let invalidateSubscriptions =\n        (tag.id !== undefined\n          ? // id given: invalidate all queries that provide this type & id\n            provided[tag.id]\n          : // no id: invalidate all queries that provide this type\n            Object.values(provided).flat()) ?? []\n\n      for (const invalidate of invalidateSubscriptions) {\n        toInvalidate.add(invalidate)\n      }\n    }\n\n    return Array.from(toInvalidate.values()).flatMap((queryCacheKey) => {\n      const querySubState = apiState.queries[queryCacheKey]\n      return querySubState\n        ? {\n            queryCacheKey,\n            endpointName: querySubState.endpointName!,\n            originalArgs: querySubState.originalArgs,\n          }\n        : []\n    })\n  }\n\n  function selectCachedArgsForQuery<\n    QueryName extends AllQueryKeys<Definitions>,\n  >(\n    state: RootState,\n    queryName: QueryName,\n  ): Array<QueryArgFromAnyQuery<Definitions[QueryName]>> {\n    return filterMap(\n      Object.values(selectQueries(state) as QueryState<any>),\n      (\n        entry,\n      ): entry is Exclude<\n        QuerySubState<Definitions[QueryName]>,\n        { status: QueryStatus.uninitialized }\n      > =>\n        entry?.endpointName === queryName &&\n        entry.status !== STATUS_UNINITIALIZED,\n      (entry) => entry.originalArgs,\n    )\n  }\n\n  function getHasNextPage(\n    options: InfiniteQueryConfigOptions<any, any, any>,\n    data?: InfiniteData<unknown, unknown>,\n    queryArg?: unknown,\n  ): boolean {\n    if (!data) return false\n    return getNextPageParam(options, data, queryArg) != null\n  }\n\n  function getHasPreviousPage(\n    options: InfiniteQueryConfigOptions<any, any, any>,\n    data?: InfiniteData<unknown, unknown>,\n    queryArg?: unknown,\n  ): boolean {\n    if (!data || !options.getPreviousPageParam) return false\n    return getPreviousPageParam(options, data, queryArg) != null\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildSlice.ts",
    "content": "import type { PayloadAction } from '@reduxjs/toolkit'\nimport {\n  combineReducers,\n  createAction,\n  createSlice,\n  isAnyOf,\n  isFulfilled,\n  isRejectedWithValue,\n  createNextState,\n  prepareAutoBatched,\n  SHOULD_AUTOBATCH,\n  nanoid,\n} from './rtkImports'\nimport type {\n  QuerySubstateIdentifier,\n  QuerySubState,\n  MutationSubstateIdentifier,\n  MutationSubState,\n  MutationState,\n  QueryState,\n  InvalidationState,\n  Subscribers,\n  QueryCacheKey,\n  SubscriptionState,\n  ConfigState,\n  InfiniteQuerySubState,\n  InfiniteQueryDirection,\n} from './apiState'\nimport {\n  STATUS_FULFILLED,\n  STATUS_PENDING,\n  QueryStatus,\n  STATUS_REJECTED,\n  STATUS_UNINITIALIZED,\n} from './apiState'\nimport type {\n  AllQueryKeys,\n  QueryArgFromAnyQueryDefinition,\n  DataFromAnyQueryDefinition,\n  InfiniteQueryThunk,\n  MutationThunk,\n  QueryThunk,\n  QueryThunkArg,\n} from './buildThunks'\nimport { calculateProvidedByThunk } from './buildThunks'\nimport {\n  ENDPOINT_QUERY,\n  isInfiniteQueryDefinition,\n  type AssertTagTypes,\n  type EndpointDefinitions,\n  type FullTagDescription,\n  type QueryDefinition,\n} from '../endpointDefinitions'\nimport type { Patch } from 'immer'\nimport { applyPatches, original, isDraft } from '../utils/immerImports'\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'\nimport {\n  isDocumentVisible,\n  isOnline,\n  copyWithStructuralSharing,\n} from '../utils'\nimport type { ApiContext } from '../apiTypes'\nimport { isUpsertQuery } from './buildInitiate'\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\nimport type { UnwrapPromise } from '../tsHelpers'\nimport { getCurrent } from '../utils/getCurrent'\n\n/**\n * A typesafe single entry to be upserted into the cache\n */\nexport type NormalizedQueryUpsertEntry<\n  Definitions extends EndpointDefinitions,\n  EndpointName extends AllQueryKeys<Definitions>,\n> = {\n  endpointName: EndpointName\n  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>\n  value: DataFromAnyQueryDefinition<Definitions, EndpointName>\n}\n\n/**\n * The internal version that is not typesafe since we can't carry the generics through `createSlice`\n */\ntype NormalizedQueryUpsertEntryPayload = {\n  endpointName: string\n  arg: unknown\n  value: unknown\n}\n\nexport type ProcessedQueryUpsertEntry = {\n  queryDescription: QueryThunkArg\n  value: unknown\n}\n\n/**\n * A typesafe representation of a util action creator that accepts cache entry descriptions to upsert\n */\nexport type UpsertEntries<Definitions extends EndpointDefinitions> = (<\n  EndpointNames extends Array<AllQueryKeys<Definitions>>,\n>(\n  entries: [\n    ...{\n      [I in keyof EndpointNames]: NormalizedQueryUpsertEntry<\n        Definitions,\n        EndpointNames[I]\n      >\n    },\n  ],\n) => PayloadAction<NormalizedQueryUpsertEntryPayload[]>) & {\n  match: (\n    action: unknown,\n  ) => action is PayloadAction<NormalizedQueryUpsertEntryPayload[]>\n}\n\nfunction updateQuerySubstateIfExists(\n  state: QueryState<any>,\n  queryCacheKey: QueryCacheKey,\n  update: (substate: QuerySubState<any> | InfiniteQuerySubState<any>) => void,\n) {\n  const substate = state[queryCacheKey]\n  if (substate) {\n    update(substate)\n  }\n}\n\nexport function getMutationCacheKey(\n  id:\n    | MutationSubstateIdentifier\n    | { requestId: string; arg: { fixedCacheKey?: string | undefined } },\n): string\nexport function getMutationCacheKey(id: {\n  fixedCacheKey?: string\n  requestId?: string\n}): string | undefined\n\nexport function getMutationCacheKey(\n  id:\n    | { fixedCacheKey?: string; requestId?: string }\n    | MutationSubstateIdentifier\n    | { requestId: string; arg: { fixedCacheKey?: string | undefined } },\n): string | undefined {\n  return ('arg' in id ? id.arg.fixedCacheKey : id.fixedCacheKey) ?? id.requestId\n}\n\nfunction updateMutationSubstateIfExists(\n  state: MutationState<any>,\n  id:\n    | MutationSubstateIdentifier\n    | { requestId: string; arg: { fixedCacheKey?: string | undefined } },\n  update: (substate: MutationSubState<any>) => void,\n) {\n  const substate = state[getMutationCacheKey(id)]\n  if (substate) {\n    update(substate)\n  }\n}\n\nconst initialState = {} as any\n\nexport function buildSlice({\n  reducerPath,\n  queryThunk,\n  mutationThunk,\n  serializeQueryArgs,\n  context: {\n    endpointDefinitions: definitions,\n    apiUid,\n    extractRehydrationInfo,\n    hasRehydrationInfo,\n  },\n  assertTagType,\n  config,\n}: {\n  reducerPath: string\n  queryThunk: QueryThunk\n  infiniteQueryThunk: InfiniteQueryThunk<any>\n  mutationThunk: MutationThunk\n  serializeQueryArgs: InternalSerializeQueryArgs\n  context: ApiContext<EndpointDefinitions>\n  assertTagType: AssertTagTypes\n  config: Omit<\n    ConfigState<string>,\n    'online' | 'focused' | 'middlewareRegistered'\n  >\n}) {\n  const resetApiState = createAction(`${reducerPath}/resetApiState`)\n\n  function writePendingCacheEntry(\n    draft: QueryState<any>,\n    arg: QueryThunkArg,\n    upserting: boolean,\n    meta: {\n      arg: QueryThunkArg\n      requestId: string\n      // requestStatus: 'pending'\n    } & { startedTimeStamp: number },\n  ) {\n    draft[arg.queryCacheKey] ??= {\n      status: STATUS_UNINITIALIZED,\n      endpointName: arg.endpointName,\n    }\n\n    updateQuerySubstateIfExists(draft, arg.queryCacheKey, (substate) => {\n      substate.status = STATUS_PENDING\n\n      substate.requestId =\n        upserting && substate.requestId\n          ? // for `upsertQuery` **updates**, keep the current `requestId`\n            substate.requestId\n          : // for normal queries or `upsertQuery` **inserts** always update the `requestId`\n            meta.requestId\n      if (arg.originalArgs !== undefined) {\n        substate.originalArgs = arg.originalArgs\n      }\n      substate.startedTimeStamp = meta.startedTimeStamp\n\n      const endpointDefinition = definitions[meta.arg.endpointName]\n\n      if (isInfiniteQueryDefinition(endpointDefinition) && 'direction' in arg) {\n        ;(substate as InfiniteQuerySubState<any>).direction =\n          arg.direction as InfiniteQueryDirection\n      }\n    })\n  }\n\n  function writeFulfilledCacheEntry(\n    draft: QueryState<any>,\n    meta: { arg: QueryThunkArg; requestId: string } & {\n      fulfilledTimeStamp: number\n      baseQueryMeta: unknown\n    },\n    payload: unknown,\n    upserting: boolean,\n  ) {\n    updateQuerySubstateIfExists(draft, meta.arg.queryCacheKey, (substate) => {\n      if (substate.requestId !== meta.requestId && !upserting) return\n      const { merge } = definitions[meta.arg.endpointName] as QueryDefinition<\n        any,\n        any,\n        any,\n        any\n      >\n      substate.status = STATUS_FULFILLED\n\n      if (merge) {\n        if (substate.data !== undefined) {\n          const { fulfilledTimeStamp, arg, baseQueryMeta, requestId } = meta\n          // There's existing cache data. Let the user merge it in themselves.\n          // We're already inside an Immer-powered reducer, and the user could just mutate `substate.data`\n          // themselves inside of `merge()`. But, they might also want to return a new value.\n          // Try to let Immer figure that part out, save the result, and assign it to `substate.data`.\n          let newData = createNextState(substate.data, (draftSubstateData) => {\n            // As usual with Immer, you can mutate _or_ return inside here, but not both\n            return merge(draftSubstateData, payload, {\n              arg: arg.originalArgs,\n              baseQueryMeta,\n              fulfilledTimeStamp,\n              requestId,\n            })\n          })\n          substate.data = newData\n        } else {\n          // Presumably a fresh request. Just cache the response data.\n          substate.data = payload\n        }\n      } else {\n        // Assign or safely update the cache data.\n        substate.data =\n          (definitions[meta.arg.endpointName].structuralSharing ?? true)\n            ? copyWithStructuralSharing(\n                isDraft(substate.data)\n                  ? original(substate.data)\n                  : substate.data,\n                payload,\n              )\n            : payload\n      }\n\n      delete substate.error\n      substate.fulfilledTimeStamp = meta.fulfilledTimeStamp\n    })\n  }\n\n  const querySlice = createSlice({\n    name: `${reducerPath}/queries`,\n    initialState: initialState as QueryState<any>,\n    reducers: {\n      removeQueryResult: {\n        reducer(\n          draft,\n          {\n            payload: { queryCacheKey },\n          }: PayloadAction<QuerySubstateIdentifier>,\n        ) {\n          delete draft[queryCacheKey]\n        },\n        prepare: prepareAutoBatched<QuerySubstateIdentifier>(),\n      },\n      cacheEntriesUpserted: {\n        reducer(\n          draft,\n          action: PayloadAction<\n            ProcessedQueryUpsertEntry[],\n            string,\n            { RTK_autoBatch: boolean; requestId: string; timestamp: number }\n          >,\n        ) {\n          for (const entry of action.payload) {\n            const { queryDescription: arg, value } = entry\n            writePendingCacheEntry(draft, arg, true, {\n              arg,\n              requestId: action.meta.requestId,\n              startedTimeStamp: action.meta.timestamp,\n            })\n\n            writeFulfilledCacheEntry(\n              draft,\n              {\n                arg,\n                requestId: action.meta.requestId,\n                fulfilledTimeStamp: action.meta.timestamp,\n                baseQueryMeta: {},\n              },\n              value,\n              // We know we're upserting here\n              true,\n            )\n          }\n        },\n        prepare: (payload: NormalizedQueryUpsertEntryPayload[]) => {\n          const queryDescriptions: ProcessedQueryUpsertEntry[] = payload.map(\n            (entry) => {\n              const { endpointName, arg, value } = entry\n              const endpointDefinition = definitions[endpointName]\n              const queryDescription: QueryThunkArg = {\n                type: ENDPOINT_QUERY as 'query',\n                endpointName,\n                originalArgs: entry.arg,\n                queryCacheKey: serializeQueryArgs({\n                  queryArgs: arg,\n                  endpointDefinition,\n                  endpointName,\n                }),\n              }\n              return { queryDescription, value }\n            },\n          )\n\n          const result = {\n            payload: queryDescriptions,\n            meta: {\n              [SHOULD_AUTOBATCH]: true,\n              requestId: nanoid(),\n              timestamp: Date.now(),\n            },\n          }\n          return result\n        },\n      },\n      queryResultPatched: {\n        reducer(\n          draft,\n          {\n            payload: { queryCacheKey, patches },\n          }: PayloadAction<\n            QuerySubstateIdentifier & { patches: readonly Patch[] }\n          >,\n        ) {\n          updateQuerySubstateIfExists(draft, queryCacheKey, (substate) => {\n            substate.data = applyPatches(substate.data as any, patches.concat())\n          })\n        },\n        prepare: prepareAutoBatched<\n          QuerySubstateIdentifier & { patches: readonly Patch[] }\n        >(),\n      },\n    },\n    extraReducers(builder) {\n      builder\n        .addCase(queryThunk.pending, (draft, { meta, meta: { arg } }) => {\n          const upserting = isUpsertQuery(arg)\n          writePendingCacheEntry(draft, arg, upserting, meta)\n        })\n        .addCase(queryThunk.fulfilled, (draft, { meta, payload }) => {\n          const upserting = isUpsertQuery(meta.arg)\n          writeFulfilledCacheEntry(draft, meta, payload, upserting)\n        })\n        .addCase(\n          queryThunk.rejected,\n          (draft, { meta: { condition, arg, requestId }, error, payload }) => {\n            updateQuerySubstateIfExists(\n              draft,\n              arg.queryCacheKey,\n              (substate) => {\n                if (condition) {\n                  // request was aborted due to condition (another query already running)\n                } else {\n                  // request failed\n                  if (substate.requestId !== requestId) return\n                  substate.status = STATUS_REJECTED\n                  substate.error = (payload ?? error) as any\n                }\n              },\n            )\n          },\n        )\n        .addMatcher(hasRehydrationInfo, (draft, action) => {\n          const { queries } = extractRehydrationInfo(action)!\n          for (const [key, entry] of Object.entries(queries)) {\n            if (\n              // do not rehydrate entries that were currently in flight.\n              entry?.status === STATUS_FULFILLED ||\n              entry?.status === STATUS_REJECTED\n            ) {\n              draft[key] = entry\n            }\n          }\n        })\n    },\n  })\n  const mutationSlice = createSlice({\n    name: `${reducerPath}/mutations`,\n    initialState: initialState as MutationState<any>,\n    reducers: {\n      removeMutationResult: {\n        reducer(draft, { payload }: PayloadAction<MutationSubstateIdentifier>) {\n          const cacheKey = getMutationCacheKey(payload)\n          if (cacheKey in draft) {\n            delete draft[cacheKey]\n          }\n        },\n        prepare: prepareAutoBatched<MutationSubstateIdentifier>(),\n      },\n    },\n    extraReducers(builder) {\n      builder\n        .addCase(\n          mutationThunk.pending,\n          (draft, { meta, meta: { requestId, arg, startedTimeStamp } }) => {\n            if (!arg.track) return\n\n            draft[getMutationCacheKey(meta)] = {\n              requestId,\n              status: STATUS_PENDING,\n              endpointName: arg.endpointName,\n              startedTimeStamp,\n            }\n          },\n        )\n        .addCase(mutationThunk.fulfilled, (draft, { payload, meta }) => {\n          if (!meta.arg.track) return\n\n          updateMutationSubstateIfExists(draft, meta, (substate) => {\n            if (substate.requestId !== meta.requestId) return\n            substate.status = STATUS_FULFILLED\n            substate.data = payload\n            substate.fulfilledTimeStamp = meta.fulfilledTimeStamp\n          })\n        })\n        .addCase(mutationThunk.rejected, (draft, { payload, error, meta }) => {\n          if (!meta.arg.track) return\n\n          updateMutationSubstateIfExists(draft, meta, (substate) => {\n            if (substate.requestId !== meta.requestId) return\n\n            substate.status = STATUS_REJECTED\n            substate.error = (payload ?? error) as any\n          })\n        })\n        .addMatcher(hasRehydrationInfo, (draft, action) => {\n          const { mutations } = extractRehydrationInfo(action)!\n          for (const [key, entry] of Object.entries(mutations)) {\n            if (\n              // do not rehydrate entries that were currently in flight.\n              (entry?.status === STATUS_FULFILLED ||\n                entry?.status === STATUS_REJECTED) &&\n              // only rehydrate endpoints that were persisted using a `fixedCacheKey`\n              key !== entry?.requestId\n            ) {\n              draft[key] = entry\n            }\n          }\n        })\n    },\n  })\n\n  type CalculateProvidedByAction = UnwrapPromise<\n    | ReturnType<ReturnType<QueryThunk>>\n    | ReturnType<ReturnType<InfiniteQueryThunk<any>>>\n  >\n\n  const initialInvalidationState: InvalidationState<string> = {\n    tags: {},\n    keys: {},\n  }\n\n  const invalidationSlice = createSlice({\n    name: `${reducerPath}/invalidation`,\n    initialState: initialInvalidationState,\n    reducers: {\n      updateProvidedBy: {\n        reducer(\n          draft,\n          action: PayloadAction<\n            Array<{\n              queryCacheKey: QueryCacheKey\n              providedTags: readonly FullTagDescription<string>[]\n            }>\n          >,\n        ) {\n          for (const { queryCacheKey, providedTags } of action.payload) {\n            removeCacheKeyFromTags(draft, queryCacheKey)\n\n            for (const { type, id } of providedTags) {\n              const subscribedQueries = ((draft.tags[type] ??= {})[\n                id || '__internal_without_id'\n              ] ??= [])\n              const alreadySubscribed =\n                subscribedQueries.includes(queryCacheKey)\n              if (!alreadySubscribed) {\n                subscribedQueries.push(queryCacheKey)\n              }\n            }\n\n            // Remove readonly from the providedTags array\n            draft.keys[queryCacheKey] =\n              providedTags as FullTagDescription<string>[]\n          }\n        },\n        prepare: prepareAutoBatched<\n          Array<{\n            queryCacheKey: QueryCacheKey\n            providedTags: readonly FullTagDescription<string>[]\n          }>\n        >(),\n      },\n    },\n    extraReducers(builder) {\n      builder\n        .addCase(\n          querySlice.actions.removeQueryResult,\n          (draft, { payload: { queryCacheKey } }) => {\n            removeCacheKeyFromTags(draft, queryCacheKey)\n          },\n        )\n        .addMatcher(hasRehydrationInfo, (draft, action) => {\n          const { provided } = extractRehydrationInfo(action)!\n          for (const [type, incomingTags] of Object.entries(\n            provided.tags ?? {},\n          )) {\n            for (const [id, cacheKeys] of Object.entries(incomingTags)) {\n              const subscribedQueries = ((draft.tags[type] ??= {})[\n                id || '__internal_without_id'\n              ] ??= [])\n              for (const queryCacheKey of cacheKeys) {\n                const alreadySubscribed =\n                  subscribedQueries.includes(queryCacheKey)\n                if (!alreadySubscribed) {\n                  subscribedQueries.push(queryCacheKey)\n                }\n                draft.keys[queryCacheKey] = provided.keys[queryCacheKey]\n              }\n            }\n          }\n        })\n        .addMatcher(\n          isAnyOf(isFulfilled(queryThunk), isRejectedWithValue(queryThunk)),\n          (draft, action) => {\n            writeProvidedTagsForQueries(draft, [action])\n          },\n        )\n        .addMatcher(\n          querySlice.actions.cacheEntriesUpserted.match,\n          (draft, action) => {\n            const mockActions: CalculateProvidedByAction[] = action.payload.map(\n              ({ queryDescription, value }) => {\n                return {\n                  type: 'UNKNOWN',\n                  payload: value,\n                  meta: {\n                    requestStatus: 'fulfilled',\n                    requestId: 'UNKNOWN',\n                    arg: queryDescription,\n                  },\n                }\n              },\n            )\n            writeProvidedTagsForQueries(draft, mockActions)\n          },\n        )\n    },\n  })\n\n  function removeCacheKeyFromTags(\n    draft: InvalidationState<any>,\n    queryCacheKey: QueryCacheKey,\n  ) {\n    const existingTags = getCurrent(draft.keys[queryCacheKey] ?? [])\n\n    // Delete this cache key from any existing tags that may have provided it\n    for (const tag of existingTags) {\n      const tagType = tag.type\n      const tagId = tag.id ?? '__internal_without_id'\n      const tagSubscriptions = draft.tags[tagType]?.[tagId]\n\n      if (tagSubscriptions) {\n        draft.tags[tagType][tagId] = getCurrent(tagSubscriptions).filter(\n          (qc) => qc !== queryCacheKey,\n        )\n      }\n    }\n\n    delete draft.keys[queryCacheKey]\n  }\n\n  function writeProvidedTagsForQueries(\n    draft: InvalidationState<string>,\n    actions: CalculateProvidedByAction[],\n  ) {\n    const providedByEntries = actions.map((action) => {\n      const providedTags = calculateProvidedByThunk(\n        action,\n        'providesTags',\n        definitions,\n        assertTagType,\n      )\n      const { queryCacheKey } = action.meta.arg\n      return { queryCacheKey, providedTags }\n    })\n\n    invalidationSlice.caseReducers.updateProvidedBy(\n      draft,\n      invalidationSlice.actions.updateProvidedBy(providedByEntries),\n    )\n  }\n\n  // Dummy slice to generate actions\n  const subscriptionSlice = createSlice({\n    name: `${reducerPath}/subscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      updateSubscriptionOptions(\n        d,\n        a: PayloadAction<\n          {\n            endpointName: string\n            requestId: string\n            options: Subscribers[number]\n          } & QuerySubstateIdentifier\n        >,\n      ) {\n        // Dummy\n      },\n      unsubscribeQueryResult(\n        d,\n        a: PayloadAction<{ requestId: string } & QuerySubstateIdentifier>,\n      ) {\n        // Dummy\n      },\n      internal_getRTKQSubscriptions() {},\n    },\n  })\n\n  const internalSubscriptionsSlice = createSlice({\n    name: `${reducerPath}/internalSubscriptions`,\n    initialState: initialState as SubscriptionState,\n    reducers: {\n      subscriptionsUpdated: {\n        reducer(state, action: PayloadAction<Patch[]>) {\n          return applyPatches(state, action.payload)\n        },\n        prepare: prepareAutoBatched<Patch[]>(),\n      },\n    },\n  })\n\n  const configSlice = createSlice({\n    name: `${reducerPath}/config`,\n    initialState: {\n      online: isOnline(),\n      focused: isDocumentVisible(),\n      middlewareRegistered: false,\n      ...config,\n    } as ConfigState<string>,\n    reducers: {\n      middlewareRegistered(state, { payload }: PayloadAction<string>) {\n        state.middlewareRegistered =\n          state.middlewareRegistered === 'conflict' || apiUid !== payload\n            ? 'conflict'\n            : true\n      },\n    },\n    extraReducers: (builder) => {\n      builder\n        .addCase(onOnline, (state) => {\n          state.online = true\n        })\n        .addCase(onOffline, (state) => {\n          state.online = false\n        })\n        .addCase(onFocus, (state) => {\n          state.focused = true\n        })\n        .addCase(onFocusLost, (state) => {\n          state.focused = false\n        })\n        // update the state to be a new object to be picked up as a \"state change\"\n        // by redux-persist's `autoMergeLevel2`\n        .addMatcher(hasRehydrationInfo, (draft) => ({ ...draft }))\n    },\n  })\n\n  const combinedReducer = combineReducers({\n    queries: querySlice.reducer,\n    mutations: mutationSlice.reducer,\n    provided: invalidationSlice.reducer,\n    subscriptions: internalSubscriptionsSlice.reducer,\n    config: configSlice.reducer,\n  })\n\n  const reducer: typeof combinedReducer = (state, action) =>\n    combinedReducer(resetApiState.match(action) ? undefined : state, action)\n\n  const actions = {\n    ...configSlice.actions,\n    ...querySlice.actions,\n    ...subscriptionSlice.actions,\n    ...internalSubscriptionsSlice.actions,\n    ...mutationSlice.actions,\n    ...invalidationSlice.actions,\n    resetApiState,\n  }\n\n  return { reducer, actions }\n}\nexport type SliceActions = ReturnType<typeof buildSlice>['actions']\n"
  },
  {
    "path": "packages/toolkit/src/query/core/buildThunks.ts",
    "content": "import type {\n  AsyncThunk,\n  AsyncThunkPayloadCreator,\n  Draft,\n  ThunkAction,\n  ThunkDispatch,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport type { Patch } from 'immer'\nimport { isDraftable, produceWithPatches } from '../utils/immerImports'\nimport type { Api, ApiContext } from '../apiTypes'\nimport type {\n  BaseQueryError,\n  BaseQueryFn,\n  QueryReturnValue,\n} from '../baseQueryTypes'\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\nimport type {\n  AssertTagTypes,\n  EndpointDefinition,\n  EndpointDefinitions,\n  InfiniteQueryArgFrom,\n  InfiniteQueryCombinedArg,\n  InfiniteQueryDefinition,\n  MutationDefinition,\n  PageParamFrom,\n  QueryArgFrom,\n  QueryDefinition,\n  ResultDescription,\n  ResultTypeFrom,\n  SchemaFailureConverter,\n  SchemaFailureHandler,\n  SchemaFailureInfo,\n  SchemaType,\n} from '../endpointDefinitions'\nimport {\n  calculateProvidedBy,\n  ENDPOINT_QUERY,\n  isInfiniteQueryDefinition,\n  isQueryDefinition,\n} from '../endpointDefinitions'\nimport { HandledError } from '../HandledError'\nimport type { UnwrapPromise } from '../tsHelpers'\nimport type {\n  RootState,\n  QueryKeys,\n  QuerySubstateIdentifier,\n  InfiniteData,\n  InfiniteQueryConfigOptions,\n  QueryCacheKey,\n  InfiniteQueryDirection,\n  InfiniteQueryKeys,\n} from './apiState'\nimport { QueryStatus, STATUS_UNINITIALIZED } from './apiState'\nimport type {\n  InfiniteQueryActionCreatorResult,\n  QueryActionCreatorResult,\n  StartInfiniteQueryActionCreatorOptions,\n  StartQueryActionCreatorOptions,\n} from './buildInitiate'\nimport { forceQueryFnSymbol, isUpsertQuery } from './buildInitiate'\nimport type { AllSelectors } from './buildSelectors'\nimport type { ApiEndpointQuery, PrefetchOptions } from './module'\nimport {\n  createAsyncThunk,\n  isAllOf,\n  isFulfilled,\n  isPending,\n  isRejected,\n  isRejectedWithValue,\n  SHOULD_AUTOBATCH,\n} from './rtkImports'\nimport {\n  parseWithSchema,\n  NamedSchemaError,\n  shouldSkip,\n} from '../standardSchema'\n\nexport type BuildThunksApiEndpointQuery<\n  Definition extends QueryDefinition<any, any, any, any, any>,\n> = Matchers<QueryThunk, Definition>\n\nexport type BuildThunksApiEndpointInfiniteQuery<\n  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = Matchers<InfiniteQueryThunk<any>, Definition>\n\nexport type BuildThunksApiEndpointMutation<\n  Definition extends MutationDefinition<any, any, any, any, any>,\n> = Matchers<MutationThunk, Definition>\n\ntype EndpointThunk<\n  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,\n  Definition extends EndpointDefinition<any, any, any, any>,\n> =\n  Definition extends EndpointDefinition<\n    infer QueryArg,\n    infer BaseQueryFn,\n    any,\n    infer ResultType\n  >\n    ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig>\n      ? AsyncThunk<\n          ResultType,\n          ATArg & { originalArgs: QueryArg },\n          ATConfig & { rejectValue: BaseQueryError<BaseQueryFn> }\n        >\n      : never\n    : Definition extends InfiniteQueryDefinition<\n          infer QueryArg,\n          infer PageParam,\n          infer BaseQueryFn,\n          any,\n          infer ResultType\n        >\n      ? Thunk extends AsyncThunk<unknown, infer ATArg, infer ATConfig>\n        ? AsyncThunk<\n            InfiniteData<ResultType, PageParam>,\n            ATArg & { originalArgs: QueryArg },\n            ATConfig & { rejectValue: BaseQueryError<BaseQueryFn> }\n          >\n        : never\n      : never\n\nexport type PendingAction<\n  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,\n  Definition extends EndpointDefinition<any, any, any, any>,\n> = ReturnType<EndpointThunk<Thunk, Definition>['pending']>\n\nexport type FulfilledAction<\n  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,\n  Definition extends EndpointDefinition<any, any, any, any>,\n> = ReturnType<EndpointThunk<Thunk, Definition>['fulfilled']>\n\nexport type RejectedAction<\n  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,\n  Definition extends EndpointDefinition<any, any, any, any>,\n> = ReturnType<EndpointThunk<Thunk, Definition>['rejected']>\n\nexport type Matcher<M> = (value: any) => value is M\n\nexport interface Matchers<\n  Thunk extends QueryThunk | MutationThunk | InfiniteQueryThunk<any>,\n  Definition extends EndpointDefinition<any, any, any, any>,\n> {\n  matchPending: Matcher<PendingAction<Thunk, Definition>>\n  matchFulfilled: Matcher<FulfilledAction<Thunk, Definition>>\n  matchRejected: Matcher<RejectedAction<Thunk, Definition>>\n}\n\nexport type QueryThunkArg = QuerySubstateIdentifier &\n  StartQueryActionCreatorOptions & {\n    type: 'query'\n    originalArgs: unknown\n    endpointName: string\n  }\n\nexport type InfiniteQueryThunkArg<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = QuerySubstateIdentifier &\n  StartInfiniteQueryActionCreatorOptions<D> & {\n    type: `query`\n    originalArgs: unknown\n    endpointName: string\n    param: unknown\n    direction?: InfiniteQueryDirection\n    refetchCachedPages?: boolean\n  }\n\ntype MutationThunkArg = {\n  type: 'mutation'\n  originalArgs: unknown\n  endpointName: string\n  track?: boolean\n  fixedCacheKey?: string\n}\n\nexport type ThunkResult = unknown\n\nexport type ThunkApiMetaConfig = {\n  pendingMeta: { startedTimeStamp: number; [SHOULD_AUTOBATCH]: true }\n  fulfilledMeta: {\n    fulfilledTimeStamp: number\n    baseQueryMeta: unknown\n    [SHOULD_AUTOBATCH]: true\n  }\n  rejectedMeta: { baseQueryMeta: unknown; [SHOULD_AUTOBATCH]: true }\n}\nexport type QueryThunk = AsyncThunk<\n  ThunkResult,\n  QueryThunkArg,\n  ThunkApiMetaConfig\n>\nexport type InfiniteQueryThunk<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = AsyncThunk<ThunkResult, InfiniteQueryThunkArg<D>, ThunkApiMetaConfig>\nexport type MutationThunk = AsyncThunk<\n  ThunkResult,\n  MutationThunkArg,\n  ThunkApiMetaConfig\n>\n\nfunction defaultTransformResponse(baseQueryReturnValue: unknown) {\n  return baseQueryReturnValue\n}\n\nexport type MaybeDrafted<T> = T | Draft<T>\nexport type Recipe<T> = (data: MaybeDrafted<T>) => void | MaybeDrafted<T>\nexport type UpsertRecipe<T> = (\n  data: MaybeDrafted<T> | undefined,\n) => void | MaybeDrafted<T>\n\nexport type PatchQueryDataThunk<\n  Definitions extends EndpointDefinitions,\n  PartialState,\n> = <EndpointName extends QueryKeys<Definitions>>(\n  endpointName: EndpointName,\n  arg: QueryArgFrom<Definitions[EndpointName]>,\n  patches: readonly Patch[],\n  updateProvided?: boolean,\n) => ThunkAction<void, PartialState, any, UnknownAction>\n\nexport type AllQueryKeys<Definitions extends EndpointDefinitions> =\n  | QueryKeys<Definitions>\n  | InfiniteQueryKeys<Definitions>\n\nexport type QueryArgFromAnyQueryDefinition<\n  Definitions extends EndpointDefinitions,\n  EndpointName extends AllQueryKeys<Definitions>,\n> =\n  Definitions[EndpointName] extends InfiniteQueryDefinition<\n    any,\n    any,\n    any,\n    any,\n    any\n  >\n    ? InfiniteQueryArgFrom<Definitions[EndpointName]>\n    : Definitions[EndpointName] extends QueryDefinition<any, any, any, any>\n      ? QueryArgFrom<Definitions[EndpointName]>\n      : never\n\nexport type DataFromAnyQueryDefinition<\n  Definitions extends EndpointDefinitions,\n  EndpointName extends AllQueryKeys<Definitions>,\n> =\n  Definitions[EndpointName] extends InfiniteQueryDefinition<\n    any,\n    any,\n    any,\n    any,\n    any\n  >\n    ? InfiniteData<\n        ResultTypeFrom<Definitions[EndpointName]>,\n        PageParamFrom<Definitions[EndpointName]>\n      >\n    : Definitions[EndpointName] extends QueryDefinition<any, any, any, any>\n      ? ResultTypeFrom<Definitions[EndpointName]>\n      : unknown\n\nexport type UpsertThunkResult<\n  Definitions extends EndpointDefinitions,\n  EndpointName extends AllQueryKeys<Definitions>,\n> =\n  Definitions[EndpointName] extends InfiniteQueryDefinition<\n    any,\n    any,\n    any,\n    any,\n    any\n  >\n    ? InfiniteQueryActionCreatorResult<Definitions[EndpointName]>\n    : Definitions[EndpointName] extends QueryDefinition<any, any, any, any>\n      ? QueryActionCreatorResult<Definitions[EndpointName]>\n      : QueryActionCreatorResult<never>\n\nexport type UpdateQueryDataThunk<\n  Definitions extends EndpointDefinitions,\n  PartialState,\n> = <EndpointName extends AllQueryKeys<Definitions>>(\n  endpointName: EndpointName,\n  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>,\n  updateRecipe: Recipe<DataFromAnyQueryDefinition<Definitions, EndpointName>>,\n  updateProvided?: boolean,\n) => ThunkAction<PatchCollection, PartialState, any, UnknownAction>\n\nexport type UpsertQueryDataThunk<\n  Definitions extends EndpointDefinitions,\n  PartialState,\n> = <EndpointName extends AllQueryKeys<Definitions>>(\n  endpointName: EndpointName,\n  arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>,\n  value: DataFromAnyQueryDefinition<Definitions, EndpointName>,\n) => ThunkAction<\n  UpsertThunkResult<Definitions, EndpointName>,\n  PartialState,\n  any,\n  UnknownAction\n>\n\n/**\n * An object returned from dispatching a `api.util.updateQueryData` call.\n */\nexport type PatchCollection = {\n  /**\n   * An `immer` Patch describing the cache update.\n   */\n  patches: Patch[]\n  /**\n   * An `immer` Patch to revert the cache update.\n   */\n  inversePatches: Patch[]\n  /**\n   * A function that will undo the cache update.\n   */\n  undo: () => void\n}\n\ntype TransformCallback = (\n  baseQueryReturnValue: unknown,\n  meta: unknown,\n  arg: unknown,\n) => any\n\nexport const addShouldAutoBatch = <T extends Record<string, any>>(\n  arg: T = {} as T,\n): T & { [SHOULD_AUTOBATCH]: true } => {\n  return { ...arg, [SHOULD_AUTOBATCH]: true }\n}\n\nexport function buildThunks<\n  BaseQuery extends BaseQueryFn,\n  ReducerPath extends string,\n  Definitions extends EndpointDefinitions,\n>({\n  reducerPath,\n  baseQuery,\n  context: { endpointDefinitions },\n  serializeQueryArgs,\n  api,\n  assertTagType,\n  selectors,\n  onSchemaFailure,\n  catchSchemaFailure: globalCatchSchemaFailure,\n  skipSchemaValidation: globalSkipSchemaValidation,\n}: {\n  baseQuery: BaseQuery\n  reducerPath: ReducerPath\n  context: ApiContext<Definitions>\n  serializeQueryArgs: InternalSerializeQueryArgs\n  api: Api<BaseQuery, Definitions, ReducerPath, any>\n  assertTagType: AssertTagTypes\n  selectors: AllSelectors\n  onSchemaFailure: SchemaFailureHandler | undefined\n  catchSchemaFailure: SchemaFailureConverter<BaseQuery> | undefined\n  skipSchemaValidation: boolean | SchemaType[] | undefined\n}) {\n  type State = RootState<any, string, ReducerPath>\n\n  const patchQueryData: PatchQueryDataThunk<EndpointDefinitions, State> =\n    (endpointName, arg, patches, updateProvided) => (dispatch, getState) => {\n      const endpointDefinition = endpointDefinitions[endpointName]\n\n      const queryCacheKey = serializeQueryArgs({\n        queryArgs: arg,\n        endpointDefinition,\n        endpointName,\n      })\n\n      dispatch(\n        api.internalActions.queryResultPatched({ queryCacheKey, patches }),\n      )\n\n      if (!updateProvided) {\n        return\n      }\n\n      const newValue = api.endpoints[endpointName].select(arg)(\n        // Work around TS 4.1 mismatch\n        getState() as RootState<any, any, any>,\n      )\n\n      const providedTags = calculateProvidedBy(\n        endpointDefinition.providesTags,\n        newValue.data,\n        undefined,\n        arg,\n        {},\n        assertTagType,\n      )\n\n      dispatch(\n        api.internalActions.updateProvidedBy([{ queryCacheKey, providedTags }]),\n      )\n    }\n\n  function addToStart<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [item, ...items]\n    return max && newItems.length > max ? newItems.slice(0, -1) : newItems\n  }\n\n  function addToEnd<T>(items: Array<T>, item: T, max = 0): Array<T> {\n    const newItems = [...items, item]\n    return max && newItems.length > max ? newItems.slice(1) : newItems\n  }\n\n  const updateQueryData: UpdateQueryDataThunk<EndpointDefinitions, State> =\n    (endpointName, arg, updateRecipe, updateProvided = true) =>\n    (dispatch, getState) => {\n      const endpointDefinition = api.endpoints[endpointName]\n\n      const currentState = endpointDefinition.select(arg)(\n        // Work around TS 4.1 mismatch\n        getState() as RootState<any, any, any>,\n      )\n\n      const ret: PatchCollection = {\n        patches: [],\n        inversePatches: [],\n        undo: () =>\n          dispatch(\n            api.util.patchQueryData(\n              endpointName,\n              arg,\n              ret.inversePatches,\n              updateProvided,\n            ),\n          ),\n      }\n      if (currentState.status === STATUS_UNINITIALIZED) {\n        return ret\n      }\n      let newValue\n      if ('data' in currentState) {\n        if (isDraftable(currentState.data)) {\n          const [value, patches, inversePatches] = produceWithPatches(\n            currentState.data,\n            updateRecipe,\n          )\n          ret.patches.push(...patches)\n          ret.inversePatches.push(...inversePatches)\n          newValue = value\n        } else {\n          newValue = updateRecipe(currentState.data)\n          ret.patches.push({ op: 'replace', path: [], value: newValue })\n          ret.inversePatches.push({\n            op: 'replace',\n            path: [],\n            value: currentState.data,\n          })\n        }\n      }\n\n      if (ret.patches.length === 0) {\n        return ret\n      }\n\n      dispatch(\n        api.util.patchQueryData(endpointName, arg, ret.patches, updateProvided),\n      )\n\n      return ret\n    }\n\n  const upsertQueryData: UpsertQueryDataThunk<Definitions, State> =\n    (endpointName, arg, value) => (dispatch) => {\n      type EndpointName = typeof endpointName\n      const res = dispatch(\n        (\n          api.endpoints[endpointName] as ApiEndpointQuery<\n            QueryDefinition<any, any, any, any, any>,\n            Definitions\n          >\n        ).initiate(arg, {\n          subscribe: false,\n          forceRefetch: true,\n          [forceQueryFnSymbol]: () => ({ data: value }),\n        }),\n      ) as UpsertThunkResult<Definitions, EndpointName>\n\n      return res\n    }\n\n  const getTransformCallbackForEndpoint = (\n    endpointDefinition: EndpointDefinition<any, any, any, any>,\n    transformFieldName: 'transformResponse' | 'transformErrorResponse',\n  ): TransformCallback => {\n    return endpointDefinition.query && endpointDefinition[transformFieldName]\n      ? (endpointDefinition[transformFieldName]! as TransformCallback)\n      : defaultTransformResponse\n  }\n\n  // The generic async payload function for all of our thunks\n  const executeEndpoint: AsyncThunkPayloadCreator<\n    ThunkResult,\n    QueryThunkArg | MutationThunkArg | InfiniteQueryThunkArg<any>,\n    ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }\n  > = async (\n    arg,\n    {\n      signal,\n      abort,\n      rejectWithValue,\n      fulfillWithValue,\n      dispatch,\n      getState,\n      extra,\n    },\n  ) => {\n    const endpointDefinition = endpointDefinitions[arg.endpointName]\n    const { metaSchema, skipSchemaValidation = globalSkipSchemaValidation } =\n      endpointDefinition\n\n    const isQuery = arg.type === ENDPOINT_QUERY\n\n    try {\n      let transformResponse: TransformCallback = defaultTransformResponse\n\n      const baseQueryApi = {\n        signal,\n        abort,\n        dispatch,\n        getState,\n        extra,\n        endpoint: arg.endpointName,\n        type: arg.type,\n        forced: isQuery ? isForcedQuery(arg, getState()) : undefined,\n        queryCacheKey: isQuery ? arg.queryCacheKey : undefined,\n      }\n\n      const forceQueryFn = isQuery ? arg[forceQueryFnSymbol] : undefined\n\n      let finalQueryReturnValue: QueryReturnValue\n\n      // Infinite query wrapper, which executes the request and returns\n      // the InfiniteData `{pages, pageParams}` structure\n      const fetchPage = async (\n        data: InfiniteData<unknown, unknown>,\n        param: unknown,\n        maxPages: number,\n        previous?: boolean,\n      ): Promise<QueryReturnValue> => {\n        // This should handle cases where there is no `getPrevPageParam`,\n        // or `getPPP` returned nullish\n        if (param == null && data.pages.length) {\n          return Promise.resolve({ data })\n        }\n\n        const finalQueryArg: InfiniteQueryCombinedArg<any, any> = {\n          queryArg: arg.originalArgs,\n          pageParam: param,\n        }\n\n        const pageResponse = await executeRequest(finalQueryArg)\n\n        const addTo = previous ? addToStart : addToEnd\n\n        return {\n          data: {\n            pages: addTo(data.pages, pageResponse.data, maxPages),\n            pageParams: addTo(data.pageParams, param, maxPages),\n          },\n          meta: pageResponse.meta,\n        }\n      }\n\n      // Wrapper for executing either `query` or `queryFn`,\n      // and handling any errors\n      async function executeRequest(\n        finalQueryArg: unknown,\n      ): Promise<QueryReturnValue> {\n        let result: QueryReturnValue\n        const { extraOptions, argSchema, rawResponseSchema, responseSchema } =\n          endpointDefinition\n\n        if (argSchema && !shouldSkip(skipSchemaValidation, 'arg')) {\n          finalQueryArg = await parseWithSchema(\n            argSchema,\n            finalQueryArg,\n            'argSchema',\n            {}, // we don't have a meta yet, so we can't pass it\n          )\n        }\n\n        if (forceQueryFn) {\n          // upsertQueryData relies on this to pass in the user-provided value\n          result = forceQueryFn()\n        } else if (endpointDefinition.query) {\n          // We should only run `transformResponse` when the endpoint has a `query` method,\n          // and we're not doing an `upsertQueryData`.\n          transformResponse = getTransformCallbackForEndpoint(\n            endpointDefinition,\n            'transformResponse',\n          )\n\n          result = await baseQuery(\n            endpointDefinition.query(finalQueryArg as any),\n            baseQueryApi,\n            extraOptions as any,\n          )\n        } else {\n          result = await endpointDefinition.queryFn(\n            finalQueryArg as any,\n            baseQueryApi,\n            extraOptions as any,\n            (arg) => baseQuery(arg, baseQueryApi, extraOptions as any),\n          )\n        }\n\n        if (\n          typeof process !== 'undefined' &&\n          process.env.NODE_ENV === 'development'\n        ) {\n          const what = endpointDefinition.query ? '`baseQuery`' : '`queryFn`'\n          let err: undefined | string\n          if (!result) {\n            err = `${what} did not return anything.`\n          } else if (typeof result !== 'object') {\n            err = `${what} did not return an object.`\n          } else if (result.error && result.data) {\n            err = `${what} returned an object containing both \\`error\\` and \\`result\\`.`\n          } else if (result.error === undefined && result.data === undefined) {\n            err = `${what} returned an object containing neither a valid \\`error\\` and \\`result\\`. At least one of them should not be \\`undefined\\``\n          } else {\n            for (const key of Object.keys(result)) {\n              if (key !== 'error' && key !== 'data' && key !== 'meta') {\n                err = `The object returned by ${what} has the unknown property ${key}.`\n                break\n              }\n            }\n          }\n          if (err) {\n            console.error(\n              `Error encountered handling the endpoint ${arg.endpointName}.\n                  ${err}\n                  It needs to return an object with either the shape \\`{ data: <value> }\\` or \\`{ error: <value> }\\` that may contain an optional \\`meta\\` property.\n                  Object returned was:`,\n              result,\n            )\n          }\n        }\n\n        if (result.error) throw new HandledError(result.error, result.meta)\n\n        let { data } = result\n\n        if (\n          rawResponseSchema &&\n          !shouldSkip(skipSchemaValidation, 'rawResponse')\n        ) {\n          data = await parseWithSchema(\n            rawResponseSchema,\n            result.data,\n            'rawResponseSchema',\n            result.meta,\n          )\n        }\n\n        let transformedResponse = await transformResponse(\n          data,\n          result.meta,\n          finalQueryArg,\n        )\n\n        if (responseSchema && !shouldSkip(skipSchemaValidation, 'response')) {\n          transformedResponse = await parseWithSchema(\n            responseSchema,\n            transformedResponse,\n            'responseSchema',\n            result.meta,\n          )\n        }\n\n        return {\n          ...result,\n          data: transformedResponse,\n        }\n      }\n\n      if (isQuery && 'infiniteQueryOptions' in endpointDefinition) {\n        // This is an infinite query endpoint\n        const { infiniteQueryOptions } = endpointDefinition\n\n        // Runtime checks should guarantee this is a positive number if provided\n        const { maxPages = Infinity } = infiniteQueryOptions\n\n        // Priority: per-call override > endpoint config > default (true)\n        const refetchCachedPages =\n          (arg as InfiniteQueryThunkArg<any>).refetchCachedPages ??\n          infiniteQueryOptions.refetchCachedPages ??\n          true\n\n        let result: QueryReturnValue\n\n        // Start by looking up the existing InfiniteData value from state,\n        // falling back to an empty value if it doesn't exist yet\n        const blankData = { pages: [], pageParams: [] }\n        const cachedData = selectors.selectQueryEntry(\n          getState(),\n          arg.queryCacheKey,\n        )?.data as InfiniteData<unknown, unknown> | undefined\n\n        // When the arg changes or the user forces a refetch,\n        // we don't include the `direction` flag. This lets us distinguish\n        // between actually refetching with a forced query, vs just fetching\n        // the next page.\n        const isForcedQueryNeedingRefetch = // arg.forceRefetch\n          isForcedQuery(arg, getState()) &&\n          !(arg as InfiniteQueryThunkArg<any>).direction\n        const existingData = (\n          isForcedQueryNeedingRefetch || !cachedData ? blankData : cachedData\n        ) as InfiniteData<unknown, unknown>\n\n        // If the thunk specified a direction and we do have at least one page,\n        // fetch the next or previous page\n        if ('direction' in arg && arg.direction && existingData.pages.length) {\n          const previous = arg.direction === 'backward'\n          const pageParamFn = previous ? getPreviousPageParam : getNextPageParam\n          const param = pageParamFn(\n            infiniteQueryOptions,\n            existingData,\n            arg.originalArgs,\n          )\n\n          result = await fetchPage(existingData, param, maxPages, previous)\n        } else {\n          // Otherwise, fetch the first page and then any remaining pages\n\n          const { initialPageParam = infiniteQueryOptions.initialPageParam } =\n            arg as InfiniteQueryThunkArg<any>\n\n          // If we're doing a refetch, we should start from\n          // the first page we have cached.\n          // Otherwise, we should start from the initialPageParam\n          const cachedPageParams = cachedData?.pageParams ?? []\n          const firstPageParam = cachedPageParams[0] ?? initialPageParam\n          const totalPages = cachedPageParams.length\n\n          // Fetch first page\n          result = await fetchPage(existingData, firstPageParam, maxPages)\n\n          if (forceQueryFn) {\n            // HACK `upsertQueryData` expects the user to pass in the `{pages, pageParams}` structure,\n            // but `fetchPage` treats that as `pages[0]`. We have to manually un-nest it.\n            result = {\n              data: (result.data as InfiniteData<unknown, unknown>).pages[0],\n            } as QueryReturnValue\n          }\n\n          if (refetchCachedPages) {\n            // Fetch remaining pages\n            for (let i = 1; i < totalPages; i++) {\n              const param = getNextPageParam(\n                infiniteQueryOptions,\n                result.data as InfiniteData<unknown, unknown>,\n                arg.originalArgs,\n              )\n              result = await fetchPage(\n                result.data as InfiniteData<unknown, unknown>,\n                param,\n                maxPages,\n              )\n            }\n          }\n        }\n\n        finalQueryReturnValue = result\n      } else {\n        // Non-infinite endpoint. Just run the one request.\n        finalQueryReturnValue = await executeRequest(arg.originalArgs)\n      }\n\n      if (\n        metaSchema &&\n        !shouldSkip(skipSchemaValidation, 'meta') &&\n        finalQueryReturnValue.meta\n      ) {\n        finalQueryReturnValue.meta = await parseWithSchema(\n          metaSchema,\n          finalQueryReturnValue.meta,\n          'metaSchema',\n          finalQueryReturnValue.meta,\n        )\n      }\n\n      // console.log('Final result: ', transformedData)\n      return fulfillWithValue(\n        finalQueryReturnValue.data,\n        addShouldAutoBatch({\n          fulfilledTimeStamp: Date.now(),\n          baseQueryMeta: finalQueryReturnValue.meta,\n        }),\n      )\n    } catch (error) {\n      let caughtError = error\n      if (caughtError instanceof HandledError) {\n        let transformErrorResponse = getTransformCallbackForEndpoint(\n          endpointDefinition,\n          'transformErrorResponse',\n        )\n        const { rawErrorResponseSchema, errorResponseSchema } =\n          endpointDefinition\n\n        let { value, meta } = caughtError\n\n        try {\n          if (\n            rawErrorResponseSchema &&\n            !shouldSkip(skipSchemaValidation, 'rawErrorResponse')\n          ) {\n            value = await parseWithSchema(\n              rawErrorResponseSchema,\n              value,\n              'rawErrorResponseSchema',\n              meta,\n            )\n          }\n\n          if (metaSchema && !shouldSkip(skipSchemaValidation, 'meta')) {\n            meta = await parseWithSchema(metaSchema, meta, 'metaSchema', meta)\n          }\n          let transformedErrorResponse = await transformErrorResponse(\n            value,\n            meta,\n            arg.originalArgs,\n          )\n          if (\n            errorResponseSchema &&\n            !shouldSkip(skipSchemaValidation, 'errorResponse')\n          ) {\n            transformedErrorResponse = await parseWithSchema(\n              errorResponseSchema,\n              transformedErrorResponse,\n              'errorResponseSchema',\n              meta,\n            )\n          }\n\n          return rejectWithValue(\n            transformedErrorResponse,\n            addShouldAutoBatch({ baseQueryMeta: meta }),\n          )\n        } catch (e) {\n          caughtError = e\n        }\n      }\n      try {\n        if (caughtError instanceof NamedSchemaError) {\n          const info: SchemaFailureInfo = {\n            endpoint: arg.endpointName,\n            arg: arg.originalArgs,\n            type: arg.type,\n            queryCacheKey: isQuery ? arg.queryCacheKey : undefined,\n          }\n          endpointDefinition.onSchemaFailure?.(caughtError, info)\n          onSchemaFailure?.(caughtError, info)\n          const { catchSchemaFailure = globalCatchSchemaFailure } =\n            endpointDefinition\n          if (catchSchemaFailure) {\n            return rejectWithValue(\n              catchSchemaFailure(caughtError, info),\n              addShouldAutoBatch({ baseQueryMeta: caughtError._bqMeta }),\n            )\n          }\n        }\n      } catch (e) {\n        caughtError = e\n      }\n      if (\n        typeof process !== 'undefined' &&\n        process.env.NODE_ENV !== 'production'\n      ) {\n        console.error(\n          `An unhandled error occurred processing a request for the endpoint \"${arg.endpointName}\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n          caughtError,\n        )\n      } else {\n        console.error(caughtError)\n      }\n      throw caughtError\n    }\n  }\n\n  function isForcedQuery(\n    arg: QueryThunkArg,\n    state: RootState<any, string, ReducerPath>,\n  ) {\n    const requestState = selectors.selectQueryEntry(state, arg.queryCacheKey)\n    const baseFetchOnMountOrArgChange =\n      selectors.selectConfig(state).refetchOnMountOrArgChange\n\n    const fulfilledVal = requestState?.fulfilledTimeStamp\n    const refetchVal =\n      arg.forceRefetch ?? (arg.subscribe && baseFetchOnMountOrArgChange)\n\n    if (refetchVal) {\n      // Return if it's true or compare the dates because it must be a number\n      return (\n        refetchVal === true ||\n        (Number(new Date()) - Number(fulfilledVal)) / 1000 >= refetchVal\n      )\n    }\n    return false\n  }\n\n  const createQueryThunk = <\n    ThunkArgType extends QueryThunkArg | InfiniteQueryThunkArg<any>,\n  >() => {\n    const generatedQueryThunk = createAsyncThunk<\n      ThunkResult,\n      ThunkArgType,\n      ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }\n    >(`${reducerPath}/executeQuery`, executeEndpoint, {\n      getPendingMeta({ arg }) {\n        const endpointDefinition = endpointDefinitions[arg.endpointName]\n        return addShouldAutoBatch({\n          startedTimeStamp: Date.now(),\n          ...(isInfiniteQueryDefinition(endpointDefinition)\n            ? { direction: (arg as InfiniteQueryThunkArg<any>).direction }\n            : {}),\n        })\n      },\n      condition(queryThunkArg, { getState }) {\n        const state = getState()\n\n        const requestState = selectors.selectQueryEntry(\n          state,\n          queryThunkArg.queryCacheKey,\n        )\n        const fulfilledVal = requestState?.fulfilledTimeStamp\n        const currentArg = queryThunkArg.originalArgs\n        const previousArg = requestState?.originalArgs\n        const endpointDefinition =\n          endpointDefinitions[queryThunkArg.endpointName]\n        const direction = (queryThunkArg as InfiniteQueryThunkArg<any>)\n          .direction\n\n        // Order of these checks matters.\n        // In order for `upsertQueryData` to successfully run while an existing request is in flight,\n        /// we have to check for that first, otherwise `queryThunk` will bail out and not run at all.\n        if (isUpsertQuery(queryThunkArg)) {\n          return true\n        }\n\n        // Don't retry a request that's currently in-flight\n        if (requestState?.status === 'pending') {\n          return false\n        }\n\n        // if this is forced, continue\n        if (isForcedQuery(queryThunkArg, state)) {\n          return true\n        }\n\n        if (\n          isQueryDefinition(endpointDefinition) &&\n          endpointDefinition?.forceRefetch?.({\n            currentArg,\n            previousArg,\n            endpointState: requestState,\n            state,\n          })\n        ) {\n          return true\n        }\n\n        // Pull from the cache unless we explicitly force refetch or qualify based on time\n        if (fulfilledVal && !direction) {\n          // Value is cached and we didn't specify to refresh, skip it.\n          return false\n        }\n\n        return true\n      },\n      dispatchConditionRejection: true,\n    })\n    return generatedQueryThunk\n  }\n\n  const queryThunk = createQueryThunk<QueryThunkArg>()\n  const infiniteQueryThunk = createQueryThunk<InfiniteQueryThunkArg<any>>()\n\n  const mutationThunk = createAsyncThunk<\n    ThunkResult,\n    MutationThunkArg,\n    ThunkApiMetaConfig & { state: RootState<any, string, ReducerPath> }\n  >(`${reducerPath}/executeMutation`, executeEndpoint, {\n    getPendingMeta() {\n      return addShouldAutoBatch({ startedTimeStamp: Date.now() })\n    },\n  })\n\n  const hasTheForce = (options: any): options is { force: boolean } =>\n    'force' in options\n  const hasMaxAge = (\n    options: any,\n  ): options is { ifOlderThan: false | number } => 'ifOlderThan' in options\n\n  const prefetch =\n    <EndpointName extends QueryKeys<Definitions>>(\n      endpointName: EndpointName,\n      arg: any,\n      options: PrefetchOptions = {},\n    ): ThunkAction<void, any, any, UnknownAction> =>\n    (dispatch: ThunkDispatch<any, any, any>, getState: () => any) => {\n      const force = hasTheForce(options) && options.force\n      const maxAge = hasMaxAge(options) && options.ifOlderThan\n\n      const queryAction = (force: boolean = true) => {\n        const options: StartQueryActionCreatorOptions = {\n          forceRefetch: force,\n          subscribe: false,\n        }\n        return (\n          api.endpoints[endpointName] as ApiEndpointQuery<any, any>\n        ).initiate(arg, options)\n      }\n      const latestStateValue = (\n        api.endpoints[endpointName] as ApiEndpointQuery<any, any>\n      ).select(arg)(getState())\n\n      if (force) {\n        dispatch(queryAction())\n      } else if (maxAge) {\n        const lastFulfilledTs = latestStateValue?.fulfilledTimeStamp\n        if (!lastFulfilledTs) {\n          dispatch(queryAction())\n          return\n        }\n        const shouldRetrigger =\n          (Number(new Date()) - Number(new Date(lastFulfilledTs))) / 1000 >=\n          maxAge\n        if (shouldRetrigger) {\n          dispatch(queryAction())\n        }\n      } else {\n        // If prefetching with no options, just let it try\n        dispatch(queryAction(false))\n      }\n    }\n\n  function matchesEndpoint(endpointName: string) {\n    return (action: any): action is UnknownAction =>\n      action?.meta?.arg?.endpointName === endpointName\n  }\n\n  function buildMatchThunkActions<\n    Thunk extends\n      | AsyncThunk<any, QueryThunkArg, ThunkApiMetaConfig>\n      | AsyncThunk<any, MutationThunkArg, ThunkApiMetaConfig>,\n  >(thunk: Thunk, endpointName: string) {\n    return {\n      matchPending: isAllOf(isPending(thunk), matchesEndpoint(endpointName)),\n      matchFulfilled: isAllOf(\n        isFulfilled(thunk),\n        matchesEndpoint(endpointName),\n      ),\n      matchRejected: isAllOf(isRejected(thunk), matchesEndpoint(endpointName)),\n    } as Matchers<Thunk, any>\n  }\n\n  return {\n    queryThunk,\n    mutationThunk,\n    infiniteQueryThunk,\n    prefetch,\n    updateQueryData,\n    upsertQueryData,\n    patchQueryData,\n    buildMatchThunkActions,\n  }\n}\n\nexport function getNextPageParam(\n  options: InfiniteQueryConfigOptions<unknown, unknown, unknown>,\n  { pages, pageParams }: InfiniteData<unknown, unknown>,\n  queryArg: unknown,\n): unknown | undefined {\n  const lastIndex = pages.length - 1\n  return options.getNextPageParam(\n    pages[lastIndex],\n    pages,\n    pageParams[lastIndex],\n    pageParams,\n    queryArg,\n  )\n}\n\nexport function getPreviousPageParam(\n  options: InfiniteQueryConfigOptions<unknown, unknown, unknown>,\n  { pages, pageParams }: InfiniteData<unknown, unknown>,\n  queryArg: unknown,\n): unknown | undefined {\n  return options.getPreviousPageParam?.(\n    pages[0],\n    pages,\n    pageParams[0],\n    pageParams,\n    queryArg,\n  )\n}\n\nexport function calculateProvidedByThunk(\n  action: UnwrapPromise<\n    | ReturnType<ReturnType<QueryThunk>>\n    | ReturnType<ReturnType<MutationThunk>>\n    | ReturnType<ReturnType<InfiniteQueryThunk<any>>>\n  >,\n  type: 'providesTags' | 'invalidatesTags',\n  endpointDefinitions: EndpointDefinitions,\n  assertTagType: AssertTagTypes,\n) {\n  return calculateProvidedBy(\n    endpointDefinitions[action.meta.arg.endpointName][\n      type\n    ] as ResultDescription<any, any, any, any, any>,\n    isFulfilled(action) ? action.payload : undefined,\n    isRejectedWithValue(action) ? action.payload : undefined,\n    action.meta.arg.originalArgs,\n    'baseQueryMeta' in action.meta ? action.meta.baseQueryMeta : undefined,\n    assertTagType,\n  )\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/core/index.ts",
    "content": "import { buildCreateApi } from '../createApi'\nimport { coreModule } from './module'\n\nexport const createApi = /* @__PURE__ */ buildCreateApi(coreModule())\n\nexport { QueryStatus } from './apiState'\nexport type {\n  CombinedState,\n  InfiniteData,\n  InfiniteQueryConfigOptions,\n  InfiniteQuerySubState,\n  MutationKeys,\n  QueryCacheKey,\n  QueryKeys,\n  QuerySubState,\n  RootState,\n  SubscriptionOptions,\n} from './apiState'\nexport type {\n  InfiniteQueryActionCreatorResult,\n  MutationActionCreatorResult,\n  QueryActionCreatorResult,\n  StartQueryActionCreatorOptions,\n} from './buildInitiate'\nexport type {\n  MutationCacheLifecycleApi,\n  MutationLifecycleApi,\n  QueryCacheLifecycleApi,\n  QueryLifecycleApi,\n  SubscriptionSelectors,\n  TypedMutationOnQueryStarted,\n  TypedQueryOnQueryStarted,\n} from './buildMiddleware/index'\nexport { skipToken } from './buildSelectors'\nexport type {\n  InfiniteQueryResultSelectorResult,\n  MutationResultSelectorResult,\n  QueryResultSelectorResult,\n  SkipToken,\n} from './buildSelectors'\nexport type { SliceActions } from './buildSlice'\nexport type {\n  PatchQueryDataThunk,\n  UpdateQueryDataThunk,\n  UpsertQueryDataThunk,\n} from './buildThunks'\nexport { coreModuleName } from './module'\nexport type {\n  ApiEndpointInfiniteQuery,\n  ApiEndpointMutation,\n  ApiEndpointQuery,\n  CoreModule,\n  InternalActions,\n  PrefetchOptions,\n  ThunkWithReturnValue,\n} from './module'\nexport { setupListeners } from './setupListeners'\nexport { buildCreateApi, coreModule }\n"
  },
  {
    "path": "packages/toolkit/src/query/core/module.ts",
    "content": "/**\n * Note: this file should import all other files for type discovery and declaration merging\n */\nimport type {\n  ActionCreatorWithPayload,\n  Dispatch,\n  Middleware,\n  Reducer,\n  ThunkAction,\n  ThunkDispatch,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport { enablePatches } from '../utils/immerImports'\nimport type { Api, Module } from '../apiTypes'\nimport type { BaseQueryFn } from '../baseQueryTypes'\nimport type { InternalSerializeQueryArgs } from '../defaultSerializeQueryArgs'\nimport type {\n  AssertTagTypes,\n  EndpointDefinitions,\n  InfiniteQueryDefinition,\n  MutationDefinition,\n  QueryArgFrom,\n  QueryArgFromAnyQuery,\n  QueryDefinition,\n  TagDescription,\n} from '../endpointDefinitions'\nimport {\n  isInfiniteQueryDefinition,\n  isMutationDefinition,\n  isQueryDefinition,\n} from '../endpointDefinitions'\nimport { assertCast, safeAssign } from '../tsHelpers'\nimport type {\n  CombinedState,\n  MutationKeys,\n  QueryKeys,\n  RootState,\n} from './apiState'\nimport type {\n  BuildInitiateApiEndpointMutation,\n  BuildInitiateApiEndpointQuery,\n  MutationActionCreatorResult,\n  QueryActionCreatorResult,\n  InfiniteQueryActionCreatorResult,\n  BuildInitiateApiEndpointInfiniteQuery,\n} from './buildInitiate'\nimport { buildInitiate } from './buildInitiate'\nimport type {\n  ReferenceCacheCollection,\n  ReferenceCacheLifecycle,\n  ReferenceQueryLifecycle,\n} from './buildMiddleware'\nimport { buildMiddleware } from './buildMiddleware'\nimport type {\n  BuildSelectorsApiEndpointInfiniteQuery,\n  BuildSelectorsApiEndpointMutation,\n  BuildSelectorsApiEndpointQuery,\n} from './buildSelectors'\nimport { buildSelectors } from './buildSelectors'\nimport type { SliceActions, UpsertEntries } from './buildSlice'\nimport { buildSlice } from './buildSlice'\nimport type {\n  AllQueryKeys,\n  BuildThunksApiEndpointInfiniteQuery,\n  BuildThunksApiEndpointMutation,\n  BuildThunksApiEndpointQuery,\n  PatchQueryDataThunk,\n  QueryArgFromAnyQueryDefinition,\n  UpdateQueryDataThunk,\n  UpsertQueryDataThunk,\n} from './buildThunks'\nimport { buildThunks } from './buildThunks'\nimport { createSelector as _createSelector } from './rtkImports'\nimport { onFocus, onFocusLost, onOffline, onOnline } from './setupListeners'\nimport type { InternalMiddlewareState } from './buildMiddleware/types'\nimport { getOrInsertComputed } from '../utils'\nimport type { CreateSelectorFunction } from 'reselect'\n\n/**\n * `ifOlderThan` - (default: `false` | `number`) - _number is value in seconds_\n * - If specified, it will only run the query if the difference between `new Date()` and the last `fulfilledTimeStamp` is greater than the given value\n *\n * @overloadSummary\n * `force`\n * - If `force: true`, it will ignore the `ifOlderThan` value if it is set and the query will be run even if it exists in the cache.\n */\nexport type PrefetchOptions =\n  | {\n      ifOlderThan?: false | number\n    }\n  | { force?: boolean }\n\nexport const coreModuleName = /* @__PURE__ */ Symbol()\nexport type CoreModule =\n  | typeof coreModuleName\n  | ReferenceCacheLifecycle\n  | ReferenceQueryLifecycle\n  | ReferenceCacheCollection\n\nexport type ThunkWithReturnValue<T> = ThunkAction<T, any, any, UnknownAction>\n\nexport interface ApiModules<\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  BaseQuery extends BaseQueryFn,\n  Definitions extends EndpointDefinitions,\n  ReducerPath extends string,\n  TagTypes extends string,\n> {\n  [coreModuleName]: {\n    /**\n     * This api's reducer should be mounted at `store[api.reducerPath]`.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducerPath: ReducerPath\n    /**\n     * Internal actions not part of the public API. Note: These are subject to change at any given time.\n     */\n    internalActions: InternalActions\n    /**\n     *  A standard redux reducer that enables core functionality. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    reducer: Reducer<\n      CombinedState<Definitions, TagTypes, ReducerPath>,\n      UnknownAction\n    >\n    /**\n     * This is a standard redux middleware and is responsible for things like polling, garbage collection and a handful of other things. Make sure it's included in your store.\n     *\n     * @example\n     * ```ts\n     * configureStore({\n     *   reducer: {\n     *     [api.reducerPath]: api.reducer,\n     *   },\n     *   middleware: (getDefaultMiddleware) => getDefaultMiddleware().concat(api.middleware),\n     * })\n     * ```\n     */\n    middleware: Middleware<\n      {},\n      RootState<Definitions, string, ReducerPath>,\n      ThunkDispatch<any, any, UnknownAction>\n    >\n    /**\n     * A collection of utility thunks for various situations.\n     */\n    util: {\n      /**\n       * A thunk that (if dispatched) will return a specific running query, identified\n       * by `endpointName` and `arg`.\n       * If that query is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific query triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueryThunk<EndpointName extends AllQueryKeys<Definitions>>(\n        endpointName: EndpointName,\n        arg: QueryArgFromAnyQueryDefinition<Definitions, EndpointName>,\n      ): ThunkWithReturnValue<\n        | QueryActionCreatorResult<\n            Definitions[EndpointName] & { type: 'query' }\n          >\n        | InfiniteQueryActionCreatorResult<\n            Definitions[EndpointName] & { type: 'infinitequery' }\n          >\n        | undefined\n      >\n\n      /**\n       * A thunk that (if dispatched) will return a specific running mutation, identified\n       * by `endpointName` and `fixedCacheKey` or `requestId`.\n       * If that mutation is not running, dispatching the thunk will result in `undefined`.\n       *\n       * Can be used to await a specific mutation triggered in any way,\n       * including via hook trigger functions or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationThunk<EndpointName extends MutationKeys<Definitions>>(\n        endpointName: EndpointName,\n        fixedCacheKeyOrRequestId: string,\n      ): ThunkWithReturnValue<\n        | MutationActionCreatorResult<\n            Definitions[EndpointName] & { type: 'mutation' }\n          >\n        | undefined\n      >\n\n      /**\n       * A thunk that (if dispatched) will return all running queries.\n       *\n       * Useful for SSR scenarios to await all running queries triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningQueriesThunk(): ThunkWithReturnValue<\n        Array<\n          QueryActionCreatorResult<any> | InfiniteQueryActionCreatorResult<any>\n        >\n      >\n\n      /**\n       * A thunk that (if dispatched) will return all running mutations.\n       *\n       * Useful for SSR scenarios to await all running mutations triggered in any way,\n       * including via hook calls or manually dispatching `initiate` actions.\n       *\n       * See https://redux-toolkit.js.org/rtk-query/usage/server-side-rendering for details.\n       */\n      getRunningMutationsThunk(): ThunkWithReturnValue<\n        Array<MutationActionCreatorResult<any>>\n      >\n\n      /**\n       * A Redux thunk that can be used to manually trigger pre-fetching of data.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a set of options used to determine if the data actually should be re-fetched based on cache staleness.\n       *\n       * React Hooks users will most likely never need to use this directly, as the `usePrefetch` hook will dispatch this thunk internally as needed when you call the prefetching function supplied by the hook.\n       *\n       * @example\n       *\n       * ```ts no-transpile\n       * dispatch(api.util.prefetch('getPosts', undefined, { force: true }))\n       * ```\n       */\n      prefetch<EndpointName extends QueryKeys<Definitions>>(\n        endpointName: EndpointName,\n        arg: QueryArgFrom<Definitions[EndpointName]>,\n        options?: PrefetchOptions,\n      ): ThunkAction<void, any, any, UnknownAction>\n      /**\n       * A Redux thunk action creator that, when dispatched, creates and applies a set of JSON diff/patch objects to the current state. This immediately updates the Redux state with those changes.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and an `updateRecipe` callback function. The callback receives an Immer-wrapped `draft` of the current state, and may modify the draft to match the expected results after the mutation completes successfully.\n       *\n       * The thunk executes _synchronously_, and returns an object containing `{patches: Patch[], inversePatches: Patch[], undo: () => void}`. The `patches` and `inversePatches` are generated using Immer's [`produceWithPatches` method](https://immerjs.github.io/immer/patches).\n       *\n       * This is typically used as the first step in implementing optimistic updates. The generated `inversePatches` can be used to revert the updates by calling `dispatch(patchQueryData(endpointName, arg, inversePatches))`. Alternatively, the `undo` method can be called directly to achieve the same effect.\n       *\n       * Note that the first two arguments (`endpointName` and `arg`) are used to determine which existing cache entry to update. If no existing cache entry is found, the `updateRecipe` callback will not run.\n       *\n       * @example\n       *\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       * ```\n       */\n      updateQueryData: UpdateQueryDataThunk<\n        Definitions,\n        RootState<Definitions, string, ReducerPath>\n      >\n\n      /**\n       * A Redux thunk action creator that, when dispatched, acts as an artificial API request to upsert a value into the cache.\n       *\n       * The thunk action creator accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and the data to upsert.\n       *\n       * If no cache entry for that cache key exists, a cache entry will be created and the data added. If a cache entry already exists, this will _overwrite_ the existing cache entry data.\n       *\n       * The thunk executes _asynchronously_, and returns a promise that resolves when the store has been updated.\n       *\n       * If dispatched while an actual request is in progress, both the upsert and request will be handled as soon as they resolve, resulting in a \"last result wins\" update behavior.\n       *\n       * @example\n       *\n       * ```ts\n       * await dispatch(\n       *   api.util.upsertQueryData('getPost', {id: 1}, {id: 1, text: \"Hello!\"})\n       * )\n       * ```\n       */\n      upsertQueryData: UpsertQueryDataThunk<\n        Definitions,\n        RootState<Definitions, string, ReducerPath>\n      >\n      /**\n       * A Redux thunk that applies a JSON diff/patch array to the cached data for a given query result. This immediately updates the Redux state with those changes.\n       *\n       * The thunk accepts three arguments: the name of the endpoint we are updating (such as `'getPost'`), the appropriate query arg values to construct the desired cache key, and a JSON diff/patch array as produced by Immer's `produceWithPatches`.\n       *\n       * This is typically used as the second step in implementing optimistic updates. If a request fails, the optimistically-applied changes can be reverted by dispatching `patchQueryData` with the `inversePatches` that were generated by `updateQueryData` earlier.\n       *\n       * In cases where it is desired to simply revert the previous changes, it may be preferable to call the `undo` method returned from dispatching `updateQueryData` instead.\n       *\n       * @example\n       * ```ts\n       * const patchCollection = dispatch(\n       *   api.util.updateQueryData('getPosts', undefined, (draftPosts) => {\n       *     draftPosts.push({ id: 1, name: 'Teddy' })\n       *   })\n       * )\n       *\n       * // later\n       * dispatch(\n       *   api.util.patchQueryData('getPosts', undefined, patchCollection.inversePatches)\n       * )\n       *\n       * // or\n       * patchCollection.undo()\n       * ```\n       */\n      patchQueryData: PatchQueryDataThunk<\n        Definitions,\n        RootState<Definitions, string, ReducerPath>\n      >\n\n      /**\n       * A Redux action creator that can be dispatched to manually reset the api state completely. This will immediately remove all existing cache entries, and all queries will be considered 'uninitialized'.\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.resetApiState())\n       * ```\n       */\n      resetApiState: SliceActions['resetApiState']\n\n      upsertQueryEntries: UpsertEntries<Definitions>\n\n      /**\n       * A Redux action creator that can be used to manually invalidate cache tags for [automated re-fetching](../../usage/automated-refetching.mdx).\n       *\n       * The action creator accepts one argument: the cache tags to be invalidated. It returns an action with those tags as a payload, and the corresponding `invalidateTags` action type for the api.\n       *\n       * Dispatching the result of this action creator will [invalidate](../../usage/automated-refetching.mdx#invalidating-cache-data) the given tags, causing queries to automatically re-fetch if they are subscribed to cache data that [provides](../../usage/automated-refetching.mdx#providing-cache-data) the corresponding tags.\n       *\n       * The array of tags provided to the action creator should be in one of the following formats, where `TagType` is equal to a string provided to the [`tagTypes`](../createApi.mdx#tagtypes) property of the api:\n       *\n       * - `[TagType]`\n       * - `[{ type: TagType }]`\n       * - `[{ type: TagType, id: number | string }]`\n       *\n       * @example\n       *\n       * ```ts\n       * dispatch(api.util.invalidateTags(['Post']))\n       * dispatch(api.util.invalidateTags([{ type: 'Post', id: 1 }]))\n       * dispatch(\n       *   api.util.invalidateTags([\n       *     { type: 'Post', id: 1 },\n       *     { type: 'Post', id: 'LIST' },\n       *   ])\n       * )\n       * ```\n       */\n      invalidateTags: ActionCreatorWithPayload<\n        Array<TagDescription<TagTypes> | null | undefined>,\n        string\n      >\n\n      /**\n       * A function to select all `{ endpointName, originalArgs, queryCacheKey }` combinations that would be invalidated by a specific set of tags.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectInvalidatedBy: (\n        state: RootState<Definitions, string, ReducerPath>,\n        tags: ReadonlyArray<TagDescription<TagTypes> | null | undefined>,\n      ) => Array<{\n        endpointName: string\n        originalArgs: any\n        queryCacheKey: string\n      }>\n\n      /**\n       * A function to select all arguments currently cached for a given endpoint.\n       *\n       * Can be used for mutations that want to do optimistic updates instead of invalidating a set of tags, but don't know exactly what they need to update.\n       */\n      selectCachedArgsForQuery: <QueryName extends AllQueryKeys<Definitions>>(\n        state: RootState<Definitions, string, ReducerPath>,\n        queryName: QueryName,\n      ) => Array<QueryArgFromAnyQuery<Definitions[QueryName]>>\n    }\n    /**\n     * Endpoints based on the input endpoints provided to `createApi`, containing `select` and `action matchers`.\n     */\n    endpoints: {\n      [K in keyof Definitions]: Definitions[K] extends QueryDefinition<\n        any,\n        any,\n        any,\n        any,\n        any\n      >\n        ? ApiEndpointQuery<Definitions[K], Definitions>\n        : Definitions[K] extends MutationDefinition<any, any, any, any, any>\n          ? ApiEndpointMutation<Definitions[K], Definitions>\n          : Definitions[K] extends InfiniteQueryDefinition<\n                any,\n                any,\n                any,\n                any,\n                any\n              >\n            ? ApiEndpointInfiniteQuery<Definitions[K], Definitions>\n            : never\n    }\n  }\n}\n\nexport interface ApiEndpointQuery<\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  Definition extends QueryDefinition<any, any, any, any, any>,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  Definitions extends EndpointDefinitions,\n> extends BuildThunksApiEndpointQuery<Definition>,\n    BuildInitiateApiEndpointQuery<Definition>,\n    BuildSelectorsApiEndpointQuery<Definition, Definitions> {\n  name: string\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>\n}\n\nexport interface ApiEndpointInfiniteQuery<\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  Definitions extends EndpointDefinitions,\n> extends BuildThunksApiEndpointInfiniteQuery<Definition>,\n    BuildInitiateApiEndpointInfiniteQuery<Definition>,\n    BuildSelectorsApiEndpointInfiniteQuery<Definition, Definitions> {\n  name: string\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>\n}\n\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nexport interface ApiEndpointMutation<\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  Definition extends MutationDefinition<any, any, any, any, any>,\n  // eslint-disable-next-line @typescript-eslint/no-unused-vars\n  Definitions extends EndpointDefinitions,\n> extends BuildThunksApiEndpointMutation<Definition>,\n    BuildInitiateApiEndpointMutation<Definition>,\n    BuildSelectorsApiEndpointMutation<Definition, Definitions> {\n  name: string\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types: NonNullable<Definition['Types']>\n}\n\nexport type ListenerActions = {\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnReconnect-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onOnline: typeof onOnline\n  onOffline: typeof onOffline\n  /**\n   * Will cause the RTK Query middleware to trigger any refetchOnFocus-related behavior\n   * @link https://redux-toolkit.js.org/rtk-query/api/setupListeners\n   */\n  onFocus: typeof onFocus\n  onFocusLost: typeof onFocusLost\n}\n\nexport type InternalActions = SliceActions & ListenerActions\n\nexport interface CoreModuleOptions {\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>\n}\n\n/**\n * Creates a module containing the basic redux logic for use with `buildCreateApi`.\n *\n * @example\n * ```ts\n * const createBaseApi = buildCreateApi(coreModule());\n * ```\n */\nexport const coreModule = ({\n  createSelector = _createSelector,\n}: CoreModuleOptions = {}): Module<CoreModule> => ({\n  name: coreModuleName,\n  init(\n    api,\n    {\n      baseQuery,\n      tagTypes,\n      reducerPath,\n      serializeQueryArgs,\n      keepUnusedDataFor,\n      refetchOnMountOrArgChange,\n      refetchOnFocus,\n      refetchOnReconnect,\n      invalidationBehavior,\n      onSchemaFailure,\n      catchSchemaFailure,\n      skipSchemaValidation,\n    },\n    context,\n  ) {\n    enablePatches()\n\n    assertCast<InternalSerializeQueryArgs>(serializeQueryArgs)\n\n    const assertTagType: AssertTagTypes = (tag) => {\n      if (\n        typeof process !== 'undefined' &&\n        process.env.NODE_ENV === 'development'\n      ) {\n        if (!tagTypes.includes(tag.type as any)) {\n          console.error(\n            `Tag type '${tag.type}' was used, but not specified in \\`tagTypes\\`!`,\n          )\n        }\n      }\n      return tag\n    }\n\n    Object.assign(api, {\n      reducerPath,\n      endpoints: {},\n      internalActions: {\n        onOnline,\n        onOffline,\n        onFocus,\n        onFocusLost,\n      },\n      util: {},\n    })\n\n    const selectors = buildSelectors({\n      serializeQueryArgs: serializeQueryArgs as any,\n      reducerPath,\n      createSelector,\n    })\n\n    const {\n      selectInvalidatedBy,\n      selectCachedArgsForQuery,\n      buildQuerySelector,\n      buildInfiniteQuerySelector,\n      buildMutationSelector,\n    } = selectors\n\n    safeAssign(api.util, { selectInvalidatedBy, selectCachedArgsForQuery })\n\n    const {\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      buildMatchThunkActions,\n    } = buildThunks({\n      baseQuery,\n      reducerPath,\n      context,\n      api,\n      serializeQueryArgs,\n      assertTagType,\n      selectors,\n      onSchemaFailure,\n      catchSchemaFailure,\n      skipSchemaValidation,\n    })\n\n    const { reducer, actions: sliceActions } = buildSlice({\n      context,\n      queryThunk,\n      infiniteQueryThunk,\n      mutationThunk,\n      serializeQueryArgs,\n      reducerPath,\n      assertTagType,\n      config: {\n        refetchOnFocus,\n        refetchOnReconnect,\n        refetchOnMountOrArgChange,\n        keepUnusedDataFor,\n        reducerPath,\n        invalidationBehavior,\n      },\n    })\n\n    safeAssign(api.util, {\n      patchQueryData,\n      updateQueryData,\n      upsertQueryData,\n      prefetch,\n      resetApiState: sliceActions.resetApiState,\n      upsertQueryEntries: sliceActions.cacheEntriesUpserted as any,\n    })\n    safeAssign(api.internalActions, sliceActions)\n\n    const internalStateMap = new WeakMap<Dispatch, InternalMiddlewareState>()\n\n    const getInternalState = (dispatch: Dispatch) => {\n      const state = getOrInsertComputed(internalStateMap, dispatch, () => ({\n        currentSubscriptions: new Map(),\n        currentPolls: new Map(),\n        runningQueries: new Map(),\n        runningMutations: new Map(),\n      }))\n\n      return state\n    }\n\n    const {\n      buildInitiateQuery,\n      buildInitiateInfiniteQuery,\n      buildInitiateMutation,\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueriesThunk,\n      getRunningQueryThunk,\n    } = buildInitiate({\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      serializeQueryArgs: serializeQueryArgs as any,\n      context,\n      getInternalState,\n    })\n\n    safeAssign(api.util, {\n      getRunningMutationThunk,\n      getRunningMutationsThunk,\n      getRunningQueryThunk,\n      getRunningQueriesThunk,\n    })\n\n    const { middleware, actions: middlewareActions } = buildMiddleware({\n      reducerPath,\n      context,\n      queryThunk,\n      mutationThunk,\n      infiniteQueryThunk,\n      api,\n      assertTagType,\n      selectors,\n      getRunningQueryThunk,\n      getInternalState,\n    })\n    safeAssign(api.util, middlewareActions)\n\n    safeAssign(api, { reducer: reducer as any, middleware })\n\n    return {\n      name: coreModuleName,\n      injectEndpoint(endpointName, definition) {\n        const anyApi = api as any as Api<\n          any,\n          Record<string, any>,\n          string,\n          string,\n          CoreModule\n        >\n        const endpoint = (anyApi.endpoints[endpointName] ??= {} as any)\n\n        if (isQueryDefinition(definition)) {\n          safeAssign(\n            endpoint,\n            {\n              name: endpointName,\n              select: buildQuerySelector(endpointName, definition),\n              initiate: buildInitiateQuery(endpointName, definition),\n            },\n            buildMatchThunkActions(queryThunk, endpointName),\n          )\n        }\n        if (isMutationDefinition(definition)) {\n          safeAssign(\n            endpoint,\n            {\n              name: endpointName,\n              select: buildMutationSelector(),\n              initiate: buildInitiateMutation(endpointName),\n            },\n            buildMatchThunkActions(mutationThunk, endpointName),\n          )\n        }\n        if (isInfiniteQueryDefinition(definition)) {\n          safeAssign(\n            endpoint,\n            {\n              name: endpointName,\n              select: buildInfiniteQuerySelector(endpointName, definition),\n              initiate: buildInitiateInfiniteQuery(endpointName, definition),\n            },\n            buildMatchThunkActions(queryThunk, endpointName),\n          )\n        }\n      },\n    }\n  },\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/core/rtkImports.ts",
    "content": "// This file exists to consolidate all of the imports from the `@reduxjs/toolkit` package.\n// ESBuild does not de-duplicate imports, so this file is used to ensure that each method\n// imported is only listed once, and there's only one mention of the `@reduxjs/toolkit` package.\n\nexport {\n  createAction,\n  createSlice,\n  createSelector,\n  createAsyncThunk,\n  combineReducers,\n  createNextState,\n  isAnyOf,\n  isAllOf,\n  isAction,\n  isPending,\n  isRejected,\n  isFulfilled,\n  isRejectedWithValue,\n  isAsyncThunkAction,\n  prepareAutoBatched,\n  SHOULD_AUTOBATCH,\n  isPlainObject,\n  nanoid,\n} from '@reduxjs/toolkit'\n"
  },
  {
    "path": "packages/toolkit/src/query/core/setupListeners.ts",
    "content": "import type {\n  ThunkDispatch,\n  ActionCreatorWithoutPayload, // Workaround for API-Extractor\n} from '@reduxjs/toolkit'\nimport { createAction } from './rtkImports'\n\nexport const INTERNAL_PREFIX = '__rtkq/'\n\nconst ONLINE = 'online'\nconst OFFLINE = 'offline'\nconst FOCUS = 'focus'\nconst FOCUSED = 'focused'\nconst VISIBILITYCHANGE = 'visibilitychange'\n\nexport const onFocus = /* @__PURE__ */ createAction(\n  `${INTERNAL_PREFIX}${FOCUSED}`,\n)\nexport const onFocusLost = /* @__PURE__ */ createAction(\n  `${INTERNAL_PREFIX}un${FOCUSED}`,\n)\nexport const onOnline = /* @__PURE__ */ createAction(\n  `${INTERNAL_PREFIX}${ONLINE}`,\n)\nexport const onOffline = /* @__PURE__ */ createAction(\n  `${INTERNAL_PREFIX}${OFFLINE}`,\n)\n\nconst actions = {\n  onFocus,\n  onFocusLost,\n  onOnline,\n  onOffline,\n}\n\nlet initialized = false\n\n/**\n * A utility used to enable `refetchOnMount` and `refetchOnReconnect` behaviors.\n * It requires the dispatch method from your store.\n * Calling `setupListeners(store.dispatch)` will configure listeners with the recommended defaults,\n * but you have the option of providing a callback for more granular control.\n *\n * @example\n * ```ts\n * setupListeners(store.dispatch)\n * ```\n *\n * @param dispatch - The dispatch method from your store\n * @param customHandler - An optional callback for more granular control over listener behavior\n * @returns Return value of the handler.\n * The default handler returns an `unsubscribe` method that can be called to remove the listeners.\n */\nexport function setupListeners(\n  dispatch: ThunkDispatch<any, any, any>,\n  customHandler?: (\n    dispatch: ThunkDispatch<any, any, any>,\n    actions: {\n      onFocus: typeof onFocus\n      onFocusLost: typeof onFocusLost\n      onOnline: typeof onOnline\n      onOffline: typeof onOffline\n    },\n  ) => () => void,\n) {\n  function defaultHandler() {\n    const [handleFocus, handleFocusLost, handleOnline, handleOffline] = [\n      onFocus,\n      onFocusLost,\n      onOnline,\n      onOffline,\n    ].map((action) => () => dispatch(action()))\n\n    const handleVisibilityChange = () => {\n      if (window.document.visibilityState === 'visible') {\n        handleFocus()\n      } else {\n        handleFocusLost()\n      }\n    }\n\n    let unsubscribe = () => {\n      initialized = false\n    }\n\n    if (!initialized) {\n      if (typeof window !== 'undefined' && window.addEventListener) {\n        const handlers = {\n          [FOCUS]: handleFocus,\n          [VISIBILITYCHANGE]: handleVisibilityChange,\n          [ONLINE]: handleOnline,\n          [OFFLINE]: handleOffline,\n        }\n\n        function updateListeners(add: boolean) {\n          Object.entries(handlers).forEach(([event, handler]) => {\n            if (add) {\n              window.addEventListener(event, handler, false)\n            } else {\n              window.removeEventListener(event, handler)\n            }\n          })\n        }\n        // Handle focus events\n        updateListeners(true)\n        initialized = true\n\n        unsubscribe = () => {\n          updateListeners(false)\n          initialized = false\n        }\n      }\n    }\n\n    return unsubscribe\n  }\n\n  return customHandler ? customHandler(dispatch, actions) : defaultHandler()\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/createApi.ts",
    "content": "import {\n  getEndpointDefinition,\n  type Api,\n  type ApiContext,\n  type Module,\n  type ModuleName,\n} from './apiTypes'\nimport type { CombinedState } from './core/apiState'\nimport type { BaseQueryArg, BaseQueryFn } from './baseQueryTypes'\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs'\nimport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'\nimport type {\n  EndpointBuilder,\n  EndpointDefinitions,\n  SchemaFailureConverter,\n  SchemaFailureHandler,\n  SchemaType,\n} from './endpointDefinitions'\nimport {\n  DefinitionType,\n  ENDPOINT_INFINITEQUERY,\n  ENDPOINT_MUTATION,\n  ENDPOINT_QUERY,\n  isInfiniteQueryDefinition,\n  isQueryDefinition,\n} from './endpointDefinitions'\nimport { nanoid } from './core/rtkImports'\nimport type { UnknownAction } from '@reduxjs/toolkit'\nimport type { NoInfer } from './tsHelpers'\nimport { weakMapMemoize } from 'reselect'\n\nexport interface CreateApiOptions<\n  BaseQuery extends BaseQueryFn,\n  Definitions extends EndpointDefinitions,\n  ReducerPath extends string = 'api',\n  TagTypes extends string = never,\n> {\n  /**\n   * The base query used by each endpoint if no `queryFn` option is specified. RTK Query exports a utility called [fetchBaseQuery](./fetchBaseQuery) as a lightweight wrapper around `fetch` for common use-cases. See [Customizing Queries](../../rtk-query/usage/customizing-queries) if `fetchBaseQuery` does not handle your requirements.\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   // highlight-start\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  baseQuery: BaseQuery\n  /**\n   * An array of string tag type names. Specifying tag types is optional, but you should define them so that they can be used for caching and invalidation. When defining a tag type, you will be able to [provide](../../rtk-query/usage/automated-refetching#providing-tags) them with `providesTags` and [invalidate](../../rtk-query/usage/automated-refetching#invalidating-tags) them with `invalidatesTags` when configuring [endpoints](#endpoints).\n   *\n   * @example\n   *\n   * ```ts\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   tagTypes: ['Post', 'User'],\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // ...endpoints\n   *   }),\n   * })\n   * ```\n   */\n  tagTypes?: readonly TagTypes[]\n  /**\n   * The `reducerPath` is a _unique_ key that your service will be mounted to in your store. If you call `createApi` more than once in your application, you will need to provide a unique value each time. Defaults to `'api'`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"apis.js\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query';\n   *\n   * const apiOne = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiOne',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   *\n   * const apiTwo = createApi({\n   *   // highlight-start\n   *   reducerPath: 'apiTwo',\n   *   // highlight-end\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (builder) => ({\n   *     // ...endpoints\n   *   }),\n   * });\n   * ```\n   */\n  reducerPath?: ReducerPath\n  /**\n   * Accepts a custom function if you have a need to change the creation of cache keys for any reason.\n   */\n  serializeQueryArgs?: SerializeQueryArgs<unknown>\n  /**\n   * Endpoints are a set of operations that you want to perform against your server. You define them as an object using the builder syntax. There are three endpoint types: [`query`](../../rtk-query/usage/queries), [`infiniteQuery`](../../rtk-query/usage/infinite-queries) and [`mutation`](../../rtk-query/usage/mutations).\n   */\n  endpoints(\n    build: EndpointBuilder<BaseQuery, TagTypes, ReducerPath>,\n  ): Definitions\n  /**\n   * Defaults to `60` _(this value is in seconds)_. This is how long RTK Query will keep your data cached for **after** the last component unsubscribes. For example, if you query an endpoint, then unmount the component, then mount another component that makes the same request within the given time frame, the most recent value will be served from the cache.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"keepUnusedDataFor example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * interface Post {\n   *   id: number\n   *   name: string\n   * }\n   * type PostsResponse = Post[]\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts'\n   *     })\n   *   }),\n   *   // highlight-start\n   *   keepUnusedDataFor: 5\n   *   // highlight-end\n   * })\n   * ```\n   */\n  keepUnusedDataFor?: number\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after the application window regains focus.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnFocus?: boolean\n  /**\n   * Defaults to `false`. This setting allows you to control whether RTK Query will try to refetch all subscribed queries after regaining a network connection.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   *\n   * Note: requires [`setupListeners`](./setupListeners) to have been called.\n   */\n  refetchOnReconnect?: boolean\n  /**\n   * Defaults to `'delayed'`. This setting allows you to control when tags are invalidated after a mutation.\n   *\n   * - `'immediately'`: Queries are invalidated instantly after the mutation finished, even if they are running.\n   *   If the query provides tags that were invalidated while it ran, it won't be re-fetched.\n   * - `'delayed'`: Invalidation only happens after all queries and mutations are settled.\n   *   This ensures that queries are always invalidated correctly and automatically \"batches\" invalidations of concurrent mutations.\n   *   Note that if you constantly have some queries (or mutations) running, this can delay tag invalidations indefinitely.\n   */\n  invalidationBehavior?: 'delayed' | 'immediately'\n  /**\n   * A function that is passed every dispatched action. If this returns something other than `undefined`,\n   * that return value will be used to rehydrate fulfilled & errored queries.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"next-redux-wrapper rehydration example\"\n   * import type { Action, PayloadAction } from '@reduxjs/toolkit'\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n   * import { HYDRATE } from 'next-redux-wrapper'\n   *\n   * type RootState = any; // normally inferred from state\n   *\n   * function isHydrateAction(action: Action): action is PayloadAction<RootState> {\n   *   return action.type === HYDRATE\n   * }\n   *\n   * export const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   // highlight-start\n   *   extractRehydrationInfo(action, { reducerPath }): any {\n   *     if (isHydrateAction(action)) {\n   *       return action.payload[reducerPath]\n   *     }\n   *   },\n   *   // highlight-end\n   *   endpoints: (build) => ({\n   *     // omitted\n   *   }),\n   * })\n   * ```\n   */\n  extractRehydrationInfo?: (\n    action: UnknownAction,\n    {\n      reducerPath,\n    }: {\n      reducerPath: ReducerPath\n    },\n  ) =>\n    | undefined\n    | CombinedState<\n        NoInfer<Definitions>,\n        NoInfer<TagTypes>,\n        NoInfer<ReducerPath>\n      >\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * Gets called with a `NamedSchemaError` and an object containing the endpoint name, the type of the endpoint, the argument passed to the endpoint, and the query cache key (if applicable).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *     }),\n   *   }),\n   *   onSchemaFailure: (error, info) => {\n   *     console.error(error, info)\n   *   },\n   * })\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   }),\n   *   catchSchemaFailure: (error, info) => ({\n   *     status: \"CUSTOM_ERROR\",\n   *     error: error.schemaName + \" failed validation\",\n   *     data: error.issues,\n   *   }),\n   * })\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>\n\n  /**\n   * Defaults to `false`.\n   *\n   * If set to `true`, will skip schema validation for all endpoints, unless overridden by the endpoint.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react'\n   * import * as v from \"valibot\"\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   skipSchemaValidation: process.env.NODE_ENV === \"test\" ? [\"response\"] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *     }),\n   *   })\n   * })\n   * ```\n   */\n  skipSchemaValidation?: boolean | SchemaType[]\n}\n\nexport type CreateApi<Modules extends ModuleName> = {\n  /**\n   * Creates a service to use in your application. Contains only the basic redux logic (the core module).\n   *\n   * @link https://redux-toolkit.js.org/rtk-query/api/createApi\n   */\n  <\n    BaseQuery extends BaseQueryFn,\n    Definitions extends EndpointDefinitions,\n    ReducerPath extends string = 'api',\n    TagTypes extends string = never,\n  >(\n    options: CreateApiOptions<BaseQuery, Definitions, ReducerPath, TagTypes>,\n  ): Api<BaseQuery, Definitions, ReducerPath, TagTypes, Modules>\n}\n\n/**\n * Builds a `createApi` method based on the provided `modules`.\n *\n * @link https://redux-toolkit.js.org/rtk-query/usage/customizing-create-api\n *\n * @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @param modules - A variable number of modules that customize how the `createApi` method handles endpoints\n * @returns A `createApi` method using the provided `modules`.\n */\nexport function buildCreateApi<Modules extends [Module<any>, ...Module<any>[]]>(\n  ...modules: Modules\n): CreateApi<Modules[number]['name']> {\n  return function baseCreateApi(options) {\n    const extractRehydrationInfo = weakMapMemoize((action: UnknownAction) =>\n      options.extractRehydrationInfo?.(action, {\n        reducerPath: (options.reducerPath ?? 'api') as any,\n      }),\n    )\n\n    const optionsWithDefaults: CreateApiOptions<any, any, any, any> = {\n      reducerPath: 'api',\n      keepUnusedDataFor: 60,\n      refetchOnMountOrArgChange: false,\n      refetchOnFocus: false,\n      refetchOnReconnect: false,\n      invalidationBehavior: 'delayed',\n      ...options,\n      extractRehydrationInfo,\n      serializeQueryArgs(queryArgsApi) {\n        let finalSerializeQueryArgs = defaultSerializeQueryArgs\n        if ('serializeQueryArgs' in queryArgsApi.endpointDefinition) {\n          const endpointSQA =\n            queryArgsApi.endpointDefinition.serializeQueryArgs!\n          finalSerializeQueryArgs = (queryArgsApi) => {\n            const initialResult = endpointSQA(queryArgsApi)\n            if (typeof initialResult === 'string') {\n              // If the user function returned a string, use it as-is\n              return initialResult\n            } else {\n              // Assume they returned an object (such as a subset of the original\n              // query args) or a primitive, and serialize it ourselves\n              return defaultSerializeQueryArgs({\n                ...queryArgsApi,\n                queryArgs: initialResult,\n              })\n            }\n          }\n        } else if (options.serializeQueryArgs) {\n          finalSerializeQueryArgs = options.serializeQueryArgs\n        }\n\n        return finalSerializeQueryArgs(queryArgsApi)\n      },\n      tagTypes: [...(options.tagTypes || [])],\n    }\n\n    const context: ApiContext<EndpointDefinitions> = {\n      endpointDefinitions: {},\n      batch(fn) {\n        // placeholder \"batch\" method to be overridden by plugins, for example with React.unstable_batchedUpdate\n        fn()\n      },\n      apiUid: nanoid(),\n      extractRehydrationInfo,\n      hasRehydrationInfo: weakMapMemoize(\n        (action) => extractRehydrationInfo(action) != null,\n      ),\n    }\n\n    const api = {\n      injectEndpoints,\n      enhanceEndpoints({ addTagTypes, endpoints }) {\n        if (addTagTypes) {\n          for (const eT of addTagTypes) {\n            if (!optionsWithDefaults.tagTypes!.includes(eT as any)) {\n              ;(optionsWithDefaults.tagTypes as any[]).push(eT)\n            }\n          }\n        }\n        if (endpoints) {\n          for (const [endpointName, partialDefinition] of Object.entries(\n            endpoints,\n          )) {\n            if (typeof partialDefinition === 'function') {\n              partialDefinition(getEndpointDefinition(context, endpointName))\n            } else {\n              Object.assign(\n                getEndpointDefinition(context, endpointName) || {},\n                partialDefinition,\n              )\n            }\n          }\n        }\n        return api\n      },\n    } as Api<BaseQueryFn, {}, string, string, Modules[number]['name']>\n\n    const initializedModules = modules.map((m) =>\n      m.init(api as any, optionsWithDefaults as any, context),\n    )\n\n    function injectEndpoints(\n      inject: Parameters<typeof api.injectEndpoints>[0],\n    ) {\n      const evaluatedEndpoints = inject.endpoints({\n        query: (x) => ({ ...x, type: ENDPOINT_QUERY }) as any,\n        mutation: (x) => ({ ...x, type: ENDPOINT_MUTATION }) as any,\n        infiniteQuery: (x) => ({ ...x, type: ENDPOINT_INFINITEQUERY }) as any,\n      })\n\n      for (const [endpointName, definition] of Object.entries(\n        evaluatedEndpoints,\n      )) {\n        if (\n          inject.overrideExisting !== true &&\n          endpointName in context.endpointDefinitions\n        ) {\n          if (inject.overrideExisting === 'throw') {\n            throw new Error(\n              `called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``,\n            )\n          } else if (\n            typeof process !== 'undefined' &&\n            process.env.NODE_ENV === 'development'\n          ) {\n            console.error(\n              `called \\`injectEndpoints\\` to override already-existing endpointName ${endpointName} without specifying \\`overrideExisting: true\\``,\n            )\n          }\n\n          continue\n        }\n\n        if (\n          typeof process !== 'undefined' &&\n          process.env.NODE_ENV === 'development'\n        ) {\n          if (isInfiniteQueryDefinition(definition)) {\n            const { infiniteQueryOptions } = definition\n            const { maxPages, getPreviousPageParam } = infiniteQueryOptions\n\n            if (typeof maxPages === 'number') {\n              if (maxPages < 1) {\n                throw new Error(\n                  `maxPages for endpoint '${endpointName}' must be a number greater than 0`,\n                )\n              }\n\n              if (typeof getPreviousPageParam !== 'function') {\n                throw new Error(\n                  `getPreviousPageParam for endpoint '${endpointName}' must be a function if maxPages is used`,\n                )\n              }\n            }\n          }\n        }\n\n        context.endpointDefinitions[endpointName] = definition\n        for (const m of initializedModules) {\n          m.injectEndpoint(endpointName, definition)\n        }\n      }\n\n      return api as any\n    }\n\n    return api.injectEndpoints({ endpoints: options.endpoints as any })\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/defaultSerializeQueryArgs.ts",
    "content": "import type { QueryCacheKey } from './core/apiState'\nimport type { EndpointDefinition } from './endpointDefinitions'\nimport { isPlainObject } from './core/rtkImports'\n\nconst cache: WeakMap<any, string> | undefined = WeakMap\n  ? new WeakMap()\n  : undefined\n\nexport const defaultSerializeQueryArgs: SerializeQueryArgs<any> = ({\n  endpointName,\n  queryArgs,\n}) => {\n  let serialized = ''\n\n  const cached = cache?.get(queryArgs)\n\n  if (typeof cached === 'string') {\n    serialized = cached\n  } else {\n    const stringified = JSON.stringify(queryArgs, (key, value) => {\n      // Handle bigints\n      value = typeof value === 'bigint' ? { $bigint: value.toString() } : value\n      // Sort the object keys before stringifying, to prevent useQuery({ a: 1, b: 2 }) having a different cache key than useQuery({ b: 2, a: 1 })\n      value = isPlainObject(value)\n        ? Object.keys(value)\n            .sort()\n            .reduce<any>((acc, key) => {\n              acc[key] = (value as any)[key]\n              return acc\n            }, {})\n        : value\n      return value\n    })\n    if (isPlainObject(queryArgs)) {\n      cache?.set(queryArgs, stringified)\n    }\n    serialized = stringified\n  }\n  return `${endpointName}(${serialized})`\n}\n\nexport type SerializeQueryArgs<QueryArgs, ReturnType = string> = (_: {\n  queryArgs: QueryArgs\n  endpointDefinition: EndpointDefinition<any, any, any, any>\n  endpointName: string\n}) => ReturnType\n\nexport type InternalSerializeQueryArgs = (_: {\n  queryArgs: any\n  endpointDefinition: EndpointDefinition<any, any, any, any>\n  endpointName: string\n}) => QueryCacheKey\n"
  },
  {
    "path": "packages/toolkit/src/query/endpointDefinitions.ts",
    "content": "import type { Api } from '@reduxjs/toolkit/query'\nimport type { StandardSchemaV1 } from '@standard-schema/spec'\nimport type {\n  BaseQueryApi,\n  BaseQueryArg,\n  BaseQueryError,\n  BaseQueryExtraOptions,\n  BaseQueryFn,\n  BaseQueryMeta,\n  BaseQueryResult,\n  QueryReturnValue,\n} from './baseQueryTypes'\nimport type { CacheCollectionQueryExtraOptions } from './core/buildMiddleware/cacheCollection'\nimport type {\n  CacheLifecycleInfiniteQueryExtraOptions,\n  CacheLifecycleMutationExtraOptions,\n  CacheLifecycleQueryExtraOptions,\n} from './core/buildMiddleware/cacheLifecycle'\nimport type {\n  QueryLifecycleInfiniteQueryExtraOptions,\n  QueryLifecycleMutationExtraOptions,\n  QueryLifecycleQueryExtraOptions,\n} from './core/buildMiddleware/queryLifecycle'\nimport type {\n  InfiniteData,\n  InfiniteQueryConfigOptions,\n  QuerySubState,\n  RootState,\n} from './core/index'\nimport type { SerializeQueryArgs } from './defaultSerializeQueryArgs'\nimport type { NEVER } from './fakeBaseQuery'\nimport type { NamedSchemaError } from './standardSchema'\nimport type {\n  CastAny,\n  HasRequiredProps,\n  MaybePromise,\n  NonUndefined,\n  OmitFromUnion,\n  UnwrapPromise,\n} from './tsHelpers'\nimport { isNotNullish } from './utils'\nimport { filterMap } from './utils/filterMap'\n\nconst rawResultType = /* @__PURE__ */ Symbol()\nconst resultType = /* @__PURE__ */ Symbol()\nconst baseQuery = /* @__PURE__ */ Symbol()\n\nexport interface SchemaFailureInfo {\n  endpoint: string\n  arg: any\n  type: 'query' | 'mutation'\n  queryCacheKey?: string\n}\n\nexport type SchemaFailureHandler = (\n  error: NamedSchemaError,\n  info: SchemaFailureInfo,\n) => void\n\nexport type SchemaFailureConverter<BaseQuery extends BaseQueryFn> = (\n  error: NamedSchemaError,\n  info: SchemaFailureInfo,\n) => BaseQueryError<BaseQuery>\n\nexport type EndpointDefinitionWithQuery<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ResultType,\n  RawResultType extends BaseQueryResult<BaseQuery>,\n> = {\n  /**\n   * `query` can be a function that returns either a `string` or an `object` which is passed to your `baseQuery`. If you are using [fetchBaseQuery](./fetchBaseQuery), this can return either a `string` or an `object` of properties in `FetchArgs`. If you use your own custom [`baseQuery`](../../rtk-query/usage/customizing-queries), you can customize this behavior to your liking.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"query example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * type PostsResponse = Post[];\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       // highlight-start\n   *       query: () => 'posts',\n   *       // highlight-end\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       // highlight-start\n   *       query: (body) => ({\n   *         url: `posts`,\n   *         method: 'POST',\n   *         body,\n   *       }),\n   *       // highlight-end\n   *       invalidatesTags: [{ type: 'Post', id: 'LIST' }],\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  query(arg: QueryArg): BaseQueryArg<BaseQuery>\n  queryFn?: never\n  /**\n   * A function to manipulate the data returned by a query or mutation.\n   */\n  transformResponse?(\n    baseQueryReturnValue: RawResultType,\n    meta: BaseQueryMeta<BaseQuery>,\n    arg: QueryArg,\n  ): ResultType | Promise<ResultType>\n  /**\n   * A function to manipulate the data returned by a failed query or mutation.\n   */\n  transformErrorResponse?(\n    baseQueryReturnValue: BaseQueryError<BaseQuery>,\n    meta: BaseQueryMeta<BaseQuery>,\n    arg: QueryArg,\n  ): unknown\n\n  /**\n   * A schema for the result *before* it's passed to `transformResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   * import * as v from 'valibot';\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() });\n   * type Post = v.InferOutput<typeof postSchema>;\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPostName: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawResponseSchema: postSchema,\n   *       transformResponse: (post) => post.name,\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  rawResponseSchema?: StandardSchemaV1<RawResultType>\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn`, *before* it's passed to `transformErrorResponse`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react';\n   * import { baseQueryErrorSchema, customBaseQuery } from './customBaseQuery';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       rawErrorResponseSchema: baseQueryErrorSchema,\n   *       transformErrorResponse: (error) => error.data,\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  rawErrorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>\n}\n\nexport type EndpointDefinitionWithQueryFn<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ResultType,\n> = {\n  /**\n   * Can be used in place of `query` as an inline function that bypasses `baseQuery` completely for the endpoint.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Basic queryFn example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * type PostsResponse = Post[];\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *     }),\n   *     flipCoin: build.query<'heads' | 'tails', void>({\n   *       // highlight-start\n   *       queryFn(arg, queryApi, extraOptions, baseQuery) {\n   *         const randomVal = Math.random();\n   *         if (randomVal < 0.45) {\n   *           return { data: 'heads' };\n   *         }\n   *         if (randomVal < 0.9) {\n   *           return { data: 'tails' };\n   *         }\n   *         return {\n   *           error: {\n   *             status: 500,\n   *             statusText: 'Internal Server Error',\n   *             data: 'Coin landed on its edge!',\n   *           },\n   *         };\n   *       },\n   *       // highlight-end\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  queryFn(\n    arg: QueryArg,\n    api: BaseQueryApi,\n    extraOptions: BaseQueryExtraOptions<BaseQuery>,\n    baseQuery: (arg: Parameters<BaseQuery>[0]) => ReturnType<BaseQuery>,\n  ): MaybePromise<\n    QueryReturnValue<\n      ResultType,\n      BaseQueryError<BaseQuery>,\n      BaseQueryMeta<BaseQuery>\n    >\n  >\n  query?: never\n  transformResponse?: never\n  transformErrorResponse?: never\n  rawResponseSchema?: never\n  rawErrorResponseSchema?: never\n}\n\ntype BaseEndpointTypes<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ResultType,\n  RawResultType,\n> = {\n  QueryArg: QueryArg\n  BaseQuery: BaseQuery\n  ResultType: ResultType\n  RawResultType: RawResultType\n}\n\nexport type SchemaType =\n  | 'arg'\n  | 'rawResponse'\n  | 'response'\n  | 'rawErrorResponse'\n  | 'errorResponse'\n  | 'meta'\n\ninterface CommonEndpointDefinition<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ResultType,\n> {\n  /**\n   * A schema for the arguments to be passed to the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   * import * as v from 'valibot';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       argSchema: v.object({ id: v.number() }),\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  argSchema?: StandardSchemaV1<QueryArg>\n\n  /**\n   * A schema for the result (including `transformResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   * import * as v from 'valibot';\n   *\n   * const postSchema = v.object({ id: v.number(), name: v.string() });\n   * type Post = v.InferOutput<typeof postSchema>;\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: postSchema,\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  responseSchema?: StandardSchemaV1<ResultType>\n\n  /**\n   * A schema for the error object returned by the `query` or `queryFn` (including `transformErrorResponse` if provided).\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react';\n   * import { baseQueryErrorSchema, customBaseQuery } from './customBaseQuery';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       errorResponseSchema: baseQueryErrorSchema,\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  errorResponseSchema?: StandardSchemaV1<BaseQueryError<BaseQuery>>\n\n  /**\n   * A schema for the `meta` property returned by the `query` or `queryFn`.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi } from '@reduxjs/toolkit/query/react';\n   * import { baseQueryMetaSchema, customBaseQuery } from './customBaseQuery';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: customBaseQuery,\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       metaSchema: baseQueryMetaSchema,\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  metaSchema?: StandardSchemaV1<BaseQueryMeta<BaseQuery>>\n\n  /**\n   * Most apps should leave this setting on. The only time it can be a performance issue\n   * is if an API returns extremely large amounts of data (e.g. 10,000 rows per request) and\n   * you're unable to paginate it.\n   *\n   * For details of how this works, please see the below. When it is set to `false`,\n   * every request will cause subscribed components to rerender, even when the data has not changed.\n   *\n   * @default true\n   *\n   * @see https://redux-toolkit.js.org/api/other-exports#copywithstructuralsharing\n   */\n  structuralSharing?: boolean\n\n  /**\n   * A function that is called when a schema validation fails.\n   *\n   * Gets called with a `NamedSchemaError` and an object containing the endpoint name, the type of the endpoint, the argument passed to the endpoint, and the query cache key (if applicable).\n   *\n   * `NamedSchemaError` has the following properties:\n   * - `issues`: an array of issues that caused the validation to fail\n   * - `value`: the value that was passed to the schema\n   * - `schemaName`: the name of the schema that was used to validate the value (e.g. `argSchema`)\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       onSchemaFailure: (error, info) => {\n   *         console.error(error, info);\n   *       },\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  onSchemaFailure?: SchemaFailureHandler\n\n  /**\n   * Convert a schema validation failure into an error shape matching base query errors.\n   *\n   * When not provided, schema failures are treated as fatal, and normal error handling such as tag invalidation will not be executed.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   * import * as v from 'valibot';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       catchSchemaFailure: (error, info) => ({\n   *         status: 'CUSTOM_ERROR',\n   *         error: `${error.schemaName} failed validation`,\n   *         data: error.issues,\n   *       }),\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  catchSchemaFailure?: SchemaFailureConverter<BaseQuery>\n\n  /**\n   * If set to `true`, will skip schema validation for this endpoint.\n   * Overrides the global setting.\n   *\n   * Can be overridden for specific schemas by passing an array of schema types to skip.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta no-transpile\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   * import * as v from 'valibot';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post, { id: number }>({\n   *       query: ({ id }) => `/post/${id}`,\n   *       responseSchema: v.object({ id: v.number(), name: v.string() }),\n   *       skipSchemaValidation:\n   *         process.env.NODE_ENV === 'test' ? ['response'] : false, // skip schema validation for response in tests, since we'll be mocking the response\n   *     }),\n   *   }),\n   * });\n   * ```\n   *\n   * @default false\n   */\n  skipSchemaValidation?: boolean | SchemaType[]\n}\n\nexport type BaseEndpointDefinition<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ResultType,\n  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n> = (\n  | ([CastAny<BaseQueryResult<BaseQuery>, {}>] extends [NEVER]\n      ? never\n      : EndpointDefinitionWithQuery<\n          QueryArg,\n          BaseQuery,\n          ResultType,\n          RawResultType\n        >)\n  | EndpointDefinitionWithQueryFn<QueryArg, BaseQuery, ResultType>\n) &\n  CommonEndpointDefinition<QueryArg, BaseQuery, ResultType> & {\n    /* phantom type */\n    [rawResultType]?: RawResultType\n    /* phantom type */\n    [resultType]?: ResultType\n    /* phantom type */\n    [baseQuery]?: BaseQuery\n  } & HasRequiredProps<\n    BaseQueryExtraOptions<BaseQuery>,\n    { extraOptions: BaseQueryExtraOptions<BaseQuery> },\n    { extraOptions?: BaseQueryExtraOptions<BaseQuery> }\n  >\n\n// NOTE As with QueryStatus in `apiState.ts`, don't use this for real comparisons\n// at runtime, use the string constants defined below.\nexport enum DefinitionType {\n  query = 'query',\n  mutation = 'mutation',\n  infinitequery = 'infinitequery',\n}\n\nexport const ENDPOINT_QUERY = DefinitionType.query\nexport const ENDPOINT_MUTATION = DefinitionType.mutation\nexport const ENDPOINT_INFINITEQUERY = DefinitionType.infinitequery\n\ntype TagDescriptionArray<TagTypes extends string> = ReadonlyArray<\n  TagDescription<TagTypes> | undefined | null\n>\n\nexport type GetResultDescriptionFn<\n  TagTypes extends string,\n  ResultType,\n  QueryArg,\n  ErrorType,\n  MetaType,\n> = (\n  result: ResultType | undefined,\n  error: ErrorType | undefined,\n  arg: QueryArg,\n  meta: MetaType,\n) => TagDescriptionArray<TagTypes>\n\nexport type FullTagDescription<TagType> = {\n  type: TagType\n  id?: number | string\n}\nexport type TagDescription<TagType> = TagType | FullTagDescription<TagType>\n\n/**\n * @public\n */\nexport type ResultDescription<\n  TagTypes extends string,\n  ResultType,\n  QueryArg,\n  ErrorType,\n  MetaType,\n> =\n  | TagDescriptionArray<TagTypes>\n  | GetResultDescriptionFn<TagTypes, ResultType, QueryArg, ErrorType, MetaType>\n\ntype QueryTypes<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  TagTypes extends string,\n  ResultType,\n  ReducerPath extends string = string,\n  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseQuery<typeof api.endpoints.query.Types.QueryDefinition> = ...\n   * ```\n   */\n  QueryDefinition: QueryDefinition<\n    QueryArg,\n    BaseQuery,\n    TagTypes,\n    ResultType,\n    ReducerPath\n  >\n  TagTypes: TagTypes\n  ReducerPath: ReducerPath\n}\n\n/**\n * @public\n */\nexport interface QueryExtraOptions<\n  TagTypes extends string,\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ReducerPath extends string = string,\n  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n> extends CacheLifecycleQueryExtraOptions<\n      ResultType,\n      QueryArg,\n      BaseQuery,\n      ReducerPath\n    >,\n    QueryLifecycleQueryExtraOptions<\n      ResultType,\n      QueryArg,\n      BaseQuery,\n      ReducerPath\n    >,\n    CacheCollectionQueryExtraOptions {\n  type: DefinitionType.query\n\n  /**\n   * Used by `query` endpoints. Determines which 'tag' is attached to the cached data returned by the query.\n   * Expects an array of tag type strings, an array of objects of tag types with ids, or a function that returns such an array.\n   * 1.  `['Post']` - equivalent to `2`\n   * 2.  `[{ type: 'Post' }]` - equivalent to `1`\n   * 3.  `[{ type: 'Post', id: 1 }]`\n   * 4.  `(result, error, arg) => ['Post']` - equivalent to `5`\n   * 5.  `(result, error, arg) => [{ type: 'Post' }]` - equivalent to `4`\n   * 6.  `(result, error, arg) => [{ type: 'Post', id: 1 }]`\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"providesTags example\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * type PostsResponse = Post[];\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       // highlight-start\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  providesTags?: ResultDescription<\n    TagTypes,\n    ResultType,\n    QueryArg,\n    BaseQueryError<BaseQuery>,\n    BaseQueryMeta<BaseQuery>\n  >\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>;\n   * }\n   *\n   * createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     // Example: an endpoint with an API client passed in as an argument,\n   *     // but only the item ID should be used as the cache key\n   *     getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *       queryFn: async ({ id, client }) => {\n   *         const post = await client.fetchPost(id);\n   *         return { data: post };\n   *       },\n   *       // highlight-start\n   *       serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *         const { id } = queryArgs;\n   *         // This can return a string, an object, a number, or a boolean.\n   *         // If it returns an object, number or boolean, that value\n   *         // will be serialized automatically via `defaultSerializeQueryArgs`\n   *         return { id }; // omit `client` from the cache key\n   *\n   *         // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *         // return defaultSerializeQueryArgs({\n   *         //   endpointName,\n   *         //   queryArgs: { id },\n   *         //   endpointDefinition\n   *         // })\n   *         // Or  create and return a string yourself:\n   *         // return `getPost(${id})`\n   *       },\n   *       // highlight-end\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<\n    QueryArg,\n    string | number | boolean | Record<any, any>\n  >\n\n  /**\n   * Can be provided to merge an incoming response value into the current cache data.\n   * If supplied, no automatic structural sharing will be applied - it's up to\n   * you to update the cache appropriately.\n   *\n   * Since RTKQ normally replaces cache entries with the new response, you will usually\n   * need to use this with the `serializeQueryArgs` or `forceRefetch` options to keep\n   * an existing cache entry so that it can be updated.\n   *\n   * Since this is wrapped with Immer, you may either mutate the `currentCacheValue` directly,\n   * or return a new value, but _not_ both at once.\n   *\n   * Will only be called if the existing `currentCacheData` is _not_ `undefined` - on first response,\n   * the cache entry will just save the response data directly.\n   *\n   * Useful if you don't want a new request to completely override the current cache value,\n   * maybe because you have manually updated it from another source and don't want those\n   * updates to get lost.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"merge: pagination\"\n   *\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     listItems: build.query<string[], number>({\n   *       query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *       // Only have one cache entry because the arg always maps to one string\n   *       serializeQueryArgs: ({ endpointName }) => {\n   *         return endpointName;\n   *       },\n   *       // Always merge incoming data to the cache entry\n   *       merge: (currentCache, newItems) => {\n   *         currentCache.push(...newItems);\n   *       },\n   *       // Refetch when the page arg changes\n   *       forceRefetch({ currentArg, previousArg }) {\n   *         return currentArg !== previousArg;\n   *       },\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  merge?(\n    currentCacheData: ResultType,\n    responseData: ResultType,\n    otherArgs: {\n      arg: QueryArg\n      baseQueryMeta: BaseQueryMeta<BaseQuery>\n      requestId: string\n      fulfilledTimeStamp: number\n    },\n  ): ResultType | void\n\n  /**\n   * Check to see if the endpoint should force a refetch in cases where it normally wouldn't.\n   * This is primarily useful for \"infinite scroll\" / pagination use cases where\n   * RTKQ is keeping a single cache entry that is added to over time, in combination\n   * with `serializeQueryArgs` returning a fixed cache key and a `merge` callback\n   * set to add incoming data to the cache entry each time.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"forceRefresh: pagination\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     listItems: build.query<string[], number>({\n   *       query: (pageNumber) => `/listItems?page=${pageNumber}`,\n   *       // Only have one cache entry because the arg always maps to one string\n   *       serializeQueryArgs: ({ endpointName }) => {\n   *         return endpointName;\n   *       },\n   *       // Always merge incoming data to the cache entry\n   *       merge: (currentCache, newItems) => {\n   *         currentCache.push(...newItems);\n   *       },\n   *       // Refetch when the page arg changes\n   *       forceRefetch({ currentArg, previousArg }) {\n   *         return currentArg !== previousArg;\n   *       },\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  forceRefetch?(params: {\n    currentArg: QueryArg | undefined\n    previousArg: QueryArg | undefined\n    state: RootState<any, any, string>\n    endpointState?: QuerySubState<any>\n  }): boolean\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: QueryTypes<\n    QueryArg,\n    BaseQuery,\n    TagTypes,\n    ResultType,\n    ReducerPath,\n    RawResultType\n  >\n}\n\nexport type QueryDefinition<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  TagTypes extends string,\n  ResultType,\n  ReducerPath extends string = string,\n  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, RawResultType> &\n  QueryExtraOptions<\n    TagTypes,\n    ResultType,\n    QueryArg,\n    BaseQuery,\n    ReducerPath,\n    RawResultType\n  >\n\nexport type InfiniteQueryTypes<\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n  TagTypes extends string,\n  ResultType,\n  ReducerPath extends string = string,\n  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseInfiniteQuery<typeof api.endpoints.query.Types.InfiniteQueryDefinition> = ...\n   * ```\n   */\n  InfiniteQueryDefinition: InfiniteQueryDefinition<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    TagTypes,\n    ResultType,\n    ReducerPath\n  >\n  TagTypes: TagTypes\n  ReducerPath: ReducerPath\n}\n\nexport interface InfiniteQueryExtraOptions<\n  TagTypes extends string,\n  ResultType,\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n  ReducerPath extends string = string,\n  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n> extends CacheLifecycleInfiniteQueryExtraOptions<\n      InfiniteData<ResultType, PageParam>,\n      QueryArg,\n      BaseQuery,\n      ReducerPath\n    >,\n    QueryLifecycleInfiniteQueryExtraOptions<\n      InfiniteData<ResultType, PageParam>,\n      QueryArg,\n      BaseQuery,\n      ReducerPath\n    >,\n    CacheCollectionQueryExtraOptions {\n  type: DefinitionType.infinitequery\n\n  providesTags?: ResultDescription<\n    TagTypes,\n    InfiniteData<ResultType, PageParam>,\n    QueryArg,\n    BaseQueryError<BaseQuery>,\n    BaseQueryMeta<BaseQuery>\n  >\n  /**\n   * Not to be used. A query should not invalidate tags in the cache.\n   */\n  invalidatesTags?: never\n\n  /**\n   * Required options to configure the infinite query behavior.\n   * `initialPageParam` and `getNextPageParam` are required, to\n   * ensure the infinite query can properly fetch the next page of data.\n   * `initialPageParam` may be specified when using the\n   * endpoint, to override the default value.\n   * `maxPages` and `getPreviousPageParam` are both optional.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"infiniteQueryOptions example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * type Pokemon = {\n   *   id: string;\n   *   name: string;\n   * };\n   *\n   * const pokemonApi = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n   *   endpoints: (build) => ({\n   *     getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>({\n   *       infiniteQueryOptions: {\n   *         initialPageParam: 0,\n   *         maxPages: 3,\n   *         getNextPageParam: (lastPage, allPages, lastPageParam, allPageParams) =>\n   *           lastPageParam + 1,\n   *         getPreviousPageParam: (\n   *           firstPage,\n   *           allPages,\n   *           firstPageParam,\n   *           allPageParams,\n   *         ) => {\n   *           return firstPageParam > 0 ? firstPageParam - 1 : undefined;\n   *         },\n   *       },\n   *       query({ pageParam }) {\n   *         return `https://example.com/listItems?page=${pageParam}`;\n   *       },\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  infiniteQueryOptions: InfiniteQueryConfigOptions<\n    ResultType,\n    PageParam,\n    QueryArg\n  >\n\n  /**\n   * Can be provided to return a custom cache key value based on the query arguments.\n   *\n   * This is primarily intended for cases where a non-serializable value is passed as part of the query arg object and should be excluded from the cache key.  It may also be used for cases where an endpoint should only have a single cache entry, such as an infinite loading / pagination implementation.\n   *\n   * Unlike the `createApi` version which can _only_ return a string, this per-endpoint option can also return an an object, number, or boolean.  If it returns a string, that value will be used as the cache key directly.  If it returns an object / number / boolean, that value will be passed to the built-in `defaultSerializeQueryArgs`.  This simplifies the use case of stripping out args you don't want included in the cache key.\n   *\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"serializeQueryArgs : exclude value\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * interface MyApiClient {\n   *   fetchPost: (id: string) => Promise<Post>;\n   * }\n   *\n   * createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   endpoints: (build) => ({\n   *     // Example: an endpoint with an API client passed in as an argument,\n   *     // but only the item ID should be used as the cache key\n   *     getPost: build.query<Post, { id: string; client: MyApiClient }>({\n   *       queryFn: async ({ id, client }) => {\n   *         const post = await client.fetchPost(id);\n   *         return { data: post };\n   *       },\n   *       // highlight-start\n   *       serializeQueryArgs: ({ queryArgs, endpointDefinition, endpointName }) => {\n   *         const { id } = queryArgs;\n   *         // This can return a string, an object, a number, or a boolean.\n   *         // If it returns an object, number or boolean, that value\n   *         // will be serialized automatically via `defaultSerializeQueryArgs`\n   *         return { id }; // omit `client` from the cache key\n   *\n   *         // Alternately, you can use `defaultSerializeQueryArgs` yourself:\n   *         // return defaultSerializeQueryArgs({\n   *         //   endpointName,\n   *         //   queryArgs: { id },\n   *         //   endpointDefinition\n   *         // })\n   *         // Or  create and return a string yourself:\n   *         // return `getPost(${id})`\n   *       },\n   *       // highlight-end\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  serializeQueryArgs?: SerializeQueryArgs<\n    QueryArg,\n    string | number | boolean | Record<any, any>\n  >\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: InfiniteQueryTypes<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    TagTypes,\n    ResultType,\n    ReducerPath,\n    RawResultType\n  >\n}\n\nexport type InfiniteQueryDefinition<\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n  TagTypes extends string,\n  ResultType,\n  ReducerPath extends string = string,\n  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n> =\n  // Infinite query endpoints receive `{queryArg, pageParam}`\n  BaseEndpointDefinition<\n    InfiniteQueryCombinedArg<QueryArg, PageParam>,\n    BaseQuery,\n    ResultType,\n    RawResultType\n  > &\n    InfiniteQueryExtraOptions<\n      TagTypes,\n      ResultType,\n      QueryArg,\n      PageParam,\n      BaseQuery,\n      ReducerPath,\n      RawResultType\n    >\n\ntype MutationTypes<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  TagTypes extends string,\n  ResultType,\n  ReducerPath extends string = string,\n  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n> = BaseEndpointTypes<QueryArg, BaseQuery, ResultType, RawResultType> & {\n  /**\n   * The endpoint definition type. To be used with some internal generic types.\n   * @example\n   * ```ts\n   * const useMyWrappedHook: UseMutation<typeof api.endpoints.query.Types.MutationDefinition> = ...\n   * ```\n   */\n  MutationDefinition: MutationDefinition<\n    QueryArg,\n    BaseQuery,\n    TagTypes,\n    ResultType,\n    ReducerPath\n  >\n  TagTypes: TagTypes\n  ReducerPath: ReducerPath\n}\n\n/**\n * @public\n */\nexport interface MutationExtraOptions<\n  TagTypes extends string,\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  ReducerPath extends string = string,\n  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n> extends CacheLifecycleMutationExtraOptions<\n      ResultType,\n      QueryArg,\n      BaseQuery,\n      ReducerPath\n    >,\n    QueryLifecycleMutationExtraOptions<\n      ResultType,\n      QueryArg,\n      BaseQuery,\n      ReducerPath\n    > {\n  type: DefinitionType.mutation\n\n  /**\n   * Used by `mutation` endpoints. Determines which cached data should be either re-fetched or removed from the cache.\n   * Expects the same shapes as `providesTags`.\n   *\n   * @example\n   *\n   * ```ts\n   * // codeblock-meta title=\"invalidatesTags example\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * type PostsResponse = Post[];\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Posts'],\n   *   endpoints: (build) => ({\n   *     getPosts: build.query<PostsResponse, void>({\n   *       query: () => 'posts',\n   *       providesTags: (result) =>\n   *         result\n   *           ? [\n   *               ...result.map(({ id }) => ({ type: 'Posts' as const, id })),\n   *               { type: 'Posts', id: 'LIST' },\n   *             ]\n   *           : [{ type: 'Posts', id: 'LIST' }],\n   *     }),\n   *     addPost: build.mutation<Post, Partial<Post>>({\n   *       query(body) {\n   *         return {\n   *           url: `posts`,\n   *           method: 'POST',\n   *           body,\n   *         };\n   *       },\n   *       // highlight-start\n   *       invalidatesTags: [{ type: 'Posts', id: 'LIST' }],\n   *       // highlight-end\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  invalidatesTags?: ResultDescription<\n    TagTypes,\n    ResultType,\n    QueryArg,\n    BaseQueryError<BaseQuery>,\n    BaseQueryMeta<BaseQuery>\n  >\n  /**\n   * Not to be used. A mutation should not provide tags to the cache.\n   */\n  providesTags?: never\n\n  /**\n   * All of these are `undefined` at runtime, purely to be used in TypeScript declarations!\n   */\n  Types?: MutationTypes<\n    QueryArg,\n    BaseQuery,\n    TagTypes,\n    ResultType,\n    ReducerPath,\n    RawResultType\n  >\n}\n\nexport type MutationDefinition<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  TagTypes extends string,\n  ResultType,\n  ReducerPath extends string = string,\n  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n> = BaseEndpointDefinition<QueryArg, BaseQuery, ResultType, RawResultType> &\n  MutationExtraOptions<\n    TagTypes,\n    ResultType,\n    QueryArg,\n    BaseQuery,\n    ReducerPath,\n    RawResultType\n  >\n\nexport type EndpointDefinition<\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  TagTypes extends string,\n  ResultType,\n  ReducerPath extends string = string,\n  PageParam = any,\n  RawResultType extends BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n> =\n  | QueryDefinition<\n      QueryArg,\n      BaseQuery,\n      TagTypes,\n      ResultType,\n      ReducerPath,\n      RawResultType\n    >\n  | MutationDefinition<\n      QueryArg,\n      BaseQuery,\n      TagTypes,\n      ResultType,\n      ReducerPath,\n      RawResultType\n    >\n  | InfiniteQueryDefinition<\n      QueryArg,\n      PageParam,\n      BaseQuery,\n      TagTypes,\n      ResultType,\n      ReducerPath,\n      RawResultType\n    >\n\nexport type EndpointDefinitions = Record<\n  string,\n  EndpointDefinition<any, any, any, any, any, any, any>\n>\n\nexport function isQueryDefinition(\n  e: EndpointDefinition<any, any, any, any, any, any, any>,\n): e is QueryDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_QUERY\n}\n\nexport function isMutationDefinition(\n  e: EndpointDefinition<any, any, any, any, any, any, any>,\n): e is MutationDefinition<any, any, any, any, any, any> {\n  return e.type === ENDPOINT_MUTATION\n}\n\nexport function isInfiniteQueryDefinition(\n  e: EndpointDefinition<any, any, any, any, any, any, any>,\n): e is InfiniteQueryDefinition<any, any, any, any, any, any, any> {\n  return e.type === ENDPOINT_INFINITEQUERY\n}\n\nexport function isAnyQueryDefinition(\n  e: EndpointDefinition<any, any, any, any>,\n): e is\n  | QueryDefinition<any, any, any, any>\n  | InfiniteQueryDefinition<any, any, any, any, any> {\n  return isQueryDefinition(e) || isInfiniteQueryDefinition(e)\n}\n\nexport type EndpointBuilder<\n  BaseQuery extends BaseQueryFn,\n  TagTypes extends string,\n  ReducerPath extends string,\n> = {\n  /**\n   * An endpoint definition that retrieves data, and may provide tags to the cache.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Example of all query endpoint options\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * interface PostsResponse {\n   *   data: Post[];\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     getPost: build.query<Post[], number, PostsResponse>({\n   *       query: (id) => ({ url: `post/${id}` }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.status,\n   *       // `result` is the server response\n   *       providesTags: (result, error, id) => [{ type: 'Post', id }],\n   *       // trigger side effects or optimistic updates\n   *       onQueryStarted(\n   *         id,\n   *         {\n   *           dispatch,\n   *           getState,\n   *           extra,\n   *           requestId,\n   *           queryFulfilled,\n   *           getCacheEntry,\n   *           updateCachedData,\n   *         },\n   *       ) {},\n   *       // handle subscriptions etc\n   *       onCacheEntryAdded(\n   *         id,\n   *         {\n   *           dispatch,\n   *           getState,\n   *           extra,\n   *           requestId,\n   *           cacheEntryRemoved,\n   *           cacheDataLoaded,\n   *           getCacheEntry,\n   *           updateCachedData,\n   *         },\n   *       ) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  query<\n    ResultType,\n    QueryArg,\n    RawResultType extends\n      BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n  >(\n    definition: OmitFromUnion<\n      QueryDefinition<\n        QueryArg,\n        BaseQuery,\n        TagTypes,\n        ResultType,\n        ReducerPath,\n        RawResultType\n      >,\n      'type'\n    >,\n  ): QueryDefinition<\n    QueryArg,\n    BaseQuery,\n    TagTypes,\n    ResultType,\n    ReducerPath,\n    RawResultType\n  >\n\n  /**\n   * An endpoint definition that alters data on the server or will possibly invalidate the cache.\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Example of all mutation endpoint options\"\n   * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n   *\n   * interface Post {\n   *   id: number;\n   *   name: string;\n   * }\n   *\n   * interface PostsResponse {\n   *   data: Post[];\n   * }\n   *\n   * const api = createApi({\n   *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n   *   tagTypes: ['Post'],\n   *   endpoints: (build) => ({\n   *     updatePost: build.mutation<Post[], Partial<Post>, PostsResponse>({\n   *       query: ({ id, ...patch }) => ({\n   *         url: `post/${id}`,\n   *         method: 'PATCH',\n   *         body: patch,\n   *       }),\n   *       // Pick out data and prevent nested properties in a hook or selector\n   *       transformResponse: (response) => response.data,\n   *       // Pick out error and prevent nested properties in a hook or selector\n   *       transformErrorResponse: (response) => response.status,\n   *       // `result` is the server response\n   *       invalidatesTags: (result, error, { id }) => [{ type: 'Post', id }],\n   *       // trigger side effects or optimistic updates\n   *       onQueryStarted(\n   *         { id },\n   *         { dispatch, getState, extra, requestId, queryFulfilled, getCacheEntry },\n   *       ) {},\n   *       // handle subscriptions etc\n   *       onCacheEntryAdded(\n   *         { id },\n   *         {\n   *           dispatch,\n   *           getState,\n   *           extra,\n   *           requestId,\n   *           cacheEntryRemoved,\n   *           cacheDataLoaded,\n   *           getCacheEntry,\n   *         },\n   *       ) {},\n   *     }),\n   *   }),\n   * });\n   * ```\n   */\n  mutation<\n    ResultType,\n    QueryArg,\n    RawResultType extends\n      BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n  >(\n    definition: OmitFromUnion<\n      MutationDefinition<\n        QueryArg,\n        BaseQuery,\n        TagTypes,\n        ResultType,\n        ReducerPath,\n        RawResultType\n      >,\n      'type'\n    >,\n  ): MutationDefinition<\n    QueryArg,\n    BaseQuery,\n    TagTypes,\n    ResultType,\n    ReducerPath,\n    RawResultType\n  >\n\n  infiniteQuery<\n    ResultType,\n    QueryArg,\n    PageParam,\n    RawResultType extends\n      BaseQueryResult<BaseQuery> = BaseQueryResult<BaseQuery>,\n  >(\n    definition: OmitFromUnion<\n      InfiniteQueryDefinition<\n        QueryArg,\n        PageParam,\n        BaseQuery,\n        TagTypes,\n        ResultType,\n        ReducerPath,\n        RawResultType\n      >,\n      'type'\n    >,\n  ): InfiniteQueryDefinition<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    TagTypes,\n    ResultType,\n    ReducerPath,\n    RawResultType\n  >\n}\n\nexport type AssertTagTypes = <T extends FullTagDescription<string>>(t: T) => T\n\nexport function calculateProvidedBy<ResultType, QueryArg, ErrorType, MetaType>(\n  description:\n    | ResultDescription<string, ResultType, QueryArg, ErrorType, MetaType>\n    | undefined,\n  result: ResultType | undefined,\n  error: ErrorType | undefined,\n  queryArg: QueryArg,\n  meta: MetaType | undefined,\n  assertTagTypes: AssertTagTypes,\n): readonly FullTagDescription<string>[] {\n  const finalDescription = isFunction(description)\n    ? description(\n        result as ResultType,\n        error as undefined,\n        queryArg,\n        meta as MetaType,\n      )\n    : description\n\n  if (finalDescription) {\n    return filterMap(finalDescription, isNotNullish, (tag) =>\n      assertTagTypes(expandTagDescription(tag)),\n    )\n  }\n\n  return []\n}\n\nfunction isFunction<T>(t: T): t is Extract<T, Function> {\n  return typeof t === 'function'\n}\n\nexport function expandTagDescription(\n  description: TagDescription<string>,\n): FullTagDescription<string> {\n  return typeof description === 'string' ? { type: description } : description\n}\n\nexport type QueryArgFrom<D extends BaseEndpointDefinition<any, any, any, any>> =\n  D extends BaseEndpointDefinition<infer QA, any, any, any> ? QA : never\n\n// Just extracting `QueryArg` from `BaseEndpointDefinition`\n// doesn't sufficiently match here.\n// We need to explicitly match against `InfiniteQueryDefinition`\nexport type InfiniteQueryArgFrom<\n  D extends BaseEndpointDefinition<any, any, any, any>,\n> =\n  D extends InfiniteQueryDefinition<infer QA, any, any, any, any, any, any>\n    ? QA\n    : never\n\nexport type QueryArgFromAnyQuery<\n  D extends BaseEndpointDefinition<any, any, any, any>,\n> =\n  D extends InfiniteQueryDefinition<any, any, any, any, any, any, any>\n    ? InfiniteQueryArgFrom<D>\n    : D extends QueryDefinition<any, any, any, any, any, any>\n      ? QueryArgFrom<D>\n      : never\n\nexport type ResultTypeFrom<\n  D extends BaseEndpointDefinition<any, any, any, any>,\n> = D extends BaseEndpointDefinition<any, any, infer RT, any> ? RT : unknown\n\nexport type ReducerPathFrom<\n  D extends EndpointDefinition<any, any, any, any, any, any, any>,\n> =\n  D extends EndpointDefinition<any, any, any, any, infer RP, any, any>\n    ? RP\n    : unknown\n\nexport type TagTypesFrom<\n  D extends EndpointDefinition<any, any, any, any, any, any, any>,\n> =\n  D extends EndpointDefinition<any, any, infer TT, any, any, any, any>\n    ? TT\n    : unknown\n\nexport type PageParamFrom<\n  D extends InfiniteQueryDefinition<any, any, any, any, any, any, any>,\n> =\n  D extends InfiniteQueryDefinition<any, infer PP, any, any, any, any, any>\n    ? PP\n    : unknown\n\nexport type InfiniteQueryCombinedArg<QueryArg, PageParam> = {\n  queryArg: QueryArg\n  pageParam: PageParam\n}\n\nexport type TagTypesFromApi<T> =\n  T extends Api<any, any, any, infer TagTypes> ? TagTypes : never\n\nexport type DefinitionsFromApi<T> =\n  T extends Api<any, infer Definitions, any, any> ? Definitions : never\n\nexport type TransformedResponse<\n  NewDefinitions extends EndpointDefinitions,\n  K,\n  ResultType,\n> = K extends keyof NewDefinitions\n  ? NewDefinitions[K]['transformResponse'] extends undefined\n    ? ResultType\n    : UnwrapPromise<\n        ReturnType<NonUndefined<NewDefinitions[K]['transformResponse']>>\n      >\n  : ResultType\n\nexport type OverrideResultType<Definition, NewResultType> =\n  Definition extends QueryDefinition<\n    infer QueryArg,\n    infer BaseQuery,\n    infer TagTypes,\n    any,\n    infer ReducerPath\n  >\n    ? QueryDefinition<QueryArg, BaseQuery, TagTypes, NewResultType, ReducerPath>\n    : Definition extends MutationDefinition<\n          infer QueryArg,\n          infer BaseQuery,\n          infer TagTypes,\n          any,\n          infer ReducerPath\n        >\n      ? MutationDefinition<\n          QueryArg,\n          BaseQuery,\n          TagTypes,\n          NewResultType,\n          ReducerPath\n        >\n      : Definition extends InfiniteQueryDefinition<\n            infer QueryArg,\n            infer PageParam,\n            infer BaseQuery,\n            infer TagTypes,\n            any,\n            infer ReducerPath\n          >\n        ? InfiniteQueryDefinition<\n            QueryArg,\n            PageParam,\n            BaseQuery,\n            TagTypes,\n            NewResultType,\n            ReducerPath\n          >\n        : never\n\nexport type UpdateDefinitions<\n  Definitions extends EndpointDefinitions,\n  NewTagTypes extends string,\n  NewDefinitions extends EndpointDefinitions,\n> = {\n  [K in keyof Definitions]: Definitions[K] extends QueryDefinition<\n    infer QueryArg,\n    infer BaseQuery,\n    any,\n    infer ResultType,\n    infer ReducerPath\n  >\n    ? QueryDefinition<\n        QueryArg,\n        BaseQuery,\n        NewTagTypes,\n        TransformedResponse<NewDefinitions, K, ResultType>,\n        ReducerPath\n      >\n    : Definitions[K] extends MutationDefinition<\n          infer QueryArg,\n          infer BaseQuery,\n          any,\n          infer ResultType,\n          infer ReducerPath\n        >\n      ? MutationDefinition<\n          QueryArg,\n          BaseQuery,\n          NewTagTypes,\n          TransformedResponse<NewDefinitions, K, ResultType>,\n          ReducerPath\n        >\n      : Definitions[K] extends InfiniteQueryDefinition<\n            infer QueryArg,\n            infer PageParam,\n            infer BaseQuery,\n            any,\n            infer ResultType,\n            infer ReducerPath\n          >\n        ? InfiniteQueryDefinition<\n            QueryArg,\n            PageParam,\n            BaseQuery,\n            NewTagTypes,\n            TransformedResponse<NewDefinitions, K, ResultType>,\n            ReducerPath\n          >\n        : never\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/fakeBaseQuery.ts",
    "content": "import type { BaseQueryFn } from './baseQueryTypes'\n\nexport const _NEVER = /* @__PURE__ */ Symbol()\nexport type NEVER = typeof _NEVER\n\n/**\n * Creates a \"fake\" baseQuery to be used if your api *only* uses the `queryFn` definition syntax.\n * This also allows you to specify a specific error type to be shared by all your `queryFn` definitions.\n */\nexport function fakeBaseQuery<ErrorType>(): BaseQueryFn<\n  void,\n  NEVER,\n  ErrorType,\n  {}\n> {\n  return function () {\n    throw new Error(\n      'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.',\n    )\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/fetchBaseQuery.ts",
    "content": "import { joinUrls } from './utils'\nimport { isPlainObject } from './core/rtkImports'\nimport type { BaseQueryApi, BaseQueryFn } from './baseQueryTypes'\nimport type { MaybePromise, Override } from './tsHelpers'\nimport { anySignal, timeoutSignal } from './utils/signals'\n\nexport type ResponseHandler =\n  | 'content-type'\n  | 'json'\n  | 'text'\n  | ((response: Response) => Promise<any>)\n\ntype CustomRequestInit = Override<\n  RequestInit,\n  {\n    headers?:\n      | Headers\n      | string[][]\n      | Record<string, string | undefined>\n      | undefined\n  }\n>\n\nexport interface FetchArgs extends CustomRequestInit {\n  url: string\n  params?: Record<string, any>\n  body?: any\n  responseHandler?: ResponseHandler\n  validateStatus?: (response: Response, body: any) => boolean\n  /**\n   * A number in milliseconds that represents that maximum time a request can take before timing out.\n   */\n  timeout?: number\n}\n\n/**\n * A mini-wrapper that passes arguments straight through to\n * {@link [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)}.\n * Avoids storing `fetch` in a closure, in order to permit mocking/monkey-patching.\n */\nconst defaultFetchFn: typeof fetch = (...args) => fetch(...args)\n\nconst defaultValidateStatus = (response: Response) =>\n  response.status >= 200 && response.status <= 299\n\nconst defaultIsJsonContentType = (headers: Headers) =>\n  /*applicat*/ /ion\\/(vnd\\.api\\+)?json/.test(headers.get('content-type') || '')\n\nexport type FetchBaseQueryError =\n  | {\n      /**\n       * * `number`:\n       *   HTTP status code\n       */\n      status: number\n      data: unknown\n    }\n  | {\n      /**\n       * * `\"FETCH_ERROR\"`:\n       *   An error that occurred during execution of `fetch` or the `fetchFn` callback option\n       **/\n      status: 'FETCH_ERROR'\n      data?: undefined\n      error: string\n    }\n  | {\n      /**\n       * * `\"PARSING_ERROR\"`:\n       *   An error happened during parsing.\n       *   Most likely a non-JSON-response was returned with the default `responseHandler` \"JSON\",\n       *   or an error occurred while executing a custom `responseHandler`.\n       **/\n      status: 'PARSING_ERROR'\n      originalStatus: number\n      data: string\n      error: string\n    }\n  | {\n      /**\n       * * `\"TIMEOUT_ERROR\"`:\n       *   Request timed out\n       **/\n      status: 'TIMEOUT_ERROR'\n      data?: undefined\n      error: string\n    }\n  | {\n      /**\n       * * `\"CUSTOM_ERROR\"`:\n       *   A custom error type that you can return from your `queryFn` where another error might not make sense.\n       **/\n      status: 'CUSTOM_ERROR'\n      data?: unknown\n      error: string\n    }\n\nfunction stripUndefined(obj: any) {\n  if (!isPlainObject(obj)) {\n    return obj\n  }\n  const copy: Record<string, any> = { ...obj }\n  for (const [k, v] of Object.entries(copy)) {\n    if (v === undefined) delete copy[k]\n  }\n  return copy\n}\n\n// Only set the content-type to json if appropriate. Will not be true for FormData, ArrayBuffer, Blob, etc.\nconst isJsonifiable = (body: any) =>\n  typeof body === 'object' &&\n  (isPlainObject(body) ||\n    Array.isArray(body) ||\n    typeof body.toJSON === 'function')\n\nexport type FetchBaseQueryArgs = {\n  baseUrl?: string\n  prepareHeaders?: (\n    headers: Headers,\n    api: Pick<\n      BaseQueryApi,\n      'getState' | 'extra' | 'endpoint' | 'type' | 'forced'\n    > & { arg: string | FetchArgs; extraOptions: unknown },\n  ) => MaybePromise<Headers | void>\n  fetchFn?: (\n    input: RequestInfo,\n    init?: RequestInit | undefined,\n  ) => Promise<Response>\n  paramsSerializer?: (params: Record<string, any>) => string\n  /**\n   * By default, we only check for 'application/json' and 'application/vnd.api+json' as the content-types for json. If you need to support another format, you can pass\n   * in a predicate function for your given api to get the same automatic stringifying behavior\n   * @example\n   * ```ts\n   * const isJsonContentType = (headers: Headers) => [\"application/vnd.api+json\", \"application/json\", \"application/vnd.hal+json\"].includes(headers.get(\"content-type\")?.trim());\n   * ```\n   */\n  isJsonContentType?: (headers: Headers) => boolean\n  /**\n   * Defaults to `application/json`;\n   */\n  jsonContentType?: string\n\n  /**\n   * Custom replacer function used when calling `JSON.stringify()`;\n   */\n  jsonReplacer?: (this: any, key: string, value: any) => any\n} & RequestInit &\n  Pick<FetchArgs, 'responseHandler' | 'validateStatus' | 'timeout'>\n\nexport type FetchBaseQueryMeta = { request: Request; response?: Response }\n\n/**\n * This is a very small wrapper around fetch that aims to simplify requests.\n *\n * @example\n * ```ts\n * const baseQuery = fetchBaseQuery({\n *   baseUrl: 'https://api.your-really-great-app.com/v1/',\n *   prepareHeaders: (headers, { getState }) => {\n *     const token = (getState() as RootState).auth.token;\n *     // If we have a token set in state, let's assume that we should be passing it.\n *     if (token) {\n *       headers.set('authorization', `Bearer ${token}`);\n *     }\n *     return headers;\n *   },\n * })\n * ```\n *\n * @param {string} baseUrl\n * The base URL for an API service.\n * Typically in the format of https://example.com/\n *\n * @param {(headers: Headers, api: { getState: () => unknown; arg: string | FetchArgs; extra: unknown; endpoint: string; type: 'query' | 'mutation'; forced: boolean; }) => Headers} prepareHeaders\n * An optional function that can be used to inject headers on requests.\n * Provides a Headers object, most of the `BaseQueryApi` (`dispatch` is not available), and the arg passed into the query function.\n * Useful for setting authentication or headers that need to be set conditionally.\n *\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Headers\n *\n * @param {(input: RequestInfo, init?: RequestInit | undefined) => Promise<Response>} fetchFn\n * Accepts a custom `fetch` function if you do not want to use the default on the window.\n * Useful in SSR environments if you need to use a library such as `isomorphic-fetch` or `cross-fetch`\n *\n * @param {(params: Record<string, unknown>) => string} paramsSerializer\n * An optional function that can be used to stringify querystring parameters.\n *\n * @param {(headers: Headers) => boolean} isJsonContentType\n * An optional predicate function to determine if `JSON.stringify()` should be called on the `body` arg of `FetchArgs`\n *\n * @param {string} jsonContentType Used when automatically setting the content-type header for a request with a jsonifiable body that does not have an explicit content-type header. Defaults to `application/json`.\n *\n * @param {(this: any, key: string, value: any) => any} jsonReplacer Custom replacer function used when calling `JSON.stringify()`.\n *\n * @param {number} timeout\n * A number in milliseconds that represents the maximum time a request can take before timing out.\n */\n\nexport function fetchBaseQuery({\n  baseUrl,\n  prepareHeaders = (x) => x,\n  fetchFn = defaultFetchFn,\n  paramsSerializer,\n  isJsonContentType = defaultIsJsonContentType,\n  jsonContentType = 'application/json',\n  jsonReplacer,\n  timeout: defaultTimeout,\n  responseHandler: globalResponseHandler,\n  validateStatus: globalValidateStatus,\n  ...baseFetchOptions\n}: FetchBaseQueryArgs = {}): BaseQueryFn<\n  string | FetchArgs,\n  unknown,\n  FetchBaseQueryError,\n  {},\n  FetchBaseQueryMeta\n> {\n  if (typeof fetch === 'undefined' && fetchFn === defaultFetchFn) {\n    console.warn(\n      'Warning: `fetch` is not available. Please supply a custom `fetchFn` property to use `fetchBaseQuery` on SSR environments.',\n    )\n  }\n  return async (arg, api, extraOptions) => {\n    const { getState, extra, endpoint, forced, type } = api\n    let meta: FetchBaseQueryMeta | undefined\n    let {\n      url,\n      headers = new Headers(baseFetchOptions.headers),\n      params = undefined,\n      responseHandler = globalResponseHandler ?? ('json' as const),\n      validateStatus = globalValidateStatus ?? defaultValidateStatus,\n      timeout = defaultTimeout,\n      ...rest\n    } = typeof arg == 'string' ? { url: arg } : arg\n\n    let config: RequestInit = {\n      ...baseFetchOptions,\n      signal: timeout\n        ? anySignal(api.signal, timeoutSignal(timeout))\n        : api.signal,\n      ...rest,\n    }\n\n    headers = new Headers(stripUndefined(headers))\n    config.headers =\n      (await prepareHeaders(headers, {\n        getState,\n        arg,\n        extra,\n        endpoint,\n        forced,\n        type,\n        extraOptions,\n      })) || headers\n\n    const bodyIsJsonifiable = isJsonifiable(config.body)\n\n    // Remove content-type for non-jsonifiable bodies to let the browser set it automatically\n    // Exception: keep content-type for string bodies as they might be intentional (text/plain, text/html, etc.)\n    if (\n      config.body != null &&\n      !bodyIsJsonifiable &&\n      typeof config.body !== 'string'\n    ) {\n      config.headers.delete('content-type')\n    }\n\n    if (!config.headers.has('content-type') && bodyIsJsonifiable) {\n      config.headers.set('content-type', jsonContentType)\n    }\n\n    if (bodyIsJsonifiable && isJsonContentType(config.headers)) {\n      config.body = JSON.stringify(config.body, jsonReplacer)\n    }\n\n    // Set Accept header based on responseHandler if not already set\n    if (!config.headers.has('accept')) {\n      if (responseHandler === 'json') {\n        config.headers.set('accept', 'application/json')\n      } else if (responseHandler === 'text') {\n        config.headers.set('accept', 'text/plain, text/html, */*')\n      }\n      // For 'content-type' responseHandler, don't set Accept (let server decide)\n    }\n\n    if (params) {\n      const divider = ~url.indexOf('?') ? '&' : '?'\n      const query = paramsSerializer\n        ? paramsSerializer(params)\n        : new URLSearchParams(stripUndefined(params))\n      url += divider + query\n    }\n\n    url = joinUrls(baseUrl, url)\n\n    const request = new Request(url, config)\n    const requestClone = new Request(url, config)\n    meta = { request: requestClone }\n\n    let response\n    try {\n      response = await fetchFn(request)\n    } catch (e) {\n      return {\n        error: {\n          status:\n            (e instanceof Error ||\n              (typeof DOMException !== 'undefined' &&\n                e instanceof DOMException)) &&\n            e.name === 'TimeoutError'\n              ? 'TIMEOUT_ERROR'\n              : 'FETCH_ERROR',\n          error: String(e),\n        },\n        meta,\n      }\n    }\n    const responseClone = response.clone()\n\n    meta.response = responseClone\n\n    let resultData: any\n    let responseText: string = ''\n    try {\n      let handleResponseError\n      await Promise.all([\n        handleResponse(response, responseHandler).then(\n          (r) => (resultData = r),\n          (e) => (handleResponseError = e),\n        ),\n        // see https://github.com/node-fetch/node-fetch/issues/665#issuecomment-538995182\n        // we *have* to \"use up\" both streams at the same time or they will stop running in node-fetch scenarios\n        responseClone.text().then(\n          (r) => (responseText = r),\n          () => {},\n        ),\n      ])\n      if (handleResponseError) throw handleResponseError\n    } catch (e) {\n      return {\n        error: {\n          status: 'PARSING_ERROR',\n          originalStatus: response.status,\n          data: responseText,\n          error: String(e),\n        },\n        meta,\n      }\n    }\n\n    return validateStatus(response, resultData)\n      ? {\n          data: resultData,\n          meta,\n        }\n      : {\n          error: {\n            status: response.status,\n            data: resultData,\n          },\n          meta,\n        }\n  }\n\n  async function handleResponse(\n    response: Response,\n    responseHandler: ResponseHandler,\n  ) {\n    if (typeof responseHandler === 'function') {\n      return responseHandler(response)\n    }\n\n    if (responseHandler === 'content-type') {\n      responseHandler = isJsonContentType(response.headers) ? 'json' : 'text'\n    }\n\n    if (responseHandler === 'json') {\n      const text = await response.text()\n      return text.length ? JSON.parse(text) : null\n    }\n\n    return response.text()\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/index.ts",
    "content": "// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit'\n\nexport type {\n  CombinedState,\n  QueryCacheKey,\n  QueryKeys,\n  QuerySubState,\n  RootState,\n  SubscriptionOptions,\n} from './core/apiState'\nexport { QueryStatus } from './core/apiState'\nexport type { Api, ApiContext, Module } from './apiTypes'\n\nexport type {\n  BaseQueryApi,\n  BaseQueryArg,\n  BaseQueryEnhancer,\n  BaseQueryError,\n  BaseQueryExtraOptions,\n  BaseQueryFn,\n  BaseQueryMeta,\n  BaseQueryResult,\n  QueryReturnValue,\n} from './baseQueryTypes'\nexport type {\n  BaseEndpointDefinition,\n  EndpointDefinitions,\n  EndpointDefinition,\n  EndpointBuilder,\n  QueryDefinition,\n  MutationDefinition,\n  MutationExtraOptions,\n  InfiniteQueryArgFrom,\n  InfiniteQueryDefinition,\n  InfiniteQueryExtraOptions,\n  PageParamFrom,\n  TagDescription,\n  QueryArgFrom,\n  QueryExtraOptions,\n  ResultTypeFrom,\n  DefinitionType,\n  DefinitionsFromApi,\n  OverrideResultType,\n  ResultDescription,\n  TagTypesFromApi,\n  UpdateDefinitions,\n  SchemaFailureHandler,\n  SchemaFailureConverter,\n  SchemaFailureInfo,\n  SchemaType,\n} from './endpointDefinitions'\nexport { fetchBaseQuery } from './fetchBaseQuery'\nexport type {\n  FetchBaseQueryArgs,\n  FetchBaseQueryError,\n  FetchBaseQueryMeta,\n  FetchArgs,\n} from './fetchBaseQuery'\nexport { retry } from './retry'\nexport type { RetryOptions } from './retry'\nexport { setupListeners } from './core/setupListeners'\nexport { skipToken } from './core/buildSelectors'\nexport type {\n  QueryResultSelectorResult,\n  MutationResultSelectorResult,\n  SkipToken,\n} from './core/buildSelectors'\nexport type {\n  QueryActionCreatorResult,\n  MutationActionCreatorResult,\n  StartQueryActionCreatorOptions,\n} from './core/buildInitiate'\nexport type { CreateApi, CreateApiOptions } from './createApi'\nexport { buildCreateApi } from './createApi'\nexport { _NEVER, fakeBaseQuery } from './fakeBaseQuery'\nexport { copyWithStructuralSharing } from './utils/copyWithStructuralSharing'\nexport { createApi, coreModule, coreModuleName } from './core/index'\nexport type {\n  InfiniteData,\n  InfiniteQueryActionCreatorResult,\n  InfiniteQueryConfigOptions,\n  InfiniteQueryResultSelectorResult,\n  InfiniteQuerySubState,\n  TypedMutationOnQueryStarted,\n  TypedQueryOnQueryStarted,\n} from './core/index'\nexport type {\n  ApiEndpointMutation,\n  ApiEndpointQuery,\n  ApiEndpointInfiniteQuery,\n  ApiModules,\n  CoreModule,\n  PrefetchOptions,\n} from './core/module'\nexport { defaultSerializeQueryArgs } from './defaultSerializeQueryArgs'\nexport type { SerializeQueryArgs } from './defaultSerializeQueryArgs'\n\nexport type {\n  Id as TSHelpersId,\n  NoInfer as TSHelpersNoInfer,\n  Override as TSHelpersOverride,\n} from './tsHelpers'\n\nexport { NamedSchemaError } from './standardSchema'\n"
  },
  {
    "path": "packages/toolkit/src/query/react/ApiProvider.tsx",
    "content": "import { configureStore } from '@reduxjs/toolkit'\nimport type { Context } from 'react'\nimport { useContext, useEffect } from './reactImports'\nimport * as React from 'react'\nimport type { ReactReduxContextValue } from 'react-redux'\nimport { Provider, ReactReduxContext } from './reactReduxImports'\nimport { setupListeners } from './rtkqImports'\nimport type { Api } from '@reduxjs/toolkit/query'\n\n/**\n * Can be used as a `Provider` if you **do not already have a Redux store**.\n *\n * @example\n * ```tsx\n * // codeblock-meta no-transpile title=\"Basic usage - wrap your App with ApiProvider\"\n * import * as React from 'react';\n * import { ApiProvider } from '@reduxjs/toolkit/query/react';\n * import { Pokemon } from './features/Pokemon';\n *\n * function App() {\n *   return (\n *     <ApiProvider api={api}>\n *       <Pokemon />\n *     </ApiProvider>\n *   );\n * }\n * ```\n *\n * @remarks\n * Using this together with an existing redux store, both will\n * conflict with each other - please use the traditional redux setup\n * in that case.\n */\nexport function ApiProvider(props: {\n  children: any\n  api: Api<any, {}, any, any>\n  setupListeners?: Parameters<typeof setupListeners>[1] | false\n  context?: Context<ReactReduxContextValue | null>\n}) {\n  const context = props.context || ReactReduxContext\n  const existingContext = useContext(context)\n  if (existingContext) {\n    throw new Error(\n      'Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.',\n    )\n  }\n  const [store] = React.useState(() =>\n    configureStore({\n      reducer: {\n        [props.api.reducerPath]: props.api.reducer,\n      },\n      middleware: (gDM) => gDM().concat(props.api.middleware),\n    }),\n  )\n  // Adds the event listeners for online/offline/focus/etc\n  useEffect(\n    (): undefined | (() => void) =>\n      props.setupListeners === false\n        ? undefined\n        : setupListeners(store.dispatch, props.setupListeners),\n    [props.setupListeners, store.dispatch],\n  )\n\n  return (\n    <Provider store={store} context={context}>\n      {props.children}\n    </Provider>\n  )\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/react/buildHooks.ts",
    "content": "import type {\n  Selector,\n  ThunkAction,\n  ThunkDispatch,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport type {\n  Api,\n  ApiContext,\n  ApiEndpointInfiniteQuery,\n  ApiEndpointMutation,\n  ApiEndpointQuery,\n  BaseQueryFn,\n  CoreModule,\n  EndpointDefinitions,\n  InfiniteQueryActionCreatorResult,\n  InfiniteQueryArgFrom,\n  InfiniteQueryDefinition,\n  InfiniteQueryResultSelectorResult,\n  InfiniteQuerySubState,\n  MutationActionCreatorResult,\n  MutationDefinition,\n  MutationResultSelectorResult,\n  PageParamFrom,\n  PrefetchOptions,\n  QueryActionCreatorResult,\n  QueryArgFrom,\n  QueryCacheKey,\n  QueryDefinition,\n  QueryKeys,\n  QueryResultSelectorResult,\n  QuerySubState,\n  ResultTypeFrom,\n  RootState,\n  SerializeQueryArgs,\n  SkipToken,\n  SubscriptionOptions,\n  TSHelpersId,\n  TSHelpersNoInfer,\n  TSHelpersOverride,\n} from '@reduxjs/toolkit/query'\nimport { QueryStatus, skipToken } from './rtkqImports'\nimport type { DependencyList } from 'react'\nimport {\n  useCallback,\n  useDebugValue,\n  useEffect,\n  useLayoutEffect,\n  useMemo,\n  useRef,\n  useState,\n} from './reactImports'\nimport { shallowEqual } from './reactReduxImports'\n\nimport type { SubscriptionSelectors } from '../core/buildMiddleware/index'\nimport type { InfiniteData, InfiniteQueryConfigOptions } from '../core/index'\nimport type { UninitializedValue } from './constants'\nimport { UNINITIALIZED_VALUE } from './constants'\nimport type { ReactHooksModuleOptions } from './module'\nimport { useStableQueryArgs } from './useSerializedStableValue'\nimport { useShallowStableValue } from './useShallowStableValue'\nimport type { InfiniteQueryDirection } from '../core/apiState'\nimport { isInfiniteQueryDefinition } from '../endpointDefinitions'\nimport type { StartInfiniteQueryActionCreator } from '../core/buildInitiate'\n\n// Copy-pasted from React-Redux\nconst canUseDOM = () =>\n  !!(\n    typeof window !== 'undefined' &&\n    typeof window.document !== 'undefined' &&\n    typeof window.document.createElement !== 'undefined'\n  )\n\nconst isDOM = /* @__PURE__ */ canUseDOM()\n\n// Under React Native, we know that we always want to use useLayoutEffect\n\nconst isRunningInReactNative = () =>\n  typeof navigator !== 'undefined' && navigator.product === 'ReactNative'\n\nconst isReactNative = /* @__PURE__ */ isRunningInReactNative()\n\nconst getUseIsomorphicLayoutEffect = () =>\n  isDOM || isReactNative ? useLayoutEffect : useEffect\n\nexport const useIsomorphicLayoutEffect =\n  /* @__PURE__ */ getUseIsomorphicLayoutEffect()\n\nexport type QueryHooks<\n  Definition extends QueryDefinition<any, any, any, any, any>,\n> = {\n  useQuery: UseQuery<Definition>\n  useLazyQuery: UseLazyQuery<Definition>\n  useQuerySubscription: UseQuerySubscription<Definition>\n  useLazyQuerySubscription: UseLazyQuerySubscription<Definition>\n  useQueryState: UseQueryState<Definition>\n}\n\nexport type InfiniteQueryHooks<\n  Definition extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = {\n  useInfiniteQuery: UseInfiniteQuery<Definition>\n  useInfiniteQuerySubscription: UseInfiniteQuerySubscription<Definition>\n  useInfiniteQueryState: UseInfiniteQueryState<Definition>\n}\n\nexport type MutationHooks<\n  Definition extends MutationDefinition<any, any, any, any, any>,\n> = {\n  useMutation: UseMutation<Definition>\n}\n\n/**\n * A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.\n *\n * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.\n *\n * This hook combines the functionality of both [`useQueryState`](#usequerystate) and [`useQuerySubscription`](#usequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport type UseQuery<D extends QueryDefinition<any, any, any, any>> = <\n  R extends Record<string, any> = UseQueryStateDefaultResult<D>,\n>(\n  arg: QueryArgFrom<D> | SkipToken,\n  options?: UseQuerySubscriptionOptions & UseQueryStateOptions<D, R>,\n) => UseQueryHookResult<D, R>\n\nexport type TypedUseQuery<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n> = UseQuery<QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>>\n\nexport type UseQueryHookResult<\n  D extends QueryDefinition<any, any, any, any>,\n  R = UseQueryStateDefaultResult<D>,\n> = UseQueryStateResult<D, R> & UseQuerySubscriptionResult<D>\n\n/**\n * Helper type to manually type the result\n * of the `useQuery` hook in userland code.\n */\nexport type TypedUseQueryHookResult<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  R = UseQueryStateDefaultResult<\n    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>\n  >,\n> = TypedUseQueryStateResult<ResultType, QueryArg, BaseQuery, R> &\n  TypedUseQuerySubscriptionResult<ResultType, QueryArg, BaseQuery>\n\nexport type UseQuerySubscriptionOptions = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number\n}\n\n/**\n * Provides a way to reference the options accepted by the `useQuerySubscription`\n * hook in userland code.\n *\n * Unlike other `Typed*` wrappers, this type has no generic parameters since\n * {@linkcode UseQuerySubscriptionOptions} does not depend on a specific query\n * definition.\n *\n * @since 2.11.3\n * @public\n */\nexport type TypedUseQuerySubscriptionOptions = UseQuerySubscriptionOptions\n\n/**\n * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data.\n *\n * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useQuery`](#usequery) or [`useQueryState`](#usequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseQuerySubscription<\n  D extends QueryDefinition<any, any, any, any>,\n> = (\n  arg: QueryArgFrom<D> | SkipToken,\n  options?: UseQuerySubscriptionOptions,\n) => UseQuerySubscriptionResult<D>\n\nexport type TypedUseQuerySubscription<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n> = UseQuerySubscription<\n  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>\n>\n\nexport type UseQuerySubscriptionResult<\n  D extends QueryDefinition<any, any, any, any>,\n> = Pick<QueryActionCreatorResult<D>, 'refetch'>\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseQuerySubscriptionResult<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n> = UseQuerySubscriptionResult<\n  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>\n>\n\nexport type UseLazyQueryLastPromiseInfo<\n  D extends QueryDefinition<any, any, any, any>,\n> = {\n  lastArg: QueryArgFrom<D>\n}\n\n/**\n * A React hook similar to [`useQuery`](#usequery), but with manual control over when the data fetching occurs.\n *\n * This hook includes the functionality of [`useLazyQuerySubscription`](#uselazyquerysubscription).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once\n *\n * #### Note\n *\n * When the trigger function returned from a LazyQuery is called, it always initiates a new request to the server even if there is cached data. Set `preferCacheValue`(the second argument to the function) as `true` if you want it to immediately return a cached value if one exists.\n */\nexport type UseLazyQuery<D extends QueryDefinition<any, any, any, any>> = <\n  R extends Record<string, any> = UseQueryStateDefaultResult<D>,\n>(\n  options?: SubscriptionOptions & Omit<UseQueryStateOptions<D, R>, 'skip'>,\n) => [\n  LazyQueryTrigger<D>,\n  UseLazyQueryStateResult<D, R>,\n  UseLazyQueryLastPromiseInfo<D>,\n]\n\nexport type TypedUseLazyQuery<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n> = UseLazyQuery<\n  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>\n>\n\nexport type UseLazyQueryStateResult<\n  D extends QueryDefinition<any, any, any, any>,\n  R = UseQueryStateDefaultResult<D>,\n> = UseQueryStateResult<D, R> & {\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void\n}\n\n/**\n * Helper type to manually type the result\n * of the `useLazyQuery` hook in userland code.\n */\nexport type TypedUseLazyQueryStateResult<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  R = UseQueryStateDefaultResult<\n    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>\n  >,\n> = UseLazyQueryStateResult<\n  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>,\n  R\n>\n\nexport type LazyQueryTrigger<D extends QueryDefinition<any, any, any, any>> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload);\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (\n    arg: QueryArgFrom<D>,\n    preferCacheValue?: boolean,\n  ): QueryActionCreatorResult<D>\n}\n\nexport type TypedLazyQueryTrigger<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n> = LazyQueryTrigger<\n  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>\n>\n\n/**\n * A React hook similar to [`useQuerySubscription`](#usequerysubscription), but with manual control over when the data fetching occurs.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useLazyQuery`](#uselazyquery).\n *\n * #### Features\n *\n * - Manual control over firing a request to retrieve data\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met and the fetch has been manually called at least once\n */\nexport type UseLazyQuerySubscription<\n  D extends QueryDefinition<any, any, any, any>,\n> = (\n  options?: SubscriptionOptions,\n) => readonly [\n  LazyQueryTrigger<D>,\n  QueryArgFrom<D> | UninitializedValue,\n  { reset: () => void },\n]\n\nexport type TypedUseLazyQuerySubscription<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n> = UseLazyQuerySubscription<\n  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>\n>\n\n/**\n * @internal\n */\nexport type QueryStateSelector<\n  R extends Record<string, any>,\n  D extends QueryDefinition<any, any, any, any>,\n> = (state: UseQueryStateDefaultResult<D>) => R\n\n/**\n * Provides a way to define a strongly-typed version of\n * {@linkcode QueryStateSelector} for use with a specific query.\n * This is useful for scenarios where you want to create a \"pre-typed\"\n * {@linkcode UseQueryStateOptions.selectFromResult | selectFromResult}\n * function.\n *\n * @example\n * <caption>#### __Create a strongly-typed `selectFromResult` selector function__</caption>\n *\n * ```tsx\n * import type { TypedQueryStateSelector } from '@reduxjs/toolkit/query/react';\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n *\n * type Post = {\n *   id: number;\n *   title: string;\n * };\n *\n * type PostsApiResponse = {\n *   posts: Post[];\n *   total: number;\n *   skip: number;\n *   limit: number;\n * };\n *\n * type QueryArgument = number | undefined;\n *\n * type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>;\n *\n * type SelectedResult = Pick<PostsApiResponse, 'posts'>;\n *\n * const postsApiSlice = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),\n *   reducerPath: 'postsApi',\n *   tagTypes: ['Posts'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsApiResponse, QueryArgument>({\n *       query: (limit = 5) => `?limit=${limit}&select=title`,\n *     }),\n *   }),\n * });\n *\n * const { useGetPostsQuery } = postsApiSlice;\n *\n * function PostById({ id }: { id: number }) {\n *   const { post } = useGetPostsQuery(undefined, {\n *     selectFromResult: (state) => ({\n *       post: state.data?.posts.find((post) => post.id === id),\n *     }),\n *   });\n *\n *   return <li>{post?.title}</li>;\n * }\n *\n * const EMPTY_ARRAY: Post[] = [];\n *\n * const typedSelectFromResult: TypedQueryStateSelector<\n *   PostsApiResponse,\n *   QueryArgument,\n *   BaseQueryFunction,\n *   SelectedResult\n * > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY });\n *\n * function PostsList() {\n *   const { posts } = useGetPostsQuery(undefined, {\n *     selectFromResult: typedSelectFromResult,\n *   });\n *\n *   return (\n *     <div>\n *       <ul>\n *         {posts.map((post) => (\n *           <PostById key={post.id} id={post.id} />\n *         ))}\n *       </ul>\n *     </div>\n *   );\n * }\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArgumentType - The type of the argument passed into the query.\n * @template BaseQueryFunctionType - The type of the base query function being used.\n * @template SelectedResultType - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.3.0\n * @public\n */\nexport type TypedQueryStateSelector<\n  ResultType,\n  QueryArgumentType,\n  BaseQueryFunctionType extends BaseQueryFn,\n  SelectedResultType extends Record<string, any> = UseQueryStateDefaultResult<\n    QueryDefinition<\n      QueryArgumentType,\n      BaseQueryFunctionType,\n      string,\n      ResultType,\n      string\n    >\n  >,\n> = QueryStateSelector<\n  SelectedResultType,\n  QueryDefinition<\n    QueryArgumentType,\n    BaseQueryFunctionType,\n    string,\n    ResultType,\n    string\n  >\n>\n\n/**\n * A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useQuery`](#usequery) or [`useQuerySubscription`](#usequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport type UseQueryState<D extends QueryDefinition<any, any, any, any>> = <\n  R extends Record<string, any> = UseQueryStateDefaultResult<D>,\n>(\n  arg: QueryArgFrom<D> | SkipToken,\n  options?: UseQueryStateOptions<D, R>,\n) => UseQueryStateResult<D, R>\n\nexport type TypedUseQueryState<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n> = UseQueryState<\n  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>\n>\n\n/**\n * @internal\n */\nexport type UseQueryStateOptions<\n  D extends QueryDefinition<any, any, any, any>,\n  R extends Record<string, any>,\n> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({\n   *       post: data?.find((post) => post.id === id),\n   *     }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: QueryStateSelector<R, D>\n}\n\n/**\n * Provides a way to define a \"pre-typed\" version of\n * {@linkcode UseQueryStateOptions} with specific options for a given query.\n * This is particularly useful for setting default query behaviors such as\n * refetching strategies, which can be overridden as needed.\n *\n * @example\n * <caption>#### __Create a `useQuery` hook with default options__</caption>\n *\n * ```ts\n * import type {\n *   SubscriptionOptions,\n *   TypedUseQueryStateOptions,\n * } from '@reduxjs/toolkit/query/react';\n * import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react';\n *\n * type Post = {\n *   id: number;\n *   name: string;\n * };\n *\n * const api = createApi({\n *   baseQuery: fetchBaseQuery({ baseUrl: '/' }),\n *   tagTypes: ['Post'],\n *   endpoints: (build) => ({\n *     getPosts: build.query<Post[], void>({\n *       query: () => 'posts',\n *     }),\n *   }),\n * });\n *\n * const { useGetPostsQuery } = api;\n *\n * export const useGetPostsQueryWithDefaults = <\n *   SelectedResult extends Record<string, any>,\n * >(\n *   overrideOptions: TypedUseQueryStateOptions<\n *     Post[],\n *     void,\n *     ReturnType<typeof fetchBaseQuery>,\n *     SelectedResult\n *   > &\n *     SubscriptionOptions,\n * ) =>\n *   useGetPostsQuery(undefined, {\n *     // Insert default options here\n *\n *     refetchOnMountOrArgChange: true,\n *     refetchOnFocus: true,\n *     ...overrideOptions,\n *   });\n * ```\n *\n * @template ResultType - The type of the result `data` returned by the query.\n * @template QueryArg - The type of the argument passed into the query.\n * @template BaseQuery - The type of the base query function being used.\n * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.2.8\n * @public\n */\nexport type TypedUseQueryStateOptions<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  SelectedResult extends Record<string, any> = UseQueryStateDefaultResult<\n    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>\n  >,\n> = UseQueryStateOptions<\n  QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>,\n  SelectedResult\n>\n\nexport type UseQueryStateResult<\n  _ extends QueryDefinition<any, any, any, any>,\n  R,\n> = TSHelpersNoInfer<R>\n\n/**\n * Helper type to manually type the result\n * of the `useQueryState` hook in userland code.\n */\nexport type TypedUseQueryStateResult<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  R = UseQueryStateDefaultResult<\n    QueryDefinition<QueryArg, BaseQuery, string, ResultType, string>\n  >,\n> = TSHelpersNoInfer<R>\n\ntype UseQueryStateBaseResult<D extends QueryDefinition<any, any, any, any>> =\n  QuerySubState<D> & {\n    /**\n     * Where `data` tries to hold data as much as possible, also re-using\n     * data from the last arguments passed into the hook, this property\n     * will always contain the received data from the query, for the current query arguments.\n     */\n    currentData?: ResultTypeFrom<D>\n    /**\n     * Query has not started yet.\n     */\n    isUninitialized: false\n    /**\n     * Query is currently loading for the first time. No data yet.\n     */\n    isLoading: false\n    /**\n     * Query is currently fetching, but might have data from an earlier request.\n     */\n    isFetching: false\n    /**\n     * Query has data from a successful load.\n     */\n    isSuccess: false\n    /**\n     * Query is currently in \"error\" state.\n     */\n    isError: false\n  }\n\ntype UseQueryStateUninitialized<D extends QueryDefinition<any, any, any, any>> =\n  TSHelpersOverride<\n    Extract<UseQueryStateBaseResult<D>, { status: QueryStatus.uninitialized }>,\n    { isUninitialized: true }\n  >\n\ntype UseQueryStateLoading<D extends QueryDefinition<any, any, any, any>> =\n  TSHelpersOverride<\n    UseQueryStateBaseResult<D>,\n    { isLoading: true; isFetching: boolean; data: undefined }\n  >\n\ntype UseQueryStateSuccessFetching<\n  D extends QueryDefinition<any, any, any, any>,\n> = TSHelpersOverride<\n  UseQueryStateBaseResult<D>,\n  {\n    isSuccess: true\n    isFetching: true\n    error: undefined\n  } & {\n    data: ResultTypeFrom<D>\n  } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>\n>\n\ntype UseQueryStateSuccessNotFetching<\n  D extends QueryDefinition<any, any, any, any>,\n> = TSHelpersOverride<\n  UseQueryStateBaseResult<D>,\n  {\n    isSuccess: true\n    isFetching: false\n    error: undefined\n  } & {\n    data: ResultTypeFrom<D>\n    currentData: ResultTypeFrom<D>\n  } & Required<Pick<UseQueryStateBaseResult<D>, 'fulfilledTimeStamp'>>\n>\n\ntype UseQueryStateError<D extends QueryDefinition<any, any, any, any>> =\n  TSHelpersOverride<\n    UseQueryStateBaseResult<D>,\n    { isError: true } & Required<Pick<UseQueryStateBaseResult<D>, 'error'>>\n  >\n\ntype UseQueryStateDefaultResult<D extends QueryDefinition<any, any, any, any>> =\n  TSHelpersId<\n    | UseQueryStateUninitialized<D>\n    | UseQueryStateLoading<D>\n    | UseQueryStateSuccessFetching<D>\n    | UseQueryStateSuccessNotFetching<D>\n    | UseQueryStateError<D>\n  > & {\n    /**\n     * @deprecated Included for completeness, but discouraged.\n     * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n     * and `isUninitialized` flags instead\n     */\n    status: QueryStatus\n  }\n\nexport type LazyInfiniteQueryTrigger<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = {\n  /**\n   * Triggers a lazy query.\n   *\n   * By default, this will start a new request even if there is already a value in the cache.\n   * If you want to use the cache value and only start a request if there is no cache value, set the second argument to `true`.\n   *\n   * @remarks\n   * If you need to access the error or success payload immediately after a lazy query, you can chain .unwrap().\n   *\n   * @example\n   * ```ts\n   * // codeblock-meta title=\"Using .unwrap with async await\"\n   * try {\n   *   const payload = await getUserById(1).unwrap();\n   *   console.log('fulfilled', payload);\n   * } catch (error) {\n   *   console.error('rejected', error);\n   * }\n   * ```\n   */\n  (\n    arg: QueryArgFrom<D>,\n    direction: InfiniteQueryDirection,\n  ): InfiniteQueryActionCreatorResult<D>\n}\n\nexport type TypedLazyInfiniteQueryTrigger<\n  ResultType,\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n> = LazyInfiniteQueryTrigger<\n  InfiniteQueryDefinition<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    string,\n    ResultType,\n    string\n  >\n>\n\nexport type UseInfiniteQuerySubscriptionOptions<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = SubscriptionOptions & {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When `skip` is true (or `skipToken` is passed in as `arg`):\n   *\n   * - **If the query has cached data:**\n   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta no-transpile title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean\n  /**\n   * Defaults to `false`. This setting allows you to control whether if a cached result is already available, RTK Query will only serve a cached result, or if it should `refetch` when set to `true` or if an adequate amount of time has passed since the last successful query result.\n   * - `false` - Will not cause a query to be performed _unless_ it does not exist yet.\n   * - `true` - Will always refetch when a new subscriber to a query is added. Behaves the same as calling the `refetch` callback or passing `forceRefetch: true` in the action creator.\n   * - `number` - **Value is in seconds**. If a number is provided and there is an existing query in the cache, it will compare the current time vs the last fulfilled timestamp, and only refetch if enough time has elapsed.\n   *\n   * If you specify this option alongside `skip: true`, this **will not be evaluated** until `skip` is false.\n   */\n  refetchOnMountOrArgChange?: boolean | number\n  initialPageParam?: PageParamFrom<D>\n  /**\n   * Defaults to `true`. When this is `true` and an infinite query endpoint is refetched\n   * (due to tag invalidation, polling, arg change configuration, or manual refetching),\n   * RTK Query will try to sequentially refetch all pages currently in the cache.\n   * When `false` only the first page will be refetched.\n   *\n   * This option applies to all automatic refetches for this subscription (polling, tag invalidation, etc.).\n   * It can be overridden on a per-call basis using the `refetch()` method.\n   */\n  refetchCachedPages?: boolean\n}\n\nexport type TypedUseInfiniteQuerySubscription<\n  ResultType,\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n> = UseInfiniteQuerySubscription<\n  InfiniteQueryDefinition<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    string,\n    ResultType,\n    string\n  >\n>\n\nexport type UseInfiniteQuerySubscriptionResult<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = {\n  refetch: (\n    options?: Pick<\n      UseInfiniteQuerySubscriptionOptions<D>,\n      'refetchCachedPages'\n    >,\n  ) => InfiniteQueryActionCreatorResult<D>\n  trigger: LazyInfiniteQueryTrigger<D>\n  fetchNextPage: () => InfiniteQueryActionCreatorResult<D>\n  fetchPreviousPage: () => InfiniteQueryActionCreatorResult<D>\n}\n\n/**\n * Helper type to manually type the result\n * of the `useQuerySubscription` hook in userland code.\n */\nexport type TypedUseInfiniteQuerySubscriptionResult<\n  ResultType,\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n> = UseInfiniteQuerySubscriptionResult<\n  InfiniteQueryDefinition<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    string,\n    ResultType,\n    string\n  >\n>\n\nexport type InfiniteQueryStateSelector<\n  R extends Record<string, any>,\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = (state: UseInfiniteQueryStateDefaultResult<D>) => R\n\nexport type TypedInfiniteQueryStateSelector<\n  ResultType,\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n  SelectedResult extends Record<\n    string,\n    any\n  > = UseInfiniteQueryStateDefaultResult<\n    InfiniteQueryDefinition<\n      QueryArg,\n      PageParam,\n      BaseQuery,\n      string,\n      ResultType,\n      string\n    >\n  >,\n> = InfiniteQueryStateSelector<\n  SelectedResult,\n  InfiniteQueryDefinition<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    string,\n    ResultType,\n    string\n  >\n>\n\n/**\n * A React hook that automatically triggers fetches of data from an endpoint, 'subscribes' the component to the cached data, and reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.  Additionally, it will cache multiple \"pages\" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.\n *\n * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already, and the hook will return the data for that query arg once it's available.\n *\n *  The `data` field will be a `{pages: Data[], pageParams: PageParam[]}` structure containing all fetched page responses and the corresponding page param values for each page. You may use this to render individual pages, combine all pages into a single infinite list, or other display logic as needed.\n *\n * This hook combines the functionality of both [`useInfiniteQueryState`](#useinfinitequerystate) and [`useInfiniteQuerySubscription`](#useinfinitequerysubscription) together, and is intended to be used in the majority of situations.\n *\n * As with normal query hooks, `skipToken` is a valid argument that will skip the query from executing.\n *\n * By default, the initial request will use the `initialPageParam` value that was defined on the infinite query endpoint. If you want to start from a different value, you can pass `initialPageParam` as part of the hook options to override that initial request value.\n *\n * Use the returned `fetchNextPage` and `fetchPreviousPage` methods on the hook result object to trigger fetches forwards and backwards. These will always calculate the next or previous page param based on the current cached pages and the provided `getNext/PreviousPageParam` callbacks defined in the endpoint.\n *\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport type UseInfiniteQuery<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(\n  arg: InfiniteQueryArgFrom<D> | SkipToken,\n  options?: UseInfiniteQuerySubscriptionOptions<D> &\n    UseInfiniteQueryStateOptions<D, R>,\n) => UseInfiniteQueryHookResult<D, R> &\n  Pick<\n    UseInfiniteQuerySubscriptionResult<D>,\n    'fetchNextPage' | 'fetchPreviousPage'\n  >\n\nexport type TypedUseInfiniteQuery<\n  ResultType,\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n> = UseInfiniteQuery<\n  InfiniteQueryDefinition<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    string,\n    ResultType,\n    string\n  >\n>\n\n/**\n * A React hook that reads the request status and cached data from the Redux store. The component will re-render as the loading status changes and the data becomes available.\n *\n * Note that this hook does not trigger fetching new data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQuerySubscription`](#useinfinitequerysubscription).\n *\n * #### Features\n *\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport type UseInfiniteQueryState<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = <R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<D>>(\n  arg: InfiniteQueryArgFrom<D> | SkipToken,\n  options?: UseInfiniteQueryStateOptions<D, R>,\n) => UseInfiniteQueryStateResult<D, R>\n\nexport type TypedUseInfiniteQueryState<\n  ResultType,\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n> = UseInfiniteQueryState<\n  InfiniteQueryDefinition<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    string,\n    ResultType,\n    string\n  >\n>\n\n/**\n * A React hook that automatically triggers fetches of data from an endpoint, and 'subscribes' the component to the cached data. Additionally, it will cache multiple \"pages\" worth of responses within a single cache entry, and allows fetching more pages forwards and backwards from the current cached pages.\n *\n * The query arg is used as a cache key. Changing the query arg will tell the hook to re-fetch the data if it does not exist in the cache already.\n *\n * Note that this hook does not return a request status or cached data. For that use-case, see [`useInfiniteQuery`](#useinfinitequery) or [`useInfiniteQueryState`](#useinfinitequerystate).\n *\n * #### Features\n *\n * - Automatically triggers requests to retrieve data based on the hook argument and whether cached data exists by default\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Caches multiple pages worth of responses, and provides methods to trigger more page fetches forwards and backwards\n * - Accepts polling/re-fetching options to trigger automatic re-fetches when the corresponding criteria is met\n */\nexport type UseInfiniteQuerySubscription<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = (\n  arg: InfiniteQueryArgFrom<D> | SkipToken,\n  options?: UseInfiniteQuerySubscriptionOptions<D>,\n) => UseInfiniteQuerySubscriptionResult<D>\n\nexport type UseInfiniteQueryHookResult<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n  R = UseInfiniteQueryStateDefaultResult<D>,\n> = UseInfiniteQueryStateResult<D, R> &\n  Pick<\n    UseInfiniteQuerySubscriptionResult<D>,\n    'refetch' | 'fetchNextPage' | 'fetchPreviousPage'\n  >\n\nexport type TypedUseInfiniteQueryHookResult<\n  ResultType,\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n  R extends Record<string, any> = UseInfiniteQueryStateDefaultResult<\n    InfiniteQueryDefinition<\n      QueryArg,\n      PageParam,\n      BaseQuery,\n      string,\n      ResultType,\n      string\n    >\n  >,\n> = UseInfiniteQueryHookResult<\n  InfiniteQueryDefinition<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    string,\n    ResultType,\n    string\n  >,\n  R\n>\n\nexport type UseInfiniteQueryStateOptions<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n  R extends Record<string, any>,\n> = {\n  /**\n   * Prevents a query from automatically running.\n   *\n   * @remarks\n   * When skip is true:\n   *\n   * - **If the query has cached data:**\n   *   * The cached data **will not be used** on the initial load, and will ignore updates from any identical query until the `skip` condition is removed\n   *   * The query will have a status of `uninitialized`\n   *   * If `skip: false` is set after skipping the initial load, the cached result will be used\n   * - **If the query does not have cached data:**\n   *   * The query will have a status of `uninitialized`\n   *   * The query will not exist in the state when viewed with the dev tools\n   *   * The query will not automatically fetch on mount\n   *   * The query will not automatically run when additional components with the same query are added that do run\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta title=\"Skip example\"\n   * const Pokemon = ({ name, skip }: { name: string; skip: boolean }) => {\n   *   const { data, error, status } = useGetPokemonByNameQuery(name, {\n   *     skip,\n   *   });\n   *\n   *   return (\n   *     <div>\n   *       {name} - {status}\n   *     </div>\n   *   );\n   * };\n   * ```\n   */\n  skip?: boolean\n  /**\n   * `selectFromResult` allows you to get a specific segment from a query result in a performant manner.\n   * When using this feature, the component will not rerender unless the underlying data of the selected item has changed.\n   * If the selected item is one element in a larger collection, it will disregard changes to elements in the same collection.\n   * Note that this should always return an object (not a primitive), as RTKQ adds fields to the return value.\n   *\n   * @example\n   * ```tsx\n   * // codeblock-meta title=\"Using selectFromResult to extract a single result\"\n   * function PostsList() {\n   *   const { data: posts } = api.useGetPostsQuery();\n   *\n   *   return (\n   *     <ul>\n   *       {posts?.data?.map((post) => (\n   *         <PostById key={post.id} id={post.id} />\n   *       ))}\n   *     </ul>\n   *   );\n   * }\n   *\n   * function PostById({ id }: { id: number }) {\n   *   // Will select the post with the given id, and will only rerender if the given posts data changes\n   *   const { post } = api.useGetPostsQuery(undefined, {\n   *     selectFromResult: ({ data }) => ({\n   *       post: data?.find((post) => post.id === id),\n   *     }),\n   *   });\n   *\n   *   return <li>{post?.name}</li>;\n   * }\n   * ```\n   */\n  selectFromResult?: InfiniteQueryStateSelector<R, D>\n}\n\nexport type TypedUseInfiniteQueryStateOptions<\n  ResultType,\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n  SelectedResult extends Record<\n    string,\n    any\n  > = UseInfiniteQueryStateDefaultResult<\n    InfiniteQueryDefinition<\n      QueryArg,\n      PageParam,\n      BaseQuery,\n      string,\n      ResultType,\n      string\n    >\n  >,\n> = UseInfiniteQueryStateOptions<\n  InfiniteQueryDefinition<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    string,\n    ResultType,\n    string\n  >,\n  SelectedResult\n>\n\nexport type UseInfiniteQueryStateResult<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n  R = UseInfiniteQueryStateDefaultResult<D>,\n> = TSHelpersNoInfer<R>\n\nexport type TypedUseInfiniteQueryStateResult<\n  ResultType,\n  QueryArg,\n  PageParam,\n  BaseQuery extends BaseQueryFn,\n  R = UseInfiniteQueryStateDefaultResult<\n    InfiniteQueryDefinition<\n      QueryArg,\n      PageParam,\n      BaseQuery,\n      string,\n      ResultType,\n      string\n    >\n  >,\n> = UseInfiniteQueryStateResult<\n  InfiniteQueryDefinition<\n    QueryArg,\n    PageParam,\n    BaseQuery,\n    string,\n    ResultType,\n    string\n  >,\n  R\n>\n\ntype UseInfiniteQueryStateBaseResult<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = InfiniteQuerySubState<D> & {\n  /**\n   * Where `data` tries to hold data as much as possible, also re-using\n   * data from the last arguments passed into the hook, this property\n   * will always contain the received data from the query, for the current query arguments.\n   */\n  currentData?: InfiniteData<ResultTypeFrom<D>, PageParamFrom<D>>\n  /**\n   * Query has not started yet.\n   */\n  isUninitialized: false\n  /**\n   * Query is currently loading for the first time. No data yet.\n   */\n  isLoading: false\n  /**\n   * Query is currently fetching, but might have data from an earlier request.\n   */\n  isFetching: false\n  /**\n   * Query has data from a successful load.\n   */\n  isSuccess: false\n  /**\n   * Query is currently in \"error\" state.\n   */\n  isError: false\n  hasNextPage: boolean\n  hasPreviousPage: boolean\n  isFetchingNextPage: boolean\n  isFetchingPreviousPage: boolean\n}\n\ntype UseInfiniteQueryStateDefaultResult<\n  D extends InfiniteQueryDefinition<any, any, any, any, any>,\n> = TSHelpersId<\n  | TSHelpersOverride<\n      Extract<\n        UseInfiniteQueryStateBaseResult<D>,\n        { status: QueryStatus.uninitialized }\n      >,\n      { isUninitialized: true }\n    >\n  | TSHelpersOverride<\n      UseInfiniteQueryStateBaseResult<D>,\n      | { isLoading: true; isFetching: boolean; data: undefined }\n      | ({\n          isSuccess: true\n          isFetching: true\n          error: undefined\n        } & Required<\n          Pick<\n            UseInfiniteQueryStateBaseResult<D>,\n            'data' | 'fulfilledTimeStamp'\n          >\n        >)\n      | ({\n          isSuccess: true\n          isFetching: false\n          error: undefined\n        } & Required<\n          Pick<\n            UseInfiniteQueryStateBaseResult<D>,\n            'data' | 'fulfilledTimeStamp' | 'currentData'\n          >\n        >)\n      | ({ isError: true } & Required<\n          Pick<UseInfiniteQueryStateBaseResult<D>, 'error'>\n        >)\n    >\n> & {\n  /**\n   * @deprecated Included for completeness, but discouraged.\n   * Please use the `isLoading`, `isFetching`, `isSuccess`, `isError`\n   * and `isUninitialized` flags instead\n   */\n  status: QueryStatus\n}\n\nexport type MutationStateSelector<\n  R extends Record<string, any>,\n  D extends MutationDefinition<any, any, any, any>,\n> = (state: MutationResultSelectorResult<D>) => R\n\nexport type UseMutationStateOptions<\n  D extends MutationDefinition<any, any, any, any>,\n  R extends Record<string, any>,\n> = {\n  selectFromResult?: MutationStateSelector<R, D>\n  fixedCacheKey?: string\n}\n\n/**\n * Provides a way to define a \"pre-typed\" version of\n * {@linkcode UseMutationStateOptions} with specific options for a given mutation.\n *\n * @template ResultType - The type of the result `data` returned by the mutation.\n * @template QueryArg - The type of the argument passed into the mutation.\n * @template BaseQuery - The type of the base query function being used.\n * @template SelectedResult - The type of the selected result returned by the __`selectFromResult`__ function.\n *\n * @since 2.11.3\n * @public\n */\nexport type TypedUseMutationStateOptions<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  SelectedResult extends Record<string, any> = MutationResultSelectorResult<\n    MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>\n  >,\n> = UseMutationStateOptions<\n  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>,\n  SelectedResult\n>\n\nexport type UseMutationStateResult<\n  D extends MutationDefinition<any, any, any, any>,\n  R,\n> = TSHelpersNoInfer<R> & {\n  originalArgs?: QueryArgFrom<D>\n  /**\n   * Resets the hook state to its initial `uninitialized` state.\n   * This will also remove the last result from the cache.\n   */\n  reset: () => void\n}\n\n/**\n * Helper type to manually type the result\n * of the `useMutation` hook in userland code.\n */\nexport type TypedUseMutationResult<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n  R = MutationResultSelectorResult<\n    MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>\n  >,\n> = UseMutationStateResult<\n  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>,\n  R\n>\n\n/**\n * A React hook that lets you trigger an update request for a given endpoint, and subscribes the component to read the request status from the Redux store. The component will re-render as the loading status changes.\n *\n * #### Features\n *\n * - Manual control over firing a request to alter data on the server or possibly invalidate the cache\n * - 'Subscribes' the component to keep cached data in the store, and 'unsubscribes' when the component unmounts\n * - Returns the latest request status and cached data from the Redux store\n * - Re-renders as the request status changes and data becomes available\n */\nexport type UseMutation<D extends MutationDefinition<any, any, any, any>> = <\n  R extends Record<string, any> = MutationResultSelectorResult<D>,\n>(\n  options?: UseMutationStateOptions<D, R>,\n) => readonly [MutationTrigger<D>, UseMutationStateResult<D, R>]\n\nexport type TypedUseMutation<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n> = UseMutation<\n  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>\n>\n\nexport type MutationTrigger<D extends MutationDefinition<any, any, any, any>> =\n  {\n    /**\n     * Triggers the mutation and returns a Promise.\n     * @remarks\n     * If you need to access the error or success payload immediately after a mutation, you can chain .unwrap().\n     *\n     * @example\n     * ```ts\n     * // codeblock-meta title=\"Using .unwrap with async await\"\n     * try {\n     *   const payload = await addPost({ id: 1, name: 'Example' }).unwrap();\n     *   console.log('fulfilled', payload);\n     * } catch (error) {\n     *   console.error('rejected', error);\n     * }\n     * ```\n     */\n    (arg: QueryArgFrom<D>): MutationActionCreatorResult<D>\n  }\n\nexport type TypedMutationTrigger<\n  ResultType,\n  QueryArg,\n  BaseQuery extends BaseQueryFn,\n> = MutationTrigger<\n  MutationDefinition<QueryArg, BaseQuery, string, ResultType, string>\n>\n\n/**\n * Wrapper around `defaultQueryStateSelector` to be used in `useQuery`.\n * We want the initial render to already come back with\n * `{ isUninitialized: false, isFetching: true, isLoading: true }`\n * to prevent that the library user has to do an additional check for `isUninitialized`/\n */\nconst noPendingQueryStateSelector: QueryStateSelector<any, any> = (\n  selected,\n) => {\n  if (selected.isUninitialized) {\n    return {\n      ...selected,\n      isUninitialized: false,\n      isFetching: true,\n      isLoading: selected.data !== undefined ? false : true,\n      // This is the one place where we still have to use `QueryStatus` as an enum,\n      // since it's the only reference in the React package and not in the core.\n      status: QueryStatus.pending,\n    } as any\n  }\n  return selected\n}\n\nfunction pick<T, K extends keyof T>(obj: T, ...keys: K[]): Pick<T, K> {\n  const ret: any = {}\n  keys.forEach((key) => {\n    ret[key] = obj[key]\n  })\n  return ret\n}\n\nconst COMMON_HOOK_DEBUG_FIELDS = [\n  'data',\n  'status',\n  'isLoading',\n  'isSuccess',\n  'isError',\n  'error',\n] as const\n\ntype GenericPrefetchThunk = (\n  endpointName: any,\n  arg: any,\n  options: PrefetchOptions,\n) => ThunkAction<void, any, any, UnknownAction>\n\n/**\n *\n * @param opts.api - An API with defined endpoints to create hooks for\n * @param opts.moduleOptions.batch - The version of the `batchedUpdates` function to be used\n * @param opts.moduleOptions.useDispatch - The version of the `useDispatch` hook to be used\n * @param opts.moduleOptions.useSelector - The version of the `useSelector` hook to be used\n * @returns An object containing functions to generate hooks based on an endpoint\n */\nexport function buildHooks<Definitions extends EndpointDefinitions>({\n  api,\n  moduleOptions: {\n    batch,\n    hooks: { useDispatch, useSelector, useStore },\n    unstable__sideEffectsInRender,\n    createSelector,\n  },\n  serializeQueryArgs,\n  context,\n}: {\n  api: Api<any, Definitions, any, any, CoreModule>\n  moduleOptions: Required<ReactHooksModuleOptions>\n  serializeQueryArgs: SerializeQueryArgs<any>\n  context: ApiContext<Definitions>\n}) {\n  const usePossiblyImmediateEffect: (\n    effect: () => void | undefined,\n    deps?: DependencyList,\n  ) => void = unstable__sideEffectsInRender ? (cb) => cb() : useEffect\n\n  type UnsubscribePromiseRef = React.RefObject<\n    { unsubscribe?: () => void } | undefined\n  >\n\n  const unsubscribePromiseRef = (ref: UnsubscribePromiseRef) =>\n    ref.current?.unsubscribe?.()\n\n  const endpointDefinitions = context.endpointDefinitions\n\n  return {\n    buildQueryHooks,\n    buildInfiniteQueryHooks,\n    buildMutationHook,\n    usePrefetch,\n  }\n\n  function queryStatePreSelector(\n    currentState: QueryResultSelectorResult<any>,\n    lastResult: UseQueryStateDefaultResult<any> | undefined,\n    queryArgs: any,\n  ): UseQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const { endpointName } = lastResult\n      const endpointDefinition = endpointDefinitions[endpointName]\n      if (\n        queryArgs !== skipToken &&\n        serializeQueryArgs({\n          queryArgs: lastResult.originalArgs,\n          endpointDefinition,\n          endpointName,\n        }) ===\n          serializeQueryArgs({\n            queryArgs,\n            endpointDefinition,\n            endpointName,\n          })\n      )\n        lastResult = undefined\n    }\n\n    // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data\n    if (data === undefined) data = currentState.data\n\n    const hasData = data !== undefined\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading\n\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading =\n      (!lastResult || lastResult.isLoading || lastResult.isUninitialized) &&\n      !hasData &&\n      isFetching\n\n    // isSuccess = true when data is present and we're not refetching after an error.\n    // That includes cases where the _current_ item is either actively\n    // fetching or about to fetch due to an uninitialized entry.\n    const isSuccess =\n      currentState.isSuccess ||\n      (hasData &&\n        ((isFetching && !lastResult?.isError) || currentState.isUninitialized))\n\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess,\n    } as UseQueryStateDefaultResult<any>\n  }\n\n  function infiniteQueryStatePreSelector(\n    currentState: InfiniteQueryResultSelectorResult<any>,\n    lastResult: UseInfiniteQueryStateDefaultResult<any> | undefined,\n    queryArgs: any,\n  ): UseInfiniteQueryStateDefaultResult<any> {\n    // if we had a last result and the current result is uninitialized,\n    // we might have called `api.util.resetApiState`\n    // in this case, reset the hook\n    if (lastResult?.endpointName && currentState.isUninitialized) {\n      const { endpointName } = lastResult\n      const endpointDefinition = endpointDefinitions[endpointName]\n      if (\n        queryArgs !== skipToken &&\n        serializeQueryArgs({\n          queryArgs: lastResult.originalArgs,\n          endpointDefinition,\n          endpointName,\n        }) ===\n          serializeQueryArgs({\n            queryArgs,\n            endpointDefinition,\n            endpointName,\n          })\n      )\n        lastResult = undefined\n    }\n\n    // data is the last known good request result we have tracked - or if none has been tracked yet the last good result for the current args\n    let data = currentState.isSuccess ? currentState.data : lastResult?.data\n    if (data === undefined) data = currentState.data\n\n    const hasData = data !== undefined\n\n    // isFetching = true any time a request is in flight\n    const isFetching = currentState.isLoading\n    // isLoading = true only when loading while no data is present yet (initial load with no data in the cache)\n    const isLoading =\n      (!lastResult || lastResult.isLoading || lastResult.isUninitialized) &&\n      !hasData &&\n      isFetching\n    // isSuccess = true when data is present\n    const isSuccess = currentState.isSuccess || (isFetching && hasData)\n\n    return {\n      ...currentState,\n      data,\n      currentData: currentState.data,\n      isFetching,\n      isLoading,\n      isSuccess,\n    } as UseInfiniteQueryStateDefaultResult<any>\n  }\n\n  function usePrefetch<EndpointName extends QueryKeys<Definitions>>(\n    endpointName: EndpointName,\n    defaultOptions?: PrefetchOptions,\n  ) {\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()\n    const stableDefaultOptions = useShallowStableValue(defaultOptions)\n\n    return useCallback(\n      (arg: any, options?: PrefetchOptions) =>\n        dispatch(\n          (api.util.prefetch as GenericPrefetchThunk)(endpointName, arg, {\n            ...stableDefaultOptions,\n            ...options,\n          }),\n        ),\n      [endpointName, dispatch, stableDefaultOptions],\n    )\n  }\n\n  function useQuerySubscriptionCommonImpl<\n    T extends\n      | QueryActionCreatorResult<any>\n      | InfiniteQueryActionCreatorResult<any>,\n  >(\n    endpointName: string,\n    arg: unknown | SkipToken,\n    {\n      refetchOnReconnect,\n      refetchOnFocus,\n      refetchOnMountOrArgChange,\n      skip = false,\n      pollingInterval = 0,\n      skipPollingIfUnfocused = false,\n      ...rest\n    }: UseQuerySubscriptionOptions = {},\n  ) {\n    const { initiate } = api.endpoints[endpointName] as ApiEndpointQuery<\n      QueryDefinition<any, any, any, any, any>,\n      Definitions\n    >\n    const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()\n\n    // TODO: Change this to `useRef<SubscriptionSelectors>(undefined)` after upgrading to React 19.\n    const subscriptionSelectorsRef = useRef<SubscriptionSelectors | undefined>(\n      undefined,\n    )\n\n    if (!subscriptionSelectorsRef.current) {\n      const returnedValue = dispatch(\n        api.internalActions.internal_getRTKQSubscriptions(),\n      )\n\n      if (process.env.NODE_ENV !== 'production') {\n        if (\n          typeof returnedValue !== 'object' ||\n          typeof returnedValue?.type === 'string'\n        ) {\n          throw new Error(\n            `Warning: Middleware for RTK-Query API at reducerPath \"${api.reducerPath}\" has not been added to the store.\n    You must add the middleware for RTK-Query to function correctly!`,\n          )\n        }\n      }\n\n      subscriptionSelectorsRef.current =\n        returnedValue as unknown as SubscriptionSelectors\n    }\n    const stableArg = useStableQueryArgs(skip ? skipToken : arg)\n    const stableSubscriptionOptions = useShallowStableValue({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval,\n      skipPollingIfUnfocused,\n    })\n\n    const initialPageParam = (rest as UseInfiniteQuerySubscriptionOptions<any>)\n      .initialPageParam\n    const stableInitialPageParam = useShallowStableValue(initialPageParam)\n\n    const refetchCachedPages = (\n      rest as UseInfiniteQuerySubscriptionOptions<any>\n    ).refetchCachedPages\n    const stableRefetchCachedPages = useShallowStableValue(refetchCachedPages)\n\n    /**\n     * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n     */\n    const promiseRef = useRef<T | undefined>(undefined)\n\n    let { queryCacheKey, requestId } = promiseRef.current || {}\n\n    // HACK We've saved the middleware subscription lookup callbacks into a ref,\n    // so we can directly check here if the subscription exists for this query.\n    let currentRenderHasSubscription = false\n    if (queryCacheKey && requestId) {\n      currentRenderHasSubscription =\n        subscriptionSelectorsRef.current.isRequestSubscribed(\n          queryCacheKey,\n          requestId,\n        )\n    }\n\n    const subscriptionRemoved =\n      !currentRenderHasSubscription && promiseRef.current !== undefined\n\n    usePossiblyImmediateEffect((): void | undefined => {\n      if (subscriptionRemoved) {\n        promiseRef.current = undefined\n      }\n    }, [subscriptionRemoved])\n\n    usePossiblyImmediateEffect((): void | undefined => {\n      const lastPromise = promiseRef.current\n      if (\n        typeof process !== 'undefined' &&\n        process.env.NODE_ENV === 'removeMeOnCompilation'\n      ) {\n        // this is only present to enforce the rule of hooks to keep `isSubscribed` in the dependency array\n        console.log(subscriptionRemoved)\n      }\n\n      if (stableArg === skipToken) {\n        lastPromise?.unsubscribe()\n        promiseRef.current = undefined\n        return\n      }\n\n      const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions\n\n      if (!lastPromise || lastPromise.arg !== stableArg) {\n        lastPromise?.unsubscribe()\n        const promise = dispatch(\n          initiate(stableArg, {\n            subscriptionOptions: stableSubscriptionOptions,\n            forceRefetch: refetchOnMountOrArgChange,\n            ...(isInfiniteQueryDefinition(endpointDefinitions[endpointName])\n              ? {\n                  initialPageParam: stableInitialPageParam,\n                  refetchCachedPages: stableRefetchCachedPages,\n                }\n              : {}),\n          }),\n        )\n\n        promiseRef.current = promise as T\n      } else if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n        lastPromise.updateSubscriptionOptions(stableSubscriptionOptions)\n      }\n    }, [\n      dispatch,\n      initiate,\n      refetchOnMountOrArgChange,\n      stableArg,\n      stableSubscriptionOptions,\n      subscriptionRemoved,\n      stableInitialPageParam,\n      stableRefetchCachedPages,\n      endpointName,\n    ])\n\n    return [promiseRef, dispatch, initiate, stableSubscriptionOptions] as const\n  }\n\n  function buildUseQueryState(\n    endpointName: string,\n    preSelector:\n      | typeof queryStatePreSelector\n      | typeof infiniteQueryStatePreSelector,\n  ) {\n    const useQueryState = (\n      arg: any,\n      {\n        skip = false,\n        selectFromResult,\n      }:\n        | UseQueryStateOptions<any, any>\n        | UseInfiniteQueryStateOptions<any, any> = {},\n    ) => {\n      const { select } = api.endpoints[endpointName] as ApiEndpointQuery<\n        QueryDefinition<any, any, any, any, any>,\n        Definitions\n      >\n      const stableArg = useStableQueryArgs(skip ? skipToken : arg)\n\n      type ApiRootState = Parameters<ReturnType<typeof select>>[0]\n\n      const lastValue = useRef<any>(undefined)\n\n      const selectDefaultResult: Selector<ApiRootState, any, [any]> = useMemo(\n        () =>\n          // Normally ts-ignores are bad and should be avoided, but we're\n          // already casting this selector to be `Selector<any>` anyway,\n          // so the inconsistencies don't matter here\n          // @ts-ignore\n          createSelector(\n            [\n              // @ts-ignore\n              select(stableArg),\n              (_: ApiRootState, lastResult: any) => lastResult,\n              (_: ApiRootState) => stableArg,\n            ],\n            preSelector,\n            {\n              memoizeOptions: {\n                resultEqualityCheck: shallowEqual,\n              },\n            },\n          ),\n        [select, stableArg],\n      )\n\n      const querySelector: Selector<ApiRootState, any, [any]> = useMemo(\n        () =>\n          selectFromResult\n            ? createSelector([selectDefaultResult], selectFromResult, {\n                devModeChecks: { identityFunctionCheck: 'never' },\n              })\n            : selectDefaultResult,\n        [selectDefaultResult, selectFromResult],\n      )\n\n      const currentState = useSelector(\n        (state: RootState<Definitions, any, any>) =>\n          querySelector(state, lastValue.current),\n        shallowEqual,\n      )\n\n      const store = useStore<RootState<Definitions, any, any>>()\n      const newLastValue = selectDefaultResult(\n        store.getState(),\n        lastValue.current,\n      )\n      useIsomorphicLayoutEffect(() => {\n        lastValue.current = newLastValue\n      }, [newLastValue])\n\n      return currentState\n    }\n\n    return useQueryState\n  }\n\n  function usePromiseRefUnsubscribeOnUnmount(\n    promiseRef: UnsubscribePromiseRef,\n  ) {\n    useEffect(() => {\n      return () => {\n        unsubscribePromiseRef(promiseRef)\n        // eslint-disable-next-line react-hooks/exhaustive-deps\n        ;(promiseRef.current as any) = undefined\n      }\n    }, [promiseRef])\n  }\n\n  function refetchOrErrorIfUnmounted<\n    T extends\n      | QueryActionCreatorResult<any>\n      | InfiniteQueryActionCreatorResult<any>,\n  >(promiseRef: React.RefObject<T | undefined>): T {\n    if (!promiseRef.current)\n      throw new Error('Cannot refetch a query that has not been started yet.')\n    return promiseRef.current.refetch() as T\n  }\n\n  function buildQueryHooks(endpointName: string): QueryHooks<any> {\n    const useQuerySubscription: UseQuerySubscription<any> = (\n      arg: any,\n      options = {},\n    ) => {\n      const [promiseRef] = useQuerySubscriptionCommonImpl<\n        QueryActionCreatorResult<any>\n      >(endpointName, arg, options)\n\n      usePromiseRefUnsubscribeOnUnmount(promiseRef)\n\n      return useMemo(\n        () => ({\n          /**\n           * A method to manually refetch data for the query\n           */\n          refetch: () => refetchOrErrorIfUnmounted(promiseRef),\n        }),\n        [promiseRef],\n      )\n    }\n\n    const useLazyQuerySubscription: UseLazyQuerySubscription<any> = ({\n      refetchOnReconnect,\n      refetchOnFocus,\n      pollingInterval = 0,\n      skipPollingIfUnfocused = false,\n    } = {}) => {\n      const { initiate } = api.endpoints[endpointName] as ApiEndpointQuery<\n        QueryDefinition<any, any, any, any, any>,\n        Definitions\n      >\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()\n\n      const [arg, setArg] = useState<any>(UNINITIALIZED_VALUE)\n\n      // TODO: Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n      /**\n       * @todo Change this to `useRef<QueryActionCreatorResult<any>>(undefined)` after upgrading to React 19.\n       */\n      const promiseRef = useRef<QueryActionCreatorResult<any> | undefined>(\n        undefined,\n      )\n\n      const stableSubscriptionOptions = useShallowStableValue({\n        refetchOnReconnect,\n        refetchOnFocus,\n        pollingInterval,\n        skipPollingIfUnfocused,\n      })\n\n      usePossiblyImmediateEffect(() => {\n        const lastSubscriptionOptions = promiseRef.current?.subscriptionOptions\n\n        if (stableSubscriptionOptions !== lastSubscriptionOptions) {\n          promiseRef.current?.updateSubscriptionOptions(\n            stableSubscriptionOptions,\n          )\n        }\n      }, [stableSubscriptionOptions])\n\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions)\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions\n      }, [stableSubscriptionOptions])\n\n      const trigger = useCallback(\n        function (arg: any, preferCacheValue = false) {\n          let promise: QueryActionCreatorResult<any>\n\n          batch(() => {\n            unsubscribePromiseRef(promiseRef)\n\n            promiseRef.current = promise = dispatch(\n              initiate(arg, {\n                subscriptionOptions: subscriptionOptionsRef.current,\n                forceRefetch: !preferCacheValue,\n              }),\n            )\n\n            setArg(arg)\n          })\n\n          return promise!\n        },\n        [dispatch, initiate],\n      )\n\n      const reset = useCallback(() => {\n        if (promiseRef.current?.queryCacheKey) {\n          dispatch(\n            api.internalActions.removeQueryResult({\n              queryCacheKey: promiseRef.current?.queryCacheKey as QueryCacheKey,\n            }),\n          )\n        }\n      }, [dispatch])\n\n      /* cleanup on unmount */\n      useEffect(() => {\n        return () => {\n          unsubscribePromiseRef(promiseRef)\n        }\n      }, [])\n\n      /* if \"cleanup on unmount\" was triggered from a fast refresh, we want to reinstate the query */\n      useEffect(() => {\n        if (arg !== UNINITIALIZED_VALUE && !promiseRef.current) {\n          trigger(arg, true)\n        }\n      }, [arg, trigger])\n\n      return useMemo(\n        () => [trigger, arg, { reset }] as const,\n        [trigger, arg, reset],\n      )\n    }\n\n    const useQueryState: UseQueryState<any> = buildUseQueryState(\n      endpointName,\n      queryStatePreSelector,\n    )\n\n    return {\n      useQueryState,\n      useQuerySubscription,\n      useLazyQuerySubscription,\n      useLazyQuery(options) {\n        const [trigger, arg, { reset }] = useLazyQuerySubscription(options)\n        const queryStateResults = useQueryState(arg, {\n          ...options,\n          skip: arg === UNINITIALIZED_VALUE,\n        })\n\n        const info = useMemo(() => ({ lastArg: arg }), [arg])\n        return useMemo(\n          () => [trigger, { ...queryStateResults, reset }, info],\n          [trigger, queryStateResults, reset, info],\n        )\n      },\n      useQuery(arg, options) {\n        const querySubscriptionResults = useQuerySubscription(arg, options)\n        const queryStateResults = useQueryState(arg, {\n          selectFromResult:\n            arg === skipToken || options?.skip\n              ? undefined\n              : noPendingQueryStateSelector,\n          ...options,\n        })\n\n        const debugValue = pick(queryStateResults, ...COMMON_HOOK_DEBUG_FIELDS)\n        useDebugValue(debugValue)\n\n        return useMemo(\n          () => ({ ...queryStateResults, ...querySubscriptionResults }),\n          [queryStateResults, querySubscriptionResults],\n        )\n      },\n    }\n  }\n\n  function buildInfiniteQueryHooks(\n    endpointName: string,\n  ): InfiniteQueryHooks<any> {\n    const useInfiniteQuerySubscription: UseInfiniteQuerySubscription<any> = (\n      arg: any,\n      options = {},\n    ) => {\n      const [promiseRef, dispatch, initiate, stableSubscriptionOptions] =\n        useQuerySubscriptionCommonImpl<InfiniteQueryActionCreatorResult<any>>(\n          endpointName,\n          arg,\n          options,\n        )\n\n      const subscriptionOptionsRef = useRef(stableSubscriptionOptions)\n      usePossiblyImmediateEffect(() => {\n        subscriptionOptionsRef.current = stableSubscriptionOptions\n      }, [stableSubscriptionOptions])\n\n      // Extract and stabilize the hook-level refetchCachedPages option\n      const hookRefetchCachedPages = (\n        options as UseInfiniteQuerySubscriptionOptions<any>\n      ).refetchCachedPages\n      const stableHookRefetchCachedPages = useShallowStableValue(\n        hookRefetchCachedPages,\n      )\n\n      const trigger: LazyInfiniteQueryTrigger<any> = useCallback(\n        function (arg: unknown, direction: 'forward' | 'backward') {\n          let promise: InfiniteQueryActionCreatorResult<any>\n\n          batch(() => {\n            unsubscribePromiseRef(promiseRef)\n\n            promiseRef.current = promise = dispatch(\n              (initiate as StartInfiniteQueryActionCreator<any>)(arg, {\n                subscriptionOptions: subscriptionOptionsRef.current,\n                direction,\n              }),\n            )\n          })\n\n          return promise!\n        },\n        [promiseRef, dispatch, initiate],\n      )\n\n      usePromiseRefUnsubscribeOnUnmount(promiseRef)\n\n      const stableArg = useStableQueryArgs(options.skip ? skipToken : arg)\n\n      const refetch = useCallback(\n        (\n          options?: Pick<\n            UseInfiniteQuerySubscriptionOptions<any>,\n            'refetchCachedPages'\n          >,\n        ) => {\n          if (!promiseRef.current)\n            throw new Error(\n              'Cannot refetch a query that has not been started yet.',\n            )\n          // Merge per-call options with hook-level default\n          const mergedOptions = {\n            refetchCachedPages:\n              options?.refetchCachedPages ?? stableHookRefetchCachedPages,\n          }\n          return promiseRef.current.refetch(mergedOptions)\n        },\n        [promiseRef, stableHookRefetchCachedPages],\n      )\n\n      return useMemo(() => {\n        const fetchNextPage = () => {\n          return trigger(stableArg, 'forward')\n        }\n\n        const fetchPreviousPage = () => {\n          return trigger(stableArg, 'backward')\n        }\n\n        return {\n          trigger,\n          /**\n           * A method to manually refetch data for the query\n           */\n          refetch,\n          fetchNextPage,\n          fetchPreviousPage,\n        }\n      }, [refetch, trigger, stableArg])\n    }\n\n    const useInfiniteQueryState: UseInfiniteQueryState<any> =\n      buildUseQueryState(endpointName, infiniteQueryStatePreSelector)\n\n    return {\n      useInfiniteQueryState,\n      useInfiniteQuerySubscription,\n      useInfiniteQuery(arg, options) {\n        const { refetch, fetchNextPage, fetchPreviousPage } =\n          useInfiniteQuerySubscription(arg, options)\n        const queryStateResults = useInfiniteQueryState(arg, {\n          selectFromResult:\n            arg === skipToken || options?.skip\n              ? undefined\n              : noPendingQueryStateSelector,\n          ...options,\n        })\n\n        const debugValue = pick(\n          queryStateResults,\n          ...COMMON_HOOK_DEBUG_FIELDS,\n          'hasNextPage',\n          'hasPreviousPage',\n        )\n        useDebugValue(debugValue)\n\n        return useMemo(\n          () => ({\n            ...queryStateResults,\n            fetchNextPage,\n            fetchPreviousPage,\n            refetch,\n          }),\n          [queryStateResults, fetchNextPage, fetchPreviousPage, refetch],\n        )\n      },\n    }\n  }\n\n  function buildMutationHook(name: string): UseMutation<any> {\n    return ({ selectFromResult, fixedCacheKey } = {}) => {\n      const { select, initiate } = api.endpoints[name] as ApiEndpointMutation<\n        MutationDefinition<any, any, any, any, any>,\n        Definitions\n      >\n      const dispatch = useDispatch<ThunkDispatch<any, any, UnknownAction>>()\n      const [promise, setPromise] = useState<MutationActionCreatorResult<any>>()\n\n      useEffect(\n        () => () => {\n          if (!promise?.arg.fixedCacheKey) {\n            promise?.reset()\n          }\n        },\n        [promise],\n      )\n\n      const triggerMutation = useCallback(\n        function (arg: Parameters<typeof initiate>['0']) {\n          const promise = dispatch(initiate(arg, { fixedCacheKey }))\n          setPromise(promise)\n          return promise\n        },\n        [dispatch, initiate, fixedCacheKey],\n      )\n\n      const { requestId } = promise || {}\n      const selectDefaultResult = useMemo(\n        () => select({ fixedCacheKey, requestId: promise?.requestId }),\n        [fixedCacheKey, promise, select],\n      )\n      const mutationSelector = useMemo(\n        (): Selector<RootState<Definitions, any, any>, any> =>\n          selectFromResult\n            ? createSelector([selectDefaultResult], selectFromResult)\n            : selectDefaultResult,\n        [selectFromResult, selectDefaultResult],\n      )\n\n      const currentState = useSelector(mutationSelector, shallowEqual)\n      const originalArgs =\n        fixedCacheKey == null ? promise?.arg.originalArgs : undefined\n      const reset = useCallback(() => {\n        batch(() => {\n          if (promise) {\n            setPromise(undefined)\n          }\n          if (fixedCacheKey) {\n            dispatch(\n              api.internalActions.removeMutationResult({\n                requestId,\n                fixedCacheKey,\n              }),\n            )\n          }\n        })\n      }, [dispatch, fixedCacheKey, promise, requestId])\n\n      const debugValue = pick(\n        currentState,\n        ...COMMON_HOOK_DEBUG_FIELDS,\n        'endpointName',\n      )\n      useDebugValue(debugValue)\n\n      const finalState = useMemo(\n        () => ({ ...currentState, originalArgs, reset }),\n        [currentState, originalArgs, reset],\n      )\n\n      return useMemo(\n        () => [triggerMutation, finalState] as const,\n        [triggerMutation, finalState],\n      )\n    }\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/react/constants.ts",
    "content": "export const UNINITIALIZED_VALUE = Symbol()\nexport type UninitializedValue = typeof UNINITIALIZED_VALUE\n"
  },
  {
    "path": "packages/toolkit/src/query/react/index.ts",
    "content": "// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit'\n\nimport { buildCreateApi, coreModule } from './rtkqImports'\nimport { reactHooksModule, reactHooksModuleName } from './module'\n\nexport * from '@reduxjs/toolkit/query'\nexport { ApiProvider } from './ApiProvider'\n\nconst createApi = /* @__PURE__ */ buildCreateApi(\n  coreModule(),\n  reactHooksModule(),\n)\n\nexport type {\n  TypedUseMutationResult,\n  TypedUseQueryHookResult,\n  TypedUseQueryStateResult,\n  TypedUseQuerySubscriptionResult,\n  TypedLazyQueryTrigger,\n  TypedUseLazyQuery,\n  TypedUseMutation,\n  TypedMutationTrigger,\n  TypedQueryStateSelector,\n  TypedUseQueryState,\n  TypedUseQuery,\n  TypedUseQuerySubscription,\n  TypedUseLazyQuerySubscription,\n  TypedUseQueryStateOptions,\n  TypedUseLazyQueryStateResult,\n  TypedUseInfiniteQuery,\n  TypedUseInfiniteQueryHookResult,\n  TypedUseInfiniteQueryStateResult,\n  TypedUseInfiniteQuerySubscriptionResult,\n  TypedUseInfiniteQueryStateOptions,\n  TypedInfiniteQueryStateSelector,\n  TypedUseInfiniteQuerySubscription,\n  TypedUseInfiniteQueryState,\n  TypedLazyInfiniteQueryTrigger,\n  TypedUseQuerySubscriptionOptions,\n  TypedUseMutationStateOptions,\n} from './buildHooks'\nexport { UNINITIALIZED_VALUE } from './constants'\nexport { createApi, reactHooksModule, reactHooksModuleName }\n"
  },
  {
    "path": "packages/toolkit/src/query/react/module.ts",
    "content": "import type {\n  Api,\n  BaseQueryFn,\n  EndpointDefinitions,\n  InfiniteQueryDefinition,\n  Module,\n  MutationDefinition,\n  PrefetchOptions,\n  QueryArgFrom,\n  QueryDefinition,\n  QueryKeys,\n} from '@reduxjs/toolkit/query'\nimport {\n  batch as rrBatch,\n  useDispatch as rrUseDispatch,\n  useSelector as rrUseSelector,\n  useStore as rrUseStore,\n} from 'react-redux'\nimport type { CreateSelectorFunction } from 'reselect'\nimport { createSelector as _createSelector } from 'reselect'\nimport {\n  isInfiniteQueryDefinition,\n  isMutationDefinition,\n  isQueryDefinition,\n} from '../endpointDefinitions'\nimport { safeAssign } from '../tsHelpers'\nimport { capitalize, countObjectKeys } from '../utils'\nimport type {\n  InfiniteQueryHooks,\n  MutationHooks,\n  QueryHooks,\n} from './buildHooks'\nimport { buildHooks } from './buildHooks'\nimport type { HooksWithUniqueNames } from './namedHooks'\n\nexport const reactHooksModuleName = /* @__PURE__ */ Symbol()\nexport type ReactHooksModule = typeof reactHooksModuleName\n\ndeclare module '@reduxjs/toolkit/query' {\n  export interface ApiModules<\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    BaseQuery extends BaseQueryFn,\n    Definitions extends EndpointDefinitions,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    ReducerPath extends string,\n    // eslint-disable-next-line @typescript-eslint/no-unused-vars\n    TagTypes extends string,\n  > {\n    [reactHooksModuleName]: {\n      /**\n       *  Endpoints based on the input endpoints provided to `createApi`, containing `select`, `hooks` and `action matchers`.\n       */\n      endpoints: {\n        [K in keyof Definitions]: Definitions[K] extends QueryDefinition<\n          any,\n          any,\n          any,\n          any,\n          any\n        >\n          ? QueryHooks<Definitions[K]>\n          : Definitions[K] extends MutationDefinition<any, any, any, any, any>\n            ? MutationHooks<Definitions[K]>\n            : Definitions[K] extends InfiniteQueryDefinition<\n                  any,\n                  any,\n                  any,\n                  any,\n                  any\n                >\n              ? InfiniteQueryHooks<Definitions[K]>\n              : never\n      }\n      /**\n       * A hook that accepts a string endpoint name, and provides a callback that when called, pre-fetches the data for that endpoint.\n       */\n      usePrefetch<EndpointName extends QueryKeys<Definitions>>(\n        endpointName: EndpointName,\n        options?: PrefetchOptions,\n      ): (\n        arg: QueryArgFrom<Definitions[EndpointName]>,\n        options?: PrefetchOptions,\n      ) => void\n    } & HooksWithUniqueNames<Definitions>\n  }\n}\n\ntype RR = typeof import('react-redux')\n\nexport interface ReactHooksModuleOptions {\n  /**\n   * The hooks from React Redux to be used\n   */\n  hooks?: {\n    /**\n     * The version of the `useDispatch` hook to be used\n     */\n    useDispatch: RR['useDispatch']\n    /**\n     * The version of the `useSelector` hook to be used\n     */\n    useSelector: RR['useSelector']\n    /**\n     * The version of the `useStore` hook to be used\n     */\n    useStore: RR['useStore']\n  }\n  /**\n   * The version of the `batchedUpdates` function to be used\n   */\n  batch?: RR['batch']\n  /**\n   * Enables performing asynchronous tasks immediately within a render.\n   *\n   * @example\n   *\n   * ```ts\n   * import {\n   *   buildCreateApi,\n   *   coreModule,\n   *   reactHooksModule\n   * } from '@reduxjs/toolkit/query/react'\n   *\n   * const createApi = buildCreateApi(\n   *   coreModule(),\n   *   reactHooksModule({ unstable__sideEffectsInRender: true })\n   * )\n   * ```\n   */\n  unstable__sideEffectsInRender?: boolean\n  /**\n   * A selector creator (usually from `reselect`, or matching the same signature)\n   */\n  createSelector?: CreateSelectorFunction<any, any, any>\n}\n\n/**\n * Creates a module that generates react hooks from endpoints, for use with `buildCreateApi`.\n *\n *  @example\n * ```ts\n * const MyContext = React.createContext<ReactReduxContextValue | null>(null);\n * const customCreateApi = buildCreateApi(\n *   coreModule(),\n *   reactHooksModule({\n *     hooks: {\n *       useDispatch: createDispatchHook(MyContext),\n *       useSelector: createSelectorHook(MyContext),\n *       useStore: createStoreHook(MyContext)\n *     }\n *   })\n * );\n * ```\n *\n * @returns A module for use with `buildCreateApi`\n */\nexport const reactHooksModule = ({\n  batch = rrBatch,\n  hooks = {\n    useDispatch: rrUseDispatch,\n    useSelector: rrUseSelector,\n    useStore: rrUseStore,\n  },\n  createSelector = _createSelector,\n  unstable__sideEffectsInRender = false,\n  ...rest\n}: ReactHooksModuleOptions = {}): Module<ReactHooksModule> => {\n  if (process.env.NODE_ENV !== 'production') {\n    const hookNames = ['useDispatch', 'useSelector', 'useStore'] as const\n    let warned = false\n    for (const hookName of hookNames) {\n      // warn for old hook options\n      if (countObjectKeys(rest) > 0) {\n        if ((rest as Partial<typeof hooks>)[hookName]) {\n          if (!warned) {\n            console.warn(\n              'As of RTK 2.0, the hooks now need to be specified as one object, provided under a `hooks` key:' +\n                '\\n`reactHooksModule({ hooks: { useDispatch, useSelector, useStore } })`',\n            )\n            warned = true\n          }\n        }\n        // migrate\n        // @ts-ignore\n        hooks[hookName] = rest[hookName]\n      }\n      // then make sure we have them all\n      if (typeof hooks[hookName] !== 'function') {\n        throw new Error(\n          `When using custom hooks for context, all ${\n            hookNames.length\n          } hooks need to be provided: ${hookNames.join(\n            ', ',\n          )}.\\nHook ${hookName} was either not provided or not a function.`,\n        )\n      }\n    }\n  }\n\n  return {\n    name: reactHooksModuleName,\n    init(api, { serializeQueryArgs }, context) {\n      const anyApi = api as any as Api<\n        any,\n        Record<string, any>,\n        any,\n        any,\n        ReactHooksModule\n      >\n      const {\n        buildQueryHooks,\n        buildInfiniteQueryHooks,\n        buildMutationHook,\n        usePrefetch,\n      } = buildHooks({\n        api,\n        moduleOptions: {\n          batch,\n          hooks,\n          unstable__sideEffectsInRender,\n          createSelector,\n        },\n        serializeQueryArgs,\n        context,\n      })\n      safeAssign(anyApi, { usePrefetch })\n      safeAssign(context, { batch })\n\n      return {\n        injectEndpoint(endpointName, definition) {\n          if (isQueryDefinition(definition)) {\n            const {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription,\n            } = buildQueryHooks(endpointName)\n            safeAssign(anyApi.endpoints[endpointName], {\n              useQuery,\n              useLazyQuery,\n              useLazyQuerySubscription,\n              useQueryState,\n              useQuerySubscription,\n            })\n            ;(api as any)[`use${capitalize(endpointName)}Query`] = useQuery\n            ;(api as any)[`useLazy${capitalize(endpointName)}Query`] =\n              useLazyQuery\n          }\n          if (isMutationDefinition(definition)) {\n            const useMutation = buildMutationHook(endpointName)\n            safeAssign(anyApi.endpoints[endpointName], {\n              useMutation,\n            })\n            ;(api as any)[`use${capitalize(endpointName)}Mutation`] =\n              useMutation\n          } else if (isInfiniteQueryDefinition(definition)) {\n            const {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState,\n            } = buildInfiniteQueryHooks(endpointName)\n            safeAssign(anyApi.endpoints[endpointName], {\n              useInfiniteQuery,\n              useInfiniteQuerySubscription,\n              useInfiniteQueryState,\n            })\n            ;(api as any)[`use${capitalize(endpointName)}InfiniteQuery`] =\n              useInfiniteQuery\n          }\n        },\n      }\n    },\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/react/namedHooks.ts",
    "content": "import type {\n  DefinitionType,\n  EndpointDefinitions,\n  MutationDefinition,\n  QueryDefinition,\n  InfiniteQueryDefinition,\n} from '@reduxjs/toolkit/query'\nimport type {\n  UseInfiniteQuery,\n  UseLazyQuery,\n  UseMutation,\n  UseQuery,\n} from './buildHooks'\n\ntype QueryHookNames<Definitions extends EndpointDefinitions> = {\n  [K in keyof Definitions as Definitions[K] extends {\n    type: DefinitionType.query\n  }\n    ? `use${Capitalize<K & string>}Query`\n    : never]: UseQuery<\n    Extract<Definitions[K], QueryDefinition<any, any, any, any>>\n  >\n}\n\ntype LazyQueryHookNames<Definitions extends EndpointDefinitions> = {\n  [K in keyof Definitions as Definitions[K] extends {\n    type: DefinitionType.query\n  }\n    ? `useLazy${Capitalize<K & string>}Query`\n    : never]: UseLazyQuery<\n    Extract<Definitions[K], QueryDefinition<any, any, any, any>>\n  >\n}\n\ntype InfiniteQueryHookNames<Definitions extends EndpointDefinitions> = {\n  [K in keyof Definitions as Definitions[K] extends {\n    type: DefinitionType.infinitequery\n  }\n    ? `use${Capitalize<K & string>}InfiniteQuery`\n    : never]: UseInfiniteQuery<\n    Extract<Definitions[K], InfiniteQueryDefinition<any, any, any, any, any>>\n  >\n}\n\ntype MutationHookNames<Definitions extends EndpointDefinitions> = {\n  [K in keyof Definitions as Definitions[K] extends {\n    type: DefinitionType.mutation\n  }\n    ? `use${Capitalize<K & string>}Mutation`\n    : never]: UseMutation<\n    Extract<Definitions[K], MutationDefinition<any, any, any, any>>\n  >\n}\n\nexport type HooksWithUniqueNames<Definitions extends EndpointDefinitions> =\n  QueryHookNames<Definitions> &\n    LazyQueryHookNames<Definitions> &\n    InfiniteQueryHookNames<Definitions> &\n    MutationHookNames<Definitions>\n"
  },
  {
    "path": "packages/toolkit/src/query/react/reactImports.ts",
    "content": "export {\n  useEffect,\n  useRef,\n  useMemo,\n  useContext,\n  useCallback,\n  useDebugValue,\n  useLayoutEffect,\n  useState,\n} from 'react'\n"
  },
  {
    "path": "packages/toolkit/src/query/react/reactReduxImports.ts",
    "content": "export { shallowEqual, Provider, ReactReduxContext } from 'react-redux'\n"
  },
  {
    "path": "packages/toolkit/src/query/react/rtkqImports.ts",
    "content": "export {\n  buildCreateApi,\n  coreModule,\n  copyWithStructuralSharing,\n  setupListeners,\n  QueryStatus,\n  skipToken,\n} from '@reduxjs/toolkit/query'\n"
  },
  {
    "path": "packages/toolkit/src/query/react/useSerializedStableValue.ts",
    "content": "import { useEffect, useRef, useMemo } from './reactImports'\nimport { copyWithStructuralSharing } from './rtkqImports'\n\nexport function useStableQueryArgs<T>(queryArgs: T) {\n  const cache = useRef(queryArgs)\n  const copy = useMemo(\n    () => copyWithStructuralSharing(cache.current, queryArgs),\n    [queryArgs],\n  )\n  useEffect(() => {\n    if (cache.current !== copy) {\n      cache.current = copy\n    }\n  }, [copy])\n\n  return copy\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/react/useShallowStableValue.ts",
    "content": "import { useEffect, useRef } from './reactImports'\nimport { shallowEqual } from './reactReduxImports'\n\nexport function useShallowStableValue<T>(value: T) {\n  const cache = useRef(value)\n  useEffect(() => {\n    if (!shallowEqual(cache.current, value)) {\n      cache.current = value\n    }\n  }, [value])\n\n  return shallowEqual(cache.current, value) ? cache.current : value\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/retry.ts",
    "content": "import type {\n  BaseQueryApi,\n  BaseQueryArg,\n  BaseQueryEnhancer,\n  BaseQueryError,\n  BaseQueryExtraOptions,\n  BaseQueryFn,\n  BaseQueryMeta,\n} from './baseQueryTypes'\nimport type { FetchBaseQueryError } from './fetchBaseQuery'\nimport { HandledError } from './HandledError'\n\n/**\n * Exponential backoff based on the attempt number.\n *\n * @remarks\n * 1. 600ms * random(0.4, 1.4)\n * 2. 1200ms * random(0.4, 1.4)\n * 3. 2400ms * random(0.4, 1.4)\n * 4. 4800ms * random(0.4, 1.4)\n * 5. 9600ms * random(0.4, 1.4)\n *\n * @param attempt - Current attempt\n * @param maxRetries - Maximum number of retries\n */\nasync function defaultBackoff(\n  attempt: number = 0,\n  maxRetries: number = 5,\n  signal?: AbortSignal,\n) {\n  const attempts = Math.min(attempt, maxRetries)\n\n  const timeout = ~~((Math.random() + 0.4) * (300 << attempts)) // Force a positive int in the case we make this an option\n\n  await new Promise<void>((resolve, reject) => {\n    const timeoutId = setTimeout(() => resolve(), timeout)\n\n    // If signal is provided and gets aborted, clear timeout and reject\n    if (signal) {\n      const abortHandler = () => {\n        clearTimeout(timeoutId)\n        reject(new Error('Aborted'))\n      }\n\n      // Check if already aborted\n      if (signal.aborted) {\n        clearTimeout(timeoutId)\n        reject(new Error('Aborted'))\n      } else {\n        signal.addEventListener('abort', abortHandler, { once: true })\n      }\n    }\n  })\n}\n\ntype RetryConditionFunction = (\n  error: BaseQueryError<BaseQueryFn>,\n  args: BaseQueryArg<BaseQueryFn>,\n  extraArgs: {\n    attempt: number\n    baseQueryApi: BaseQueryApi\n    extraOptions: BaseQueryExtraOptions<BaseQueryFn> & RetryOptions\n  },\n) => boolean\n\nexport type RetryOptions = {\n  /**\n   * Function used to determine delay between retries\n   */\n  backoff?: (\n    attempt: number,\n    maxRetries: number,\n    signal?: AbortSignal,\n  ) => Promise<void>\n} & (\n  | {\n      /**\n       * How many times the query will be retried (default: 5)\n       */\n      maxRetries?: number\n      retryCondition?: undefined\n    }\n  | {\n      /**\n       * Callback to determine if a retry should be attempted.\n       * Return `true` for another retry and `false` to quit trying prematurely.\n       */\n      retryCondition?: RetryConditionFunction\n      maxRetries?: undefined\n    }\n)\n\nfunction fail<BaseQuery extends BaseQueryFn = BaseQueryFn>(\n  error: BaseQueryError<BaseQuery>,\n  meta?: BaseQueryMeta<BaseQuery>,\n): never {\n  throw Object.assign(new HandledError({ error, meta }), {\n    throwImmediately: true,\n  })\n}\n\n/**\n * Checks if the abort signal is aborted and fails immediately if so.\n * Used to exit retry loops cleanly when a request is aborted.\n */\nfunction failIfAborted(signal: AbortSignal): void {\n  if (signal.aborted) {\n    fail({ status: 'CUSTOM_ERROR', error: 'Aborted' })\n  }\n}\n\nconst EMPTY_OPTIONS = {}\n\nconst retryWithBackoff: BaseQueryEnhancer<\n  unknown,\n  RetryOptions,\n  RetryOptions | void\n> = (baseQuery, defaultOptions) => async (args, api, extraOptions) => {\n  // We need to figure out `maxRetries` before we define `defaultRetryCondition.\n  // This is probably goofy, but ought to work.\n  // Put our defaults in one array, filter out undefineds, grab the last value.\n  const possibleMaxRetries: number[] = [\n    5,\n    ((defaultOptions as any) || EMPTY_OPTIONS).maxRetries,\n    ((extraOptions as any) || EMPTY_OPTIONS).maxRetries,\n  ].filter((x) => x !== undefined)\n  const [maxRetries] = possibleMaxRetries.slice(-1)\n\n  const defaultRetryCondition: RetryConditionFunction = (_, __, { attempt }) =>\n    attempt <= maxRetries\n\n  const options: {\n    maxRetries: number\n    backoff: typeof defaultBackoff\n    retryCondition: typeof defaultRetryCondition\n  } = {\n    maxRetries,\n    backoff: defaultBackoff,\n    retryCondition: defaultRetryCondition,\n    ...defaultOptions,\n    ...extraOptions,\n  }\n  let retry = 0\n\n  while (true) {\n    // Check if aborted before each attempt\n    failIfAborted(api.signal)\n\n    try {\n      const result = await baseQuery(args, api, extraOptions)\n      // baseQueries _should_ return an error property, so we should check for that and throw it to continue retrying\n      if (result.error) {\n        throw new HandledError(result)\n      }\n      return result\n    } catch (e: any) {\n      retry++\n\n      if (e.throwImmediately) {\n        if (e instanceof HandledError) {\n          return e.value\n        }\n\n        // We don't know what this is, so we have to rethrow it\n        throw e\n      }\n\n      if (e instanceof HandledError) {\n        if (\n          !options.retryCondition(e.value.error as FetchBaseQueryError, args, {\n            attempt: retry,\n            baseQueryApi: api,\n            extraOptions,\n          })\n        ) {\n          return e.value // Max retries for expected error\n        }\n      } else {\n        // For unexpected errors, respect maxRetries\n        if (retry > options.maxRetries) {\n          // Return the error as a proper error response instead of throwing\n          return { error: e }\n        }\n      }\n\n      // Check if aborted before backoff\n      failIfAborted(api.signal)\n\n      try {\n        await options.backoff(retry, options.maxRetries, api.signal)\n      } catch (backoffError) {\n        // If backoff was aborted, exit the retry loop\n        failIfAborted(api.signal)\n        // Otherwise, rethrow the backoff error\n        throw backoffError\n      }\n    }\n  }\n}\n\n/**\n * A utility that can wrap `baseQuery` in the API definition to provide retries with a basic exponential backoff.\n *\n * @example\n *\n * ```ts\n * // codeblock-meta title=\"Retry every request 5 times by default\"\n * import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query/react'\n * interface Post {\n *   id: number\n *   name: string\n * }\n * type PostsResponse = Post[]\n *\n * // maxRetries: 5 is the default, and can be omitted. Shown for documentation purposes.\n * const staggeredBaseQuery = retry(fetchBaseQuery({ baseUrl: '/' }), { maxRetries: 5 });\n * export const api = createApi({\n *   baseQuery: staggeredBaseQuery,\n *   endpoints: (build) => ({\n *     getPosts: build.query<PostsResponse, void>({\n *       query: () => ({ url: 'posts' }),\n *     }),\n *     getPost: build.query<PostsResponse, string>({\n *       query: (id) => ({ url: `post/${id}` }),\n *       extraOptions: { maxRetries: 8 }, // You can override the retry behavior on each endpoint\n *     }),\n *   }),\n * });\n *\n * export const { useGetPostsQuery, useGetPostQuery } = api;\n * ```\n */\nexport const retry = /* @__PURE__ */ Object.assign(retryWithBackoff, { fail })\n"
  },
  {
    "path": "packages/toolkit/src/query/standardSchema.ts",
    "content": "import type { StandardSchemaV1 } from '@standard-schema/spec'\nimport { SchemaError } from '@standard-schema/utils'\nimport type { SchemaType } from './endpointDefinitions'\n\nexport class NamedSchemaError extends SchemaError {\n  constructor(\n    issues: readonly StandardSchemaV1.Issue[],\n    public readonly value: any,\n    public readonly schemaName: `${SchemaType}Schema`,\n    public readonly _bqMeta: any,\n  ) {\n    super(issues)\n  }\n}\n\nexport const shouldSkip = (\n  skipSchemaValidation: boolean | SchemaType[] | undefined,\n  schemaName: SchemaType,\n) =>\n  Array.isArray(skipSchemaValidation)\n    ? skipSchemaValidation.includes(schemaName)\n    : !!skipSchemaValidation\n\nexport async function parseWithSchema<Schema extends StandardSchemaV1>(\n  schema: Schema,\n  data: unknown,\n  schemaName: `${SchemaType}Schema`,\n  bqMeta: any,\n): Promise<StandardSchemaV1.InferOutput<Schema>> {\n  const result = await schema['~standard'].validate(data)\n  if (result.issues) {\n    throw new NamedSchemaError(result.issues, data, schemaName, bqMeta)\n  }\n  return result.value\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/apiProvider.test.tsx",
    "content": "import { configureStore } from '@reduxjs/toolkit'\nimport {\n  ApiProvider,\n  buildCreateApi,\n  coreModule,\n  createApi,\n  reactHooksModule,\n} from '@reduxjs/toolkit/query/react'\nimport { fireEvent, render, waitFor } from '@testing-library/react'\nimport { delay } from 'msw'\nimport * as React from 'react'\nimport type { ReactReduxContextValue } from 'react-redux'\nimport {\n  Provider,\n  createDispatchHook,\n  createSelectorHook,\n  createStoreHook,\n} from 'react-redux'\n\nconst api = createApi({\n  baseQuery: async (arg: any) => {\n    await delay(150)\n    return { data: arg?.body ? arg.body : null }\n  },\n  endpoints: (build) => ({\n    getUser: build.query<any, number>({\n      query: (arg) => arg,\n    }),\n    updateUser: build.mutation<any, { name: string }>({\n      query: (update) => ({ body: update }),\n    }),\n  }),\n})\n\nafterEach(() => {\n  vi.resetAllMocks()\n})\n\ndescribe('ApiProvider', () => {\n  test('ApiProvider allows a user to make queries without a traditional Redux setup', async () => {\n    function User() {\n      const [value, setValue] = React.useState(0)\n\n      const { isFetching } = api.endpoints.getUser.useQuery(1, {\n        skip: value < 1,\n      })\n\n      return (\n        <div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <button onClick={() => setValue((val) => val + 1)}>\n            Increment value\n          </button>\n        </div>\n      )\n    }\n\n    const { getByText, getByTestId } = render(\n      <ApiProvider api={api}>\n        <User />\n      </ApiProvider>,\n    )\n\n    await waitFor(() =>\n      expect(getByTestId('isFetching').textContent).toBe('false'),\n    )\n    fireEvent.click(getByText('Increment value'))\n    await waitFor(() =>\n      expect(getByTestId('isFetching').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(getByTestId('isFetching').textContent).toBe('false'),\n    )\n    fireEvent.click(getByText('Increment value'))\n    // Being that nothing has changed in the args, this should never fire.\n    expect(getByTestId('isFetching').textContent).toBe('false')\n  })\n  test('ApiProvider throws if nested inside a Redux context', () => {\n    // Intentionally swallow the \"unhandled error\" message\n    vi.spyOn(console, 'error').mockImplementation(() => {})\n    expect(() =>\n      render(\n        <Provider store={configureStore({ reducer: () => null })}>\n          <ApiProvider api={api}>child</ApiProvider>\n        </Provider>,\n      ),\n    ).toThrowErrorMatchingInlineSnapshot(\n      `[Error: Existing Redux context detected. If you already have a store set up, please use the traditional Redux setup.]`,\n    )\n  })\n  test('ApiProvider allows a custom context', async () => {\n    const customContext = React.createContext<ReactReduxContextValue | null>(\n      null,\n    )\n\n    const createApiWithCustomContext = buildCreateApi(\n      coreModule(),\n      reactHooksModule({\n        hooks: {\n          useStore: createStoreHook(customContext),\n          useSelector: createSelectorHook(customContext),\n          useDispatch: createDispatchHook(customContext),\n        },\n      }),\n    )\n\n    const customApi = createApiWithCustomContext({\n      baseQuery: async (arg: any) => {\n        await delay(150)\n        return { data: arg?.body ? arg.body : null }\n      },\n      endpoints: (build) => ({\n        getUser: build.query<any, number>({\n          query: (arg) => arg,\n        }),\n        updateUser: build.mutation<any, { name: string }>({\n          query: (update) => ({ body: update }),\n        }),\n      }),\n    })\n\n    function User() {\n      const [value, setValue] = React.useState(0)\n\n      const { isFetching } = customApi.endpoints.getUser.useQuery(1, {\n        skip: value < 1,\n      })\n\n      return (\n        <div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <button onClick={() => setValue((val) => val + 1)}>\n            Increment value\n          </button>\n        </div>\n      )\n    }\n\n    const { getByText, getByTestId } = render(\n      <ApiProvider api={customApi} context={customContext}>\n        <User />\n      </ApiProvider>,\n    )\n\n    await waitFor(() =>\n      expect(getByTestId('isFetching').textContent).toBe('false'),\n    )\n    fireEvent.click(getByText('Increment value'))\n    await waitFor(() =>\n      expect(getByTestId('isFetching').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(getByTestId('isFetching').textContent).toBe('false'),\n    )\n    fireEvent.click(getByText('Increment value'))\n    // Being that nothing has changed in the args, this should never fire.\n    expect(getByTestId('isFetching').textContent).toBe('false')\n\n    // won't throw if nested, because context is different\n    expect(() =>\n      render(\n        <Provider store={configureStore({ reducer: () => null })}>\n          <ApiProvider api={customApi} context={customContext}>\n            child\n          </ApiProvider>\n        </Provider>,\n      ),\n    ).not.toThrow()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/baseQueryTypes.test-d.ts",
    "content": "import { createApi, fetchBaseQuery, retry } from '@reduxjs/toolkit/query'\n\ndescribe('type tests', () => {\n  test('BaseQuery meta types propagate to endpoint callbacks', () => {\n    createApi({\n      baseQuery: fetchBaseQuery(),\n      endpoints: (build) => ({\n        getDummy: build.query<null, undefined>({\n          query: () => 'dummy',\n          onCacheEntryAdded: async (arg, { cacheDataLoaded }) => {\n            const { meta } = await cacheDataLoaded\n            const { request, response } = meta! // Expect request and response to be there\n          },\n        }),\n      }),\n    })\n\n    const baseQuery = retry(fetchBaseQuery()) // Even when wrapped with retry\n    createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        getDummy: build.query<null, undefined>({\n          query: () => 'dummy',\n          onCacheEntryAdded: async (arg, { cacheDataLoaded }) => {\n            const { meta } = await cacheDataLoaded\n            const { request, response } = meta! // Expect request and response to be there\n          },\n        }),\n      }),\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/buildCreateApi.test.tsx",
    "content": "import { createSelectorCreator, lruMemoize } from '@reduxjs/toolkit'\nimport {\n  buildCreateApi,\n  coreModule,\n  reactHooksModule,\n} from '@reduxjs/toolkit/query/react'\nimport { render, screen, waitFor } from '@testing-library/react'\nimport { delay } from 'msw'\nimport * as React from 'react'\nimport type { ReactReduxContextValue } from 'react-redux'\nimport {\n  Provider,\n  createDispatchHook,\n  createSelectorHook,\n  createStoreHook,\n} from 'react-redux'\nimport { setupApiStore, useRenderCounter } from '../../tests/utils/helpers'\n\nconst MyContext = React.createContext<ReactReduxContextValue | null>(null)\n\ndescribe('buildCreateApi', () => {\n  test('Works with all hooks provided', async () => {\n    const customCreateApi = buildCreateApi(\n      coreModule(),\n      reactHooksModule({\n        hooks: {\n          useDispatch: createDispatchHook(MyContext),\n          useSelector: createSelectorHook(MyContext),\n          useStore: createStoreHook(MyContext),\n        },\n      }),\n    )\n\n    const api = customCreateApi({\n      baseQuery: async (arg: any) => {\n        await delay(150)\n\n        return {\n          data: arg?.body ? { ...arg.body } : {},\n        }\n      },\n      endpoints: (build) => ({\n        getUser: build.query<{ name: string }, number>({\n          query: () => ({\n            body: { name: 'Timmy' },\n          }),\n        }),\n      }),\n    })\n\n    let getRenderCount: () => number = () => 0\n\n    const storeRef = setupApiStore(api, {}, { withoutTestLifecycles: true })\n\n    // Copy of 'useQuery hook basic render count assumptions' from `buildHooks.test.tsx`\n    function User() {\n      const { isFetching } = api.endpoints.getUser.useQuery(1)\n      getRenderCount = useRenderCounter()\n\n      return (\n        <div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n        </div>\n      )\n    }\n\n    function Wrapper({ children }: any) {\n      return (\n        <Provider store={storeRef.store} context={MyContext}>\n          {children}\n        </Provider>\n      )\n    }\n\n    render(<User />, { wrapper: Wrapper })\n    // By the time this runs, the initial render will happen, and the query\n    //  will start immediately running by the time we can expect this\n    expect(getRenderCount()).toBe(2)\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n    )\n    expect(getRenderCount()).toBe(3)\n  })\n\n  test(\"Throws an error if you don't provide all hooks\", async () => {\n    const callBuildCreateApi = () => {\n      const customCreateApi = buildCreateApi(\n        coreModule(),\n        reactHooksModule({\n          // @ts-ignore\n          hooks: {\n            useDispatch: createDispatchHook(MyContext),\n            useSelector: createSelectorHook(MyContext),\n          },\n        }),\n      )\n    }\n\n    expect(callBuildCreateApi).toThrowErrorMatchingInlineSnapshot(\n      `\n      [Error: When using custom hooks for context, all 3 hooks need to be provided: useDispatch, useSelector, useStore.\n      Hook useStore was either not provided or not a function.]\n    `,\n    )\n  })\n  test('allows passing createSelector instance', async () => {\n    const memoize = vi.fn(lruMemoize)\n    const createSelector = createSelectorCreator(memoize)\n    const createApi = buildCreateApi(\n      coreModule({ createSelector }),\n      reactHooksModule({ createSelector }),\n    )\n    const api = createApi({\n      baseQuery: async (arg: any) => {\n        await delay(150)\n\n        return {\n          data: arg?.body ? { ...arg.body } : {},\n        }\n      },\n      endpoints: (build) => ({\n        getUser: build.query<{ name: string }, number>({\n          query: () => ({\n            body: { name: 'Timmy' },\n          }),\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, {}, { withoutTestLifecycles: true })\n\n    await storeRef.store.dispatch(api.endpoints.getUser.initiate(1))\n\n    const selectUser = api.endpoints.getUser.select(1)\n\n    expect(selectUser(storeRef.store.getState()).data).toEqual({\n      name: 'Timmy',\n    })\n\n    expect(memoize).toHaveBeenCalledTimes(4)\n\n    memoize.mockClear()\n\n    function User() {\n      const { isFetching } = api.endpoints.getUser.useQuery(1)\n\n      return (\n        <div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n        </div>\n      )\n    }\n\n    function Wrapper({ children }: any) {\n      return <Provider store={storeRef.store}>{children}</Provider>\n    }\n\n    render(<User />, { wrapper: Wrapper })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n    )\n\n    // select() + selectFromResult\n    expect(memoize).toHaveBeenCalledTimes(8)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/buildHooks.test-d.tsx",
    "content": "import type { UseMutation, UseQuery } from '@internal/query/react/buildHooks'\nimport { ANY } from '@internal/tests/utils/helpers'\nimport type { SerializedError } from '@reduxjs/toolkit'\nimport type {\n  SubscriptionOptions,\n  TypedQueryStateSelector,\n} from '@reduxjs/toolkit/query/react'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { useState } from 'react'\n\nlet amount = 0\nlet nextItemId = 0\n\ninterface Item {\n  id: number\n}\n\nconst api = createApi({\n  baseQuery: (arg: any) => {\n    if (arg?.body && 'amount' in arg.body) {\n      amount += 1\n    }\n\n    if (arg?.body && 'forceError' in arg.body) {\n      return {\n        error: {\n          status: 500,\n          data: null,\n        },\n      }\n    }\n\n    if (arg?.body && 'listItems' in arg.body) {\n      const items: Item[] = []\n      for (let i = 0; i < 3; i++) {\n        const item = { id: nextItemId++ }\n        items.push(item)\n      }\n      return { data: items }\n    }\n\n    return {\n      data: arg?.body ? { ...arg.body, ...(amount ? { amount } : {}) } : {},\n    }\n  },\n  endpoints: (build) => ({\n    getUser: build.query<{ name: string }, number>({\n      query: () => ({\n        body: { name: 'Timmy' },\n      }),\n    }),\n    getUserAndForceError: build.query<{ name: string }, number>({\n      query: () => ({\n        body: {\n          forceError: true,\n        },\n      }),\n    }),\n    getIncrementedAmount: build.query<{ amount: number }, void>({\n      query: () => ({\n        url: '',\n        body: {\n          amount,\n        },\n      }),\n    }),\n    updateUser: build.mutation<{ name: string }, { name: string }>({\n      query: (update) => ({ body: update }),\n    }),\n    getError: build.query({\n      query: () => '/error',\n    }),\n    listItems: build.query<Item[], { pageNumber: number }>({\n      serializeQueryArgs: ({ endpointName }) => {\n        return endpointName\n      },\n      query: ({ pageNumber }) => ({\n        url: `items?limit=1&offset=${pageNumber}`,\n        body: {\n          listItems: true,\n        },\n      }),\n      merge: (currentCache, newItems) => {\n        currentCache.push(...newItems)\n      },\n      forceRefetch: () => {\n        return true\n      },\n    }),\n  }),\n})\n\ndescribe('type tests', () => {\n  test('useLazyQuery hook callback returns various properties to handle the result', () => {\n    function User() {\n      const [getUser] = api.endpoints.getUser.useLazyQuery()\n      const [{ successMsg, errMsg, isAborted }, setValues] = useState({\n        successMsg: '',\n        errMsg: '',\n        isAborted: false,\n      })\n\n      const handleClick = (abort: boolean) => async () => {\n        const res = getUser(1)\n\n        // no-op simply for clearer type assertions\n        res.then((result) => {\n          if (result.isSuccess) {\n            expectTypeOf(result).toMatchObjectType<{\n              data: {\n                name: string\n              }\n            }>()\n          }\n\n          if (result.isError) {\n            expectTypeOf(result).toExtend<{\n              error: { status: number; data: unknown } | SerializedError\n            }>()\n          }\n        })\n\n        expectTypeOf(res.arg).toBeNumber()\n\n        expectTypeOf(res.requestId).toBeString()\n\n        expectTypeOf(res.abort).toEqualTypeOf<() => void>()\n\n        expectTypeOf(res.unsubscribe).toEqualTypeOf<() => void>()\n\n        expectTypeOf(res.updateSubscriptionOptions).toEqualTypeOf<\n          (options: SubscriptionOptions) => void\n        >()\n\n        expectTypeOf(res.refetch).toExtend<() => void>()\n\n        expectTypeOf(res.unwrap()).resolves.toEqualTypeOf<{ name: string }>()\n      }\n\n      return (\n        <div>\n          <button onClick={handleClick(false)}>Fetch User successfully</button>\n          <button onClick={handleClick(true)}>Fetch User and abort</button>\n          <div>{successMsg}</div>\n          <div>{errMsg}</div>\n          <div>{isAborted ? 'Request was aborted' : ''}</div>\n        </div>\n      )\n    }\n  })\n\n  test('useMutation hook callback returns various properties to handle the result', async () => {\n    function User() {\n      const [updateUser] = api.endpoints.updateUser.useMutation()\n      const [successMsg, setSuccessMsg] = useState('')\n      const [errMsg, setErrMsg] = useState('')\n      const [isAborted, setIsAborted] = useState(false)\n\n      const handleClick = async () => {\n        const res = updateUser({ name: 'Banana' })\n\n        expectTypeOf(res).resolves.toExtend<\n          | {\n              error: { status: number; data: unknown } | SerializedError\n            }\n          | {\n              data: {\n                name: string\n              }\n            }\n        >()\n\n        expectTypeOf(res.arg).toMatchObjectType<{\n          endpointName: string\n          originalArgs: { name: string }\n          track?: boolean\n        }>()\n\n        expectTypeOf(res.requestId).toBeString()\n\n        expectTypeOf(res.abort).toEqualTypeOf<() => void>()\n\n        expectTypeOf(res.unwrap()).resolves.toEqualTypeOf<{ name: string }>()\n\n        expectTypeOf(res.reset).toEqualTypeOf<() => void>()\n      }\n\n      return (\n        <div>\n          <button onClick={handleClick}>Update User and abort</button>\n          <div>{successMsg}</div>\n          <div>{errMsg}</div>\n          <div>{isAborted ? 'Request was aborted' : ''}</div>\n        </div>\n      )\n    }\n  })\n\n  test('top level named hooks', () => {\n    interface Post {\n      id: number\n      name: string\n      fetched_at: string\n    }\n\n    type PostsResponse = Post[]\n\n    const api = createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }),\n      tagTypes: ['Posts'],\n      endpoints: (build) => ({\n        getPosts: build.query<PostsResponse, void>({\n          query: () => ({ url: 'posts' }),\n          providesTags: (result) =>\n            result ? result.map(({ id }) => ({ type: 'Posts', id })) : [],\n        }),\n        updatePost: build.mutation<Post, Partial<Post>>({\n          query: ({ id, ...body }) => ({\n            url: `post/${id}`,\n            method: 'PUT',\n            body,\n          }),\n          invalidatesTags: (result, error, { id }) => [{ type: 'Posts', id }],\n        }),\n        addPost: build.mutation<Post, Partial<Post>>({\n          query: (body) => ({\n            url: `post`,\n            method: 'POST',\n            body,\n          }),\n          invalidatesTags: ['Posts'],\n        }),\n      }),\n    })\n\n    expectTypeOf(api.useGetPostsQuery).toEqualTypeOf(\n      api.endpoints.getPosts.useQuery,\n    )\n\n    expectTypeOf(api.useUpdatePostMutation).toEqualTypeOf(\n      api.endpoints.updatePost.useMutation,\n    )\n\n    expectTypeOf(api.useAddPostMutation).toEqualTypeOf(\n      api.endpoints.addPost.useMutation,\n    )\n  })\n\n  test('UseQuery type can be used to recreate the hook type', () => {\n    const fakeQuery = ANY as UseQuery<\n      typeof api.endpoints.getUser.Types.QueryDefinition\n    >\n\n    expectTypeOf(fakeQuery).toEqualTypeOf(api.endpoints.getUser.useQuery)\n  })\n\n  test('UseMutation type can be used to recreate the hook type', () => {\n    const fakeMutation = ANY as UseMutation<\n      typeof api.endpoints.updateUser.Types.MutationDefinition\n    >\n\n    expectTypeOf(fakeMutation).toEqualTypeOf(\n      api.endpoints.updateUser.useMutation,\n    )\n  })\n\n  test('TypedQueryStateSelector creates a pre-typed version of QueryStateSelector', () => {\n    type Post = {\n      id: number\n      title: string\n    }\n\n    type PostsApiResponse = {\n      posts: Post[]\n      total: number\n      skip: number\n      limit: number\n    }\n\n    type QueryArgument = number | undefined\n\n    type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n\n    type SelectedResult = Pick<PostsApiResponse, 'posts'>\n\n    const postsApiSlice = createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com/posts' }),\n      reducerPath: 'postsApi',\n      tagTypes: ['Posts'],\n      endpoints: (build) => ({\n        getPosts: build.query<PostsApiResponse, QueryArgument>({\n          query: (limit = 5) => `?limit=${limit}&select=title`,\n        }),\n      }),\n    })\n\n    const { useGetPostsQuery } = postsApiSlice\n\n    function PostById({ id }: { id: number }) {\n      const { post } = useGetPostsQuery(undefined, {\n        selectFromResult: (state) => ({\n          post: state.data?.posts.find((post) => post.id === id),\n        }),\n      })\n\n      expectTypeOf(post).toEqualTypeOf<Post | undefined>()\n\n      return <li>{post?.title}</li>\n    }\n\n    const EMPTY_ARRAY: Post[] = []\n\n    const typedSelectFromResult: TypedQueryStateSelector<\n      PostsApiResponse,\n      QueryArgument,\n      BaseQueryFunction,\n      SelectedResult\n    > = (state) => ({ posts: state.data?.posts ?? EMPTY_ARRAY })\n\n    function PostsList() {\n      const { posts } = useGetPostsQuery(undefined, {\n        selectFromResult: typedSelectFromResult,\n      })\n\n      expectTypeOf(posts).toEqualTypeOf<Post[]>()\n\n      return (\n        <div>\n          <ul>\n            {posts.map((post) => (\n              <PostById key={post.id} id={post.id} />\n            ))}\n          </ul>\n        </div>\n      )\n    }\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/buildHooks.test.tsx",
    "content": "import { noop } from '@internal/listenerMiddleware/utils'\nimport type { SubscriptionSelectors } from '@internal/query/core/buildMiddleware/types'\nimport { server } from '@internal/query/tests/mocks/server'\nimport { countObjectKeys } from '@internal/query/utils/countObjectKeys'\nimport {\n  actionsReducer,\n  setupApiStore,\n  useRenderCounter,\n  waitForFakeTimer,\n  waitMs,\n  withProvider,\n} from '@internal/tests/utils/helpers'\nimport type { UnknownAction } from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createListenerMiddleware,\n  createSlice,\n} from '@reduxjs/toolkit'\nimport type { SubscriptionOptions } from '@reduxjs/toolkit/query/react'\nimport {\n  QueryStatus,\n  createApi,\n  fetchBaseQuery,\n  skipToken,\n} from '@reduxjs/toolkit/query/react'\nimport {\n  act,\n  fireEvent,\n  render,\n  renderHook,\n  screen,\n  waitFor,\n} from '@testing-library/react'\nimport type { SyncScreen } from '@testing-library/react-render-stream/pure'\nimport { createRenderStream } from '@testing-library/react-render-stream/pure'\nimport { userEvent } from '@testing-library/user-event'\nimport { HttpResponse, delay, http } from 'msw'\nimport { useEffect, useMemo, useRef, useState } from 'react'\nimport type { InfiniteQueryResultFlags } from '../core/buildSelectors'\n\n// Just setup a temporary in-memory counter for tests that `getIncrementedAmount`.\n// This can be used to test how many renders happen due to data changes or\n// the refetching behavior of components.\nlet amount = 0\nlet nextItemId = 0\nlet refetchCount = 0\n\ninterface Item {\n  id: number\n}\n\nconst api = createApi({\n  baseQuery: async (arg: any) => {\n    await waitForFakeTimer(150)\n    if (arg?.body && 'amount' in arg.body) {\n      amount += 1\n    }\n\n    if (arg?.body && 'forceError' in arg.body) {\n      return {\n        error: {\n          status: 500,\n          data: null,\n        },\n      }\n    }\n\n    if (arg?.body && 'listItems' in arg.body) {\n      const items: Item[] = []\n      for (let i = 0; i < 3; i++) {\n        const item = { id: nextItemId++ }\n        items.push(item)\n      }\n      return { data: items }\n    }\n\n    return {\n      data: arg?.body ? { ...arg.body, ...(amount ? { amount } : {}) } : {},\n    }\n  },\n  tagTypes: ['IncrementedAmount'],\n  endpoints: (build) => ({\n    getUser: build.query<{ name: string }, number>({\n      query: () => ({\n        body: { name: 'Timmy' },\n      }),\n    }),\n    getUserAndForceError: build.query<{ name: string }, number>({\n      query: () => ({\n        body: {\n          forceError: true,\n        },\n      }),\n    }),\n    getUserWithRefetchError: build.query<{ name: string }, number>({\n      queryFn: async (id) => {\n        refetchCount += 1\n\n        if (refetchCount > 1) {\n          return { error: true } as any\n        }\n\n        return { data: { name: 'Timmy' } }\n      },\n    }),\n    getIncrementedAmount: build.query<{ amount: number }, void>({\n      query: () => ({\n        url: '',\n        body: {\n          amount,\n        },\n      }),\n      providesTags: ['IncrementedAmount'],\n    }),\n    triggerUpdatedAmount: build.mutation<void, void>({\n      queryFn: async () => {\n        return { data: undefined }\n      },\n      invalidatesTags: ['IncrementedAmount'],\n    }),\n    updateUser: build.mutation<{ name: string }, { name: string }>({\n      query: (update) => ({ body: update }),\n    }),\n    getError: build.query({\n      query: () => '/error',\n    }),\n    listItems: build.query<Item[], { pageNumber: number | bigint }>({\n      serializeQueryArgs: ({ endpointName }) => {\n        return endpointName\n      },\n      query: ({ pageNumber }) => ({\n        url: `items?limit=1&offset=${pageNumber}`,\n        body: {\n          listItems: true,\n        },\n      }),\n      merge: (currentCache, newItems) => {\n        currentCache.push(...newItems)\n      },\n      forceRefetch: () => {\n        return true\n      },\n    }),\n    queryWithDeepArg: build.query<string, { param: { nested: string } }>({\n      query: ({ param: { nested } }) => nested,\n      serializeQueryArgs: ({ queryArgs }) => {\n        return queryArgs.param.nested\n      },\n    }),\n  }),\n})\n\nconst listenerMiddleware = createListenerMiddleware()\n\nlet actions: UnknownAction[] = []\n\nconst storeRef = setupApiStore(\n  api,\n  {},\n  {\n    middleware: {\n      prepend: [listenerMiddleware.middleware],\n    },\n  },\n)\n\nlet getSubscriptions: SubscriptionSelectors['getSubscriptions']\nlet getSubscriptionCount: SubscriptionSelectors['getSubscriptionCount']\n\nbeforeEach(() => {\n  actions = []\n  listenerMiddleware.startListening({\n    predicate: () => true,\n    effect: (action) => {\n      actions.push(action)\n    },\n  })\n  ;({ getSubscriptions, getSubscriptionCount } = storeRef.store.dispatch(\n    api.internalActions.internal_getRTKQSubscriptions(),\n  ) as unknown as SubscriptionSelectors)\n})\n\nafterEach(() => {\n  nextItemId = 0\n  amount = 0\n  listenerMiddleware.clearListeners()\n\n  server.resetHandlers()\n})\n\nlet getRenderCount: () => number = () => 0\n\ndescribe('hooks tests', () => {\n  describe('useQuery', () => {\n    test('useQuery hook basic render count assumptions', async () => {\n      function User() {\n        const { isFetching } = api.endpoints.getUser.useQuery(1)\n        getRenderCount = useRenderCounter()\n\n        return (\n          <div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      // By the time this runs, the initial render will happen, and the query\n      //  will start immediately running by the time we can expect this\n      expect(getRenderCount()).toBe(2)\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n      expect(getRenderCount()).toBe(3)\n    })\n\n    test('useQuery hook sets isFetching=true whenever a request is in flight', async () => {\n      function User() {\n        const [value, setValue] = useState(0)\n\n        const { isFetching } = api.endpoints.getUser.useQuery(1, {\n          skip: value < 1,\n        })\n        getRenderCount = useRenderCounter()\n\n        return (\n          <div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <button onClick={() => setValue((val) => val + 1)}>\n              Increment value\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      expect(getRenderCount()).toBe(1)\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n      fireEvent.click(screen.getByText('Increment value')) // setState = 1, perform request = 2\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n      expect(getRenderCount()).toBe(4)\n\n      fireEvent.click(screen.getByText('Increment value'))\n      // Being that nothing has changed in the args, this should never fire.\n      expect(screen.getByTestId('isFetching').textContent).toBe('false')\n      expect(getRenderCount()).toBe(5) // even though there was no request, the button click updates the state so this is an expected render\n    })\n\n    test('useQuery hook sets isLoading=true only on initial request', async () => {\n      let refetch: any, isLoading: boolean, isFetching: boolean\n      function User() {\n        const [value, setValue] = useState(0)\n\n        ;({ isLoading, isFetching, refetch } = api.endpoints.getUser.useQuery(\n          2,\n          {\n            skip: value < 1,\n          },\n        ))\n        return (\n          <div>\n            <div data-testid=\"isLoading\">{String(isLoading)}</div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <button onClick={() => setValue((val) => val + 1)}>\n              Increment value\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      // Being that we skipped the initial request on mount, this should be false\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n      )\n      fireEvent.click(screen.getByText('Increment value'))\n      // Condition is met, should load\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n      ) // Make sure the original loading has completed.\n      fireEvent.click(screen.getByText('Increment value'))\n      // Being that we already have data, isLoading should be false\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n      )\n      // We call a refetch, should still be `false`\n      act(() => void refetch())\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      expect(screen.getByTestId('isLoading').textContent).toBe('false')\n    })\n\n    test('useQuery hook sets isLoading and isFetching to the correct states', async () => {\n      let refetchMe: () => void = () => {}\n      function User() {\n        const [value, setValue] = useState(0)\n        getRenderCount = useRenderCounter()\n\n        const { isLoading, isFetching, refetch } =\n          api.endpoints.getUser.useQuery(22, { skip: value < 1 })\n        refetchMe = refetch\n        return (\n          <div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <div data-testid=\"isLoading\">{String(isLoading)}</div>\n            <button onClick={() => setValue((val) => val + 1)}>\n              Increment value\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      expect(getRenderCount()).toBe(1)\n\n      expect(screen.getByTestId('isLoading').textContent).toBe('false')\n      expect(screen.getByTestId('isFetching').textContent).toBe('false')\n\n      fireEvent.click(screen.getByText('Increment value')) // renders: set state = 1, perform request = 2\n      // Condition is met, should load\n      await waitFor(() => {\n        expect(screen.getByTestId('isLoading').textContent).toBe('true')\n        expect(screen.getByTestId('isFetching').textContent).toBe('true')\n      })\n\n      // Make sure the request is done for sure.\n      await waitFor(() => {\n        expect(screen.getByTestId('isLoading').textContent).toBe('false')\n        expect(screen.getByTestId('isFetching').textContent).toBe('false')\n      })\n      expect(getRenderCount()).toBe(4)\n\n      fireEvent.click(screen.getByText('Increment value'))\n      // Being that we already have data and changing the value doesn't trigger a new request, only the button click should impact the render\n      await waitFor(() => {\n        expect(screen.getByTestId('isLoading').textContent).toBe('false')\n        expect(screen.getByTestId('isFetching').textContent).toBe('false')\n      })\n      expect(getRenderCount()).toBe(5)\n\n      // We call a refetch, should set `isFetching` to true, then false when complete/errored\n      act(() => void refetchMe())\n      await waitFor(() => {\n        expect(screen.getByTestId('isLoading').textContent).toBe('false')\n        expect(screen.getByTestId('isFetching').textContent).toBe('true')\n      })\n      await waitFor(() => {\n        expect(screen.getByTestId('isLoading').textContent).toBe('false')\n        expect(screen.getByTestId('isFetching').textContent).toBe('false')\n      })\n      expect(getRenderCount()).toBe(7)\n    })\n\n    test('`isLoading` does not jump back to true, while `isFetching` does', async () => {\n      const loadingHist: boolean[] = [],\n        fetchingHist: boolean[] = []\n\n      function User({ id }: { id: number }) {\n        const { isLoading, isFetching, status } =\n          api.endpoints.getUser.useQuery(id)\n\n        useEffect(() => {\n          loadingHist.push(isLoading)\n        }, [isLoading])\n        useEffect(() => {\n          fetchingHist.push(isFetching)\n        }, [isFetching])\n        return (\n          <div data-testid=\"status\">\n            {status === QueryStatus.fulfilled && id}\n          </div>\n        )\n      }\n\n      let { rerender } = render(<User id={1} />, { wrapper: storeRef.wrapper })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('1'),\n      )\n      rerender(<User id={2} />)\n\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('2'),\n      )\n\n      expect(loadingHist).toEqual([true, false])\n      expect(fetchingHist).toEqual([true, false, true, false])\n    })\n\n    test('`isSuccess` does not jump back false on subsequent queries', async () => {\n      type LoadingState = {\n        id: number\n        isFetching: boolean\n        isSuccess: boolean\n      }\n      const loadingHistory: LoadingState[] = []\n\n      function User({ id }: { id: number }) {\n        const queryRes = api.endpoints.getUser.useQuery(id)\n\n        useEffect(() => {\n          const { isFetching, isSuccess } = queryRes\n          loadingHistory.push({ id, isFetching, isSuccess })\n        }, [id, queryRes])\n        return (\n          <div data-testid=\"status\">\n            {queryRes.status === QueryStatus.fulfilled && id}\n          </div>\n        )\n      }\n\n      let { rerender } = render(<User id={1} />, { wrapper: storeRef.wrapper })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('1'),\n      )\n      rerender(<User id={2} />)\n\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('2'),\n      )\n\n      expect(loadingHistory).toEqual([\n        // Initial render(s)\n        { id: 1, isFetching: true, isSuccess: false },\n        { id: 1, isFetching: true, isSuccess: false },\n        // Data returned\n        { id: 1, isFetching: false, isSuccess: true },\n        // ID changed, there's an uninitialized cache entry.\n        // IMPORTANT: `isSuccess` should not be false here.\n        // We have valid data already for the old item.\n        { id: 2, isFetching: true, isSuccess: true },\n        { id: 2, isFetching: true, isSuccess: true },\n        { id: 2, isFetching: false, isSuccess: true },\n      ])\n    })\n\n    test('isSuccess stays consistent if there is an error while refetching', async () => {\n      type LoadingState = {\n        id: number\n        isFetching: boolean\n        isSuccess: boolean\n        isError: boolean\n      }\n      const loadingHistory: LoadingState[] = []\n\n      function Component({ id = 1 }) {\n        const queryRes = api.endpoints.getUserWithRefetchError.useQuery(id)\n        const { refetch, data, status } = queryRes\n\n        useEffect(() => {\n          const { isFetching, isSuccess, isError } = queryRes\n          loadingHistory.push({ id, isFetching, isSuccess, isError })\n        }, [id, queryRes])\n\n        return (\n          <div>\n            <button\n              onClick={() => {\n                refetch()\n              }}\n            >\n              refetch\n            </button>\n            <div data-testid=\"name\">{data?.name}</div>\n            <div data-testid=\"status\">{status}</div>\n          </div>\n        )\n      }\n\n      render(<Component />, { wrapper: storeRef.wrapper })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('name').textContent).toBe('Timmy'),\n      )\n\n      fireEvent.click(screen.getByText('refetch'))\n\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('pending'),\n      )\n\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('rejected'),\n      )\n\n      fireEvent.click(screen.getByText('refetch'))\n\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('pending'),\n      )\n\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('rejected'),\n      )\n\n      expect(loadingHistory).toEqual([\n        // Initial renders\n        { id: 1, isFetching: true, isSuccess: false, isError: false },\n        { id: 1, isFetching: true, isSuccess: false, isError: false },\n        // Data is returned\n        { id: 1, isFetching: false, isSuccess: true, isError: false },\n        // Started first refetch\n        { id: 1, isFetching: true, isSuccess: true, isError: false },\n        // First refetch errored\n        { id: 1, isFetching: false, isSuccess: false, isError: true },\n        // Started second refetch\n        // IMPORTANT We expect `isSuccess` to still be false,\n        // despite having started the refetch again.\n        { id: 1, isFetching: true, isSuccess: false, isError: false },\n        // Second refetch errored\n        { id: 1, isFetching: false, isSuccess: false, isError: true },\n      ])\n    })\n\n    test('useQuery hook respects refetchOnMountOrArgChange: true', async () => {\n      let data, isLoading, isFetching\n      function User() {\n        ;({ data, isLoading, isFetching } =\n          api.endpoints.getIncrementedAmount.useQuery(undefined, {\n            refetchOnMountOrArgChange: true,\n          }))\n        return (\n          <div>\n            <div data-testid=\"isLoading\">{String(isLoading)}</div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <div data-testid=\"amount\">{String(data?.amount)}</div>\n          </div>\n        )\n      }\n\n      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n      )\n\n      await waitFor(() =>\n        expect(screen.getByTestId('amount').textContent).toBe('1'),\n      )\n\n      unmount()\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      // Let's make sure we actually fetch, and we increment\n      expect(screen.getByTestId('isLoading').textContent).toBe('false')\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n\n      await waitFor(() =>\n        expect(screen.getByTestId('amount').textContent).toBe('2'),\n      )\n    })\n\n    test('useQuery does not refetch when refetchOnMountOrArgChange: NUMBER condition is not met', async () => {\n      let data, isLoading, isFetching\n      function User() {\n        ;({ data, isLoading, isFetching } =\n          api.endpoints.getIncrementedAmount.useQuery(undefined, {\n            refetchOnMountOrArgChange: 10,\n          }))\n        return (\n          <div>\n            <div data-testid=\"isLoading\">{String(isLoading)}</div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <div data-testid=\"amount\">{String(data?.amount)}</div>\n          </div>\n        )\n      }\n\n      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n      )\n\n      await waitFor(() =>\n        expect(screen.getByTestId('amount').textContent).toBe('1'),\n      )\n\n      unmount()\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      // Let's make sure we actually fetch, and we increment. Should be false because we do this immediately\n      // and the condition is set to 10 seconds\n      expect(screen.getByTestId('isFetching').textContent).toBe('false')\n      await waitFor(() =>\n        expect(screen.getByTestId('amount').textContent).toBe('1'),\n      )\n    })\n\n    test('useQuery refetches when refetchOnMountOrArgChange: NUMBER condition is met', async () => {\n      let data, isLoading, isFetching\n      function User() {\n        ;({ data, isLoading, isFetching } =\n          api.endpoints.getIncrementedAmount.useQuery(undefined, {\n            refetchOnMountOrArgChange: 0.5,\n          }))\n        return (\n          <div>\n            <div data-testid=\"isLoading\">{String(isLoading)}</div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <div data-testid=\"amount\">{String(data?.amount)}</div>\n          </div>\n        )\n      }\n\n      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n      )\n\n      await waitFor(() =>\n        expect(screen.getByTestId('amount').textContent).toBe('1'),\n      )\n\n      unmount()\n\n      // Wait to make sure we've passed the `refetchOnMountOrArgChange` value\n      await waitMs(510)\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      // Let's make sure we actually fetch, and we increment\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n\n      await waitFor(() =>\n        expect(screen.getByTestId('amount').textContent).toBe('2'),\n      )\n    })\n\n    test('refetchOnMountOrArgChange works as expected when changing skip from false->true', async () => {\n      let data, isLoading, isFetching\n      function User() {\n        const [skip, setSkip] = useState(true)\n        ;({ data, isLoading, isFetching } =\n          api.endpoints.getIncrementedAmount.useQuery(undefined, {\n            refetchOnMountOrArgChange: 0.5,\n            skip,\n          }))\n\n        return (\n          <div>\n            <div data-testid=\"isLoading\">{String(isLoading)}</div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <div data-testid=\"amount\">{String(data?.amount)}</div>\n            <button onClick={() => setSkip((prev) => !prev)}>\n              change skip\n            </button>\n            ;\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      expect(screen.getByTestId('isLoading').textContent).toBe('false')\n      expect(screen.getByTestId('amount').textContent).toBe('undefined')\n\n      fireEvent.click(screen.getByText('change skip'))\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n\n      await waitFor(() =>\n        expect(screen.getByTestId('amount').textContent).toBe('1'),\n      )\n    })\n\n    test('refetchOnMountOrArgChange works as expected when changing skip from false->true with a cached query', async () => {\n      // 1. we need to mount a skipped query, then toggle skip to generate a cached result\n      // 2. we need to mount a skipped component after that, then toggle skip as well. should pull from the cache.\n      // 3. we need to mount another skipped component, then toggle skip after the specified duration and expect the time condition to be satisfied\n\n      let data, isLoading, isFetching\n      function User() {\n        const [skip, setSkip] = useState(true)\n        ;({ data, isLoading, isFetching } =\n          api.endpoints.getIncrementedAmount.useQuery(undefined, {\n            skip,\n            refetchOnMountOrArgChange: 0.5,\n          }))\n\n        return (\n          <div>\n            <div data-testid=\"isLoading\">{String(isLoading)}</div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <div data-testid=\"amount\">{String(data?.amount)}</div>\n            <button onClick={() => setSkip((prev) => !prev)}>\n              change skip\n            </button>\n            ;\n          </div>\n        )\n      }\n\n      let { unmount } = render(<User />, { wrapper: storeRef.wrapper })\n\n      expect(screen.getByTestId('isFetching').textContent).toBe('false')\n\n      // skipped queries do nothing by default, so we need to toggle that to get a cached result\n      fireEvent.click(screen.getByText('change skip'))\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n\n      await waitFor(() => {\n        expect(screen.getByTestId('amount').textContent).toBe('1')\n        expect(screen.getByTestId('isFetching').textContent).toBe('false')\n      })\n\n      unmount()\n\n      await waitMs(100)\n\n      // This will pull from the cache as the time criteria is not met.\n      ;({ unmount } = render(<User />, {\n        wrapper: storeRef.wrapper,\n      }))\n\n      // skipped queries return nothing\n      expect(screen.getByTestId('isFetching').textContent).toBe('false')\n      expect(screen.getByTestId('amount').textContent).toBe('undefined')\n\n      // toggle skip -> true... won't refetch as the time critera is not met, and just loads the cached values\n      fireEvent.click(screen.getByText('change skip'))\n      expect(screen.getByTestId('isFetching').textContent).toBe('false')\n      expect(screen.getByTestId('amount').textContent).toBe('1')\n\n      unmount()\n\n      await waitMs(500)\n      ;({ unmount } = render(<User />, {\n        wrapper: storeRef.wrapper,\n      }))\n\n      // toggle skip -> true... will cause a refetch as the time criteria is now satisfied\n      fireEvent.click(screen.getByText('change skip'))\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n\n      await waitFor(() =>\n        expect(screen.getByTestId('amount').textContent).toBe('2'),\n      )\n    })\n\n    test(`useQuery refetches when query args object changes even if serialized args don't change`, async () => {\n      const user = userEvent.setup()\n\n      function ItemList() {\n        const [pageNumber, setPageNumber] = useState(0)\n        const { data = [] } = api.useListItemsQuery({\n          pageNumber,\n        })\n\n        const renderedItems = data.map((item) => (\n          <li key={item.id}>ID: {item.id}</li>\n        ))\n        return (\n          <div>\n            <button onClick={() => setPageNumber(pageNumber + 1)}>\n              Next Page\n            </button>\n            <ul>{renderedItems}</ul>\n          </div>\n        )\n      }\n\n      render(<ItemList />, { wrapper: storeRef.wrapper })\n\n      await screen.findByText('ID: 0')\n\n      await user.click(screen.getByText('Next Page'))\n\n      await screen.findByText('ID: 3')\n    })\n\n    test(`useQuery shouldn't call args serialization if request skipped`, async () => {\n      expect(() =>\n        renderHook(() => api.endpoints.queryWithDeepArg.useQuery(skipToken), {\n          wrapper: storeRef.wrapper,\n        }),\n      ).not.toThrow()\n    })\n\n    test(`useQuery gracefully handles bigint types`, async () => {\n      const user = userEvent.setup()\n\n      function ItemList() {\n        const [pageNumber, setPageNumber] = useState(0)\n        const { data = [] } = api.useListItemsQuery({\n          pageNumber: BigInt(pageNumber),\n        })\n\n        const renderedItems = data.map((item) => (\n          <li key={item.id}>ID: {item.id}</li>\n        ))\n        return (\n          <div>\n            <button onClick={() => setPageNumber(pageNumber + 1)}>\n              Next Page\n            </button>\n            <ul>{renderedItems}</ul>\n          </div>\n        )\n      }\n\n      render(<ItemList />, { wrapper: storeRef.wrapper })\n\n      await screen.findByText('ID: 0')\n\n      await user.click(screen.getByText('Next Page'))\n\n      await screen.findByText('ID: 3')\n    })\n\n    describe('api.util.resetApiState resets hook', () => {\n      test('without `selectFromResult`', async () => {\n        const { result } = renderHook(() => api.endpoints.getUser.useQuery(5), {\n          wrapper: storeRef.wrapper,\n        })\n\n        await waitFor(() => expect(result.current.isSuccess).toBe(true))\n\n        act(() => void storeRef.store.dispatch(api.util.resetApiState()))\n\n        expect(result.current).toEqual(\n          expect.objectContaining({\n            isError: false,\n            isFetching: true,\n            isLoading: true,\n            isSuccess: false,\n            isUninitialized: false,\n            refetch: expect.any(Function),\n            status: 'pending',\n          }),\n        )\n      })\n      test('with `selectFromResult`', async () => {\n        const selectFromResult = vi.fn((x) => x)\n        const { result } = renderHook(\n          () => api.endpoints.getUser.useQuery(5, { selectFromResult }),\n          {\n            wrapper: storeRef.wrapper,\n          },\n        )\n\n        await waitFor(() => expect(result.current.isSuccess).toBe(true))\n        selectFromResult.mockClear()\n        act(() => {\n          storeRef.store.dispatch(api.util.resetApiState())\n        })\n\n        expect(selectFromResult).toHaveBeenNthCalledWith(1, {\n          isError: false,\n          isFetching: false,\n          isLoading: false,\n          isSuccess: false,\n          isUninitialized: true,\n          status: 'uninitialized',\n        })\n      })\n\n      test('hook should not be stuck loading post resetApiState after re-render', async () => {\n        const user = userEvent.setup()\n\n        function QueryComponent() {\n          const { isLoading, data } = api.endpoints.getUser.useQuery(1)\n\n          if (isLoading) {\n            return <p>Loading...</p>\n          }\n\n          return <p>{data?.name}</p>\n        }\n\n        function Wrapper() {\n          const [open, setOpen] = useState(true)\n\n          const handleRerender = () => {\n            setOpen(false)\n            setTimeout(() => {\n              setOpen(true)\n            }, 250)\n          }\n\n          const handleReset = () => {\n            storeRef.store.dispatch(api.util.resetApiState())\n          }\n\n          return (\n            <>\n              <button onClick={handleRerender} aria-label=\"Rerender component\">\n                Rerender\n              </button>\n              {open ? (\n                <div>\n                  <button onClick={handleReset} aria-label=\"Reset API state\">\n                    Reset\n                  </button>\n\n                  <QueryComponent />\n                </div>\n              ) : null}\n            </>\n          )\n        }\n\n        render(<Wrapper />, { wrapper: storeRef.wrapper })\n\n        await user.click(\n          screen.getByRole('button', { name: /Rerender component/i }),\n        )\n        await waitFor(() => {\n          expect(screen.getByText('Timmy')).toBeTruthy()\n        })\n\n        await user.click(\n          screen.getByRole('button', { name: /reset api state/i }),\n        )\n        await waitFor(() => {\n          expect(screen.queryByText('Loading...')).toBeNull()\n        })\n        await waitFor(() => {\n          expect(screen.getByText('Timmy')).toBeTruthy()\n        })\n      })\n    })\n\n    test('useQuery refetch method returns a promise that resolves with the result', async () => {\n      const { result } = renderHook(\n        () => api.endpoints.getIncrementedAmount.useQuery(),\n        {\n          wrapper: storeRef.wrapper,\n        },\n      )\n\n      await waitFor(() => expect(result.current.isSuccess).toBe(true))\n      const originalAmount = result.current.data!.amount\n\n      const { refetch } = result.current\n\n      let resPromise: ReturnType<typeof refetch> = null as any\n      await act(async () => {\n        resPromise = refetch()\n      })\n      expect(resPromise).toBeInstanceOf(Promise)\n      const res = await act(() => resPromise)\n      expect(res.data!.amount).toBeGreaterThan(originalAmount)\n    })\n\n    // See https://github.com/reduxjs/redux-toolkit/issues/4267 - Memory leak in useQuery rapid query arg changes\n    test('Hook subscriptions are properly cleaned up when query is fulfilled/rejected', async () => {\n      // This is imported already, but it seems to be causing issues with the test on certain matrixes\n\n      const pokemonApi = createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n        endpoints: (builder) => ({\n          getTest: builder.query<string, number>({\n            async queryFn() {\n              await new Promise((resolve) => setTimeout(resolve, 1000))\n              return { data: 'data!' }\n            },\n            keepUnusedDataFor: 0,\n          }),\n        }),\n      })\n\n      const storeRef = setupApiStore(pokemonApi, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      const checkNumQueries = (count: number) => {\n        const cacheEntries = Object.keys(storeRef.store.getState().api.queries)\n        const queries = cacheEntries.length\n\n        expect(queries).toBe(count)\n      }\n\n      let i = 0\n\n      function User() {\n        const [fetchTest, { isFetching, isUninitialized }] =\n          pokemonApi.endpoints.getTest.useLazyQuery()\n\n        return (\n          <div>\n            <div data-testid=\"isUninitialized\">{String(isUninitialized)}</div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <button data-testid=\"fetchButton\" onClick={() => fetchTest(i++)}>\n              fetchUser\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      fireEvent.click(screen.getByTestId('fetchButton'))\n      fireEvent.click(screen.getByTestId('fetchButton'))\n      fireEvent.click(screen.getByTestId('fetchButton'))\n      checkNumQueries(3)\n\n      await act(async () => {\n        await delay(1500)\n      })\n\n      // There should only be one stored query once they have had time to resolve\n      checkNumQueries(1)\n    })\n\n    // See https://github.com/reduxjs/redux-toolkit/issues/3182\n    test('Hook subscriptions are properly cleaned up when changing skip back and forth', async () => {\n      const pokemonApi = createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n        endpoints: (builder) => ({\n          getPokemonByName: builder.query({\n            queryFn: (name: string) => ({ data: null }),\n            keepUnusedDataFor: 1,\n          }),\n        }),\n      })\n\n      const storeRef = setupApiStore(pokemonApi, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      const checkNumSubscriptions = (arg: string, count: number) => {\n        const subscriptions = getSubscriptions()\n        const cacheKeyEntry = subscriptions.get(arg)\n\n        if (cacheKeyEntry) {\n          const subscriptionCount = Object.keys(cacheKeyEntry) //getSubscriptionCount(arg)\n          expect(subscriptionCount).toBe(count)\n        }\n      }\n\n      // 1) Initial state: an active subscription\n      const { rerender, unmount } = renderHook(\n        ([arg, options]: Parameters<\n          typeof pokemonApi.useGetPokemonByNameQuery\n        >) => pokemonApi.useGetPokemonByNameQuery(arg, options),\n        {\n          wrapper: storeRef.wrapper,\n          initialProps: ['a'],\n        },\n      )\n\n      await act(async () => {\n        await waitMs(1)\n      })\n\n      // 2) Set the current subscription to `{skip: true}\n      rerender(['a', { skip: true }])\n\n      // 3) Change _both_ the cache key _and_ `{skip: false}` at the same time.\n      // This causes the `subscriptionRemoved` check to be `true`.\n      rerender(['b'])\n\n      // There should only be one active subscription after changing the arg\n      checkNumSubscriptions('b', 1)\n\n      // 4) Re-render with the same arg.\n      // This causes the `subscriptionRemoved` check to be `false`.\n      // Correct behavior is this does _not_ clear the promise ref,\n      // so\n      rerender(['b'])\n\n      // There should only be one active subscription after changing the arg\n      checkNumSubscriptions('b', 1)\n\n      await act(async () => {\n        await waitMs(1)\n      })\n\n      unmount()\n\n      await act(async () => {\n        await waitMs(1)\n      })\n\n      // There should be no subscription entries left over after changing\n      // cache key args and swapping `skip` on and off\n      checkNumSubscriptions('b', 0)\n\n      const finalSubscriptions = getSubscriptions()\n\n      for (const cacheKeyEntry of Object.values(finalSubscriptions)) {\n        expect(Object.values(cacheKeyEntry!).length).toBe(0)\n      }\n    })\n\n    test('Hook subscription failures do not reset isLoading state', async () => {\n      const states: boolean[] = []\n\n      function Parent() {\n        const { isLoading } = api.endpoints.getUserAndForceError.useQuery(1)\n\n        // Collect loading states to verify that it does not revert back to true.\n        states.push(isLoading)\n\n        // Parent conditionally renders child when loading.\n        if (isLoading) return null\n\n        return <Child />\n      }\n\n      function Child() {\n        // Using the same args as the parent\n        api.endpoints.getUserAndForceError.useQuery(1)\n\n        return null\n      }\n\n      render(<Parent />, { wrapper: storeRef.wrapper })\n\n      expect(states).toHaveLength(2)\n\n      // Allow at least three state effects to hit.\n      // Trying to see if any [true, false, true] occurs.\n      await act(async () => {\n        await waitForFakeTimer(150)\n      })\n\n      expect(states).toHaveLength(4)\n\n      await act(async () => {\n        await waitForFakeTimer(150)\n      })\n\n      expect(states).toHaveLength(5)\n\n      await act(async () => {\n        await waitForFakeTimer(150)\n      })\n\n      expect(states).toHaveLength(5)\n\n      // Find if at any time the isLoading state has reverted\n      // E.G.: `[..., true, false, ..., true]`\n      //              ^^^^  ^^^^^       ^^^^\n      const firstTrue = states.indexOf(true)\n      const firstFalse = states.slice(firstTrue).indexOf(false)\n      const revertedState = states.slice(firstFalse).indexOf(true)\n\n      expect(\n        revertedState,\n        `Expected isLoading state to never revert back to true but did after ${revertedState} renders...`,\n      ).toBe(-1)\n    })\n\n    test('query thunk should be aborted when component unmounts and cache entry is removed', async () => {\n      let abortSignalFromQueryFn: AbortSignal | undefined\n\n      const pokemonApi = createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n        endpoints: (builder) => ({\n          getTest: builder.query<string, number>({\n            async queryFn(arg, { signal }) {\n              abortSignalFromQueryFn = signal\n\n              // Simulate a long-running request that should be aborted\n              await new Promise((resolve, reject) => {\n                const timeout = setTimeout(resolve, 5000)\n\n                signal.addEventListener('abort', () => {\n                  clearTimeout(timeout)\n                  reject(new Error('Aborted'))\n                })\n              })\n\n              return { data: 'data!' }\n            },\n            keepUnusedDataFor: 0.01, // Very short timeout (10ms)\n          }),\n        }),\n      })\n\n      const storeRef = setupApiStore(pokemonApi, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      function TestComponent() {\n        const { data, isFetching } = pokemonApi.endpoints.getTest.useQuery(1)\n\n        return (\n          <div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <div data-testid=\"data\">{data || 'no data'}</div>\n          </div>\n        )\n      }\n\n      function App() {\n        const [showComponent, setShowComponent] = useState(true)\n\n        return (\n          <div>\n            {showComponent && <TestComponent />}\n            <button\n              data-testid=\"unmount\"\n              onClick={() => setShowComponent(false)}\n            >\n              Unmount Component\n            </button>\n          </div>\n        )\n      }\n\n      render(<App />, { wrapper: storeRef.wrapper })\n\n      // Wait for the query to start\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n\n      // Verify we have an abort signal\n      expect(abortSignalFromQueryFn).toBeDefined()\n      expect(abortSignalFromQueryFn!.aborted).toBe(false)\n\n      // Unmount the component\n      fireEvent.click(screen.getByTestId('unmount'))\n\n      // Wait for the cache entry to be removed (keepUnusedDataFor: 0.01s = 10ms)\n      await act(async () => {\n        await delay(100)\n      })\n\n      // The abort signal should now be aborted\n      expect(abortSignalFromQueryFn!.aborted).toBe(true)\n    })\n\n    describe('Hook middleware requirements', () => {\n      const consoleErrorSpy = vi\n        .spyOn(console, 'error')\n        .mockImplementation(noop)\n\n      afterEach(() => {\n        consoleErrorSpy.mockClear()\n      })\n\n      afterAll(() => {\n        consoleErrorSpy.mockRestore()\n      })\n\n      test('Throws error if middleware is not added to the store', async () => {\n        const store = configureStore({\n          reducer: {\n            [api.reducerPath]: api.reducer,\n          },\n        })\n\n        const doRender = () => {\n          renderHook(() => api.endpoints.getIncrementedAmount.useQuery(), {\n            wrapper: withProvider(store),\n          })\n        }\n\n        expect(doRender).toThrowError(\n          /Warning: Middleware for RTK-Query API at reducerPath \"api\" has not been added to the store/,\n        )\n      })\n    })\n  })\n\n  describe('useLazyQuery', () => {\n    let data: any\n\n    afterEach(() => {\n      data = undefined\n    })\n\n    let getRenderCount: () => number = () => 0\n    test('useLazyQuery does not automatically fetch when mounted and has undefined data', async () => {\n      function User() {\n        const [fetchUser, { data: hookData, isFetching, isUninitialized }] =\n          api.endpoints.getUser.useLazyQuery()\n        getRenderCount = useRenderCounter()\n\n        data = hookData\n\n        return (\n          <div>\n            <div data-testid=\"isUninitialized\">{String(isUninitialized)}</div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <button data-testid=\"fetchButton\" onClick={() => fetchUser(1)}>\n              fetchUser\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      expect(getRenderCount()).toBe(1)\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isUninitialized').textContent).toBe('true'),\n      )\n      await waitFor(() => expect(data).toBeUndefined())\n\n      fireEvent.click(screen.getByTestId('fetchButton'))\n      expect(getRenderCount()).toBe(2)\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isUninitialized').textContent).toBe('false'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n      expect(getRenderCount()).toBe(3)\n\n      fireEvent.click(screen.getByTestId('fetchButton'))\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n      expect(getRenderCount()).toBe(5)\n    })\n\n    test('useLazyQuery accepts updated subscription options and only dispatches updateSubscriptionOptions when values are updated', async () => {\n      let interval = 1000\n      function User() {\n        const [options, setOptions] = useState<SubscriptionOptions>()\n        const [fetchUser, { data: hookData, isFetching, isUninitialized }] =\n          api.endpoints.getUser.useLazyQuery(options)\n        getRenderCount = useRenderCounter()\n\n        data = hookData\n\n        return (\n          <div>\n            <div data-testid=\"isUninitialized\">{String(isUninitialized)}</div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n\n            <button data-testid=\"fetchButton\" onClick={() => fetchUser(1)}>\n              fetchUser\n            </button>\n            <button\n              data-testid=\"updateOptions\"\n              onClick={() =>\n                setOptions({\n                  pollingInterval: interval,\n                })\n              }\n            >\n              updateOptions\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      expect(getRenderCount()).toBe(1) // hook mount\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isUninitialized').textContent).toBe('true'),\n      )\n      await waitFor(() => expect(data).toBeUndefined())\n\n      fireEvent.click(screen.getByTestId('fetchButton'))\n      expect(getRenderCount()).toBe(2)\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n      expect(getRenderCount()).toBe(3)\n\n      fireEvent.click(screen.getByTestId('updateOptions')) // setState = 1\n      expect(getRenderCount()).toBe(4)\n\n      fireEvent.click(screen.getByTestId('fetchButton')) // perform new request = 2\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n      expect(getRenderCount()).toBe(6)\n\n      interval = 1000\n\n      fireEvent.click(screen.getByTestId('updateOptions')) // setState = 1\n      expect(getRenderCount()).toBe(7)\n\n      fireEvent.click(screen.getByTestId('fetchButton'))\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n      expect(getRenderCount()).toBe(9)\n\n      expect(\n        actions.filter(api.internalActions.updateSubscriptionOptions.match),\n      ).toHaveLength(1)\n    })\n\n    test('useLazyQuery accepts updated args and unsubscribes the original query', async () => {\n      function User() {\n        const [fetchUser, { data: hookData, isFetching, isUninitialized }] =\n          api.endpoints.getUser.useLazyQuery()\n\n        data = hookData\n\n        return (\n          <div>\n            <div data-testid=\"isUninitialized\">{String(isUninitialized)}</div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n\n            <button data-testid=\"fetchUser1\" onClick={() => fetchUser(1)}>\n              fetchUser1\n            </button>\n            <button data-testid=\"fetchUser2\" onClick={() => fetchUser(2)}>\n              fetchUser2\n            </button>\n          </div>\n        )\n      }\n\n      const { unmount } = render(<User />, { wrapper: storeRef.wrapper })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isUninitialized').textContent).toBe('true'),\n      )\n      await waitFor(() => expect(data).toBeUndefined())\n\n      fireEvent.click(screen.getByTestId('fetchUser1'))\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n\n      // Being that there is only the initial query, no unsubscribe should be dispatched\n      expect(\n        actions.filter(api.internalActions.unsubscribeQueryResult.match),\n      ).toHaveLength(0)\n\n      fireEvent.click(screen.getByTestId('fetchUser2'))\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n\n      expect(\n        actions.filter(api.internalActions.unsubscribeQueryResult.match),\n      ).toHaveLength(1)\n\n      fireEvent.click(screen.getByTestId('fetchUser1'))\n\n      expect(\n        actions.filter(api.internalActions.unsubscribeQueryResult.match),\n      ).toHaveLength(2)\n\n      // we always unsubscribe the original promise and create a new one\n      fireEvent.click(screen.getByTestId('fetchUser1'))\n      expect(\n        actions.filter(api.internalActions.unsubscribeQueryResult.match),\n      ).toHaveLength(3)\n\n      unmount()\n\n      // We unsubscribe after the component unmounts\n      expect(\n        actions.filter(api.internalActions.unsubscribeQueryResult.match),\n      ).toHaveLength(4)\n    })\n\n    test('useLazyQuery hook callback returns various properties to handle the result', async () => {\n      const user = userEvent.setup()\n\n      function User() {\n        const [getUser] = api.endpoints.getUser.useLazyQuery()\n        const [{ successMsg, errMsg, isAborted }, setValues] = useState({\n          successMsg: '',\n          errMsg: '',\n          isAborted: false,\n        })\n\n        const handleClick = (abort: boolean) => async () => {\n          const res = getUser(1)\n\n          // abort the query immediately to force an error\n          if (abort) res.abort()\n          res\n            .unwrap()\n            .then((result) => {\n              setValues({\n                successMsg: `Successfully fetched user ${result.name}`,\n                errMsg: '',\n                isAborted: false,\n              })\n            })\n            .catch((err) => {\n              setValues({\n                successMsg: '',\n                errMsg: `An error has occurred fetching userId: ${res.arg}`,\n                isAborted: err.name === 'AbortError',\n              })\n            })\n        }\n\n        return (\n          <div>\n            <button onClick={handleClick(false)}>\n              Fetch User successfully\n            </button>\n            <button onClick={handleClick(true)}>Fetch User and abort</button>\n            <div>{successMsg}</div>\n            <div>{errMsg}</div>\n            <div>{isAborted ? 'Request was aborted' : ''}</div>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      expect(screen.queryByText(/An error has occurred/i)).toBeNull()\n      expect(screen.queryByText(/Successfully fetched user/i)).toBeNull()\n      expect(screen.queryByText('Request was aborted')).toBeNull()\n\n      fireEvent.click(\n        screen.getByRole('button', { name: 'Fetch User and abort' }),\n      )\n      await screen.findByText('An error has occurred fetching userId: 1')\n      expect(screen.queryByText(/Successfully fetched user/i)).toBeNull()\n      screen.getByText('Request was aborted')\n\n      await user.click(\n        screen.getByRole('button', { name: 'Fetch User successfully' }),\n      )\n\n      await screen.findByText('Successfully fetched user Timmy')\n      expect(screen.queryByText(/An error has occurred/i)).toBeNull()\n      expect(screen.queryByText('Request was aborted')).toBeNull()\n    })\n\n    // Based on issue #5079, which I couldn't reproduce but we might as well capture\n    test('useLazyQuery calling abort() multiple times does not throw an error', async () => {\n      const user = userEvent.setup()\n\n      // Create a fresh API instance with fetchBaseQuery and timeout, matching the user's example\n      const timeoutApi = createApi({\n        baseQuery: fetchBaseQuery({\n          baseUrl: 'https://example.com',\n          timeout: 5000,\n        }),\n        endpoints: (builder) => ({\n          getData: builder.query<string, void>({\n            query: () => ({ url: '/data/' }),\n          }),\n        }),\n      })\n\n      const timeoutStoreRef = setupApiStore(timeoutApi, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      // Set up a mock handler for the endpoint\n      server.use(\n        http.get('https://example.com/data/', async () => {\n          await delay(100)\n          return HttpResponse.json('test data')\n        }),\n      )\n\n      function Component() {\n        const [trigger] = timeoutApi.endpoints.getData.useLazyQuery()\n        const abortRef = useRef<(() => void) | undefined>(undefined)\n        const [errorMsg, setErrorMsg] = useState('')\n\n        const handleChange = () => {\n          // Abort any previous request\n          abortRef.current?.()\n\n          // Trigger new request\n          const result = trigger()\n\n          // Store abort function for next call\n          abortRef.current = () => {\n            try {\n              result.abort()\n            } catch (err: any) {\n              setErrorMsg(err.message)\n            }\n          }\n        }\n\n        return (\n          <div>\n            <input data-testid=\"input\" onChange={handleChange} />\n            <div data-testid=\"error\">{errorMsg}</div>\n          </div>\n        )\n      }\n\n      render(<Component />, { wrapper: timeoutStoreRef.wrapper })\n\n      const input = screen.getByTestId('input')\n\n      // Trigger multiple rapid changes that will call abort() multiple times\n      await user.type(input, 'abc')\n\n      // Wait a bit to ensure any errors would have been caught\n      await waitMs(200)\n\n      // Should not have any error messages\n      expect(screen.getByTestId('error').textContent).toBe('')\n    })\n\n    test('unwrapping the useLazyQuery trigger result does not throw on ConditionError and instead returns the aggregate error', async () => {\n      function User() {\n        const [getUser, { data, error }] =\n          api.endpoints.getUserAndForceError.useLazyQuery()\n\n        const [unwrappedError, setUnwrappedError] = useState<any>()\n\n        const handleClick = async () => {\n          const res = getUser(1)\n\n          try {\n            await res.unwrap()\n          } catch (error) {\n            setUnwrappedError(error)\n          }\n        }\n\n        return (\n          <div>\n            <button onClick={handleClick}>Fetch User</button>\n            <div data-testid=\"result\">{JSON.stringify(data)}</div>\n            <div data-testid=\"error\">{JSON.stringify(error)}</div>\n            <div data-testid=\"unwrappedError\">\n              {JSON.stringify(unwrappedError)}\n            </div>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      const fetchButton = screen.getByRole('button', { name: 'Fetch User' })\n      fireEvent.click(fetchButton)\n      fireEvent.click(fetchButton) // This technically dispatches a ConditionError, but we don't want to see that here. We want the real error to resolve.\n\n      await waitFor(() => {\n        const errorResult = screen.getByTestId('error')?.textContent\n        const unwrappedErrorResult =\n          screen.getByTestId('unwrappedError')?.textContent\n\n        if (errorResult && unwrappedErrorResult) {\n          expect(JSON.parse(errorResult)).toMatchObject({\n            status: 500,\n            data: null,\n          })\n          expect(JSON.parse(unwrappedErrorResult)).toMatchObject(\n            JSON.parse(errorResult),\n          )\n        }\n      })\n\n      expect(screen.getByTestId('result').textContent).toBe('')\n    })\n\n    test('useLazyQuery does not throw on ConditionError and instead returns the aggregate result', async () => {\n      function User() {\n        const [getUser, { data, error }] = api.endpoints.getUser.useLazyQuery()\n\n        const [unwrappedResult, setUnwrappedResult] = useState<\n          undefined | { name: string }\n        >()\n\n        const handleClick = async () => {\n          const res = getUser(1)\n\n          const result = await res.unwrap()\n          setUnwrappedResult(result)\n        }\n\n        return (\n          <div>\n            <button onClick={handleClick}>Fetch User</button>\n            <div data-testid=\"result\">{JSON.stringify(data)}</div>\n            <div data-testid=\"error\">{JSON.stringify(error)}</div>\n            <div data-testid=\"unwrappedResult\">\n              {JSON.stringify(unwrappedResult)}\n            </div>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      const fetchButton = screen.getByRole('button', { name: 'Fetch User' })\n      fireEvent.click(fetchButton)\n      fireEvent.click(fetchButton) // This technically dispatches a ConditionError, but we don't want to see that here. We want the real result to resolve and ignore the error.\n\n      await waitFor(() => {\n        const dataResult = screen.getByTestId('error')?.textContent\n        const unwrappedDataResult =\n          screen.getByTestId('unwrappedResult')?.textContent\n\n        if (dataResult && unwrappedDataResult) {\n          expect(JSON.parse(dataResult)).toMatchObject({\n            name: 'Timmy',\n          })\n          expect(JSON.parse(unwrappedDataResult)).toMatchObject(\n            JSON.parse(dataResult),\n          )\n        }\n      })\n\n      expect(screen.getByTestId('error').textContent).toBe('')\n    })\n\n    test('useLazyQuery trigger promise returns the correctly updated data', async () => {\n      const consoleErrorSpy = vi\n        .spyOn(console, 'error')\n        .mockImplementation(noop)\n\n      const user = userEvent.setup()\n\n      const LazyUnwrapUseEffect = () => {\n        const [triggerGetIncrementedAmount, { isFetching, isSuccess, data }] =\n          api.endpoints.getIncrementedAmount.useLazyQuery()\n\n        type AmountData = { amount: number } | undefined\n\n        const [triggerUpdate] = api.endpoints.triggerUpdatedAmount.useMutation()\n\n        const [dataFromQuery, setDataFromQuery] =\n          useState<AmountData>(undefined)\n        const [dataFromTrigger, setDataFromTrigger] =\n          useState<AmountData>(undefined)\n\n        const handleLoad = async () => {\n          try {\n            const res = await triggerGetIncrementedAmount().unwrap()\n\n            setDataFromTrigger(res) // adding client side state here will cause stale data\n          } catch (error) {\n            consoleErrorSpy('Error handling increment trigger', error)\n          }\n        }\n\n        const handleMutate = async () => {\n          try {\n            await triggerUpdate()\n            // Force the lazy trigger to refetch\n            await handleLoad()\n          } catch (error) {\n            consoleErrorSpy('Error handling mutate trigger', error)\n          }\n        }\n\n        useEffect(() => {\n          // Intentionally copy to local state for comparison purposes\n          setDataFromQuery(data)\n        }, [data])\n\n        let content: React.ReactNode | null = null\n\n        if (isFetching) {\n          content = <div className=\"loading\">Loading</div>\n        } else if (isSuccess) {\n          content = (\n            <div className=\"wrapper\">\n              <div>\n                useEffect data: {dataFromQuery?.amount ?? 'No query amount'}\n              </div>\n              <div>\n                Unwrap data: {dataFromTrigger?.amount ?? 'No trigger amount'}\n              </div>\n            </div>\n          )\n        }\n\n        return (\n          <div className=\"outer\">\n            <button onClick={() => handleLoad()}>Load Data</button>\n            <button onClick={() => handleMutate()}>Update Data</button>\n            {content}\n          </div>\n        )\n      }\n\n      render(<LazyUnwrapUseEffect />, { wrapper: storeRef.wrapper })\n\n      // Kick off the initial fetch via lazy query trigger\n      await user.click(screen.getByText('Load Data'))\n\n      // We get back initial data, which should get copied into local state,\n      // and also should come back as valid via the lazy trigger promise\n      await waitFor(() => {\n        expect(screen.getByText('useEffect data: 1')).toBeTruthy()\n        expect(screen.getByText('Unwrap data: 1')).toBeTruthy()\n      })\n\n      // If we mutate and then re-run the lazy trigger afterwards...\n      await user.click(screen.getByText('Update Data'))\n\n      // We should see both sets of data agree (ie, the lazy trigger promise\n      // should not return stale data or be out of sync with the hook).\n      // Prior to PR #4651, this would fail because the trigger never updated properly.\n      await waitFor(() => {\n        expect(screen.getByText('useEffect data: 2')).toBeTruthy()\n        expect(screen.getByText('Unwrap data: 2')).toBeTruthy()\n      })\n\n      consoleErrorSpy.mockRestore()\n    })\n\n    test('`reset` sets state back to original state', async () => {\n      const user = userEvent.setup()\n\n      function User() {\n        const [getUser, { isSuccess, isUninitialized, reset }, _lastInfo] =\n          api.endpoints.getUser.useLazyQuery()\n\n        const handleFetchClick = async () => {\n          await getUser(1).unwrap()\n        }\n\n        return (\n          <div>\n            <span>\n              {isUninitialized\n                ? 'isUninitialized'\n                : isSuccess\n                  ? 'isSuccess'\n                  : 'other'}\n            </span>\n            <button onClick={handleFetchClick}>Fetch User</button>\n            <button onClick={reset}>Reset</button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      await screen.findByText(/isUninitialized/i)\n      expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(0)\n\n      await user.click(screen.getByRole('button', { name: 'Fetch User' }))\n\n      await screen.findByText(/isSuccess/i)\n      expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(1)\n\n      await user.click(\n        screen.getByRole('button', {\n          name: 'Reset',\n        }),\n      )\n\n      await screen.findByText(/isUninitialized/i)\n      expect(countObjectKeys(storeRef.store.getState().api.queries)).toBe(0)\n    })\n  })\n\n  describe('useInfiniteQuery', () => {\n    type Pokemon = {\n      id: string\n      name: string\n    }\n\n    const pokemonApi = createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n      endpoints: (builder) => ({\n        getInfinitePokemon: builder.infiniteQuery<Pokemon, string, number>({\n          infiniteQueryOptions: {\n            initialPageParam: 0,\n            getNextPageParam: (\n              lastPage,\n              allPages,\n              lastPageParam,\n              allPageParams,\n            ) => lastPageParam + 1,\n            getPreviousPageParam: (\n              firstPage,\n              allPages,\n              firstPageParam,\n              allPageParams,\n            ) => {\n              return firstPageParam > 0 ? firstPageParam - 1 : undefined\n            },\n          },\n          query({ pageParam }) {\n            return `https://example.com/listItems?page=${pageParam}`\n          },\n        }),\n      }),\n    })\n\n    const pokemonApiWithRefetch = createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n      endpoints: (builder) => ({\n        getInfinitePokemon: builder.infiniteQuery<Pokemon, string, number>({\n          infiniteQueryOptions: {\n            initialPageParam: 0,\n            getNextPageParam: (\n              lastPage,\n              allPages,\n              lastPageParam,\n              allPageParams,\n            ) => lastPageParam + 1,\n            getPreviousPageParam: (\n              firstPage,\n              allPages,\n              firstPageParam,\n              allPageParams,\n            ) => {\n              return firstPageParam > 0 ? firstPageParam - 1 : undefined\n            },\n          },\n          query({ pageParam }) {\n            return `https://example.com/listItems?page=${pageParam}`\n          },\n        }),\n      }),\n      refetchOnMountOrArgChange: true,\n    })\n\n    function PokemonList({\n      api,\n      arg = 'fire',\n      initialPageParam = 0,\n    }: {\n      api: typeof pokemonApi\n      arg?: string\n      initialPageParam?: number\n    }) {\n      const {\n        data,\n        isFetching,\n        isUninitialized,\n        fetchNextPage,\n        fetchPreviousPage,\n        refetch,\n      } = api.useGetInfinitePokemonInfiniteQuery(arg, {\n        initialPageParam,\n      })\n\n      const handlePreviousPage = async () => {\n        const res = await fetchPreviousPage()\n      }\n\n      const handleNextPage = async () => {\n        const res = await fetchNextPage()\n      }\n\n      const handleRefetch = async () => {\n        const res = await refetch()\n      }\n\n      return (\n        <div>\n          <div data-testid=\"isUninitialized\">{String(isUninitialized)}</div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <div>Type: {arg}</div>\n          <div data-testid=\"data\">\n            {data?.pages.map((page, i: number | null | undefined) => (\n              <div key={i}>{page.name}</div>\n            ))}\n          </div>\n          <button data-testid=\"prevPage\" onClick={() => handlePreviousPage()}>\n            previousPage\n          </button>\n          <button data-testid=\"nextPage\" onClick={() => handleNextPage()}>\n            nextPage\n          </button>\n          <button data-testid=\"refetch\" onClick={() => handleRefetch()}>\n            refetch\n          </button>\n        </div>\n      )\n    }\n\n    beforeEach(() => {\n      server.use(\n        http.get('https://example.com/listItems', ({ request }) => {\n          const url = new URL(request.url)\n          const pageString = url.searchParams.get('page')\n          const pageNum = parseInt(pageString || '0')\n\n          const results: Pokemon = {\n            id: `${pageNum}`,\n            name: `Pokemon ${pageNum}`,\n          }\n\n          return HttpResponse.json(results)\n        }),\n      )\n    })\n\n    test.each([\n      ['no refetch', pokemonApi],\n      ['with refetch', pokemonApiWithRefetch],\n    ])(`useInfiniteQuery %s`, async (_, pokemonApi) => {\n      const storeRef = setupApiStore(pokemonApi, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      const { takeRender, render, getCurrentRender } = createRenderStream({\n        snapshotDOM: true,\n      })\n\n      const checkNumQueries = (count: number) => {\n        const cacheEntries = Object.keys(storeRef.store.getState().api.queries)\n        const queries = cacheEntries.length\n\n        expect(queries).toBe(count)\n      }\n\n      const checkEntryFlags = (\n        arg: string,\n        expectedFlags: Partial<InfiniteQueryResultFlags>,\n      ) => {\n        const selector = pokemonApi.endpoints.getInfinitePokemon.select(arg)\n        const entry = selector(storeRef.store.getState())\n\n        const actualFlags: InfiniteQueryResultFlags = {\n          hasNextPage: false,\n          hasPreviousPage: false,\n          isFetchingNextPage: false,\n          isFetchingPreviousPage: false,\n          isFetchNextPageError: false,\n          isFetchPreviousPageError: false,\n          ...expectedFlags,\n        }\n\n        expect(entry).toMatchObject(actualFlags)\n      }\n\n      const checkPageRows = (\n        withinDOM: () => SyncScreen,\n        type: string,\n        ids: number[],\n      ) => {\n        expect(withinDOM().getByText(`Type: ${type}`)).toBeTruthy()\n        for (const id of ids) {\n          expect(withinDOM().getByText(`Pokemon ${id}`)).toBeTruthy()\n        }\n      }\n\n      async function waitForFetch(handleExtraMiddleRender = false) {\n        {\n          const { withinDOM } = await takeRender()\n          expect(withinDOM().getByTestId('isFetching').textContent).toBe('true')\n        }\n\n        // We seem to do an extra render when fetching an uninitialized entry\n        if (handleExtraMiddleRender) {\n          {\n            const { withinDOM } = await takeRender()\n            expect(withinDOM().getByTestId('isFetching').textContent).toBe(\n              'true',\n            )\n          }\n        }\n\n        {\n          // Second fetch complete\n          const { withinDOM } = await takeRender()\n          expect(withinDOM().getByTestId('isFetching').textContent).toBe(\n            'false',\n          )\n        }\n      }\n\n      const utils = render(<PokemonList api={pokemonApi} />, {\n        wrapper: storeRef.wrapper,\n      })\n      checkNumQueries(1)\n      checkEntryFlags('fire', {})\n      await waitForFetch(true)\n      checkNumQueries(1)\n      checkPageRows(getCurrentRender().withinDOM, 'fire', [0])\n      checkEntryFlags('fire', {\n        hasNextPage: true,\n      })\n\n      fireEvent.click(screen.getByTestId('nextPage'), {})\n      checkEntryFlags('fire', {\n        hasNextPage: true,\n        isFetchingNextPage: true,\n      })\n      await waitForFetch()\n      checkPageRows(getCurrentRender().withinDOM, 'fire', [0, 1])\n      checkEntryFlags('fire', {\n        hasNextPage: true,\n      })\n\n      fireEvent.click(screen.getByTestId('nextPage'))\n      await waitForFetch()\n      checkPageRows(getCurrentRender().withinDOM, 'fire', [0, 1, 2])\n\n      utils.rerender(\n        <PokemonList api={pokemonApi} arg=\"water\" initialPageParam={3} />,\n      )\n      checkEntryFlags('water', {})\n      await waitForFetch(true)\n      checkNumQueries(2)\n      checkPageRows(getCurrentRender().withinDOM, 'water', [3])\n      checkEntryFlags('water', {\n        hasNextPage: true,\n        hasPreviousPage: true,\n      })\n\n      fireEvent.click(screen.getByTestId('nextPage'))\n      checkEntryFlags('water', {\n        hasNextPage: true,\n        hasPreviousPage: true,\n        isFetchingNextPage: true,\n      })\n      await waitForFetch()\n      checkPageRows(getCurrentRender().withinDOM, 'water', [3, 4])\n      checkEntryFlags('water', {\n        hasNextPage: true,\n        hasPreviousPage: true,\n      })\n\n      fireEvent.click(screen.getByTestId('prevPage'))\n      checkEntryFlags('water', {\n        hasNextPage: true,\n        hasPreviousPage: true,\n        isFetchingPreviousPage: true,\n      })\n      await waitForFetch()\n      checkPageRows(getCurrentRender().withinDOM, 'water', [2, 3, 4])\n      checkEntryFlags('water', {\n        hasNextPage: true,\n        hasPreviousPage: true,\n      })\n\n      fireEvent.click(screen.getByTestId('refetch'))\n      checkEntryFlags('water', {\n        hasNextPage: true,\n        hasPreviousPage: true,\n      })\n      await waitForFetch()\n      checkPageRows(getCurrentRender().withinDOM, 'water', [2, 3, 4])\n      checkEntryFlags('water', {\n        hasNextPage: true,\n        hasPreviousPage: true,\n      })\n    })\n\n    test('Object page params does not keep forcing refetching', async () => {\n      type Project = {\n        id: number\n        createdAt: string\n      }\n\n      type ProjectsResponse = {\n        projects: Project[]\n        numFound: number\n        serverTime: string\n      }\n\n      interface ProjectsInitialPageParam {\n        offset: number\n        limit: number\n      }\n\n      const apiWithInfiniteScroll = createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }),\n        endpoints: (builder) => ({\n          projectsLimitOffset: builder.infiniteQuery<\n            ProjectsResponse,\n            void,\n            ProjectsInitialPageParam\n          >({\n            infiniteQueryOptions: {\n              initialPageParam: {\n                offset: 0,\n                limit: 20,\n              },\n              getNextPageParam: (\n                lastPage,\n                allPages,\n                lastPageParam,\n                allPageParams,\n              ) => {\n                const nextOffset = lastPageParam.offset + lastPageParam.limit\n                const remainingItems = lastPage?.numFound - nextOffset\n\n                if (remainingItems <= 0) {\n                  return undefined\n                }\n\n                return {\n                  ...lastPageParam,\n                  offset: nextOffset,\n                }\n              },\n              getPreviousPageParam: (\n                firstPage,\n                allPages,\n                firstPageParam,\n                allPageParams,\n              ) => {\n                const prevOffset = firstPageParam.offset - firstPageParam.limit\n                if (prevOffset < 0) return undefined\n\n                return {\n                  ...firstPageParam,\n                  offset: firstPageParam.offset - firstPageParam.limit,\n                }\n              },\n            },\n            query: ({ pageParam }) => {\n              const { offset, limit } = pageParam\n              return {\n                url: `https://example.com/api/projectsLimitOffset?offset=${offset}&limit=${limit}`,\n                method: 'GET',\n              }\n            },\n          }),\n        }),\n      })\n\n      const projects = Array.from({ length: 50 }, (_, i) => {\n        return {\n          id: i,\n          createdAt: Date.now() + i * 1000,\n        }\n      })\n\n      let numRequests = 0\n\n      server.use(\n        http.get(\n          'https://example.com/api/projectsLimitOffset',\n          async ({ request }) => {\n            const url = new URL(request.url)\n            const limit = parseInt(url.searchParams.get('limit') ?? '5', 10)\n            let offset = parseInt(url.searchParams.get('offset') ?? '0', 10)\n\n            numRequests++\n\n            if (isNaN(offset) || offset < 0) {\n              offset = 0\n            }\n            if (isNaN(limit) || limit <= 0) {\n              return HttpResponse.json(\n                {\n                  message:\n                    \"Invalid 'limit' parameter. It must be a positive integer.\",\n                } as any,\n                { status: 400 },\n              )\n            }\n\n            const result = projects.slice(offset, offset + limit)\n\n            await delay(10)\n            return HttpResponse.json({\n              projects: result,\n              serverTime: Date.now(),\n              numFound: projects.length,\n            })\n          },\n        ),\n      )\n\n      function LimitOffsetExample() {\n        const {\n          data,\n          hasPreviousPage,\n          hasNextPage,\n          error,\n          isFetching,\n          isLoading,\n          isError,\n          fetchNextPage,\n          fetchPreviousPage,\n          isFetchingNextPage,\n          isFetchingPreviousPage,\n          status,\n        } = apiWithInfiniteScroll.useProjectsLimitOffsetInfiniteQuery(\n          undefined,\n          {\n            initialPageParam: {\n              offset: 10,\n              limit: 10,\n            },\n          },\n        )\n\n        const [counter, setCounter] = useState(0)\n\n        const combinedData = useMemo(() => {\n          return data?.pages?.map((item) => item?.projects)?.flat()\n        }, [data])\n\n        return (\n          <div>\n            <h2>Limit and Offset Infinite Scroll</h2>\n            <button onClick={() => setCounter((c) => c + 1)}>Increment</button>\n            <div>Counter: {counter}</div>\n            {isLoading ? (\n              <p>Loading...</p>\n            ) : isError ? (\n              <span>Error: {error.message}</span>\n            ) : null}\n\n            <>\n              <div>\n                <button\n                  onClick={() => fetchPreviousPage()}\n                  disabled={!hasPreviousPage || isFetchingPreviousPage}\n                >\n                  {isFetchingPreviousPage\n                    ? 'Loading more...'\n                    : hasPreviousPage\n                      ? 'Load Older'\n                      : 'Nothing more to load'}\n                </button>\n              </div>\n              <div data-testid=\"projects\">\n                {combinedData?.map((project, index, arr) => {\n                  return (\n                    <div key={project.id}>\n                      <div data-testid=\"project\">\n                        <div>{`Project ${project.id} (created at: ${project.createdAt})`}</div>\n                      </div>\n                    </div>\n                  )\n                })}\n              </div>\n              <div>\n                <button\n                  onClick={() => fetchNextPage()}\n                  disabled={!hasNextPage || isFetchingNextPage}\n                >\n                  {isFetchingNextPage\n                    ? 'Loading more...'\n                    : hasNextPage\n                      ? 'Load Newer'\n                      : 'Nothing more to load'}\n                </button>\n              </div>\n              <div>\n                {isFetching && !isFetchingPreviousPage && !isFetchingNextPage\n                  ? 'Background Updating...'\n                  : null}\n              </div>\n            </>\n          </div>\n        )\n      }\n\n      const storeRef = setupApiStore(\n        apiWithInfiniteScroll,\n        { ...actionsReducer },\n        {\n          withoutTestLifecycles: true,\n        },\n      )\n\n      const { takeRender, render, totalRenderCount } = createRenderStream({\n        snapshotDOM: true,\n      })\n\n      render(<LimitOffsetExample />, {\n        wrapper: storeRef.wrapper,\n      })\n\n      {\n        const { withinDOM } = await takeRender()\n        withinDOM().getByText('Counter: 0')\n        withinDOM().getByText('Loading...')\n      }\n\n      {\n        const { withinDOM } = await takeRender()\n        withinDOM().getByText('Counter: 0')\n        withinDOM().getByText('Loading...')\n      }\n\n      {\n        const { withinDOM } = await takeRender()\n        withinDOM().getByText('Counter: 0')\n\n        expect(withinDOM().getAllByTestId('project').length).toBe(10)\n        expect(withinDOM().queryByTestId('Loading...')).toBeNull()\n      }\n\n      expect(totalRenderCount()).toBe(3)\n      expect(numRequests).toBe(1)\n    })\n\n    test.each([\n      ['skip token', true],\n      ['skip option', false],\n    ])(\n      'useInfiniteQuery hook does not fetch when skipped via %s',\n      async (_, useSkipToken) => {\n        function Pokemon() {\n          const [value, setValue] = useState(0)\n\n          const shouldFetch = value > 0\n\n          const arg = shouldFetch || !useSkipToken ? 'fire' : skipToken\n          const skip = useSkipToken ? undefined : shouldFetch ? undefined : true\n\n          const { isFetching } = pokemonApi.useGetInfinitePokemonInfiniteQuery(\n            arg,\n            {\n              skip,\n            },\n          )\n          getRenderCount = useRenderCounter()\n\n          return (\n            <div>\n              <div data-testid=\"isFetching\">{String(isFetching)}</div>\n              <button onClick={() => setValue((val) => val + 1)}>\n                Increment value\n              </button>\n            </div>\n          )\n        }\n\n        render(<Pokemon />, { wrapper: storeRef.wrapper })\n        expect(getRenderCount()).toBe(1)\n\n        await waitFor(() =>\n          expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n        )\n        fireEvent.click(screen.getByText('Increment value'))\n        await waitFor(() =>\n          expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n        )\n        expect(getRenderCount()).toBe(2)\n      },\n    )\n\n    test('useInfiniteQuery hook option refetchCachedPages: false only refetches first page', async () => {\n      const storeRef = setupApiStore(pokemonApi, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      function PokemonList() {\n        const { data, fetchNextPage, refetch } =\n          pokemonApi.useGetInfinitePokemonInfiniteQuery('fire', {\n            refetchCachedPages: false,\n          })\n\n        return (\n          <div>\n            <div data-testid=\"data\">\n              {data?.pages.map((page, i) => (\n                <div key={i} data-testid={`page-${i}`}>\n                  {page.name}\n                </div>\n              ))}\n            </div>\n            <button data-testid=\"nextPage\" onClick={() => fetchNextPage()}>\n              Next Page\n            </button>\n            <button data-testid=\"refetch\" onClick={() => refetch()}>\n              Refetch\n            </button>\n          </div>\n        )\n      }\n\n      render(<PokemonList />, { wrapper: storeRef.wrapper })\n\n      // Wait for initial page to load\n      await waitFor(() => {\n        expect(screen.getByTestId('page-0').textContent).toBe('Pokemon 0')\n      })\n\n      // Fetch second page\n      fireEvent.click(screen.getByTestId('nextPage'))\n      await waitFor(() => {\n        expect(screen.getByTestId('page-1').textContent).toBe('Pokemon 1')\n      })\n\n      // Fetch third page\n      fireEvent.click(screen.getByTestId('nextPage'))\n      await waitFor(() => {\n        expect(screen.getByTestId('page-2').textContent).toBe('Pokemon 2')\n      })\n\n      // Now we have 3 pages. Refetch with refetchCachedPages: false should only refetch page 0\n      fireEvent.click(screen.getByTestId('refetch'))\n\n      await waitFor(\n        () => {\n          // Should only have 1 page\n          expect(screen.queryByTestId('page-0')).toBeTruthy()\n          expect(screen.queryByTestId('page-1')).toBeNull()\n          expect(screen.queryByTestId('page-2')).toBeNull()\n        },\n        { timeout: 1000 },\n      )\n\n      // Verify we only have 1 page (not refetched all)\n      const pages = screen.getAllByTestId(/^page-/)\n      expect(pages).toHaveLength(1)\n    })\n\n    test('useInfiniteQuery refetch() method option refetchCachedPages: false only refetches first page', async () => {\n      const storeRef = setupApiStore(pokemonApi, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      function PokemonList() {\n        const { data, fetchNextPage, refetch } =\n          pokemonApi.useGetInfinitePokemonInfiniteQuery('fire')\n\n        return (\n          <div>\n            <div data-testid=\"data\">\n              {data?.pages.map((page, i) => (\n                <div key={i} data-testid={`page-${i}`}>\n                  {page.name}\n                </div>\n              ))}\n            </div>\n            <button data-testid=\"nextPage\" onClick={() => fetchNextPage()}>\n              Next Page\n            </button>\n            <button\n              data-testid=\"refetch\"\n              onClick={() => refetch({ refetchCachedPages: false })}\n            >\n              Refetch\n            </button>\n          </div>\n        )\n      }\n\n      render(<PokemonList />, { wrapper: storeRef.wrapper })\n\n      // Wait for initial page to load\n      await waitFor(() => {\n        expect(screen.getByTestId('page-0').textContent).toBe('Pokemon 0')\n      })\n\n      // Fetch second page\n      fireEvent.click(screen.getByTestId('nextPage'))\n      await waitFor(() => {\n        expect(screen.getByTestId('page-1').textContent).toBe('Pokemon 1')\n      })\n\n      // Fetch third page\n      fireEvent.click(screen.getByTestId('nextPage'))\n      await waitFor(() => {\n        expect(screen.getByTestId('page-2').textContent).toBe('Pokemon 2')\n      })\n\n      // Now we have 3 pages. Refetch with refetchCachedPages: false should only refetch page 0\n      fireEvent.click(screen.getByTestId('refetch'))\n\n      await waitFor(() => {\n        // Should only have 1 page\n        expect(screen.queryByTestId('page-0')).toBeTruthy()\n        expect(screen.queryByTestId('page-1')).toBeNull()\n        expect(screen.queryByTestId('page-2')).toBeNull()\n      })\n\n      // Verify we only have 1 page (not refetched all)\n      const pages = screen.getAllByTestId(/^page-/)\n      expect(pages).toHaveLength(1)\n    })\n  })\n\n  describe('useMutation', () => {\n    test('useMutation hook sets and unsets the isLoading flag when running', async () => {\n      function User() {\n        const [updateUser, { isLoading }] =\n          api.endpoints.updateUser.useMutation()\n\n        return (\n          <div>\n            <div data-testid=\"isLoading\">{String(isLoading)}</div>\n            <button onClick={() => updateUser({ name: 'Banana' })}>\n              Update User\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n      )\n      fireEvent.click(screen.getByText('Update User'))\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n      )\n    })\n\n    test('useMutation hook sets data to the resolved response on success', async () => {\n      const result = { name: 'Banana' }\n\n      function User() {\n        const [updateUser, { data }] = api.endpoints.updateUser.useMutation()\n\n        return (\n          <div>\n            <div data-testid=\"result\">{JSON.stringify(data)}</div>\n            <button onClick={() => updateUser({ name: 'Banana' })}>\n              Update User\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      fireEvent.click(screen.getByText('Update User'))\n      await waitFor(() =>\n        expect(screen.getByTestId('result').textContent).toBe(\n          JSON.stringify(result),\n        ),\n      )\n    })\n\n    test('useMutation hook callback returns various properties to handle the result', async () => {\n      const user = userEvent.setup()\n\n      function User() {\n        const [updateUser] = api.endpoints.updateUser.useMutation()\n        const [successMsg, setSuccessMsg] = useState('')\n        const [errMsg, setErrMsg] = useState('')\n        const [isAborted, setIsAborted] = useState(false)\n\n        const handleClick = async () => {\n          const res = updateUser({ name: 'Banana' })\n\n          // abort the mutation immediately to force an error\n          res.abort()\n          res\n            .unwrap()\n            .then((result) => {\n              setSuccessMsg(`Successfully updated user ${result.name}`)\n            })\n            .catch((err) => {\n              setErrMsg(\n                `An error has occurred updating user ${res.arg.originalArgs.name}`,\n              )\n              if (err.name === 'AbortError') {\n                setIsAborted(true)\n              }\n            })\n        }\n\n        return (\n          <div>\n            <button onClick={handleClick}>Update User and abort</button>\n            <div>{successMsg}</div>\n            <div>{errMsg}</div>\n            <div>{isAborted ? 'Request was aborted' : ''}</div>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      expect(screen.queryByText(/An error has occurred/i)).toBeNull()\n      expect(screen.queryByText(/Successfully updated user/i)).toBeNull()\n      expect(screen.queryByText('Request was aborted')).toBeNull()\n\n      await user.click(\n        screen.getByRole('button', { name: 'Update User and abort' }),\n      )\n      await screen.findByText('An error has occurred updating user Banana')\n      expect(screen.queryByText(/Successfully updated user/i)).toBeNull()\n      screen.getByText('Request was aborted')\n    })\n\n    test('useMutation return value contains originalArgs', async () => {\n      const { result } = renderHook(\n        () => api.endpoints.updateUser.useMutation(),\n        {\n          wrapper: storeRef.wrapper,\n        },\n      )\n      const arg = { name: 'Foo' }\n\n      const firstRenderResult = result.current\n      expect(firstRenderResult[1].originalArgs).toBe(undefined)\n      await act(async () => {\n        await firstRenderResult[0](arg)\n      })\n      const secondRenderResult = result.current\n      expect(firstRenderResult[1].originalArgs).toBe(undefined)\n      expect(secondRenderResult[1].originalArgs).toBe(arg)\n    })\n\n    test('`reset` sets state back to original state', async () => {\n      const user = userEvent.setup()\n\n      function User() {\n        const [updateUser, result] = api.endpoints.updateUser.useMutation()\n        return (\n          <>\n            <span>\n              {result.isUninitialized\n                ? 'isUninitialized'\n                : result.isSuccess\n                  ? 'isSuccess'\n                  : 'other'}\n            </span>\n            <span>{result.originalArgs?.name}</span>\n            <button onClick={() => updateUser({ name: 'Yay' })}>trigger</button>\n            <button onClick={result.reset}>reset</button>\n          </>\n        )\n      }\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      await screen.findByText(/isUninitialized/i)\n      expect(screen.queryByText('Yay')).toBeNull()\n      expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(0)\n\n      await user.click(screen.getByRole('button', { name: 'trigger' }))\n\n      await screen.findByText(/isSuccess/i)\n      expect(screen.queryByText('Yay')).not.toBeNull()\n      expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(1)\n\n      await user.click(screen.getByRole('button', { name: 'reset' }))\n\n      await screen.findByText(/isUninitialized/i)\n      expect(screen.queryByText('Yay')).toBeNull()\n      expect(countObjectKeys(storeRef.store.getState().api.mutations)).toBe(0)\n    })\n  })\n\n  describe('usePrefetch', () => {\n    test('usePrefetch respects force arg', async () => {\n      const user = userEvent.setup()\n\n      const { usePrefetch } = api\n      const USER_ID = 4\n      function User() {\n        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)\n        const prefetchUser = usePrefetch('getUser', { force: true })\n\n        return (\n          <div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <button\n              onMouseEnter={() => prefetchUser(USER_ID, { force: true })}\n              data-testid=\"highPriority\"\n            >\n              High priority action intent\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      // Resolve initial query\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n\n      await user.hover(screen.getByTestId('highPriority'))\n\n      expect(\n        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),\n      ).toEqual({\n        data: { name: 'Timmy' },\n        endpointName: 'getUser',\n        error: undefined,\n        fulfilledTimeStamp: expect.any(Number),\n        isError: false,\n        isLoading: true,\n        isSuccess: false,\n        isUninitialized: false,\n        originalArgs: USER_ID,\n        requestId: expect.any(String),\n        startedTimeStamp: expect.any(Number),\n        status: QueryStatus.pending,\n      })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n\n      expect(\n        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),\n      ).toEqual({\n        data: { name: 'Timmy' },\n        endpointName: 'getUser',\n        fulfilledTimeStamp: expect.any(Number),\n        isError: false,\n        isLoading: false,\n        isSuccess: true,\n        isUninitialized: false,\n        originalArgs: USER_ID,\n        requestId: expect.any(String),\n        startedTimeStamp: expect.any(Number),\n        status: QueryStatus.fulfilled,\n      })\n    })\n\n    test('usePrefetch does not make an additional request if already in the cache and force=false', async () => {\n      const user = userEvent.setup()\n\n      const { usePrefetch } = api\n      const USER_ID = 2\n\n      function User() {\n        // Load the initial query\n        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)\n        const prefetchUser = usePrefetch('getUser', { force: false })\n\n        return (\n          <div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <button\n              onMouseEnter={() => prefetchUser(USER_ID)}\n              data-testid=\"lowPriority\"\n            >\n              Low priority user action intent\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      // Let the initial query resolve\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n      // Try to prefetch what we just loaded\n      await user.hover(screen.getByTestId('lowPriority'))\n\n      expect(\n        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),\n      ).toEqual({\n        data: { name: 'Timmy' },\n        endpointName: 'getUser',\n        fulfilledTimeStamp: expect.any(Number),\n        isError: false,\n        isLoading: false,\n        isSuccess: true,\n        isUninitialized: false,\n        originalArgs: USER_ID,\n        requestId: expect.any(String),\n        startedTimeStamp: expect.any(Number),\n        status: QueryStatus.fulfilled,\n      })\n\n      await waitMs()\n\n      expect(\n        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),\n      ).toEqual({\n        data: { name: 'Timmy' },\n        endpointName: 'getUser',\n        fulfilledTimeStamp: expect.any(Number),\n        isError: false,\n        isLoading: false,\n        isSuccess: true,\n        isUninitialized: false,\n        originalArgs: USER_ID,\n        requestId: expect.any(String),\n        startedTimeStamp: expect.any(Number),\n        status: QueryStatus.fulfilled,\n      })\n    })\n\n    test('usePrefetch respects ifOlderThan when it evaluates to true', async () => {\n      const user = userEvent.setup()\n\n      const { usePrefetch } = api\n      const USER_ID = 47\n\n      function User() {\n        // Load the initial query\n        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)\n        const prefetchUser = usePrefetch('getUser', { ifOlderThan: 0.2 })\n\n        return (\n          <div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <button\n              onMouseEnter={() => prefetchUser(USER_ID)}\n              data-testid=\"lowPriority\"\n            >\n              Low priority user action intent\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n\n      // Wait 400ms, making it respect ifOlderThan\n      await waitMs(400)\n\n      // This should run the query being that we're past the threshold\n      await user.hover(screen.getByTestId('lowPriority'))\n\n      expect(\n        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),\n      ).toEqual({\n        data: { name: 'Timmy' },\n        endpointName: 'getUser',\n        fulfilledTimeStamp: expect.any(Number),\n        isError: false,\n        isLoading: true,\n        isSuccess: false,\n        isUninitialized: false,\n        originalArgs: USER_ID,\n        requestId: expect.any(String),\n        startedTimeStamp: expect.any(Number),\n        status: QueryStatus.pending,\n      })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n\n      expect(\n        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),\n      ).toEqual({\n        data: { name: 'Timmy' },\n        endpointName: 'getUser',\n        fulfilledTimeStamp: expect.any(Number),\n        isError: false,\n        isLoading: false,\n        isSuccess: true,\n        isUninitialized: false,\n        originalArgs: USER_ID,\n        requestId: expect.any(String),\n        startedTimeStamp: expect.any(Number),\n        status: QueryStatus.fulfilled,\n      })\n    })\n\n    test('usePrefetch returns the last success result when ifOlderThan evaluates to false', async () => {\n      const user = userEvent.setup()\n\n      const { usePrefetch } = api\n      const USER_ID = 2\n\n      function User() {\n        // Load the initial query\n        const { isFetching } = api.endpoints.getUser.useQuery(USER_ID)\n        const prefetchUser = usePrefetch('getUser', { ifOlderThan: 10 })\n\n        return (\n          <div>\n            <div data-testid=\"isFetching\">{String(isFetching)}</div>\n            <button\n              onMouseEnter={() => prefetchUser(USER_ID)}\n              data-testid=\"lowPriority\"\n            >\n              Low priority user action intent\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      await waitFor(() =>\n        expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n      )\n      await waitMs()\n\n      // Get a snapshot of the last result\n      const latestQueryData = api.endpoints.getUser.select(USER_ID)(\n        storeRef.store.getState() as any,\n      )\n\n      await user.hover(screen.getByTestId('lowPriority'))\n\n      //  Serve up the result from the cache being that the condition wasn't met\n      expect(\n        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState() as any),\n      ).toEqual(latestQueryData)\n    })\n\n    test('usePrefetch executes a query even if conditions fail when the cache is empty', async () => {\n      const user = userEvent.setup()\n\n      const { usePrefetch } = api\n      const USER_ID = 2\n\n      function User() {\n        const prefetchUser = usePrefetch('getUser', { ifOlderThan: 10 })\n\n        return (\n          <div>\n            <button\n              onMouseEnter={() => prefetchUser(USER_ID)}\n              data-testid=\"lowPriority\"\n            >\n              Low priority user action intent\n            </button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n\n      await user.hover(screen.getByTestId('lowPriority'))\n\n      expect(\n        api.endpoints.getUser.select(USER_ID)(storeRef.store.getState()),\n      ).toEqual({\n        endpointName: 'getUser',\n        isError: false,\n        isLoading: true,\n        isSuccess: false,\n        isUninitialized: false,\n        originalArgs: USER_ID,\n        requestId: expect.any(String),\n        startedTimeStamp: expect.any(Number),\n        status: 'pending',\n      })\n    })\n\n    it('should create subscription when hook mounts after prefetch', async () => {\n      const api = createApi({\n        baseQuery: async () => ({ data: 'test data' }),\n        endpoints: (build) => ({\n          getTest: build.query<string, void>({\n            query: () => '',\n          }),\n        }),\n      })\n      const storeRef = setupApiStore(api, undefined, { withoutListeners: true })\n\n      // 1. Prefetch data (no subscription)\n      await storeRef.store.dispatch(api.util.prefetch('getTest', undefined))\n\n      // Verify data is cached\n      await waitFor(() => {\n        let state = storeRef.store.getState()\n        expect(state.api.queries['getTest(undefined)']?.data).toBe('test data')\n      })\n\n      // Verify no subscription exists\n      const subscriptions = storeRef.store.dispatch(\n        api.internalActions.internal_getRTKQSubscriptions(),\n      ) as any\n      expect(subscriptions.getSubscriptionCount('getTest(undefined)')).toBe(0)\n\n      // 2. Mount component with useQuery hook\n      function TestComponent() {\n        const result = api.endpoints.getTest.useQuery()\n        return <div>{result.data}</div>\n      }\n\n      const { unmount } = render(<TestComponent />, {\n        wrapper: storeRef.wrapper,\n      })\n\n      // Wait for hook to initialize\n      await waitFor(() => {\n        // EXPECTED: Subscription should be created\n        expect(subscriptions.getSubscriptionCount('getTest(undefined)')).toBe(1)\n      })\n\n      // 3. Verify data is still available\n      let state = storeRef.store.getState()\n      expect(state.api.queries['getTest(undefined)']?.data).toBe('test data')\n\n      // 4. Unmount and verify subscription is removed\n      unmount()\n\n      await waitFor(() => {\n        expect(subscriptions.getSubscriptionCount('getTest(undefined)')).toBe(0)\n      })\n    })\n  })\n\n  describe('useQuery and useMutation invalidation behavior', () => {\n    const api = createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n      tagTypes: ['User'],\n      endpoints: (build) => ({\n        checkSession: build.query<any, void>({\n          query: () => '/me',\n          providesTags: ['User'],\n        }),\n        login: build.mutation<any, any>({\n          query: () => ({ url: '/login', method: 'POST' }),\n          invalidatesTags: ['User'],\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, { ...actionsReducer })\n    test('initially failed useQueries that provide an tag will refetch after a mutation invalidates it', async () => {\n      const checkSessionData = { name: 'matt' }\n      server.use(\n        http.get(\n          'https://example.com/me',\n          () => {\n            return HttpResponse.json(null, { status: 500 })\n          },\n          { once: true },\n        ),\n        http.get('https://example.com/me', () => {\n          return HttpResponse.json(checkSessionData)\n        }),\n        http.post('https://example.com/login', () => {\n          return HttpResponse.json(null, { status: 200 })\n        }),\n      )\n      let data, isLoading, isError\n      function User() {\n        ;({ data, isError, isLoading } = api.endpoints.checkSession.useQuery())\n        const [login, { isLoading: loginLoading }] =\n          api.endpoints.login.useMutation()\n\n        return (\n          <div>\n            <div data-testid=\"isLoading\">{String(isLoading)}</div>\n            <div data-testid=\"isError\">{String(isError)}</div>\n            <div data-testid=\"user\">{JSON.stringify(data)}</div>\n            <div data-testid=\"loginLoading\">{String(loginLoading)}</div>\n            <button onClick={() => login(null)}>Login</button>\n          </div>\n        )\n      }\n\n      render(<User />, { wrapper: storeRef.wrapper })\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('isError').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('user').textContent).toBe(''),\n      )\n\n      fireEvent.click(screen.getByRole('button', { name: /Login/i }))\n\n      await waitFor(() =>\n        expect(screen.getByTestId('loginLoading').textContent).toBe('true'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('loginLoading').textContent).toBe('false'),\n      )\n      // login mutation will cause the original errored out query to refire, clearing the error and setting the user\n      await waitFor(() =>\n        expect(screen.getByTestId('isError').textContent).toBe('false'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('user').textContent).toBe(\n          JSON.stringify(checkSessionData),\n        ),\n      )\n\n      const { checkSession, login } = api.endpoints\n      expect(storeRef.store.getState().actions).toMatchSequence(\n        api.internalActions.middlewareRegistered.match,\n        checkSession.matchPending,\n        checkSession.matchRejected,\n        login.matchPending,\n        login.matchFulfilled,\n        checkSession.matchPending,\n        checkSession.matchFulfilled,\n      )\n    })\n  })\n})\n\ndescribe('hooks with createApi defaults set', () => {\n  const defaultApi = createApi({\n    baseQuery: async (arg: any) => {\n      await waitMs()\n      if ('amount' in arg?.body) {\n        amount += 1\n      }\n      return {\n        data: arg?.body\n          ? { ...arg.body, ...(amount ? { amount } : {}) }\n          : undefined,\n      }\n    },\n    endpoints: (build) => ({\n      getIncrementedAmount: build.query<any, void>({\n        query: () => ({\n          url: '',\n          body: {\n            amount,\n          },\n        }),\n      }),\n    }),\n    refetchOnMountOrArgChange: true,\n  })\n\n  const storeRef = setupApiStore(defaultApi)\n  test('useQuery hook respects refetchOnMountOrArgChange: true when set in createApi options', async () => {\n    let data, isLoading, isFetching\n\n    function User() {\n      ;({ data, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery())\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    const { unmount } = render(<User />, { wrapper: storeRef.wrapper })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n\n    unmount()\n\n    function OtherUser() {\n      ;({ data, isFetching } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {\n          refetchOnMountOrArgChange: true,\n        }))\n      return (\n        <div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    render(<OtherUser />, { wrapper: storeRef.wrapper })\n    // Let's make sure we actually fetch, and we increment\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n    )\n\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('2'),\n    )\n  })\n\n  test('useQuery hook overrides default refetchOnMountOrArgChange: false that was set by createApi', async () => {\n    let data, isLoading, isFetching\n\n    function User() {\n      ;({ data, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery())\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    let { unmount } = render(<User />, { wrapper: storeRef.wrapper })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n\n    unmount()\n\n    function OtherUser() {\n      ;({ data, isFetching } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {\n          refetchOnMountOrArgChange: false,\n        }))\n      return (\n        <div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    render(<OtherUser />, { wrapper: storeRef.wrapper })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n  })\n\n  describe('selectFromResult (query) behaviors', () => {\n    let startingId = 3\n    const initialPosts = [\n      { id: 1, name: 'A sample post', fetched_at: new Date().toUTCString() },\n      {\n        id: 2,\n        name: 'A post about rtk-query',\n        fetched_at: new Date().toUTCString(),\n      },\n    ]\n    let posts = [] as typeof initialPosts\n\n    beforeEach(() => {\n      startingId = 3\n      posts = [...initialPosts]\n\n      const handlers = [\n        http.get('https://example.com/posts', () => {\n          return HttpResponse.json(posts)\n        }),\n        http.put<{ id: string }, Partial<Post>>(\n          'https://example.com/post/:id',\n          async ({ request, params }) => {\n            const body = await request.json()\n            const id = Number(params.id)\n            const idx = posts.findIndex((post) => post.id === id)\n\n            const newPosts = posts.map((post, index) =>\n              index !== idx\n                ? post\n                : {\n                    ...body,\n                    id,\n                    name: body?.name || post.name,\n                    fetched_at: new Date().toUTCString(),\n                  },\n            )\n            posts = [...newPosts]\n\n            return HttpResponse.json(posts)\n          },\n        ),\n        http.post<any, Omit<Post, 'id'>>(\n          'https://example.com/post',\n          async ({ request }) => {\n            const body = await request.json()\n            const post = body\n            startingId += 1\n            posts.concat({\n              ...post,\n              fetched_at: new Date().toISOString(),\n              id: startingId,\n            })\n            return HttpResponse.json(posts)\n          },\n        ),\n      ]\n\n      server.use(...handlers)\n    })\n\n    interface Post {\n      id: number\n      name: string\n      fetched_at: string\n    }\n\n    type PostsResponse = Post[]\n\n    const api = createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com/' }),\n      tagTypes: ['Posts'],\n      endpoints: (build) => ({\n        getPosts: build.query<PostsResponse, void>({\n          query: () => ({ url: 'posts' }),\n          providesTags: (result) =>\n            result ? result.map(({ id }) => ({ type: 'Posts', id })) : [],\n        }),\n        updatePost: build.mutation<Post, Partial<Post>>({\n          query: ({ id, ...body }) => ({\n            url: `post/${id}`,\n            method: 'PUT',\n            body,\n          }),\n          invalidatesTags: (result, error, { id }) => [{ type: 'Posts', id }],\n        }),\n        addPost: build.mutation<Post, Partial<Post>>({\n          query: (body) => ({\n            url: `post`,\n            method: 'POST',\n            body,\n          }),\n          invalidatesTags: ['Posts'],\n        }),\n      }),\n    })\n\n    const counterSlice = createSlice({\n      name: 'counter',\n      initialState: { count: 0 },\n      reducers: {\n        increment(state) {\n          state.count++\n        },\n      },\n    })\n\n    const storeRef = setupApiStore(api, {\n      counter: counterSlice.reducer,\n    })\n\n    test('useQueryState serves a deeply memoized value and does not rerender unnecessarily', async () => {\n      function Posts() {\n        const { data: posts } = api.endpoints.getPosts.useQuery()\n        const [addPost] = api.endpoints.addPost.useMutation()\n        return (\n          <div>\n            <button\n              data-testid=\"addPost\"\n              onClick={() => addPost({ name: `some text ${posts?.length}` })}\n            >\n              Add random post\n            </button>\n          </div>\n        )\n      }\n\n      function SelectedPost() {\n        const { post } = api.endpoints.getPosts.useQueryState(undefined, {\n          selectFromResult: ({ data }) => ({\n            post: data?.find((post) => post.id === 1),\n          }),\n        })\n        getRenderCount = useRenderCounter()\n\n        /**\n         * Notes on the renderCount behavior\n         *\n         * We initialize at 0, and the first render will bump that 1 while post is `undefined`.\n         * Once the request resolves, it will be at 2. What we're looking for is to make sure that\n         * any requests that don't directly change the value of the selected item will have no impact\n         * on rendering.\n         */\n\n        return <div />\n      }\n\n      render(\n        <div>\n          <Posts />\n          <SelectedPost />\n        </div>,\n        { wrapper: storeRef.wrapper },\n      )\n\n      expect(getRenderCount()).toBe(1)\n\n      const addBtn = screen.getByTestId('addPost')\n\n      await waitFor(() => expect(getRenderCount()).toBe(2))\n\n      fireEvent.click(addBtn)\n      await waitFor(() => expect(getRenderCount()).toBe(2))\n      // We fire off a few requests that would typically cause a rerender as JSON.parse() on a request would always be a new object.\n      fireEvent.click(addBtn)\n      fireEvent.click(addBtn)\n      await waitFor(() => expect(getRenderCount()).toBe(2))\n      // Being that it didn't rerender, we can be assured that the behavior is correct\n    })\n\n    /**\n     * This test shows that even though a user can select a specific post, the fetching/loading flags\n     * will still cause rerenders for the query. This should show that if you're using selectFromResult,\n     * the 'performance' value comes with selecting _only_ the data.\n     */\n    test('useQuery with selectFromResult with all flags destructured rerenders like the default useQuery behavior', async () => {\n      function Posts() {\n        const { data: posts } = api.endpoints.getPosts.useQuery()\n        const [addPost] = api.endpoints.addPost.useMutation()\n        getRenderCount = useRenderCounter()\n        return (\n          <div>\n            <button\n              data-testid=\"addPost\"\n              onClick={() =>\n                addPost({\n                  name: `some text ${posts?.length}`,\n                  fetched_at: new Date().toISOString(),\n                })\n              }\n            >\n              Add random post\n            </button>\n          </div>\n        )\n      }\n\n      function SelectedPost() {\n        getRenderCount = useRenderCounter()\n\n        const { post } = api.endpoints.getPosts.useQuery(undefined, {\n          selectFromResult: ({\n            data,\n            isUninitialized,\n            isLoading,\n            isFetching,\n            isSuccess,\n            isError,\n          }) => ({\n            post: data?.find((post) => post.id === 1),\n            isUninitialized,\n            isLoading,\n            isFetching,\n            isSuccess,\n            isError,\n          }),\n        })\n\n        return <div />\n      }\n\n      render(\n        <div>\n          <Posts />\n          <SelectedPost />\n        </div>,\n        { wrapper: storeRef.wrapper },\n      )\n      expect(getRenderCount()).toBe(2)\n\n      const addBtn = screen.getByTestId('addPost')\n\n      await waitFor(() => expect(getRenderCount()).toBe(3))\n\n      fireEvent.click(addBtn)\n      await waitFor(() => expect(getRenderCount()).toBe(5))\n      fireEvent.click(addBtn)\n      fireEvent.click(addBtn)\n      await waitFor(() => expect(getRenderCount()).toBe(7))\n    })\n\n    test('useQuery with selectFromResult option serves a deeply memoized value and does not rerender unnecessarily', async () => {\n      function Posts() {\n        const { data: posts } = api.endpoints.getPosts.useQuery()\n        const [addPost] = api.endpoints.addPost.useMutation()\n        return (\n          <div>\n            <button\n              data-testid=\"addPost\"\n              onClick={() =>\n                addPost({\n                  name: `some text ${posts?.length}`,\n                  fetched_at: new Date().toISOString(),\n                })\n              }\n            >\n              Add random post\n            </button>\n          </div>\n        )\n      }\n\n      function SelectedPost() {\n        getRenderCount = useRenderCounter()\n        const { post } = api.endpoints.getPosts.useQuery(undefined, {\n          selectFromResult: ({ data }) => ({\n            post: data?.find((post) => post.id === 1),\n          }),\n        })\n\n        return <div />\n      }\n\n      render(\n        <div>\n          <Posts />\n          <SelectedPost />\n        </div>,\n        { wrapper: storeRef.wrapper },\n      )\n      expect(getRenderCount()).toBe(1)\n\n      const addBtn = screen.getByTestId('addPost')\n\n      await waitFor(() => expect(getRenderCount()).toBe(2))\n\n      fireEvent.click(addBtn)\n      await waitFor(() => expect(getRenderCount()).toBe(2))\n      fireEvent.click(addBtn)\n      fireEvent.click(addBtn)\n      await waitFor(() => expect(getRenderCount()).toBe(2))\n    })\n\n    test('useQuery with selectFromResult option serves a deeply memoized value, then ONLY updates when the underlying data changes', async () => {\n      let expectablePost: Post | undefined\n      function Posts() {\n        const { data: posts } = api.endpoints.getPosts.useQuery()\n        const [addPost] = api.endpoints.addPost.useMutation()\n        const [updatePost] = api.endpoints.updatePost.useMutation()\n\n        return (\n          <div>\n            <button\n              data-testid=\"addPost\"\n              onClick={() =>\n                addPost({\n                  name: `some text ${posts?.length}`,\n                  fetched_at: new Date().toISOString(),\n                })\n              }\n            >\n              Add random post\n            </button>\n            <button\n              data-testid=\"updatePost\"\n              onClick={() => updatePost({ id: 1, name: 'supercoooll!' })}\n            >\n              Update post\n            </button>\n          </div>\n        )\n      }\n\n      function SelectedPost() {\n        const { post } = api.endpoints.getPosts.useQuery(undefined, {\n          selectFromResult: ({ data }) => ({\n            post: data?.find((post) => post.id === 1),\n          }),\n        })\n        getRenderCount = useRenderCounter()\n\n        useEffect(() => {\n          expectablePost = post\n        }, [post])\n\n        return (\n          <div>\n            <div data-testid=\"postName\">{post?.name}</div>\n          </div>\n        )\n      }\n\n      render(\n        <div>\n          <Posts />\n          <SelectedPost />\n        </div>,\n        { wrapper: storeRef.wrapper },\n      )\n      expect(getRenderCount()).toBe(1)\n\n      const addBtn = screen.getByTestId('addPost')\n      const updateBtn = screen.getByTestId('updatePost')\n\n      fireEvent.click(addBtn)\n      await waitFor(() => expect(getRenderCount()).toBe(2))\n      fireEvent.click(addBtn)\n      fireEvent.click(addBtn)\n      await waitFor(() => expect(getRenderCount()).toBe(2))\n\n      fireEvent.click(updateBtn)\n      await waitFor(() => expect(getRenderCount()).toBe(3))\n      expect(expectablePost?.name).toBe('supercoooll!')\n\n      fireEvent.click(addBtn)\n      await waitFor(() => expect(getRenderCount()).toBe(3))\n    })\n\n    test('useQuery with selectFromResult option does not update when unrelated data in the store changes', async () => {\n      function Posts() {\n        const { posts } = api.endpoints.getPosts.useQuery(undefined, {\n          selectFromResult: ({ data }) => ({\n            // Intentionally use an unstable reference to force a rerender\n            posts: data?.filter((post) => post.name.includes('post')),\n          }),\n        })\n\n        getRenderCount = useRenderCounter()\n\n        return (\n          <div>\n            {posts?.map((post) => <div key={post.id}>{post.name}</div>)}\n          </div>\n        )\n      }\n\n      function CounterButton() {\n        return (\n          <div\n            data-testid=\"incrementButton\"\n            onClick={() =>\n              storeRef.store.dispatch(counterSlice.actions.increment())\n            }\n          >\n            Increment Count\n          </div>\n        )\n      }\n\n      render(\n        <div>\n          <Posts />\n          <CounterButton />\n        </div>,\n        { wrapper: storeRef.wrapper },\n      )\n\n      await waitFor(() => expect(getRenderCount()).toBe(2))\n\n      const incrementBtn = screen.getByTestId('incrementButton')\n      fireEvent.click(incrementBtn)\n      expect(getRenderCount()).toBe(2)\n    })\n\n    test('useQuery with selectFromResult option has a type error if the result is not an object', async () => {\n      function SelectedPost() {\n        const res2 = api.endpoints.getPosts.useQuery(undefined, {\n          // selectFromResult must always return an object\n          selectFromResult: ({ data }) => ({ size: data?.length ?? 0 }),\n        })\n\n        return (\n          <div>\n            <div data-testid=\"size2\">{res2.size}</div>\n          </div>\n        )\n      }\n\n      render(\n        <div>\n          <SelectedPost />\n        </div>,\n        { wrapper: storeRef.wrapper },\n      )\n\n      expect(screen.getByTestId('size2').textContent).toBe('0')\n    })\n  })\n\n  describe('selectFromResult (mutation) behavior', () => {\n    const api = createApi({\n      baseQuery: async (arg: any) => {\n        await waitMs()\n        if ('amount' in arg?.body) {\n          amount += 1\n        }\n        return {\n          data: arg?.body\n            ? { ...arg.body, ...(amount ? { amount } : {}) }\n            : undefined,\n        }\n      },\n      endpoints: (build) => ({\n        increment: build.mutation<{ amount: number }, number>({\n          query: (amount) => ({\n            url: '',\n            method: 'POST',\n            body: {\n              amount,\n            },\n          }),\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, {\n      ...actionsReducer,\n    })\n\n    it('causes no more than one rerender when using selectFromResult with an empty object', async () => {\n      function Counter() {\n        const [increment] = api.endpoints.increment.useMutation({\n          selectFromResult: () => ({}),\n        })\n        getRenderCount = useRenderCounter()\n\n        return (\n          <div>\n            <button\n              data-testid=\"incrementButton\"\n              onClick={() => increment(1)}\n            ></button>\n          </div>\n        )\n      }\n\n      render(<Counter />, { wrapper: storeRef.wrapper })\n\n      expect(getRenderCount()).toBe(1)\n\n      fireEvent.click(screen.getByTestId('incrementButton'))\n      await waitMs(200) // give our baseQuery a chance to return\n      expect(getRenderCount()).toBe(2)\n\n      fireEvent.click(screen.getByTestId('incrementButton'))\n      await waitMs(200)\n      expect(getRenderCount()).toBe(3)\n\n      const { increment } = api.endpoints\n\n      expect(storeRef.store.getState().actions).toMatchSequence(\n        api.internalActions.middlewareRegistered.match,\n        increment.matchPending,\n        increment.matchFulfilled,\n        increment.matchPending,\n        api.internalActions.removeMutationResult.match,\n        increment.matchFulfilled,\n      )\n    })\n\n    it('causes rerenders when only selected data changes', async () => {\n      function Counter() {\n        const [increment, { data }] = api.endpoints.increment.useMutation({\n          selectFromResult: ({ data }) => ({ data }),\n        })\n        getRenderCount = useRenderCounter()\n\n        return (\n          <div>\n            <button\n              data-testid=\"incrementButton\"\n              onClick={() => increment(1)}\n            ></button>\n            <div data-testid=\"data\">{JSON.stringify(data)}</div>\n          </div>\n        )\n      }\n\n      render(<Counter />, { wrapper: storeRef.wrapper })\n\n      expect(getRenderCount()).toBe(1)\n\n      fireEvent.click(screen.getByTestId('incrementButton'))\n      await waitFor(() =>\n        expect(screen.getByTestId('data').textContent).toBe(\n          JSON.stringify({ amount: 1 }),\n        ),\n      )\n      expect(getRenderCount()).toBe(3)\n\n      fireEvent.click(screen.getByTestId('incrementButton'))\n      await waitFor(() =>\n        expect(screen.getByTestId('data').textContent).toBe(\n          JSON.stringify({ amount: 2 }),\n        ),\n      )\n      expect(getRenderCount()).toBe(5)\n    })\n\n    it('causes the expected # of rerenders when NOT using selectFromResult', async () => {\n      function Counter() {\n        const [increment, data] = api.endpoints.increment.useMutation()\n        getRenderCount = useRenderCounter()\n\n        return (\n          <div>\n            <button\n              data-testid=\"incrementButton\"\n              onClick={() => increment(1)}\n            ></button>\n            <div data-testid=\"status\">{String(data.status)}</div>\n          </div>\n        )\n      }\n\n      render(<Counter />, { wrapper: storeRef.wrapper })\n\n      expect(getRenderCount()).toBe(1) // mount, uninitialized status in substate\n\n      fireEvent.click(screen.getByTestId('incrementButton'))\n\n      expect(getRenderCount()).toBe(2) // will be pending, isLoading: true,\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('pending'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('fulfilled'),\n      )\n      expect(getRenderCount()).toBe(3)\n\n      fireEvent.click(screen.getByTestId('incrementButton'))\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('pending'),\n      )\n      await waitFor(() =>\n        expect(screen.getByTestId('status').textContent).toBe('fulfilled'),\n      )\n      expect(getRenderCount()).toBe(5)\n    })\n\n    it('useMutation with selectFromResult option has a type error if the result is not an object', async () => {\n      function Counter() {\n        const [increment] = api.endpoints.increment.useMutation({\n          // selectFromResult must always return an object\n          // @ts-expect-error\n          selectFromResult: () => 42,\n        })\n\n        return (\n          <div>\n            <button\n              data-testid=\"incrementButton\"\n              onClick={() => increment(1)}\n            ></button>\n          </div>\n        )\n      }\n\n      render(<Counter />, { wrapper: storeRef.wrapper })\n    })\n  })\n})\n\ndescribe('skip behavior', () => {\n  const uninitialized = {\n    status: QueryStatus.uninitialized,\n    refetch: expect.any(Function),\n    data: undefined,\n    isError: false,\n    isFetching: false,\n    isLoading: false,\n    isSuccess: false,\n    isUninitialized: true,\n  }\n\n  test('normal skip', async () => {\n    const { result, rerender } = renderHook(\n      ([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) =>\n        api.endpoints.getUser.useQuery(arg, options),\n      {\n        wrapper: storeRef.wrapper,\n        initialProps: [1, { skip: true }],\n      },\n    )\n\n    expect(result.current).toEqual(uninitialized)\n    await waitMs(1)\n    expect(getSubscriptionCount('getUser(1)')).toBe(0)\n\n    rerender([1])\n\n    await act(async () => {\n      await waitForFakeTimer(150)\n    })\n\n    expect(result.current).toMatchObject({ status: QueryStatus.fulfilled })\n    await waitMs(1)\n    expect(getSubscriptionCount('getUser(1)')).toBe(1)\n\n    rerender([1, { skip: true }])\n\n    expect(result.current).toEqual({\n      ...uninitialized,\n      isSuccess: true,\n      currentData: undefined,\n      data: { name: 'Timmy' },\n    })\n    await waitMs(1)\n    expect(getSubscriptionCount('getUser(1)')).toBe(0)\n  })\n\n  test('skipToken', async () => {\n    const { result, rerender } = renderHook(\n      ([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) =>\n        api.endpoints.getUser.useQuery(arg, options),\n      {\n        wrapper: storeRef.wrapper,\n        initialProps: [skipToken],\n      },\n    )\n\n    expect(result.current).toEqual(uninitialized)\n    await waitMs(1)\n\n    expect(getSubscriptionCount('getUser(1)')).toBe(0)\n    // also no subscription on `getUser(skipToken)` or similar:\n    expect(getSubscriptions().size).toBe(0)\n\n    rerender([1])\n\n    await act(async () => {\n      await waitForFakeTimer(150)\n    })\n\n    expect(result.current).toMatchObject({ status: QueryStatus.fulfilled })\n    await waitMs(1)\n    expect(getSubscriptionCount('getUser(1)')).toBe(1)\n    expect(getSubscriptions().size).toBe(1)\n\n    rerender([skipToken])\n\n    expect(result.current).toEqual({\n      ...uninitialized,\n      isSuccess: true,\n      currentData: undefined,\n      data: { name: 'Timmy' },\n    })\n    await waitMs(1)\n    expect(getSubscriptionCount('getUser(1)')).toBe(0)\n  })\n\n  test('skipToken does not break serializeQueryArgs', async () => {\n    const { result, rerender } = renderHook(\n      ([arg, options]: Parameters<\n        typeof api.endpoints.queryWithDeepArg.useQuery\n      >) => api.endpoints.queryWithDeepArg.useQuery(arg, options),\n      {\n        wrapper: storeRef.wrapper,\n        initialProps: [skipToken],\n      },\n    )\n\n    expect(result.current).toEqual(uninitialized)\n    await waitMs(1)\n\n    expect(getSubscriptionCount('nestedValue')).toBe(0)\n    // also no subscription on `getUser(skipToken)` or similar:\n    expect(getSubscriptions().size).toBe(0)\n\n    rerender([{ param: { nested: 'nestedValue' } }])\n\n    await act(async () => {\n      await waitForFakeTimer(150)\n    })\n\n    expect(result.current).toMatchObject({ status: QueryStatus.fulfilled })\n    await waitMs(1)\n\n    expect(getSubscriptionCount('nestedValue')).toBe(1)\n    expect(getSubscriptions().size).toBe(1)\n\n    rerender([skipToken])\n\n    expect(result.current).toEqual({\n      ...uninitialized,\n      isSuccess: true,\n      currentData: undefined,\n      data: {},\n    })\n    await waitMs(1)\n    expect(getSubscriptionCount('nestedValue')).toBe(0)\n  })\n\n  test('skipping a previously fetched query retains the existing value as `data`, but clears `currentData`', async () => {\n    const { result, rerender } = renderHook(\n      ([arg, options]: Parameters<typeof api.endpoints.getUser.useQuery>) =>\n        api.endpoints.getUser.useQuery(arg, options),\n      {\n        wrapper: storeRef.wrapper,\n        initialProps: [1],\n      },\n    )\n\n    await act(async () => {\n      await waitForFakeTimer(150)\n    })\n\n    // Normal fulfilled result, with both `data` and `currentData`\n    expect(result.current).toMatchObject({\n      status: QueryStatus.fulfilled,\n      isSuccess: true,\n      data: { name: 'Timmy' },\n      currentData: { name: 'Timmy' },\n    })\n\n    rerender([1, { skip: true }])\n\n    // After skipping, the query is \"uninitialized\", but still retains the last fetched `data`\n    // even though it's skipped. `currentData` is undefined, since that matches the current arg.\n    expect(result.current).toMatchObject({\n      status: QueryStatus.uninitialized,\n      isSuccess: true,\n      data: { name: 'Timmy' },\n      currentData: undefined,\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/buildInitiate.test.tsx",
    "content": "import { setupApiStore } from '@internal/tests/utils/helpers'\nimport { delay } from '@internal/utils'\nimport { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query'\nimport type { SubscriptionSelectors } from '../core/buildMiddleware/types'\n\nlet calls = 0\nconst api = createApi({\n  baseQuery: fakeBaseQuery(),\n  endpoints: (build) => ({\n    increment: build.query<number, void>({\n      async queryFn() {\n        const data = calls++\n        await Promise.resolve()\n        return { data }\n      },\n    }),\n    incrementKeep0: build.query<number, void>({\n      async queryFn() {\n        const data = calls++\n        await delay(10)\n        return { data }\n      },\n      keepUnusedDataFor: 0,\n    }),\n    failing: build.query<void, void>({\n      async queryFn() {\n        await Promise.resolve()\n        return { error: { status: 500, data: 'error' } }\n      },\n    }),\n  }),\n})\n\nconst storeRef = setupApiStore(api)\n\nlet getSubscriptions: SubscriptionSelectors['getSubscriptions']\nlet isRequestSubscribed: SubscriptionSelectors['isRequestSubscribed']\n\nbeforeEach(() => {\n  ;({ getSubscriptions, isRequestSubscribed } = storeRef.store.dispatch(\n    api.internalActions.internal_getRTKQSubscriptions(),\n  ) as unknown as SubscriptionSelectors)\n})\n\ntest('multiple synchonrous initiate calls with pre-existing cache entry', async () => {\n  const { store, api } = storeRef\n  // seed the store\n  const firstValue = await store.dispatch(api.endpoints.increment.initiate())\n\n  expect(firstValue).toMatchObject({ data: 0, status: 'fulfilled' })\n\n  // dispatch another increment\n  const secondValuePromise = store.dispatch(api.endpoints.increment.initiate())\n  // and one with a forced refresh\n  const thirdValuePromise = store.dispatch(\n    api.endpoints.increment.initiate(undefined, { forceRefetch: true }),\n  )\n  // and another increment\n  const fourthValuePromise = store.dispatch(api.endpoints.increment.initiate())\n\n  const secondValue = await secondValuePromise\n  const thirdValue = await thirdValuePromise\n  const fourthValue = await fourthValuePromise\n\n  expect(secondValue).toMatchObject({\n    data: firstValue.data,\n    status: 'fulfilled',\n    requestId: firstValue.requestId,\n  })\n\n  expect(thirdValue).toMatchObject({ data: 1, status: 'fulfilled' })\n  expect(thirdValue.requestId).not.toBe(firstValue.requestId)\n  expect(fourthValue).toMatchObject({\n    data: thirdValue.data,\n    status: 'fulfilled',\n    requestId: thirdValue.requestId,\n  })\n})\n\ndescribe('calling initiate without a cache entry, with subscribe: false still returns correct values', () => {\n  test('successful query', async () => {\n    const { store, api } = storeRef\n    calls = 0\n    const promise = store.dispatch(\n      api.endpoints.increment.initiate(undefined, { subscribe: false }),\n    )\n    expect(isRequestSubscribed('increment(undefined)', promise.requestId)).toBe(\n      false,\n    )\n\n    await expect(promise).resolves.toMatchObject({\n      data: 0,\n      status: 'fulfilled',\n    })\n  })\n\n  test('successful query with keepUnusedDataFor: 0', async () => {\n    const { store, api } = storeRef\n    calls = 0\n    const promise = store.dispatch(\n      api.endpoints.incrementKeep0.initiate(undefined, { subscribe: false }),\n    )\n    expect(isRequestSubscribed('increment(undefined)', promise.requestId)).toBe(\n      false,\n    )\n\n    await expect(promise.unwrap()).resolves.toBe(0)\n  })\n\n  test('rejected query', async () => {\n    const { store, api } = storeRef\n    calls = 0\n    const promise = store.dispatch(\n      api.endpoints.failing.initiate(undefined, { subscribe: false }),\n    )\n    expect(isRequestSubscribed('failing(undefined)', promise.requestId)).toBe(\n      false,\n    )\n\n    await expect(promise).resolves.toMatchObject({\n      status: 'rejected',\n    })\n  })\n})\n\ndescribe('calling initiate should have resulting queryCacheKey match baseQuery queryCacheKey', () => {\n  const baseQuery = vi.fn(() => ({ data: 'success' }))\n  function getNewApi() {\n    return createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        query: build.query<void, { arg1: string; arg2: string }>({\n          query: (args) => `queryUrl/${args.arg1}/${args.arg2}`,\n        }),\n        mutation: build.mutation<void, { arg1: string; arg2: string }>({\n          query: () => 'mutationUrl',\n        }),\n      }),\n    })\n  }\n  let api = getNewApi()\n  beforeEach(() => {\n    baseQuery.mockClear()\n    api = getNewApi()\n  })\n\n  test('should be a string and matching on queries', () => {\n    const { store: storeApi } = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n    const promise = storeApi.dispatch(\n      api.endpoints.query.initiate({ arg2: 'secondArg', arg1: 'firstArg' }),\n    )\n    expect(baseQuery).toHaveBeenCalledWith(\n      expect.any(String),\n      expect.objectContaining({\n        queryCacheKey: promise.queryCacheKey,\n      }),\n      undefined,\n    )\n  })\n\n  test('should be undefined and matching on mutations', () => {\n    const { store: storeApi } = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n    storeApi.dispatch(\n      api.endpoints.mutation.initiate({ arg2: 'secondArg', arg1: 'firstArg' }),\n    )\n    expect(baseQuery).toHaveBeenCalledWith(\n      expect.any(String),\n      expect.objectContaining({\n        queryCacheKey: undefined,\n      }),\n      undefined,\n    )\n  })\n})\n\ndescribe('getRunningQueryThunk with multiple stores', () => {\n  test('should isolate running queries between different store instances using the same API', async () => {\n    // Create a shared API instance\n    const sharedApi = createApi({\n      baseQuery: fakeBaseQuery(),\n      endpoints: (build) => ({\n        testQuery: build.query<string, string>({\n          async queryFn(arg) {\n            // Add delay to ensure queries are running when we check\n            await new Promise((resolve) => setTimeout(resolve, 50))\n            return { data: `result-${arg}` }\n          },\n        }),\n      }),\n    })\n\n    // Create two separate stores using the same API instance\n    const store1 = setupApiStore(sharedApi, undefined, {\n      withoutTestLifecycles: true,\n    }).store\n    const store2 = setupApiStore(sharedApi, undefined, {\n      withoutTestLifecycles: true,\n    }).store\n\n    // Start queries on both stores\n    const query1Promise = store1.dispatch(\n      sharedApi.endpoints.testQuery.initiate('arg1'),\n    )\n    const query2Promise = store2.dispatch(\n      sharedApi.endpoints.testQuery.initiate('arg2'),\n    )\n\n    // Verify that getRunningQueryThunk returns the correct query for each store\n    const runningQuery1 = store1.dispatch(\n      sharedApi.util.getRunningQueryThunk('testQuery', 'arg1'),\n    )\n    const runningQuery2 = store2.dispatch(\n      sharedApi.util.getRunningQueryThunk('testQuery', 'arg2'),\n    )\n\n    // Each store should only see its own running query\n    expect(runningQuery1).toBeDefined()\n    expect(runningQuery2).toBeDefined()\n    expect(runningQuery1?.requestId).toBe(query1Promise.requestId)\n    expect(runningQuery2?.requestId).toBe(query2Promise.requestId)\n\n    // Cross-store queries should not be visible\n    const crossQuery1 = store1.dispatch(\n      sharedApi.util.getRunningQueryThunk('testQuery', 'arg2'),\n    )\n    const crossQuery2 = store2.dispatch(\n      sharedApi.util.getRunningQueryThunk('testQuery', 'arg1'),\n    )\n\n    expect(crossQuery1).toBeUndefined()\n    expect(crossQuery2).toBeUndefined()\n\n    // Wait for queries to complete\n    await Promise.all([query1Promise, query2Promise])\n\n    // After completion, getRunningQueryThunk should return undefined for both stores\n    const completedQuery1 = store1.dispatch(\n      sharedApi.util.getRunningQueryThunk('testQuery', 'arg1'),\n    )\n    const completedQuery2 = store2.dispatch(\n      sharedApi.util.getRunningQueryThunk('testQuery', 'arg2'),\n    )\n\n    expect(completedQuery1).toBeUndefined()\n    expect(completedQuery2).toBeUndefined()\n  })\n\n  test('should handle same query args on different stores independently', async () => {\n    // Create a shared API instance\n    const sharedApi = createApi({\n      baseQuery: fakeBaseQuery(),\n      endpoints: (build) => ({\n        sameArgQuery: build.query<string, string>({\n          async queryFn(arg) {\n            await new Promise((resolve) => setTimeout(resolve, 50))\n            return { data: `result-${arg}-${Math.random()}` }\n          },\n        }),\n      }),\n    })\n\n    // Create two separate stores\n    const store1 = setupApiStore(sharedApi, undefined, {\n      withoutTestLifecycles: true,\n    }).store\n    const store2 = setupApiStore(sharedApi, undefined, {\n      withoutTestLifecycles: true,\n    }).store\n\n    // Start the same query on both stores\n    const sameArg = 'shared-arg'\n    const query1Promise = store1.dispatch(\n      sharedApi.endpoints.sameArgQuery.initiate(sameArg),\n    )\n    const query2Promise = store2.dispatch(\n      sharedApi.endpoints.sameArgQuery.initiate(sameArg),\n    )\n\n    // Both stores should see their own running query with the same cache key\n    const runningQuery1 = store1.dispatch(\n      sharedApi.util.getRunningQueryThunk('sameArgQuery', sameArg),\n    )\n    const runningQuery2 = store2.dispatch(\n      sharedApi.util.getRunningQueryThunk('sameArgQuery', sameArg),\n    )\n\n    expect(runningQuery1).toBeDefined()\n    expect(runningQuery2).toBeDefined()\n    expect(runningQuery1?.requestId).toBe(query1Promise.requestId)\n    expect(runningQuery2?.requestId).toBe(query2Promise.requestId)\n\n    // The request IDs should be different even though the cache key is the same\n    expect(runningQuery1?.requestId).not.toBe(runningQuery2?.requestId)\n\n    // But the cache keys should be the same\n    expect(runningQuery1?.queryCacheKey).toBe(runningQuery2?.queryCacheKey)\n\n    // Wait for completion\n    await Promise.all([query1Promise, query2Promise])\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/buildMiddleware.test-d.ts",
    "content": "import { createApi } from '@reduxjs/toolkit/query'\n\nconst baseQuery = (args?: any) => ({ data: args })\n\nconst api = createApi({\n  baseQuery,\n  tagTypes: ['Banana', 'Bread'],\n  endpoints: (build) => ({\n    getBanana: build.query<unknown, number>({\n      query(id) {\n        return { url: `banana/${id}` }\n      },\n      providesTags: ['Banana'],\n    }),\n    getBananas: build.query<unknown, void>({\n      query() {\n        return { url: 'bananas' }\n      },\n      providesTags: ['Banana'],\n    }),\n    getBread: build.query<unknown, number>({\n      query(id) {\n        return { url: `bread/${id}` }\n      },\n      providesTags: ['Bread'],\n    }),\n  }),\n})\n\ndescribe('type tests', () => {\n  it('should allow for an array of string TagTypes', () => {\n    api.util.invalidateTags(['Banana', 'Bread'])\n  })\n\n  it('should allow for an array of full TagTypes descriptions', () => {\n    api.util.invalidateTags([{ type: 'Banana' }, { type: 'Bread', id: 1 }])\n  })\n\n  it('should allow for a mix of full descriptions as well as plain strings', () => {\n    api.util.invalidateTags(['Banana', { type: 'Bread', id: 1 }])\n  })\n\n  it('should error when using non-existing TagTypes', () => {\n    // @ts-expect-error\n    api.util.invalidateTags(['Missing Tag'])\n  })\n\n  it('should error when using non-existing TagTypes in the full format', () => {\n    // @ts-expect-error\n    api.util.invalidateTags([{ type: 'Missing' }])\n  })\n\n  it('should allow pre-fetching for an endpoint that takes an arg', () => {\n    api.util.prefetch('getBanana', 5, { force: true })\n    api.util.prefetch('getBanana', 5, { force: false })\n    api.util.prefetch('getBanana', 5, { ifOlderThan: false })\n    api.util.prefetch('getBanana', 5, { ifOlderThan: 30 })\n    api.util.prefetch('getBanana', 5, {})\n  })\n\n  it('should error when pre-fetching with the incorrect arg type', () => {\n    // @ts-expect-error arg should be number, not string\n    api.util.prefetch('getBanana', '5', { force: true })\n  })\n\n  it('should allow pre-fetching for an endpoint with a void arg', () => {\n    api.util.prefetch('getBananas', undefined, { force: true })\n    api.util.prefetch('getBananas', undefined, { force: false })\n    api.util.prefetch('getBananas', undefined, { ifOlderThan: false })\n    api.util.prefetch('getBananas', undefined, { ifOlderThan: 30 })\n    api.util.prefetch('getBananas', undefined, {})\n  })\n\n  it('should error when pre-fetching with a defined arg when expecting void', () => {\n    // @ts-expect-error arg should be void, not number\n    api.util.prefetch('getBananas', 5, { force: true })\n  })\n\n  it('should error when pre-fetching for an incorrect endpoint name', () => {\n    // @ts-expect-error endpoint name does not exist\n    api.util.prefetch('getPomegranates', undefined, { force: true })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/buildMiddleware.test.tsx",
    "content": "import { createApi } from '@reduxjs/toolkit/query'\nimport { delay } from 'msw'\nimport { actionsReducer, setupApiStore } from '../../tests/utils/helpers'\nimport { vi } from 'vitest'\n\nconst baseQuery = (args?: any) => ({ data: args })\nconst api = createApi({\n  baseQuery,\n  tagTypes: ['Banana', 'Bread'],\n  endpoints: (build) => ({\n    getBanana: build.query<unknown, number>({\n      query(id) {\n        return { url: `banana/${id}` }\n      },\n      providesTags: ['Banana'],\n    }),\n    getBananas: build.query<unknown, void>({\n      query() {\n        return { url: 'bananas' }\n      },\n      providesTags: ['Banana'],\n    }),\n    getBread: build.query<unknown, number>({\n      query(id) {\n        return { url: `bread/${id}` }\n      },\n      providesTags: ['Bread'],\n    }),\n    invalidateFruit: build.mutation({\n      query: (fruit?: 'Banana' | 'Bread' | null) => ({\n        url: `invalidate/fruit/${fruit || ''}`,\n      }),\n      invalidatesTags(result, error, arg) {\n        return [arg]\n      },\n    }),\n  }),\n})\nconst { getBanana, getBread, invalidateFruit } = api.endpoints\n\nconst storeRef = setupApiStore(api, {\n  ...actionsReducer,\n})\n\nit('invalidates the specified tags', async () => {\n  await storeRef.store.dispatch(getBanana.initiate(1))\n  expect(storeRef.store.getState().actions).toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    getBanana.matchPending,\n    getBanana.matchFulfilled,\n  )\n\n  await storeRef.store.dispatch(api.util.invalidateTags(['Banana', 'Bread']))\n\n  // Slight pause to let the middleware run and such\n  await delay(20)\n\n  const firstSequence = [\n    api.internalActions.middlewareRegistered.match,\n    getBanana.matchPending,\n    getBanana.matchFulfilled,\n    api.util.invalidateTags.match,\n    getBanana.matchPending,\n    getBanana.matchFulfilled,\n  ]\n  expect(storeRef.store.getState().actions).toMatchSequence(...firstSequence)\n\n  await storeRef.store.dispatch(getBread.initiate(1))\n  await storeRef.store.dispatch(api.util.invalidateTags([{ type: 'Bread' }]))\n\n  await delay(20)\n\n  expect(storeRef.store.getState().actions).toMatchSequence(\n    ...firstSequence,\n    getBread.matchPending,\n    getBread.matchFulfilled,\n    api.util.invalidateTags.match,\n    getBread.matchPending,\n    getBread.matchFulfilled,\n  )\n})\n\nit('invalidates tags correctly when null or undefined are provided as tags', async () => {\n  await storeRef.store.dispatch(getBanana.initiate(1))\n  await storeRef.store.dispatch(\n    api.util.invalidateTags([undefined, null, 'Banana']),\n  )\n\n  // Slight pause to let the middleware run and such\n  await delay(20)\n\n  const apiActions = [\n    api.internalActions.middlewareRegistered.match,\n    getBanana.matchPending,\n    getBanana.matchFulfilled,\n    api.util.invalidateTags.match,\n    getBanana.matchPending,\n    getBanana.matchFulfilled,\n  ]\n\n  expect(storeRef.store.getState().actions).toMatchSequence(...apiActions)\n})\n\nit.each([\n  {\n    tags: [undefined, null, 'Bread'] as Parameters<\n      typeof api.util.invalidateTags\n    >['0'],\n  },\n  { tags: [undefined, null] },\n  { tags: [] },\n])(\n  'does not invalidate with tags=$tags if no query matches',\n  async ({ tags }) => {\n    await storeRef.store.dispatch(getBanana.initiate(1))\n    await storeRef.store.dispatch(api.util.invalidateTags(tags))\n\n    // Slight pause to let the middleware run and such\n    await delay(20)\n\n    const apiActions = [\n      api.internalActions.middlewareRegistered.match,\n      getBanana.matchPending,\n      getBanana.matchFulfilled,\n      api.util.invalidateTags.match,\n    ]\n\n    expect(storeRef.store.getState().actions).toMatchSequence(...apiActions)\n  },\n)\n\nit.each([\n  { mutationArg: 'Bread' as 'Bread' | null | undefined },\n  { mutationArg: undefined },\n  { mutationArg: null },\n])(\n  'does not invalidate queries when a mutation with tags=[$mutationArg] runs and does not match anything',\n  async ({ mutationArg }) => {\n    await storeRef.store.dispatch(getBanana.initiate(1))\n    await storeRef.store.dispatch(invalidateFruit.initiate(mutationArg))\n\n    // Slight pause to let the middleware run and such\n    await delay(20)\n\n    const apiActions = [\n      api.internalActions.middlewareRegistered.match,\n      getBanana.matchPending,\n      getBanana.matchFulfilled,\n      invalidateFruit.matchPending,\n      invalidateFruit.matchFulfilled,\n    ]\n\n    expect(storeRef.store.getState().actions).toMatchSequence(...apiActions)\n  },\n)\n\nit('correctly stringifies subscription state and dispatches subscriptionsUpdated', async () => {\n  // Create a fresh store for this test to avoid interference\n  const testStoreRef = setupApiStore(\n    api,\n    {\n      ...actionsReducer,\n    },\n    { withoutListeners: true },\n  )\n\n  // Start multiple subscriptions\n  const subscription1 = testStoreRef.store.dispatch(\n    getBanana.initiate(1, {\n      subscriptionOptions: { pollingInterval: 1000 },\n    }),\n  )\n  const subscription2 = testStoreRef.store.dispatch(\n    getBanana.initiate(2, {\n      subscriptionOptions: { refetchOnFocus: true },\n    }),\n  )\n  const subscription3 = testStoreRef.store.dispatch(\n    api.endpoints.getBananas.initiate(),\n  )\n\n  // Wait for the subscriptions to be established\n  await Promise.all([subscription1, subscription2, subscription3])\n\n  // Wait for the subscription sync timer (500ms + buffer)\n  await delay(600)\n\n  // Check the final subscription state in the store\n  const finalState = testStoreRef.store.getState()\n  const subscriptionState = finalState[api.reducerPath].subscriptions\n\n  // Should have subscriptions for getBanana(1), getBanana(2), and getBananas()\n  expect(subscriptionState).toMatchObject({\n    'getBanana(1)': {\n      [subscription1.requestId]: { pollingInterval: 1000 },\n    },\n    'getBanana(2)': {\n      [subscription2.requestId]: { refetchOnFocus: true },\n    },\n    'getBananas(undefined)': {\n      [subscription3.requestId]: {},\n    },\n  })\n\n  // Verify the subscription entries have the expected structure\n  expect(Object.keys(subscriptionState)).toHaveLength(3)\n  expect(subscriptionState['getBanana(1)']?.[subscription1.requestId]).toEqual({\n    pollingInterval: 1000,\n  })\n  expect(subscriptionState['getBanana(2)']?.[subscription2.requestId]).toEqual({\n    refetchOnFocus: true,\n  })\n  expect(\n    subscriptionState['getBananas(undefined)']?.[subscription3.requestId],\n  ).toEqual({})\n})\n\nit('does not leak subscription state between multiple stores using the same API instance (SSR scenario)', async () => {\n  vi.useFakeTimers()\n  // Simulate SSR: create API once at module level\n  const sharedApi = createApi({\n    baseQuery: (args?: any) => ({ data: args }),\n    tagTypes: ['Test'],\n    endpoints: (build) => ({\n      getTest: build.query<unknown, number>({\n        query(id) {\n          return { url: `test/${id}` }\n        },\n      }),\n    }),\n  })\n\n  // Create first store (simulating first SSR request)\n  const store1Ref = setupApiStore(sharedApi, {}, { withoutListeners: true })\n\n  // Add subscription in store1\n  const sub1 = store1Ref.store.dispatch(\n    sharedApi.endpoints.getTest.initiate(1, {\n      subscriptionOptions: { pollingInterval: 1000 },\n    }),\n  )\n  vi.advanceTimersByTime(10)\n  await sub1\n\n  // Wait for subscription sync (500ms + buffer)\n  vi.advanceTimersByTime(600)\n\n  // Verify store1 has the subscription\n  const store1SubscriptionSelectors = store1Ref.store.dispatch(\n    sharedApi.internalActions.internal_getRTKQSubscriptions(),\n  ) as any\n  const store1InternalSubs = store1SubscriptionSelectors.getSubscriptions()\n  expect(store1InternalSubs.size).toBe(1)\n\n  // Create second store (simulating second SSR request)\n  const store2Ref = setupApiStore(sharedApi, {}, { withoutListeners: true })\n\n  // Check subscriptions via internal action\n  const store2SubscriptionSelectors = store2Ref.store.dispatch(\n    sharedApi.internalActions.internal_getRTKQSubscriptions(),\n  ) as any\n\n  const store2InternalSubs = store2SubscriptionSelectors.getSubscriptions()\n\n  expect(store2InternalSubs.size).toBe(0)\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/buildSelector.test-d.ts",
    "content": "import { configureStore, createSelector } from '@reduxjs/toolkit'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ndescribe('type tests', () => {\n  test('buildSelector type test', () => {\n    interface Todo {\n      userId: number\n      id: number\n      title: string\n      completed: boolean\n    }\n\n    type Todos = Array<Todo>\n\n    const exampleApi = createApi({\n      reducerPath: 'api',\n      baseQuery: fetchBaseQuery({\n        baseUrl: 'https://jsonplaceholder.typicode.com',\n      }),\n      endpoints: (build) => ({\n        getTodos: build.query<Todos, string>({\n          query: () => '/todos',\n        }),\n      }),\n    })\n\n    const exampleQuerySelector = exampleApi.endpoints.getTodos.select('/')\n\n    const todosSelector = createSelector(\n      [exampleQuerySelector],\n      (queryState) => {\n        return queryState?.data?.[0] ?? ({} as Todo)\n      },\n    )\n\n    const firstTodoTitleSelector = createSelector(\n      [todosSelector],\n      (todo) => todo?.title,\n    )\n\n    const store = configureStore({\n      reducer: {\n        [exampleApi.reducerPath]: exampleApi.reducer,\n        other: () => 1,\n      },\n    })\n\n    const todoTitle = firstTodoTitleSelector(store.getState())\n\n    // This only compiles if we carried the types through\n    const upperTitle = todoTitle.toUpperCase()\n\n    expectTypeOf(upperTitle).toBeString()\n  })\n\n  test('selectCachedArgsForQuery type test', () => {\n    interface Todo {\n      userId: number\n      id: number\n      title: string\n      completed: boolean\n    }\n\n    type Todos = Array<Todo>\n\n    const exampleApi = createApi({\n      reducerPath: 'api',\n      baseQuery: fetchBaseQuery({\n        baseUrl: 'https://jsonplaceholder.typicode.com',\n      }),\n      endpoints: (build) => ({\n        getTodos: build.query<Todos, string>({\n          query: () => '/todos',\n        }),\n        getInfiniteTodos: build.infiniteQuery<Todos, string, number>({\n          infiniteQueryOptions: {\n            initialPageParam: 0,\n            maxPages: 3,\n            getNextPageParam: (\n              lastPage,\n              allPages,\n              lastPageParam,\n              allPageParams,\n            ) => lastPageParam + 1,\n          },\n          query({ pageParam }) {\n            return `/todos?page=${pageParam}`\n          },\n        }),\n      }),\n    })\n\n    const store = configureStore({\n      reducer: {\n        [exampleApi.reducerPath]: exampleApi.reducer,\n        other: () => 1,\n      },\n    })\n\n    expectTypeOf(\n      exampleApi.util.selectCachedArgsForQuery(store.getState(), 'getTodos'),\n    ).toEqualTypeOf<string[]>()\n    expectTypeOf(\n      exampleApi.util.selectCachedArgsForQuery(\n        store.getState(),\n        'getInfiniteTodos',\n      ),\n    ).toEqualTypeOf<string[]>()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/buildSlice.test.ts",
    "content": "import { createSlice, createAction } from '@reduxjs/toolkit'\nimport type { CombinedState } from '@reduxjs/toolkit/query'\nimport { createApi } from '@reduxjs/toolkit/query'\nimport { delay } from 'msw'\nimport { setupApiStore } from '../../tests/utils/helpers'\n\nlet shouldApiResponseSuccess = true\n\nconst rehydrateAction = createAction<{ api: CombinedState<any, any, any> }>(\n  'persist/REHYDRATE',\n)\n\nconst baseQuery = (args?: any) => ({ data: args })\nconst api = createApi({\n  baseQuery,\n  tagTypes: ['SUCCEED', 'FAILED'],\n  endpoints: (build) => ({\n    getUser: build.query<{ url: string; success: boolean }, number>({\n      query(id) {\n        return { url: `user/${id}`, success: shouldApiResponseSuccess }\n      },\n      providesTags: (result) => (result?.success ? ['SUCCEED'] : ['FAILED']),\n    }),\n  }),\n  extractRehydrationInfo(action, { reducerPath }) {\n    if (rehydrateAction.match(action)) {\n      return action.payload?.[reducerPath]\n    }\n    return undefined\n  },\n})\nconst { getUser } = api.endpoints\n\nconst authSlice = createSlice({\n  name: 'auth',\n  initialState: {\n    token: '1234',\n  },\n  reducers: {\n    setToken(state, action) {\n      state.token = action.payload\n    },\n  },\n})\n\nconst storeRef = setupApiStore(api, { auth: authSlice.reducer })\n\ndescribe('buildSlice', () => {\n  beforeEach(() => {\n    shouldApiResponseSuccess = true\n  })\n\n  it('only resets the api state when resetApiState is dispatched', async () => {\n    storeRef.store.dispatch({ type: 'unrelated' }) // trigger \"registered middleware\" into place\n    const initialState = storeRef.store.getState()\n\n    await storeRef.store.dispatch(\n      getUser.initiate(1, { subscriptionOptions: { pollingInterval: 10 } }),\n    )\n\n    const initialQueryState = {\n      api: {\n        config: {\n          focused: true,\n          invalidationBehavior: 'delayed',\n          keepUnusedDataFor: 60,\n          middlewareRegistered: true,\n          online: true,\n          reducerPath: 'api',\n          refetchOnFocus: false,\n          refetchOnMountOrArgChange: false,\n          refetchOnReconnect: false,\n        },\n        mutations: {},\n        provided: expect.any(Object),\n        queries: {\n          'getUser(1)': {\n            data: {\n              success: true,\n              url: 'user/1',\n            },\n            endpointName: 'getUser',\n            fulfilledTimeStamp: expect.any(Number),\n            originalArgs: 1,\n            requestId: expect.any(String),\n            startedTimeStamp: expect.any(Number),\n            status: 'fulfilled',\n          },\n        },\n        // Filled some time later\n        subscriptions: {},\n      },\n      auth: {\n        token: '1234',\n      },\n    }\n\n    expect(storeRef.store.getState()).toEqual(initialQueryState)\n\n    storeRef.store.dispatch(api.util.resetApiState())\n\n    expect(storeRef.store.getState()).toEqual(initialState)\n  })\n\n  it('replaces previous tags with new provided tags', async () => {\n    await storeRef.store.dispatch(getUser.initiate(1))\n\n    expect(\n      api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']),\n    ).toHaveLength(1)\n    expect(\n      api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']),\n    ).toHaveLength(0)\n\n    shouldApiResponseSuccess = false\n\n    storeRef.store.dispatch(getUser.initiate(1)).refetch()\n\n    await delay(10)\n\n    expect(\n      api.util.selectInvalidatedBy(storeRef.store.getState(), ['SUCCEED']),\n    ).toHaveLength(0)\n    expect(\n      api.util.selectInvalidatedBy(storeRef.store.getState(), ['FAILED']),\n    ).toHaveLength(1)\n  })\n\n  it('handles extractRehydrationInfo correctly', async () => {\n    await storeRef.store.dispatch(getUser.initiate(1))\n    await storeRef.store.dispatch(getUser.initiate(2))\n\n    const stateWithUser = storeRef.store.getState()\n\n    storeRef.store.dispatch(api.util.resetApiState())\n\n    storeRef.store.dispatch(rehydrateAction({ api: stateWithUser.api }))\n\n    const rehydratedState = storeRef.store.getState()\n    expect(rehydratedState).toEqual(stateWithUser)\n  })\n})\n\ndescribe('`merge` callback', () => {\n  const baseQuery = (args?: any) => ({ data: args })\n\n  interface Todo {\n    id: string\n    text: string\n  }\n\n  it('Calls `merge` once there is existing data, and allows mutations of cache state', async () => {\n    let mergeCalled = false\n    let queryFnCalls = 0\n    const todoTexts = ['A', 'B', 'C', 'D']\n\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        getTodos: build.query<Todo[], void>({\n          async queryFn() {\n            const text = todoTexts[queryFnCalls]\n            return { data: [{ id: `${queryFnCalls++}`, text }] }\n          },\n          merge(currentCacheValue, responseData) {\n            mergeCalled = true\n            currentCacheValue.push(...responseData)\n          },\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    const selectTodoEntry = api.endpoints.getTodos.select()\n\n    const res = storeRef.store.dispatch(api.endpoints.getTodos.initiate())\n    await res\n    expect(mergeCalled).toBe(false)\n    const todoEntry1 = selectTodoEntry(storeRef.store.getState())\n    expect(todoEntry1.data).toEqual([{ id: '0', text: 'A' }])\n\n    res.refetch()\n\n    await delay(10)\n\n    expect(mergeCalled).toBe(true)\n    const todoEntry2 = selectTodoEntry(storeRef.store.getState())\n\n    expect(todoEntry2.data).toEqual([\n      { id: '0', text: 'A' },\n      { id: '1', text: 'B' },\n    ])\n  })\n\n  it('Allows returning a different value from `merge`', async () => {\n    let firstQueryFnCall = true\n\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        getTodos: build.query<Todo[], void>({\n          async queryFn() {\n            const item = firstQueryFnCall\n              ? { id: '0', text: 'A' }\n              : { id: '1', text: 'B' }\n            firstQueryFnCall = false\n            return { data: [item] }\n          },\n          merge(currentCacheValue, responseData) {\n            return responseData\n          },\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    const selectTodoEntry = api.endpoints.getTodos.select()\n\n    const res = storeRef.store.dispatch(api.endpoints.getTodos.initiate())\n    await res\n\n    const todoEntry1 = selectTodoEntry(storeRef.store.getState())\n    expect(todoEntry1.data).toEqual([{ id: '0', text: 'A' }])\n\n    res.refetch()\n\n    await delay(10)\n\n    const todoEntry2 = selectTodoEntry(storeRef.store.getState())\n\n    expect(todoEntry2.data).toEqual([{ id: '1', text: 'B' }])\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/buildThunks.test.tsx",
    "content": "import { configureStore } from '@reduxjs/toolkit'\nimport type { BaseQueryApi } from '@reduxjs/toolkit/query/react'\nimport { createApi } from '@reduxjs/toolkit/query/react'\nimport { renderHook, waitFor } from '@testing-library/react'\nimport {\n  actionsReducer,\n  setupApiStore,\n  withProvider,\n} from '../../tests/utils/helpers'\n\ndescribe('baseline thunk behavior', () => {\n  test('handles a non-async baseQuery without error', async () => {\n    const baseQuery = (args?: any) => ({ data: args })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        getUser: build.query<unknown, number>({\n          query(id) {\n            return { url: `user/${id}` }\n          },\n        }),\n      }),\n    })\n    const { getUser } = api.endpoints\n    const store = configureStore({\n      reducer: {\n        [api.reducerPath]: api.reducer,\n      },\n      middleware: (gDM) => gDM().concat(api.middleware),\n    })\n\n    const promise = store.dispatch(getUser.initiate(1))\n    const { data } = await promise\n\n    expect(data).toEqual({\n      url: 'user/1',\n    })\n\n    const storeResult = getUser.select(1)(store.getState())\n    expect(storeResult).toEqual({\n      data: {\n        url: 'user/1',\n      },\n      endpointName: 'getUser',\n      isError: false,\n      isLoading: false,\n      isSuccess: true,\n      isUninitialized: false,\n      originalArgs: 1,\n      requestId: expect.any(String),\n      status: 'fulfilled',\n      startedTimeStamp: expect.any(Number),\n      fulfilledTimeStamp: expect.any(Number),\n    })\n  })\n\n  test('passes the extraArgument property to the baseQueryApi', async () => {\n    const baseQuery = (_args: any, api: BaseQueryApi) => ({ data: api.extra })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        getUser: build.query<unknown, void>({\n          query: () => '',\n        }),\n      }),\n    })\n    const store = configureStore({\n      reducer: {\n        [api.reducerPath]: api.reducer,\n      },\n      middleware: (gDM) =>\n        gDM({ thunk: { extraArgument: 'cakes' } }).concat(api.middleware),\n    })\n    const { getUser } = api.endpoints\n    const { data } = await store.dispatch(getUser.initiate())\n    expect(data).toBe('cakes')\n  })\n\n  test('only triggers transformResponse when a query method is actually used', async () => {\n    const baseQuery = (args?: any) => ({ data: args })\n    const transformResponse = vi.fn((response: any) => response)\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        hasQuery: build.query<string, string>({\n          query: (arg) => 'test',\n          transformResponse,\n        }),\n        hasQueryFn: build.query<string, void>(\n          // @ts-expect-error\n          {\n            queryFn: () => ({ data: 'test' }),\n            transformResponse,\n          },\n        ),\n      }),\n    })\n\n    const store = configureStore({\n      reducer: {\n        [api.reducerPath]: api.reducer,\n      },\n      middleware: (gDM) =>\n        gDM({ thunk: { extraArgument: 'cakes' } }).concat(api.middleware),\n    })\n\n    await store.dispatch(api.util.upsertQueryData('hasQuery', 'a', 'test'))\n    expect(transformResponse).not.toHaveBeenCalled()\n\n    transformResponse.mockReset()\n\n    await store.dispatch(api.endpoints.hasQuery.initiate('b'))\n    expect(transformResponse).toHaveBeenCalledTimes(1)\n\n    transformResponse.mockReset()\n\n    await store.dispatch(api.endpoints.hasQueryFn.initiate())\n    expect(transformResponse).not.toHaveBeenCalled()\n  })\n})\n\ndescribe('re-triggering behavior on arg change', () => {\n  const api = createApi({\n    baseQuery: () => ({ data: null }),\n    endpoints: (build) => ({\n      getUser: build.query<any, any>({\n        query: (obj) => obj,\n      }),\n    }),\n  })\n  const { getUser } = api.endpoints\n  const store = configureStore({\n    reducer: { [api.reducerPath]: api.reducer },\n    middleware: (gDM) => gDM().concat(api.middleware),\n  })\n\n  const spy = vi.spyOn(getUser, 'initiate')\n  beforeEach(() => void spy.mockClear())\n\n  test('re-trigger on literal value change', async () => {\n    const { result, rerender } = renderHook(\n      (props) => getUser.useQuery(props),\n      {\n        wrapper: withProvider(store),\n        initialProps: 5,\n      },\n    )\n\n    await waitFor(() => {\n      expect(result.current.status).not.toBe('pending')\n    })\n\n    expect(spy).toHaveBeenCalledOnce()\n\n    for (let x = 1; x < 3; x++) {\n      rerender(6)\n      await waitFor(() => {\n        expect(result.current.status).not.toBe('pending')\n      })\n      expect(spy).toHaveBeenCalledTimes(2)\n    }\n\n    for (let x = 1; x < 3; x++) {\n      rerender(7)\n      await waitFor(() => {\n        expect(result.current.status).not.toBe('pending')\n      })\n      expect(spy).toHaveBeenCalledTimes(3)\n    }\n  })\n\n  test('only re-trigger on shallow-equal arg change', async () => {\n    const { result, rerender } = renderHook(\n      (props) => getUser.useQuery(props),\n      {\n        wrapper: withProvider(store),\n        initialProps: { name: 'Bob', likes: 'iceCream' },\n      },\n    )\n\n    await waitFor(() => {\n      expect(result.current.status).not.toBe('pending')\n    })\n    expect(spy).toHaveBeenCalledOnce()\n\n    for (let x = 1; x < 3; x++) {\n      rerender({ name: 'Bob', likes: 'waffles' })\n      await waitFor(() => {\n        expect(result.current.status).not.toBe('pending')\n      })\n      expect(spy).toHaveBeenCalledTimes(2)\n    }\n\n    for (let x = 1; x < 3; x++) {\n      rerender({ name: 'Alice', likes: 'waffles' })\n      await waitFor(() => {\n        expect(result.current.status).not.toBe('pending')\n      })\n      expect(spy).toHaveBeenCalledTimes(3)\n    }\n  })\n\n  test('re-triggers every time on deeper value changes', async () => {\n    const name = 'Tim'\n\n    const { result, rerender } = renderHook(\n      (props) => getUser.useQuery(props),\n      {\n        wrapper: withProvider(store),\n        initialProps: { person: { name } },\n      },\n    )\n\n    await waitFor(() => {\n      expect(result.current.status).not.toBe('pending')\n    })\n    expect(spy).toHaveBeenCalledOnce()\n\n    for (let x = 1; x < 3; x++) {\n      rerender({ person: { name: name + x } })\n      await waitFor(() => {\n        expect(result.current.status).not.toBe('pending')\n      })\n      expect(spy).toHaveBeenCalledTimes(x + 1)\n    }\n  })\n\n  test('do not re-trigger if the order of keys change while maintaining the same values', async () => {\n    const { result, rerender } = renderHook(\n      (props) => getUser.useQuery(props),\n      {\n        wrapper: withProvider(store),\n        initialProps: { name: 'Tim', likes: 'Bananas' },\n      },\n    )\n\n    await waitFor(() => {\n      expect(result.current.status).not.toBe('pending')\n    })\n    expect(spy).toHaveBeenCalledOnce()\n\n    for (let x = 1; x < 3; x++) {\n      rerender({ likes: 'Bananas', name: 'Tim' })\n      await waitFor(() => {\n        expect(result.current.status).not.toBe('pending')\n      })\n      expect(spy).toHaveBeenCalledOnce()\n    }\n  })\n})\n\ndescribe('prefetch', () => {\n  const baseQuery = () => ({ data: { name: 'Test User' } })\n\n  const api = createApi({\n    baseQuery,\n    tagTypes: ['User'],\n    endpoints: (build) => ({\n      getUser: build.query<any, number>({\n        query: (id) => ({ url: `user/${id}` }),\n        providesTags: (result, error, id) => [{ type: 'User', id }],\n      }),\n      updateUser: build.mutation<any, { id: number; name: string }>({\n        query: ({ id, name }) => ({\n          url: `user/${id}`,\n          method: 'PUT',\n          body: { name },\n        }),\n        invalidatesTags: (result, error, { id }) => [{ type: 'User', id }],\n      }),\n    }),\n    keepUnusedDataFor: 0.1, // 100ms for faster test cleanup\n  })\n\n  let storeRef = setupApiStore(\n    api,\n    { ...actionsReducer },\n    {\n      withoutListeners: true,\n    },\n  )\n\n  let getSubscriptions: () => Map<string, any>\n  let getSubscriptionCount: (queryCacheKey: string) => number\n\n  beforeEach(() => {\n    storeRef = setupApiStore(\n      api,\n      { ...actionsReducer },\n      {\n        withoutListeners: true,\n      },\n    )\n    // Get subscription helpers\n    const subscriptionSelectors = storeRef.store.dispatch(\n      api.internalActions.internal_getRTKQSubscriptions(),\n    ) as any\n    getSubscriptions = subscriptionSelectors.getSubscriptions\n    getSubscriptionCount = subscriptionSelectors.getSubscriptionCount\n  })\n\n  describe('subscription behavior', () => {\n    it('prefetch should NOT create a subscription', async () => {\n      const queryCacheKey = 'getUser(1)'\n\n      // Initially no subscriptions\n      expect(getSubscriptionCount(queryCacheKey)).toBe(0)\n\n      // Dispatch prefetch\n      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))\n      await Promise.all(\n        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),\n      )\n\n      expect(getSubscriptionCount(queryCacheKey)).toBe(0)\n    })\n\n    it('prefetch allows cache cleanup after keepUnusedDataFor', async () => {\n      const queryCacheKey = 'getUser(1)'\n\n      // Prefetch the data\n      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))\n      await Promise.all(\n        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),\n      )\n\n      // Verify data is in cache\n      let state = api.endpoints.getUser.select(1)(storeRef.store.getState())\n      expect(state.data).toEqual({ name: 'Test User' })\n\n      // Wait longer than keepUnusedDataFor\n      await new Promise((resolve) => setTimeout(resolve, 150))\n\n      state = api.endpoints.getUser.select(1)(storeRef.store.getState())\n      expect(state.status).toBe('uninitialized')\n      expect(state.data).toBeUndefined()\n    })\n\n    it('prefetch does NOT trigger refetch on tag invalidation', async () => {\n      // Prefetch user 1\n      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))\n      await Promise.all(\n        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),\n      )\n\n      // Verify data is in cache\n      let state = api.endpoints.getUser.select(1)(storeRef.store.getState())\n      expect(state.data).toEqual({ name: 'Test User' })\n\n      // Invalidate the tag by updating the user\n      await storeRef.store.dispatch(\n        api.endpoints.updateUser.initiate({ id: 1, name: 'Updated' }),\n      )\n\n      // Since there's no subscription, the cache entry gets removed on invalidation\n      await Promise.all(\n        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),\n      )\n\n      // Cache entry should be cleared (no subscription to keep it alive)\n      state = api.endpoints.getUser.select(1)(storeRef.store.getState())\n      expect(state.status).toBe('uninitialized')\n      expect(state.data).toBeUndefined()\n    })\n\n    it('multiple prefetches do not accumulate subscriptions', async () => {\n      const queryCacheKey = 'getUser(1)'\n\n      expect(getSubscriptionCount(queryCacheKey)).toBe(0)\n\n      // First prefetch\n      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))\n      await Promise.all(\n        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),\n      )\n      expect(getSubscriptionCount(queryCacheKey)).toBe(0)\n\n      // Second prefetch (force refetch)\n      storeRef.store.dispatch(api.util.prefetch('getUser', 1, { force: true }))\n      await Promise.all(\n        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),\n      )\n\n      // Still no subscriptions\n      expect(getSubscriptionCount(queryCacheKey)).toBe(0)\n\n      // Third prefetch\n      storeRef.store.dispatch(api.util.prefetch('getUser', 1, { force: true }))\n      await Promise.all(\n        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),\n      )\n      expect(getSubscriptionCount(queryCacheKey)).toBe(0)\n    })\n\n    it('prefetch followed by regular query should work correctly', async () => {\n      const queryCacheKey = 'getUser(1)'\n\n      // Prefetch first\n      storeRef.store.dispatch(api.util.prefetch('getUser', 1, {}))\n      await Promise.all(\n        storeRef.store.dispatch(api.util.getRunningQueriesThunk()),\n      )\n\n      // No subscription from prefetch\n      expect(getSubscriptionCount(queryCacheKey)).toBe(0)\n\n      // Now create a real subscription via initiate\n      const promise = storeRef.store.dispatch(api.endpoints.getUser.initiate(1))\n\n      // Should have 1 subscription from the initiate call\n      expect(getSubscriptionCount(queryCacheKey)).toBe(1)\n\n      // Unsubscribe\n      promise.unsubscribe()\n\n      // Subscription should be cleaned up\n      expect(getSubscriptionCount(queryCacheKey)).toBe(0)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/cacheCollection.test.ts",
    "content": "import type { Middleware, Reducer } from '@reduxjs/toolkit'\nimport { configureStore } from '@reduxjs/toolkit'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport {\n  THIRTY_TWO_BIT_MAX_INT,\n  THIRTY_TWO_BIT_MAX_TIMER_SECONDS,\n} from '../core/buildMiddleware/cacheCollection'\nimport { countObjectKeys } from '../utils/index'\n\nbeforeAll(() => {\n  vi.useFakeTimers()\n})\n\nconst onCleanup = vi.fn()\n\nbeforeEach(() => {\n  onCleanup.mockClear()\n})\n\ntest(`query: await cleanup, defaults`, async () => {\n  const { store, api } = storeForApi(\n    createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n      endpoints: (build) => ({\n        query: build.query<unknown, string>({\n          query: () => '/success',\n        }),\n      }),\n    }),\n  )\n\n  const promise = store.dispatch(api.endpoints.query.initiate('arg'))\n  await promise\n  promise.unsubscribe()\n  vi.advanceTimersByTime(59000)\n  expect(onCleanup).not.toHaveBeenCalled()\n  vi.advanceTimersByTime(2000)\n  expect(onCleanup).toHaveBeenCalled()\n})\n\ntest(`query: await cleanup, keepUnusedDataFor set`, async () => {\n  const { store, api } = storeForApi(\n    createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n      endpoints: (build) => ({\n        query: build.query<unknown, string>({\n          query: () => '/success',\n        }),\n      }),\n      keepUnusedDataFor: 29,\n    }),\n  )\n\n  const promise = store.dispatch(api.endpoints.query.initiate('arg'))\n  await promise\n  promise.unsubscribe()\n  vi.advanceTimersByTime(28000)\n  expect(onCleanup).not.toHaveBeenCalled()\n  vi.advanceTimersByTime(2000)\n  expect(onCleanup).toHaveBeenCalled()\n})\n\ntest(`query: handles large keepUnuseDataFor values over 32-bit ms`, async () => {\n  const { store, api } = storeForApi(\n    createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n      endpoints: (build) => ({\n        query: build.query<unknown, string>({\n          query: () => '/success',\n        }),\n      }),\n      keepUnusedDataFor: THIRTY_TWO_BIT_MAX_TIMER_SECONDS - 10,\n    }),\n  )\n\n  const promise = store.dispatch(api.endpoints.query.initiate('arg'))\n  await promise\n  promise.unsubscribe()\n\n  // Shouldn't have been called right away\n  vi.advanceTimersByTime(1000)\n  expect(onCleanup).not.toHaveBeenCalled()\n\n  // Shouldn't have been called any time in the next few minutes\n  vi.advanceTimersByTime(1_000_000)\n  expect(onCleanup).not.toHaveBeenCalled()\n\n  // _Should_ be called _wayyyy_ in the future (like 24.8 days from now)\n  vi.advanceTimersByTime(THIRTY_TWO_BIT_MAX_TIMER_SECONDS * 1000)\n  expect(onCleanup).toHaveBeenCalled()\n})\n\ndescribe(`query: await cleanup, keepUnusedDataFor set`, () => {\n  const { store, api } = storeForApi(\n    createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n      endpoints: (build) => ({\n        query: build.query<unknown, string>({\n          query: () => '/success',\n        }),\n        query2: build.query<unknown, string>({\n          query: () => '/success',\n          keepUnusedDataFor: 35,\n        }),\n        query3: build.query<unknown, string>({\n          query: () => '/success',\n          keepUnusedDataFor: 0,\n        }),\n        query4: build.query<unknown, string>({\n          query: () => '/success',\n          keepUnusedDataFor: Infinity,\n        }),\n      }),\n      keepUnusedDataFor: 29,\n    }),\n  )\n\n  test('global keepUnusedDataFor', async () => {\n    const promise = store.dispatch(api.endpoints.query.initiate('arg'))\n    await promise\n    promise.unsubscribe()\n    vi.advanceTimersByTime(28000)\n    expect(onCleanup).not.toHaveBeenCalled()\n    vi.advanceTimersByTime(2000)\n    expect(onCleanup).toHaveBeenCalled()\n  })\n\n  test('endpoint keepUnusedDataFor', async () => {\n    const promise = store.dispatch(api.endpoints.query2.initiate('arg'))\n    await promise\n    promise.unsubscribe()\n\n    vi.advanceTimersByTime(34000)\n    expect(onCleanup).not.toHaveBeenCalled()\n    vi.advanceTimersByTime(2000)\n    expect(onCleanup).toHaveBeenCalled()\n  })\n\n  test('endpoint keepUnusedDataFor: 0 ', async () => {\n    expect(onCleanup).not.toHaveBeenCalled()\n    const promise = store.dispatch(api.endpoints.query3.initiate('arg'))\n    await promise\n    promise.unsubscribe()\n    expect(onCleanup).not.toHaveBeenCalled()\n    vi.advanceTimersByTime(1)\n    expect(onCleanup).toHaveBeenCalled()\n  })\n\n  test('endpoint keepUnusedDataFor: Infinity', async () => {\n    expect(onCleanup).not.toHaveBeenCalled()\n    store.dispatch(api.endpoints.query4.initiate('arg')).unsubscribe()\n    expect(onCleanup).not.toHaveBeenCalled()\n    vi.advanceTimersByTime(THIRTY_TWO_BIT_MAX_INT)\n    expect(onCleanup).not.toHaveBeenCalled()\n  })\n})\n\ndescribe('resetApiState cleanup', () => {\n  test('resetApiState aborts multiple running queries and mutations', async () => {\n    const { store, api } = storeForApi(\n      createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n        endpoints: (build) => ({\n          query1: build.query<unknown, string>({\n            query: () => '/success',\n          }),\n          query2: build.query<unknown, string>({\n            query: () => '/success',\n          }),\n          mutation: build.mutation<unknown, string>({\n            query: () => ({\n              url: '/success',\n              method: 'POST',\n            }),\n          }),\n        }),\n      }),\n    )\n\n    // Start multiple queries and a mutation\n    const queryPromise1 = store.dispatch(api.endpoints.query1.initiate('arg1'))\n    const queryPromise2 = store.dispatch(api.endpoints.query2.initiate('arg2'))\n    const mutationPromise = store.dispatch(\n      api.endpoints.mutation.initiate('arg'),\n    )\n\n    // Spy on abort methods\n    queryPromise1.abort = vi.fn(queryPromise1.abort)\n    queryPromise2.abort = vi.fn(queryPromise2.abort)\n    mutationPromise.abort = vi.fn(mutationPromise.abort)\n\n    // Dispatch resetApiState\n    store.dispatch(api.util.resetApiState())\n\n    // Verify all aborts were called\n    expect(queryPromise1.abort).toHaveBeenCalled()\n    expect(queryPromise2.abort).toHaveBeenCalled()\n    expect(mutationPromise.abort).toHaveBeenCalled()\n  })\n})\n\nfunction storeForApi<\n  A extends {\n    reducerPath: 'api'\n    reducer: Reducer<any, any>\n    middleware: Middleware\n    util: { resetApiState(): any }\n  },\n>(api: A) {\n  const store = configureStore({\n    reducer: { api: api.reducer },\n    middleware: (gdm) =>\n      gdm({ serializableCheck: false, immutableCheck: false }).concat(\n        api.middleware,\n      ),\n    enhancers: (gde) =>\n      gde({\n        autoBatch: false,\n      }),\n  })\n  let hadQueries = false\n  store.subscribe(() => {\n    const queryState = store.getState().api.queries\n    if (hadQueries && countObjectKeys(queryState) === 0) {\n      onCleanup()\n    }\n    hadQueries = hadQueries || countObjectKeys(queryState) > 0\n  })\n  return { api, store }\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/cacheLifecycle.test-d.ts",
    "content": "import type { FetchBaseQueryMeta } from '@reduxjs/toolkit/query'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n  endpoints: () => ({}),\n})\n\ndescribe('type tests', () => {\n  test(`mutation: await cacheDataLoaded, await cacheEntryRemoved (success)`, () => {\n    const extended = api.injectEndpoints({\n      overrideExisting: true,\n      endpoints: (build) => ({\n        injected: build.mutation<number, string>({\n          query: () => '/success',\n          async onCacheEntryAdded(\n            arg,\n            { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },\n          ) {\n            const firstValue = await cacheDataLoaded\n\n            expectTypeOf(firstValue).toExtend<{\n              data: number\n              meta?: FetchBaseQueryMeta\n            }>()\n          },\n        }),\n      }),\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/cacheLifecycle.test.ts",
    "content": "import {\n  DEFAULT_DELAY_MS,\n  fakeTimerWaitFor,\n  setupApiStore,\n} from '@internal/tests/utils/helpers'\nimport type { QueryActionCreatorResult } from '@reduxjs/toolkit/query'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\nbeforeAll(() => {\n  vi.useFakeTimers()\n})\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n  endpoints: () => ({}),\n})\nconst storeRef = setupApiStore(api)\n\nconst onNewCacheEntry = vi.fn()\nconst gotFirstValue = vi.fn()\nconst onCleanup = vi.fn()\nconst onCatch = vi.fn()\n\nbeforeEach(() => {\n  onNewCacheEntry.mockClear()\n  gotFirstValue.mockClear()\n  onCleanup.mockClear()\n  onCatch.mockClear()\n})\n\ndescribe.each([['query'], ['mutation']] as const)(\n  'generic cases: %s',\n  (type) => {\n    test(`${type}: new cache entry only`, async () => {\n      const extended = api.injectEndpoints({\n        overrideExisting: true,\n        endpoints: (build) => ({\n          injected: build[type as 'mutation']<unknown, string>({\n            query: () => '/success',\n            onCacheEntryAdded(arg, { dispatch, getState }) {\n              onNewCacheEntry(arg)\n            },\n          }),\n        }),\n      })\n      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))\n      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')\n    })\n\n    test(`${type}: await cacheEntryRemoved`, async () => {\n      const extended = api.injectEndpoints({\n        overrideExisting: true,\n        endpoints: (build) => ({\n          // Lying to TS here\n          injected: build[type as 'mutation']<unknown, string>({\n            query: () => '/success',\n            async onCacheEntryAdded(\n              arg,\n              { dispatch, getState, cacheEntryRemoved },\n            ) {\n              onNewCacheEntry(arg)\n              await cacheEntryRemoved\n              onCleanup()\n            },\n          }),\n        }),\n      })\n      const promise = storeRef.store.dispatch(\n        extended.endpoints.injected.initiate('arg'),\n      )\n\n      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')\n      expect(onCleanup).not.toHaveBeenCalled()\n\n      await promise\n      if (type === 'mutation') {\n        promise.reset()\n      } else {\n        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()\n      }\n      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)\n      if (type === 'query') {\n        await vi.advanceTimersByTimeAsync(59000)\n        expect(onCleanup).not.toHaveBeenCalled()\n        await vi.advanceTimersByTimeAsync(2000)\n      }\n\n      expect(onCleanup).toHaveBeenCalled()\n    })\n\n    test(`${type}: await cacheDataLoaded, await cacheEntryRemoved (success)`, async () => {\n      const extended = api.injectEndpoints({\n        overrideExisting: true,\n        endpoints: (build) => ({\n          injected: build[type as 'mutation']<number, string>({\n            query: () => '/success',\n            async onCacheEntryAdded(\n              arg,\n              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },\n            ) {\n              onNewCacheEntry(arg)\n              const firstValue = await cacheDataLoaded\n              gotFirstValue(firstValue)\n              await cacheEntryRemoved\n              onCleanup()\n            },\n          }),\n        }),\n      })\n      const promise = storeRef.store.dispatch(\n        extended.endpoints.injected.initiate('arg'),\n      )\n\n      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')\n\n      expect(gotFirstValue).not.toHaveBeenCalled()\n      expect(onCleanup).not.toHaveBeenCalled()\n\n      await fakeTimerWaitFor(() => {\n        expect(gotFirstValue).toHaveBeenCalled()\n      })\n      expect(gotFirstValue).toHaveBeenCalledWith({\n        data: { value: 'success' },\n        meta: {\n          request: expect.any(Request),\n          response: expect.any(Object), // Response is not available in jest env\n        },\n      })\n      expect(onCleanup).not.toHaveBeenCalled()\n\n      if (type === 'mutation') {\n        promise.reset()\n      } else {\n        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()\n      }\n      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)\n      if (type === 'query') {\n        await vi.advanceTimersByTimeAsync(59000)\n        expect(onCleanup).not.toHaveBeenCalled()\n        await vi.advanceTimersByTimeAsync(2000)\n      }\n\n      expect(onCleanup).toHaveBeenCalled()\n    })\n\n    test(`${type}: await cacheDataLoaded, await cacheEntryRemoved (cacheDataLoaded never resolves)`, async () => {\n      const extended = api.injectEndpoints({\n        overrideExisting: true,\n        endpoints: (build) => ({\n          injected: build[type as 'mutation']<unknown, string>({\n            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve\n            async onCacheEntryAdded(\n              arg,\n              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },\n            ) {\n              onNewCacheEntry(arg)\n              // this will wait until cacheEntryRemoved, then reject => nothing past that line will execute\n              // but since this special \"cacheEntryRemoved\" rejection is handled outside, there will be no\n              // uncaught rejection error\n              const firstValue = await cacheDataLoaded\n              gotFirstValue(firstValue)\n              await cacheEntryRemoved\n              onCleanup()\n            },\n          }),\n        }),\n      })\n      const promise = storeRef.store.dispatch(\n        extended.endpoints.injected.initiate('arg'),\n      )\n      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')\n\n      if (type === 'mutation') {\n        promise.reset()\n      } else {\n        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()\n      }\n      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)\n      if (type === 'query') {\n        await vi.advanceTimersByTimeAsync(120000)\n      }\n      expect(gotFirstValue).not.toHaveBeenCalled()\n      expect(onCleanup).not.toHaveBeenCalled()\n    })\n\n    test(`${type}: try { await cacheDataLoaded }, await cacheEntryRemoved (cacheDataLoaded never resolves)`, async () => {\n      const extended = api.injectEndpoints({\n        overrideExisting: true,\n        endpoints: (build) => ({\n          injected: build[type as 'mutation']<unknown, string>({\n            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve\n            async onCacheEntryAdded(\n              arg,\n              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },\n            ) {\n              onNewCacheEntry(arg)\n\n              try {\n                // this will wait until cacheEntryRemoved, then reject => nothing else in this try..catch block will execute\n                const firstValue = await cacheDataLoaded\n                gotFirstValue(firstValue)\n              } catch (e) {\n                onCatch(e)\n              }\n              await cacheEntryRemoved\n              onCleanup()\n            },\n          }),\n        }),\n      })\n      const promise = storeRef.store.dispatch(\n        extended.endpoints.injected.initiate('arg'),\n      )\n\n      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')\n      await promise\n      if (type === 'mutation') {\n        promise.reset()\n      } else {\n        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()\n      }\n      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)\n\n      if (type === 'query') {\n        await vi.advanceTimersByTimeAsync(59000)\n        expect(onCleanup).not.toHaveBeenCalled()\n        await vi.advanceTimersByTimeAsync(2000)\n      }\n\n      expect(onCleanup).toHaveBeenCalled()\n      expect(gotFirstValue).not.toHaveBeenCalled()\n      expect(onCatch.mock.calls[0][0]).toMatchObject({\n        message: 'Promise never resolved before cacheEntryRemoved.',\n      })\n    })\n\n    test(`${type}: try { await cacheDataLoaded, await cacheEntryRemoved } (cacheDataLoaded never resolves)`, async () => {\n      const extended = api.injectEndpoints({\n        overrideExisting: true,\n        endpoints: (build) => ({\n          injected: build[type as 'mutation']<unknown, string>({\n            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve\n            async onCacheEntryAdded(\n              arg,\n              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },\n            ) {\n              onNewCacheEntry(arg)\n\n              try {\n                // this will wait until cacheEntryRemoved, then reject => nothing else in this try..catch block will execute\n                const firstValue = await cacheDataLoaded\n                gotFirstValue(firstValue)\n                // cleanup in this scenario only needs to be done for stuff within this try..catch block - totally valid scenario\n                await cacheEntryRemoved\n                onCleanup()\n              } catch (e) {\n                onCatch(e)\n              }\n            },\n          }),\n        }),\n      })\n      const promise = storeRef.store.dispatch(\n        extended.endpoints.injected.initiate('arg'),\n      )\n\n      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')\n      await promise\n\n      if (type === 'mutation') {\n        promise.reset()\n      } else {\n        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()\n      }\n      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)\n      if (type === 'query') {\n        await vi.advanceTimersByTimeAsync(59000)\n        expect(onCleanup).not.toHaveBeenCalled()\n        await vi.advanceTimersByTimeAsync(2000)\n      }\n      expect(onCleanup).not.toHaveBeenCalled()\n      expect(gotFirstValue).not.toHaveBeenCalled()\n      expect(onCatch.mock.calls[0][0]).toMatchObject({\n        message: 'Promise never resolved before cacheEntryRemoved.',\n      })\n    })\n\n    test(`${type}: try { await cacheDataLoaded } finally { await cacheEntryRemoved } (cacheDataLoaded never resolves)`, async () => {\n      const extended = api.injectEndpoints({\n        overrideExisting: true,\n        endpoints: (build) => ({\n          injected: build[type as 'mutation']<unknown, string>({\n            query: () => '/error', // we will initiate only once and that one time will be an error -> cacheDataLoaded will never resolve\n            async onCacheEntryAdded(\n              arg,\n              { dispatch, getState, cacheEntryRemoved, cacheDataLoaded },\n            ) {\n              onNewCacheEntry(arg)\n\n              try {\n                // this will wait until cacheEntryRemoved, then reject => nothing else in this try..catch block will execute\n                const firstValue = await cacheDataLoaded\n                gotFirstValue(firstValue)\n              } catch (e) {\n                onCatch(e)\n              } finally {\n                await cacheEntryRemoved\n                onCleanup()\n              }\n            },\n          }),\n        }),\n      })\n      const promise = storeRef.store.dispatch(\n        extended.endpoints.injected.initiate('arg'),\n      )\n\n      expect(onNewCacheEntry).toHaveBeenCalledWith('arg')\n\n      await promise\n      if (type === 'mutation') {\n        promise.reset()\n      } else {\n        ;(promise as unknown as QueryActionCreatorResult<any>).unsubscribe()\n      }\n      await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)\n      if (type === 'query') {\n        await vi.advanceTimersByTimeAsync(59000)\n        expect(onCleanup).not.toHaveBeenCalled()\n        await vi.advanceTimersByTimeAsync(2000)\n      }\n      expect(onCleanup).toHaveBeenCalled()\n      expect(gotFirstValue).not.toHaveBeenCalled()\n      expect(onCatch.mock.calls[0][0]).toMatchObject({\n        message: 'Promise never resolved before cacheEntryRemoved.',\n      })\n    })\n  },\n)\n\ntest(`query: getCacheEntry`, async () => {\n  const snapshot = vi.fn()\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.query<unknown, string>({\n        query: () => '/success',\n        async onCacheEntryAdded(\n          arg,\n          {\n            dispatch,\n            getState,\n            getCacheEntry,\n            cacheEntryRemoved,\n            cacheDataLoaded,\n          },\n        ) {\n          snapshot(getCacheEntry())\n          gotFirstValue(await cacheDataLoaded)\n          snapshot(getCacheEntry())\n          await cacheEntryRemoved\n          snapshot(getCacheEntry())\n        },\n      }),\n    }),\n  })\n  const promise = storeRef.store.dispatch(\n    extended.endpoints.injected.initiate('arg'),\n  )\n  await promise\n  promise.unsubscribe()\n\n  await fakeTimerWaitFor(() => {\n    expect(gotFirstValue).toHaveBeenCalled()\n  })\n\n  await vi.advanceTimersByTimeAsync(120000)\n\n  expect(snapshot).toHaveBeenCalledTimes(3)\n  expect(snapshot.mock.calls[0][0]).toMatchObject({\n    endpointName: 'injected',\n    isError: false,\n    isLoading: true,\n    isSuccess: false,\n    isUninitialized: false,\n    originalArgs: 'arg',\n    requestId: promise.requestId,\n    startedTimeStamp: expect.any(Number),\n    status: 'pending',\n  })\n  expect(snapshot.mock.calls[1][0]).toMatchObject({\n    data: {\n      value: 'success',\n    },\n    endpointName: 'injected',\n    fulfilledTimeStamp: expect.any(Number),\n    isError: false,\n    isLoading: false,\n    isSuccess: true,\n    isUninitialized: false,\n    originalArgs: 'arg',\n    requestId: promise.requestId,\n    startedTimeStamp: expect.any(Number),\n    status: 'fulfilled',\n  })\n  expect(snapshot.mock.calls[2][0]).toMatchObject({\n    isError: false,\n    isLoading: false,\n    isSuccess: false,\n    isUninitialized: true,\n    status: 'uninitialized',\n  })\n})\n\ntest(`mutation: getCacheEntry`, async () => {\n  const snapshot = vi.fn()\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.mutation<unknown, string>({\n        query: () => '/success',\n        async onCacheEntryAdded(\n          arg,\n          {\n            dispatch,\n            getState,\n            getCacheEntry,\n            cacheEntryRemoved,\n            cacheDataLoaded,\n          },\n        ) {\n          snapshot(getCacheEntry())\n          gotFirstValue(await cacheDataLoaded)\n          snapshot(getCacheEntry())\n          await cacheEntryRemoved\n          snapshot(getCacheEntry())\n        },\n      }),\n    }),\n  })\n  const promise = storeRef.store.dispatch(\n    extended.endpoints.injected.initiate('arg'),\n  )\n  await fakeTimerWaitFor(() => {\n    expect(gotFirstValue).toHaveBeenCalled()\n  })\n\n  promise.reset()\n  await vi.advanceTimersByTimeAsync(DEFAULT_DELAY_MS)\n\n  expect(snapshot).toHaveBeenCalledTimes(3)\n  expect(snapshot.mock.calls[0][0]).toMatchObject({\n    endpointName: 'injected',\n    isError: false,\n    isLoading: true,\n    isSuccess: false,\n    isUninitialized: false,\n    startedTimeStamp: expect.any(Number),\n    status: 'pending',\n  })\n  expect(snapshot.mock.calls[1][0]).toMatchObject({\n    data: {\n      value: 'success',\n    },\n    endpointName: 'injected',\n    fulfilledTimeStamp: expect.any(Number),\n    isError: false,\n    isLoading: false,\n    isSuccess: true,\n    isUninitialized: false,\n    startedTimeStamp: expect.any(Number),\n    status: 'fulfilled',\n  })\n  expect(snapshot.mock.calls[2][0]).toMatchObject({\n    isError: false,\n    isLoading: false,\n    isSuccess: false,\n    isUninitialized: true,\n    status: 'uninitialized',\n  })\n})\n\ntest('query: updateCachedData', async () => {\n  const trackCalls = vi.fn()\n\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.query<{ value: string }, string>({\n        query: () => '/success',\n        async onCacheEntryAdded(\n          arg,\n          {\n            dispatch,\n            getState,\n            getCacheEntry,\n            updateCachedData,\n            cacheEntryRemoved,\n            cacheDataLoaded,\n          },\n        ) {\n          expect(getCacheEntry().data).toEqual(undefined)\n          // calling `updateCachedData` when there is no data yet should not do anything\n          updateCachedData((draft) => {\n            draft.value = 'TEST'\n            trackCalls()\n          })\n          expect(trackCalls).not.toHaveBeenCalled()\n          expect(getCacheEntry().data).toEqual(undefined)\n\n          gotFirstValue(await cacheDataLoaded)\n\n          expect(getCacheEntry().data).toEqual({ value: 'success' })\n          updateCachedData((draft) => {\n            draft.value = 'TEST'\n            trackCalls()\n          })\n          expect(trackCalls).toHaveBeenCalledOnce()\n          expect(getCacheEntry().data).toEqual({ value: 'TEST' })\n\n          await cacheEntryRemoved\n\n          expect(getCacheEntry().data).toEqual(undefined)\n          // calling `updateCachedData` when there is no data any more should not do anything\n          updateCachedData((draft) => {\n            draft.value = 'TEST2'\n            trackCalls()\n          })\n          expect(trackCalls).toHaveBeenCalledOnce()\n          expect(getCacheEntry().data).toEqual(undefined)\n\n          onCleanup()\n        },\n      }),\n    }),\n  })\n  const promise = storeRef.store.dispatch(\n    extended.endpoints.injected.initiate('arg'),\n  )\n  await promise\n  promise.unsubscribe()\n\n  await fakeTimerWaitFor(() => {\n    expect(gotFirstValue).toHaveBeenCalled()\n  })\n\n  await vi.advanceTimersByTimeAsync(61000)\n\n  await fakeTimerWaitFor(() => {\n    expect(onCleanup).toHaveBeenCalled()\n  })\n})\n\ntest('updateCachedData - infinite query', async () => {\n  const trackCalls = vi.fn()\n\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      infiniteInjected: build.infiniteQuery<{ value: string }, string, number>({\n        query: () => '/success',\n        infiniteQueryOptions: {\n          initialPageParam: 1,\n          getNextPageParam: (\n            lastPage,\n            allPages,\n            lastPageParam,\n            allPageParams,\n          ) => lastPageParam + 1,\n        },\n        async onCacheEntryAdded(\n          arg,\n          {\n            dispatch,\n            getState,\n            getCacheEntry,\n            updateCachedData,\n            cacheEntryRemoved,\n            cacheDataLoaded,\n          },\n        ) {\n          expect(getCacheEntry().data).toEqual(undefined)\n          // calling `updateCachedData` when there is no data yet should not do anything\n          updateCachedData((draft) => {\n            draft.pages = [{ value: 'TEST' }]\n            draft.pageParams = [1]\n            trackCalls()\n          })\n          expect(trackCalls).not.toHaveBeenCalled()\n          expect(getCacheEntry().data).toEqual(undefined)\n\n          gotFirstValue(await cacheDataLoaded)\n\n          expect(getCacheEntry().data).toEqual({\n            pages: [{ value: 'success' }],\n            pageParams: [1],\n          })\n          updateCachedData((draft) => {\n            draft.pages = [{ value: 'TEST' }]\n            draft.pageParams = [1]\n            trackCalls()\n          })\n          expect(trackCalls).toHaveBeenCalledOnce()\n          expect(getCacheEntry().data).toEqual({\n            pages: [{ value: 'TEST' }],\n            pageParams: [1],\n          })\n\n          await cacheEntryRemoved\n\n          expect(getCacheEntry().data).toEqual(undefined)\n          // calling `updateCachedData` when there is no data any more should not do anything\n          updateCachedData((draft) => {\n            draft.pages = [{ value: 'TEST' }, { value: 'TEST2' }]\n            draft.pageParams = [1, 2]\n            trackCalls()\n          })\n          expect(trackCalls).toHaveBeenCalledOnce()\n          expect(getCacheEntry().data).toEqual(undefined)\n\n          onCleanup()\n        },\n      }),\n    }),\n  })\n  const promise = storeRef.store.dispatch(\n    extended.endpoints.infiniteInjected.initiate('arg'),\n  )\n  await promise\n  promise.unsubscribe()\n\n  await fakeTimerWaitFor(() => {\n    expect(gotFirstValue).toHaveBeenCalled()\n  })\n\n  await vi.advanceTimersByTimeAsync(61000)\n\n  await fakeTimerWaitFor(() => {\n    expect(onCleanup).toHaveBeenCalled()\n  })\n})\n\ntest('dispatching further actions does not trigger another lifecycle', async () => {\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.query<unknown, void>({\n        query: () => '/success',\n        async onCacheEntryAdded() {\n          onNewCacheEntry()\n        },\n      }),\n    }),\n  })\n  await storeRef.store.dispatch(extended.endpoints.injected.initiate())\n  expect(onNewCacheEntry).toHaveBeenCalledOnce()\n\n  await storeRef.store.dispatch(extended.endpoints.injected.initiate())\n  expect(onNewCacheEntry).toHaveBeenCalledOnce()\n\n  await storeRef.store.dispatch(\n    extended.endpoints.injected.initiate(undefined, { forceRefetch: true }),\n  )\n  expect(onNewCacheEntry).toHaveBeenCalledOnce()\n})\n\ntest('dispatching a query initializer with `subscribe: false` does also start a lifecycle', async () => {\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.query<unknown, void>({\n        query: () => '/success',\n        async onCacheEntryAdded() {\n          onNewCacheEntry()\n        },\n      }),\n    }),\n  })\n  await storeRef.store.dispatch(\n    extended.endpoints.injected.initiate(undefined, { subscribe: false }),\n  )\n  expect(onNewCacheEntry).toHaveBeenCalledOnce()\n\n  // will not be called a second time though\n  await storeRef.store.dispatch(extended.endpoints.injected.initiate(undefined))\n  expect(onNewCacheEntry).toHaveBeenCalledOnce()\n})\n\ntest('dispatching a mutation initializer with `track: false` does not start a lifecycle', async () => {\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.mutation<unknown, void>({\n        query: () => '/success',\n        async onCacheEntryAdded() {\n          onNewCacheEntry()\n        },\n      }),\n    }),\n  })\n  await storeRef.store.dispatch(\n    extended.endpoints.injected.initiate(undefined, { track: false }),\n  )\n  expect(onNewCacheEntry).not.toHaveBeenCalled()\n\n  await storeRef.store.dispatch(extended.endpoints.injected.initiate(undefined))\n  expect(onNewCacheEntry).toHaveBeenCalledOnce()\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/cleanup.test.tsx",
    "content": "// tests for \"cleanup-after-unsubscribe\" behavior\nimport React from 'react'\n\nimport { createListenerMiddleware } from '@reduxjs/toolkit'\nimport { createApi, QueryStatus } from '@reduxjs/toolkit/query/react'\nimport { act, render, screen, waitFor } from '@testing-library/react'\nimport { setupApiStore } from '../../tests/utils/helpers'\nimport type { SubscriptionSelectors } from '../core/buildMiddleware/types'\n\nconst api = createApi({\n  baseQuery: () => ({ data: 42 }),\n  endpoints: (build) => ({\n    a: build.query<unknown, void>({ query: () => '' }),\n    b: build.query<unknown, void>({ query: () => '' }),\n  }),\n})\nconst storeRef = setupApiStore(api)\n\nconst getSubStateA = () => storeRef.store.getState().api.queries['a(undefined)']\nconst getSubStateB = () => storeRef.store.getState().api.queries['b(undefined)']\n\nfunction UsingA() {\n  const { data } = api.endpoints.a.useQuery()\n\n  return <>Result: {data as React.ReactNode} </>\n}\n\nfunction UsingB() {\n  api.endpoints.b.useQuery()\n\n  return <></>\n}\n\nfunction UsingAB() {\n  api.endpoints.a.useQuery()\n  api.endpoints.b.useQuery()\n\n  return <></>\n}\n\nbeforeAll(() => {\n  vi.useFakeTimers({ shouldAdvanceTime: true })\n})\n\ntest('data stays in store when component stays rendered', async () => {\n  expect(getSubStateA()).toBeUndefined()\n\n  render(<UsingA />, { wrapper: storeRef.wrapper })\n  await waitFor(() =>\n    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled),\n  )\n\n  vi.advanceTimersByTime(120_000)\n\n  expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)\n})\n\ntest('data is removed from store after 60 seconds', async () => {\n  expect(getSubStateA()).toBeUndefined()\n\n  const { unmount } = render(<UsingA />, { wrapper: storeRef.wrapper })\n  await waitFor(() =>\n    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled),\n  )\n\n  unmount()\n\n  vi.advanceTimersByTime(59_000)\n\n  expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)\n\n  vi.advanceTimersByTime(2000)\n\n  expect(getSubStateA()).toBeUndefined()\n})\n\ntest('data stays in store when component stays rendered while data for another component is removed after it unmounted', async () => {\n  expect(getSubStateA()).toBeUndefined()\n  expect(getSubStateB()).toBeUndefined()\n\n  const { rerender } = render(\n    <>\n      <UsingA />\n      <UsingB />\n    </>,\n    { wrapper: storeRef.wrapper },\n  )\n  await waitFor(() => {\n    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)\n    expect(getSubStateB()?.status).toBe(QueryStatus.fulfilled)\n  })\n\n  const statusA = getSubStateA()\n\n  await act(async () => {\n    rerender(<UsingA />)\n\n    vi.advanceTimersByTime(10)\n  })\n\n  vi.advanceTimersByTime(120_000)\n\n  expect(getSubStateA()).toEqual(statusA)\n  expect(getSubStateB()).toBeUndefined()\n})\n\ntest('data stays in store when one component requiring the data stays in the store', async () => {\n  expect(getSubStateA()).toBeUndefined()\n  expect(getSubStateB()).toBeUndefined()\n\n  const { rerender } = render(\n    <>\n      <UsingA key=\"a\" />\n      <UsingAB key=\"ab\" />\n    </>,\n    { wrapper: storeRef.wrapper },\n  )\n  await waitFor(() => {\n    expect(getSubStateA()?.status).toBe(QueryStatus.fulfilled)\n    expect(getSubStateB()?.status).toBe(QueryStatus.fulfilled)\n  })\n\n  const statusA = getSubStateA()\n  const statusB = getSubStateB()\n\n  await act(async () => {\n    rerender(<UsingAB key=\"ab\" />)\n    vi.advanceTimersByTime(10)\n    vi.runAllTimers()\n  })\n\n  await act(async () => {\n    vi.advanceTimersByTime(120000)\n    vi.runAllTimers()\n  })\n\n  expect(getSubStateA()).toEqual(statusA)\n  expect(getSubStateB()).toEqual(statusB)\n})\n\ntest('Minimizes the number of subscription dispatches when multiple components ask for the same data', async () => {\n  const listenerMiddleware = createListenerMiddleware()\n  const storeRef = setupApiStore(api, undefined, {\n    middleware: {\n      concat: [listenerMiddleware.middleware],\n    },\n    withoutTestLifecycles: true,\n  })\n\n  const actionTypes: unknown[] = []\n\n  listenerMiddleware.startListening({\n    predicate: () => true,\n    effect: (action) => {\n      if (\n        action.type.includes('subscriptionsUpdated') ||\n        action.type.includes('internal_')\n      ) {\n        return\n      }\n\n      actionTypes.push(action.type)\n    },\n  })\n\n  const { getSubscriptionCount } = storeRef.store.dispatch(\n    api.internalActions.internal_getRTKQSubscriptions(),\n  ) as unknown as SubscriptionSelectors\n\n  const NUM_LIST_ITEMS = 1000\n\n  function ParentComponent() {\n    const listItems = Array.from({ length: NUM_LIST_ITEMS }).map((_, i) => (\n      <UsingA key={i} />\n    ))\n\n    return <>{listItems}</>\n  }\n\n  render(<ParentComponent />, {\n    wrapper: storeRef.wrapper,\n  })\n\n  await act(async () => {\n    vi.advanceTimersByTime(10)\n    vi.runAllTimers()\n  })\n\n  await waitFor(() => {\n    return screen.getAllByText(/42/).length > 0\n  })\n\n  expect(getSubscriptionCount('a(undefined)')).toBe(NUM_LIST_ITEMS)\n\n  expect(actionTypes).toEqual([\n    'api/config/middlewareRegistered',\n    'api/executeQuery/pending',\n    'api/executeQuery/fulfilled',\n  ])\n}, 25_000)\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/copyWithStructuralSharing.test.ts",
    "content": "import { copyWithStructuralSharing } from '@reduxjs/toolkit/query'\n\ntest('equal object from JSON Object', () => {\n  const json = JSON.stringify({\n    a: { b: { c: { d: 1, e: '2', f: true }, g: false }, h: null },\n    i: null,\n  })\n  const objA = JSON.parse(json)\n  const objB = JSON.parse(json)\n  expect(objA).toStrictEqual(objB)\n  expect(objA).not.toBe(objB)\n  const newCopy = copyWithStructuralSharing(objA, objB)\n  expect(newCopy).toBe(objA)\n  expect(newCopy).not.toBe(objB)\n  expect(newCopy).toStrictEqual(objB)\n})\n\ntest('equal object from JSON Object', () => {\n  const json = JSON.stringify({\n    a: { b: { c: { d: 1, e: '2', f: true }, g: false }, h: null },\n    i: null,\n  })\n  const objA = JSON.parse(json)\n  const objB = JSON.parse(json)\n  objB.a.h = 4\n  expect(objA).not.toStrictEqual(objB)\n  expect(objA).not.toBe(objB)\n  expect(objA.a.b).toStrictEqual(objB.a.b)\n  expect(objA.a.b).not.toBe(objB.a.b)\n\n  const newCopy = copyWithStructuralSharing(objA, objB)\n  expect(newCopy).not.toBe(objA)\n  expect(newCopy).not.toStrictEqual(objA)\n  expect(newCopy).toStrictEqual(objB)\n\n  expect(newCopy.a.b).toBe(objA.a.b)\n  expect(newCopy.a.b).not.toBe(objB.a.b)\n  expect(newCopy.a.b).toStrictEqual(objB.a.b)\n})\n\ntest('equal object from JSON Array', () => {\n  const json = JSON.stringify([\n    1,\n    'a',\n    { 2: 'b' },\n    { 3: { 4: 'c' }, d: null },\n    null,\n    5,\n  ])\n  const objA = JSON.parse(json)\n  const objB = JSON.parse(json)\n\n  expect(objA).toStrictEqual(objB)\n  expect(objA).not.toBe(objB)\n  const newCopy = copyWithStructuralSharing(objA, objB)\n  expect(newCopy).toBe(objA)\n  expect(newCopy).not.toBe(objB)\n  expect(newCopy).toStrictEqual(objB)\n})\n\ntest('equal object from JSON Array', () => {\n  const json = JSON.stringify([\n    1,\n    'a',\n    { 2: 'b' },\n    { 3: { 4: 'c' }, d: null },\n    null,\n    5,\n  ])\n  const objA = JSON.parse(json)\n  const objB = JSON.parse(json)\n  objB[2][2] = 'x'\n\n  expect(objA).not.toStrictEqual(objB)\n  expect(objA).not.toBe(objB)\n  const newCopy = copyWithStructuralSharing(objA, objB)\n  expect(newCopy).not.toBe(objA)\n  expect(newCopy).not.toBe(objB)\n  expect(newCopy).toStrictEqual(objB)\n\n  expect(newCopy[3]).toBe(objA[3])\n  expect(newCopy[3]).not.toBe(objB[3])\n  expect(newCopy[3]).toStrictEqual(objB[3])\n\n  expect(newCopy[2]).not.toBe(objA[2])\n  expect(newCopy[2]).not.toBe(objB[2])\n  expect(newCopy[2]).toStrictEqual(objB[2])\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/createApi.test-d.ts",
    "content": "import { setupApiStore } from '@internal/tests/utils/helpers'\nimport type { EntityState, SerializedError } from '@reduxjs/toolkit'\nimport { configureStore, createEntityAdapter } from '@reduxjs/toolkit'\nimport type {\n  DefinitionsFromApi,\n  FetchBaseQueryError,\n  FetchBaseQueryMeta,\n  MutationDefinition,\n  OverrideResultType,\n  QueryDefinition,\n  TagDescription,\n  TagTypesFromApi,\n} from '@reduxjs/toolkit/query'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport * as v from 'valibot'\nimport type { Post } from './mocks/handlers'\n\ndescribe('type tests', () => {\n  test('sensible defaults', () => {\n    const api = createApi({\n      baseQuery: fetchBaseQuery(),\n      endpoints: (build) => ({\n        getUser: build.query<unknown, void>({\n          query(id) {\n            return { url: `user/${id}` }\n          },\n        }),\n        updateUser: build.mutation<unknown, void>({\n          query: () => '',\n        }),\n      }),\n    })\n\n    configureStore({\n      reducer: {\n        [api.reducerPath]: api.reducer,\n      },\n      middleware: (gDM) => gDM().concat(api.middleware),\n    })\n\n    expectTypeOf(api.reducerPath).toEqualTypeOf<'api'>()\n\n    expectTypeOf(api.util.invalidateTags)\n      .parameter(0)\n      .toEqualTypeOf<(null | undefined | TagDescription<never>)[]>()\n  })\n\n  describe('endpoint definition typings', () => {\n    const api = createApi({\n      baseQuery: (from: 'From'): { data: 'To' } | Promise<{ data: 'To' }> => ({\n        data: 'To',\n      }),\n      endpoints: () => ({}),\n      tagTypes: ['typeA', 'typeB'],\n    })\n\n    test('query: query & transformResponse types', () => {\n      api.injectEndpoints({\n        endpoints: (build) => ({\n          query: build.query<'RetVal', 'Arg'>({\n            query: (x: 'Arg') => 'From' as const,\n            transformResponse(r: 'To') {\n              return 'RetVal' as const\n            },\n          }),\n          query1: build.query<'RetVal', 'Arg'>({\n            // @ts-expect-error\n            query: (x: 'Error') => 'From' as const,\n            transformResponse(r: 'To') {\n              return 'RetVal' as const\n            },\n          }),\n          query2: build.query<'RetVal', 'Arg'>({\n            // @ts-expect-error\n            query: (x: 'Arg') => 'Error' as const,\n            transformResponse(r: 'To') {\n              return 'RetVal' as const\n            },\n          }),\n          query3: build.query<'RetVal', 'Arg'>({\n            query: (x: 'Arg') => 'From' as const,\n            // @ts-expect-error\n            transformResponse(r: 'Error') {\n              return 'RetVal' as const\n            },\n          }),\n          query4: build.query<'RetVal', 'Arg'>({\n            query: (x: 'Arg') => 'From' as const,\n            // @ts-expect-error\n            transformResponse(r: 'To') {\n              return 'Error' as const\n            },\n          }),\n          queryInference1: build.query<'RetVal', 'Arg'>({\n            query: (x) => {\n              expectTypeOf(x).toEqualTypeOf<'Arg'>()\n\n              return 'From'\n            },\n            transformResponse(r) {\n              expectTypeOf(r).toEqualTypeOf<'To'>()\n\n              return 'RetVal'\n            },\n          }),\n          queryInference2: (() => {\n            const query = build.query({\n              query: (x: 'Arg') => 'From' as const,\n              transformResponse(r: 'To') {\n                return 'RetVal' as const\n              },\n            })\n\n            expectTypeOf(query).toExtend<\n              QueryDefinition<'Arg', any, any, 'RetVal'>\n            >()\n\n            return query\n          })(),\n        }),\n      })\n    })\n\n    test('mutation: query & transformResponse types', () => {\n      api.injectEndpoints({\n        endpoints: (build) => ({\n          query: build.mutation<'RetVal', 'Arg'>({\n            query: (x: 'Arg') => 'From' as const,\n            transformResponse(r: 'To') {\n              return 'RetVal' as const\n            },\n          }),\n          query1: build.mutation<'RetVal', 'Arg'>({\n            // @ts-expect-error\n            query: (x: 'Error') => 'From' as const,\n            transformResponse(r: 'To') {\n              return 'RetVal' as const\n            },\n          }),\n          query2: build.mutation<'RetVal', 'Arg'>({\n            // @ts-expect-error\n            query: (x: 'Arg') => 'Error' as const,\n            transformResponse(r: 'To') {\n              return 'RetVal' as const\n            },\n          }),\n          query3: build.mutation<'RetVal', 'Arg'>({\n            query: (x: 'Arg') => 'From' as const,\n            // @ts-expect-error\n            transformResponse(r: 'Error') {\n              return 'RetVal' as const\n            },\n          }),\n          query4: build.mutation<'RetVal', 'Arg'>({\n            query: (x: 'Arg') => 'From' as const,\n            // @ts-expect-error\n            transformResponse(r: 'To') {\n              return 'Error' as const\n            },\n          }),\n          mutationInference1: build.mutation<'RetVal', 'Arg'>({\n            query: (x) => {\n              expectTypeOf(x).toEqualTypeOf<'Arg'>()\n\n              return 'From'\n            },\n            transformResponse(r) {\n              expectTypeOf(r).toEqualTypeOf<'To'>()\n\n              return 'RetVal'\n            },\n          }),\n          mutationInference2: (() => {\n            const query = build.mutation({\n              query: (x: 'Arg') => 'From' as const,\n              transformResponse(r: 'To') {\n                return 'RetVal' as const\n              },\n            })\n\n            expectTypeOf(query).toExtend<\n              MutationDefinition<'Arg', any, any, 'RetVal'>\n            >()\n\n            return query\n          })(),\n        }),\n      })\n    })\n\n    describe('enhancing endpoint definitions', () => {\n      const baseQuery = (x: string) => ({ data: 'success' })\n\n      function getNewApi() {\n        return createApi({\n          baseQuery,\n          tagTypes: ['old'],\n          endpoints: (build) => ({\n            query1: build.query<'out1', 'in1'>({ query: (id) => `${id}` }),\n            query2: build.query<'out2', 'in2'>({ query: (id) => `${id}` }),\n            mutation1: build.mutation<'out1', 'in1'>({\n              query: (id) => `${id}`,\n            }),\n            mutation2: build.mutation<'out2', 'in2'>({\n              query: (id) => `${id}`,\n            }),\n          }),\n        })\n      }\n\n      const api1 = getNewApi()\n\n      test('warn on wrong tagType', () => {\n        const storeRef = setupApiStore(api1, undefined, {\n          withoutTestLifecycles: true,\n        })\n\n        api1.enhanceEndpoints({\n          endpoints: {\n            query1: {\n              // @ts-expect-error\n              providesTags: ['new'],\n            },\n            query2: {\n              // @ts-expect-error\n              providesTags: ['missing'],\n            },\n          },\n        })\n\n        const enhanced = api1.enhanceEndpoints({\n          addTagTypes: ['new'],\n          endpoints: {\n            query1: {\n              providesTags: ['new'],\n            },\n            query2: {\n              // @ts-expect-error\n              providesTags: ['missing'],\n            },\n          },\n        })\n\n        storeRef.store.dispatch(api1.endpoints.query1.initiate('in1'))\n\n        storeRef.store.dispatch(api1.endpoints.query2.initiate('in2'))\n\n        enhanced.enhanceEndpoints({\n          endpoints: {\n            query1: {\n              // returned `enhanced` api contains \"new\" entityType\n              providesTags: ['new'],\n            },\n            query2: {\n              // @ts-expect-error\n              providesTags: ['missing'],\n            },\n          },\n        })\n      })\n\n      test('modify', () => {\n        const storeRef = setupApiStore(api1, undefined, {\n          withoutTestLifecycles: true,\n        })\n\n        api1.enhanceEndpoints({\n          endpoints: {\n            query1: {\n              query: (x) => {\n                expectTypeOf(x).toEqualTypeOf<'in1'>()\n\n                return 'modified1'\n              },\n            },\n            query2(definition) {\n              definition.query = (x) => {\n                expectTypeOf(x).toEqualTypeOf<'in2'>()\n\n                return 'modified2'\n              }\n            },\n            mutation1: {\n              query: (x) => {\n                expectTypeOf(x).toEqualTypeOf<'in1'>()\n\n                return 'modified1'\n              },\n            },\n            mutation2(definition) {\n              definition.query = (x) => {\n                expectTypeOf(x).toEqualTypeOf<'in2'>()\n\n                return 'modified2'\n              }\n            },\n            // @ts-expect-error\n            nonExisting: {},\n          },\n        })\n\n        storeRef.store.dispatch(api1.endpoints.query1.initiate('in1'))\n        storeRef.store.dispatch(api1.endpoints.query2.initiate('in2'))\n        storeRef.store.dispatch(api1.endpoints.mutation1.initiate('in1'))\n        storeRef.store.dispatch(api1.endpoints.mutation2.initiate('in2'))\n      })\n\n      test('updated transform response types', async () => {\n        const baseApi = createApi({\n          baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n          tagTypes: ['old'],\n          endpoints: (build) => ({\n            query1: build.query<'out1', void>({ query: () => 'success' }),\n            mutation1: build.mutation<'out1', void>({ query: () => 'success' }),\n          }),\n        })\n\n        type Transformed = { value: string }\n\n        type Definitions = DefinitionsFromApi<typeof api1>\n\n        type TagTypes = TagTypesFromApi<typeof api1>\n\n        type Q1Definition = OverrideResultType<\n          Definitions['query1'],\n          Transformed\n        >\n\n        type M1Definition = OverrideResultType<\n          Definitions['mutation1'],\n          Transformed\n        >\n\n        type UpdatedDefinitions = Omit<Definitions, 'query1' | 'mutation1'> & {\n          query1: Q1Definition\n          mutation1: M1Definition\n        }\n\n        const enhancedApi = baseApi.enhanceEndpoints<\n          TagTypes,\n          UpdatedDefinitions\n        >({\n          endpoints: {\n            query1: {\n              transformResponse: (a, b, c) => ({\n                value: 'transformed',\n              }),\n            },\n            mutation1: {\n              transformResponse: (a, b, c) => ({\n                value: 'transformed',\n              }),\n            },\n          },\n        })\n\n        const storeRef = setupApiStore(enhancedApi, undefined, {\n          withoutTestLifecycles: true,\n        })\n\n        const queryResponse = await storeRef.store.dispatch(\n          enhancedApi.endpoints.query1.initiate(),\n        )\n\n        expectTypeOf(queryResponse.data).toExtend<Transformed | undefined>()\n\n        const mutationResponse = await storeRef.store.dispatch(\n          enhancedApi.endpoints.mutation1.initiate(),\n        )\n\n        expectTypeOf(mutationResponse).toExtend<\n          | { data: Transformed }\n          | { error: FetchBaseQueryError | SerializedError }\n        >()\n      })\n    })\n    describe('endpoint schemas', () => {\n      const argSchema = v.object({ id: v.number() })\n      const postSchema = v.object({\n        id: v.number(),\n        title: v.string(),\n        body: v.string(),\n      }) satisfies v.GenericSchema<Post>\n      const errorResponseSchema = v.object({\n        status: v.number(),\n        data: v.unknown(),\n      }) satisfies v.GenericSchema<FetchBaseQueryError>\n      const metaSchema = v.object({\n        request: v.instance(Request),\n        response: v.optional(v.instance(Response)),\n      }) satisfies v.GenericSchema<FetchBaseQueryMeta>\n      test('schemas must match', () => {\n        createApi({\n          baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n          endpoints: (build) => ({\n            query: build.query<Post, { id: number }>({\n              query: ({ id }) => `/post/${id}`,\n              argSchema,\n              responseSchema: postSchema,\n              errorResponseSchema,\n              metaSchema,\n            }),\n            bothMismatch: build.query<Post, { id: number }>({\n              query: ({ id }) => `/post/${id}`,\n              // @ts-expect-error wrong schema\n              argSchema: v.object({ id: v.string() }),\n              // @ts-expect-error wrong schema\n              responseSchema: v.object({ id: v.string() }),\n              // @ts-expect-error wrong schema\n              errorResponseSchema: v.object({ status: v.string() }),\n              // @ts-expect-error wrong schema\n              metaSchema: v.object({ request: v.string() }),\n            }),\n            inputMismatch: build.query<Post, { id: number }>({\n              query: ({ id }) => `/post/${id}`,\n              // @ts-expect-error can't expect different input\n              argSchema: v.object({\n                id: v.pipe(v.string(), v.transform(Number), v.number()),\n              }),\n              // @ts-expect-error can't expect different input\n              responseSchema: v.object({\n                ...postSchema.entries,\n                id: v.pipe(v.string(), v.transform(Number)),\n              }) satisfies v.GenericSchema<any, Post>,\n              // @ts-expect-error can't expect different input\n              errorResponseSchema: v.object({\n                ...errorResponseSchema.entries,\n                status: v.pipe(v.string(), v.transform(Number)),\n              }) satisfies v.GenericSchema<any, FetchBaseQueryError>,\n              // @ts-expect-error can't expect different input\n              metaSchema: v.object({\n                ...metaSchema.entries,\n                request: v.pipe(\n                  v.string(),\n                  v.transform((url) => new Request(url)),\n                ),\n              }) satisfies v.GenericSchema<any, FetchBaseQueryMeta>,\n            }),\n            outputMismatch: build.query<Post, { id: number }>({\n              query: ({ id }) => `/post/${id}`,\n              // @ts-expect-error can't provide different output\n              argSchema: v.object({\n                id: v.pipe(v.number(), v.transform(String)),\n              }),\n              // @ts-expect-error can't provide different output\n              responseSchema: v.object({\n                ...postSchema.entries,\n                id: v.pipe(v.number(), v.transform(String)),\n              }) satisfies v.GenericSchema<Post, any>,\n              // @ts-expect-error can't provide different output\n              errorResponseSchema: v.object({\n                ...errorResponseSchema.entries,\n                status: v.pipe(v.number(), v.transform(String)),\n              }) satisfies v.GenericSchema<FetchBaseQueryError, any>,\n              // @ts-expect-error can't provide different output\n              metaSchema: v.object({\n                ...metaSchema.entries,\n                request: v.pipe(\n                  v.instance(Request),\n                  v.transform((r) => r.url),\n                ),\n              }) satisfies v.GenericSchema<FetchBaseQueryMeta, any>,\n            }),\n          }),\n        })\n      })\n      test('schemas as a source of inference', () => {\n        const postAdapter = createEntityAdapter<Post>()\n        const api = createApi({\n          baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n          endpoints: (build) => ({\n            query: build.query({\n              query: ({ id }: { id: number }) => `/post/${id}`,\n              responseSchema: postSchema,\n            }),\n            query2: build.query({\n              query: (arg) => {\n                expectTypeOf(arg).toEqualTypeOf<{ id: number }>()\n                return `/post/${arg.id}`\n              },\n              argSchema,\n              responseSchema: postSchema,\n            }),\n            query3: build.query({\n              query: (_arg: void) => `/posts`,\n              rawResponseSchema: v.array(postSchema),\n              transformResponse: (posts) => {\n                expectTypeOf(posts).toEqualTypeOf<Post[]>()\n                return postAdapter.getInitialState(undefined, posts)\n              },\n            }),\n          }),\n        })\n\n        expectTypeOf(api.endpoints.query.Types.QueryArg).toEqualTypeOf<{\n          id: number\n        }>()\n        expectTypeOf(api.endpoints.query.Types.ResultType).toEqualTypeOf<Post>()\n        expectTypeOf(api.endpoints.query.Types.RawResultType).toBeAny()\n\n        expectTypeOf(api.endpoints.query2.Types.QueryArg).toEqualTypeOf<{\n          id: number\n        }>()\n        expectTypeOf(\n          api.endpoints.query2.Types.ResultType,\n        ).toEqualTypeOf<Post>()\n        expectTypeOf(api.endpoints.query2.Types.RawResultType).toBeAny()\n\n        expectTypeOf(api.endpoints.query3.Types.QueryArg).toBeVoid()\n        expectTypeOf(api.endpoints.query3.Types.ResultType).toEqualTypeOf<\n          EntityState<Post, Post['id']>\n        >()\n        expectTypeOf(api.endpoints.query3.Types.RawResultType).toEqualTypeOf<\n          Post[]\n        >()\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/createApi.test.ts",
    "content": "import { noop } from '@internal/listenerMiddleware/utils'\nimport { server } from '@internal/query/tests/mocks/server'\nimport {\n  getSerializedHeaders,\n  setupApiStore,\n} from '@internal/tests/utils/helpers'\nimport type { SerializedError } from '@reduxjs/toolkit'\nimport { configureStore, createAction, createReducer } from '@reduxjs/toolkit'\nimport type {\n  DefinitionsFromApi,\n  FetchBaseQueryError,\n  FetchBaseQueryMeta,\n  OverrideResultType,\n  SchemaFailureConverter,\n  SchemaFailureHandler,\n  SchemaType,\n  SerializeQueryArgs,\n  TagTypesFromApi,\n} from '@reduxjs/toolkit/query'\nimport {\n  createApi,\n  fetchBaseQuery,\n  NamedSchemaError,\n} from '@reduxjs/toolkit/query'\nimport { delay, http, HttpResponse } from 'msw'\nimport nodeFetch from 'node-fetch'\nimport * as v from 'valibot'\n\nbeforeAll(() => {\n  vi.stubEnv('NODE_ENV', 'development')\n\n  return vi.unstubAllEnvs\n})\n\nconst consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n\nafterEach(() => {\n  vi.clearAllMocks()\n  server.resetHandlers()\n})\n\nafterAll(() => {\n  vi.restoreAllMocks()\n})\n\nfunction paginate<T>(array: T[], page_size: number, page_number: number) {\n  // human-readable page numbers usually start with 1, so we reduce 1 in the first argument\n  return array.slice((page_number - 1) * page_size, page_number * page_size)\n}\n\ntest('sensible defaults', () => {\n  const api = createApi({\n    baseQuery: fetchBaseQuery(),\n    endpoints: (build) => ({\n      getUser: build.query<unknown, void>({\n        query(id) {\n          return { url: `user/${id}` }\n        },\n      }),\n      updateUser: build.mutation<unknown, void>({\n        query: () => '',\n      }),\n    }),\n  })\n  configureStore({\n    reducer: {\n      [api.reducerPath]: api.reducer,\n    },\n    middleware: (gDM) => gDM().concat(api.middleware),\n  })\n  expect(api.reducerPath).toBe('api')\n\n  expect(api.endpoints.getUser.name).toBe('getUser')\n  expect(api.endpoints.updateUser.name).toBe('updateUser')\n})\n\ndescribe('wrong tagTypes log errors', () => {\n  const baseQuery = vi.fn()\n  const api = createApi({\n    baseQuery,\n    tagTypes: ['User'],\n    endpoints: (build) => ({\n      provideNothing: build.query<unknown, void>({\n        query: () => '',\n      }),\n      provideTypeString: build.query<unknown, void>({\n        query: () => '',\n        providesTags: ['User'],\n      }),\n      provideTypeWithId: build.query<unknown, void>({\n        query: () => '',\n        providesTags: [{ type: 'User', id: 5 }],\n      }),\n      provideTypeWithIdAndCallback: build.query<unknown, void>({\n        query: () => '',\n        providesTags: () => [{ type: 'User', id: 5 }],\n      }),\n      provideWrongTypeString: build.query<unknown, void>({\n        query: () => '',\n        // @ts-expect-error\n        providesTags: ['Users'],\n      }),\n      provideWrongTypeWithId: build.query<unknown, void>({\n        query: () => '',\n        // @ts-expect-error\n        providesTags: [{ type: 'Users', id: 5 }],\n      }),\n      provideWrongTypeWithIdAndCallback: build.query<unknown, void>({\n        query: () => '',\n        // @ts-expect-error\n        providesTags: () => [{ type: 'Users', id: 5 }],\n      }),\n      invalidateNothing: build.query<unknown, void>({\n        query: () => '',\n      }),\n      invalidateTypeString: build.mutation<unknown, void>({\n        query: () => '',\n        invalidatesTags: ['User'],\n      }),\n      invalidateTypeWithId: build.mutation<unknown, void>({\n        query: () => '',\n        invalidatesTags: [{ type: 'User', id: 5 }],\n      }),\n      invalidateTypeWithIdAndCallback: build.mutation<unknown, void>({\n        query: () => '',\n        invalidatesTags: () => [{ type: 'User', id: 5 }],\n      }),\n\n      invalidateWrongTypeString: build.mutation<unknown, void>({\n        query: () => '',\n        // @ts-expect-error\n        invalidatesTags: ['Users'],\n      }),\n      invalidateWrongTypeWithId: build.mutation<unknown, void>({\n        query: () => '',\n        // @ts-expect-error\n        invalidatesTags: [{ type: 'Users', id: 5 }],\n      }),\n      invalidateWrongTypeWithIdAndCallback: build.mutation<unknown, void>({\n        query: () => '',\n        // @ts-expect-error\n        invalidatesTags: () => [{ type: 'Users', id: 5 }],\n      }),\n    }),\n  })\n  const store = configureStore({\n    reducer: {\n      [api.reducerPath]: api.reducer,\n    },\n    middleware: (gDM) => gDM().concat(api.middleware),\n  })\n\n  beforeEach(() => {\n    baseQuery.mockResolvedValue({ data: 'foo' })\n  })\n\n  test.each<[keyof typeof api.endpoints, boolean?]>([\n    ['provideNothing', false],\n    ['provideTypeString', false],\n    ['provideTypeWithId', false],\n    ['provideTypeWithIdAndCallback', false],\n    ['provideWrongTypeString', true],\n    ['provideWrongTypeWithId', true],\n    ['provideWrongTypeWithIdAndCallback', true],\n    ['invalidateNothing', false],\n    ['invalidateTypeString', false],\n    ['invalidateTypeWithId', false],\n    ['invalidateTypeWithIdAndCallback', false],\n    ['invalidateWrongTypeString', true],\n    ['invalidateWrongTypeWithId', true],\n    ['invalidateWrongTypeWithIdAndCallback', true],\n  ])(`endpoint %s should log an error? %s`, async (endpoint, shouldError) => {\n    vi.stubEnv('NODE_ENV', 'development')\n\n    // @ts-ignore\n    store.dispatch(api.endpoints[endpoint].initiate())\n    let result: { status: string }\n    do {\n      await delay(5)\n      // @ts-ignore\n      result = api.endpoints[endpoint].select()(store.getState())\n    } while (result.status === 'pending')\n\n    if (shouldError) {\n      expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n        \"Tag type 'Users' was used, but not specified in `tagTypes`!\",\n      )\n    } else {\n      expect(consoleErrorSpy).not.toHaveBeenCalled()\n    }\n  })\n})\n\ndescribe('endpoint definition typings', () => {\n  const api = createApi({\n    baseQuery: (from: 'From'): { data: 'To' } | Promise<{ data: 'To' }> => ({\n      data: 'To',\n    }),\n    endpoints: () => ({}),\n    tagTypes: ['typeA', 'typeB'],\n  })\n  test('query: query & transformResponse types', () => {\n    api.injectEndpoints({\n      endpoints: (build) => ({\n        query: build.query<'RetVal', 'Arg'>({\n          query: (x: 'Arg') => 'From' as const,\n          transformResponse(r: 'To') {\n            return 'RetVal' as const\n          },\n        }),\n        query1: build.query<'RetVal', 'Arg'>({\n          // @ts-expect-error\n          query: (x: 'Error') => 'From' as const,\n          transformResponse(r: 'To') {\n            return 'RetVal' as const\n          },\n        }),\n        query2: build.query<'RetVal', 'Arg'>({\n          // @ts-expect-error\n          query: (x: 'Arg') => 'Error' as const,\n          transformResponse(r: 'To') {\n            return 'RetVal' as const\n          },\n        }),\n        query3: build.query<'RetVal', 'Arg'>({\n          query: (x: 'Arg') => 'From' as const,\n          // @ts-expect-error\n          transformResponse(r: 'Error') {\n            return 'RetVal' as const\n          },\n        }),\n        query4: build.query<'RetVal', 'Arg'>({\n          query: (x: 'Arg') => 'From' as const,\n          // @ts-expect-error\n          transformResponse(r: 'To') {\n            return 'Error' as const\n          },\n        }),\n        queryInference1: build.query<'RetVal', 'Arg'>({\n          query: (x) => {\n            return 'From'\n          },\n          transformResponse(r) {\n            return 'RetVal'\n          },\n        }),\n        queryInference2: (() => {\n          const query = build.query({\n            query: (x: 'Arg') => 'From' as const,\n            transformResponse(r: 'To') {\n              return 'RetVal' as const\n            },\n          })\n          return query\n        })(),\n      }),\n    })\n  })\n  test('mutation: query & transformResponse types', () => {\n    api.injectEndpoints({\n      endpoints: (build) => ({\n        query: build.mutation<'RetVal', 'Arg'>({\n          query: (x: 'Arg') => 'From' as const,\n          transformResponse(r: 'To') {\n            return 'RetVal' as const\n          },\n        }),\n        query1: build.mutation<'RetVal', 'Arg'>({\n          // @ts-expect-error\n          query: (x: 'Error') => 'From' as const,\n          transformResponse(r: 'To') {\n            return 'RetVal' as const\n          },\n        }),\n        query2: build.mutation<'RetVal', 'Arg'>({\n          // @ts-expect-error\n          query: (x: 'Arg') => 'Error' as const,\n          transformResponse(r: 'To') {\n            return 'RetVal' as const\n          },\n        }),\n        query3: build.mutation<'RetVal', 'Arg'>({\n          query: (x: 'Arg') => 'From' as const,\n          // @ts-expect-error\n          transformResponse(r: 'Error') {\n            return 'RetVal' as const\n          },\n        }),\n        query4: build.mutation<'RetVal', 'Arg'>({\n          query: (x: 'Arg') => 'From' as const,\n          // @ts-expect-error\n          transformResponse(r: 'To') {\n            return 'Error' as const\n          },\n        }),\n        mutationInference1: build.mutation<'RetVal', 'Arg'>({\n          query: (x) => {\n            return 'From'\n          },\n          transformResponse(r) {\n            return 'RetVal'\n          },\n        }),\n        mutationInference2: (() => {\n          const query = build.mutation({\n            query: (x: 'Arg') => 'From' as const,\n            transformResponse(r: 'To') {\n              return 'RetVal' as const\n            },\n          })\n          return query\n        })(),\n      }),\n    })\n  })\n\n  describe('enhancing endpoint definitions', () => {\n    const baseQuery = vi.fn((x: string) => ({ data: 'success' }))\n    const commonBaseQueryApi = {\n      dispatch: expect.any(Function),\n      endpoint: expect.any(String),\n      abort: expect.any(Function),\n      extra: undefined,\n      forced: expect.any(Boolean),\n      getState: expect.any(Function),\n      signal: expect.any(Object),\n      type: expect.any(String),\n      queryCacheKey: expect.any(String),\n    }\n    beforeEach(() => {\n      baseQuery.mockClear()\n    })\n    function getNewApi() {\n      return createApi({\n        baseQuery,\n        tagTypes: ['old'],\n        endpoints: (build) => ({\n          query1: build.query<'out1', 'in1'>({ query: (id) => `${id}` }),\n          query2: build.query<'out2', 'in2'>({ query: (id) => `${id}` }),\n          mutation1: build.mutation<'out1', 'in1'>({ query: (id) => `${id}` }),\n          mutation2: build.mutation<'out2', 'in2'>({ query: (id) => `${id}` }),\n        }),\n      })\n    }\n    let api = getNewApi()\n    beforeEach(() => {\n      api = getNewApi()\n    })\n\n    test('pre-modification behavior', async () => {\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      storeRef.store.dispatch(api.endpoints.query1.initiate('in1'))\n      storeRef.store.dispatch(api.endpoints.query2.initiate('in2'))\n      storeRef.store.dispatch(api.endpoints.mutation1.initiate('in1'))\n      storeRef.store.dispatch(api.endpoints.mutation2.initiate('in2'))\n\n      expect(baseQuery.mock.calls).toEqual([\n        [\n          'in1',\n          {\n            dispatch: expect.any(Function),\n            endpoint: expect.any(String),\n            getState: expect.any(Function),\n            signal: expect.any(Object),\n            abort: expect.any(Function),\n            forced: expect.any(Boolean),\n            type: expect.any(String),\n            queryCacheKey: expect.any(String),\n          },\n          undefined,\n        ],\n        [\n          'in2',\n          {\n            dispatch: expect.any(Function),\n            endpoint: expect.any(String),\n            getState: expect.any(Function),\n            signal: expect.any(Object),\n            abort: expect.any(Function),\n            forced: expect.any(Boolean),\n            type: expect.any(String),\n            queryCacheKey: expect.any(String),\n          },\n          undefined,\n        ],\n        [\n          'in1',\n          {\n            dispatch: expect.any(Function),\n            endpoint: expect.any(String),\n            getState: expect.any(Function),\n            signal: expect.any(Object),\n            abort: expect.any(Function),\n            // forced: undefined,\n            type: expect.any(String),\n          },\n          undefined,\n        ],\n        [\n          'in2',\n          {\n            dispatch: expect.any(Function),\n            endpoint: expect.any(String),\n            getState: expect.any(Function),\n            signal: expect.any(Object),\n            abort: expect.any(Function),\n            // forced: undefined,\n            type: expect.any(String),\n          },\n          undefined,\n        ],\n      ])\n    })\n\n    test('warn on wrong tagType', async () => {\n      vi.stubEnv('NODE_ENV', 'development')\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      // only type-test this part\n      if (2 > 1) {\n        api.enhanceEndpoints({\n          endpoints: {\n            query1: {\n              // @ts-expect-error\n              providesTags: ['new'],\n            },\n            query2: {\n              // @ts-expect-error\n              providesTags: ['missing'],\n            },\n          },\n        })\n      }\n\n      const enhanced = api.enhanceEndpoints({\n        addTagTypes: ['new'],\n        endpoints: {\n          query1: {\n            providesTags: ['new'],\n          },\n          query2: {\n            // @ts-expect-error\n            providesTags: ['missing'],\n          },\n        },\n      })\n\n      storeRef.store.dispatch(api.endpoints.query1.initiate('in1'))\n      await delay(1)\n      expect(consoleErrorSpy).not.toHaveBeenCalled()\n\n      storeRef.store.dispatch(api.endpoints.query2.initiate('in2'))\n      await delay(1)\n\n      expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n      expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n        \"Tag type 'missing' was used, but not specified in `tagTypes`!\",\n      )\n\n      // only type-test this part\n      if (2 > 1) {\n        enhanced.enhanceEndpoints({\n          endpoints: {\n            query1: {\n              // returned `enhanced` api contains \"new\" enitityType\n              providesTags: ['new'],\n            },\n            query2: {\n              // @ts-expect-error\n              providesTags: ['missing'],\n            },\n          },\n        })\n      }\n    })\n\n    test('modify', () => {\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      api.enhanceEndpoints({\n        endpoints: {\n          query1: {\n            query: (x) => {\n              return 'modified1'\n            },\n          },\n          query2(definition) {\n            definition.query = (x) => {\n              return 'modified2'\n            }\n          },\n          mutation1: {\n            query: (x) => {\n              return 'modified1'\n            },\n          },\n          mutation2(definition) {\n            definition.query = (x) => {\n              return 'modified2'\n            }\n          },\n          // @ts-expect-error\n          nonExisting: {},\n        },\n      })\n\n      storeRef.store.dispatch(api.endpoints.query1.initiate('in1'))\n      storeRef.store.dispatch(api.endpoints.query2.initiate('in2'))\n      storeRef.store.dispatch(api.endpoints.mutation1.initiate('in1'))\n      storeRef.store.dispatch(api.endpoints.mutation2.initiate('in2'))\n\n      expect(baseQuery.mock.calls).toEqual([\n        ['modified1', commonBaseQueryApi, undefined],\n        ['modified2', commonBaseQueryApi, undefined],\n        [\n          'modified1',\n          {\n            ...commonBaseQueryApi,\n            forced: undefined,\n            queryCacheKey: undefined,\n          },\n          undefined,\n        ],\n        [\n          'modified2',\n          {\n            ...commonBaseQueryApi,\n            forced: undefined,\n            queryCacheKey: undefined,\n          },\n          undefined,\n        ],\n      ])\n    })\n\n    test('updated transform response types', async () => {\n      const baseApi = createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n        tagTypes: ['old'],\n        endpoints: (build) => ({\n          query1: build.query<'out1', void>({ query: () => 'success' }),\n          mutation1: build.mutation<'out1', void>({ query: () => 'success' }),\n        }),\n      })\n\n      type Transformed = { value: string }\n\n      type Definitions = DefinitionsFromApi<typeof api>\n      type TagTypes = TagTypesFromApi<typeof api>\n\n      type Q1Definition = OverrideResultType<Definitions['query1'], Transformed>\n      type M1Definition = OverrideResultType<\n        Definitions['mutation1'],\n        Transformed\n      >\n\n      type UpdatedDefitions = Omit<Definitions, 'query1' | 'mutation1'> & {\n        query1: Q1Definition\n        mutation1: M1Definition\n      }\n\n      const enhancedApi = baseApi.enhanceEndpoints<TagTypes, UpdatedDefitions>({\n        endpoints: {\n          query1: {\n            transformResponse: (a, b, c) => ({\n              value: 'transformed',\n            }),\n          },\n          mutation1: {\n            transformResponse: (a, b, c) => ({\n              value: 'transformed',\n            }),\n          },\n        },\n      })\n\n      const storeRef = setupApiStore(enhancedApi, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      const queryResponse = await storeRef.store.dispatch(\n        enhancedApi.endpoints.query1.initiate(),\n      )\n      expect(queryResponse.data).toEqual({ value: 'transformed' })\n\n      const mutationResponse = await storeRef.store.dispatch(\n        enhancedApi.endpoints.mutation1.initiate(),\n      )\n      expect('data' in mutationResponse && mutationResponse.data).toEqual({\n        value: 'transformed',\n      })\n    })\n  })\n})\n\ndescribe('additional transformResponse behaviors', () => {\n  type SuccessResponse = { value: 'success' }\n  type EchoResponseData = { banana: 'bread' }\n  type ErrorResponse = { value: 'error' }\n  const api = createApi({\n    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n    endpoints: (build) => ({\n      echo: build.mutation({\n        query: () => ({ method: 'PUT', url: '/echo' }),\n      }),\n      mutation: build.mutation({\n        query: () => ({\n          url: '/echo',\n          method: 'POST',\n          body: { nested: { banana: 'bread' } },\n        }),\n        transformResponse: (response: { body: { nested: EchoResponseData } }) =>\n          response.body.nested,\n      }),\n      mutationWithError: build.mutation({\n        query: () => ({\n          url: '/error',\n          method: 'POST',\n        }),\n        transformErrorResponse: (response) => {\n          const data = response.data as ErrorResponse\n          return data.value\n        },\n      }),\n      mutationWithMeta: build.mutation({\n        query: () => ({\n          url: '/echo',\n          method: 'POST',\n          body: { nested: { banana: 'bread' } },\n        }),\n        transformResponse: (\n          response: { body: { nested: EchoResponseData } },\n          meta,\n        ) => {\n          return {\n            ...response.body.nested,\n            meta: {\n              request: { headers: getSerializedHeaders(meta?.request.headers) },\n              response: {\n                headers: getSerializedHeaders(meta?.response?.headers),\n              },\n            },\n          }\n        },\n      }),\n      query: build.query<SuccessResponse & EchoResponseData, void>({\n        query: () => '/success',\n        transformResponse: async (response: SuccessResponse) => {\n          const res: any = await nodeFetch('https://example.com/echo', {\n            method: 'POST',\n            body: JSON.stringify({ banana: 'bread' }),\n          }).then((res) => res.json())\n\n          const additionalData = res.body as EchoResponseData\n          return { ...response, ...additionalData }\n        },\n      }),\n      queryWithMeta: build.query<SuccessResponse, void>({\n        query: () => '/success',\n        transformResponse: async (response: SuccessResponse, meta) => {\n          return {\n            ...response,\n            meta: {\n              request: { headers: getSerializedHeaders(meta?.request.headers) },\n              response: {\n                headers: getSerializedHeaders(meta?.response?.headers),\n              },\n            },\n          }\n        },\n      }),\n    }),\n  })\n\n  const storeRef = setupApiStore(api)\n\n  test('transformResponse handles an async transformation and returns the merged data (query)', async () => {\n    const result = await storeRef.store.dispatch(api.endpoints.query.initiate())\n\n    expect(result.data).toEqual({ value: 'success', banana: 'bread' })\n  })\n\n  test('transformResponse transforms a response from a mutation', async () => {\n    const result = await storeRef.store.dispatch(\n      api.endpoints.mutation.initiate({}),\n    )\n\n    expect('data' in result && result.data).toEqual({ banana: 'bread' })\n  })\n\n  test('transformResponse transforms a response from a mutation with an error', async () => {\n    const result = await storeRef.store.dispatch(\n      api.endpoints.mutationWithError.initiate({}),\n    )\n\n    expect('error' in result && result.error).toEqual('error')\n  })\n\n  test('transformResponse can inject baseQuery meta into the end result from a mutation', async () => {\n    const result = await storeRef.store.dispatch(\n      api.endpoints.mutationWithMeta.initiate({}),\n    )\n\n    expect('data' in result && result.data).toEqual({\n      banana: 'bread',\n      meta: {\n        request: {\n          headers: {\n            accept: 'application/json',\n            'content-type': 'application/json',\n          },\n        },\n        response: {\n          headers: {\n            'content-type': 'application/json',\n          },\n        },\n      },\n    })\n  })\n\n  test('transformResponse can inject baseQuery meta into the end result from a query', async () => {\n    const result = await storeRef.store.dispatch(\n      api.endpoints.queryWithMeta.initiate(),\n    )\n\n    expect(result.data).toEqual({\n      value: 'success',\n      meta: {\n        request: {\n          headers: {\n            accept: 'application/json',\n          },\n        },\n        response: {\n          headers: {\n            'content-type': 'application/json',\n          },\n        },\n      },\n    })\n  })\n})\n\ndescribe('query endpoint lifecycles - onStart, onSuccess, onError', () => {\n  const initialState = {\n    count: null as null | number,\n  }\n  const setCount = createAction<number>('setCount')\n  const testReducer = createReducer(initialState, (builder) => {\n    builder.addCase(setCount, (state, action) => {\n      state.count = action.payload\n    })\n  })\n\n  type SuccessResponse = { value: 'success' }\n  const api = createApi({\n    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n    endpoints: (build) => ({\n      echo: build.mutation({\n        query: () => ({ method: 'PUT', url: '/echo' }),\n      }),\n      query: build.query<SuccessResponse, void>({\n        query: () => '/success',\n        async onQueryStarted(_, api) {\n          api.dispatch(setCount(0))\n          try {\n            await api.queryFulfilled\n            api.dispatch(setCount(1))\n          } catch {\n            api.dispatch(setCount(-1))\n          }\n        },\n      }),\n      mutation: build.mutation<SuccessResponse, void>({\n        query: () => ({ url: '/success', method: 'POST' }),\n        async onQueryStarted(_, api) {\n          api.dispatch(setCount(0))\n          try {\n            await api.queryFulfilled\n            api.dispatch(setCount(1))\n          } catch {\n            api.dispatch(setCount(-1))\n          }\n        },\n      }),\n    }),\n  })\n\n  const storeRef = setupApiStore(api, { testReducer })\n\n  test('query lifecycle events fire properly', async () => {\n    // We intentionally fail the first request so we can test all lifecycles\n    server.use(\n      http.get(\n        'https://example.com/success',\n        () => HttpResponse.json({ value: 'failed' }, { status: 500 }),\n        { once: true },\n      ),\n    )\n\n    expect(storeRef.store.getState().testReducer.count).toBe(null)\n    const failAttempt = storeRef.store.dispatch(api.endpoints.query.initiate())\n    expect(storeRef.store.getState().testReducer.count).toBe(0)\n    await failAttempt\n    await delay(10)\n    expect(storeRef.store.getState().testReducer.count).toBe(-1)\n\n    const successAttempt = storeRef.store.dispatch(\n      api.endpoints.query.initiate(),\n    )\n    expect(storeRef.store.getState().testReducer.count).toBe(0)\n    await successAttempt\n    await delay(10)\n    expect(storeRef.store.getState().testReducer.count).toBe(1)\n  })\n\n  test('mutation lifecycle events fire properly', async () => {\n    // We intentionally fail the first request so we can test all lifecycles\n    server.use(\n      http.post(\n        'https://example.com/success',\n        () => HttpResponse.json({ value: 'failed' }, { status: 500 }),\n        { once: true },\n      ),\n    )\n\n    expect(storeRef.store.getState().testReducer.count).toBe(null)\n    const failAttempt = storeRef.store.dispatch(\n      api.endpoints.mutation.initiate(),\n    )\n    expect(storeRef.store.getState().testReducer.count).toBe(0)\n    await failAttempt\n    expect(storeRef.store.getState().testReducer.count).toBe(-1)\n\n    const successAttempt = storeRef.store.dispatch(\n      api.endpoints.mutation.initiate(),\n    )\n    expect(storeRef.store.getState().testReducer.count).toBe(0)\n    await successAttempt\n    expect(storeRef.store.getState().testReducer.count).toBe(1)\n  })\n})\n\ntest('providesTags and invalidatesTags can use baseQueryMeta', async () => {\n  let _meta: FetchBaseQueryMeta | undefined\n\n  type SuccessResponse = { value: 'success' }\n\n  const api = createApi({\n    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n    tagTypes: ['success'],\n    endpoints: (build) => ({\n      query: build.query<SuccessResponse, void>({\n        query: () => '/success',\n        providesTags: (_result, _error, _arg, meta) => {\n          _meta = meta\n          return ['success']\n        },\n      }),\n      mutation: build.mutation<SuccessResponse, void>({\n        query: () => ({ url: '/success', method: 'POST' }),\n        invalidatesTags: (_result, _error, _arg, meta) => {\n          _meta = meta\n          return ['success']\n        },\n      }),\n    }),\n  })\n\n  const storeRef = setupApiStore(api, undefined, {\n    withoutTestLifecycles: true,\n  })\n\n  await storeRef.store.dispatch(api.endpoints.query.initiate())\n  expect('request' in _meta! && 'response' in _meta!).toBe(true)\n\n  _meta = undefined\n\n  await storeRef.store.dispatch(api.endpoints.mutation.initiate())\n\n  expect('request' in _meta! && 'response' in _meta!).toBe(true)\n})\n\ndescribe('structuralSharing flag behaviors', () => {\n  type SuccessResponse = { value: 'success' }\n\n  const api = createApi({\n    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n    tagTypes: ['success'],\n    endpoints: (build) => ({\n      enabled: build.query<SuccessResponse, void>({\n        query: () => '/success',\n      }),\n      disabled: build.query<SuccessResponse, void>({\n        query: () => ({ url: '/success' }),\n        structuralSharing: false,\n      }),\n    }),\n  })\n\n  const storeRef = setupApiStore(api)\n\n  it('enables structural sharing for query endpoints by default', async () => {\n    await storeRef.store.dispatch(api.endpoints.enabled.initiate())\n    const firstRef = api.endpoints.enabled.select()(storeRef.store.getState())\n\n    await storeRef.store.dispatch(\n      api.endpoints.enabled.initiate(undefined, { forceRefetch: true }),\n    )\n\n    const secondRef = api.endpoints.enabled.select()(storeRef.store.getState())\n\n    expect(firstRef.requestId).not.toEqual(secondRef.requestId)\n    expect(firstRef.data === secondRef.data).toBeTruthy()\n  })\n\n  it('allows a query endpoint to opt-out of structural sharing', async () => {\n    await storeRef.store.dispatch(api.endpoints.disabled.initiate())\n    const firstRef = api.endpoints.disabled.select()(storeRef.store.getState())\n\n    await storeRef.store.dispatch(\n      api.endpoints.disabled.initiate(undefined, { forceRefetch: true }),\n    )\n\n    const secondRef = api.endpoints.disabled.select()(storeRef.store.getState())\n\n    expect(firstRef.requestId).not.toEqual(secondRef.requestId)\n    expect(firstRef.data === secondRef.data).toBeFalsy()\n  })\n})\n\ndescribe('custom serializeQueryArgs per endpoint', () => {\n  const customArgsSerializer: SerializeQueryArgs<number> = ({\n    endpointName,\n    queryArgs,\n  }) => `${endpointName}-${queryArgs}`\n\n  type SuccessResponse = { value: 'success' }\n\n  const serializer1 = vi.fn(customArgsSerializer)\n\n  interface MyApiClient {\n    fetchPost: (id: string) => Promise<SuccessResponse>\n  }\n\n  const dummyClient: MyApiClient = {\n    async fetchPost() {\n      return { value: 'success' }\n    },\n  }\n\n  const api = createApi({\n    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n    serializeQueryArgs: ({ endpointName, queryArgs }) =>\n      `base-${endpointName}-${queryArgs}`,\n    endpoints: (build) => ({\n      queryWithNoSerializer: build.query<SuccessResponse, number>({\n        query: (arg) => `${arg}`,\n      }),\n      queryWithCustomSerializer: build.query<SuccessResponse, number>({\n        query: (arg) => `${arg}`,\n        serializeQueryArgs: serializer1,\n      }),\n      queryWithCustomObjectSerializer: build.query<\n        SuccessResponse,\n        { id: number; client: MyApiClient }\n      >({\n        query: (arg) => `${arg.id}`,\n        serializeQueryArgs: ({\n          endpointDefinition,\n          endpointName,\n          queryArgs,\n        }) => {\n          const { id } = queryArgs\n          return { id }\n        },\n      }),\n      queryWithCustomNumberSerializer: build.query<\n        SuccessResponse,\n        { id: number; client: MyApiClient }\n      >({\n        query: (arg) => `${arg.id}`,\n        serializeQueryArgs: ({\n          endpointDefinition,\n          endpointName,\n          queryArgs,\n        }) => {\n          const { id } = queryArgs\n          return id\n        },\n      }),\n      listItems: build.query<string[], number>({\n        query: (pageNumber) => `/listItems?page=${pageNumber}`,\n        serializeQueryArgs: ({ endpointName }) => {\n          return endpointName\n        },\n        merge: (currentCache, newItems) => {\n          currentCache.push(...newItems)\n        },\n        forceRefetch({ currentArg, previousArg }) {\n          return currentArg !== previousArg\n        },\n      }),\n      listItems2: build.query<{ items: string[]; meta?: any }, number>({\n        query: (pageNumber) => `/listItems2?page=${pageNumber}`,\n        serializeQueryArgs: ({ endpointName }) => {\n          return endpointName\n        },\n        transformResponse(items: string[]) {\n          return { items }\n        },\n        merge: (currentCache, newData, meta) => {\n          currentCache.items.push(...newData.items)\n          currentCache.meta = meta\n        },\n        forceRefetch({ currentArg, previousArg }) {\n          return currentArg !== previousArg\n        },\n      }),\n    }),\n  })\n\n  const storeRef = setupApiStore(api)\n\n  it('Works via createApi', async () => {\n    await storeRef.store.dispatch(\n      api.endpoints.queryWithNoSerializer.initiate(99),\n    )\n\n    expect(serializer1).not.toHaveBeenCalled()\n\n    await storeRef.store.dispatch(\n      api.endpoints.queryWithCustomSerializer.initiate(42),\n    )\n\n    expect(serializer1).toHaveBeenCalled()\n\n    expect(\n      storeRef.store.getState().api.queries['base-queryWithNoSerializer-99'],\n    ).toBeTruthy()\n\n    expect(\n      storeRef.store.getState().api.queries['queryWithCustomSerializer-42'],\n    ).toBeTruthy()\n  })\n\n  const serializer2 = vi.fn(customArgsSerializer)\n\n  const injectedApi = api.injectEndpoints({\n    endpoints: (build) => ({\n      injectedQueryWithCustomSerializer: build.query<SuccessResponse, number>({\n        query: (arg) => `${arg}`,\n        serializeQueryArgs: serializer2,\n      }),\n    }),\n  })\n\n  it('Works via injectEndpoints', async () => {\n    expect(serializer2).not.toHaveBeenCalled()\n\n    await storeRef.store.dispatch(\n      injectedApi.endpoints.injectedQueryWithCustomSerializer.initiate(5),\n    )\n\n    expect(serializer2).toHaveBeenCalled()\n    expect(\n      storeRef.store.getState().api.queries[\n        'injectedQueryWithCustomSerializer-5'\n      ],\n    ).toBeTruthy()\n  })\n\n  test('Serializes a returned object for query args', async () => {\n    await storeRef.store.dispatch(\n      api.endpoints.queryWithCustomObjectSerializer.initiate({\n        id: 42,\n        client: dummyClient,\n      }),\n    )\n\n    expect(\n      storeRef.store.getState().api.queries[\n        'queryWithCustomObjectSerializer({\"id\":42})'\n      ],\n    ).toBeTruthy()\n  })\n\n  test('Serializes a returned primitive for query args', async () => {\n    await storeRef.store.dispatch(\n      api.endpoints.queryWithCustomNumberSerializer.initiate({\n        id: 42,\n        client: dummyClient,\n      }),\n    )\n\n    expect(\n      storeRef.store.getState().api.queries[\n        'queryWithCustomNumberSerializer(42)'\n      ],\n    ).toBeTruthy()\n  })\n\n  test('serializeQueryArgs + merge allows refetching as args change with same cache key', async () => {\n    const allItems = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i']\n    const PAGE_SIZE = 3\n\n    server.use(\n      http.get('https://example.com/listItems', ({ request }) => {\n        const url = new URL(request.url)\n        const pageString = url.searchParams.get('page')\n        const pageNum = parseInt(pageString || '0')\n\n        const results = paginate(allItems, PAGE_SIZE, pageNum)\n        return HttpResponse.json(results)\n      }),\n    )\n\n    // Page number shouldn't matter here, because the cache key ignores that.\n    // We just need to select the only cache entry.\n    const selectListItems = api.endpoints.listItems.select(0)\n\n    await storeRef.store.dispatch(api.endpoints.listItems.initiate(1))\n\n    const initialEntry = selectListItems(storeRef.store.getState())\n    expect(initialEntry.data).toEqual(['a', 'b', 'c'])\n\n    await storeRef.store.dispatch(api.endpoints.listItems.initiate(2))\n    const updatedEntry = selectListItems(storeRef.store.getState())\n    expect(updatedEntry.data).toEqual(['a', 'b', 'c', 'd', 'e', 'f'])\n  })\n\n  test('merge receives a meta object as an argument', async () => {\n    const allItems = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'i']\n    const PAGE_SIZE = 3\n\n    server.use(\n      http.get('https://example.com/listItems2', ({ request }) => {\n        const url = new URL(request.url)\n        const pageString = url.searchParams.get('page')\n        const pageNum = parseInt(pageString || '0')\n\n        const results = paginate(allItems, PAGE_SIZE, pageNum)\n        return HttpResponse.json(results)\n      }),\n    )\n\n    const selectListItems = api.endpoints.listItems2.select(0)\n\n    await storeRef.store.dispatch(api.endpoints.listItems2.initiate(1))\n    await storeRef.store.dispatch(api.endpoints.listItems2.initiate(2))\n    const cacheEntry = selectListItems(storeRef.store.getState())\n\n    // Should have passed along the third arg from `merge` containing these fields\n    expect(cacheEntry.data?.meta).toEqual({\n      requestId: expect.any(String),\n      fulfilledTimeStamp: expect.any(Number),\n      arg: 2,\n      baseQueryMeta: expect.any(Object),\n    })\n  })\n})\n\ndescribe('timeout behavior', () => {\n  test('triggers TIMEOUT_ERROR', async () => {\n    const api = createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com', timeout: 5 }),\n      endpoints: (build) => ({\n        query: build.query<unknown, void>({\n          query: () => '/success',\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    server.use(\n      http.get(\n        'https://example.com/success',\n        async () => {\n          await delay(50)\n          return HttpResponse.json({ value: 'failed' }, { status: 500 })\n        },\n        { once: true },\n      ),\n    )\n\n    const result = await storeRef.store.dispatch(api.endpoints.query.initiate())\n\n    expect(result?.error).toEqual({\n      status: 'TIMEOUT_ERROR',\n      error: expect.stringMatching(/^TimeoutError/),\n    })\n  })\n})\n\ndescribe('endpoint schemas', () => {\n  const schemaConverter: SchemaFailureConverter<\n    ReturnType<typeof fetchBaseQuery>\n  > = (error) => {\n    return {\n      status: 'CUSTOM_ERROR',\n      error: error.schemaName + ' failed validation',\n      data: error.issues,\n    }\n  }\n\n  const serializedSchemaError = {\n    name: 'SchemaError',\n    message: expect.any(String),\n    stack: expect.any(String),\n  } satisfies SerializedError\n\n  const onSchemaFailureGlobal = vi.fn<SchemaFailureHandler>()\n  const onSchemaFailureEndpoint = vi.fn<SchemaFailureHandler>()\n  afterEach(() => {\n    onSchemaFailureGlobal.mockClear()\n    onSchemaFailureEndpoint.mockClear()\n  })\n\n  function expectFailureHandlersToHaveBeenCalled({\n    schemaName,\n    value,\n    arg,\n  }: {\n    schemaName: `${SchemaType}Schema`\n    value: unknown\n    arg: unknown\n  }) {\n    for (const handler of [onSchemaFailureGlobal, onSchemaFailureEndpoint]) {\n      expect(handler).toHaveBeenCalledOnce()\n      const [namedError, info] = handler.mock.calls[0]\n      expect(namedError).toBeInstanceOf(NamedSchemaError)\n      expect(namedError.issues.length).toBeGreaterThan(0)\n      expect(namedError.value).toEqual(value)\n      expect(namedError.schemaName).toBe(schemaName)\n      expect(info.endpoint).toBe('query')\n      expect(info.type).toBe('query')\n      expect(info.arg).toEqual(arg)\n    }\n  }\n\n  interface SkipApiOptions {\n    globalSkip?: boolean\n    endpointSkip?: boolean\n    useArray?: boolean\n    globalCatch?: boolean\n    endpointCatch?: boolean\n  }\n\n  const apiOptions = (\n    type: SchemaType,\n    { useArray, globalSkip, globalCatch }: SkipApiOptions = {},\n  ) => ({\n    onSchemaFailure: onSchemaFailureGlobal,\n    skipSchemaValidation: useArray ? globalSkip && [type] : globalSkip,\n    catchSchemaFailure: globalCatch ? schemaConverter : undefined,\n  })\n\n  const endpointOptions = (\n    type: SchemaType,\n    { useArray, endpointSkip, endpointCatch }: SkipApiOptions = {},\n  ) => ({\n    onSchemaFailure: onSchemaFailureEndpoint,\n    skipSchemaValidation: useArray ? endpointSkip && [type] : endpointSkip,\n    catchSchemaFailure: endpointCatch ? schemaConverter : undefined,\n  })\n\n  const skipCases: [string, SkipApiOptions][] = [\n    ['globally', { globalSkip: true }],\n    ['on the endpoint', { endpointSkip: true }],\n    ['globally (array)', { globalSkip: true, useArray: true }],\n    ['on the endpoint (array)', { endpointSkip: true, useArray: true }],\n  ]\n\n  describe('argSchema', () => {\n    const makeApi = (opts?: SkipApiOptions) =>\n      createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n        ...apiOptions('arg', opts),\n        endpoints: (build) => ({\n          query: build.query<unknown, { id: number }>({\n            query: ({ id }) => `/post/${id}`,\n            argSchema: v.object({ id: v.number() }),\n            ...endpointOptions('arg', opts),\n          }),\n        }),\n      })\n    test(\"can be used to validate the endpoint's arguments\", async () => {\n      const api = makeApi()\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate({ id: 1 }),\n      )\n\n      expect(result?.error).toBeUndefined()\n\n      const invalidResult = await storeRef.store.dispatch(\n        // @ts-expect-error\n        api.endpoints.query.initiate({ id: '1' }),\n      )\n\n      expect(invalidResult?.error).toEqual(serializedSchemaError)\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'argSchema',\n        value: { id: '1' },\n        arg: { id: '1' },\n      })\n    })\n\n    test.each(skipCases)('can be skipped %s', async (_, arg) => {\n      const api = makeApi(arg)\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      const result = await storeRef.store.dispatch(\n        // @ts-expect-error\n        api.endpoints.query.initiate({ id: '1' }),\n      )\n\n      expect(result?.error).toBeUndefined()\n    })\n    // we only need to test this once\n    test('endpoint overrides global skip', async () => {\n      const api = makeApi({ globalSkip: true, endpointSkip: false })\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      const result = await storeRef.store.dispatch(\n        // @ts-expect-error\n        api.endpoints.query.initiate({ id: '1' }),\n      )\n\n      expect(result?.error).toEqual(serializedSchemaError)\n    })\n\n    test('can be converted to a standard error object at global level', async () => {\n      const api = makeApi({ globalCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      const result = await storeRef.store.dispatch(\n        // @ts-expect-error\n        api.endpoints.query.initiate({ id: '1' }),\n      )\n\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'argSchema failed validation',\n        data: expect.any(Array),\n      })\n\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'argSchema',\n        value: { id: '1' },\n        arg: { id: '1' },\n      })\n    })\n    test('can be converted to a standard error object at endpoint level', async () => {\n      const api = makeApi({ endpointCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n\n      const result = await storeRef.store.dispatch(\n        // @ts-expect-error\n        api.endpoints.query.initiate({ id: '1' }),\n      )\n\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'argSchema failed validation',\n        data: expect.any(Array),\n      })\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'argSchema',\n        value: { id: '1' },\n        arg: { id: '1' },\n      })\n    })\n  })\n  describe('rawResponseSchema', () => {\n    const makeApi = (opts?: SkipApiOptions) =>\n      createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n        ...apiOptions('rawResponse', opts),\n        endpoints: (build) => ({\n          query: build.query<{ success: boolean }, void>({\n            query: () => '/success',\n            rawResponseSchema: v.object({ value: v.literal('success!') }),\n            ...endpointOptions('rawResponse', opts),\n          }),\n        }),\n      })\n    test(\"can be used to validate the endpoint's raw result\", async () => {\n      const api = makeApi()\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual(serializedSchemaError)\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'rawResponseSchema',\n        value: { value: 'success' },\n        arg: undefined,\n      })\n    })\n    test.each(skipCases)('can be skipped %s', async (_, arg) => {\n      const api = makeApi(arg)\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toBeUndefined()\n    })\n    test('can be skipped on the endpoint', async () => {\n      const api = makeApi({ endpointSkip: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toBeUndefined()\n    })\n    test('can be converted to a standard error object at global level', async () => {\n      const api = makeApi({ globalCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'rawResponseSchema failed validation',\n        data: expect.any(Array),\n      })\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'rawResponseSchema',\n        value: { value: 'success' },\n        arg: undefined,\n      })\n    })\n    test('can be converted to a standard error object at endpoint level', async () => {\n      const api = makeApi({ endpointCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'rawResponseSchema failed validation',\n        data: expect.any(Array),\n      })\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'rawResponseSchema',\n        value: { value: 'success' },\n        arg: undefined,\n      })\n    })\n  })\n  describe('responseSchema', () => {\n    const makeApi = (opts?: SkipApiOptions) =>\n      createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n        ...apiOptions('response', opts),\n        endpoints: (build) => ({\n          query: build.query<{ success: boolean }, void>({\n            query: () => '/success',\n            transformResponse: () => ({ success: false }),\n            responseSchema: v.object({ success: v.literal(true) }),\n            ...endpointOptions('response', opts),\n          }),\n        }),\n      })\n    test(\"can be used to validate the endpoint's final result\", async () => {\n      const api = makeApi()\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual(serializedSchemaError)\n\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'responseSchema',\n        value: { success: false },\n        arg: undefined,\n      })\n    })\n    test.each(skipCases)('can be skipped %s', async (_, arg) => {\n      const api = makeApi(arg)\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toBeUndefined()\n    })\n    test('can be converted to a standard error object at global level', async () => {\n      const api = makeApi({ globalCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'responseSchema failed validation',\n        data: expect.any(Array),\n      })\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'responseSchema',\n        value: { success: false },\n        arg: undefined,\n      })\n    })\n    test('can be converted to a standard error object at endpoint level', async () => {\n      const api = makeApi({ endpointCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'responseSchema failed validation',\n        data: expect.any(Array),\n      })\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'responseSchema',\n        value: { success: false },\n        arg: undefined,\n      })\n    })\n  })\n  describe('rawErrorResponseSchema', () => {\n    const makeApi = (opts?: SkipApiOptions) =>\n      createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n        ...apiOptions('rawErrorResponse', opts),\n        endpoints: (build) => ({\n          query: build.query<{ success: boolean }, void>({\n            query: () => '/error',\n            rawErrorResponseSchema: v.object({\n              status: v.pipe(v.number(), v.minValue(400), v.maxValue(499)),\n              data: v.unknown(),\n            }),\n            ...endpointOptions('rawErrorResponse', opts),\n          }),\n        }),\n      })\n    test(\"can be used to validate the endpoint's raw error result\", async () => {\n      const api = makeApi()\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual(serializedSchemaError)\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'rawErrorResponseSchema',\n        value: { status: 500, data: { value: 'error' } },\n        arg: undefined,\n      })\n    })\n    test.each(skipCases)('can be skipped %s', async (_, arg) => {\n      const api = makeApi(arg)\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).not.toEqual(serializedSchemaError)\n    })\n    test('can be converted to a standard error object at global level', async () => {\n      const api = makeApi({ globalCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'rawErrorResponseSchema failed validation',\n        data: expect.any(Array),\n      })\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'rawErrorResponseSchema',\n        value: { status: 500, data: { value: 'error' } },\n        arg: undefined,\n      })\n    })\n    test('can be converted to a standard error object at endpoint level', async () => {\n      const api = makeApi({ endpointCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'rawErrorResponseSchema failed validation',\n        data: expect.any(Array),\n      })\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'rawErrorResponseSchema',\n        value: { status: 500, data: { value: 'error' } },\n        arg: undefined,\n      })\n    })\n  })\n  describe('errorResponseSchema', () => {\n    const makeApi = (opts?: SkipApiOptions) =>\n      createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n        ...apiOptions('errorResponse', opts),\n        endpoints: (build) => ({\n          query: build.query<{ success: boolean }, void>({\n            query: () => '/error',\n            transformErrorResponse: (error): FetchBaseQueryError => ({\n              status: 'CUSTOM_ERROR',\n              data: error,\n              error: 'whoops',\n            }),\n            errorResponseSchema: v.object({\n              status: v.literal('CUSTOM_ERROR'),\n              error: v.literal('oh no'),\n              data: v.unknown(),\n            }),\n            ...endpointOptions('errorResponse', opts),\n          }),\n        }),\n      })\n    test(\"can be used to validate the endpoint's final error result\", async () => {\n      const api = makeApi()\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual(serializedSchemaError)\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'errorResponseSchema',\n        value: {\n          status: 'CUSTOM_ERROR',\n          error: 'whoops',\n          data: { status: 500, data: { value: 'error' } },\n        },\n        arg: undefined,\n      })\n    })\n    test.each(skipCases)('can be skipped %s', async (_, arg) => {\n      const api = makeApi(arg)\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).not.toEqual(serializedSchemaError)\n    })\n    test('can be converted to a standard error object at global level', async () => {\n      const api = makeApi({ globalCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'errorResponseSchema failed validation',\n        data: expect.any(Array),\n      })\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'errorResponseSchema',\n        value: {\n          status: 'CUSTOM_ERROR',\n          error: 'whoops',\n          data: { status: 500, data: { value: 'error' } },\n        },\n        arg: undefined,\n      })\n    })\n    test('can be converted to a standard error object at endpoint level', async () => {\n      const api = makeApi({ endpointCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'errorResponseSchema failed validation',\n        data: expect.any(Array),\n      })\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'errorResponseSchema',\n        value: {\n          status: 'CUSTOM_ERROR',\n          error: 'whoops',\n          data: { status: 500, data: { value: 'error' } },\n        },\n        arg: undefined,\n      })\n    })\n  })\n  describe('metaSchema', () => {\n    const makeApi = (opts?: SkipApiOptions) =>\n      createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n        ...apiOptions('meta', opts),\n        endpoints: (build) => ({\n          query: build.query<{ success: boolean }, void>({\n            query: () => '/success',\n            metaSchema: v.object({\n              request: v.instance(Request),\n              response: v.instance(Response),\n              timestamp: v.number(),\n            }),\n            ...endpointOptions('meta', opts),\n          }),\n        }),\n      })\n    test(\"can be used to validate the endpoint's meta result\", async () => {\n      const api = makeApi()\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual(serializedSchemaError)\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'metaSchema',\n        value: {\n          request: expect.any(Request),\n          response: expect.any(Response),\n        },\n        arg: undefined,\n      })\n    })\n    test.each(skipCases)('can be skipped %s', async (_, arg) => {\n      const api = makeApi(arg)\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toBeUndefined()\n    })\n    test('can be converted to a standard error object at global level', async () => {\n      const api = makeApi({ globalCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'metaSchema failed validation',\n        data: expect.any(Array),\n      })\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'metaSchema',\n        value: {\n          request: expect.any(Request),\n          response: expect.any(Response),\n        },\n        arg: undefined,\n      })\n    })\n    test('can be converted to a standard error object at endpoint level', async () => {\n      const api = makeApi({ endpointCatch: true })\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const result = await storeRef.store.dispatch(\n        api.endpoints.query.initiate(),\n      )\n      expect(result?.error).toEqual({\n        status: 'CUSTOM_ERROR',\n        error: 'metaSchema failed validation',\n        data: expect.any(Array),\n      })\n      expectFailureHandlersToHaveBeenCalled({\n        schemaName: 'metaSchema',\n        value: {\n          request: expect.any(Request),\n          response: expect.any(Response),\n        },\n        arg: undefined,\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/defaultSerializeQueryArgs.test.ts",
    "content": "import { defaultSerializeQueryArgs } from '@reduxjs/toolkit/query'\n\nconst endpointDefinition: any = {}\nconst endpointName = 'test'\n\ntest('string arg', () => {\n  expect(\n    defaultSerializeQueryArgs({\n      endpointDefinition,\n      endpointName,\n      queryArgs: 'arg',\n    }),\n  ).toMatchInlineSnapshot(`\"test(\"arg\")\"`)\n})\n\ntest('number arg', () => {\n  expect(\n    defaultSerializeQueryArgs({\n      endpointDefinition,\n      endpointName,\n      queryArgs: 5,\n    }),\n  ).toMatchInlineSnapshot(`\"test(5)\"`)\n})\n\ntest('bigint arg has non-default serialization (intead of throwing)', () => {\n  expect(\n    defaultSerializeQueryArgs({\n      endpointDefinition,\n      endpointName,\n      queryArgs: BigInt(10),\n    }),\n  ).toMatchInlineSnapshot(`\"test({\"$bigint\":\"10\"})\"`)\n})\n\ntest('simple object arg is sorted', () => {\n  expect(\n    defaultSerializeQueryArgs({\n      endpointDefinition,\n      endpointName,\n      queryArgs: { name: 'arg', age: 5 },\n    }),\n  ).toMatchInlineSnapshot(`\"test({\"age\":5,\"name\":\"arg\"})\"`)\n})\n\ntest('nested object arg is sorted recursively', () => {\n  expect(\n    defaultSerializeQueryArgs({\n      endpointDefinition,\n      endpointName,\n      queryArgs: { name: { last: 'Split', first: 'Banana' }, age: 5 },\n    }),\n  ).toMatchInlineSnapshot(\n    `\"test({\"age\":5,\"name\":{\"first\":\"Banana\",\"last\":\"Split\"}})\"`,\n  )\n})\n\ntest('Fully serializes a deeply nested object', () => {\n  const nestedObj = {\n    a: {\n      a1: {\n        a11: {\n          a111: 1,\n        },\n      },\n    },\n    b: {\n      b2: {\n        b21: 3,\n      },\n      b1: {\n        b11: 2,\n      },\n    },\n  }\n\n  const res = defaultSerializeQueryArgs({\n    endpointDefinition,\n    endpointName,\n    queryArgs: nestedObj,\n  })\n  expect(res).toMatchInlineSnapshot(\n    `\"test({\"a\":{\"a1\":{\"a11\":{\"a111\":1}}},\"b\":{\"b1\":{\"b11\":2},\"b2\":{\"b21\":3}}})\"`,\n  )\n})\n\ntest('Caches results for plain objects', () => {\n  const testData = Array.from({ length: 10000 }).map((_, i) => {\n    return {\n      albumId: i,\n      id: i,\n      title: 'accusamus beatae ad facilis cum similique qui sunt',\n      url: 'https://via.placeholder.com/600/92c952',\n      thumbnailUrl: 'https://via.placeholder.com/150/92c952',\n    }\n  })\n\n  const data = {\n    testData,\n  }\n\n  const runWithTimer = (data: any) => {\n    const start = Date.now()\n    const res = defaultSerializeQueryArgs({\n      endpointDefinition,\n      endpointName,\n      queryArgs: data,\n    })\n    const end = Date.now()\n    const duration = end - start\n    return [res, duration] as const\n  }\n\n  const [res1, time1] = runWithTimer(data)\n  const [res2, time2] = runWithTimer(data)\n\n  expect(res1).toBe(res2)\n  expect(time2).toBeLessThanOrEqual(time1)\n  // Locally, stringifying 10K items takes 25-30ms.\n  // Assuming the WeakMap cache hit, this _should_ be 0\n  expect(time2).toBeLessThan(2)\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/devWarnings.test.tsx",
    "content": "import { noop } from '@internal/listenerMiddleware/utils'\nimport { configureStore } from '@reduxjs/toolkit'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\nconst consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)\n\nconst consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n\nbeforeEach(() => {\n  vi.stubEnv('NODE_ENV', 'development')\n})\n\nafterEach(() => {\n  vi.unstubAllEnvs()\n  vi.clearAllMocks()\n})\n\nafterAll(() => {\n  vi.restoreAllMocks()\n  vi.unstubAllEnvs()\n})\n\nconst baseUrl = 'https://example.com'\n\nfunction createApis() {\n  const api1 = createApi({\n    baseQuery: fetchBaseQuery({ baseUrl }),\n    endpoints: (builder) => ({\n      q1: builder.query({ query: () => '/success' }),\n    }),\n  })\n\n  const api1_2 = createApi({\n    baseQuery: fetchBaseQuery({ baseUrl }),\n    endpoints: (builder) => ({\n      q1: builder.query({ query: () => '/success' }),\n    }),\n  })\n\n  const api2 = createApi({\n    reducerPath: 'api2',\n    baseQuery: fetchBaseQuery({ baseUrl }),\n    endpoints: (builder) => ({\n      q1: builder.query({ query: () => '/success' }),\n    }),\n  })\n  return [api1, api1_2, api2] as const\n}\n\nlet [api1, api1_2, api2] = createApis()\nbeforeEach(() => {\n  ;[api1, api1_2, api2] = createApis()\n})\n\nconst reMatchMissingMiddlewareError =\n  /Warning: Middleware for RTK-Query API at reducerPath \"api\" has not been added to the store/\n\ndescribe('missing middleware', () => {\n  test.each([\n    ['development', true],\n    ['production', false],\n  ])('%s warns if middleware is missing: %s', (env, shouldWarn) => {\n    vi.stubEnv('NODE_ENV', env)\n\n    const store = configureStore({\n      reducer: { [api1.reducerPath]: api1.reducer },\n    })\n    const doDispatch = () => {\n      store.dispatch(api1.endpoints.q1.initiate(undefined))\n    }\n    if (shouldWarn) {\n      expect(doDispatch).toThrowError(reMatchMissingMiddlewareError)\n    } else {\n      expect(doDispatch).not.toThrowError()\n    }\n  })\n\n  test('does not warn if middleware is not missing', () => {\n    const store = configureStore({\n      reducer: { [api1.reducerPath]: api1.reducer },\n      middleware: (gdm) => gdm().concat(api1.middleware),\n    })\n    store.dispatch(api1.endpoints.q1.initiate(undefined))\n\n    expect(consoleErrorSpy).not.toHaveBeenCalled()\n\n    expect(consoleWarnSpy).not.toHaveBeenCalled()\n  })\n\n  test('warns only once per api', () => {\n    const store = configureStore({\n      reducer: { [api1.reducerPath]: api1.reducer },\n    })\n    const doDispatch = () => {\n      store.dispatch(api1.endpoints.q1.initiate(undefined))\n    }\n\n    expect(doDispatch).toThrowError(reMatchMissingMiddlewareError)\n    expect(doDispatch).not.toThrowError()\n  })\n\n  test('warns multiple times for multiple apis', () => {\n    const store = configureStore({\n      reducer: {\n        [api1.reducerPath]: api1.reducer,\n        [api2.reducerPath]: api2.reducer,\n      },\n    })\n    const doDispatch1 = () => {\n      store.dispatch(api1.endpoints.q1.initiate(undefined))\n    }\n    const doDispatch2 = () => {\n      store.dispatch(api2.endpoints.q1.initiate(undefined))\n    }\n    expect(doDispatch1).toThrowError(reMatchMissingMiddlewareError)\n    expect(doDispatch2).toThrowError(\n      /Warning: Middleware for RTK-Query API at reducerPath \"api2\" has not been added to the store/,\n    )\n  })\n})\n\ndescribe('missing reducer', () => {\n  describe.each([\n    ['development', true],\n    ['production', false],\n  ])('%s warns if reducer is missing: %s', (env, shouldWarn) => {\n    beforeEach(() => {\n      vi.stubEnv('NODE_ENV', env)\n    })\n\n    afterAll(() => {\n      vi.unstubAllEnvs()\n    })\n\n    test('middleware not crashing if reducer is missing', async () => {\n      const store = configureStore({\n        reducer: { x: () => 0 },\n        // @ts-expect-error\n        middleware: (gdm) => gdm().concat(api1.middleware),\n      })\n      await store.dispatch(api1.endpoints.q1.initiate(undefined))\n\n      expect(process.env.NODE_ENV).toBe(env)\n    })\n\n    test(`warning behavior`, () => {\n      const store = configureStore({\n        reducer: { x: () => 0 },\n        // @ts-expect-error\n        middleware: (gdm) => gdm().concat(api1.middleware),\n      })\n      // @ts-expect-error\n      api1.endpoints.q1.select(undefined)(store.getState())\n\n      expect(consoleWarnSpy).not.toHaveBeenCalled()\n\n      expect(process.env.NODE_ENV).toBe(env)\n\n      if (shouldWarn) {\n        expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n        expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n          'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',\n        )\n      } else {\n        expect(consoleErrorSpy).not.toHaveBeenCalled()\n      }\n    })\n  })\n\n  test('does not warn if reducer is not missing', () => {\n    const store = configureStore({\n      reducer: { [api1.reducerPath]: api1.reducer },\n      middleware: (gdm) => gdm().concat(api1.middleware),\n    })\n    api1.endpoints.q1.select(undefined)(store.getState())\n\n    expect(consoleErrorSpy).not.toHaveBeenCalled()\n\n    expect(consoleWarnSpy).not.toHaveBeenCalled()\n  })\n\n  test('warns only once per api', () => {\n    const store = configureStore({\n      reducer: { x: () => 0 },\n      // @ts-expect-error\n      middleware: (gdm) => gdm().concat(api1.middleware),\n    })\n    // @ts-expect-error\n    api1.endpoints.q1.select(undefined)(store.getState())\n    // @ts-expect-error\n    api1.endpoints.q1.select(undefined)(store.getState())\n\n    expect(consoleWarnSpy).not.toHaveBeenCalled()\n\n    expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n    expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n      'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',\n    )\n  })\n\n  test('warns multiple times for multiple apis', () => {\n    const store = configureStore({\n      reducer: { x: () => 0 },\n      // @ts-expect-error\n      middleware: (gdm) => gdm().concat(api1.middleware),\n    })\n    // @ts-expect-error\n    api1.endpoints.q1.select(undefined)(store.getState())\n    // @ts-expect-error\n    api2.endpoints.q1.select(undefined)(store.getState())\n\n    expect(consoleWarnSpy).not.toHaveBeenCalled()\n\n    expect(consoleErrorSpy).toHaveBeenCalledTimes(2)\n\n    expect(consoleErrorSpy).toHaveBeenNthCalledWith(\n      1,\n      'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',\n    )\n\n    expect(consoleErrorSpy).toHaveBeenNthCalledWith(\n      2,\n      'Error: No data found at `state.api2`. Did you forget to add the reducer to the store?',\n    )\n  })\n})\n\ntest('warns for reducer and also throws error if everything is missing', async () => {\n  const store = configureStore({\n    reducer: { x: () => 0 },\n  })\n  // @ts-expect-error\n  api1.endpoints.q1.select(undefined)(store.getState())\n  const doDispatch = () => {\n    store.dispatch(api1.endpoints.q1.initiate(undefined))\n  }\n  expect(doDispatch).toThrowError(reMatchMissingMiddlewareError)\n\n  expect(consoleWarnSpy).not.toHaveBeenCalled()\n\n  expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n  expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n    'Error: No data found at `state.api`. Did you forget to add the reducer to the store?',\n  )\n})\n\ndescribe('warns on multiple apis using the same `reducerPath`', () => {\n  test('common: two apis, same order', async () => {\n    const store = configureStore({\n      reducer: {\n        // TS 5.3 now errors on identical object keys. We want to force that behavior.\n        // @ts-ignore\n        [api1.reducerPath]: api1.reducer,\n        // @ts-ignore\n        [api1_2.reducerPath]: api1_2.reducer,\n      },\n      middleware: (gDM) => gDM().concat(api1.middleware, api1_2.middleware),\n    })\n    await store.dispatch(api1.endpoints.q1.initiate(undefined))\n\n    expect(consoleErrorSpy).not.toHaveBeenCalled()\n\n    expect(consoleWarnSpy).toHaveBeenCalledOnce()\n\n    // only second api prints\n    expect(consoleWarnSpy).toHaveBeenLastCalledWith(\n      `There is a mismatch between slice and middleware for the reducerPath \"api\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,\n    )\n  })\n\n  test('common: two apis, opposing order', async () => {\n    const store = configureStore({\n      reducer: {\n        // @ts-ignore\n        [api1.reducerPath]: api1.reducer,\n        // @ts-ignore\n        [api1_2.reducerPath]: api1_2.reducer,\n      },\n      middleware: (gDM) => gDM().concat(api1_2.middleware, api1.middleware),\n    })\n    await store.dispatch(api1.endpoints.q1.initiate(undefined))\n\n    expect(consoleErrorSpy).not.toHaveBeenCalled()\n\n    expect(consoleWarnSpy).toHaveBeenCalledTimes(2)\n\n    // both apis print\n    expect(consoleWarnSpy).toHaveBeenNthCalledWith(\n      1,\n      `There is a mismatch between slice and middleware for the reducerPath \"api\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,\n    )\n\n    expect(consoleWarnSpy).toHaveBeenNthCalledWith(\n      2,\n      `There is a mismatch between slice and middleware for the reducerPath \"api\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,\n    )\n  })\n\n  test('common: two apis, only first middleware', async () => {\n    const store = configureStore({\n      reducer: {\n        // @ts-ignore\n        [api1.reducerPath]: api1.reducer,\n        // @ts-ignore\n        [api1_2.reducerPath]: api1_2.reducer,\n      },\n      middleware: (gDM) => gDM().concat(api1.middleware),\n    })\n    await store.dispatch(api1.endpoints.q1.initiate(undefined))\n\n    expect(consoleErrorSpy).not.toHaveBeenCalled()\n\n    expect(consoleWarnSpy).toHaveBeenCalledOnce()\n\n    expect(consoleWarnSpy).toHaveBeenLastCalledWith(\n      `There is a mismatch between slice and middleware for the reducerPath \"api\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,\n    )\n  })\n\n  /**\n   * This is the one edge case that we currently cannot detect:\n   * Multiple apis with the same reducer key and only the middleware of the last api is being used.\n   *\n   * It would be great to support this case as well, but for now:\n   * \"It is what it is.\"\n   */\n  test.todo('common: two apis, only second middleware', async () => {\n    const store = configureStore({\n      reducer: {\n        // @ts-ignore\n        [api1.reducerPath]: api1.reducer,\n        // @ts-ignore\n        [api1_2.reducerPath]: api1_2.reducer,\n      },\n      middleware: (gDM) => gDM().concat(api1_2.middleware),\n    })\n    await store.dispatch(api1.endpoints.q1.initiate(undefined))\n\n    expect(consoleErrorSpy).not.toHaveBeenCalled()\n\n    expect(consoleWarnSpy).toHaveBeenCalledOnce()\n\n    expect(consoleWarnSpy).toHaveBeenLastCalledWith(\n      `There is a mismatch between slice and middleware for the reducerPath \"api\".\nYou can only have one api per reducer path, this will lead to crashes in various situations!\nIf you have multiple apis, you *have* to specify the reducerPath option when using createApi!`,\n    )\n  })\n})\n\ndescribe('`console.error` on unhandled errors during `initiate`', () => {\n  test('error thrown in `baseQuery`', async () => {\n    const api = createApi({\n      baseQuery(): { data: any } {\n        throw new Error('this was kinda expected')\n      },\n      endpoints: (build) => ({\n        baseQuery: build.query<any, void>({ query() {} }),\n      }),\n    })\n    const store = configureStore({\n      reducer: { [api.reducerPath]: api.reducer },\n      middleware: (gdm) => gdm().concat(api.middleware),\n    })\n    await store.dispatch(api.endpoints.baseQuery.initiate())\n\n    expect(consoleWarnSpy).not.toHaveBeenCalled()\n\n    expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n    expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n      `An unhandled error occurred processing a request for the endpoint \"baseQuery\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n      Error('this was kinda expected'),\n    )\n  })\n\n  test('error thrown in `queryFn`', async () => {\n    const api = createApi({\n      baseQuery() {\n        return { data: {} }\n      },\n      endpoints: (build) => ({\n        queryFn: build.query<any, void>({\n          queryFn() {\n            throw new Error('this was kinda expected')\n          },\n        }),\n      }),\n    })\n    const store = configureStore({\n      reducer: { [api.reducerPath]: api.reducer },\n      middleware: (gdm) => gdm().concat(api.middleware),\n    })\n    await store.dispatch(api.endpoints.queryFn.initiate())\n\n    expect(consoleWarnSpy).not.toHaveBeenCalled()\n\n    expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n    expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n      `An unhandled error occurred processing a request for the endpoint \"queryFn\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n      Error('this was kinda expected'),\n    )\n  })\n\n  test('error thrown in `transformResponse`', async () => {\n    const api = createApi({\n      baseQuery() {\n        return { data: {} }\n      },\n      endpoints: (build) => ({\n        transformRspn: build.query<any, void>({\n          query() {},\n          transformResponse() {\n            throw new Error('this was kinda expected')\n          },\n        }),\n      }),\n    })\n    const store = configureStore({\n      reducer: { [api.reducerPath]: api.reducer },\n      middleware: (gdm) => gdm().concat(api.middleware),\n    })\n    await store.dispatch(api.endpoints.transformRspn.initiate())\n\n    expect(consoleWarnSpy).not.toHaveBeenCalled()\n\n    expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n    expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n      `An unhandled error occurred processing a request for the endpoint \"transformRspn\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n      Error('this was kinda expected'),\n    )\n  })\n\n  test('error thrown in `transformErrorResponse`', async () => {\n    const api = createApi({\n      baseQuery() {\n        return { error: {} }\n      },\n      endpoints: (build) => ({\n        // @ts-ignore TS doesn't like `() => never` for `tER`\n        transformErRspn: build.query<number, void>({\n          // @ts-ignore TS doesn't like `() => never` for `tER`\n          query: () => '/dummy',\n          // @ts-ignore TS doesn't like `() => never` for `tER`\n          transformErrorResponse() {\n            throw new Error('this was kinda expected')\n          },\n        }),\n      }),\n    })\n    const store = configureStore({\n      reducer: { [api.reducerPath]: api.reducer },\n      middleware: (gdm) => gdm().concat(api.middleware),\n    })\n    await store.dispatch(api.endpoints.transformErRspn.initiate())\n\n    expect(consoleWarnSpy).not.toHaveBeenCalled()\n\n    expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n    expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n      `An unhandled error occurred processing a request for the endpoint \"transformErRspn\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n      Error('this was kinda expected'),\n    )\n  })\n\n  test('`fetchBaseQuery`: error thrown in `prepareHeaders`', async () => {\n    const api = createApi({\n      baseQuery: fetchBaseQuery({\n        baseUrl,\n        prepareHeaders() {\n          throw new Error('this was kinda expected')\n        },\n      }),\n      endpoints: (build) => ({\n        prep: build.query<any, void>({\n          query() {\n            return '/success'\n          },\n        }),\n      }),\n    })\n    const store = configureStore({\n      reducer: { [api.reducerPath]: api.reducer },\n      middleware: (gdm) => gdm().concat(api.middleware),\n    })\n    await store.dispatch(api.endpoints.prep.initiate())\n\n    expect(consoleWarnSpy).not.toHaveBeenCalled()\n\n    expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n    expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n      `An unhandled error occurred processing a request for the endpoint \"prep\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n      Error('this was kinda expected'),\n    )\n  })\n\n  test('`fetchBaseQuery`: error thrown in `validateStatus`', async () => {\n    const api = createApi({\n      baseQuery: fetchBaseQuery({\n        baseUrl,\n      }),\n      endpoints: (build) => ({\n        val: build.query<any, void>({\n          query() {\n            return {\n              url: '/success',\n\n              validateStatus() {\n                throw new Error('this was kinda expected')\n              },\n            }\n          },\n        }),\n      }),\n    })\n    const store = configureStore({\n      reducer: { [api.reducerPath]: api.reducer },\n      middleware: (gdm) => gdm().concat(api.middleware),\n    })\n    await store.dispatch(api.endpoints.val.initiate())\n\n    expect(consoleWarnSpy).not.toHaveBeenCalled()\n\n    expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n    expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n      `An unhandled error occurred processing a request for the endpoint \"val\".\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n      Error('this was kinda expected'),\n    )\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/errorHandling.test-d.tsx",
    "content": "import { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { useState } from 'react'\n\nconst mockSuccessResponse = { value: 'success' }\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n  endpoints: (build) => ({\n    update: build.mutation<typeof mockSuccessResponse, any>({\n      query: () => ({ url: 'success' }),\n    }),\n    failedUpdate: build.mutation<typeof mockSuccessResponse, any>({\n      query: () => ({ url: 'error' }),\n    }),\n  }),\n})\n\ndescribe('type tests', () => {\n  test('a mutation is unwrappable and has the correct types', () => {\n    function User() {\n      const [manualError, setManualError] = useState<any>()\n\n      const [update, { isLoading, data, error }] =\n        api.endpoints.update.useMutation()\n\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"data\">{JSON.stringify(data)}</div>\n          <div data-testid=\"error\">{JSON.stringify(error)}</div>\n          <div data-testid=\"manuallySetError\">\n            {JSON.stringify(manualError)}\n          </div>\n          <button\n            onClick={() => {\n              update({ name: 'hello' })\n                .unwrap()\n                .then((result) => {\n                  expectTypeOf(result).toEqualTypeOf(mockSuccessResponse)\n\n                  setManualError(undefined)\n                })\n                .catch(setManualError)\n            }}\n          >\n            Update User\n          </button>\n        </div>\n      )\n    }\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/errorHandling.test.tsx",
    "content": "import type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'\nimport type { BaseQueryFn, BaseQueryApi } from '@reduxjs/toolkit/query/react'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport {\n  act,\n  fireEvent,\n  render,\n  renderHook,\n  screen,\n  waitFor,\n} from '@testing-library/react'\nimport type { AxiosError, AxiosRequestConfig, AxiosResponse } from 'axios'\nimport axios from 'axios'\nimport { HttpResponse, http } from 'msw'\nimport * as React from 'react'\nimport { useDispatch } from 'react-redux'\nimport { hookWaitFor, setupApiStore } from '@internal/tests/utils/helpers'\nimport { server } from '@internal/query/tests/mocks/server'\n\nconst baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com' })\n\nconst api = createApi({\n  baseQuery,\n  endpoints(build) {\n    return {\n      query: build.query({ query: () => '/query' }),\n      mutation: build.mutation({\n        query: () => ({ url: '/mutation', method: 'POST' }),\n      }),\n    }\n  },\n})\n\nconst storeRef = setupApiStore(api)\n\nconst failQueryOnce = http.get(\n  '/query',\n  () => HttpResponse.json({ value: 'failed' }, { status: 500 }),\n  { once: true },\n)\n\ndescribe('fetchBaseQuery', () => {\n  let commonBaseQueryApiArgs: BaseQueryApi = {} as any\n  beforeEach(() => {\n    const abortController = new AbortController()\n    commonBaseQueryApiArgs = {\n      signal: abortController.signal,\n      abort: (reason) =>\n        //@ts-ignore\n        abortController.abort(reason),\n      dispatch: storeRef.store.dispatch,\n      getState: storeRef.store.getState,\n      extra: undefined,\n      type: 'query',\n      endpoint: 'doesntmatterhere',\n    }\n  })\n  test('success', async () => {\n    await expect(\n      baseQuery('/success', commonBaseQueryApiArgs, {}),\n    ).resolves.toEqual({\n      data: { value: 'success' },\n      meta: {\n        request: expect.any(Object),\n        response: expect.any(Object),\n      },\n    })\n  })\n  test('error', async () => {\n    server.use(failQueryOnce)\n    await expect(\n      baseQuery('/error', commonBaseQueryApiArgs, {}),\n    ).resolves.toEqual({\n      error: {\n        data: { value: 'error' },\n        status: 500,\n      },\n      meta: {\n        request: expect.any(Object),\n        response: expect.any(Object),\n      },\n    })\n  })\n})\n\ndescribe('query error handling', () => {\n  test('success', async () => {\n    server.use(\n      http.get('https://example.com/query', () =>\n        HttpResponse.json({ value: 'success' }),\n      ),\n    )\n    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {\n      wrapper: storeRef.wrapper,\n    })\n\n    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())\n    expect(result.current).toEqual(\n      expect.objectContaining({\n        isLoading: false,\n        isError: false,\n        isSuccess: true,\n        data: { value: 'success' },\n      }),\n    )\n  })\n\n  test('error', async () => {\n    server.use(\n      http.get('https://example.com/query', () =>\n        HttpResponse.json({ value: 'error' }, { status: 500 }),\n      ),\n    )\n    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {\n      wrapper: storeRef.wrapper,\n    })\n\n    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())\n    expect(result.current).toEqual(\n      expect.objectContaining({\n        isLoading: false,\n        isError: true,\n        isSuccess: false,\n        error: {\n          status: 500,\n          data: { value: 'error' },\n        },\n      }),\n    )\n  })\n\n  test('success -> error', async () => {\n    server.use(\n      http.get('https://example.com/query', () =>\n        HttpResponse.json({ value: 'success' }),\n      ),\n    )\n    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {\n      wrapper: storeRef.wrapper,\n    })\n\n    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())\n    expect(result.current).toEqual(\n      expect.objectContaining({\n        isLoading: false,\n        isError: false,\n        isSuccess: true,\n        data: { value: 'success' },\n      }),\n    )\n\n    server.use(\n      http.get(\n        'https://example.com/query',\n        () => HttpResponse.json({ value: 'error' }, { status: 500 }),\n        { once: true },\n      ),\n    )\n\n    act(() => void result.current.refetch())\n\n    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())\n    expect(result.current).toEqual(\n      expect.objectContaining({\n        isLoading: false,\n        isError: true,\n        isSuccess: false,\n        error: {\n          status: 500,\n          data: { value: 'error' },\n        },\n        // last data will stay available\n        data: { value: 'success' },\n      }),\n    )\n  })\n\n  test('error -> success', async () => {\n    server.use(\n      http.get('https://example.com/query', () =>\n        HttpResponse.json({ value: 'success' }),\n      ),\n    )\n    server.use(\n      http.get(\n        'https://example.com/query',\n        () => HttpResponse.json({ value: 'error' }, { status: 500 }),\n        { once: true },\n      ),\n    )\n    const { result } = renderHook(() => api.endpoints.query.useQuery({}), {\n      wrapper: storeRef.wrapper,\n    })\n\n    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())\n    expect(result.current).toEqual(\n      expect.objectContaining({\n        isLoading: false,\n        isError: true,\n        isSuccess: false,\n        error: {\n          status: 500,\n          data: { value: 'error' },\n        },\n      }),\n    )\n\n    act(() => void result.current.refetch())\n\n    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())\n    expect(result.current).toEqual(\n      expect.objectContaining({\n        isLoading: false,\n        isError: false,\n        isSuccess: true,\n        data: { value: 'success' },\n      }),\n    )\n  })\n})\n\ndescribe('mutation error handling', () => {\n  test('success', async () => {\n    server.use(\n      http.post('https://example.com/mutation', () =>\n        HttpResponse.json({ value: 'success' }),\n      ),\n    )\n    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {\n      wrapper: storeRef.wrapper,\n    })\n\n    const [trigger] = result.current\n\n    act(() => void trigger({}))\n\n    await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())\n    expect(result.current[1]).toEqual(\n      expect.objectContaining({\n        isLoading: false,\n        isError: false,\n        isSuccess: true,\n        data: { value: 'success' },\n      }),\n    )\n  })\n\n  test('error', async () => {\n    server.use(\n      http.post('https://example.com/mutation', () =>\n        HttpResponse.json({ value: 'error' }, { status: 500 }),\n      ),\n    )\n    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {\n      wrapper: storeRef.wrapper,\n    })\n\n    const [trigger] = result.current\n\n    act(() => void trigger({}))\n\n    await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())\n    expect(result.current[1]).toEqual(\n      expect.objectContaining({\n        isLoading: false,\n        isError: true,\n        isSuccess: false,\n        error: {\n          status: 500,\n          data: { value: 'error' },\n        },\n      }),\n    )\n  })\n\n  test('success -> error', async () => {\n    server.use(\n      http.post('https://example.com/mutation', () =>\n        HttpResponse.json({ value: 'success' }),\n      ),\n    )\n    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {\n      wrapper: storeRef.wrapper,\n    })\n\n    {\n      const [trigger] = result.current\n\n      act(() => void trigger({}))\n\n      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())\n      expect(result.current[1]).toEqual(\n        expect.objectContaining({\n          isLoading: false,\n          isError: false,\n          isSuccess: true,\n          data: { value: 'success' },\n        }),\n      )\n    }\n\n    server.use(\n      http.post(\n        'https://example.com/mutation',\n        () => HttpResponse.json({ value: 'error' }, { status: 500 }),\n        { once: true },\n      ),\n    )\n\n    {\n      const [trigger] = result.current\n\n      act(() => void trigger({}))\n\n      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())\n      expect(result.current[1]).toEqual(\n        expect.objectContaining({\n          isLoading: false,\n          isError: true,\n          isSuccess: false,\n          error: {\n            status: 500,\n            data: { value: 'error' },\n          },\n        }),\n      )\n      expect(result.current[1].data).toBeUndefined()\n    }\n  })\n\n  test('error -> success', async () => {\n    server.use(\n      http.post('https://example.com/mutation', () =>\n        HttpResponse.json({ value: 'success' }),\n      ),\n    )\n    server.use(\n      http.post(\n        'https://example.com/mutation',\n        () => HttpResponse.json({ value: 'error' }, { status: 500 }),\n        { once: true },\n      ),\n    )\n\n    const { result } = renderHook(() => api.endpoints.mutation.useMutation(), {\n      wrapper: storeRef.wrapper,\n    })\n\n    {\n      const [trigger] = result.current\n\n      act(() => void trigger({}))\n\n      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())\n      expect(result.current[1]).toEqual(\n        expect.objectContaining({\n          isLoading: false,\n          isError: true,\n          isSuccess: false,\n          error: {\n            status: 500,\n            data: { value: 'error' },\n          },\n        }),\n      )\n    }\n\n    {\n      const [trigger] = result.current\n\n      act(() => void trigger({}))\n\n      await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())\n      expect(result.current[1]).toEqual(\n        expect.objectContaining({\n          isLoading: false,\n          isError: false,\n          isSuccess: true,\n        }),\n      )\n      expect(result.current[1].error).toBeUndefined()\n    }\n  })\n})\n\ndescribe('custom axios baseQuery', () => {\n  const axiosBaseQuery =\n    (\n      { baseUrl }: { baseUrl: string } = { baseUrl: '' },\n    ): BaseQueryFn<\n      {\n        url: string\n        method?: AxiosRequestConfig['method']\n        data?: AxiosRequestConfig['data']\n      },\n      unknown,\n      unknown,\n      unknown,\n      { response: AxiosResponse; request: AxiosRequestConfig }\n    > =>\n    async ({ url, method, data }) => {\n      const config = { url: baseUrl + url, method, data }\n      try {\n        const result = await axios(config)\n        return {\n          data: result.data,\n          meta: { request: config, response: result },\n        }\n      } catch (axiosError) {\n        const err = axiosError as AxiosError\n        return {\n          error: {\n            status: err.response?.status,\n            data: err.response?.data,\n          },\n          meta: { request: config, response: err.response as AxiosResponse },\n        }\n      }\n    }\n\n  type SuccessResponse = { value: 'success' }\n  const api = createApi({\n    baseQuery: axiosBaseQuery({\n      baseUrl: 'https://example.com',\n    }),\n    endpoints(build) {\n      return {\n        query: build.query<SuccessResponse, void>({\n          query: () => ({ url: '/success', method: 'get' }),\n          transformResponse: (result: SuccessResponse, meta) => {\n            return { ...result, metaResponseData: meta?.response.data }\n          },\n        }),\n        mutation: build.mutation<SuccessResponse, any>({\n          query: () => ({ url: '/success', method: 'post' }),\n        }),\n      }\n    },\n  })\n\n  const storeRef = setupApiStore(api)\n\n  test('axiosBaseQuery transformResponse uses its custom meta format', async () => {\n    const result = await storeRef.store.dispatch(api.endpoints.query.initiate())\n\n    expect(result.data).toEqual({\n      value: 'success',\n      metaResponseData: { value: 'success' },\n    })\n  })\n\n  test('axios errors behave as expected', async () => {\n    server.use(\n      http.get('https://example.com/success', () =>\n        HttpResponse.json({ value: 'error' }, { status: 500 }),\n      ),\n    )\n    const { result } = renderHook(() => api.endpoints.query.useQuery(), {\n      wrapper: storeRef.wrapper,\n    })\n\n    await hookWaitFor(() => expect(result.current.isFetching).toBeFalsy())\n    expect(result.current).toEqual(\n      expect.objectContaining({\n        isLoading: false,\n        isError: true,\n        isSuccess: false,\n        error: { status: 500, data: { value: 'error' } },\n      }),\n    )\n  })\n})\n\ndescribe('error handling in a component', () => {\n  const mockErrorResponse = { value: 'error', very: 'mean' }\n  const mockSuccessResponse = { value: 'success' }\n\n  const api = createApi({\n    baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n    endpoints: (build) => ({\n      update: build.mutation<typeof mockSuccessResponse, any>({\n        query: () => ({ url: 'success' }),\n      }),\n      failedUpdate: build.mutation<typeof mockSuccessResponse, any>({\n        query: () => ({ url: 'error' }),\n      }),\n    }),\n  })\n  const storeRef = setupApiStore(api)\n\n  test('a mutation is unwrappable and has the correct types', async () => {\n    server.use(\n      http.get(\n        'https://example.com/success',\n        () => HttpResponse.json(mockErrorResponse, { status: 500 }),\n        { once: true },\n      ),\n    )\n\n    function User() {\n      const [manualError, setManualError] = React.useState<any>()\n      const [update, { isLoading, data, error }] =\n        api.endpoints.update.useMutation()\n\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"data\">{JSON.stringify(data)}</div>\n          <div data-testid=\"error\">{JSON.stringify(error)}</div>\n          <div data-testid=\"manuallySetError\">\n            {JSON.stringify(manualError)}\n          </div>\n          <button\n            onClick={() => {\n              update({ name: 'hello' })\n                .unwrap()\n                .then((result) => {\n                  setManualError(undefined)\n                })\n                .catch((error) => act(() => setManualError(error)))\n            }}\n          >\n            Update User\n          </button>\n        </div>\n      )\n    }\n\n    render(<User />, { wrapper: storeRef.wrapper })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n    fireEvent.click(screen.getByText('Update User'))\n    expect(screen.getByTestId('isLoading').textContent).toBe('true')\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n\n    // Make sure the hook and the unwrapped action return the same things in an error state\n    await waitFor(() =>\n      expect(screen.getByTestId('error').textContent).toEqual(\n        screen.getByTestId('manuallySetError').textContent,\n      ),\n    )\n\n    fireEvent.click(screen.getByText('Update User'))\n    expect(screen.getByTestId('isLoading').textContent).toBe('true')\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('error').textContent).toBeFalsy(),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('manuallySetError').textContent).toBeFalsy(),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('data').textContent).toEqual(\n        JSON.stringify(mockSuccessResponse),\n      ),\n    )\n  })\n\n  for (const track of [true, false]) {\n    test(`an un-subscribed mutation will still return something useful (success case, track: ${track})`, async () => {\n      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })\n\n      const dispatch = hook.result.current as ThunkDispatch<\n        any,\n        any,\n        UnknownAction\n      >\n      let mutationqueryFulfilled: ReturnType<\n        ReturnType<typeof api.endpoints.update.initiate>\n      >\n      act(() => {\n        mutationqueryFulfilled = dispatch(\n          api.endpoints.update.initiate({}, { track }),\n        )\n      })\n      const result = await mutationqueryFulfilled!\n      expect(result).toMatchObject({\n        data: { value: 'success' },\n      })\n    })\n\n    test(`an un-subscribed mutation will still return something useful (error case, track: ${track})`, async () => {\n      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })\n\n      const dispatch = hook.result.current as ThunkDispatch<\n        any,\n        any,\n        UnknownAction\n      >\n      let mutationqueryFulfilled: ReturnType<\n        ReturnType<typeof api.endpoints.failedUpdate.initiate>\n      >\n      act(() => {\n        mutationqueryFulfilled = dispatch(\n          api.endpoints.failedUpdate.initiate({}, { track }),\n        )\n      })\n      const result = await mutationqueryFulfilled!\n      expect(result).toMatchObject({\n        error: {\n          status: 500,\n          data: { value: 'error' },\n        },\n      })\n    })\n    test(`an un-subscribed mutation will still be unwrappable (success case), track: ${track}`, async () => {\n      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })\n\n      const dispatch = hook.result.current as ThunkDispatch<\n        any,\n        any,\n        UnknownAction\n      >\n      let mutationqueryFulfilled: ReturnType<\n        ReturnType<typeof api.endpoints.update.initiate>\n      >\n      act(() => {\n        mutationqueryFulfilled = dispatch(\n          api.endpoints.update.initiate({}, { track }),\n        )\n      })\n      const result = await mutationqueryFulfilled!.unwrap()\n      expect(result).toMatchObject({\n        value: 'success',\n      })\n    })\n\n    test(`an un-subscribed mutation will still be unwrappable (error case, track: ${track})`, async () => {\n      const hook = renderHook(useDispatch, { wrapper: storeRef.wrapper })\n\n      const dispatch = hook.result.current as ThunkDispatch<\n        any,\n        any,\n        UnknownAction\n      >\n      let mutationqueryFulfilled: ReturnType<\n        ReturnType<typeof api.endpoints.failedUpdate.initiate>\n      >\n      act(() => {\n        mutationqueryFulfilled = dispatch(\n          api.endpoints.failedUpdate.initiate({}, { track }),\n        )\n      })\n      const unwrappedPromise = mutationqueryFulfilled!.unwrap()\n      await expect(unwrappedPromise).rejects.toMatchObject({\n        status: 500,\n        data: { value: 'error' },\n      })\n    })\n  }\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/fakeBaseQuery.test.tsx",
    "content": "import { noop } from '@internal/listenerMiddleware/utils'\nimport { configureStore } from '@reduxjs/toolkit'\nimport { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query'\n\ntype CustomErrorType = { type: 'Custom' }\n\nconst api = createApi({\n  baseQuery: fakeBaseQuery<CustomErrorType>(),\n  endpoints: (build) => ({\n    withQuery: build.query<string, string>({\n      // @ts-expect-error\n      query(arg: string) {\n        return `resultFrom(${arg})`\n      },\n      // @ts-expect-error\n      transformResponse(response) {\n        return response.wrappedByBaseQuery\n      },\n    }),\n    withQueryFn: build.query<string, string>({\n      queryFn(arg: string) {\n        return { data: `resultFrom(${arg})` }\n      },\n    }),\n    withInvalidDataQueryFn: build.query<string, string>({\n      // @ts-expect-error\n      queryFn(arg: string) {\n        return { data: 5 }\n      },\n    }),\n    withErrorQueryFn: build.query<string, string>({\n      queryFn(arg: string) {\n        return { error: { type: 'Custom' } }\n      },\n    }),\n    withInvalidErrorQueryFn: build.query<string, string>({\n      // @ts-expect-error\n      queryFn(arg: string) {\n        return { error: 5 }\n      },\n    }),\n    withAsyncQueryFn: build.query<string, string>({\n      async queryFn(arg: string) {\n        return { data: `resultFrom(${arg})` }\n      },\n    }),\n    withInvalidDataAsyncQueryFn: build.query<string, string>({\n      // @ts-expect-error\n      async queryFn(arg: string) {\n        return { data: 5 }\n      },\n    }),\n    withAsyncErrorQueryFn: build.query<string, string>({\n      async queryFn(arg: string) {\n        return { error: { type: 'Custom' } }\n      },\n    }),\n    withInvalidAsyncErrorQueryFn: build.query<string, string>({\n      // @ts-expect-error\n      async queryFn(arg: string) {\n        return { error: 5 }\n      },\n    }),\n\n    mutationWithQueryFn: build.mutation<string, string>({\n      queryFn(arg: string) {\n        return { data: `resultFrom(${arg})` }\n      },\n    }),\n    mutationWithInvalidDataQueryFn: build.mutation<string, string>({\n      // @ts-expect-error\n      queryFn(arg: string) {\n        return { data: 5 }\n      },\n    }),\n    mutationWithErrorQueryFn: build.mutation<string, string>({\n      queryFn(arg: string) {\n        return { error: { type: 'Custom' } }\n      },\n    }),\n    mutationWithInvalidErrorQueryFn: build.mutation<string, string>({\n      // @ts-expect-error\n      queryFn(arg: string) {\n        return { error: 5 }\n      },\n    }),\n\n    mutationWithAsyncQueryFn: build.mutation<string, string>({\n      async queryFn(arg: string) {\n        return { data: `resultFrom(${arg})` }\n      },\n    }),\n    mutationWithInvalidAsyncQueryFn: build.mutation<string, string>({\n      // @ts-expect-error\n      async queryFn(arg: string) {\n        return { data: 5 }\n      },\n    }),\n    mutationWithAsyncErrorQueryFn: build.mutation<string, string>({\n      async queryFn(arg: string) {\n        return { error: { type: 'Custom' } }\n      },\n    }),\n    mutationWithInvalidAsyncErrorQueryFn: build.mutation<string, string>({\n      // @ts-expect-error\n      async queryFn(arg: string) {\n        return { error: 5 }\n      },\n    }),\n    // @ts-expect-error\n    withNeither: build.query<string, string>({}),\n    // @ts-expect-error\n    mutationWithNeither: build.mutation<string, string>({}),\n  }),\n})\n\nconst store = configureStore({\n  reducer: {\n    [api.reducerPath]: api.reducer,\n  },\n  middleware: (gDM) => gDM({}).concat(api.middleware),\n})\n\ntest('fakeBaseQuery throws when invoking query', async () => {\n  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n\n  const thunk = api.endpoints.withQuery.initiate('')\n\n  const result = await store.dispatch(thunk)\n\n  expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n  expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n    `An unhandled error occurred processing a request for the endpoint \"withQuery\".\\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n    Error(\n      'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.',\n    ),\n  )\n\n  expect(result!.error).toEqual({\n    message:\n      'When using `fakeBaseQuery`, all queries & mutations must use the `queryFn` definition syntax.',\n    name: 'Error',\n    stack: expect.any(String),\n  })\n\n  consoleErrorSpy.mockRestore()\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/fetchBaseQuery.test.tsx",
    "content": "import { createSlice } from '@reduxjs/toolkit'\nimport type { BaseQueryApi, FetchArgs } from '@reduxjs/toolkit/query'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport { headersToObject } from 'headers-polyfill'\nimport { HttpResponse, delay, http } from 'msw'\nimport nodeFetch from 'node-fetch'\nimport queryString from 'query-string'\nimport { vi } from 'vitest'\nimport { setupApiStore } from '../../tests/utils/helpers'\nimport { server } from './mocks/server'\n\nconst defaultHeaders: Record<string, string> = {\n  fake: 'header',\n  delete: 'true',\n  delete2: '1',\n}\n\nconst baseUrl = 'https://example.com'\n\nconst baseQuery = fetchBaseQuery({\n  baseUrl,\n  prepareHeaders: (headers, { getState }) => {\n    const { token } = (getState() as RootState).auth\n\n    // If we have a token set in state, let's assume that we should be passing it.\n    if (token) {\n      headers.set('authorization', `Bearer ${token}`)\n    }\n    // A user could customize their behavior here, so we'll just test that custom scenarios would work.\n    const potentiallyConflictingKeys = Object.keys(defaultHeaders)\n    potentiallyConflictingKeys.forEach((key) => {\n      // Check for presence of a default key, if the incoming endpoint headers don't specify it as '', then set it\n      const existingValue = headers.get(key)\n      if (!existingValue && existingValue !== '') {\n        headers.set(key, String(defaultHeaders[key]))\n        // If an endpoint sets a header with a value of '', just delete the header.\n      } else if (headers.get(key) === '') {\n        headers.delete(key)\n      }\n    })\n\n    return headers\n  },\n})\n\nconst api = createApi({\n  baseQuery,\n  endpoints(build) {\n    return {\n      query: build.query({ query: () => ({ url: '/echo', headers: {} }) }),\n      mutation: build.mutation({\n        query: () => ({ url: '/echo', method: 'POST', credentials: 'omit' }),\n      }),\n    }\n  },\n})\n\nconst authSlice = createSlice({\n  name: 'auth',\n  initialState: {\n    token: '',\n  },\n  reducers: {\n    setToken(state, action) {\n      state.token = action.payload\n    },\n  },\n})\n\nconst storeRef = setupApiStore(api, { auth: authSlice.reducer })\ntype RootState = ReturnType<typeof storeRef.store.getState>\n\nlet commonBaseQueryApi: BaseQueryApi = {} as any\nbeforeEach(() => {\n  let abortController = new AbortController()\n  commonBaseQueryApi = {\n    signal: abortController.signal,\n    abort: (reason) =>\n      // @ts-ignore\n      abortController.abort(reason),\n    dispatch: storeRef.store.dispatch,\n    getState: storeRef.store.getState,\n    extra: undefined,\n    type: 'query',\n    endpoint: 'doesntmatterhere',\n  }\n})\n\ndescribe('fetchBaseQuery', () => {\n  describe('basic functionality', () => {\n    it('should return an object for a simple GET request when it is json data', async () => {\n      const req = baseQuery('/success', commonBaseQueryApi, {})\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.data).toEqual({ value: 'success' })\n    })\n\n    it('should return undefined for a simple GET request when the response is empty', async () => {\n      const req = baseQuery('/empty', commonBaseQueryApi, {})\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBeInstanceOf(Object)\n\n      expect(res.data).toBeNull()\n    })\n\n    it('should return an error and status for error responses', async () => {\n      const req = baseQuery('/error', commonBaseQueryApi, {})\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBeInstanceOf(Object)\n      expect(res.error).toEqual({\n        status: 500,\n        data: { value: 'error' },\n      })\n    })\n\n    it('should handle a connection loss semi-gracefully', async () => {\n      const fetchFn = vi\n        .fn()\n        .mockRejectedValueOnce(new TypeError('Failed to fetch'))\n\n      const req = fetchBaseQuery({\n        baseUrl,\n        fetchFn,\n      })('/success', commonBaseQueryApi, {})\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBe(undefined)\n      expect(res.error).toEqual({\n        status: 'FETCH_ERROR',\n        error: 'TypeError: Failed to fetch',\n      })\n    })\n  })\n\n  describe('non-JSON-body', () => {\n    it('success: should return data (\"text\" responseHandler)', async () => {\n      server.use(\n        http.get(\n          'https://example.com/success',\n          () => HttpResponse.text(`this is not json!`),\n          { once: true },\n        ),\n      )\n\n      const req = baseQuery(\n        { url: '/success', responseHandler: 'text' },\n        commonBaseQueryApi,\n        {},\n      )\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBeInstanceOf(Object)\n      expect(res.data).toEqual(`this is not json!`)\n    })\n\n    it('success: should fail gracefully (default=\"json\" responseHandler)', async () => {\n      server.use(\n        http.get(\n          'https://example.com/success',\n          () => HttpResponse.text(`this is not json!`),\n          { once: true },\n        ),\n      )\n\n      const req = baseQuery('/success', commonBaseQueryApi, {})\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBeInstanceOf(Object)\n      expect(res.error).toEqual({\n        status: 'PARSING_ERROR',\n        error: expect.stringMatching(/SyntaxError: Unexpected token/),\n        originalStatus: 200,\n        data: `this is not json!`,\n      })\n    })\n\n    it('success: parse text without error (\"content-type\" responseHandler)', async () => {\n      server.use(\n        http.get(\n          'https://example.com/success',\n          () => HttpResponse.text(`this is not json!`),\n          { once: true },\n        ),\n      )\n\n      const req = baseQuery(\n        {\n          url: '/success',\n          responseHandler: 'content-type',\n        },\n        commonBaseQueryApi,\n        {},\n      )\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.response?.headers.get('content-type')).toEqual(\n        'text/plain',\n      )\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBeInstanceOf(Object)\n      expect(res.data).toEqual(`this is not json!`)\n    })\n\n    it('success: parse json without error (\"content-type\" responseHandler)', async () => {\n      server.use(\n        http.get(\n          'https://example.com/success',\n          () => HttpResponse.json(`this will become json!`),\n          { once: true },\n        ),\n      )\n\n      const req = baseQuery(\n        {\n          url: '/success',\n          responseHandler: 'content-type',\n        },\n        commonBaseQueryApi,\n        {},\n      )\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.response?.headers.get('content-type')).toEqual(\n        'application/json',\n      )\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBeInstanceOf(Object)\n      expect(res.data).toEqual(`this will become json!`)\n    })\n\n    it('server error: should fail normally with a 500 status (\"text\" responseHandler)', async () => {\n      server.use(\n        http.get('https://example.com/error', () =>\n          HttpResponse.text(`this is not json!`, { status: 500 }),\n        ),\n      )\n\n      const req = baseQuery(\n        { url: '/error', responseHandler: 'text' },\n        commonBaseQueryApi,\n        {},\n      )\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBeInstanceOf(Object)\n      expect(res.error).toEqual({\n        status: 500,\n        data: `this is not json!`,\n      })\n    })\n\n    it('server error: should fail normally with a 500 status as text (\"content-type\" responseHandler)', async () => {\n      const serverResponse = 'Internal Server Error'\n      server.use(\n        http.get('https://example.com/error', () =>\n          HttpResponse.text(serverResponse, { status: 500 }),\n        ),\n      )\n\n      const req = baseQuery(\n        { url: '/error', responseHandler: 'content-type' },\n        commonBaseQueryApi,\n        {},\n      )\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBeInstanceOf(Object)\n      expect(res.meta?.response?.headers.get('content-type')).toEqual(\n        'text/plain',\n      )\n      expect(res.error).toEqual({\n        status: 500,\n        data: serverResponse,\n      })\n    })\n\n    it('server error: should fail normally with a 500 status as json (\"content-type\" responseHandler)', async () => {\n      const serverResponse = {\n        errors: { field1: \"Password cannot be 'password'\" },\n      }\n      server.use(\n        http.get('https://example.com/error', () =>\n          HttpResponse.json(serverResponse, { status: 500 }),\n        ),\n      )\n\n      const req = baseQuery(\n        { url: '/error', responseHandler: 'content-type' },\n        commonBaseQueryApi,\n        {},\n      )\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBeInstanceOf(Object)\n      expect(res.meta?.response?.headers.get('content-type')).toEqual(\n        'application/json',\n      )\n      expect(res.error).toEqual({\n        status: 500,\n        data: serverResponse,\n      })\n    })\n\n    it('server error: should fail gracefully (default=\"json\" responseHandler)', async () => {\n      server.use(\n        http.get('https://example.com/error', () =>\n          HttpResponse.text(`this is not json!`, { status: 500 }),\n        ),\n      )\n\n      const req = baseQuery('/error', commonBaseQueryApi, {})\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBeInstanceOf(Object)\n      expect(res.error).toEqual({\n        status: 'PARSING_ERROR',\n        error: expect.stringMatching(/SyntaxError: Unexpected token/),\n        originalStatus: 500,\n        data: `this is not json!`,\n      })\n    })\n  })\n\n  describe('arg.body', () => {\n    test('an object provided to body will be serialized when content-type is json', async () => {\n      const data = {\n        test: 'value',\n      }\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        { url: '/echo', body: data, method: 'POST' },\n        { ...commonBaseQueryApi, type: 'mutation' },\n        {},\n      ))\n\n      expect(request.headers['content-type']).toBe('application/json')\n      expect(request.body).toEqual(data)\n    })\n\n    test('an array provided to body will be serialized when content-type is json', async () => {\n      const data = ['test', 'value']\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        { url: '/echo', body: data, method: 'POST' },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.headers['content-type']).toBe('application/json')\n      expect(request.body).toEqual(data)\n    })\n\n    test('an object provided to body will not be serialized when content-type is not json', async () => {\n      const data = {\n        test: 'value',\n      }\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        {\n          url: '/echo',\n          body: data,\n          method: 'POST',\n          headers: { 'content-type': 'text/html' },\n        },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.headers['content-type']).toBe('text/html')\n      expect(request.body).toEqual('[object Object]')\n    })\n\n    test('an array provided to body will not be serialized when content-type is not json', async () => {\n      const data = ['test', 'value']\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        {\n          url: '/echo',\n          body: data,\n          method: 'POST',\n          headers: { 'content-type': 'text/html' },\n        },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.headers['content-type']).toBe('text/html')\n      expect(request.body).toEqual(data.join(','))\n    })\n\n    it('supports a custom jsonContentType', async () => {\n      const baseQuery = fetchBaseQuery({\n        baseUrl,\n        jsonContentType: 'application/vnd.api+json',\n      })\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        {\n          url: '/echo',\n          body: {},\n          method: 'POST',\n        },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.headers['content-type']).toBe('application/vnd.api+json')\n    })\n\n    it('supports a custom jsonReplacer', async () => {\n      const body = {\n        items: new Set(['A', 'B', 'C']),\n      }\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        {\n          url: '/echo',\n          body,\n          method: 'POST',\n        },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.headers['content-type']).toBe('application/json')\n      expect(request.body).toEqual({ items: {} }) // Set is not properly marshalled by default\n\n      // Use jsonReplacer\n      const baseQueryWithReplacer = fetchBaseQuery({\n        baseUrl,\n        jsonReplacer: (key, value) =>\n          value instanceof Set ? [...value] : value,\n      })\n\n      ;({ data: request } = await baseQueryWithReplacer(\n        {\n          url: '/echo',\n          body,\n          method: 'POST',\n        },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.headers['content-type']).toBe('application/json')\n      expect(request.body).toEqual({ items: ['A', 'B', 'C'] }) // Set is marshalled correctly by jsonReplacer\n    })\n  })\n\n  describe('arg.params', () => {\n    it('should not serialize missing params', async () => {\n      let request: any\n      ;({ data: request } = await baseQuery(\n        { url: '/echo' },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.url).toEqual(`${baseUrl}/echo`)\n    })\n\n    it('should serialize numeric and boolean params', async () => {\n      const params = { a: 1, b: true }\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        { url: '/echo', params },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.url).toEqual(`${baseUrl}/echo?a=1&b=true`)\n    })\n\n    it('should merge params into existing url querystring', async () => {\n      const params = { a: 1, b: true }\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        { url: '/echo?banana=pudding', params },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.url).toEqual(`${baseUrl}/echo?banana=pudding&a=1&b=true`)\n    })\n\n    it('should accept a URLSearchParams instance', async () => {\n      const params = new URLSearchParams({ apple: 'fruit' })\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        { url: '/echo', params },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit`)\n    })\n\n    it('should strip undefined values from the end params', async () => {\n      const params = { apple: 'fruit', banana: undefined, randy: null }\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        { url: '/echo', params },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit&randy=null`)\n    })\n\n    it('should support a paramsSerializer', async () => {\n      const baseQuery = fetchBaseQuery({\n        baseUrl,\n        paramsSerializer: (params: Record<string, unknown>) =>\n          queryString.stringify(params, { arrayFormat: 'bracket' }),\n      })\n\n      const api = createApi({\n        baseQuery,\n        endpoints(build) {\n          return {\n            query: build.query({\n              query: () => ({ url: '/echo', headers: {} }),\n            }),\n            mutation: build.mutation({\n              query: () => ({\n                url: '/echo',\n                method: 'POST',\n                credentials: 'omit',\n              }),\n            }),\n          }\n        },\n      })\n\n      const params = {\n        someArray: ['a', 'b', 'c'],\n      }\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        { url: '/echo', params },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.url).toEqual(\n        `${baseUrl}/echo?someArray[]=a&someArray[]=b&someArray[]=c`,\n      )\n    })\n\n    it('should supports a custom isJsonContentType function', async () => {\n      const testBody = {\n        i_should_be_stringified: true,\n      }\n      const baseQuery = fetchBaseQuery({\n        baseUrl,\n        isJsonContentType: (headers) =>\n          [\n            'application/vnd.api+json',\n            'application/json',\n            'application/vnd.hal+json',\n          ].includes(headers.get('content-type') ?? ''),\n      })\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        {\n          url: '/echo',\n          method: 'POST',\n          body: testBody,\n          headers: { 'content-type': 'application/vnd.hal+json' },\n        },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.body).toMatchObject(testBody)\n    })\n  })\n\n  describe('validateStatus', () => {\n    test('validateStatus can return an error even on normal 200 responses', async () => {\n      // This is a scenario where an API may always return a 200, but indicates there is an error when success = false\n      const res = await baseQuery(\n        {\n          url: '/nonstandard-error',\n          validateStatus: (response, body) =>\n            response.status === 200 && body.success === false ? false : true,\n        },\n        commonBaseQueryApi,\n        {},\n      )\n\n      expect(res.error).toEqual({\n        status: 200,\n        data: {\n          success: false,\n          message: 'This returns a 200 but is really an error',\n        },\n      })\n    })\n  })\n\n  describe('arg.headers and prepareHeaders', () => {\n    test('uses the default headers set in prepareHeaders', async () => {\n      let request: any\n      ;({ data: request } = await baseQuery(\n        { url: '/echo' },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.headers['fake']).toBe(defaultHeaders['fake'])\n      expect(request.headers['delete']).toBe(defaultHeaders['delete'])\n      expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])\n    })\n\n    test('adds endpoint-level headers to the defaults', async () => {\n      let request: any\n      ;({ data: request } = await baseQuery(\n        { url: '/echo', headers: { authorization: 'Bearer banana' } },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.headers['authorization']).toBe('Bearer banana')\n      expect(request.headers['fake']).toBe(defaultHeaders['fake'])\n      expect(request.headers['delete']).toBe(defaultHeaders['delete'])\n      expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])\n    })\n\n    test('it does not set application/json when content-type is set', async () => {\n      let request: any\n      ;({ data: request } = await baseQuery(\n        {\n          url: '/echo',\n          headers: {\n            authorization: 'Bearer banana',\n            'content-type': 'custom-content-type',\n          },\n        },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.headers['authorization']).toBe('Bearer banana')\n      expect(request.headers['content-type']).toBe('custom-content-type')\n      expect(request.headers['fake']).toBe(defaultHeaders['fake'])\n      expect(request.headers['delete']).toBe(defaultHeaders['delete'])\n      expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])\n    })\n\n    test('respects the headers from an endpoint over the base headers', async () => {\n      const fake = 'fake endpoint value'\n\n      let request: any\n      ;({ data: request } = await baseQuery(\n        { url: '/echo', headers: { fake, delete: '', delete2: '' } },\n        commonBaseQueryApi,\n        {},\n      ))\n\n      expect(request.headers['fake']).toBe(fake)\n      expect(request.headers['delete']).toBeUndefined()\n      expect(request.headers['delete2']).toBeUndefined()\n    })\n\n    test('prepareHeaders can return undefined', async () => {\n      let request: any\n\n      const token = 'accessToken'\n\n      const _baseQuery = fetchBaseQuery({\n        baseUrl,\n        prepareHeaders: (headers) => {\n          headers.set('authorization', `Bearer ${token}`)\n        },\n      })\n\n      const doRequest = async () =>\n        _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})\n\n      ;({ data: request } = await doRequest())\n\n      expect(request.headers['authorization']).toBe(`Bearer ${token}`)\n    })\n\n    test('prepareHeaders is able to be an async function', async () => {\n      let request: any\n\n      const token = 'accessToken'\n      const getAccessTokenAsync = async () => token\n\n      const _baseQuery = fetchBaseQuery({\n        baseUrl,\n        prepareHeaders: async (headers) => {\n          headers.set('authorization', `Bearer ${await getAccessTokenAsync()}`)\n          return headers\n        },\n      })\n\n      const doRequest = async () =>\n        _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})\n\n      ;({ data: request } = await doRequest())\n\n      expect(request.headers['authorization']).toBe(`Bearer ${token}`)\n    })\n\n    test('prepareHeaders is able to be an async function returning undefined', async () => {\n      let request: any\n\n      const token = 'accessToken'\n      const getAccessTokenAsync = async () => token\n\n      const _baseQuery = fetchBaseQuery({\n        baseUrl,\n        prepareHeaders: async (headers) => {\n          headers.set('authorization', `Bearer ${await getAccessTokenAsync()}`)\n        },\n      })\n\n      const doRequest = async () =>\n        _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})\n\n      ;({ data: request } = await doRequest())\n\n      expect(request.headers['authorization']).toBe(`Bearer ${token}`)\n    })\n\n    test('prepareHeaders is able to select from a state', async () => {\n      let request: any\n\n      const doRequest = async () => {\n        const abortController = new AbortController()\n        return baseQuery(\n          { url: '/echo' },\n          {\n            signal: abortController.signal,\n            abort: (reason) =>\n              // @ts-ignore\n              abortController.abort(reason),\n            dispatch: storeRef.store.dispatch,\n            getState: storeRef.store.getState,\n            extra: undefined,\n            type: 'query',\n            endpoint: '',\n          },\n          {},\n        )\n      }\n\n      ;({ data: request } = await doRequest())\n\n      expect(request.headers['authorization']).toBeUndefined()\n\n      // Set a token and the follow up request should have the header injected by prepareHeaders\n      const token = 'fakeToken!'\n      storeRef.store.dispatch(authSlice.actions.setToken(token))\n      ;({ data: request } = await doRequest())\n\n      expect(request.headers['authorization']).toBe(`Bearer ${token}`)\n    })\n\n    test('prepareHeaders provides extra api information for getState, extra, endpoint, type and forced', async () => {\n      let _getState, _arg: any, _extra, _endpoint, _type, _forced\n\n      const baseQuery = fetchBaseQuery({\n        baseUrl,\n        prepareHeaders: (\n          headers,\n          { getState, arg, extra, endpoint, type, forced },\n        ) => {\n          _getState = getState\n          _arg = arg\n          _endpoint = endpoint\n          _type = type\n          _forced = forced\n          _extra = extra\n\n          return headers\n        },\n      })\n\n      const fakeAuth0Client = {\n        getTokenSilently: async () => 'fakeToken',\n      }\n\n      const doRequest = async () => {\n        const abortController = new AbortController()\n        return baseQuery(\n          { url: '/echo' },\n          {\n            signal: abortController.signal,\n            abort: (reason) =>\n              // @ts-ignore\n              abortController.abort(reason),\n            dispatch: storeRef.store.dispatch,\n            getState: storeRef.store.getState,\n            extra: fakeAuth0Client,\n            type: 'query',\n            forced: true,\n            endpoint: 'someEndpointName',\n          },\n          {},\n        )\n      }\n\n      await doRequest()\n\n      expect(_getState).toBeDefined()\n      expect(_arg!.url).toBe('/echo')\n      expect(_endpoint).toBe('someEndpointName')\n      expect(_type).toBe('query')\n      expect(_forced).toBe(true)\n      expect(_extra).toBe(fakeAuth0Client)\n    })\n\n    test('can be instantiated with a `ExtraOptions` generic and `extraOptions` will be available in `prepareHeaders', async () => {\n      const prepare = vitest.fn()\n      const baseQuery = fetchBaseQuery({\n        prepareHeaders(headers, api) {\n          prepare.apply(undefined, arguments as unknown as any[])\n        },\n      })\n      baseQuery('https://example.com', commonBaseQueryApi, {\n        foo: 'baz',\n        bar: 5,\n      })\n      expect(prepare).toHaveBeenCalledWith(\n        expect.anything(),\n        expect.objectContaining({ extraOptions: { foo: 'baz', bar: 5 } }),\n      )\n\n      // ensure types\n      createApi({\n        baseQuery,\n        endpoints(build) {\n          return {\n            testQuery: build.query({\n              query: () => ({ url: '/echo', headers: {} }),\n              extraOptions: {\n                foo: 'asd',\n                bar: 1,\n              },\n            }),\n            testMutation: build.mutation({\n              query: () => ({\n                url: '/echo',\n                method: 'POST',\n                credentials: 'omit',\n              }),\n              extraOptions: {\n                foo: 'qwe',\n                bar: 15,\n              },\n            }),\n          }\n        },\n      })\n    })\n  })\n\n  test('can pass `headers` into `fetchBaseQuery`', async () => {\n    let request: any\n\n    const token = 'accessToken'\n\n    const _baseQuery = fetchBaseQuery({\n      baseUrl,\n      headers: { authorization: `Bearer ${token}` },\n    })\n\n    const doRequest = async () =>\n      _baseQuery({ url: '/echo' }, commonBaseQueryApi, {})\n\n    ;({ data: request } = await doRequest())\n\n    expect(request.headers['authorization']).toBe(`Bearer ${token}`)\n  })\n\n  test('lets a header be undefined', async () => {\n    let request: any\n    ;({ data: request } = await baseQuery(\n      { url: '/echo', headers: undefined },\n      commonBaseQueryApi,\n      {},\n    ))\n\n    expect(request.headers['fake']).toBe(defaultHeaders['fake'])\n    expect(request.headers['delete']).toBe(defaultHeaders['delete'])\n    expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])\n  })\n\n  test('allows for possibly undefined header key/values', async () => {\n    const banana = '1' as '1' | undefined\n    let request: any\n    ;({ data: request } = await baseQuery(\n      { url: '/echo', headers: { banana } },\n      commonBaseQueryApi,\n      {},\n    ))\n\n    expect(request.headers['banana']).toBe('1')\n    expect(request.headers['fake']).toBe(defaultHeaders['fake'])\n    expect(request.headers['delete']).toBe(defaultHeaders['delete'])\n    expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])\n  })\n\n  test('strips undefined values from the headers', async () => {\n    const banana = undefined as '1' | undefined\n    let request: any\n    ;({ data: request } = await baseQuery(\n      { url: '/echo', headers: { banana } },\n      commonBaseQueryApi,\n      {},\n    ))\n\n    expect(request.headers['banana']).toBeUndefined()\n    expect(request.headers['fake']).toBe(defaultHeaders['fake'])\n    expect(request.headers['delete']).toBe(defaultHeaders['delete'])\n    expect(request.headers['delete2']).toBe(defaultHeaders['delete2'])\n  })\n\n  describe('Accepts global arguments', () => {\n    test('Global responseHandler', async () => {\n      server.use(\n        http.get(\n          'https://example.com/success',\n          () => HttpResponse.text(`this is not json!`),\n          { once: true },\n        ),\n      )\n\n      const globalizedBaseQuery = fetchBaseQuery({\n        baseUrl,\n        responseHandler: 'text',\n      })\n\n      const req = globalizedBaseQuery(\n        { url: '/success' },\n        commonBaseQueryApi,\n        {},\n      )\n      expect(req).toBeInstanceOf(Promise)\n      const res = await req\n      expect(res).toBeInstanceOf(Object)\n      expect(res.meta?.request).toBeInstanceOf(Request)\n      expect(res.meta?.response).toBeInstanceOf(Object)\n      expect(res.error).toBeUndefined()\n      expect(res.data).toEqual(`this is not json!`)\n    })\n\n    test('Global responseHandler: content-type with text response', async () => {\n      server.use(\n        http.get(\n          'https://example.com/success',\n          () => HttpResponse.text(`this is plain text!`),\n          { once: true },\n        ),\n      )\n\n      const globalizedBaseQuery = fetchBaseQuery({\n        baseUrl,\n        responseHandler: 'content-type',\n      })\n\n      const res = await globalizedBaseQuery(\n        { url: '/success' },\n        commonBaseQueryApi,\n        {},\n      )\n\n      expect(res.error).toBeUndefined()\n      expect(res.data).toEqual(`this is plain text!`)\n      expect(res.meta?.response?.headers.get('content-type')).toEqual(\n        'text/plain',\n      )\n    })\n\n    test('Global responseHandler: content-type with JSON response', async () => {\n      server.use(\n        http.get(\n          'https://example.com/success',\n          () => HttpResponse.json({ message: 'this is json!' }),\n          { once: true },\n        ),\n      )\n\n      const globalizedBaseQuery = fetchBaseQuery({\n        baseUrl,\n        responseHandler: 'content-type',\n      })\n\n      const res = await globalizedBaseQuery(\n        { url: '/success' },\n        commonBaseQueryApi,\n        {},\n      )\n\n      expect(res.error).toBeUndefined()\n      expect(res.data).toEqual({ message: 'this is json!' })\n      expect(res.meta?.response?.headers.get('content-type')).toEqual(\n        'application/json',\n      )\n    })\n\n    test('Global responseHandler: content-type can be overridden at endpoint level', async () => {\n      server.use(\n        http.get(\n          'https://example.com/success',\n          () => HttpResponse.text(`this is text but will be parsed as json`),\n          { once: true },\n        ),\n      )\n\n      const globalizedBaseQuery = fetchBaseQuery({\n        baseUrl,\n        responseHandler: 'content-type',\n      })\n\n      // Override global content-type handler with explicit text handler\n      const res = await globalizedBaseQuery(\n        { url: '/success', responseHandler: 'text' },\n        commonBaseQueryApi,\n        {},\n      )\n\n      expect(res.error).toBeUndefined()\n      expect(res.data).toEqual(`this is text but will be parsed as json`)\n    })\n\n    test('Global responseHandler: content-type with error response (text)', async () => {\n      const errorMessage = 'Internal Server Error'\n      server.use(\n        http.get('https://example.com/error', () =>\n          HttpResponse.text(errorMessage, { status: 500 }),\n        ),\n      )\n\n      const globalizedBaseQuery = fetchBaseQuery({\n        baseUrl,\n        responseHandler: 'content-type',\n      })\n\n      const res = await globalizedBaseQuery(\n        { url: '/error' },\n        commonBaseQueryApi,\n        {},\n      )\n\n      expect(res.error).toEqual({\n        status: 500,\n        data: errorMessage,\n      })\n      expect(res.meta?.response?.headers.get('content-type')).toEqual(\n        'text/plain',\n      )\n    })\n\n    test('Global responseHandler: content-type with error response (JSON)', async () => {\n      const errorData = { error: 'Something went wrong', code: 'ERR_500' }\n      server.use(\n        http.get('https://example.com/error', () =>\n          HttpResponse.json(errorData, { status: 500 }),\n        ),\n      )\n\n      const globalizedBaseQuery = fetchBaseQuery({\n        baseUrl,\n        responseHandler: 'content-type',\n      })\n\n      const res = await globalizedBaseQuery(\n        { url: '/error' },\n        commonBaseQueryApi,\n        {},\n      )\n\n      expect(res.error).toEqual({\n        status: 500,\n        data: errorData,\n      })\n      expect(res.meta?.response?.headers.get('content-type')).toEqual(\n        'application/json',\n      )\n    })\n\n    test('Global validateStatus', async () => {\n      const globalizedBaseQuery = fetchBaseQuery({\n        baseUrl,\n        validateStatus: (response, body) =>\n          response.status === 200 && body.success === false ? false : true,\n      })\n\n      // This is a scenario where an API may always return a 200, but indicates there is an error when success = false\n      const res = await globalizedBaseQuery(\n        {\n          url: '/nonstandard-error',\n        },\n        commonBaseQueryApi,\n        {},\n      )\n\n      expect(res.error).toEqual({\n        status: 200,\n        data: {\n          success: false,\n          message: 'This returns a 200 but is really an error',\n        },\n      })\n    })\n\n    test('Global timeout', async () => {\n      server.use(\n        http.get(\n          'https://example.com/empty1',\n          async ({ request, cookies, params, requestId }) => {\n            await delay(300)\n\n            return HttpResponse.json({\n              ...request,\n              cookies,\n              params,\n              requestId,\n              url: new URL(request.url),\n              headers: headersToObject(request.headers),\n            })\n          },\n          { once: true },\n        ),\n      )\n\n      const globalizedBaseQuery = fetchBaseQuery({\n        baseUrl,\n        timeout: 200,\n      })\n\n      const result = await globalizedBaseQuery(\n        { url: '/empty1' },\n        commonBaseQueryApi,\n        {},\n      )\n\n      expect(result?.error).toEqual({\n        status: 'TIMEOUT_ERROR',\n        error: expect.stringMatching(/^TimeoutError/),\n      })\n    })\n  })\n})\n\ndescribe('fetchFn', () => {\n  test('accepts a custom fetchFn', async () => {\n    const baseUrl = 'https://example.com'\n    const params = new URLSearchParams({ apple: 'fruit' })\n\n    const baseQuery = fetchBaseQuery({\n      baseUrl,\n      fetchFn: nodeFetch as any,\n    })\n    let request: any\n    ;({ data: request } = await baseQuery(\n      { url: '/echo', params },\n      commonBaseQueryApi,\n      {},\n    ))\n\n    expect(request.url).toEqual(`${baseUrl}/echo?apple=fruit`)\n  })\n\n  test('respects mocking window.fetch after a fetch base query is created', async () => {\n    const baseUrl = 'https://example.com'\n    const baseQuery = fetchBaseQuery({ baseUrl })\n\n    const fakeResponse = {\n      ok: true,\n      status: 200,\n      text: async () => `{ \"url\": \"mock-return-url\" }`,\n      clone: () => fakeResponse,\n    }\n\n    const spiedFetch = vi.spyOn(window, 'fetch')\n    spiedFetch.mockResolvedValueOnce(fakeResponse as any)\n\n    const { data } = await baseQuery({ url: '/echo' }, commonBaseQueryApi, {})\n    expect(data).toEqual({ url: 'mock-return-url' })\n\n    spiedFetch.mockClear()\n  })\n})\n\ndescribe('FormData', () => {\n  test('sets the right headers when sending FormData', async () => {\n    const body = new FormData()\n\n    body.append('username', 'test')\n\n    body.append(\n      'file',\n      new Blob([JSON.stringify({ hello: 'there' }, null, 2)], {\n        type: 'application/json',\n      }),\n    )\n\n    const res = await baseQuery(\n      { url: '/echo', method: 'POST', body },\n      commonBaseQueryApi,\n      {},\n    )\n\n    const request: any = res.data\n\n    expect(request.headers['content-type']).not.toContain('application/json')\n  })\n\n  test('FormData works correctly when prepareHeaders sets Content-Type to application/json', async () => {\n    // This test covers the exact scenario from issue #4669\n    const baseQueryWithJsonDefault = fetchBaseQuery({\n      baseUrl,\n      prepareHeaders: (headers) => {\n        // Set default Content-Type for all requests\n        headers.set('Content-Type', 'application/json')\n        return headers\n      },\n    })\n\n    const body = new FormData()\n    body.append('username', 'test')\n    body.append(\n      'file',\n      new Blob([JSON.stringify({ hello: 'there' }, null, 2)], {\n        type: 'application/json',\n      }),\n    )\n\n    const res = await baseQueryWithJsonDefault(\n      { url: '/echo', method: 'POST', body },\n      commonBaseQueryApi,\n      {},\n    )\n\n    const request: any = res.data\n\n    // The Content-Type should NOT be application/json when FormData is used\n    expect(request.headers['content-type']).not.toContain('application/json')\n    // It should contain multipart/form-data (set automatically by the browser)\n    expect(request.headers['content-type']).toContain('multipart/form-data')\n  })\n\n  test('FormData works when prepareHeaders conditionally removes Content-Type', async () => {\n    // This tests the workaround solution from the issue comments\n    const baseQueryWithConditionalHeader = fetchBaseQuery({\n      baseUrl,\n      prepareHeaders: (headers, { arg }) => {\n        // Check if body is FormData and skip setting Content-Type\n        if ((arg as FetchArgs).body instanceof FormData) {\n          // Delete Content-Type to let browser set it automatically\n          headers.delete('Content-Type')\n        } else {\n          // Set default Content-Type for non-FormData requests\n          headers.set('Content-Type', 'application/json')\n        }\n        return headers\n      },\n    })\n\n    const body = new FormData()\n    body.append('username', 'test')\n    body.append('file', new Blob(['test content'], { type: 'text/plain' }))\n\n    const res = await baseQueryWithConditionalHeader(\n      { url: '/echo', method: 'POST', body },\n      commonBaseQueryApi,\n      {},\n    )\n\n    const request: any = res.data\n\n    // Should have multipart/form-data set by browser\n    expect(request.headers['content-type']).toContain('multipart/form-data')\n    expect(request.headers['content-type']).not.toContain('application/json')\n  })\n\n  test('endpoint-level headers cannot override to multipart/form-data manually', async () => {\n    // This tests the fetch API quirk mentioned in the issue\n    const baseQueryWithJsonDefault = fetchBaseQuery({\n      baseUrl,\n      prepareHeaders: (headers) => {\n        headers.set('Content-Type', 'application/json')\n        return headers\n      },\n    })\n\n    const body = new FormData()\n    body.append('test', 'value')\n\n    const res = await baseQueryWithJsonDefault(\n      {\n        url: '/echo',\n        method: 'POST',\n        body,\n        // Attempting to manually set multipart/form-data (this won't work as expected)\n        headers: { 'Content-Type': 'multipart/form-data' },\n      },\n      commonBaseQueryApi,\n      {},\n    )\n\n    const request: any = res.data\n\n    // Due to prepareHeaders running after endpoint headers,\n    // and the fetch API not allowing manual multipart/form-data setting,\n    // this demonstrates the problem from the issue\n    // The actual behavior depends on fetchBaseQuery implementation\n    expect(request.headers['content-type']).toBeDefined()\n  })\n\n  test('non-FormData requests still get application/json from prepareHeaders', async () => {\n    // Verify that the workaround doesn't break normal JSON requests\n    const baseQueryWithConditionalHeader = fetchBaseQuery({\n      baseUrl,\n      prepareHeaders: (headers, { arg }) => {\n        if (!((arg as FetchArgs).body instanceof FormData)) {\n          headers.set('Content-Type', 'application/json')\n        }\n        return headers\n      },\n    })\n\n    const jsonBody = { test: 'value' }\n\n    const res = await baseQueryWithConditionalHeader(\n      { url: '/echo', method: 'POST', body: jsonBody },\n      commonBaseQueryApi,\n      {},\n    )\n\n    const request: any = res.data\n\n    // Regular JSON requests should still get application/json\n    expect(request.headers['content-type']).toBe('application/json')\n    expect(request.body).toEqual(jsonBody)\n  })\n})\n\ndescribe('Accept header handling', () => {\n  test('sets Accept header to application/json for json responseHandler', async () => {\n    let request: any\n    ;({ data: request } = await baseQuery(\n      { url: '/echo', responseHandler: 'json' },\n      commonBaseQueryApi,\n      {},\n    ))\n\n    expect(request.headers['accept']).toBe('application/json')\n  })\n\n  test('sets Accept header to application/json by default (json is default responseHandler)', async () => {\n    let request: any\n    ;({ data: request } = await baseQuery(\n      { url: '/echo' },\n      commonBaseQueryApi,\n      {},\n    ))\n\n    expect(request.headers['accept']).toBe('application/json')\n  })\n\n  test('sets Accept header for text responseHandler', async () => {\n    // Create a baseQuery with text as the global responseHandler\n    const textBaseQuery = fetchBaseQuery({\n      baseUrl,\n      responseHandler: 'text',\n    })\n\n    let request: any\n      // Override to json just for this test so we can inspect the echoed request object\n    ;({ data: request } = await textBaseQuery(\n      { url: '/echo', responseHandler: 'json' },\n      commonBaseQueryApi,\n      {},\n    ))\n\n    // The endpoint-level 'json' responseHandler overrides the global 'text',\n    // so the Accept header should be application/json\n    expect(request.headers['accept']).toBe('application/json')\n  })\n\n  test('does not override explicit Accept header from endpoint', async () => {\n    let request: any\n    ;({ data: request } = await baseQuery(\n      {\n        url: '/echo',\n        responseHandler: 'json',\n        headers: { Accept: 'application/xml' },\n      },\n      commonBaseQueryApi,\n      {},\n    ))\n\n    expect(request.headers['accept']).toBe('application/xml')\n  })\n\n  test('does not override Accept header set in prepareHeaders', async () => {\n    const customBaseQuery = fetchBaseQuery({\n      baseUrl,\n      prepareHeaders: (headers) => {\n        headers.set('Accept', 'application/vnd.api+json')\n        return headers\n      },\n    })\n\n    let request: any\n    ;({ data: request } = await customBaseQuery(\n      { url: '/echo', responseHandler: 'json' },\n      commonBaseQueryApi,\n      {},\n    ))\n\n    expect(request.headers['accept']).toBe('application/vnd.api+json')\n  })\n\n  test('does not set Accept header for content-type responseHandler', async () => {\n    let request: any\n    ;({ data: request } = await baseQuery(\n      { url: '/echo', responseHandler: 'content-type' },\n      commonBaseQueryApi,\n      {},\n    ))\n\n    // Should either not have accept header or have a permissive one\n    // content-type handler adapts to whatever server sends\n    const acceptHeader = request.headers['accept']\n    if (acceptHeader) {\n      expect(acceptHeader).toMatch(/\\*\\/\\*/)\n    }\n  })\n\n  test('respects global responseHandler for Accept header', async () => {\n    const textBaseQuery = fetchBaseQuery({\n      baseUrl,\n      responseHandler: 'text',\n    })\n\n    let request: any\n      // Override to json just for this test so we can inspect the echoed request object\n    ;({ data: request } = await textBaseQuery(\n      { url: '/echo', responseHandler: 'json' },\n      commonBaseQueryApi,\n      {},\n    ))\n\n    // The endpoint-level 'json' responseHandler overrides the global 'text',\n    // so the Accept header should be application/json (proving endpoint-level takes precedence)\n    expect(request.headers['accept']).toBe('application/json')\n  })\n})\n\ndescribe('still throws on completely unexpected errors', () => {\n  test('', async () => {\n    const error = new Error('some unexpected error')\n    const req = baseQuery(\n      {\n        url: '/success',\n        validateStatus() {\n          throw error\n        },\n      },\n      commonBaseQueryApi,\n      {},\n    )\n    expect(req).toBeInstanceOf(Promise)\n    await expect(req).rejects.toBe(error)\n  })\n})\n\ndescribe('timeout', () => {\n  test('throws a timeout error when a request takes longer than specified timeout duration', async () => {\n    server.use(\n      http.get(\n        'https://example.com/empty2',\n        async ({ request, cookies, params, requestId }) => {\n          await delay(300)\n\n          return HttpResponse.json({\n            ...request,\n            url: new URL(request.url),\n            cookies,\n            params,\n            requestId,\n            headers: headersToObject(request.headers),\n          })\n        },\n        { once: true },\n      ),\n    )\n\n    const result = await baseQuery(\n      { url: '/empty2', timeout: 200 },\n      commonBaseQueryApi,\n      {},\n    )\n\n    expect(result?.error).toEqual({\n      status: 'TIMEOUT_ERROR',\n      error: expect.stringMatching(/^TimeoutError/),\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/infiniteQueries.test-d.ts",
    "content": "import { createSlice } from '@reduxjs/toolkit'\nimport type { InfiniteData, skipToken } from '@reduxjs/toolkit/query/react'\nimport {\n  createApi,\n  fetchBaseQuery,\n  QueryStatus,\n} from '@reduxjs/toolkit/query/react'\nimport { setupApiStore } from '../../tests/utils/helpers'\n\ndescribe('Infinite queries', () => {\n  test('Basic infinite query behavior', async () => {\n    type Pokemon = {\n      id: string\n      name: string\n    }\n\n    const pokemonApi = createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n      endpoints: (build) => ({\n        getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({\n          infiniteQueryOptions: {\n            initialPageParam: 0,\n            getNextPageParam: (\n              lastPage,\n              allPages,\n              lastPageParam,\n              allPageParams,\n              queryArg,\n            ) => {\n              expectTypeOf(lastPage).toEqualTypeOf<Pokemon[]>()\n\n              expectTypeOf(allPages).toEqualTypeOf<Pokemon[][]>()\n\n              expectTypeOf(lastPageParam).toBeNumber()\n\n              expectTypeOf(allPageParams).toEqualTypeOf<number[]>()\n\n              expectTypeOf(queryArg).toBeString()\n\n              return lastPageParam + 1\n            },\n          },\n          query({ pageParam, queryArg }) {\n            expectTypeOf(pageParam).toBeNumber()\n            expectTypeOf(queryArg).toBeString()\n\n            return `https://example.com/listItems?page=${pageParam}`\n          },\n          async onCacheEntryAdded(arg, api) {\n            const data = await api.cacheDataLoaded\n            expectTypeOf(data.data).toEqualTypeOf<\n              InfiniteData<Pokemon[], number>\n            >()\n          },\n          async onQueryStarted(arg, api) {\n            const data = await api.queryFulfilled\n            expectTypeOf(data.data).toEqualTypeOf<\n              InfiniteData<Pokemon[], number>\n            >()\n          },\n          providesTags: (result) => {\n            expectTypeOf(result).toEqualTypeOf<\n              InfiniteData<Pokemon[], number> | undefined\n            >()\n            return []\n          },\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(pokemonApi, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    expectTypeOf(pokemonApi.endpoints.getInfinitePokemon.initiate)\n      .parameter(0)\n      .toBeString()\n\n    expectTypeOf(pokemonApi.useGetInfinitePokemonInfiniteQuery).toBeFunction()\n\n    expectTypeOf<\n      Parameters<\n        typeof pokemonApi.endpoints.getInfinitePokemon.useInfiniteQuery\n      >[0]\n    >().toEqualTypeOf<string | typeof skipToken>()\n\n    expectTypeOf(pokemonApi.endpoints.getInfinitePokemon.useInfiniteQueryState)\n      .parameter(0)\n      .toEqualTypeOf<string | typeof skipToken>()\n\n    expectTypeOf(\n      pokemonApi.endpoints.getInfinitePokemon.useInfiniteQuerySubscription,\n    )\n      .parameter(0)\n      .toEqualTypeOf<string | typeof skipToken>()\n\n    const slice = createSlice({\n      name: 'pokemon',\n      initialState: {} as { data: Pokemon[] },\n      reducers: {},\n      extraReducers: (builder) => {\n        builder.addMatcher(\n          pokemonApi.endpoints.getInfinitePokemon.matchFulfilled,\n          (state, action) => {\n            expectTypeOf(action.payload).toEqualTypeOf<\n              InfiniteData<Pokemon[], number>\n            >()\n          },\n        )\n      },\n    })\n\n    const res = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),\n    )\n\n    const firstResult = await res\n\n    if (firstResult.status === QueryStatus.fulfilled) {\n      expectTypeOf(firstResult.data.pages).toEqualTypeOf<Pokemon[][]>()\n      expectTypeOf(firstResult.data.pageParams).toEqualTypeOf<number[]>()\n    }\n\n    storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {\n        direction: 'forward',\n      }),\n    )\n\n    const useGetInfinitePokemonQuery =\n      pokemonApi.endpoints.getInfinitePokemon.useInfiniteQuery\n\n    expectTypeOf<\n      Parameters<typeof useGetInfinitePokemonQuery>[0]\n    >().toEqualTypeOf<string | typeof skipToken>()\n\n    function PokemonList() {\n      const {\n        data,\n        currentData,\n        isFetching,\n        isUninitialized,\n        isSuccess,\n        fetchNextPage,\n      } = useGetInfinitePokemonQuery('a')\n\n      expectTypeOf(data).toEqualTypeOf<\n        InfiniteData<Pokemon[], number> | undefined\n      >()\n\n      if (isSuccess) {\n        expectTypeOf(data.pages).toEqualTypeOf<Pokemon[][]>()\n        expectTypeOf(data.pageParams).toEqualTypeOf<number[]>()\n      }\n\n      if (currentData) {\n        expectTypeOf(currentData.pages).toEqualTypeOf<Pokemon[][]>()\n        expectTypeOf(currentData.pageParams).toEqualTypeOf<number[]>()\n      }\n\n      const handleClick = async () => {\n        const res = await fetchNextPage()\n\n        if (res.status === QueryStatus.fulfilled) {\n          expectTypeOf(res.data.pages).toEqualTypeOf<Pokemon[][]>()\n          expectTypeOf(res.data.pageParams).toEqualTypeOf<number[]>()\n        }\n      }\n    }\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/infiniteQueries.test.ts",
    "content": "import { server } from '@internal/query/tests/mocks/server'\nimport type { InfiniteQueryActionCreatorResult } from '@reduxjs/toolkit/query/react'\nimport {\n  QueryStatus,\n  createApi,\n  fakeBaseQuery,\n  fetchBaseQuery,\n} from '@reduxjs/toolkit/query/react'\nimport { HttpResponse, delay, http } from 'msw'\nimport { actionsReducer, setupApiStore } from '../../tests/utils/helpers'\nimport type { InfiniteQueryResultFlags } from '../core/buildSelectors'\n\ndescribe('Infinite queries', () => {\n  type Pokemon = {\n    id: string\n    name: string\n  }\n\n  type HitCounter = { page: number; hitCounter: number }\n  let counters: Record<string, number> = {}\n  let queryCounter = 0\n\n  const pokemonApi = createApi({\n    baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n    endpoints: (build) => ({\n      getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({\n        infiniteQueryOptions: {\n          initialPageParam: 0,\n          getNextPageParam: (\n            lastPage,\n            allPages,\n            lastPageParam,\n            allPageParams,\n            queryArg,\n          ) => {\n            expect(typeof queryArg).toBe('string')\n            return lastPageParam + 1\n          },\n          getPreviousPageParam: (\n            firstPage,\n            allPages,\n            firstPageParam,\n            allPageParams,\n            queryArg,\n          ) => {\n            expect(typeof queryArg).toBe('string')\n            return firstPageParam > 0 ? firstPageParam - 1 : undefined\n          },\n        },\n        query({ pageParam }) {\n          return `https://example.com/listItems?page=${pageParam}`\n        },\n      }),\n      getInfinitePokemonWithMax: build.infiniteQuery<Pokemon[], string, number>(\n        {\n          infiniteQueryOptions: {\n            initialPageParam: 0,\n            maxPages: 3,\n            getNextPageParam: (\n              lastPage,\n              allPages,\n              lastPageParam,\n              allPageParams,\n            ) => lastPageParam + 1,\n            getPreviousPageParam: (\n              firstPage,\n              allPages,\n              firstPageParam,\n              allPageParams,\n            ) => {\n              return firstPageParam > 0 ? firstPageParam - 1 : undefined\n            },\n          },\n          query({ pageParam }) {\n            return `https://example.com/listItems?page=${pageParam}`\n          },\n        },\n      ),\n      counters: build.query<{ id: string; counter: number }, string>({\n        queryFn: async (arg) => {\n          if (!(arg in counters)) {\n            counters[arg] = 0\n          }\n          counters[arg]++\n\n          return { data: { id: arg, counter: counters[arg] } }\n        },\n      }),\n    }),\n  })\n\n  function createCountersApi() {\n    let hitCounter = 0\n\n    const countersApi = createApi({\n      baseQuery: fakeBaseQuery(),\n      tagTypes: ['Counter'],\n      endpoints: (build) => ({\n        counters: build.infiniteQuery<HitCounter, string, number>({\n          queryFn({ pageParam }) {\n            hitCounter++\n\n            return { data: { page: pageParam, hitCounter } }\n          },\n          infiniteQueryOptions: {\n            initialPageParam: 0,\n            getNextPageParam: (\n              lastPage,\n              allPages,\n              lastPageParam,\n              allPageParams,\n            ) => lastPageParam + 1,\n          },\n          providesTags: ['Counter'],\n        }),\n        mutation: build.mutation<null, void>({\n          queryFn: async () => {\n            return { data: null }\n          },\n          invalidatesTags: ['Counter'],\n        }),\n      }),\n    })\n\n    return countersApi\n  }\n\n  let storeRef = setupApiStore(\n    pokemonApi,\n    { ...actionsReducer },\n    {\n      withoutTestLifecycles: true,\n    },\n  )\n\n  beforeEach(() => {\n    server.use(\n      http.get('https://example.com/listItems', ({ request }) => {\n        const url = new URL(request.url)\n        const pageString = url.searchParams.get('page')\n        const pageNum = parseInt(pageString || '0')\n        queryCounter++\n\n        const results: Pokemon[] = [\n          { id: `${pageNum}`, name: `Pokemon ${pageNum}` },\n        ]\n        return HttpResponse.json(results)\n      }),\n    )\n\n    storeRef = setupApiStore(\n      pokemonApi,\n      { ...actionsReducer },\n      {\n        withoutTestLifecycles: true,\n      },\n    )\n\n    counters = {}\n\n    queryCounter = 0\n  })\n\n  type InfiniteQueryResult = Awaited<InfiniteQueryActionCreatorResult<any>>\n\n  const checkResultData = (\n    result: InfiniteQueryResult,\n    expectedValues: Pokemon[][],\n  ) => {\n    expect(result.status).toBe(QueryStatus.fulfilled)\n    if (result.status === QueryStatus.fulfilled) {\n      expect(result.data.pages).toEqual(expectedValues)\n    }\n  }\n\n  const checkResultLength = (\n    result: InfiniteQueryResult,\n    expectedLength: number,\n  ) => {\n    expect(result.status).toBe(QueryStatus.fulfilled)\n    if (result.status === QueryStatus.fulfilled) {\n      expect(result.data.pages).toHaveLength(expectedLength)\n    }\n  }\n\n  test('Basic infinite query behavior', async () => {\n    const checkFlags = (\n      value: unknown,\n      expectedFlags: Partial<InfiniteQueryResultFlags>,\n    ) => {\n      const actualFlags: InfiniteQueryResultFlags = {\n        hasNextPage: false,\n        hasPreviousPage: false,\n        isFetchingNextPage: false,\n        isFetchingPreviousPage: false,\n        isFetchNextPageError: false,\n        isFetchPreviousPageError: false,\n        ...expectedFlags,\n      }\n\n      expect(value).toMatchObject(actualFlags)\n    }\n\n    const checkEntryFlags = (\n      arg: string,\n      expectedFlags: Partial<InfiniteQueryResultFlags>,\n    ) => {\n      const selector = pokemonApi.endpoints.getInfinitePokemon.select(arg)\n      const entry = selector(storeRef.store.getState())\n\n      checkFlags(entry, expectedFlags)\n    }\n\n    const res1 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),\n    )\n\n    checkEntryFlags('fire', {})\n\n    const entry1InitialLoad = await res1\n\n    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])\n    checkFlags(entry1InitialLoad, {\n      hasNextPage: true,\n    })\n\n    const res2 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {\n        direction: 'forward',\n      }),\n    )\n\n    checkEntryFlags('fire', {\n      hasNextPage: true,\n      isFetchingNextPage: true,\n    })\n\n    const entry1SecondPage = await res2\n\n    checkResultData(entry1SecondPage, [\n      [{ id: '0', name: 'Pokemon 0' }],\n      [{ id: '1', name: 'Pokemon 1' }],\n    ])\n    checkFlags(entry1SecondPage, {\n      hasNextPage: true,\n    })\n\n    const res3 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {\n        direction: 'backward',\n      }),\n    )\n\n    checkEntryFlags('fire', {\n      hasNextPage: true,\n      isFetchingPreviousPage: true,\n    })\n\n    const entry1PrevPageMissing = await res3\n\n    checkResultData(entry1PrevPageMissing, [\n      [{ id: '0', name: 'Pokemon 0' }],\n      [{ id: '1', name: 'Pokemon 1' }],\n    ])\n    checkFlags(entry1PrevPageMissing, {\n      hasNextPage: true,\n    })\n\n    const res4 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('water', {\n        initialPageParam: 3,\n      }),\n    )\n\n    checkEntryFlags('water', {})\n\n    const entry2InitialLoad = await res4\n\n    checkResultData(entry2InitialLoad, [[{ id: '3', name: 'Pokemon 3' }]])\n    checkFlags(entry2InitialLoad, {\n      hasNextPage: true,\n      hasPreviousPage: true,\n    })\n\n    const res5 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('water', {\n        direction: 'forward',\n      }),\n    )\n\n    checkEntryFlags('water', {\n      hasNextPage: true,\n      hasPreviousPage: true,\n      isFetchingNextPage: true,\n    })\n\n    const entry2NextPage = await res5\n\n    checkResultData(entry2NextPage, [\n      [{ id: '3', name: 'Pokemon 3' }],\n      [{ id: '4', name: 'Pokemon 4' }],\n    ])\n    checkFlags(entry2NextPage, {\n      hasNextPage: true,\n      hasPreviousPage: true,\n    })\n\n    const res6 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('water', {\n        direction: 'backward',\n      }),\n    )\n\n    checkEntryFlags('water', {\n      hasNextPage: true,\n      hasPreviousPage: true,\n      isFetchingPreviousPage: true,\n    })\n\n    const entry2PrevPage = await res6\n\n    checkResultData(entry2PrevPage, [\n      [{ id: '2', name: 'Pokemon 2' }],\n      [{ id: '3', name: 'Pokemon 3' }],\n      [{ id: '4', name: 'Pokemon 4' }],\n    ])\n    checkFlags(entry2PrevPage, {\n      hasNextPage: true,\n      hasPreviousPage: true,\n    })\n  })\n\n  test('does not have a page limit without maxPages', async () => {\n    for (let i = 1; i <= 10; i++) {\n      const res = await storeRef.store.dispatch(\n        pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {\n          direction: 'forward',\n        }),\n      )\n\n      checkResultLength(res, i)\n    }\n  })\n\n  test('applies a page limit with maxPages', async () => {\n    for (let i = 1; i <= 10; i++) {\n      const res = await storeRef.store.dispatch(\n        pokemonApi.endpoints.getInfinitePokemonWithMax.initiate('fire', {\n          direction: 'forward',\n        }),\n      )\n\n      checkResultLength(res, Math.min(i, 3))\n    }\n\n    // Should now have entries 7, 8, 9 after the loop\n\n    const res = await storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemonWithMax.initiate('fire', {\n        direction: 'backward',\n      }),\n    )\n\n    checkResultData(res, [\n      [{ id: '6', name: 'Pokemon 6' }],\n      [{ id: '7', name: 'Pokemon 7' }],\n      [{ id: '8', name: 'Pokemon 8' }],\n    ])\n  })\n\n  test('validates maxPages during createApi call', async () => {\n    vi.stubEnv('NODE_ENV', 'development')\n\n    const createApiWithMaxPages = (\n      maxPages: number,\n      getPreviousPageParam: (() => number) | undefined,\n    ) => {\n      createApi({\n        baseQuery: fakeBaseQuery(),\n        endpoints: (build) => ({\n          getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({\n            query(pageParam) {\n              return `https://example.com/listItems?page=${pageParam}`\n            },\n            infiniteQueryOptions: {\n              initialPageParam: 0,\n              maxPages,\n              getNextPageParam: () => 1,\n              getPreviousPageParam,\n            },\n          }),\n        }),\n      })\n    }\n\n    expect(() => createApiWithMaxPages(0, () => 0)).toThrowError(\n      `maxPages for endpoint 'getInfinitePokemon' must be a number greater than 0`,\n    )\n\n    expect(() => createApiWithMaxPages(1, undefined)).toThrowError(\n      `getPreviousPageParam for endpoint 'getInfinitePokemon' must be a function if maxPages is used`,\n    )\n  })\n\n  test('refetches all existing pages', async () => {\n    const checkResultData = (\n      result: InfiniteQueryResult,\n      expectedValues: HitCounter[],\n    ) => {\n      expect(result.status).toBe(QueryStatus.fulfilled)\n      if (result.status === QueryStatus.fulfilled) {\n        expect(result.data.pages).toEqual(expectedValues)\n      }\n    }\n\n    const countersApi = createCountersApi()\n\n    const storeRef = setupApiStore(\n      countersApi,\n      { ...actionsReducer },\n      {\n        withoutTestLifecycles: true,\n      },\n    )\n\n    await storeRef.store.dispatch(\n      countersApi.endpoints.counters.initiate('item', {\n        initialPageParam: 3,\n      }),\n    )\n\n    await storeRef.store.dispatch(\n      countersApi.endpoints.counters.initiate('item', {\n        direction: 'forward',\n      }),\n    )\n\n    const thirdPromise = storeRef.store.dispatch(\n      countersApi.endpoints.counters.initiate('item', {\n        direction: 'forward',\n      }),\n    )\n\n    const thirdRes = await thirdPromise\n\n    checkResultData(thirdRes, [\n      { page: 3, hitCounter: 1 },\n      { page: 4, hitCounter: 2 },\n      { page: 5, hitCounter: 3 },\n    ])\n\n    const fourthRes = await thirdPromise.refetch()\n\n    checkResultData(fourthRes, [\n      { page: 3, hitCounter: 4 },\n      { page: 4, hitCounter: 5 },\n      { page: 5, hitCounter: 6 },\n    ])\n  })\n\n  test('Refetches on invalidation', async () => {\n    const checkResultData = (\n      result: InfiniteQueryResult,\n      expectedValues: HitCounter[],\n    ) => {\n      expect(result.status).toBe(QueryStatus.fulfilled)\n      if (result.status === QueryStatus.fulfilled) {\n        expect(result.data.pages).toEqual(expectedValues)\n      }\n    }\n\n    const countersApi = createCountersApi()\n\n    const storeRef = setupApiStore(\n      countersApi,\n      { ...actionsReducer },\n      {\n        withoutTestLifecycles: true,\n      },\n    )\n\n    await storeRef.store.dispatch(\n      countersApi.endpoints.counters.initiate('item', {\n        initialPageParam: 3,\n      }),\n    )\n\n    await storeRef.store.dispatch(\n      countersApi.endpoints.counters.initiate('item', {\n        direction: 'forward',\n      }),\n    )\n\n    const thirdPromise = storeRef.store.dispatch(\n      countersApi.endpoints.counters.initiate('item', {\n        direction: 'forward',\n      }),\n    )\n\n    const thirdRes = await thirdPromise\n\n    checkResultData(thirdRes, [\n      { page: 3, hitCounter: 1 },\n      { page: 4, hitCounter: 2 },\n      { page: 5, hitCounter: 3 },\n    ])\n\n    await storeRef.store.dispatch(countersApi.endpoints.mutation.initiate())\n\n    let entry = countersApi.endpoints.counters.select('item')(\n      storeRef.store.getState(),\n    )\n    const promise = storeRef.store.dispatch(\n      countersApi.util.getRunningQueryThunk('counters', 'item'),\n    )\n    const promises = storeRef.store.dispatch(\n      countersApi.util.getRunningQueriesThunk(),\n    )\n    expect(entry).toMatchObject({\n      status: 'pending',\n    })\n\n    expect(promise).toBeInstanceOf(Promise)\n\n    expect(promises).toEqual([promise])\n\n    const finalRes = await promise\n\n    checkResultData(finalRes as any, [\n      { page: 3, hitCounter: 4 },\n      { page: 4, hitCounter: 5 },\n      { page: 5, hitCounter: 6 },\n    ])\n  })\n\n  test('Refetches on polling', async () => {\n    const countersApi = createCountersApi()\n    const checkResultData = (\n      result: InfiniteQueryResult,\n      expectedValues: HitCounter[],\n    ) => {\n      expect(result.status).toBe(QueryStatus.fulfilled)\n      if (result.status === QueryStatus.fulfilled) {\n        expect(result.data.pages).toEqual(expectedValues)\n      }\n    }\n\n    const storeRef = setupApiStore(\n      countersApi,\n      { ...actionsReducer },\n      {\n        withoutTestLifecycles: true,\n      },\n    )\n\n    await storeRef.store.dispatch(\n      countersApi.endpoints.counters.initiate('item', {\n        initialPageParam: 3,\n      }),\n    )\n\n    await storeRef.store.dispatch(\n      countersApi.endpoints.counters.initiate('item', {\n        direction: 'forward',\n      }),\n    )\n\n    const thirdPromise = storeRef.store.dispatch(\n      countersApi.endpoints.counters.initiate('item', {\n        direction: 'forward',\n      }),\n    )\n\n    const thirdRes = await thirdPromise\n\n    checkResultData(thirdRes, [\n      { page: 3, hitCounter: 1 },\n      { page: 4, hitCounter: 2 },\n      { page: 5, hitCounter: 3 },\n    ])\n\n    thirdPromise.updateSubscriptionOptions({\n      pollingInterval: 50,\n    })\n\n    await delay(25)\n\n    let entry = countersApi.endpoints.counters.select('item')(\n      storeRef.store.getState(),\n    )\n\n    checkResultData(thirdRes, [\n      { page: 3, hitCounter: 1 },\n      { page: 4, hitCounter: 2 },\n      { page: 5, hitCounter: 3 },\n    ])\n\n    await delay(50)\n\n    entry = countersApi.endpoints.counters.select('item')(\n      storeRef.store.getState(),\n    )\n\n    checkResultData(entry as any, [\n      { page: 3, hitCounter: 4 },\n      { page: 4, hitCounter: 5 },\n      { page: 5, hitCounter: 6 },\n    ])\n  })\n\n  test('Handles multiple next page fetches at once', async () => {\n    const initialEntry = await storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),\n    )\n\n    checkResultData(initialEntry, [[{ id: '0', name: 'Pokemon 0' }]])\n\n    expect(queryCounter).toBe(1)\n\n    const promise1 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {\n        direction: 'forward',\n      }),\n    )\n\n    expect(queryCounter).toBe(1)\n\n    const promise2 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {\n        direction: 'forward',\n      }),\n    )\n\n    const entry1 = await promise1\n    const entry2 = await promise2\n\n    // The second thunk should have bailed out because the entry was now\n    // pending, so we should only have sent one request.\n    expect(queryCounter).toBe(2)\n\n    expect(entry1).toEqual(entry2)\n\n    checkResultData(entry1, [\n      [{ id: '0', name: 'Pokemon 0' }],\n      [{ id: '1', name: 'Pokemon 1' }],\n    ])\n\n    expect(queryCounter).toBe(2)\n\n    const promise3 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {\n        direction: 'forward',\n      }),\n    )\n\n    expect(queryCounter).toBe(2)\n\n    // We can abort an existing promise, but due to timing issues,\n    // we have to await the promise first before triggering the next request.\n    promise3.abort()\n    const entry3 = await promise3\n\n    const promise4 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {\n        direction: 'forward',\n      }),\n    )\n\n    const entry4 = await promise4\n\n    expect(queryCounter).toBe(4)\n\n    checkResultData(entry4, [\n      [{ id: '0', name: 'Pokemon 0' }],\n      [{ id: '1', name: 'Pokemon 1' }],\n      [{ id: '2', name: 'Pokemon 2' }],\n    ])\n  })\n\n  test('can fetch pages with refetchOnMountOrArgChange active', async () => {\n    const pokemonApiWithRefetch = createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n      endpoints: (build) => ({\n        getInfinitePokemon: build.infiniteQuery<Pokemon[], string, number>({\n          infiniteQueryOptions: {\n            initialPageParam: 0,\n            getNextPageParam: (\n              lastPage,\n              allPages,\n              // Page param type should be `number`\n              lastPageParam,\n              allPageParams,\n            ) => lastPageParam + 1,\n            getPreviousPageParam: (\n              firstPage,\n              allPages,\n              firstPageParam,\n              allPageParams,\n            ) => {\n              return firstPageParam > 0 ? firstPageParam - 1 : undefined\n            },\n          },\n          query({ pageParam }) {\n            return `https://example.com/listItems?page=${pageParam}`\n          },\n        }),\n      }),\n      refetchOnMountOrArgChange: true,\n    })\n\n    const storeRef = setupApiStore(\n      pokemonApiWithRefetch,\n      { ...actionsReducer },\n      {\n        withoutTestLifecycles: true,\n      },\n    )\n\n    const res1 = storeRef.store.dispatch(\n      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {}),\n    )\n\n    const entry1InitialLoad = await res1\n    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])\n\n    const res2 = storeRef.store.dispatch(\n      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {\n        direction: 'forward',\n      }),\n    )\n\n    const entry1SecondPage = await res2\n    checkResultData(entry1SecondPage, [\n      [{ id: '0', name: 'Pokemon 0' }],\n      [{ id: '1', name: 'Pokemon 1' }],\n    ])\n\n    expect(queryCounter).toBe(2)\n\n    const entry2InitialLoad = await storeRef.store.dispatch(\n      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('water', {}),\n    )\n\n    checkResultData(entry2InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])\n\n    expect(queryCounter).toBe(3)\n\n    const entry2SecondPage = await storeRef.store.dispatch(\n      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('water', {\n        direction: 'forward',\n      }),\n    )\n    checkResultData(entry2SecondPage, [\n      [{ id: '0', name: 'Pokemon 0' }],\n      [{ id: '1', name: 'Pokemon 1' }],\n    ])\n\n    expect(queryCounter).toBe(4)\n\n    // Should now be able to switch back to the first query.\n    // The hooks dispatch on arg change without a direction.\n    // That should trigger a refetch of the first query, meaning two requests.\n    // It should also _replace_ the existing results, rather than appending\n    // duplicate entries ([0, 1, 0, 1])\n    const entry1Refetched = await storeRef.store.dispatch(\n      pokemonApiWithRefetch.endpoints.getInfinitePokemon.initiate('fire', {}),\n    )\n\n    checkResultData(entry1Refetched, [\n      [{ id: '0', name: 'Pokemon 0' }],\n      [{ id: '1', name: 'Pokemon 1' }],\n    ])\n\n    expect(queryCounter).toBe(6)\n  })\n\n  test('Works with cache manipulation utils', async () => {\n    const res1 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('fire', {}),\n    )\n\n    const entry1InitialLoad = await res1\n    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])\n\n    storeRef.store.dispatch(\n      pokemonApi.util.updateQueryData('getInfinitePokemon', 'fire', (draft) => {\n        draft.pages.push([{ id: '1', name: 'Pokemon 1' }])\n        draft.pageParams.push(1)\n      }),\n    )\n\n    const selectFire = pokemonApi.endpoints.getInfinitePokemon.select('fire')\n    const entry1Updated = selectFire(storeRef.store.getState())\n\n    expect(entry1Updated.data).toEqual({\n      pages: [\n        [{ id: '0', name: 'Pokemon 0' }],\n        [{ id: '1', name: 'Pokemon 1' }],\n      ],\n      pageParams: [0, 1],\n    })\n\n    const res2 = storeRef.store.dispatch(\n      pokemonApi.util.upsertQueryData('getInfinitePokemon', 'water', {\n        pages: [[{ id: '2', name: 'Pokemon 2' }]],\n        pageParams: [2],\n      }),\n    )\n\n    const entry2InitialLoad = await res2\n    const selectWater = pokemonApi.endpoints.getInfinitePokemon.select('water')\n    const entry2Updated = selectWater(storeRef.store.getState())\n\n    expect(entry2Updated.data).toEqual({\n      pages: [[{ id: '2', name: 'Pokemon 2' }]],\n      pageParams: [2],\n    })\n\n    storeRef.store.dispatch(\n      pokemonApi.util.upsertQueryEntries([\n        {\n          endpointName: 'getInfinitePokemon',\n          arg: 'air',\n          value: {\n            pages: [[{ id: '3', name: 'Pokemon 3' }]],\n            pageParams: [3],\n          },\n        },\n      ]),\n    )\n\n    const selectAir = pokemonApi.endpoints.getInfinitePokemon.select('air')\n    const entry3Initial = selectAir(storeRef.store.getState())\n\n    expect(entry3Initial.data).toEqual({\n      pages: [[{ id: '3', name: 'Pokemon 3' }]],\n      pageParams: [3],\n    })\n\n    await storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemon.initiate('air', {\n        direction: 'forward',\n      }),\n    )\n\n    const entry3Updated = selectAir(storeRef.store.getState())\n\n    expect(entry3Updated.data).toEqual({\n      pages: [\n        [{ id: '3', name: 'Pokemon 3' }],\n        [{ id: '4', name: 'Pokemon 4' }],\n      ],\n      pageParams: [3, 4],\n    })\n  })\n\n  test('Cache lifecycle methods are called', async () => {\n    const cacheEntryAddedCallback = vi.fn()\n    const queryStartedCallback = vi.fn()\n\n    const pokemonApi = createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n      endpoints: (build) => ({\n        getInfinitePokemonWithLifecycles: build.infiniteQuery<\n          Pokemon[],\n          string,\n          number\n        >({\n          infiniteQueryOptions: {\n            initialPageParam: 0,\n            getNextPageParam: (\n              lastPage,\n              allPages,\n              // Page param type should be `number`\n              lastPageParam,\n              allPageParams,\n            ) => lastPageParam + 1,\n            getPreviousPageParam: (\n              firstPage,\n              allPages,\n              firstPageParam,\n              allPageParams,\n            ) => {\n              return firstPageParam > 0 ? firstPageParam - 1 : undefined\n            },\n          },\n          query({ pageParam }) {\n            return `https://example.com/listItems?page=${pageParam}`\n          },\n          async onCacheEntryAdded(arg, api) {\n            const data = await api.cacheDataLoaded\n            cacheEntryAddedCallback(arg, data)\n          },\n          async onQueryStarted(arg, api) {\n            const data = await api.queryFulfilled\n            queryStartedCallback(arg, data)\n          },\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(\n      pokemonApi,\n      { ...actionsReducer },\n      {\n        withoutTestLifecycles: true,\n      },\n    )\n\n    const res1 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemonWithLifecycles.initiate(\n        'fire',\n        {},\n      ),\n    )\n\n    const entry1InitialLoad = await res1\n    checkResultData(entry1InitialLoad, [[{ id: '0', name: 'Pokemon 0' }]])\n\n    expect(cacheEntryAddedCallback).toHaveBeenCalledWith('fire', {\n      data: {\n        pages: [[{ id: '0', name: 'Pokemon 0' }]],\n        pageParams: [0],\n      },\n      meta: expect.objectContaining({\n        request: expect.anything(),\n        response: expect.anything(),\n      }),\n    })\n\n    expect(queryStartedCallback).toHaveBeenCalledWith('fire', {\n      data: {\n        pages: [[{ id: '0', name: 'Pokemon 0' }]],\n        pageParams: [0],\n      },\n      meta: expect.objectContaining({\n        request: expect.anything(),\n        response: expect.anything(),\n      }),\n    })\n  })\n\n  test('Can use transformResponse', async () => {\n    type PokemonPage = { items: Pokemon[]; page: number }\n    const pokemonApi = createApi({\n      baseQuery: fetchBaseQuery({ baseUrl: 'https://pokeapi.co/api/v2/' }),\n      endpoints: (build) => ({\n        getInfinitePokemonWithTransform: build.infiniteQuery<\n          PokemonPage,\n          string,\n          number\n        >({\n          infiniteQueryOptions: {\n            initialPageParam: 0,\n            getNextPageParam: (\n              lastPage,\n              allPages,\n              // Page param type should be `number`\n              lastPageParam,\n              allPageParams,\n            ) => lastPageParam + 1,\n          },\n          query({ pageParam }) {\n            return `https://example.com/listItems?page=${pageParam}`\n          },\n          transformResponse(baseQueryReturnValue: Pokemon[], meta, arg) {\n            expect(Array.isArray(baseQueryReturnValue)).toBe(true)\n            return {\n              items: baseQueryReturnValue,\n              page: arg.pageParam,\n            }\n          },\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(\n      pokemonApi,\n      { ...actionsReducer },\n      {\n        withoutTestLifecycles: true,\n      },\n    )\n\n    const checkResultData = (\n      result: InfiniteQueryResult,\n      expectedValues: PokemonPage[],\n    ) => {\n      expect(result.status).toBe(QueryStatus.fulfilled)\n      if (result.status === QueryStatus.fulfilled) {\n        expect(result.data.pages).toEqual(expectedValues)\n      }\n    }\n\n    const res1 = storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemonWithTransform.initiate('fire', {}),\n    )\n\n    const entry1InitialLoad = await res1\n    checkResultData(entry1InitialLoad, [\n      { items: [{ id: '0', name: 'Pokemon 0' }], page: 0 },\n    ])\n\n    const entry1Updated = await storeRef.store.dispatch(\n      pokemonApi.endpoints.getInfinitePokemonWithTransform.initiate('fire', {\n        direction: 'forward',\n      }),\n    )\n\n    checkResultData(entry1Updated, [\n      { items: [{ id: '0', name: 'Pokemon 0' }], page: 0 },\n      { items: [{ id: '1', name: 'Pokemon 1' }], page: 1 },\n    ])\n  })\n\n  describe('refetchCachedPages option', () => {\n    test('refetches all pages by default (refetchCachedPages: true)', async () => {\n      let hitCounter = 0\n\n      const countersApi = createApi({\n        baseQuery: fakeBaseQuery(),\n        tagTypes: ['Counter'],\n        endpoints: (build) => ({\n          counters: build.infiniteQuery<HitCounter, string, number>({\n            queryFn({ pageParam }) {\n              hitCounter++\n              return { data: { page: pageParam, hitCounter } }\n            },\n            infiniteQueryOptions: {\n              initialPageParam: 0,\n              getNextPageParam: (\n                lastPage,\n                allPages,\n                lastPageParam,\n                allPageParams,\n              ) => lastPageParam + 1,\n            },\n            providesTags: ['Counter'],\n          }),\n        }),\n      })\n\n      const storeRef = setupApiStore(\n        countersApi,\n        { ...actionsReducer },\n        {\n          withoutTestLifecycles: true,\n        },\n      )\n\n      // Load 3 pages\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          initialPageParam: 0,\n        }),\n      )\n\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      const thirdPromise = storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      const thirdRes = await thirdPromise\n\n      // Should have 3 pages with hitCounters 1, 2, 3\n      expect(thirdRes.data!.pages).toEqual([\n        { page: 0, hitCounter: 1 },\n        { page: 1, hitCounter: 2 },\n        { page: 2, hitCounter: 3 },\n      ])\n\n      // Refetch without specifying refetchCachedPages\n      const refetchRes = await thirdPromise.refetch()\n\n      // All 3 pages should be refetched (hitCounters 4, 5, 6)\n      expect(refetchRes.data!.pages).toEqual([\n        { page: 0, hitCounter: 4 },\n        { page: 1, hitCounter: 5 },\n        { page: 2, hitCounter: 6 },\n      ])\n      expect(refetchRes.data!.pages).toHaveLength(3)\n    })\n\n    test('refetches all pages when refetchCachedPages is explicitly true', async () => {\n      let hitCounter = 0\n\n      const countersApi = createApi({\n        baseQuery: fakeBaseQuery(),\n        tagTypes: ['Counter'],\n        endpoints: (build) => ({\n          counters: build.infiniteQuery<HitCounter, string, number>({\n            queryFn({ pageParam }) {\n              hitCounter++\n              return { data: { page: pageParam, hitCounter } }\n            },\n            infiniteQueryOptions: {\n              initialPageParam: 0,\n              getNextPageParam: (\n                lastPage,\n                allPages,\n                lastPageParam,\n                allPageParams,\n              ) => lastPageParam + 1,\n              refetchCachedPages: true, // Explicit true\n            },\n            providesTags: ['Counter'],\n          }),\n        }),\n      })\n\n      const storeRef = setupApiStore(\n        countersApi,\n        { ...actionsReducer },\n        {\n          withoutTestLifecycles: true,\n        },\n      )\n\n      // Load 3 pages\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          initialPageParam: 0,\n        }),\n      )\n\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      const thirdPromise = storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      const thirdRes = await thirdPromise\n\n      expect(thirdRes.data!.pages).toHaveLength(3)\n\n      // Refetch\n      const refetchRes = await thirdPromise.refetch()\n\n      // All 3 pages should be refetched\n      expect(refetchRes.data!.pages).toHaveLength(3)\n      expect(refetchRes.data!.pages[0].hitCounter).toBeGreaterThan(\n        thirdRes.data!.pages[0].hitCounter,\n      )\n    })\n\n    test('refetches only first page when refetchCachedPages is false', async () => {\n      let hitCounter = 0\n\n      const countersApi = createApi({\n        baseQuery: fakeBaseQuery(),\n        tagTypes: ['Counter'],\n        endpoints: (build) => ({\n          counters: build.infiniteQuery<HitCounter, string, number>({\n            queryFn({ pageParam }) {\n              hitCounter++\n              return { data: { page: pageParam, hitCounter } }\n            },\n            infiniteQueryOptions: {\n              initialPageParam: 0,\n              getNextPageParam: (\n                lastPage,\n                allPages,\n                lastPageParam,\n                allPageParams,\n              ) => lastPageParam + 1,\n              refetchCachedPages: false, // Only refetch first page\n            },\n            providesTags: ['Counter'],\n          }),\n        }),\n      })\n\n      const storeRef = setupApiStore(\n        countersApi,\n        { ...actionsReducer },\n        {\n          withoutTestLifecycles: true,\n        },\n      )\n\n      // Load 3 pages\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          initialPageParam: 0,\n        }),\n      )\n\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      const thirdPromise = storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      const thirdRes = await thirdPromise\n\n      // Should have 3 pages with hitCounters 1, 2, 3\n      expect(thirdRes.data!.pages).toEqual([\n        { page: 0, hitCounter: 1 },\n        { page: 1, hitCounter: 2 },\n        { page: 2, hitCounter: 3 },\n      ])\n\n      // Refetch with refetchCachedPages: false\n      const refetchRes = await thirdPromise.refetch()\n\n      // Only first page should be refetched, cache reset to 1 page\n      expect(refetchRes.data!.pages).toEqual([{ page: 0, hitCounter: 4 }])\n      expect(refetchRes.data!.pageParams).toEqual([0])\n    })\n\n    test('refetches only first page on tag invalidation when refetchCachedPages is false', async () => {\n      let hitCounter = 0\n\n      const countersApi = createApi({\n        baseQuery: fakeBaseQuery(),\n        tagTypes: ['Counter'],\n        endpoints: (build) => ({\n          counters: build.infiniteQuery<HitCounter, string, number>({\n            queryFn({ pageParam }) {\n              hitCounter++\n              return { data: { page: pageParam, hitCounter } }\n            },\n            infiniteQueryOptions: {\n              initialPageParam: 0,\n              getNextPageParam: (\n                lastPage,\n                allPages,\n                lastPageParam,\n                allPageParams,\n              ) => lastPageParam + 1,\n              refetchCachedPages: false,\n            },\n            providesTags: ['Counter'],\n          }),\n          mutation: build.mutation<null, void>({\n            queryFn: async () => ({ data: null }),\n            invalidatesTags: ['Counter'],\n          }),\n        }),\n      })\n\n      const storeRef = setupApiStore(\n        countersApi,\n        { ...actionsReducer },\n        {\n          withoutTestLifecycles: true,\n        },\n      )\n\n      // Load 3 pages\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          initialPageParam: 0,\n        }),\n      )\n\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      // Verify we have 3 pages\n      let entry = countersApi.endpoints.counters.select('item')(\n        storeRef.store.getState(),\n      )\n      expect(entry.data?.pages).toHaveLength(3)\n\n      // Trigger mutation to invalidate tags\n      await storeRef.store.dispatch(countersApi.endpoints.mutation.initiate())\n\n      // Wait for refetch to complete\n      const promise = storeRef.store.dispatch(\n        countersApi.util.getRunningQueryThunk('counters', 'item'),\n      )\n      const finalRes = await promise\n\n      // Only first page should be refetched\n      expect((finalRes as any).data.pages).toEqual([{ page: 0, hitCounter: 4 }])\n    })\n\n    test('refetches only first page during polling when refetchCachedPages is false', async () => {\n      let hitCounter = 0\n\n      const countersApi = createApi({\n        baseQuery: fakeBaseQuery(),\n        endpoints: (build) => ({\n          counters: build.infiniteQuery<HitCounter, string, number>({\n            queryFn({ pageParam }) {\n              hitCounter++\n              return { data: { page: pageParam, hitCounter } }\n            },\n            infiniteQueryOptions: {\n              initialPageParam: 0,\n              getNextPageParam: (\n                lastPage,\n                allPages,\n                lastPageParam,\n                allPageParams,\n              ) => lastPageParam + 1,\n              refetchCachedPages: false,\n            },\n          }),\n        }),\n      })\n\n      const storeRef = setupApiStore(\n        countersApi,\n        { ...actionsReducer },\n        {\n          withoutTestLifecycles: true,\n        },\n      )\n\n      // Load 3 pages\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          initialPageParam: 0,\n        }),\n      )\n\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      const thirdPromise = storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      await thirdPromise\n\n      // Enable polling\n      thirdPromise.updateSubscriptionOptions({\n        pollingInterval: 50,\n      })\n\n      // Wait for first poll\n      await delay(75)\n\n      const entry = countersApi.endpoints.counters.select('item')(\n        storeRef.store.getState(),\n      )\n\n      // Should only have 1 page after poll\n      expect(entry.data?.pages).toEqual([{ page: 0, hitCounter: 4 }])\n    })\n\n    test('refetchCachedPages: false works with maxPages', async () => {\n      let hitCounter = 0\n\n      const countersApi = createApi({\n        baseQuery: fakeBaseQuery(),\n        endpoints: (build) => ({\n          counters: build.infiniteQuery<HitCounter, string, number>({\n            queryFn({ pageParam }) {\n              hitCounter++\n              return { data: { page: pageParam, hitCounter } }\n            },\n            infiniteQueryOptions: {\n              initialPageParam: 0,\n              maxPages: 3,\n              getNextPageParam: (\n                lastPage,\n                allPages,\n                lastPageParam,\n                allPageParams,\n              ) => lastPageParam + 1,\n              getPreviousPageParam: (\n                firstPage,\n                allPages,\n                firstPageParam,\n                allPageParams,\n              ) => (firstPageParam > 0 ? firstPageParam - 1 : undefined),\n              refetchCachedPages: false,\n            },\n          }),\n        }),\n      })\n\n      const storeRef = setupApiStore(\n        countersApi,\n        { ...actionsReducer },\n        {\n          withoutTestLifecycles: true,\n        },\n      )\n\n      // Load 5 pages (but maxPages will limit to 3)\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          initialPageParam: 0,\n        }),\n      )\n\n      for (let i = 0; i < 4; i++) {\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            direction: 'forward',\n          }),\n        )\n      }\n\n      let entry = countersApi.endpoints.counters.select('item')(\n        storeRef.store.getState(),\n      )\n\n      // Should have 3 pages due to maxPages\n      expect(entry.data?.pages).toHaveLength(3)\n\n      // Refetch\n      const refetchPromise = storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          forceRefetch: true,\n        }),\n      )\n\n      const refetchRes = await refetchPromise\n\n      // Should only have 1 page after refetch (refetchCachedPages: false)\n      // Note: With maxPages: 3, the cache kept pages 2, 3, 4\n      // So refetch starts from the first cached page param, which is 2\n      expect(refetchRes.data!.pages).toHaveLength(1)\n      expect(refetchRes.data!.pages[0].page).toBe(2)\n    })\n\n    test('can fetch next page after refetch with refetchCachedPages: false', async () => {\n      let hitCounter = 0\n\n      const countersApi = createApi({\n        baseQuery: fakeBaseQuery(),\n        endpoints: (build) => ({\n          counters: build.infiniteQuery<HitCounter, string, number>({\n            queryFn({ pageParam }) {\n              hitCounter++\n              return { data: { page: pageParam, hitCounter } }\n            },\n            infiniteQueryOptions: {\n              initialPageParam: 0,\n              getNextPageParam: (\n                lastPage,\n                allPages,\n                lastPageParam,\n                allPageParams,\n              ) => lastPageParam + 1,\n              refetchCachedPages: false,\n            },\n          }),\n        }),\n      })\n\n      const storeRef = setupApiStore(\n        countersApi,\n        { ...actionsReducer },\n        {\n          withoutTestLifecycles: true,\n        },\n      )\n\n      // Load 3 pages\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          initialPageParam: 0,\n        }),\n      )\n\n      await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      const thirdPromise = storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      await thirdPromise\n\n      // Refetch (resets to 1 page)\n      await thirdPromise.refetch()\n\n      let entry = countersApi.endpoints.counters.select('item')(\n        storeRef.store.getState(),\n      )\n      expect(entry.data?.pages).toHaveLength(1)\n\n      // Fetch next page\n      const nextPageRes = await storeRef.store.dispatch(\n        countersApi.endpoints.counters.initiate('item', {\n          direction: 'forward',\n        }),\n      )\n\n      // Should now have 2 pages\n      expect(nextPageRes.data!.pages).toEqual([\n        { page: 0, hitCounter: 4 },\n        { page: 1, hitCounter: 5 },\n      ])\n    })\n\n    describe('per-call refetchCachedPages override', () => {\n      test('per-call false overrides endpoint true', async () => {\n        let hitCounter = 0\n\n        const countersApi = createApi({\n          baseQuery: fakeBaseQuery(),\n          endpoints: (build) => ({\n            counters: build.infiniteQuery<HitCounter, string, number>({\n              queryFn({ pageParam }) {\n                hitCounter++\n                return { data: { page: pageParam, hitCounter } }\n              },\n              infiniteQueryOptions: {\n                initialPageParam: 0,\n                getNextPageParam: (\n                  lastPage,\n                  allPages,\n                  lastPageParam,\n                  allPageParams,\n                ) => lastPageParam + 1,\n                refetchCachedPages: true, // Endpoint default: refetch all\n              },\n            }),\n          }),\n        })\n\n        const storeRef = setupApiStore(\n          countersApi,\n          { ...actionsReducer },\n          {\n            withoutTestLifecycles: true,\n          },\n        )\n\n        // Load 3 pages\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            initialPageParam: 0,\n          }),\n        )\n\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            direction: 'forward',\n          }),\n        )\n\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            direction: 'forward',\n          }),\n        )\n\n        // Should have 3 pages with hitCounters 1, 2, 3\n        let entry = countersApi.endpoints.counters.select('item')(\n          storeRef.store.getState(),\n        )\n        expect(entry.data?.pages).toEqual([\n          { page: 0, hitCounter: 1 },\n          { page: 1, hitCounter: 2 },\n          { page: 2, hitCounter: 3 },\n        ])\n\n        // Refetch with per-call override: false\n        const refetchRes = await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            forceRefetch: true,\n            refetchCachedPages: false, // Override to false\n          }),\n        )\n\n        // Only first page should be refetched (hitCounter 4)\n        expect(refetchRes.data!.pages).toEqual([{ page: 0, hitCounter: 4 }])\n        expect(refetchRes.data!.pageParams).toEqual([0])\n      })\n\n      test('per-call true overrides endpoint false', async () => {\n        let hitCounter = 0\n\n        const countersApi = createApi({\n          baseQuery: fakeBaseQuery(),\n          endpoints: (build) => ({\n            counters: build.infiniteQuery<HitCounter, string, number>({\n              queryFn({ pageParam }) {\n                hitCounter++\n                return { data: { page: pageParam, hitCounter } }\n              },\n              infiniteQueryOptions: {\n                initialPageParam: 0,\n                getNextPageParam: (\n                  lastPage,\n                  allPages,\n                  lastPageParam,\n                  allPageParams,\n                ) => lastPageParam + 1,\n                refetchCachedPages: false, // Endpoint default: only first page\n              },\n            }),\n          }),\n        })\n\n        const storeRef = setupApiStore(\n          countersApi,\n          { ...actionsReducer },\n          {\n            withoutTestLifecycles: true,\n          },\n        )\n\n        // Load 3 pages\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            initialPageParam: 0,\n          }),\n        )\n\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            direction: 'forward',\n          }),\n        )\n\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            direction: 'forward',\n          }),\n        )\n\n        // Should have 3 pages\n        let entry = countersApi.endpoints.counters.select('item')(\n          storeRef.store.getState(),\n        )\n        expect(entry.data?.pages).toHaveLength(3)\n\n        // Refetch with per-call override: true\n        const refetchRes = await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            forceRefetch: true,\n            refetchCachedPages: true, // Override to true\n          }),\n        )\n\n        // All 3 pages should be refetched\n        expect(refetchRes.data!.pages).toEqual([\n          { page: 0, hitCounter: 4 },\n          { page: 1, hitCounter: 5 },\n          { page: 2, hitCounter: 6 },\n        ])\n        expect(refetchRes.data!.pages).toHaveLength(3)\n      })\n\n      test('uses endpoint config when no per-call override', async () => {\n        let hitCounter = 0\n\n        const countersApi = createApi({\n          baseQuery: fakeBaseQuery(),\n          endpoints: (build) => ({\n            counters: build.infiniteQuery<HitCounter, string, number>({\n              queryFn({ pageParam }) {\n                hitCounter++\n                return { data: { page: pageParam, hitCounter } }\n              },\n              infiniteQueryOptions: {\n                initialPageParam: 0,\n                getNextPageParam: (\n                  lastPage,\n                  allPages,\n                  lastPageParam,\n                  allPageParams,\n                ) => lastPageParam + 1,\n                refetchCachedPages: false, // Endpoint config\n              },\n            }),\n          }),\n        })\n\n        const storeRef = setupApiStore(\n          countersApi,\n          { ...actionsReducer },\n          {\n            withoutTestLifecycles: true,\n          },\n        )\n\n        // Load 3 pages\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            initialPageParam: 0,\n          }),\n        )\n\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            direction: 'forward',\n          }),\n        )\n\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            direction: 'forward',\n          }),\n        )\n\n        // Refetch without per-call override\n        const refetchRes = await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            forceRefetch: true,\n            // No refetchCachedPages specified\n          }),\n        )\n\n        // Should use endpoint config (false) - only first page\n        expect(refetchRes.data!.pages).toEqual([{ page: 0, hitCounter: 4 }])\n      })\n\n      test('defaults to true when no config at any level', async () => {\n        let hitCounter = 0\n\n        const countersApi = createApi({\n          baseQuery: fakeBaseQuery(),\n          endpoints: (build) => ({\n            counters: build.infiniteQuery<HitCounter, string, number>({\n              queryFn({ pageParam }) {\n                hitCounter++\n                return { data: { page: pageParam, hitCounter } }\n              },\n              infiniteQueryOptions: {\n                initialPageParam: 0,\n                getNextPageParam: (\n                  lastPage,\n                  allPages,\n                  lastPageParam,\n                  allPageParams,\n                ) => lastPageParam + 1,\n                // No refetchCachedPages specified\n              },\n            }),\n          }),\n        })\n\n        const storeRef = setupApiStore(\n          countersApi,\n          { ...actionsReducer },\n          {\n            withoutTestLifecycles: true,\n          },\n        )\n\n        // Load 3 pages\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            initialPageParam: 0,\n          }),\n        )\n\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            direction: 'forward',\n          }),\n        )\n\n        await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            direction: 'forward',\n          }),\n        )\n\n        // Refetch without any config\n        const refetchRes = await storeRef.store.dispatch(\n          countersApi.endpoints.counters.initiate('item', {\n            forceRefetch: true,\n          }),\n        )\n\n        // Should default to true - refetch all pages\n        expect(refetchRes.data!.pages).toEqual([\n          { page: 0, hitCounter: 4 },\n          { page: 1, hitCounter: 5 },\n          { page: 2, hitCounter: 6 },\n        ])\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/injectEndpoints.test.tsx",
    "content": "import { noop } from '@internal/listenerMiddleware/utils'\nimport { configureStore } from '@reduxjs/toolkit'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n  endpoints: () => ({}),\n})\n\ndescribe('injectEndpoints', () => {\n  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n\n  afterEach(() => {\n    vi.clearAllMocks()\n    vi.unstubAllEnvs()\n  })\n\n  afterAll(() => {\n    vi.restoreAllMocks()\n    vi.unstubAllEnvs()\n  })\n\n  test(\"query: overriding with `overrideEndpoints`='throw' throws an error\", async () => {\n    const extended = api.injectEndpoints({\n      endpoints: (build) => ({\n        injected: build.query<unknown, string>({\n          query: () => '/success',\n        }),\n      }),\n    })\n\n    expect(() => {\n      extended.injectEndpoints({\n        overrideExisting: 'throw',\n        endpoints: (build) => ({\n          injected: build.query<unknown, string>({\n            query: () => '/success',\n          }),\n        }),\n      })\n    }).toThrowError(\n      new Error(\n        `called \\`injectEndpoints\\` to override already-existing endpointName injected without specifying \\`overrideExisting: true\\``,\n      ),\n    )\n  })\n\n  test('query: overriding an endpoint with `overrideEndpoints`=false does nothing in production', async () => {\n    vi.stubEnv('NODE_ENV', 'development')\n\n    const extended = api.injectEndpoints({\n      endpoints: (build) => ({\n        injected: build.query<unknown, string>({\n          query: () => '/success',\n        }),\n      }),\n    })\n\n    extended.injectEndpoints({\n      overrideExisting: false,\n      endpoints: (build) => ({\n        injected: build.query<unknown, string>({\n          query: () => '/success',\n        }),\n      }),\n    })\n\n    expect(consoleErrorSpy).toHaveBeenCalledWith(\n      `called \\`injectEndpoints\\` to override already-existing endpointName injected without specifying \\`overrideExisting: true\\``,\n    )\n  })\n\n  test('query: overriding with `overrideEndpoints`=false logs an error in development', async () => {\n    vi.stubEnv('NODE_ENV', 'production')\n\n    const extended = api.injectEndpoints({\n      endpoints: (build) => ({\n        injected: build.query<unknown, string>({\n          query: () => '/success',\n        }),\n      }),\n    })\n\n    extended.injectEndpoints({\n      overrideExisting: false,\n      endpoints: (build) => ({\n        injected: build.query<unknown, string>({\n          query: () => '/success',\n        }),\n      }),\n    })\n\n    expect(consoleErrorSpy).not.toHaveBeenCalled()\n  })\n\n  test('adding the same middleware to the store twice throws an error', () => {\n    // Strictly speaking this is a duplicate of the tests in configureStore.test.ts,\n    // but this helps confirm that we throw the error for adding\n    // the same API middleware twice.\n    const extendedApi = api.injectEndpoints({\n      endpoints: (build) => ({\n        injected: build.query<unknown, string>({\n          query: () => '/success',\n        }),\n      }),\n    })\n\n    const makeStore = () =>\n      configureStore({\n        reducer: {\n          api: api.reducer,\n        },\n        middleware: (getDefaultMiddleware) =>\n          getDefaultMiddleware().concat(api.middleware, extendedApi.middleware),\n      })\n\n    expect(makeStore).toThrowError(\n      'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',\n    )\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/invalidation.test.tsx",
    "content": "import type { TagDescription } from '@reduxjs/toolkit/query'\nimport { createApi, fakeBaseQuery } from '@reduxjs/toolkit/query'\nimport { waitFor } from '@testing-library/react'\nimport { delay } from 'msw'\nimport { setupApiStore } from '../../tests/utils/helpers'\n\nconst tagTypes = [\n  'apple',\n  'pear',\n  'banana',\n  'tomato',\n  'cat',\n  'dog',\n  'giraffe',\n] as const\ntype TagTypes = (typeof tagTypes)[number]\ntype ProvidedTags = TagDescription<TagTypes>[]\ntype InvalidatesTags = (ProvidedTags[number] | null | undefined)[]\n/** providesTags, invalidatesTags, shouldInvalidate */\nconst caseMatrix: [ProvidedTags, InvalidatesTags, boolean][] = [\n  // *****************************\n  // basic invalidation behavior\n  // *****************************\n\n  // string\n  [['apple'], ['apple'], true],\n  [['apple'], ['pear'], false],\n  // string and type only behave identical\n  [[{ type: 'apple' }], ['apple'], true],\n  [[{ type: 'apple' }], ['pear'], false],\n  [['apple'], [{ type: 'apple' }], true],\n  [['apple'], [{ type: 'pear' }], false],\n  // type only invalidates type + id\n  [[{ type: 'apple', id: 1 }], [{ type: 'apple' }], true],\n  [[{ type: 'pear', id: 1 }], ['apple'], false],\n  // type + id never invalidates type only\n  [['apple'], [{ type: 'apple', id: 1 }], false],\n  [['pear'], [{ type: 'apple', id: 1 }], false],\n  // type + id invalidates type + id\n  [[{ type: 'apple', id: 1 }], [{ type: 'apple', id: 1 }], true],\n  [[{ type: 'apple', id: 1 }], [{ type: 'apple', id: 2 }], false],\n  // null and undefined\n  [['apple'], [null], false],\n  [['apple'], [undefined], false],\n  [['apple'], [null, 'apple'], true],\n  [['apple'], [undefined, 'apple'], true],\n  // *****************************\n  // test multiple values in array\n  // *****************************\n\n  [['apple', 'banana', 'tomato'], ['apple'], true],\n  [['apple'], ['pear', 'banana', 'tomato'], false],\n  [\n    [\n      { type: 'apple', id: 1 },\n      { type: 'apple', id: 3 },\n      { type: 'apple', id: 4 },\n    ],\n    [{ type: 'apple', id: 1 }],\n    true,\n  ],\n  [\n    [{ type: 'apple', id: 1 }],\n    [\n      { type: 'apple', id: 2 },\n      { type: 'apple', id: 3 },\n      { type: 'apple', id: 4 },\n    ],\n    false,\n  ],\n]\n\ntest.each(caseMatrix)(\n  '\\tprovidesTags: %O,\\n\\tinvalidatesTags: %O,\\n\\tshould invalidate: %s',\n  async (providesTags, invalidatesTags, shouldInvalidate) => {\n    let queryCount = 0\n    const {\n      store,\n      api,\n      api: {\n        endpoints: { invalidating, providing, unrelated },\n      },\n    } = setupApiStore(\n      createApi({\n        baseQuery: fakeBaseQuery(),\n        tagTypes,\n        endpoints: (build) => ({\n          providing: build.query<unknown, void>({\n            queryFn() {\n              queryCount++\n              return { data: {} }\n            },\n            providesTags,\n          }),\n          unrelated: build.query<unknown, void>({\n            queryFn() {\n              return { data: {} }\n            },\n            providesTags: ['cat', 'dog', { type: 'giraffe', id: 8 }],\n          }),\n          invalidating: build.mutation<unknown, void>({\n            queryFn() {\n              return { data: {} }\n            },\n            invalidatesTags,\n          }),\n        }),\n      }),\n      undefined,\n      { withoutTestLifecycles: true },\n    )\n\n    store.dispatch(providing.initiate())\n    store.dispatch(unrelated.initiate())\n    expect(queryCount).toBe(1)\n    await waitFor(() => {\n      expect(api.endpoints.providing.select()(store.getState()).status).toBe(\n        'fulfilled',\n      )\n      expect(api.endpoints.unrelated.select()(store.getState()).status).toBe(\n        'fulfilled',\n      )\n    })\n    const toInvalidate = api.util.selectInvalidatedBy(\n      store.getState(),\n      invalidatesTags,\n    )\n\n    if (shouldInvalidate) {\n      expect(toInvalidate).toEqual([\n        {\n          queryCacheKey: 'providing(undefined)',\n          endpointName: 'providing',\n          originalArgs: undefined,\n        },\n      ])\n    } else {\n      expect(toInvalidate).toEqual([])\n    }\n\n    store.dispatch(invalidating.initiate())\n    expect(queryCount).toBe(1)\n    await delay(2)\n    expect(queryCount).toBe(shouldInvalidate ? 2 : 1)\n  },\n)\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/matchers.test-d.tsx",
    "content": "import type { SerializedError } from '@reduxjs/toolkit'\nimport { createSlice } from '@reduxjs/toolkit'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\ninterface ResultType {\n  result: 'complex'\n}\n\ninterface ArgType {\n  foo: 'bar'\n  count: 3\n}\n\nconst baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com' })\nconst api = createApi({\n  baseQuery,\n  endpoints(build) {\n    return {\n      querySuccess: build.query<ResultType, ArgType>({\n        query: () => '/success',\n      }),\n      querySuccess2: build.query({ query: () => '/success' }),\n      queryFail: build.query({ query: () => '/error' }),\n      mutationSuccess: build.mutation({\n        query: () => ({ url: '/success', method: 'POST' }),\n      }),\n      mutationSuccess2: build.mutation({\n        query: () => ({ url: '/success', method: 'POST' }),\n      }),\n      mutationFail: build.mutation({\n        query: () => ({ url: '/error', method: 'POST' }),\n      }),\n    }\n  },\n})\n\ndescribe('type tests', () => {\n  test('inferred types', () => {\n    createSlice({\n      name: 'auth',\n      initialState: {},\n      reducers: {},\n      extraReducers: (builder) => {\n        builder\n          .addMatcher(\n            api.endpoints.querySuccess.matchPending,\n            (state, action) => {\n              expectTypeOf(action.payload).toBeUndefined()\n\n              expectTypeOf(\n                action.meta.arg.originalArgs,\n              ).toEqualTypeOf<ArgType>()\n            },\n          )\n          .addMatcher(\n            api.endpoints.querySuccess.matchFulfilled,\n            (state, action) => {\n              expectTypeOf(action.payload).toEqualTypeOf<ResultType>()\n\n              expectTypeOf(action.meta.fulfilledTimeStamp).toBeNumber()\n\n              expectTypeOf(\n                action.meta.arg.originalArgs,\n              ).toEqualTypeOf<ArgType>()\n            },\n          )\n          .addMatcher(\n            api.endpoints.querySuccess.matchRejected,\n            (state, action) => {\n              expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n\n              expectTypeOf(\n                action.meta.arg.originalArgs,\n              ).toEqualTypeOf<ArgType>()\n            },\n          )\n      },\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/matchers.test.tsx",
    "content": "import {\n  actionsReducer,\n  hookWaitFor,\n  setupApiStore,\n} from '@internal/tests/utils/helpers'\nimport { createSlice } from '@reduxjs/toolkit'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\nimport { act, renderHook } from '@testing-library/react'\n\ninterface ResultType {\n  result: 'complex'\n}\n\ninterface ArgType {\n  foo: 'bar'\n  count: 3\n}\n\nconst baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com' })\nconst api = createApi({\n  baseQuery,\n  endpoints(build) {\n    return {\n      querySuccess: build.query<ResultType, ArgType>({\n        query: () => '/success',\n      }),\n      querySuccess2: build.query({ query: () => '/success' }),\n      queryFail: build.query({ query: () => '/error' }),\n      mutationSuccess: build.mutation({\n        query: () => ({ url: '/success', method: 'POST' }),\n      }),\n      mutationSuccess2: build.mutation({\n        query: () => ({ url: '/success', method: 'POST' }),\n      }),\n      mutationFail: build.mutation({\n        query: () => ({ url: '/error', method: 'POST' }),\n      }),\n    }\n  },\n})\n\nconst storeRef = setupApiStore(api, {\n  ...actionsReducer,\n})\n\nconst {\n  mutationFail,\n  mutationSuccess,\n  mutationSuccess2,\n  queryFail,\n  querySuccess,\n  querySuccess2,\n} = api.endpoints\n\ntest('matches query pending & fulfilled actions for the given endpoint', async () => {\n  const endpoint = querySuccess2\n  const otherEndpoint = queryFail\n  const { result } = renderHook(() => endpoint.useQuery({} as any), {\n    wrapper: storeRef.wrapper,\n  })\n  await hookWaitFor(() => expect(result.current.isLoading).toBeFalsy())\n\n  expect(storeRef.store.getState().actions).toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchFulfilled,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    otherEndpoint.matchPending,\n    otherEndpoint.matchFulfilled,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchFulfilled,\n    api.endpoints.mutationSuccess.matchFulfilled,\n    endpoint.matchRejected,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchRejected,\n  )\n})\ntest('matches query pending & rejected actions for the given endpoint', async () => {\n  const endpoint = queryFail\n  const { result } = renderHook(() => endpoint.useQuery({}), {\n    wrapper: storeRef.wrapper,\n  })\n  await hookWaitFor(() => expect(result.current.isLoading).toBeFalsy())\n  expect(storeRef.store.getState().actions).toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchRejected,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchFulfilled,\n    endpoint.matchRejected,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchFulfilled,\n  )\n})\n\ntest('matches lazy query pending & fulfilled actions for given endpoint', async () => {\n  const endpoint = querySuccess\n  const { result } = renderHook(() => endpoint.useLazyQuery(), {\n    wrapper: storeRef.wrapper,\n  })\n  act(() => void result.current[0]({} as any))\n  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())\n\n  expect(storeRef.store.getState().actions).toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchFulfilled,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchFulfilled,\n    endpoint.matchRejected,\n  )\n\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchRejected,\n  )\n})\n\ntest('matches lazy query pending & rejected actions for given endpoint', async () => {\n  const endpoint = queryFail\n  const { result } = renderHook(() => endpoint.useLazyQuery(), {\n    wrapper: storeRef.wrapper,\n  })\n  act(() => void result.current[0]({}))\n  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())\n\n  expect(storeRef.store.getState().actions).toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchRejected,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchFulfilled,\n    endpoint.matchRejected,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchFulfilled,\n  )\n})\n\ntest('matches mutation pending & fulfilled actions for the given endpoint', async () => {\n  const endpoint = mutationSuccess\n  const otherEndpoint = mutationSuccess2\n  const { result } = renderHook(() => endpoint.useMutation(), {\n    wrapper: storeRef.wrapper,\n  })\n  act(() => void result.current[0]({}))\n  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())\n\n  expect(storeRef.store.getState().actions).toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchFulfilled,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    otherEndpoint.matchPending,\n    otherEndpoint.matchFulfilled,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchFulfilled,\n    endpoint.matchRejected,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchRejected,\n  )\n})\ntest('matches mutation pending & rejected actions for the given endpoint', async () => {\n  const endpoint = mutationFail\n  const { result } = renderHook(() => endpoint.useMutation(), {\n    wrapper: storeRef.wrapper,\n  })\n  act(() => void result.current[0]({}))\n  await hookWaitFor(() => expect(result.current[1].isLoading).toBeFalsy())\n\n  expect(storeRef.store.getState().actions).toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchRejected,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchFulfilled,\n    endpoint.matchRejected,\n  )\n  expect(storeRef.store.getState().actions).not.toMatchSequence(\n    api.internalActions.middlewareRegistered.match,\n    endpoint.matchPending,\n    endpoint.matchFulfilled,\n  )\n})\n\ntest('inferred types', () => {\n  createSlice({\n    name: 'auth',\n    initialState: {},\n    reducers: {},\n    extraReducers: (builder) => {\n      builder\n        .addMatcher(\n          api.endpoints.querySuccess.matchPending,\n          (state, action) => {\n            // @ts-expect-error\n            console.log(action.error)\n          },\n        )\n        .addMatcher(\n          api.endpoints.querySuccess.matchFulfilled,\n          (state, action) => {\n            // @ts-expect-error\n            console.log(action.error)\n          },\n        )\n        .addMatcher(\n          api.endpoints.querySuccess.matchRejected,\n          (state, action) => {},\n        )\n    },\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/mocks/handlers.ts",
    "content": "import { headersToObject } from 'headers-polyfill'\nimport { HttpResponse, http } from 'msw'\n\nexport type Post = {\n  id: number\n  title: string\n  body: string\n}\n\nexport const posts: Record<string, Post> = {\n  1: { id: 1, title: 'hello', body: 'extra body!' },\n}\n\nexport const handlers = [\n  http.get(\n    'https://example.com',\n    async ({ request, params, cookies, requestId }) => {\n      HttpResponse.json({ value: 'success' })\n    },\n  ),\n  http.get(\n    'https://example.com/echo',\n    async ({ request, params, cookies, requestId }) => {\n      return HttpResponse.json({\n        ...request,\n        params,\n        cookies,\n        requestId,\n        url: new URL(request.url),\n        headers: headersToObject(request.headers),\n      })\n    },\n  ),\n\n  http.post(\n    'https://example.com/echo',\n    async ({ request, cookies, params, requestId }) => {\n      let body\n\n      try {\n        body =\n          headersToObject(request.headers)['content-type'] === 'text/html'\n            ? await request.text()\n            : await request.json()\n      } catch (err) {\n        body = request.body\n      }\n\n      return HttpResponse.json({\n        ...request,\n        cookies,\n        params,\n        requestId,\n        body,\n        url: new URL(request.url),\n        headers: headersToObject(request.headers),\n      })\n    },\n  ),\n\n  http.get('https://example.com/success', () =>\n    HttpResponse.json({ value: 'success' }),\n  ),\n\n  http.post('https://example.com/success', () =>\n    HttpResponse.json({ value: 'success' }),\n  ),\n\n  http.get('https://example.com/empty', () => new HttpResponse('')),\n\n  http.get('https://example.com/error', () =>\n    HttpResponse.json({ value: 'error' }, { status: 500 }),\n  ),\n\n  http.post('https://example.com/error', () =>\n    HttpResponse.json({ value: 'error' }, { status: 500 }),\n  ),\n\n  http.get('https://example.com/nonstandard-error', () =>\n    HttpResponse.json(\n      {\n        success: false,\n        message: 'This returns a 200 but is really an error',\n      },\n      { status: 200 },\n    ),\n  ),\n\n  http.get('https://example.com/mirror', ({ params }) =>\n    HttpResponse.json(params),\n  ),\n\n  http.post('https://example.com/mirror', ({ params }) =>\n    HttpResponse.json(params),\n  ),\n\n  http.get('https://example.com/posts/random', () => {\n    // just simulate an api that returned a random ID\n    const { id } = posts[1]\n    return HttpResponse.json({ id })\n  }),\n\n  http.get<{ id: string }, any, Pick<Post, 'id'>>(\n    'https://example.com/post/:id',\n    ({ params }) => HttpResponse.json(posts[params.id]),\n  ),\n]\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/mocks/server.ts",
    "content": "import { setupServer } from 'msw/node'\nimport { handlers } from './handlers'\n\n// This configures a request mocking server with the given request handlers.\nexport const server = setupServer(...handlers)\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/optimisticUpdates.test.tsx",
    "content": "import { createApi } from '@reduxjs/toolkit/query/react'\nimport { act, renderHook } from '@testing-library/react'\nimport { delay } from 'msw'\nimport {\n  actionsReducer,\n  hookWaitFor,\n  setupApiStore,\n} from '../../tests/utils/helpers'\nimport type { InvalidationState } from '../core/apiState'\n\ninterface Post {\n  id: string\n  title: string\n  contents: string\n}\n\nconst baseQuery = vi.fn()\nbeforeEach(() => {\n  baseQuery.mockReset()\n})\n\nconst api = createApi({\n  baseQuery: (...args: any[]) => {\n    const result = baseQuery(...args)\n    if (typeof result === 'object' && 'then' in result)\n      return result\n        .then((data: any) => ({ data, meta: 'meta' }))\n        .catch((e: any) => ({ error: e }))\n    return { data: result, meta: 'meta' }\n  },\n  tagTypes: ['Post'],\n  endpoints: (build) => ({\n    post: build.query<Post, string>({\n      query: (id) => `post/${id}`,\n      providesTags: ['Post'],\n    }),\n    listPosts: build.query<Post[], void>({\n      query: () => `posts`,\n      providesTags: (result) => [\n        ...(result?.map(({ id }) => ({ type: 'Post' as const, id })) ?? []),\n        'Post',\n      ],\n    }),\n    updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n      query: ({ id, ...patch }) => ({\n        url: `post/${id}`,\n        method: 'PATCH',\n        body: patch,\n      }),\n      async onQueryStarted({ id, ...patch }, { dispatch, queryFulfilled }) {\n        const { undo } = dispatch(\n          api.util.updateQueryData('post', id, (draft) => {\n            Object.assign(draft, patch)\n          }),\n        )\n        queryFulfilled.catch(undo)\n      },\n      invalidatesTags: (result) => (result ? ['Post'] : []),\n    }),\n  }),\n})\n\nconst storeRef = setupApiStore(api, { ...actionsReducer })\n\ndescribe('basic lifecycle', () => {\n  let onStart = vi.fn(),\n    onError = vi.fn(),\n    onSuccess = vi.fn()\n\n  const extendedApi = api.injectEndpoints({\n    endpoints: (build) => ({\n      test: build.mutation({\n        query: (x) => x,\n        async onQueryStarted(arg, api) {\n          onStart(arg)\n          try {\n            const result = await api.queryFulfilled\n            onSuccess(result)\n          } catch (e) {\n            onError(e)\n          }\n        },\n      }),\n    }),\n    overrideExisting: true,\n  })\n\n  beforeEach(() => {\n    onStart.mockReset()\n    onError.mockReset()\n    onSuccess.mockReset()\n  })\n\n  test('success', async () => {\n    const { result } = renderHook(\n      () => extendedApi.endpoints.test.useMutation(),\n      { wrapper: storeRef.wrapper },\n    )\n\n    baseQuery.mockResolvedValue('success')\n\n    expect(onStart).not.toHaveBeenCalled()\n    expect(baseQuery).not.toHaveBeenCalled()\n    act(() => void result.current[0]('arg'))\n    expect(onStart).toHaveBeenCalledWith('arg')\n    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)\n\n    expect(onError).not.toHaveBeenCalled()\n    expect(onSuccess).not.toHaveBeenCalled()\n    await act(() => delay(5))\n    expect(onError).not.toHaveBeenCalled()\n    expect(onSuccess).toHaveBeenCalledWith({ data: 'success', meta: 'meta' })\n  })\n\n  test('error', async () => {\n    const { result } = renderHook(\n      () => extendedApi.endpoints.test.useMutation(),\n      { wrapper: storeRef.wrapper },\n    )\n\n    baseQuery.mockRejectedValueOnce('error')\n    expect(onStart).not.toHaveBeenCalled()\n    expect(baseQuery).not.toHaveBeenCalled()\n\n    act(() => void result.current[0]('arg'))\n    expect(onStart).toHaveBeenCalledWith('arg')\n    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)\n    expect(onError).not.toHaveBeenCalled()\n    expect(onSuccess).not.toHaveBeenCalled()\n    await act(() => delay(5))\n    expect(onError).toHaveBeenCalledWith({\n      error: 'error',\n      isUnhandledError: false,\n      meta: undefined,\n    })\n    expect(onSuccess).not.toHaveBeenCalled()\n  })\n})\n\ndescribe('updateQueryData', () => {\n  test('updates cache values, can apply inverse patch', async () => {\n    baseQuery\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'All about cheese.',\n        contents: 'TODO',\n      })\n      // TODO I have no idea why the query is getting called multiple times,\n      // but passing an additional mocked value (_any_ value)\n      // seems to silence some annoying \"got an undefined result\" logging\n      .mockResolvedValueOnce(42)\n    const { result } = renderHook(() => api.endpoints.post.useQuery('3'), {\n      wrapper: storeRef.wrapper,\n    })\n    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())\n\n    const dataBefore = result.current.data\n    expect(dataBefore).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'TODO',\n    })\n\n    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>\n    act(() => {\n      returnValue = storeRef.store.dispatch(\n        api.util.updateQueryData('post', '3', (draft) => {\n          draft.contents = 'I love cheese!'\n        }),\n      )\n    })\n\n    expect(result.current.data).not.toBe(dataBefore)\n    expect(result.current.data).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'I love cheese!',\n    })\n\n    expect(returnValue).toEqual({\n      inversePatches: [{ op: 'replace', path: ['contents'], value: 'TODO' }],\n      patches: [{ op: 'replace', path: ['contents'], value: 'I love cheese!' }],\n      undo: expect.any(Function),\n    })\n\n    act(() => {\n      storeRef.store.dispatch(\n        api.util.patchQueryData('post', '3', returnValue.inversePatches),\n      )\n    })\n\n    expect(result.current.data).toEqual(dataBefore)\n  })\n\n  test('updates (list) cache values including provided tags, undos that', async () => {\n    baseQuery\n      .mockResolvedValueOnce([\n        { id: '3', title: 'All about cheese.', contents: 'TODO' },\n      ])\n      .mockResolvedValueOnce(42)\n    const { result } = renderHook(() => api.endpoints.listPosts.useQuery(), {\n      wrapper: storeRef.wrapper,\n    })\n    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())\n\n    let provided!: InvalidationState<'Post'>\n    act(() => {\n      provided = storeRef.store.getState().api.provided\n    })\n\n    const provided3 = provided.tags.Post['3']\n\n    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>\n    act(() => {\n      returnValue = storeRef.store.dispatch(\n        api.util.updateQueryData(\n          'listPosts',\n          undefined,\n          (draft) => {\n            draft.push({\n              id: '4',\n              title: 'Mostly about cheese.',\n              contents: 'TODO',\n            })\n          },\n          true,\n        ),\n      )\n    })\n\n    act(() => {\n      provided = storeRef.store.getState().api.provided\n    })\n\n    const provided4 = provided.tags.Post['4']\n\n    expect(provided4).toEqual(provided3)\n\n    act(() => {\n      returnValue.undo()\n    })\n\n    act(() => {\n      provided = storeRef.store.getState().api.provided\n    })\n\n    const provided4Next = provided.tags.Post['4']\n\n    expect(provided4Next).toEqual([])\n  })\n\n  test('updates (list) cache values excluding provided tags, undoes that', async () => {\n    baseQuery\n      .mockResolvedValueOnce([\n        { id: '3', title: 'All about cheese.', contents: 'TODO' },\n      ])\n      .mockResolvedValueOnce(42)\n    const { result } = renderHook(() => api.endpoints.listPosts.useQuery(), {\n      wrapper: storeRef.wrapper,\n    })\n    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())\n\n    let provided!: InvalidationState<'Post'>\n    act(() => {\n      provided = storeRef.store.getState().api.provided\n    })\n\n    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>\n    act(() => {\n      returnValue = storeRef.store.dispatch(\n        api.util.updateQueryData(\n          'listPosts',\n          undefined,\n          (draft) => {\n            draft.push({\n              id: '4',\n              title: 'Mostly about cheese.',\n              contents: 'TODO',\n            })\n          },\n          false,\n        ),\n      )\n    })\n\n    act(() => {\n      provided = storeRef.store.getState().api.provided\n    })\n\n    const provided4 = provided.tags.Post['4']\n\n    expect(provided4).toEqual(undefined)\n\n    act(() => {\n      returnValue.undo()\n    })\n\n    act(() => {\n      provided = storeRef.store.getState().api.provided\n    })\n\n    const provided4Next = provided.tags.Post['4']\n\n    expect(provided4Next).toEqual(undefined)\n  })\n\n  test('does not update non-existing values', async () => {\n    baseQuery\n      .mockImplementationOnce(async () => ({\n        id: '3',\n        title: 'All about cheese.',\n        contents: 'TODO',\n      }))\n      .mockResolvedValueOnce(42)\n\n    const { result } = renderHook(() => api.endpoints.post.useQuery('3'), {\n      wrapper: storeRef.wrapper,\n    })\n    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())\n\n    const dataBefore = result.current.data\n    expect(dataBefore).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'TODO',\n    })\n\n    let returnValue!: ReturnType<ReturnType<typeof api.util.updateQueryData>>\n    act(() => {\n      returnValue = storeRef.store.dispatch(\n        api.util.updateQueryData('post', '4', (draft) => {\n          draft.contents = 'I love cheese!'\n        }),\n      )\n    })\n\n    expect(result.current.data).toBe(dataBefore)\n\n    expect(returnValue).toEqual({\n      inversePatches: [],\n      patches: [],\n      undo: expect.any(Function),\n    })\n  })\n})\n\ndescribe('full integration', () => {\n  test('success case', async () => {\n    baseQuery\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'All about cheese.',\n        contents: 'TODO',\n      })\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'Meanwhile, this changed server-side.',\n        contents: 'Delicious cheese!',\n      })\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'Meanwhile, this changed server-side.',\n        contents: 'Delicious cheese!',\n      })\n      .mockResolvedValueOnce(42)\n    const { result } = renderHook(\n      () => ({\n        query: api.endpoints.post.useQuery('3'),\n        mutation: api.endpoints.updatePost.useMutation(),\n      }),\n      { wrapper: storeRef.wrapper },\n    )\n    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())\n\n    expect(result.current.query.data).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'TODO',\n    })\n\n    act(() => {\n      result.current.mutation[0]({ id: '3', contents: 'Delicious cheese!' })\n    })\n\n    expect(result.current.query.data).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'Delicious cheese!',\n    })\n\n    await hookWaitFor(() =>\n      expect(result.current.query.data).toEqual({\n        id: '3',\n        title: 'Meanwhile, this changed server-side.',\n        contents: 'Delicious cheese!',\n      }),\n    )\n  })\n\n  test('error case', async () => {\n    baseQuery\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'All about cheese.',\n        contents: 'TODO',\n      })\n      .mockRejectedValueOnce('some error!')\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'Meanwhile, this changed server-side.',\n        contents: 'TODO',\n      })\n      .mockResolvedValueOnce(42)\n\n    const { result } = renderHook(\n      () => ({\n        query: api.endpoints.post.useQuery('3'),\n        mutation: api.endpoints.updatePost.useMutation(),\n      }),\n      { wrapper: storeRef.wrapper },\n    )\n    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())\n\n    expect(result.current.query.data).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'TODO',\n    })\n\n    act(() => {\n      result.current.mutation[0]({ id: '3', contents: 'Delicious cheese!' })\n    })\n\n    // optimistic update\n    expect(result.current.query.data).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'Delicious cheese!',\n    })\n\n    // rollback\n    await hookWaitFor(() =>\n      expect(result.current.query.data).toEqual({\n        id: '3',\n        title: 'All about cheese.',\n        contents: 'TODO',\n      }),\n    )\n\n    // mutation failed - will not invalidate query and not refetch data from the server\n    await expect(() =>\n      hookWaitFor(\n        () =>\n          expect(result.current.query.data).toEqual({\n            id: '3',\n            title: 'Meanwhile, this changed server-side.',\n            contents: 'TODO',\n          }),\n        50,\n      ),\n    ).rejects.toBeTruthy()\n\n    act(() => void result.current.query.refetch())\n\n    // manually refetching gives up-to-date data\n    await hookWaitFor(\n      () =>\n        expect(result.current.query.data).toEqual({\n          id: '3',\n          title: 'Meanwhile, this changed server-side.',\n          contents: 'TODO',\n        }),\n      50,\n    )\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/optimisticUpserts.test.tsx",
    "content": "import { createApi } from '@reduxjs/toolkit/query/react'\nimport { createAction } from '@reduxjs/toolkit'\nimport {\n  actionsReducer,\n  hookWaitFor,\n  setupApiStore,\n} from '../../tests/utils/helpers'\nimport {\n  render,\n  renderHook,\n  act,\n  waitFor,\n  screen,\n} from '@testing-library/react'\nimport { delay } from 'msw'\n\ninterface Post {\n  id: string\n  title: string\n  contents: string\n}\n\ninterface FolderT {\n  id: number\n  children: FolderT[]\n}\n\nconst baseQuery = vi.fn()\nbeforeEach(() => baseQuery.mockReset())\n\nconst postAddedAction = createAction<string>('postAdded')\n\nconst api = createApi({\n  baseQuery: (...args: any[]) => {\n    const result = baseQuery(...args)\n    if (typeof result === 'object' && 'then' in result)\n      return result\n        .then((data: any) => ({ data, meta: 'meta' }))\n        .catch((e: any) => ({ error: e }))\n    return { data: result, meta: 'meta' }\n  },\n  tagTypes: ['Post', 'Folder'],\n  endpoints: (build) => ({\n    getPosts: build.query<Post[], void>({ query: () => '/posts' }),\n    post: build.query<Post, string>({\n      query: (id) => `post/${id}`,\n      providesTags: ['Post'],\n    }),\n    updatePost: build.mutation<void, Pick<Post, 'id'> & Partial<Post>>({\n      query: ({ id, ...patch }) => ({\n        url: `post/${id}`,\n        method: 'PATCH',\n        body: patch,\n      }),\n      async onQueryStarted(arg, { dispatch, queryFulfilled, getState }) {\n        const currentItem = api.endpoints.post.select(arg.id)(getState())\n        if (currentItem?.data) {\n          dispatch(\n            api.util.upsertQueryData('post', arg.id, {\n              ...currentItem.data,\n              ...arg,\n            }),\n          )\n        }\n      },\n      invalidatesTags: (result) => (result ? ['Post'] : []),\n    }),\n    post2: build.query<Post, string>({\n      queryFn: async (id) => {\n        await delay(20)\n        return { data: { id, title: 'All about cheese.', contents: 'TODO' } }\n      },\n    }),\n    postWithSideEffect: build.query<Post, string>({\n      query: (id) => `post/${id}`,\n      providesTags: (result) => {\n        if (result) {\n          return [{ type: 'Post', id: result.id } as const]\n        }\n        return []\n      },\n      async onCacheEntryAdded(arg, api) {\n        // Verify that lifecycle promise resolution works\n        const res = await api.cacheDataLoaded\n\n        // and leave a side effect we can check in the test\n        api.dispatch(postAddedAction(res.data.id))\n      },\n      keepUnusedDataFor: 0.1,\n    }),\n    getFolder: build.query<FolderT, number>({\n      queryFn: async (args) => {\n        return {\n          data: {\n            id: args,\n            // Folder contains children that are as well folders\n            children: [{ id: 2, children: [] }],\n          },\n        }\n      },\n      providesTags: (result, err, args) => [{ type: 'Folder', id: args }],\n      onQueryStarted: async (args, queryApi) => {\n        const { data } = await queryApi.queryFulfilled\n\n        // Upsert getFolder endpoint with children from response data\n        const upsertData = data.children.map((child) => ({\n          arg: child.id,\n          endpointName: 'getFolder' as const,\n          value: child,\n        }))\n\n        queryApi.dispatch(api.util.upsertQueryEntries(upsertData))\n      },\n    }),\n  }),\n})\n\nconst storeRef = setupApiStore(api, { ...actionsReducer })\n\ndescribe('basic lifecycle', () => {\n  let onStart = vi.fn(),\n    onError = vi.fn(),\n    onSuccess = vi.fn()\n\n  const extendedApi = api.injectEndpoints({\n    endpoints: (build) => ({\n      test: build.mutation({\n        query: (x) => x,\n        async onQueryStarted(arg, api) {\n          onStart(arg)\n          try {\n            const result = await api.queryFulfilled\n            onSuccess(result)\n          } catch (e) {\n            onError(e)\n          }\n        },\n      }),\n    }),\n    overrideExisting: true,\n  })\n\n  beforeEach(() => {\n    onStart.mockReset()\n    onError.mockReset()\n    onSuccess.mockReset()\n  })\n\n  test('Does basic inserts and upserts', async () => {\n    const newPost: Post = {\n      id: '3',\n      contents: 'Inserted content',\n      title: 'Inserted title',\n    }\n    const insertPromise = storeRef.store.dispatch(\n      api.util.upsertQueryData('post', newPost.id, newPost),\n    )\n\n    await insertPromise\n\n    const selectPost3 = api.endpoints.post.select(newPost.id)\n    const insertedPostEntry = selectPost3(storeRef.store.getState())\n    expect(insertedPostEntry.isSuccess).toBe(true)\n    expect(insertedPostEntry.data).toEqual(newPost)\n\n    const updatedPost: Post = {\n      id: '3',\n      contents: 'Updated content',\n      title: 'Updated title',\n    }\n\n    const updatePromise = storeRef.store.dispatch(\n      api.util.upsertQueryData('post', updatedPost.id, updatedPost),\n    )\n\n    await updatePromise\n\n    const updatedPostEntry = selectPost3(storeRef.store.getState())\n\n    expect(updatedPostEntry.isSuccess).toBe(true)\n    expect(updatedPostEntry.data).toEqual(updatedPost)\n  })\n\n  test('success', async () => {\n    const { result } = renderHook(\n      () => extendedApi.endpoints.test.useMutation(),\n      { wrapper: storeRef.wrapper },\n    )\n\n    baseQuery.mockResolvedValue('success')\n\n    expect(onStart).not.toHaveBeenCalled()\n    expect(baseQuery).not.toHaveBeenCalled()\n    act(() => void result.current[0]('arg'))\n    expect(onStart).toHaveBeenCalledWith('arg')\n    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)\n\n    expect(onError).not.toHaveBeenCalled()\n    expect(onSuccess).not.toHaveBeenCalled()\n    await act(() => delay(5))\n    expect(onError).not.toHaveBeenCalled()\n    expect(onSuccess).toHaveBeenCalledWith({ data: 'success', meta: 'meta' })\n  })\n\n  test('error', async () => {\n    const { result } = renderHook(\n      () => extendedApi.endpoints.test.useMutation(),\n      { wrapper: storeRef.wrapper },\n    )\n\n    baseQuery.mockRejectedValueOnce('error')\n\n    expect(onStart).not.toHaveBeenCalled()\n    expect(baseQuery).not.toHaveBeenCalled()\n    act(() => void result.current[0]('arg'))\n    expect(onStart).toHaveBeenCalledWith('arg')\n    expect(baseQuery).toHaveBeenCalledWith('arg', expect.any(Object), undefined)\n\n    expect(onError).not.toHaveBeenCalled()\n    expect(onSuccess).not.toHaveBeenCalled()\n    await act(() => delay(5))\n    expect(onError).toHaveBeenCalledWith({\n      error: 'error',\n      isUnhandledError: false,\n      meta: undefined,\n    })\n    expect(onSuccess).not.toHaveBeenCalled()\n  })\n})\n\ndescribe('upsertQueryData', () => {\n  test('inserts cache entry', async () => {\n    baseQuery\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'All about cheese.',\n        contents: 'TODO',\n      })\n      // TODO I have no idea why the query is getting called multiple times,\n      // but passing an additional mocked value (_any_ value)\n      // seems to silence some annoying \"got an undefined result\" logging\n      .mockResolvedValueOnce(42)\n    const { result } = renderHook(() => api.endpoints.post.useQuery('3'), {\n      wrapper: storeRef.wrapper,\n    })\n    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())\n\n    const dataBefore = result.current.data\n    expect(dataBefore).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'TODO',\n    })\n\n    await act(async () => {\n      storeRef.store.dispatch(\n        api.util.upsertQueryData('post', '3', {\n          id: '3',\n          title: 'All about cheese.',\n          contents: 'I love cheese!',\n        }),\n      )\n    })\n\n    expect(result.current.data).not.toBe(dataBefore)\n    expect(result.current.data).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'I love cheese!',\n    })\n  })\n\n  test('does update non-existing values', async () => {\n    baseQuery\n      // throw an error to make sure there is no cached data\n      .mockImplementationOnce(async () => {\n        throw new Error('failed to load')\n      })\n      .mockResolvedValueOnce(42)\n\n    // a subscriber is needed to have the data stay in the cache\n    // Not sure if this is the wanted behavior, I would have liked\n    // it to stay in the cache for the x amount of time the cache\n    // is preserved normally after the last subscriber was unmounted\n    const { result, rerender } = renderHook(\n      () => api.endpoints.post.useQuery('4'),\n      { wrapper: storeRef.wrapper },\n    )\n    await hookWaitFor(() => expect(result.current.isError).toBeTruthy())\n\n    // upsert the data\n    act(() => {\n      storeRef.store.dispatch(\n        api.util.upsertQueryData('post', '4', {\n          id: '4',\n          title: 'All about cheese',\n          contents: 'I love cheese!',\n        }),\n      )\n    })\n\n    // rerender the hook\n    rerender()\n    // wait until everything has settled\n    await hookWaitFor(() => expect(result.current.isSuccess).toBeTruthy())\n\n    // the cached data is returned as the result\n    expect(result.current.data).toStrictEqual({\n      id: '4',\n      title: 'All about cheese',\n      contents: 'I love cheese!',\n    })\n  })\n\n  test('upsert while a normal query is running (success)', async () => {\n    const fetchedData = {\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'Yummy',\n    }\n    baseQuery.mockImplementation(() => delay(20).then(() => fetchedData))\n    const upsertedData = {\n      id: '3',\n      title: 'Data from a SSR Render',\n      contents: 'This is just some random data',\n    }\n\n    const selector = api.endpoints.post.select('3')\n    const fetchRes = storeRef.store.dispatch(api.endpoints.post.initiate('3'))\n    const upsertRes = storeRef.store.dispatch(\n      api.util.upsertQueryData('post', '3', upsertedData),\n    )\n\n    await upsertRes\n    let state = selector(storeRef.store.getState())\n    expect(state.data).toEqual(upsertedData)\n\n    await fetchRes\n    state = selector(storeRef.store.getState())\n    expect(state.data).toEqual(fetchedData)\n  })\n  test('upsert while a normal query is running (rejected)', async () => {\n    baseQuery.mockImplementationOnce(async () => {\n      await delay(20)\n      // eslint-disable-next-line no-throw-literal\n      throw 'Error!'\n    })\n    const upsertedData = {\n      id: '3',\n      title: 'Data from a SSR Render',\n      contents: 'This is just some random data',\n    }\n\n    const selector = api.endpoints.post.select('3')\n    const fetchRes = storeRef.store.dispatch(api.endpoints.post.initiate('3'))\n    const upsertRes = storeRef.store.dispatch(\n      api.util.upsertQueryData('post', '3', upsertedData),\n    )\n\n    await upsertRes\n    let state = selector(storeRef.store.getState())\n    expect(state.data).toEqual(upsertedData)\n    expect(state.isSuccess).toBeTruthy()\n\n    await fetchRes\n    state = selector(storeRef.store.getState())\n    expect(state.data).toEqual(upsertedData)\n    expect(state.isError).toBeTruthy()\n  })\n})\n\ndescribe('upsertQueryEntries', () => {\n  const posts: Post[] = [\n    { id: '1', contents: 'A', title: 'A' },\n    { id: '2', contents: 'B', title: 'B' },\n    { id: '3', contents: 'C', title: 'C' },\n  ]\n\n  const entriesAction = api.util.upsertQueryEntries([\n    { endpointName: 'getPosts', arg: undefined, value: posts },\n    ...posts.map((post) => ({\n      endpointName: 'postWithSideEffect' as const,\n      arg: post.id,\n      value: post,\n    })),\n  ])\n\n  test('Upserts many entries at once', async () => {\n    storeRef.store.dispatch(entriesAction)\n\n    const state = storeRef.store.getState()\n\n    expect(api.endpoints.getPosts.select()(state).data).toBe(posts)\n\n    for (const post of posts) {\n      expect(api.endpoints.postWithSideEffect.select(post.id)(state).data).toBe(\n        post,\n      )\n\n      // Should have added tags\n      expect(state.api.provided.tags.Post[post.id]).toEqual([\n        `postWithSideEffect(\"${post.id}\")`,\n      ])\n    }\n  })\n\n  test('Triggers cache lifecycles and side effects', async () => {\n    storeRef.store.dispatch(entriesAction)\n\n    // Tricky timing. The cache data promises will be resolved\n    // in microtasks. We need to wait for them. Best to do this\n    // in a loop just to avoid a hardcoded delay, but also this\n    // needs to complete before `keepUnusedDataFor` expires them.\n    await waitFor(\n      () => {\n        const state = storeRef.store.getState()\n\n        // onCacheEntryAdded should have run for each post,\n        // including cache data being resolved\n        for (const post of posts) {\n          const matchingSideEffectAction = state.actions.find(\n            (action) =>\n              postAddedAction.match(action) && action.payload === post.id,\n          )\n          expect(matchingSideEffectAction).toBeTruthy()\n        }\n\n        const selectedData =\n          api.endpoints.postWithSideEffect.select('1')(state).data\n\n        expect(selectedData).toBe(posts[0])\n      },\n      { timeout: 150, interval: 5 },\n    )\n\n    // The cache data should be removed after the keepUnusedDataFor time,\n    // so wait longer than that\n    await delay(300)\n\n    const stateAfter = storeRef.store.getState()\n\n    expect(api.endpoints.postWithSideEffect.select('1')(stateAfter).data).toBe(\n      undefined,\n    )\n  })\n\n  test('Handles repeated upserts and async lifecycles', async () => {\n    const StateForUpsertFolder = ({ folderId }: { folderId: number }) => {\n      const { status } = api.useGetFolderQuery(folderId)\n\n      return (\n        <>\n          <div>\n            Status getFolder with ID (\n            {folderId === 1 ? 'original request' : 'upserted'}) {folderId}:{' '}\n            <span data-testid={`status-${folderId}`}>{status}</span>\n          </div>\n        </>\n      )\n    }\n\n    const Folder = () => {\n      const { data, isLoading, isError } = api.useGetFolderQuery(1)\n\n      return (\n        <div>\n          <h1>Folders</h1>\n\n          {isLoading && <div>Loading...</div>}\n\n          {isError && <div>Error...</div>}\n\n          <StateForUpsertFolder key={`state-${1}`} folderId={1} />\n          <StateForUpsertFolder key={`state-${2}`} folderId={2} />\n        </div>\n      )\n    }\n\n    render(<Folder />, { wrapper: storeRef.wrapper })\n\n    await waitFor(() => {\n      const { actions } = storeRef.store.getState()\n      // Inspection:\n      // - 2 inits\n      // - 2 pendings, 2 fulfilleds for the hook queries\n      // - 2 upserts\n      expect(actions.length).toBe(8)\n      expect(\n        actions.filter((a) => api.util.upsertQueryEntries.match(a)).length,\n      ).toBe(2)\n    })\n    expect(screen.getByTestId('status-2').textContent).toBe('fulfilled')\n  })\n})\n\ndescribe('full integration', () => {\n  test('success case', async () => {\n    baseQuery\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'All about cheese.',\n        contents: 'TODO',\n      })\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'Meanwhile, this changed server-side.',\n        contents: 'Delicious cheese!',\n      })\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'Meanwhile, this changed server-side.',\n        contents: 'Delicious cheese!',\n      })\n      .mockResolvedValueOnce(42)\n    const { result } = renderHook(\n      () => ({\n        query: api.endpoints.post.useQuery('3'),\n        mutation: api.endpoints.updatePost.useMutation(),\n      }),\n      { wrapper: storeRef.wrapper },\n    )\n    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())\n\n    expect(result.current.query.data).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'TODO',\n    })\n\n    await act(async () => {\n      await result.current.mutation[0]({\n        id: '3',\n        contents: 'Delicious cheese!',\n      })\n    })\n\n    expect(result.current.query.data).toEqual({\n      id: '3',\n      title: 'Meanwhile, this changed server-side.',\n      contents: 'Delicious cheese!',\n    })\n\n    await hookWaitFor(() =>\n      expect(result.current.query.data).toEqual({\n        id: '3',\n        title: 'Meanwhile, this changed server-side.',\n        contents: 'Delicious cheese!',\n      }),\n    )\n  })\n\n  test('error case', async () => {\n    baseQuery\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'All about cheese.',\n        contents: 'TODO',\n      })\n      .mockRejectedValueOnce('some error!')\n      .mockResolvedValueOnce({\n        id: '3',\n        title: 'Meanwhile, this changed server-side.',\n        contents: 'TODO',\n      })\n      .mockResolvedValueOnce(42)\n\n    const { result } = renderHook(\n      () => ({\n        query: api.endpoints.post.useQuery('3'),\n        mutation: api.endpoints.updatePost.useMutation(),\n      }),\n      { wrapper: storeRef.wrapper },\n    )\n    await hookWaitFor(() => expect(result.current.query.isSuccess).toBeTruthy())\n\n    expect(result.current.query.data).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'TODO',\n    })\n\n    await act(async () => {\n      await result.current.mutation[0]({\n        id: '3',\n        contents: 'Delicious cheese!',\n      })\n    })\n\n    // optimistic update\n    expect(result.current.query.data).toEqual({\n      id: '3',\n      title: 'All about cheese.',\n      contents: 'Delicious cheese!',\n    })\n\n    // mutation failed - will not invalidate query and not refetch data from the server\n    await expect(() =>\n      hookWaitFor(\n        () =>\n          expect(result.current.query.data).toEqual({\n            id: '3',\n            title: 'Meanwhile, this changed server-side.',\n            contents: 'TODO',\n          }),\n        50,\n      ),\n    ).rejects.toBeTruthy()\n\n    act(() => void result.current.query.refetch())\n\n    // manually refetching gives up-to-date data\n    await hookWaitFor(\n      () =>\n        expect(result.current.query.data).toEqual({\n          id: '3',\n          title: 'Meanwhile, this changed server-side.',\n          contents: 'TODO',\n        }),\n      50,\n    )\n  })\n\n  test('Interop with in-flight requests', async () => {\n    await act(async () => {\n      const fetchRes = storeRef.store.dispatch(\n        api.endpoints.post2.initiate('3'),\n      )\n\n      const upsertRes = storeRef.store.dispatch(\n        api.util.upsertQueryData('post2', '3', {\n          id: '3',\n          title: 'Upserted title',\n          contents: 'Upserted contents',\n        }),\n      )\n\n      const selectEntry = api.endpoints.post2.select('3')\n      await waitFor(\n        () => {\n          const entry1 = selectEntry(storeRef.store.getState())\n          expect(entry1.data).toEqual({\n            id: '3',\n            title: 'Upserted title',\n            contents: 'Upserted contents',\n          })\n        },\n        { interval: 1, timeout: 15 },\n      )\n      await waitFor(\n        () => {\n          const entry2 = selectEntry(storeRef.store.getState())\n          expect(entry2.data).toEqual({\n            id: '3',\n            title: 'All about cheese.',\n            contents: 'TODO',\n          })\n        },\n        { interval: 1 },\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/polling.test.tsx",
    "content": "import { createApi } from '@reduxjs/toolkit/query'\nimport type { QueryActionCreatorResult } from '@reduxjs/toolkit/query'\nimport { delay } from 'msw'\nimport { setupApiStore } from '../../tests/utils/helpers'\nimport type { SubscriptionSelectors } from '../core/buildMiddleware/types'\n\nconst mockBaseQuery = vi\n  .fn()\n  .mockImplementation((args: any) => ({ data: args }))\n\nconst api = createApi({\n  baseQuery: mockBaseQuery,\n  tagTypes: ['Posts'],\n  endpoints: (build) => ({\n    getPosts: build.query<unknown, number>({\n      query(pageNumber) {\n        return { url: 'posts', params: pageNumber }\n      },\n      providesTags: ['Posts'],\n    }),\n  }),\n})\nconst { getPosts } = api.endpoints\n\nconst storeRef = setupApiStore(api)\n\nlet getSubscriptions: SubscriptionSelectors['getSubscriptions']\n\nbeforeEach(() => {\n  ;({ getSubscriptions } = storeRef.store.dispatch(\n    api.internalActions.internal_getRTKQSubscriptions(),\n  ) as unknown as SubscriptionSelectors)\n\n  const currentPolls = storeRef.store.dispatch({\n    type: `${api.reducerPath}/getPolling`,\n  }) as any\n  ;(currentPolls as any).pollUpdateCounters = {}\n})\n\nconst getSubscribersForQueryCacheKey = (queryCacheKey: string) =>\n  getSubscriptions().get(queryCacheKey) ?? new Map()\nconst createSubscriptionGetter = (queryCacheKey: string) => () =>\n  getSubscribersForQueryCacheKey(queryCacheKey)\n\ndescribe('polling tests', () => {\n  it('clears intervals when seeing a resetApiState action', async () => {\n    await storeRef.store.dispatch(\n      getPosts.initiate(1, {\n        subscriptionOptions: { pollingInterval: 10 },\n        subscribe: true,\n      }),\n    )\n\n    expect(mockBaseQuery).toHaveBeenCalledOnce()\n\n    storeRef.store.dispatch(api.util.resetApiState())\n\n    await delay(30)\n\n    expect(mockBaseQuery).toHaveBeenCalledOnce()\n  })\n\n  it('replaces polling interval when the subscription options are updated', async () => {\n    const { requestId, queryCacheKey, ...subscription } =\n      storeRef.store.dispatch(\n        getPosts.initiate(1, {\n          subscriptionOptions: { pollingInterval: 10 },\n          subscribe: true,\n        }),\n      )\n\n    const getSubs = createSubscriptionGetter(queryCacheKey)\n\n    await delay(1)\n    expect(getSubs().size).toBe(1)\n    expect(getSubs()?.get(requestId)?.pollingInterval).toBe(10)\n\n    subscription.updateSubscriptionOptions({ pollingInterval: 20 })\n\n    await delay(1)\n    expect(getSubs().size).toBe(1)\n    expect(getSubs()?.get(requestId)?.pollingInterval).toBe(20)\n  })\n\n  it(`doesn't replace the interval when removing a shared query instance with a poll `, async () => {\n    const subscriptionOne = storeRef.store.dispatch(\n      getPosts.initiate(1, {\n        subscriptionOptions: { pollingInterval: 10 },\n        subscribe: true,\n      }),\n    )\n\n    storeRef.store.dispatch(\n      getPosts.initiate(1, {\n        subscriptionOptions: { pollingInterval: 10 },\n        subscribe: true,\n      }),\n    )\n\n    await delay(10)\n\n    const getSubs = createSubscriptionGetter(subscriptionOne.queryCacheKey)\n\n    expect(getSubs().size).toBe(2)\n\n    subscriptionOne.unsubscribe()\n\n    await delay(1)\n    expect(getSubs().size).toBe(1)\n  })\n\n  it('uses lowest specified interval when two components are mounted', async () => {\n    storeRef.store.dispatch(\n      getPosts.initiate(1, {\n        subscriptionOptions: { pollingInterval: 30000 },\n        subscribe: true,\n      }),\n    )\n\n    storeRef.store.dispatch(\n      getPosts.initiate(1, {\n        subscriptionOptions: { pollingInterval: 10 },\n        subscribe: true,\n      }),\n    )\n\n    await delay(20)\n\n    expect(mockBaseQuery.mock.calls.length).toBeGreaterThanOrEqual(2)\n  })\n\n  it('respects skipPollingIfUnfocused', async () => {\n    mockBaseQuery.mockClear()\n    storeRef.store.dispatch(\n      getPosts.initiate(2, {\n        subscriptionOptions: {\n          pollingInterval: 10,\n          skipPollingIfUnfocused: true,\n        },\n        subscribe: true,\n      }),\n    )\n    storeRef.store.dispatch(api.internalActions?.onFocusLost())\n\n    await delay(50)\n    const callsWithSkip = mockBaseQuery.mock.calls.length\n\n    storeRef.store.dispatch(\n      getPosts.initiate(2, {\n        subscriptionOptions: {\n          pollingInterval: 10,\n          skipPollingIfUnfocused: false,\n        },\n        subscribe: true,\n      }),\n    )\n\n    storeRef.store.dispatch(api.internalActions?.onFocus())\n\n    await delay(50)\n    const callsWithoutSkip = mockBaseQuery.mock.calls.length\n\n    expect(callsWithSkip).toBe(1)\n    expect(callsWithoutSkip).toBeGreaterThanOrEqual(2)\n\n    storeRef.store.dispatch(api.util.resetApiState())\n  })\n\n  it('respects skipPollingIfUnfocused if at least one subscription has it', async () => {\n    storeRef.store.dispatch(\n      getPosts.initiate(3, {\n        subscriptionOptions: {\n          pollingInterval: 10,\n          skipPollingIfUnfocused: false,\n        },\n        subscribe: true,\n      }),\n    )\n\n    await delay(50)\n    const callsWithoutSkip = mockBaseQuery.mock.calls.length\n\n    storeRef.store.dispatch(\n      getPosts.initiate(3, {\n        subscriptionOptions: {\n          pollingInterval: 15,\n          skipPollingIfUnfocused: true,\n        },\n        subscribe: true,\n      }),\n    )\n\n    storeRef.store.dispatch(\n      getPosts.initiate(3, {\n        subscriptionOptions: {\n          pollingInterval: 20,\n          skipPollingIfUnfocused: false,\n        },\n        subscribe: true,\n      }),\n    )\n\n    storeRef.store.dispatch(api.internalActions?.onFocusLost())\n\n    await delay(50)\n    const callsWithSkip = mockBaseQuery.mock.calls.length\n\n    expect(callsWithoutSkip).toBeGreaterThan(2)\n    expect(callsWithSkip).toBe(callsWithoutSkip + 1)\n  })\n\n  it('replaces skipPollingIfUnfocused when the subscription options are updated', async () => {\n    const { requestId, queryCacheKey, ...subscription } =\n      storeRef.store.dispatch(\n        getPosts.initiate(1, {\n          subscriptionOptions: {\n            pollingInterval: 10,\n            skipPollingIfUnfocused: false,\n          },\n          subscribe: true,\n        }),\n      )\n\n    const getSubs = createSubscriptionGetter(queryCacheKey)\n\n    await delay(1)\n    expect(getSubs().size).toBe(1)\n    expect(getSubs().get(requestId)?.skipPollingIfUnfocused).toBe(false)\n\n    subscription.updateSubscriptionOptions({\n      pollingInterval: 20,\n      skipPollingIfUnfocused: true,\n    })\n\n    await delay(1)\n    expect(getSubs().size).toBe(1)\n    expect(getSubs().get(requestId)?.skipPollingIfUnfocused).toBe(true)\n  })\n\n  it('should minimize polling recalculations when adding multiple subscribers', async () => {\n    // Reset any existing state\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    const SUBSCRIBER_COUNT = 10\n    const subscriptions: QueryActionCreatorResult<any>[] = []\n\n    // Add 10 subscribers to the same endpoint with polling enabled\n    for (let i = 0; i < SUBSCRIBER_COUNT; i++) {\n      const subscription = storeRef.store.dispatch(\n        getPosts.initiate(1, {\n          subscriptionOptions: { pollingInterval: 1000 },\n          subscribe: true,\n        }),\n      )\n      subscriptions.push(subscription)\n    }\n\n    // Wait a bit for all subscriptions to be processed\n    await Promise.all(subscriptions)\n\n    // Wait for the poll update timer\n    await delay(25)\n\n    // Get the polling state using the secret \"getPolling\" action\n    const currentPolls = storeRef.store.dispatch({\n      type: `${api.reducerPath}/getPolling`,\n    }) as any\n\n    // Get the query cache key for our endpoint\n    const queryCacheKey = subscriptions[0].queryCacheKey\n\n    // Check the poll update counters\n    const pollUpdateCounters = currentPolls.pollUpdateCounters || {}\n    const updateCount = pollUpdateCounters[queryCacheKey] || 0\n\n    // With batching optimization, this should be much lower than SUBSCRIBER_COUNT\n    // Ideally 1, but could be slightly higher due to timing\n    expect(updateCount).toBeGreaterThanOrEqual(1)\n    expect(updateCount).toBeLessThanOrEqual(2)\n\n    // Clean up subscriptions\n    subscriptions.forEach((sub) => sub.unsubscribe())\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/queryFn.test.tsx",
    "content": "import { noop } from '@internal/listenerMiddleware/utils'\nimport type { Post } from '@internal/query/tests/mocks/handlers'\nimport { posts } from '@internal/query/tests/mocks/handlers'\nimport { actionsReducer, setupApiStore } from '@internal/tests/utils/helpers'\nimport type { SerializedError } from '@reduxjs/toolkit'\nimport { configureStore } from '@reduxjs/toolkit'\nimport type {\n  BaseQueryFn,\n  FetchBaseQueryError,\n  QuerySubState,\n} from '@reduxjs/toolkit/query'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\ndescribe('queryFn base implementation tests', () => {\n  const baseQuery: BaseQueryFn<string, { wrappedByBaseQuery: string }, string> =\n    vi.fn((arg: string) =>\n      arg.includes('withErrorQuery')\n        ? { error: `cut${arg}` }\n        : { data: { wrappedByBaseQuery: arg } },\n    )\n\n  const api = createApi({\n    baseQuery,\n    endpoints: (build) => ({\n      withQuery: build.query<string, string>({\n        query(arg: string) {\n          return `resultFrom(${arg})`\n        },\n        transformResponse(response) {\n          return response.wrappedByBaseQuery\n        },\n      }),\n      withErrorQuery: build.query<string, string>({\n        query(arg: string) {\n          return `resultFrom(${arg})`\n        },\n        transformErrorResponse(response) {\n          return response.slice(3)\n        },\n      }),\n      withQueryFn: build.query<string, string>({\n        queryFn(arg: string) {\n          return { data: `resultFrom(${arg})` }\n        },\n      }),\n      withInvalidDataQueryFn: build.query<string, string>({\n        // @ts-expect-error\n        queryFn(arg: string) {\n          return { data: 5 }\n        },\n      }),\n      withErrorQueryFn: build.query<string, string>({\n        queryFn(arg: string) {\n          return { error: `resultFrom(${arg})` }\n        },\n      }),\n      withInvalidErrorQueryFn: build.query<string, string>({\n        // @ts-expect-error\n        queryFn(arg: string) {\n          return { error: 5 }\n        },\n      }),\n      withThrowingQueryFn: build.query<string, string>({\n        queryFn(arg: string) {\n          throw new Error(`resultFrom(${arg})`)\n        },\n      }),\n      withAsyncQueryFn: build.query<string, string>({\n        async queryFn(arg: string) {\n          return { data: `resultFrom(${arg})` }\n        },\n      }),\n      withInvalidDataAsyncQueryFn: build.query<string, string>({\n        // @ts-expect-error\n        async queryFn(arg: string) {\n          return { data: 5 }\n        },\n      }),\n      withAsyncErrorQueryFn: build.query<string, string>({\n        async queryFn(arg: string) {\n          return { error: `resultFrom(${arg})` }\n        },\n      }),\n      withInvalidAsyncErrorQueryFn: build.query<string, string>({\n        // @ts-expect-error\n        async queryFn(arg: string) {\n          return { error: 5 }\n        },\n      }),\n      withAsyncThrowingQueryFn: build.query<string, string>({\n        async queryFn(arg: string) {\n          throw new Error(`resultFrom(${arg})`)\n        },\n      }),\n      mutationWithQueryFn: build.mutation<string, string>({\n        queryFn(arg: string) {\n          return { data: `resultFrom(${arg})` }\n        },\n      }),\n      mutationWithInvalidDataQueryFn: build.mutation<string, string>({\n        // @ts-expect-error\n        queryFn(arg: string) {\n          return { data: 5 }\n        },\n      }),\n      mutationWithErrorQueryFn: build.mutation<string, string>({\n        queryFn(arg: string) {\n          return { error: `resultFrom(${arg})` }\n        },\n      }),\n      mutationWithInvalidErrorQueryFn: build.mutation<string, string>({\n        // @ts-expect-error\n        queryFn(arg: string) {\n          return { error: 5 }\n        },\n      }),\n      mutationWithThrowingQueryFn: build.mutation<string, string>({\n        queryFn(arg: string) {\n          throw new Error(`resultFrom(${arg})`)\n        },\n      }),\n      mutationWithAsyncQueryFn: build.mutation<string, string>({\n        async queryFn(arg: string) {\n          return { data: `resultFrom(${arg})` }\n        },\n      }),\n      mutationWithInvalidAsyncQueryFn: build.mutation<string, string>({\n        // @ts-expect-error\n        async queryFn(arg: string) {\n          return { data: 5 }\n        },\n      }),\n      mutationWithAsyncErrorQueryFn: build.mutation<string, string>({\n        async queryFn(arg: string) {\n          return { error: `resultFrom(${arg})` }\n        },\n      }),\n      mutationWithInvalidAsyncErrorQueryFn: build.mutation<string, string>({\n        // @ts-expect-error\n        async queryFn(arg: string) {\n          return { error: 5 }\n        },\n      }),\n      mutationWithAsyncThrowingQueryFn: build.mutation<string, string>({\n        async queryFn(arg: string) {\n          throw new Error(`resultFrom(${arg})`)\n        },\n      }),\n      // @ts-expect-error\n      withNeither: build.query<string, string>({}),\n      // @ts-expect-error\n      mutationWithNeither: build.mutation<string, string>({}),\n    }),\n  })\n\n  const {\n    withQuery,\n    withErrorQuery,\n    withQueryFn,\n    withErrorQueryFn,\n    withThrowingQueryFn,\n    withAsyncQueryFn,\n    withAsyncErrorQueryFn,\n    withAsyncThrowingQueryFn,\n    mutationWithQueryFn,\n    mutationWithErrorQueryFn,\n    mutationWithThrowingQueryFn,\n    mutationWithAsyncQueryFn,\n    mutationWithAsyncErrorQueryFn,\n    mutationWithAsyncThrowingQueryFn,\n    withNeither,\n    mutationWithNeither,\n  } = api.endpoints\n\n  const store = configureStore({\n    reducer: {\n      [api.reducerPath]: api.reducer,\n    },\n    middleware: (gDM) => gDM({}).concat(api.middleware),\n  })\n\n  test.each([\n    ['withQuery', withQuery, 'data'],\n    ['withErrorQuery', withErrorQuery, 'error'],\n    ['withQueryFn', withQueryFn, 'data'],\n    ['withErrorQueryFn', withErrorQueryFn, 'error'],\n    ['withThrowingQueryFn', withThrowingQueryFn, 'throw'],\n    ['withAsyncQueryFn', withAsyncQueryFn, 'data'],\n    ['withAsyncErrorQueryFn', withAsyncErrorQueryFn, 'error'],\n    ['withAsyncThrowingQueryFn', withAsyncThrowingQueryFn, 'throw'],\n  ])('%s', async (endpointName, endpoint, expectedResult) => {\n    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n\n    const thunk = endpoint.initiate(endpointName)\n\n    const result: undefined | QuerySubState<any> = await store.dispatch(thunk)\n\n    if (endpointName.includes('Throw')) {\n      expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n      expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n        `An unhandled error occurred processing a request for the endpoint \"${endpointName}\".\\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n        Error(`resultFrom(${endpointName})`),\n      )\n    } else {\n      expect(consoleErrorSpy).not.toHaveBeenCalled()\n    }\n\n    if (expectedResult === 'data') {\n      expect(result).toEqual(\n        expect.objectContaining({\n          data: `resultFrom(${endpointName})`,\n        }),\n      )\n    } else if (expectedResult === 'error') {\n      expect(result).toEqual(\n        expect.objectContaining({\n          error: `resultFrom(${endpointName})`,\n        }),\n      )\n    } else {\n      expect(result).toEqual(\n        expect.objectContaining({\n          error: expect.objectContaining({\n            message: `resultFrom(${endpointName})`,\n          }),\n        }),\n      )\n    }\n\n    consoleErrorSpy.mockRestore()\n  })\n\n  test.each([\n    ['mutationWithQueryFn', mutationWithQueryFn, 'data'],\n    ['mutationWithErrorQueryFn', mutationWithErrorQueryFn, 'error'],\n    ['mutationWithThrowingQueryFn', mutationWithThrowingQueryFn, 'throw'],\n    ['mutationWithAsyncQueryFn', mutationWithAsyncQueryFn, 'data'],\n    ['mutationWithAsyncErrorQueryFn', mutationWithAsyncErrorQueryFn, 'error'],\n    [\n      'mutationWithAsyncThrowingQueryFn',\n      mutationWithAsyncThrowingQueryFn,\n      'throw',\n    ],\n  ])('%s', async (endpointName, endpoint, expectedResult) => {\n    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n\n    const thunk = endpoint.initiate(endpointName)\n\n    const result:\n      | undefined\n      | { data: string }\n      | { error: string | SerializedError } = await store.dispatch(thunk)\n\n    if (endpointName.includes('Throw')) {\n      expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n      expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n        `An unhandled error occurred processing a request for the endpoint \"${endpointName}\".\\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n        Error(`resultFrom(${endpointName})`),\n      )\n    } else {\n      expect(consoleErrorSpy).not.toHaveBeenCalled()\n    }\n\n    if (expectedResult === 'data') {\n      expect(result).toEqual(\n        expect.objectContaining({\n          data: `resultFrom(${endpointName})`,\n        }),\n      )\n    } else if (expectedResult === 'error') {\n      expect(result).toEqual(\n        expect.objectContaining({\n          error: `resultFrom(${endpointName})`,\n        }),\n      )\n    } else {\n      expect(result).toEqual(\n        expect.objectContaining({\n          error: expect.objectContaining({\n            message: `resultFrom(${endpointName})`,\n          }),\n        }),\n      )\n    }\n\n    consoleErrorSpy.mockRestore()\n  })\n\n  test('neither provided', async () => {\n    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n\n    {\n      const thunk = withNeither.initiate('withNeither')\n\n      const result: QuerySubState<any> = await store.dispatch(thunk)\n\n      expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n      expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n        `An unhandled error occurred processing a request for the endpoint \"withNeither\".\\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n        TypeError('endpointDefinition.queryFn is not a function'),\n      )\n\n      expect(result.error).toEqual(\n        expect.objectContaining({\n          message: 'endpointDefinition.queryFn is not a function',\n        }),\n      )\n\n      consoleErrorSpy.mockClear()\n    }\n    {\n      const thunk = mutationWithNeither.initiate('mutationWithNeither')\n\n      const result:\n        | undefined\n        | { data: string }\n        | { error: string | SerializedError } = await store.dispatch(thunk)\n\n      expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n      expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n        `An unhandled error occurred processing a request for the endpoint \"mutationWithNeither\".\\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n        TypeError('endpointDefinition.queryFn is not a function'),\n      )\n\n      if (!('error' in result)) {\n        expect.fail()\n      }\n\n      expect(result.error).toEqual(\n        expect.objectContaining({\n          message: 'endpointDefinition.queryFn is not a function',\n        }),\n      )\n    }\n\n    consoleErrorSpy.mockRestore()\n  })\n})\n\ndescribe('usage scenario tests', () => {\n  const mockData = { id: 1, name: 'Banana' }\n  const mockDocResult = {\n    exists: () => true,\n    data: () => mockData,\n  }\n  const get = vi.fn(() => Promise.resolve(mockDocResult))\n  const doc = vi.fn((name) => ({\n    get,\n  }))\n  const collection = vi.fn((name) => ({ get, doc }))\n  const firestore = () => {\n    return { collection, doc }\n  }\n\n  const baseQuery = fetchBaseQuery({ baseUrl: 'https://example.com/' })\n  const api = createApi({\n    baseQuery,\n    endpoints: (build) => ({\n      getRandomUser: build.query<Post, void>({\n        async queryFn(_arg: void, _queryApi, _extraOptions, fetchWithBQ) {\n          // get a random post\n          const randomResult = await fetchWithBQ('posts/random')\n          if (randomResult.error) {\n            throw randomResult.error\n          }\n          const post = randomResult.data as Post\n          const result = await fetchWithBQ(`/post/${post.id}`)\n          return result.data\n            ? { data: result.data as Post }\n            : { error: result.error as FetchBaseQueryError }\n        },\n      }),\n      getFirebaseUser: build.query<typeof mockData, number>({\n        async queryFn(arg: number) {\n          const getResult = await firestore().collection('users').doc(arg).get()\n          if (!getResult.exists()) {\n            throw new Error('Missing user')\n          }\n          return { data: getResult.data() }\n        },\n      }),\n      getMissingFirebaseUser: build.query<typeof mockData, number>({\n        async queryFn(arg: number) {\n          const getResult = await firestore().collection('users').doc(arg).get()\n          // intentionally throw if it exists to keep the mocking overhead low\n          if (getResult.exists()) {\n            throw new Error('Missing user')\n          }\n          return { data: getResult.data() }\n        },\n      }),\n    }),\n  })\n\n  const storeRef = setupApiStore(api, {\n    ...actionsReducer,\n  })\n\n  /**\n   * Allow for a scenario where you can chain X requests\n   * https://discord.com/channels/102860784329052160/103538784460615680/825430959247720449\n   * const resp1 = await api.get(url);\n   * const resp2 = await api.get(`${url2}/id=${resp1.data.id}`);\n   */\n\n  it('can chain multiple queries together', async () => {\n    const result = await storeRef.store.dispatch(\n      api.endpoints.getRandomUser.initiate(),\n    )\n    expect(result.data).toEqual(posts[1])\n  })\n\n  it('can wrap a service like Firebase', async () => {\n    const result = await storeRef.store.dispatch(\n      api.endpoints.getFirebaseUser.initiate(1),\n    )\n    expect(result.data).toEqual(mockData)\n  })\n\n  it('can wrap a service like Firebase and handle errors', async () => {\n    const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n\n    const result: QuerySubState<any> = await storeRef.store.dispatch(\n      api.endpoints.getMissingFirebaseUser.initiate(1),\n    )\n\n    expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n    expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n      `An unhandled error occurred processing a request for the endpoint \"getMissingFirebaseUser\".\\nIn the case of an unhandled error, no tags will be \"provided\" or \"invalidated\".`,\n      Error('Missing user'),\n    )\n\n    expect(result.data).toBeUndefined()\n    expect(result.error).toEqual(\n      expect.objectContaining({\n        message: 'Missing user',\n        name: 'Error',\n      }),\n    )\n\n    consoleErrorSpy.mockRestore()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/queryLifecycle.test-d.tsx",
    "content": "import type { PatchCollection, Recipe } from '@internal/query/core/buildThunks'\nimport type { ThunkDispatch, UnknownAction } from '@reduxjs/toolkit'\nimport type {\n  FetchBaseQueryError,\n  FetchBaseQueryMeta,\n  RootState,\n  TypedMutationOnQueryStarted,\n  TypedQueryOnQueryStarted,\n} from '@reduxjs/toolkit/query'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n  endpoints: () => ({}),\n})\n\ndescribe('type tests', () => {\n  test(`mutation: onStart and onSuccess`, async () => {\n    const extended = api.injectEndpoints({\n      overrideExisting: true,\n      endpoints: (build) => ({\n        injected: build.mutation<number, string>({\n          query: () => '/success',\n          async onQueryStarted(arg, { queryFulfilled }) {\n            // awaiting without catching like this would result in an `unhandledRejection` exception if there was an error\n            // unfortunately we cannot test for that in jest.\n            const result = await queryFulfilled\n\n            expectTypeOf(result).toExtend<{\n              data: number\n              meta?: FetchBaseQueryMeta\n            }>()\n          },\n        }),\n      }),\n    })\n  })\n\n  test('query types', () => {\n    const extended = api.injectEndpoints({\n      overrideExisting: true,\n      endpoints: (build) => ({\n        injected: build.query<number, string>({\n          query: () => '/success',\n          async onQueryStarted(arg, { queryFulfilled }) {\n            queryFulfilled.then(\n              (result) => {\n                expectTypeOf(result).toExtend<{\n                  data: number\n                  meta?: FetchBaseQueryMeta\n                }>()\n              },\n              (reason) => {\n                if (reason.isUnhandledError) {\n                  expectTypeOf(reason).toEqualTypeOf<{\n                    error: unknown\n                    meta?: undefined\n                    isUnhandledError: true\n                  }>()\n                } else {\n                  expectTypeOf(reason).toEqualTypeOf<{\n                    error: FetchBaseQueryError\n                    isUnhandledError: false\n                    meta: FetchBaseQueryMeta | undefined\n                  }>()\n                }\n              },\n            )\n\n            queryFulfilled.catch((reason) => {\n              if (reason.isUnhandledError) {\n                expectTypeOf(reason).toEqualTypeOf<{\n                  error: unknown\n                  meta?: undefined\n                  isUnhandledError: true\n                }>()\n              } else {\n                expectTypeOf(reason).toEqualTypeOf<{\n                  error: FetchBaseQueryError\n                  isUnhandledError: false\n                  meta: FetchBaseQueryMeta | undefined\n                }>()\n              }\n            })\n\n            const result = await queryFulfilled\n\n            expectTypeOf(result).toExtend<{\n              data: number\n              meta?: FetchBaseQueryMeta\n            }>()\n          },\n        }),\n      }),\n    })\n  })\n\n  test('mutation types', () => {\n    const extended = api.injectEndpoints({\n      overrideExisting: true,\n      endpoints: (build) => ({\n        injected: build.query<number, string>({\n          query: () => '/success',\n          async onQueryStarted(arg, { queryFulfilled }) {\n            queryFulfilled.then(\n              (result) => {\n                expectTypeOf(result).toExtend<{\n                  data: number\n                  meta?: FetchBaseQueryMeta\n                }>()\n              },\n              (reason) => {\n                if (reason.isUnhandledError) {\n                  expectTypeOf(reason).toEqualTypeOf<{\n                    error: unknown\n                    meta?: undefined\n                    isUnhandledError: true\n                  }>()\n                } else {\n                  expectTypeOf(reason).toEqualTypeOf<{\n                    error: FetchBaseQueryError\n                    isUnhandledError: false\n                    meta: FetchBaseQueryMeta | undefined\n                  }>()\n                }\n              },\n            )\n\n            queryFulfilled.catch((reason) => {\n              if (reason.isUnhandledError) {\n                expectTypeOf(reason).toEqualTypeOf<{\n                  error: unknown\n                  meta?: undefined\n                  isUnhandledError: true\n                }>()\n              } else {\n                expectTypeOf(reason).toEqualTypeOf<{\n                  error: FetchBaseQueryError\n                  isUnhandledError: false\n                  meta: FetchBaseQueryMeta | undefined\n                }>()\n              }\n            })\n\n            const result = await queryFulfilled\n\n            expectTypeOf(result).toExtend<{\n              data: number\n              meta?: FetchBaseQueryMeta\n            }>()\n          },\n        }),\n      }),\n    })\n  })\n\n  describe('typed `onQueryStarted` function', () => {\n    test('TypedQueryOnQueryStarted creates a pre-typed version of onQueryStarted', () => {\n      type Post = {\n        id: number\n        title: string\n        userId: number\n      }\n\n      type PostsApiResponse = {\n        posts: Post[]\n        total: number\n        skip: number\n        limit: number\n      }\n\n      type QueryArgument = number | undefined\n\n      type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n\n      const baseApiSlice = createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n        reducerPath: 'postsApi',\n        tagTypes: ['Posts'],\n        endpoints: (builder) => ({\n          getPosts: builder.query<PostsApiResponse, void>({\n            query: () => `/posts`,\n          }),\n\n          getPostById: builder.query<Post, QueryArgument>({\n            query: (postId) => `/posts/${postId}`,\n          }),\n        }),\n      })\n\n      const updatePostOnFulfilled: TypedQueryOnQueryStarted<\n        PostsApiResponse,\n        QueryArgument,\n        BaseQueryFunction,\n        'postsApi'\n      > = async (queryArgument, queryLifeCycleApi) => {\n        const {\n          dispatch,\n          extra,\n          getCacheEntry,\n          getState,\n          queryFulfilled,\n          requestId,\n          updateCachedData,\n        } = queryLifeCycleApi\n\n        expectTypeOf(queryArgument).toEqualTypeOf<QueryArgument>()\n\n        expectTypeOf(dispatch).toEqualTypeOf<\n          ThunkDispatch<any, any, UnknownAction>\n        >()\n\n        expectTypeOf(extra).toBeUnknown()\n\n        expectTypeOf(getState).toEqualTypeOf<\n          () => RootState<any, any, 'postsApi'>\n        >()\n\n        expectTypeOf(requestId).toBeString()\n\n        expectTypeOf(getCacheEntry).toBeFunction()\n\n        expectTypeOf(updateCachedData).toEqualTypeOf<\n          (updateRecipe: Recipe<PostsApiResponse>) => PatchCollection\n        >()\n\n        expectTypeOf(queryFulfilled).resolves.toEqualTypeOf<{\n          data: PostsApiResponse\n          meta: FetchBaseQueryMeta | undefined\n        }>()\n\n        const result = await queryFulfilled\n\n        const { posts } = result.data\n\n        dispatch(\n          baseApiSlice.util.upsertQueryEntries(\n            posts.map((post) => ({\n              // Without `as const` this will result in a TS error in TS 4.7.\n              endpointName: 'getPostById' as const,\n              arg: post.id,\n              value: post,\n            })),\n          ),\n        )\n      }\n\n      const extendedApiSlice = baseApiSlice.injectEndpoints({\n        endpoints: (builder) => ({\n          getPostsByUserId: builder.query<PostsApiResponse, QueryArgument>({\n            query: (userId) => `/posts/user/${userId}`,\n\n            onQueryStarted: updatePostOnFulfilled,\n          }),\n        }),\n      })\n    })\n\n    test('TypedMutationOnQueryStarted creates a pre-typed version of onQueryStarted', () => {\n      type Post = {\n        id: number\n        title: string\n        userId: number\n      }\n\n      type PostsApiResponse = {\n        posts: Post[]\n        total: number\n        skip: number\n        limit: number\n      }\n\n      type QueryArgument = Pick<Post, 'id'> & Partial<Post>\n\n      type BaseQueryFunction = ReturnType<typeof fetchBaseQuery>\n\n      const baseApiSlice = createApi({\n        baseQuery: fetchBaseQuery({ baseUrl: 'https://dummyjson.com' }),\n        reducerPath: 'postsApi',\n        tagTypes: ['Posts'],\n        endpoints: (builder) => ({\n          getPosts: builder.query<PostsApiResponse, void>({\n            query: () => `/posts`,\n          }),\n\n          getPostById: builder.query<Post, number>({\n            query: (postId) => `/posts/${postId}`,\n          }),\n        }),\n      })\n\n      const updatePostOnFulfilled: TypedMutationOnQueryStarted<\n        Post,\n        QueryArgument,\n        BaseQueryFunction,\n        'postsApi'\n      > = async (queryArgument, mutationLifeCycleApi) => {\n        const { id, ...patch } = queryArgument\n        const {\n          dispatch,\n          extra,\n          getCacheEntry,\n          getState,\n          queryFulfilled,\n          requestId,\n        } = mutationLifeCycleApi\n\n        const patchCollection = dispatch(\n          baseApiSlice.util.updateQueryData('getPostById', id, (draftPost) => {\n            Object.assign(draftPost, patch)\n          }),\n        )\n\n        expectTypeOf(queryFulfilled).resolves.toEqualTypeOf<{\n          data: Post\n          meta: FetchBaseQueryMeta | undefined\n        }>()\n\n        expectTypeOf(queryArgument).toEqualTypeOf<QueryArgument>()\n\n        expectTypeOf(dispatch).toEqualTypeOf<\n          ThunkDispatch<any, any, UnknownAction>\n        >()\n\n        expectTypeOf(extra).toBeUnknown()\n\n        expectTypeOf(getState).toEqualTypeOf<\n          () => RootState<any, any, 'postsApi'>\n        >()\n\n        expectTypeOf(requestId).toBeString()\n\n        expectTypeOf(getCacheEntry).toBeFunction()\n\n        expectTypeOf(mutationLifeCycleApi).not.toHaveProperty(\n          'updateCachedData',\n        )\n\n        try {\n          await queryFulfilled\n        } catch {\n          patchCollection.undo()\n        }\n      }\n\n      const extendedApiSlice = baseApiSlice.injectEndpoints({\n        endpoints: (builder) => ({\n          addPost: builder.mutation<Post, Omit<QueryArgument, 'id'>>({\n            query: (body) => ({\n              url: `posts/add`,\n              method: 'POST',\n              body,\n            }),\n\n            onQueryStarted: updatePostOnFulfilled,\n          }),\n\n          updatePost: builder.mutation<Post, QueryArgument>({\n            query: ({ id, ...patch }) => ({\n              url: `post/${id}`,\n              method: 'PATCH',\n              body: patch,\n            }),\n\n            onQueryStarted: updatePostOnFulfilled,\n          }),\n        }),\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/queryLifecycle.test.tsx",
    "content": "import { server } from '@internal/query/tests/mocks/server'\nimport { setupApiStore } from '@internal/tests/utils/helpers'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\nimport { waitFor } from '@testing-library/react'\nimport { HttpResponse, http } from 'msw'\nimport { vi } from 'vitest'\n\nconst api = createApi({\n  baseQuery: fetchBaseQuery({ baseUrl: 'https://example.com' }),\n  endpoints: () => ({}),\n})\nconst storeRef = setupApiStore(api)\n\nconst onStart = vi.fn()\nconst onSuccess = vi.fn()\nconst onError = vi.fn()\n\nbeforeEach(() => {\n  onStart.mockClear()\n  onSuccess.mockClear()\n  onError.mockClear()\n})\n\ndescribe.each([['query'], ['mutation']] as const)(\n  'generic cases: %s',\n  (type) => {\n    test(`${type}: onStart only`, async () => {\n      const extended = api.injectEndpoints({\n        overrideExisting: true,\n        endpoints: (build) => ({\n          injected: build[type as 'mutation']<unknown, string>({\n            query: () => '/success',\n            onQueryStarted(arg) {\n              onStart(arg)\n            },\n          }),\n        }),\n      })\n      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))\n      expect(onStart).toHaveBeenCalledWith('arg')\n    })\n\n    test(`${type}: onStart and onSuccess`, async () => {\n      const extended = api.injectEndpoints({\n        overrideExisting: true,\n        endpoints: (build) => ({\n          injected: build[type as 'mutation']<number, string>({\n            query: () => '/success',\n            async onQueryStarted(arg, { queryFulfilled }) {\n              onStart(arg)\n              // awaiting without catching like this would result in an `unhandledRejection` exception if there was an error\n              // unfortunately we cannot test for that in jest.\n              const result = await queryFulfilled\n              onSuccess(result)\n            },\n          }),\n        }),\n      })\n      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))\n      expect(onStart).toHaveBeenCalledWith('arg')\n      await waitFor(() => {\n        expect(onSuccess).toHaveBeenCalledWith({\n          data: { value: 'success' },\n          meta: {\n            request: expect.any(Request),\n            response: expect.any(Object), // Response is not available in jest env\n          },\n        })\n      })\n    })\n\n    test(`${type}: onStart and onError`, async () => {\n      const extended = api.injectEndpoints({\n        overrideExisting: true,\n        endpoints: (build) => ({\n          injected: build[type as 'mutation']<unknown, string>({\n            query: () => '/error',\n            async onQueryStarted(arg, { queryFulfilled }) {\n              onStart(arg)\n              try {\n                const result = await queryFulfilled\n                onSuccess(result)\n              } catch (e) {\n                onError(e)\n              }\n            },\n          }),\n        }),\n      })\n      storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))\n      expect(onStart).toHaveBeenCalledWith('arg')\n      await waitFor(() => {\n        expect(onError).toHaveBeenCalledWith({\n          error: {\n            status: 500,\n            data: { value: 'error' },\n          },\n          isUnhandledError: false,\n          meta: {\n            request: expect.any(Request),\n            response: expect.any(Object), // Response is not available in jest env\n          },\n        })\n      })\n      expect(onSuccess).not.toHaveBeenCalled()\n    })\n  },\n)\n\ntest('query: getCacheEntry (success)', async () => {\n  const snapshot = vi.fn()\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.query<unknown, string>({\n        query: () => '/success',\n        async onQueryStarted(\n          arg,\n          { dispatch, getState, getCacheEntry, queryFulfilled },\n        ) {\n          try {\n            snapshot(getCacheEntry())\n            const result = await queryFulfilled\n            onSuccess(result)\n            snapshot(getCacheEntry())\n          } catch (e) {\n            onError(e)\n            snapshot(getCacheEntry())\n          }\n        },\n      }),\n    }),\n  })\n  const promise = storeRef.store.dispatch(\n    extended.endpoints.injected.initiate('arg'),\n  )\n\n  await waitFor(() => {\n    expect(onSuccess).toHaveBeenCalled()\n  })\n\n  expect(snapshot).toHaveBeenCalledTimes(2)\n  expect(snapshot.mock.calls[0][0]).toMatchObject({\n    endpointName: 'injected',\n    isError: false,\n    isLoading: true,\n    isSuccess: false,\n    isUninitialized: false,\n    originalArgs: 'arg',\n    requestId: promise.requestId,\n    startedTimeStamp: expect.any(Number),\n    status: 'pending',\n  })\n  expect(snapshot.mock.calls[1][0]).toMatchObject({\n    data: {\n      value: 'success',\n    },\n    endpointName: 'injected',\n    fulfilledTimeStamp: expect.any(Number),\n    isError: false,\n    isLoading: false,\n    isSuccess: true,\n    isUninitialized: false,\n    originalArgs: 'arg',\n    requestId: promise.requestId,\n    startedTimeStamp: expect.any(Number),\n    status: 'fulfilled',\n  })\n})\n\ntest('query: getCacheEntry (error)', async () => {\n  const snapshot = vi.fn()\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.query<unknown, string>({\n        query: () => '/error',\n        async onQueryStarted(\n          arg,\n          { dispatch, getState, getCacheEntry, queryFulfilled },\n        ) {\n          try {\n            snapshot(getCacheEntry())\n            const result = await queryFulfilled\n            onSuccess(result)\n            snapshot(getCacheEntry())\n          } catch (e) {\n            onError(e)\n            snapshot(getCacheEntry())\n          }\n        },\n      }),\n    }),\n  })\n  const promise = storeRef.store.dispatch(\n    extended.endpoints.injected.initiate('arg'),\n  )\n\n  await waitFor(() => {\n    expect(onError).toHaveBeenCalled()\n  })\n\n  expect(snapshot.mock.calls[0][0]).toMatchObject({\n    endpointName: 'injected',\n    isError: false,\n    isLoading: true,\n    isSuccess: false,\n    isUninitialized: false,\n    originalArgs: 'arg',\n    requestId: promise.requestId,\n    startedTimeStamp: expect.any(Number),\n    status: 'pending',\n  })\n  expect(snapshot.mock.calls[1][0]).toMatchObject({\n    error: {\n      data: { value: 'error' },\n      status: 500,\n    },\n    endpointName: 'injected',\n    isError: true,\n    isLoading: false,\n    isSuccess: false,\n    isUninitialized: false,\n    originalArgs: 'arg',\n    requestId: promise.requestId,\n    startedTimeStamp: expect.any(Number),\n    status: 'rejected',\n  })\n})\n\ntest('mutation: getCacheEntry (success)', async () => {\n  const snapshot = vi.fn()\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.mutation<unknown, string>({\n        query: () => '/success',\n        async onQueryStarted(\n          arg,\n          { dispatch, getState, getCacheEntry, queryFulfilled },\n        ) {\n          try {\n            snapshot(getCacheEntry())\n            const result = await queryFulfilled\n            onSuccess(result)\n            snapshot(getCacheEntry())\n          } catch (e) {\n            onError(e)\n            snapshot(getCacheEntry())\n          }\n        },\n      }),\n    }),\n  })\n  const promise = storeRef.store.dispatch(\n    extended.endpoints.injected.initiate('arg'),\n  )\n\n  await waitFor(() => {\n    expect(onSuccess).toHaveBeenCalled()\n  })\n\n  expect(snapshot).toHaveBeenCalledTimes(2)\n  expect(snapshot.mock.calls[0][0]).toMatchObject({\n    endpointName: 'injected',\n    isError: false,\n    isLoading: true,\n    isSuccess: false,\n    isUninitialized: false,\n    startedTimeStamp: expect.any(Number),\n    status: 'pending',\n  })\n  expect(snapshot.mock.calls[1][0]).toMatchObject({\n    data: {\n      value: 'success',\n    },\n    endpointName: 'injected',\n    fulfilledTimeStamp: expect.any(Number),\n    isError: false,\n    isLoading: false,\n    isSuccess: true,\n    isUninitialized: false,\n    startedTimeStamp: expect.any(Number),\n    status: 'fulfilled',\n  })\n})\n\ntest('mutation: getCacheEntry (error)', async () => {\n  const snapshot = vi.fn()\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.mutation<unknown, string>({\n        query: () => '/error',\n        async onQueryStarted(\n          arg,\n          { dispatch, getState, getCacheEntry, queryFulfilled },\n        ) {\n          try {\n            snapshot(getCacheEntry())\n            const result = await queryFulfilled\n            onSuccess(result)\n            snapshot(getCacheEntry())\n          } catch (e) {\n            onError(e)\n            snapshot(getCacheEntry())\n          }\n        },\n      }),\n    }),\n  })\n  const promise = storeRef.store.dispatch(\n    extended.endpoints.injected.initiate('arg'),\n  )\n\n  await waitFor(() => {\n    expect(onError).toHaveBeenCalled()\n  })\n\n  expect(snapshot.mock.calls[0][0]).toMatchObject({\n    endpointName: 'injected',\n    isError: false,\n    isLoading: true,\n    isSuccess: false,\n    isUninitialized: false,\n    startedTimeStamp: expect.any(Number),\n    status: 'pending',\n  })\n  expect(snapshot.mock.calls[1][0]).toMatchObject({\n    error: {\n      data: { value: 'error' },\n      status: 500,\n    },\n    endpointName: 'injected',\n    isError: true,\n    isLoading: false,\n    isSuccess: false,\n    isUninitialized: false,\n    startedTimeStamp: expect.any(Number),\n    status: 'rejected',\n  })\n})\n\ntest('query: updateCachedData', async () => {\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.query<{ value: string }, string>({\n        query: () => '/success',\n        async onQueryStarted(\n          arg,\n          {\n            dispatch,\n            getState,\n            getCacheEntry,\n            updateCachedData,\n            queryFulfilled,\n          },\n        ) {\n          // calling `updateCachedData` when there is no data yet should not do anything\n          // but if there is a cache value it will be updated & overwritten by the next successful result\n          updateCachedData((draft) => {\n            draft.value += '.'\n          })\n\n          try {\n            await queryFulfilled\n            onSuccess(getCacheEntry().data)\n          } catch (error) {\n            updateCachedData((draft) => {\n              draft.value += 'x'\n            })\n            onError(getCacheEntry().data)\n          }\n        },\n      }),\n    }),\n  })\n\n  // request 1: success\n  expect(onSuccess).not.toHaveBeenCalled()\n  storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))\n\n  await waitFor(() => {\n    expect(onSuccess).toHaveBeenCalled()\n  })\n  expect(onSuccess).toHaveBeenCalledWith({ value: 'success' })\n  onSuccess.mockClear()\n\n  // request 2: error\n  expect(onError).not.toHaveBeenCalled()\n  server.use(\n    http.get(\n      'https://example.com/success',\n      () => {\n        return HttpResponse.json({ value: 'failed' }, { status: 500 })\n      },\n      { once: true },\n    ),\n  )\n  storeRef.store.dispatch(\n    extended.endpoints.injected.initiate('arg', { forceRefetch: true }),\n  )\n\n  await waitFor(() => {\n    expect(onError).toHaveBeenCalled()\n  })\n  expect(onError).toHaveBeenCalledWith({ value: 'success.x' })\n\n  // request 3: success\n  expect(onSuccess).not.toHaveBeenCalled()\n\n  storeRef.store.dispatch(\n    extended.endpoints.injected.initiate('arg', { forceRefetch: true }),\n  )\n\n  await waitFor(() => {\n    expect(onSuccess).toHaveBeenCalled()\n  })\n  expect(onSuccess).toHaveBeenCalledWith({ value: 'success' })\n  onSuccess.mockClear()\n})\n\ntest('infinite query: updateCachedData', async () => {\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      infiniteInjected: build.infiniteQuery<{ value: string }, string, number>({\n        query: () => '/success',\n        infiniteQueryOptions: {\n          initialPageParam: 1,\n          getNextPageParam: (\n            lastPage,\n            allPages,\n            lastPageParam,\n            allPageParams,\n          ) => lastPageParam + 1,\n        },\n        async onQueryStarted(\n          arg,\n          {\n            dispatch,\n            getState,\n            getCacheEntry,\n            updateCachedData,\n            queryFulfilled,\n          },\n        ) {\n          // calling `updateCachedData` when there is no data yet should not do anything\n          // but if there is a cache value it will be updated & overwritten by the next successful result\n          updateCachedData((draft) => {\n            draft.pages = [{ value: '.' }]\n            draft.pageParams = [1]\n          })\n\n          try {\n            await queryFulfilled\n            onSuccess(getCacheEntry().data)\n          } catch (error) {\n            updateCachedData((draft) => {\n              draft.pages = [{ value: 'success.x' }]\n              draft.pageParams = [1]\n            })\n            onError(getCacheEntry().data)\n          }\n        },\n      }),\n    }),\n  })\n\n  // request 1: success\n  expect(onSuccess).not.toHaveBeenCalled()\n  storeRef.store.dispatch(extended.endpoints.infiniteInjected.initiate('arg'))\n\n  await waitFor(() => {\n    expect(onSuccess).toHaveBeenCalled()\n  })\n  expect(onSuccess).toHaveBeenCalledWith({\n    pages: [{ value: 'success' }],\n    pageParams: [1],\n  })\n  onSuccess.mockClear()\n\n  // request 2: error\n  expect(onError).not.toHaveBeenCalled()\n  server.use(\n    http.get(\n      'https://example.com/success',\n      () => {\n        return HttpResponse.json({ value: 'failed' }, { status: 500 })\n      },\n      { once: true },\n    ),\n  )\n  storeRef.store.dispatch(\n    extended.endpoints.infiniteInjected.initiate('arg', { forceRefetch: true }),\n  )\n\n  await waitFor(() => {\n    expect(onError).toHaveBeenCalled()\n  })\n  expect(onError).toHaveBeenCalledWith({\n    pages: [{ value: 'success.x' }],\n    pageParams: [1],\n  })\n\n  // request 3: success\n  expect(onSuccess).not.toHaveBeenCalled()\n\n  storeRef.store.dispatch(\n    extended.endpoints.infiniteInjected.initiate('arg', { forceRefetch: true }),\n  )\n\n  await waitFor(() => {\n    expect(onSuccess).toHaveBeenCalled()\n  })\n  expect(onSuccess).toHaveBeenCalledWith({\n    pages: [{ value: 'success' }],\n    pageParams: [1],\n  })\n  onSuccess.mockClear()\n})\n\ntest('query: will only start lifecycle if query is not skipped due to `condition`', async () => {\n  const extended = api.injectEndpoints({\n    overrideExisting: true,\n    endpoints: (build) => ({\n      injected: build.query<unknown, string>({\n        query: () => '/success',\n        onQueryStarted(arg) {\n          onStart(arg)\n        },\n      }),\n    }),\n  })\n  const promise = storeRef.store.dispatch(\n    extended.endpoints.injected.initiate('arg'),\n  )\n  expect(onStart).toHaveBeenCalledOnce()\n  storeRef.store.dispatch(extended.endpoints.injected.initiate('arg'))\n  expect(onStart).toHaveBeenCalledOnce()\n  await promise\n  storeRef.store.dispatch(\n    extended.endpoints.injected.initiate('arg', { forceRefetch: true }),\n  )\n  expect(onStart).toHaveBeenCalledTimes(2)\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/raceConditions.test.ts",
    "content": "import { createApi, QueryStatus } from '@reduxjs/toolkit/query'\nimport { delay } from 'msw'\nimport { actionsReducer, setupApiStore } from '../../tests/utils/helpers'\n\n// We need to be able to control when which query resolves to simulate race\n// conditions properly, that's the purpose of this factory.\nconst createPromiseFactory = () => {\n  const resolveQueue: (() => void)[] = []\n  const createPromise = () =>\n    new Promise<void>((resolve) => {\n      resolveQueue.push(resolve)\n    })\n  const resolveOldest = () => {\n    resolveQueue.shift()?.()\n  }\n  return { createPromise, resolveOldest }\n}\n\nconst getEatenBananaPromises = createPromiseFactory()\nconst eatBananaPromises = createPromiseFactory()\n\nlet eatenBananas = 0\nconst api = createApi({\n  invalidationBehavior: 'delayed',\n  baseQuery: () => undefined as any,\n  tagTypes: ['Banana'],\n  endpoints: (build) => ({\n    // Eat a banana.\n    eatBanana: build.mutation<unknown, void>({\n      queryFn: async () => {\n        await eatBananaPromises.createPromise()\n        eatenBananas += 1\n        return { data: null, meta: {} }\n      },\n      invalidatesTags: ['Banana'],\n    }),\n\n    // Get the number of eaten bananas.\n    getEatenBananas: build.query<number, void>({\n      queryFn: async (arg, arg1, arg2, arg3) => {\n        const result = eatenBananas\n        await getEatenBananaPromises.createPromise()\n        return { data: result }\n      },\n      providesTags: ['Banana'],\n    }),\n  }),\n})\nconst { getEatenBananas, eatBanana } = api.endpoints\n\nconst storeRef = setupApiStore(api, {\n  ...actionsReducer,\n})\n\nit('invalidates a query after a corresponding mutation', async () => {\n  eatenBananas = 0\n\n  const query = storeRef.store.dispatch(getEatenBananas.initiate())\n  const getQueryState = () =>\n    storeRef.store.getState().api.queries[query.queryCacheKey]\n  getEatenBananaPromises.resolveOldest()\n  await delay(2)\n\n  expect(getQueryState()?.data).toBe(0)\n  expect(getQueryState()?.status).toBe(QueryStatus.fulfilled)\n\n  const mutation = storeRef.store.dispatch(eatBanana.initiate())\n  const getMutationState = () =>\n    storeRef.store.getState().api.mutations[mutation.requestId]\n  eatBananaPromises.resolveOldest()\n  await delay(2)\n\n  expect(getMutationState()?.status).toBe(QueryStatus.fulfilled)\n  expect(getQueryState()?.data).toBe(0)\n  expect(getQueryState()?.status).toBe(QueryStatus.pending)\n\n  getEatenBananaPromises.resolveOldest()\n  await delay(2)\n\n  expect(getQueryState()?.data).toBe(1)\n  expect(getQueryState()?.status).toBe(QueryStatus.fulfilled)\n})\n\nit('invalidates a query whose corresponding mutation finished while the query was in flight', async () => {\n  eatenBananas = 0\n\n  const query = storeRef.store.dispatch(getEatenBananas.initiate())\n  const getQueryState = () =>\n    storeRef.store.getState().api.queries[query.queryCacheKey]\n\n  const mutation = storeRef.store.dispatch(eatBanana.initiate())\n  const getMutationState = () =>\n    storeRef.store.getState().api.mutations[mutation.requestId]\n  eatBananaPromises.resolveOldest()\n  await delay(2)\n  expect(getMutationState()?.status).toBe(QueryStatus.fulfilled)\n\n  getEatenBananaPromises.resolveOldest()\n  await delay(2)\n  expect(getQueryState()?.data).toBe(0)\n  expect(getQueryState()?.status).toBe(QueryStatus.pending)\n\n  // should already be refetching\n  getEatenBananaPromises.resolveOldest()\n  await delay(2)\n\n  expect(getQueryState()?.status).toBe(QueryStatus.fulfilled)\n  expect(getQueryState()?.data).toBe(1)\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/refetchingBehaviors.test.tsx",
    "content": "import { createApi, setupListeners } from '@reduxjs/toolkit/query/react'\nimport { act, fireEvent, render, screen, waitFor } from '@testing-library/react'\nimport { delay } from 'msw'\nimport { setupApiStore } from '../../tests/utils/helpers'\n\n// Just setup a temporary in-memory counter for tests that `getIncrementedAmount`.\n// This can be used to test how many renders happen due to data changes or\n// the refetching behavior of components.\nlet amount = 0\n\nconst defaultApi = createApi({\n  baseQuery: async (arg: any) => {\n    await delay(150)\n    if ('amount' in arg?.body) {\n      amount += 1\n    }\n    return {\n      data: arg?.body\n        ? { ...arg.body, ...(amount ? { amount } : {}) }\n        : undefined,\n    }\n  },\n  endpoints: (build) => ({\n    getIncrementedAmount: build.query<any, void>({\n      query: () => ({\n        url: '',\n        body: {\n          amount,\n        },\n      }),\n    }),\n  }),\n  refetchOnFocus: true,\n  refetchOnReconnect: true,\n})\n\nconst storeRef = setupApiStore(defaultApi)\n\nconst getIncrementedAmountState = () =>\n  storeRef.store.getState().api.queries['getIncrementedAmount(undefined)']\n\nafterEach(() => {\n  amount = 0\n})\n\ndescribe('refetchOnFocus tests', () => {\n  test('useQuery hook respects refetchOnFocus: true when set in createApi options', async () => {\n    let data, isLoading, isFetching\n\n    function User() {\n      ;({ data, isFetching, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery())\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    render(<User />, { wrapper: storeRef.wrapper })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n\n    fireEvent.focus(window)\n\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('2'),\n    )\n  })\n\n  test('useQuery hook respects refetchOnFocus: false from a hook and overrides createApi defaults', async () => {\n    let data, isLoading, isFetching\n\n    function User() {\n      ;({ data, isFetching, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {\n          refetchOnFocus: false,\n        }))\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    render(<User />, { wrapper: storeRef.wrapper })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n\n    fireEvent.focus(window)\n\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n  })\n\n  test('useQuery hook prefers refetchOnFocus: true when multiple components have different configurations', async () => {\n    let data, isLoading, isFetching\n\n    function User() {\n      ;({ data, isFetching, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {\n          refetchOnFocus: false,\n        }))\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    function UserWithRefetchTrue() {\n      ;({ data, isFetching, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {\n          refetchOnFocus: true,\n        }))\n      return <div />\n    }\n\n    render(\n      <div>\n        <User />\n        <UserWithRefetchTrue />\n      </div>,\n      { wrapper: storeRef.wrapper },\n    )\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n\n    fireEvent.focus(window)\n    expect(screen.getByTestId('isLoading').textContent).toBe('false')\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('2'),\n    )\n  })\n\n  test('useQuery hook cleans data if refetch without active subscribers', async () => {\n    let data, isLoading, isFetching\n\n    function User() {\n      ;({ data, isFetching, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {\n          refetchOnFocus: true,\n        }))\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    const { unmount } = render(<User />, { wrapper: storeRef.wrapper })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n\n    unmount()\n\n    expect(getIncrementedAmountState()).not.toBeUndefined()\n\n    fireEvent.focus(window)\n\n    await delay(1)\n    expect(getIncrementedAmountState()).toBeUndefined()\n  })\n})\n\ndescribe('refetchOnReconnect tests', () => {\n  test('useQuery hook respects refetchOnReconnect: true when set in createApi options', async () => {\n    let data, isLoading, isFetching\n\n    function User() {\n      ;({ data, isFetching, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery())\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    render(<User />, { wrapper: storeRef.wrapper })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n\n    act(() => {\n      window.dispatchEvent(new Event('offline'))\n      window.dispatchEvent(new Event('online'))\n    })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('2'),\n    )\n  })\n\n  test('useQuery hook should not refetch when refetchOnReconnect: false from a hook and overrides createApi defaults', async () => {\n    let data, isLoading, isFetching\n\n    function User() {\n      ;({ data, isFetching, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {\n          refetchOnReconnect: false,\n        }))\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    render(<User />, { wrapper: storeRef.wrapper })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n\n    act(() => {\n      window.dispatchEvent(new Event('offline'))\n      window.dispatchEvent(new Event('online'))\n    })\n    expect(screen.getByTestId('isFetching').textContent).toBe('false')\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n  })\n\n  test('useQuery hook prefers refetchOnReconnect: true when multiple components have different configurations', async () => {\n    let data, isLoading, isFetching\n\n    function User() {\n      ;({ data, isFetching, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {\n          refetchOnReconnect: false,\n        }))\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    function UserWithRefetchTrue() {\n      ;({ data, isFetching, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {\n          refetchOnReconnect: true,\n        }))\n      return <div />\n    }\n\n    render(\n      <div>\n        <User />\n        <UserWithRefetchTrue />\n      </div>,\n      { wrapper: storeRef.wrapper },\n    )\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n\n    act(() => {\n      window.dispatchEvent(new Event('offline'))\n      window.dispatchEvent(new Event('online'))\n    })\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('2'),\n    )\n  })\n})\n\ndescribe('customListenersHandler', () => {\n  const storeRef = setupApiStore(defaultApi, undefined, {\n    withoutListeners: true,\n  })\n\n  test('setupListeners accepts a custom callback and executes it', async () => {\n    const consoleSpy = vi.spyOn(console, 'log')\n    consoleSpy.mockImplementation((...args: any[]) => {\n      // console.info(...args)\n    })\n    const dispatchSpy = vi.spyOn(storeRef.store, 'dispatch')\n\n    let unsubscribe = () => {}\n    unsubscribe = setupListeners(\n      storeRef.store.dispatch,\n      (dispatch, actions) => {\n        const handleOnline = () =>\n          dispatch(defaultApi.internalActions.onOnline())\n        window.addEventListener('online', handleOnline, false)\n        console.log('setup!')\n        return () => {\n          window.removeEventListener('online', handleOnline)\n          console.log('cleanup!')\n        }\n      },\n    )\n\n    await delay(150)\n\n    let data, isLoading, isFetching\n\n    function User() {\n      ;({ data, isFetching, isLoading } =\n        defaultApi.endpoints.getIncrementedAmount.useQuery(undefined, {\n          refetchOnReconnect: true,\n        }))\n      return (\n        <div>\n          <div data-testid=\"isLoading\">{String(isLoading)}</div>\n          <div data-testid=\"isFetching\">{String(isFetching)}</div>\n          <div data-testid=\"amount\">{String(data?.amount)}</div>\n        </div>\n      )\n    }\n\n    render(<User />, { wrapper: storeRef.wrapper })\n\n    expect(consoleSpy).toHaveBeenCalledWith('setup!')\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isLoading').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('1'),\n    )\n\n    act(() => {\n      window.dispatchEvent(new Event('offline'))\n      window.dispatchEvent(new Event('online'))\n    })\n    expect(dispatchSpy).toHaveBeenCalled()\n\n    // Ignore RTKQ middleware internal data calls\n    const mockCallsWithoutInternals = dispatchSpy.mock.calls.filter((call) => {\n      const type = (call[0] as any)?.type ?? ''\n      const reIsInternal = /internal/i\n      return !reIsInternal.test(type)\n    })\n\n    expect(\n      defaultApi.internalActions.onOnline.match(\n        mockCallsWithoutInternals[1][0] as any,\n      ),\n    ).toBe(true)\n\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('true'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('isFetching').textContent).toBe('false'),\n    )\n    await waitFor(() =>\n      expect(screen.getByTestId('amount').textContent).toBe('2'),\n    )\n\n    unsubscribe()\n    expect(consoleSpy).toHaveBeenCalledWith('cleanup!')\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/retry.test-d.ts",
    "content": "import type {\n  FetchBaseQueryError,\n  FetchBaseQueryMeta,\n  RetryOptions,\n} from '@reduxjs/toolkit/query'\nimport { fetchBaseQuery, retry } from '@reduxjs/toolkit/query'\n\ndescribe('type tests', () => {\n  test('RetryOptions only accepts one of maxRetries or retryCondition', () => {\n    // Should not complain if only `maxRetries` exists\n    expectTypeOf({ maxRetries: 5 }).toExtend<RetryOptions>()\n\n    // Should not complain if only `retryCondition` exists\n    expectTypeOf({ retryCondition: () => false }).toExtend<RetryOptions>()\n\n    // Should complain if both `maxRetries` and `retryCondition` exist at once\n    expectTypeOf({\n      maxRetries: 5,\n      retryCondition: () => false,\n    }).not.toExtend<RetryOptions>()\n  })\n  test('fail can be pretyped to only accept correct error and meta', () => {\n    expectTypeOf(retry.fail).parameter(0).toBeUnknown()\n    expectTypeOf(retry.fail).parameter(1).toEqualTypeOf<{} | undefined>()\n    expectTypeOf(retry.fail).toBeCallableWith('Literally anything', {})\n\n    const myBaseQuery = fetchBaseQuery()\n    const typedFail = retry.fail<typeof myBaseQuery>\n\n    expectTypeOf(typedFail).parameter(0).toExtend<FetchBaseQueryError>()\n    expectTypeOf(typedFail)\n      .parameter(1)\n      .toExtend<FetchBaseQueryMeta | undefined>()\n\n    expectTypeOf(typedFail).toBeCallableWith(\n      {\n        status: 401,\n        data: 'Unauthorized',\n      },\n      { request: new Request('http://localhost') },\n    )\n\n    expectTypeOf(typedFail).parameter(0).not.toBeString()\n    expectTypeOf(typedFail).parameter(1).not.toExtend<{}>()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/retry.test.ts",
    "content": "import type { BaseQueryFn, FetchBaseQueryError } from '@reduxjs/toolkit/query'\nimport { createApi, retry } from '@reduxjs/toolkit/query'\nimport { setupApiStore } from '../../tests/utils/helpers'\n\nbeforeEach(() => {\n  vi.useFakeTimers()\n})\n\nconst loopTimers = async (max: number = 12) => {\n  let count = 0\n  while (count < max) {\n    await vi.advanceTimersByTimeAsync(1)\n    vi.advanceTimersByTime(120_000)\n    count++\n  }\n}\n\ndescribe('configuration', () => {\n  test('retrying without any config options', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery.mockResolvedValue({ error: 'rejected' })\n\n    const baseQuery = retry(baseBaseQuery)\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers(7)\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(6)\n  })\n\n  test('retrying with baseQuery config that overrides default behavior (maxRetries: 5)', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery.mockResolvedValue({ error: 'rejected' })\n\n    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers(5)\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(4)\n  })\n\n  test('retrying with endpoint config that overrides baseQuery config', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery.mockResolvedValue({ error: 'rejected' })\n\n    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n        q2: build.query({\n          query: () => {},\n          extraOptions: { maxRetries: 8 },\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n    await loopTimers(5)\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(4)\n\n    baseBaseQuery.mockClear()\n\n    storeRef.store.dispatch(api.endpoints.q2.initiate({}))\n\n    await loopTimers(10)\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(9)\n  })\n\n  test('stops retrying a query after a success', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery\n      .mockResolvedValueOnce({ error: 'rejected' })\n      .mockResolvedValueOnce({ error: 'rejected' })\n      .mockResolvedValue({ data: { success: true } })\n\n    const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.mutation({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers(6)\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(3)\n  })\n\n  test('retrying also works with mutations', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery.mockResolvedValue({ error: 'rejected' })\n\n    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        m1: build.mutation({\n          query: () => ({ method: 'PUT' }),\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    storeRef.store.dispatch(api.endpoints.m1.initiate({}))\n\n    await loopTimers(5)\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(4)\n  })\n\n  test('retrying stops after a success from a mutation', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery\n      .mockRejectedValueOnce(new Error('rejected'))\n      .mockRejectedValueOnce(new Error('rejected'))\n      .mockResolvedValue({ data: { success: true } })\n\n    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        m1: build.mutation({\n          query: () => ({ method: 'PUT' }),\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    storeRef.store.dispatch(api.endpoints.m1.initiate({}))\n\n    await loopTimers(5)\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(3)\n  })\n  test('non-error-cases should **not** retry', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery.mockResolvedValue({ data: { success: true } })\n\n    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers(2)\n\n    expect(baseBaseQuery).toHaveBeenCalledOnce()\n  })\n  test('calling retry.fail(error) will skip retrying and expose the error directly', async () => {\n    const error = { message: 'banana' }\n\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery.mockImplementation((input) => {\n      retry.fail(error)\n      return { data: `this won't happen` }\n    })\n\n    const baseQuery = retry(baseBaseQuery)\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    const result = await storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers(2)\n\n    expect(baseBaseQuery).toHaveBeenCalledOnce()\n    expect(result.error).toEqual(error)\n    expect(result).toEqual({\n      endpointName: 'q1',\n      error,\n      isError: true,\n      isLoading: false,\n      isSuccess: false,\n      isUninitialized: false,\n      originalArgs: expect.any(Object),\n      requestId: expect.any(String),\n      startedTimeStamp: expect.any(Number),\n      status: 'rejected',\n    })\n  })\n\n  test('wrapping retry(retry(..., { maxRetries: 3 }), { maxRetries: 3 }) should retry 16 times', async () => {\n    /**\n     * Note:\n     * This will retry 16 total times because we try the initial + 3 retries (sum: 4), then retry that process 3 times (starting at 0 for a total of 4)... 4x4=16 (allegedly)\n     */\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery.mockResolvedValue({ error: 'rejected' })\n\n    const baseQuery = retry(retry(baseBaseQuery, { maxRetries: 3 }), {\n      maxRetries: 3,\n    })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers(18)\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(16)\n  })\n\n  test('accepts a custom backoff fn', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery.mockResolvedValue({ error: 'rejected' })\n\n    const baseQuery = retry(baseBaseQuery, {\n      maxRetries: 8,\n      backoff: async (attempt, maxRetries) => {\n        const attempts = Math.min(attempt, maxRetries)\n        const timeout = attempts * 300 // Scale up by 300ms per request, ex: 300ms, 600ms, 900ms, 1200ms...\n        await new Promise((resolve) =>\n          setTimeout((res: any) => resolve(res), timeout),\n        )\n      },\n    })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers()\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(9)\n  })\n\n  test('accepts a custom retryCondition fn', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery.mockResolvedValue({ error: 'rejected' })\n\n    const overrideMaxRetries = 3\n\n    const baseQuery = retry(baseBaseQuery, {\n      retryCondition: (_, __, { attempt }) => attempt <= overrideMaxRetries,\n    })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers()\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(overrideMaxRetries + 1)\n  })\n\n  test('retryCondition with endpoint config that overrides baseQuery config', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery.mockResolvedValue({ error: 'rejected' })\n\n    const baseQuery = retry(baseBaseQuery, {\n      maxRetries: 10,\n    })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n          extraOptions: {\n            retryCondition: (_, __, { attempt }) => attempt <= 5,\n          },\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers()\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(6)\n  })\n\n  test('retryCondition also works with mutations', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n\n    baseBaseQuery\n      .mockRejectedValueOnce(new Error('rejected'))\n      .mockRejectedValueOnce(new Error('hello retryCondition'))\n      .mockRejectedValueOnce(new Error('rejected'))\n      .mockResolvedValue({ error: 'hello retryCondition' })\n\n    const baseQuery = retry(baseBaseQuery, {})\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        m1: build.mutation({\n          query: () => ({ method: 'PUT' }),\n          extraOptions: {\n            retryCondition: (e) =>\n              (e as FetchBaseQueryError).data === 'hello retryCondition',\n          },\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n    storeRef.store.dispatch(api.endpoints.m1.initiate({}))\n\n    await loopTimers()\n\n    expect(baseBaseQuery).toHaveBeenCalledTimes(4)\n  })\n\n  test('Specifying maxRetries as 0 in RetryOptions prevents retries', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery.mockResolvedValue({ error: 'rejected' })\n\n    const baseQuery = retry(baseBaseQuery, { maxRetries: 0 })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n    await loopTimers(2)\n\n    expect(baseBaseQuery).toHaveBeenCalledOnce()\n  })\n\n  test('retryCondition receives abort signal and stops retrying when cache entry is removed', async () => {\n    let capturedSignal: AbortSignal | undefined\n    let retryAttempts = 0\n\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n\n    // Always return an error to trigger retries\n    baseBaseQuery.mockResolvedValue({ error: 'network error' })\n\n    let retryConditionCalled = false\n\n    const baseQuery = retry(baseBaseQuery, {\n      retryCondition: (error, args, { attempt, baseQueryApi }) => {\n        retryConditionCalled = true\n        retryAttempts = attempt\n        capturedSignal = baseQueryApi.signal\n\n        // Stop retrying if the signal is aborted\n        if (baseQueryApi.signal.aborted) {\n          return false\n        }\n\n        // Otherwise, retry up to 10 times\n        return attempt <= 10\n      },\n      backoff: async () => {\n        // Short backoff for faster test\n        await new Promise((resolve) => setTimeout(resolve, 10))\n      },\n    })\n\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        getTest: build.query<string, number>({\n          query: (id) => ({ url: `test/${id}` }),\n          keepUnusedDataFor: 0.01, // Very short timeout (10ms)\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    // Start the query\n    const queryPromise = storeRef.store.dispatch(\n      api.endpoints.getTest.initiate(1),\n    )\n\n    // Wait for the first retry to happen so we capture the signal\n    await loopTimers(2)\n\n    // Verify the retry condition was called and we have a signal\n    expect(retryConditionCalled).toBe(true)\n    expect(capturedSignal).toBeDefined()\n    expect(capturedSignal!.aborted).toBe(false)\n\n    // Unsubscribe to trigger cache removal\n    queryPromise.unsubscribe()\n\n    // Wait for the cache entry to be removed (keepUnusedDataFor: 0.01s = 10ms)\n    await vi.advanceTimersByTimeAsync(50)\n\n    // Allow some time for more retries to potentially happen\n    await loopTimers(3)\n\n    // The signal should now be aborted\n    expect(capturedSignal!.aborted).toBe(true)\n\n    // We should have stopped retrying early due to the abort signal\n    // If abort signal wasn't working, we'd see many more retry attempts\n    expect(retryAttempts).toBeLessThan(10)\n\n    // The base query should have been called at least once (initial attempt)\n    // but not the full 10+ times it would without abort signal\n    expect(baseBaseQuery).toHaveBeenCalled()\n    expect(baseBaseQuery.mock.calls.length).toBeLessThan(10)\n  })\n\n  // Tests for issue #4079: Thrown errors should respect maxRetries\n  test('thrown errors (not HandledError) should respect maxRetries', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    // Simulate network error that keeps throwing\n    baseBaseQuery.mockRejectedValue(new Error('Network timeout'))\n\n    const baseQuery = retry(baseBaseQuery, { maxRetries: 3 })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers(5)\n\n    // Should try initial + 3 retries = 4 total, then stop\n    // Currently this will fail because it retries infinitely\n    expect(baseBaseQuery).toHaveBeenCalledTimes(4)\n  })\n\n  test('graphql-style thrown errors should respect maxRetries', async () => {\n    class ClientError extends Error {\n      constructor(message: string) {\n        super(message)\n        this.name = 'ClientError'\n      }\n    }\n\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    // Simulate graphql-request throwing ClientError\n    baseBaseQuery.mockImplementation(() => {\n      throw new ClientError('GraphQL network error')\n    })\n\n    const baseQuery = retry(baseBaseQuery, { maxRetries: 2 })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers(4)\n\n    // Should try initial + 2 retries = 3 total, then stop\n    // Currently this will fail because it retries infinitely\n    expect(baseBaseQuery).toHaveBeenCalledTimes(3)\n  })\n\n  test('handles mix of returned errors and thrown errors', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    baseBaseQuery\n      .mockResolvedValueOnce({ error: 'returned error' }) // HandledError\n      .mockRejectedValueOnce(new Error('thrown error')) // Not HandledError\n      .mockResolvedValueOnce({ error: 'returned error' }) // HandledError\n      .mockResolvedValue({ data: { success: true } })\n\n    const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        q1: build.query({\n          query: () => {},\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n    await loopTimers(6)\n\n    // Should eventually succeed after 4 attempts\n    expect(baseBaseQuery).toHaveBeenCalledTimes(4)\n  })\n\n  test('thrown errors with mutations should respect maxRetries', async () => {\n    const baseBaseQuery = vi.fn<BaseQueryFn>()\n    // Simulate persistent network error\n    baseBaseQuery.mockRejectedValue(new Error('Connection refused'))\n\n    const baseQuery = retry(baseBaseQuery, { maxRetries: 2 })\n    const api = createApi({\n      baseQuery,\n      endpoints: (build) => ({\n        m1: build.mutation({\n          query: () => ({ method: 'POST' }),\n        }),\n      }),\n    })\n\n    const storeRef = setupApiStore(api, undefined, {\n      withoutTestLifecycles: true,\n    })\n\n    storeRef.store.dispatch(api.endpoints.m1.initiate({}))\n\n    await loopTimers(4)\n\n    // Should try initial + 2 retries = 3 total, then stop\n    // Currently this will fail because it retries infinitely\n    expect(baseBaseQuery).toHaveBeenCalledTimes(3)\n  })\n\n  // These tests validate the abort signal handling implementation\n  describe('abort signal handling', () => {\n    test('retry loop exits immediately when signal is aborted before retry', async () => {\n      const baseBaseQuery = vi.fn<BaseQueryFn>()\n      baseBaseQuery.mockResolvedValue({ error: 'network error' })\n\n      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })\n      const api = createApi({\n        baseQuery,\n        endpoints: (build) => ({\n          q1: build.query({ query: () => {} }),\n        }),\n      })\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n      // Let first attempt fail\n      await loopTimers(1)\n      expect(baseBaseQuery).toHaveBeenCalledTimes(1)\n\n      // Abort the query\n      promise.abort()\n\n      // Advance timers to allow retry attempts\n      await loopTimers(5)\n\n      // Should not have retried after abort\n      expect(baseBaseQuery).toHaveBeenCalledTimes(1)\n    })\n\n    test('abort during active request prevents retry', async () => {\n      let requestInProgress = false\n      const baseBaseQuery = vi.fn<BaseQueryFn>()\n\n      baseBaseQuery.mockImplementation(async () => {\n        requestInProgress = true\n        await new Promise((resolve) => setTimeout(resolve, 100))\n        requestInProgress = false\n        return { error: 'network error' }\n      })\n\n      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })\n      const api = createApi({\n        baseQuery,\n        endpoints: (build) => ({\n          q1: build.query({ query: () => {} }),\n        }),\n      })\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n      // Wait for request to start\n      await vi.advanceTimersByTimeAsync(50)\n      expect(requestInProgress).toBe(true)\n\n      // Abort while request is in progress\n      promise.abort()\n\n      // Let request complete\n      await loopTimers(2)\n\n      // Should not retry after abort\n      expect(baseBaseQuery).toHaveBeenCalledTimes(1)\n    })\n\n    test('custom backoff without signal parameter still works', async () => {\n      const baseBaseQuery = vi.fn<BaseQueryFn>()\n      baseBaseQuery.mockResolvedValue({ error: 'network error' })\n\n      // Custom backoff that doesn't accept signal (backward compatibility)\n      const customBackoff = async (attempt: number, maxRetries: number) => {\n        await new Promise((resolve) => setTimeout(resolve, 100))\n      }\n\n      const baseQuery = retry(baseBaseQuery, {\n        maxRetries: 3,\n        backoff: customBackoff,\n      })\n\n      const api = createApi({\n        baseQuery,\n        endpoints: (build) => ({\n          q1: build.query({ query: () => {} }),\n        }),\n      })\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n      await loopTimers(5)\n\n      // Should complete all retries (not cancellable without signal)\n      expect(baseBaseQuery).toHaveBeenCalledTimes(4)\n    })\n\n    test('abort signal is checked before each retry attempt', async () => {\n      const attemptNumbers: number[] = []\n      const baseBaseQuery = vi.fn<BaseQueryFn>()\n      baseBaseQuery.mockImplementation(async () => {\n        attemptNumbers.push(attemptNumbers.length + 1)\n        return { error: 'network error' }\n      })\n\n      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })\n      const api = createApi({\n        baseQuery,\n        endpoints: (build) => ({\n          q1: build.query({ query: () => {} }),\n        }),\n      })\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n      // Let 3 attempts happen\n      await loopTimers(3)\n      expect(attemptNumbers).toEqual([1, 2, 3])\n\n      // Abort\n      promise.abort()\n\n      // Try to let more attempts happen\n      await loopTimers(5)\n\n      // Should not have any more attempts\n      expect(attemptNumbers).toEqual([1, 2, 3])\n    })\n\n    test('mutations respect abort signal during retry', async () => {\n      const baseBaseQuery = vi.fn<BaseQueryFn>()\n      baseBaseQuery.mockResolvedValue({ error: 'network error' })\n\n      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })\n      const api = createApi({\n        baseQuery,\n        endpoints: (build) => ({\n          m1: build.mutation({ query: () => ({ method: 'POST' }) }),\n        }),\n      })\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const promise = storeRef.store.dispatch(api.endpoints.m1.initiate({}))\n\n      // Let first attempt fail\n      await loopTimers(1)\n      expect(baseBaseQuery).toHaveBeenCalledTimes(1)\n\n      // Abort\n      promise.abort()\n\n      // Try to let retries happen\n      await loopTimers(5)\n\n      // Should not have retried\n      expect(baseBaseQuery).toHaveBeenCalledTimes(1)\n    })\n\n    test('abort after successful retry does not affect result', async () => {\n      const baseBaseQuery = vi.fn<BaseQueryFn>()\n      baseBaseQuery\n        .mockResolvedValueOnce({ error: 'network error' })\n        .mockResolvedValue({ data: { success: true } })\n\n      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })\n      const api = createApi({\n        baseQuery,\n        endpoints: (build) => ({\n          q1: build.query({ query: () => {} }),\n        }),\n      })\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n      // Let it succeed on retry\n      await loopTimers(3)\n      expect(baseBaseQuery).toHaveBeenCalledTimes(2)\n\n      const result = await promise\n\n      // Abort after success\n      promise.abort()\n\n      // Result should still be successful\n      expect(result.isSuccess).toBe(true)\n      expect(result.data).toEqual({ success: true })\n    })\n\n    test('multiple aborts are handled gracefully', async () => {\n      const baseBaseQuery = vi.fn<BaseQueryFn>()\n      baseBaseQuery.mockResolvedValue({ error: 'network error' })\n\n      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })\n      const api = createApi({\n        baseQuery,\n        endpoints: (build) => ({\n          q1: build.query({ query: () => {} }),\n        }),\n      })\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n      await loopTimers(1)\n\n      // Call abort multiple times\n      promise.abort()\n      promise.abort()\n      promise.abort()\n\n      await loopTimers(3)\n\n      // Should handle gracefully\n      expect(baseBaseQuery).toHaveBeenCalledTimes(1)\n    })\n\n    test('abort signal already aborted before retry starts', async () => {\n      const baseBaseQuery = vi.fn<BaseQueryFn>()\n      baseBaseQuery.mockResolvedValue({ error: 'network error' })\n\n      const baseQuery = retry(baseBaseQuery, { maxRetries: 5 })\n      const api = createApi({\n        baseQuery,\n        endpoints: (build) => ({\n          q1: build.query({ query: () => {} }),\n        }),\n      })\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      const promise = storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n      // Abort immediately\n      promise.abort()\n\n      await loopTimers(5)\n\n      // May have started the first attempt before abort was processed\n      // but should not retry\n      expect(baseBaseQuery.mock.calls.length).toBeLessThanOrEqual(1)\n    })\n\n    test('resetApiState aborts retrying queries', async () => {\n      const baseBaseQuery = vi.fn<BaseQueryFn>()\n      baseBaseQuery.mockResolvedValue({ error: 'network error' })\n\n      const baseQuery = retry(baseBaseQuery, { maxRetries: 10 })\n      const api = createApi({\n        baseQuery,\n        endpoints: (build) => ({\n          q1: build.query({ query: () => {} }),\n        }),\n      })\n\n      const storeRef = setupApiStore(api, undefined, {\n        withoutTestLifecycles: true,\n      })\n      storeRef.store.dispatch(api.endpoints.q1.initiate({}))\n\n      // Let first attempt fail and start retrying\n      await loopTimers(2)\n      expect(baseBaseQuery).toHaveBeenCalledTimes(2)\n\n      // Reset API state (should abort the retry loop)\n      storeRef.store.dispatch(api.util.resetApiState())\n\n      // Try to let more retries happen\n      await loopTimers(5)\n\n      // Should not have retried after resetApiState\n      expect(baseBaseQuery).toHaveBeenCalledTimes(2)\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/unionTypes.test-d.ts",
    "content": "import type { UseQueryStateOptions } from '@internal/query/react/buildHooks'\nimport type { SerializedError } from '@reduxjs/toolkit'\nimport type {\n  FetchBaseQueryError,\n  QueryDefinition,\n  TypedLazyQueryTrigger,\n  TypedMutationTrigger,\n  TypedUseLazyQuery,\n  TypedUseLazyQueryStateResult,\n  TypedUseLazyQuerySubscription,\n  TypedUseMutation,\n  TypedUseMutationResult,\n  TypedUseQuery,\n  TypedUseQueryHookResult,\n  TypedUseQueryState,\n  TypedUseQueryStateOptions,\n  TypedUseQueryStateResult,\n  TypedUseQuerySubscription,\n  TypedUseQuerySubscriptionResult,\n} from '@reduxjs/toolkit/query/react'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query/react'\n\nconst baseQuery = fetchBaseQuery()\n\nconst api = createApi({\n  baseQuery,\n  endpoints: (build) => ({\n    getTest: build.query<string, void>({ query: () => '' }),\n    mutation: build.mutation<string, void>({ query: () => '' }),\n  }),\n})\n\ndescribe('union types', () => {\n  test('query selector union', () => {\n    const result = api.endpoints.getTest.select()({} as any)\n\n    if (result.isUninitialized) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n    }\n\n    if (result.isLoading) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError | undefined\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n    }\n\n    if (result.isError) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n    }\n\n    if (result.isSuccess) {\n      expectTypeOf(result.data).toBeString()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n    }\n\n    expectTypeOf(result).not.toBeNever()\n\n    // is always one of those four\n    if (\n      !result.isUninitialized &&\n      !result.isLoading &&\n      !result.isError &&\n      !result.isSuccess\n    ) {\n      expectTypeOf(result).toBeNever()\n    }\n  })\n\n  test('useQuery union', () => {\n    const result = api.endpoints.getTest.useQuery()\n\n    if (result.isUninitialized) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toEqualTypeOf<false>()\n    }\n\n    if (result.isLoading) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError | undefined\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toBeBoolean()\n    }\n\n    if (result.isError) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toEqualTypeOf<false>()\n    }\n\n    if (result.isSuccess) {\n      expectTypeOf(result.data).toBeString()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toBeBoolean()\n    }\n\n    if (result.isFetching) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError | undefined\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toBeBoolean()\n\n      expectTypeOf(result.isSuccess).toBeBoolean()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n    }\n\n    expectTypeOf(result.currentData).toEqualTypeOf<string | undefined>()\n\n    if (result.isSuccess) {\n      if (!result.isFetching) {\n        expectTypeOf(result.currentData).toBeString()\n      } else {\n        expectTypeOf(result.currentData).toEqualTypeOf<string | undefined>()\n      }\n    }\n\n    expectTypeOf(result).not.toBeNever()\n\n    // is always one of those four\n    if (\n      !result.isUninitialized &&\n      !result.isLoading &&\n      !result.isError &&\n      !result.isSuccess\n    ) {\n      expectTypeOf(result).toBeNever()\n    }\n  })\n  test('useQuery TS4.1 union', () => {\n    const result = api.useGetTestQuery()\n\n    if (result.isUninitialized) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toEqualTypeOf<false>()\n    }\n\n    if (result.isLoading) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError | undefined\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toBeBoolean()\n    }\n\n    if (result.isError) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toEqualTypeOf<false>()\n    }\n\n    if (result.isSuccess) {\n      expectTypeOf(result.data).toBeString()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toBeBoolean()\n    }\n\n    if (result.isFetching) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError | undefined\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toBeBoolean()\n\n      expectTypeOf(result.isSuccess).toBeBoolean()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n    }\n\n    expectTypeOf(result).not.toBeNever()\n\n    // is always one of those four\n    if (\n      !result.isUninitialized &&\n      !result.isLoading &&\n      !result.isError &&\n      !result.isSuccess\n    ) {\n      expectTypeOf(result).toBeNever()\n    }\n  })\n\n  test('useLazyQuery union', () => {\n    const [_trigger, result] = api.endpoints.getTest.useLazyQuery()\n\n    if (result.isUninitialized) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toEqualTypeOf<false>()\n    }\n\n    if (result.isLoading) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError | undefined\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toBeBoolean()\n    }\n\n    if (result.isError) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toEqualTypeOf<false>()\n    }\n\n    if (result.isSuccess) {\n      expectTypeOf(result.data).toBeString()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toBeBoolean()\n    }\n\n    if (result.isFetching) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError | undefined\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toBeBoolean()\n\n      expectTypeOf(result.isSuccess).toBeBoolean()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n    }\n\n    expectTypeOf(result).not.toBeNever()\n\n    // is always one of those four\n    if (\n      !result.isUninitialized &&\n      !result.isLoading &&\n      !result.isError &&\n      !result.isSuccess\n    ) {\n      expectTypeOf(result).toBeNever()\n    }\n  })\n\n  test('useLazyQuery TS4.1 union', () => {\n    const [_trigger, result] = api.useLazyGetTestQuery()\n\n    if (result.isUninitialized) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toEqualTypeOf<false>()\n    }\n\n    if (result.isLoading) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError | undefined\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toBeBoolean()\n    }\n\n    if (result.isError) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toEqualTypeOf<false>()\n    }\n\n    if (result.isSuccess) {\n      expectTypeOf(result.data).toBeString()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isFetching).toBeBoolean()\n    }\n\n    if (result.isFetching) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError | undefined\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toBeBoolean()\n\n      expectTypeOf(result.isSuccess).toBeBoolean()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n    }\n\n    expectTypeOf(result).not.toBeNever()\n\n    // is always one of those four\n    if (\n      !result.isUninitialized &&\n      !result.isLoading &&\n      !result.isError &&\n      !result.isSuccess\n    ) {\n      expectTypeOf(result).toBeNever()\n    }\n  })\n\n  test('queryHookResult (without selector) union', async () => {\n    const useQueryStateResult = api.endpoints.getTest.useQueryState()\n\n    const useQueryResult = api.endpoints.getTest.useQuery()\n\n    const useQueryStateWithSelectFromResult =\n      api.endpoints.getTest.useQueryState(undefined, {\n        selectFromResult: () => ({ x: true }),\n      })\n\n    const { refetch, ...useQueryResultWithoutMethods } = useQueryResult\n\n    assertType<typeof useQueryResultWithoutMethods>(useQueryStateResult)\n\n    expectTypeOf(useQueryStateResult).toExtend<\n      typeof useQueryResultWithoutMethods\n    >()\n\n    expectTypeOf(useQueryStateWithSelectFromResult)\n      .parameter(0)\n      .not.toExtend<typeof useQueryResultWithoutMethods>()\n\n    expectTypeOf(api.endpoints.getTest.select).returns.returns.toEqualTypeOf<\n      Awaited<ReturnType<typeof refetch>>\n    >()\n  })\n\n  test('useQueryState (with selectFromResult)', () => {\n    const result = api.endpoints.getTest.useQueryState(undefined, {\n      selectFromResult({\n        data,\n        isLoading,\n        isFetching,\n        isError,\n        isSuccess,\n        isUninitialized,\n      }) {\n        return {\n          data: data ?? 1,\n          isLoading,\n          isFetching,\n          isError,\n          isSuccess,\n          isUninitialized,\n        }\n      },\n    })\n\n    expectTypeOf({\n      data: '' as string | number,\n      isUninitialized: false,\n      isLoading: true,\n      isFetching: true,\n      isSuccess: false,\n      isError: false,\n    }).toEqualTypeOf(result)\n  })\n\n  test('useQuery (with selectFromResult)', async () => {\n    const { refetch, ...result } = api.endpoints.getTest.useQuery(undefined, {\n      selectFromResult({\n        data,\n        isLoading,\n        isFetching,\n        isError,\n        isSuccess,\n        isUninitialized,\n      }) {\n        return {\n          data: data ?? 1,\n          isLoading,\n          isFetching,\n          isError,\n          isSuccess,\n          isUninitialized,\n        }\n      },\n    })\n\n    expectTypeOf({\n      data: '' as string | number,\n      isUninitialized: false,\n      isLoading: true,\n      isFetching: true,\n      isSuccess: false,\n      isError: false,\n    }).toEqualTypeOf(result)\n\n    expectTypeOf(api.endpoints.getTest.select).returns.returns.toEqualTypeOf<\n      Awaited<ReturnType<typeof refetch>>\n    >()\n  })\n\n  test('useMutation union', () => {\n    const [_trigger, result] = api.endpoints.mutation.useMutation()\n\n    if (result.isUninitialized) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n    }\n\n    if (result.isLoading) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError | undefined\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n    }\n\n    if (result.isError) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n    }\n\n    if (result.isSuccess) {\n      expectTypeOf(result.data).toBeString()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n    }\n\n    expectTypeOf(result).not.toBeNever()\n\n    // is always one of those four\n    if (\n      !result.isUninitialized &&\n      !result.isLoading &&\n      !result.isError &&\n      !result.isSuccess\n    ) {\n      expectTypeOf(result).toBeNever()\n    }\n  })\n\n  test('useMutation (with selectFromResult)', () => {\n    const [_trigger, result] = api.endpoints.mutation.useMutation({\n      selectFromResult({\n        data,\n        isLoading,\n        isError,\n        isSuccess,\n        isUninitialized,\n      }) {\n        return {\n          data: data ?? 'hi',\n          isLoading,\n          isError,\n          isSuccess,\n          isUninitialized,\n        }\n      },\n    })\n\n    expectTypeOf({\n      data: '' as string,\n      isUninitialized: false,\n      isLoading: true,\n      isSuccess: false,\n      isError: false,\n      reset: () => {},\n    }).toExtend<typeof result>()\n  })\n\n  test('useMutation TS4.1 union', () => {\n    const [_trigger, result] = api.useMutationMutation()\n\n    if (result.isUninitialized) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n    }\n\n    if (result.isLoading) {\n      expectTypeOf(result.data).toBeUndefined()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError | undefined\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n    }\n\n    if (result.isError) {\n      expectTypeOf(result.data).toEqualTypeOf<string | undefined>()\n\n      expectTypeOf(result.error).toEqualTypeOf<\n        SerializedError | FetchBaseQueryError\n      >()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isSuccess).toEqualTypeOf<false>()\n    }\n\n    if (result.isSuccess) {\n      expectTypeOf(result.data).toBeString()\n\n      expectTypeOf(result.error).toBeUndefined()\n\n      expectTypeOf(result.isUninitialized).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isLoading).toEqualTypeOf<false>()\n\n      expectTypeOf(result.isError).toEqualTypeOf<false>()\n    }\n\n    expectTypeOf(result).not.toBeNever()\n\n    // is always one of those four\n    if (\n      !result.isUninitialized &&\n      !result.isLoading &&\n      !result.isError &&\n      !result.isSuccess\n    ) {\n      expectTypeOf(result).toBeNever()\n    }\n  })\n})\n\ndescribe('\"Typed\" helper types', () => {\n  test('useQuery', () => {\n    expectTypeOf<TypedUseQuery<string, void, typeof baseQuery>>().toExtend<\n      typeof api.endpoints.getTest.useQuery\n    >()\n\n    const result = api.endpoints.getTest.useQuery()\n\n    expectTypeOf<\n      TypedUseQueryHookResult<string, void, typeof baseQuery>\n    >().toEqualTypeOf(result)\n  })\n\n  test('useQuery with selectFromResult', () => {\n    const result = api.endpoints.getTest.useQuery(undefined, {\n      selectFromResult: () => ({ x: true }),\n    })\n\n    expectTypeOf<\n      TypedUseQueryHookResult<string, void, typeof baseQuery, { x: boolean }>\n    >().toEqualTypeOf(result)\n  })\n\n  test('useQueryState', () => {\n    expectTypeOf<TypedUseQueryState<string, void, typeof baseQuery>>().toExtend<\n      typeof api.endpoints.getTest.useQueryState\n    >()\n\n    const result = api.endpoints.getTest.useQueryState()\n\n    expectTypeOf<\n      TypedUseQueryStateResult<string, void, typeof baseQuery>\n    >().toEqualTypeOf(result)\n  })\n\n  test('useQueryState with selectFromResult', () => {\n    const result = api.endpoints.getTest.useQueryState(undefined, {\n      selectFromResult: () => ({ x: true }),\n    })\n\n    expectTypeOf<\n      TypedUseQueryStateResult<string, void, typeof baseQuery, { x: boolean }>\n    >().toEqualTypeOf(result)\n  })\n\n  test('useQueryState options', () => {\n    expectTypeOf<\n      TypedUseQueryStateOptions<string, void, typeof baseQuery>\n    >().toExtend<Parameters<typeof api.endpoints.getTest.useQueryState>[1]>()\n\n    expectTypeOf<\n      UseQueryStateOptions<\n        QueryDefinition<void, typeof baseQuery, string, string>,\n        { x: boolean }\n      >\n    >().toEqualTypeOf<\n      TypedUseQueryStateOptions<string, void, typeof baseQuery, { x: boolean }>\n    >()\n  })\n\n  test('useQuerySubscription', () => {\n    expectTypeOf<\n      TypedUseQuerySubscription<string, void, typeof baseQuery>\n    >().toExtend<typeof api.endpoints.getTest.useQuerySubscription>()\n\n    const result = api.endpoints.getTest.useQuerySubscription()\n\n    expectTypeOf<\n      TypedUseQuerySubscriptionResult<string, void, typeof baseQuery>\n    >().toEqualTypeOf(result)\n  })\n\n  test('useLazyQuery', () => {\n    expectTypeOf<TypedUseLazyQuery<string, void, typeof baseQuery>>().toExtend<\n      typeof api.endpoints.getTest.useLazyQuery\n    >()\n\n    const [trigger, result] = api.endpoints.getTest.useLazyQuery()\n\n    expectTypeOf<\n      TypedLazyQueryTrigger<string, void, typeof baseQuery>\n    >().toExtend<typeof trigger>()\n\n    expectTypeOf<\n      TypedUseLazyQueryStateResult<string, void, typeof baseQuery>\n    >().toExtend<typeof result>()\n  })\n\n  test('useLazyQuery with selectFromResult', () => {\n    const [trigger, result] = api.endpoints.getTest.useLazyQuery({\n      selectFromResult: () => ({ x: true }),\n    })\n\n    expectTypeOf<\n      TypedLazyQueryTrigger<string, void, typeof baseQuery>\n    >().toExtend<typeof trigger>()\n\n    expectTypeOf<\n      TypedUseLazyQueryStateResult<\n        string,\n        void,\n        typeof baseQuery,\n        { x: boolean }\n      >\n    >().toExtend<typeof result>()\n  })\n\n  test('useLazyQuerySubscription', () => {\n    expectTypeOf<\n      TypedUseLazyQuerySubscription<string, void, typeof baseQuery>\n    >().toExtend<typeof api.endpoints.getTest.useLazyQuerySubscription>()\n\n    const [trigger] = api.endpoints.getTest.useLazyQuerySubscription()\n\n    expectTypeOf<\n      TypedLazyQueryTrigger<string, void, typeof baseQuery>\n    >().toExtend<typeof trigger>()\n  })\n\n  test('useMutation', () => {\n    expectTypeOf<TypedUseMutation<string, void, typeof baseQuery>>().toExtend<\n      typeof api.endpoints.mutation.useMutation\n    >()\n\n    const [trigger, result] = api.endpoints.mutation.useMutation()\n\n    expectTypeOf<\n      TypedMutationTrigger<string, void, typeof baseQuery>\n    >().toExtend<typeof trigger>()\n\n    expectTypeOf<\n      TypedUseMutationResult<string, void, typeof baseQuery>\n    >().toExtend<typeof result>()\n  })\n\n  test('useQuery - defining selectFromResult separately', () => {\n    const selectFromResult = (\n      result: TypedUseQueryStateResult<string, void, typeof baseQuery>,\n    ) => ({ x: true })\n\n    const result = api.endpoints.getTest.useQuery(undefined, {\n      selectFromResult,\n    })\n\n    expectTypeOf(result).toEqualTypeOf<\n      TypedUseQueryHookResult<\n        string,\n        void,\n        typeof baseQuery,\n        ReturnType<typeof selectFromResult>\n      >\n    >()\n  })\n\n  test('useMutation - defining selectFromResult separately', () => {\n    const selectFromResult = (\n      result: Omit<\n        TypedUseMutationResult<string, void, typeof baseQuery>,\n        'reset' | 'originalArgs'\n      >,\n    ) => ({ x: true })\n\n    const [trigger, result] = api.endpoints.mutation.useMutation({\n      selectFromResult,\n    })\n    expectTypeOf(result).toEqualTypeOf<\n      TypedUseMutationResult<\n        string,\n        void,\n        typeof baseQuery,\n        ReturnType<typeof selectFromResult>\n      >\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/useMutation-fixedCacheKey.test.tsx",
    "content": "import { createApi } from '@reduxjs/toolkit/query/react'\nimport {\n  act,\n  getByTestId,\n  render,\n  screen,\n  waitFor,\n} from '@testing-library/react'\nimport { delay } from 'msw'\nimport { vi } from 'vitest'\nimport { setupApiStore } from '../../tests/utils/helpers'\n\ndescribe('fixedCacheKey', () => {\n  const onNewCacheEntry = vi.fn()\n\n  const api = createApi({\n    async baseQuery(arg: string | Promise<string>) {\n      return { data: await arg }\n    },\n    endpoints: (build) => ({\n      send: build.mutation<string, string | Promise<string>>({\n        query: (arg) => arg,\n      }),\n    }),\n  })\n  const storeRef = setupApiStore(api)\n\n  function Component({\n    name,\n    fixedCacheKey,\n    value = name,\n  }: {\n    name: string\n    fixedCacheKey?: string\n    value?: string | Promise<string>\n  }) {\n    const [trigger, result] = api.endpoints.send.useMutation({ fixedCacheKey })\n\n    return (\n      <div data-testid={name}>\n        <div data-testid=\"status\">{result.status}</div>\n        <div data-testid=\"data\">{result.data}</div>\n        <div data-testid=\"originalArgs\">{String(result.originalArgs)}</div>\n        <button data-testid=\"trigger\" onClick={() => trigger(value)}>\n          trigger\n        </button>\n        <button data-testid=\"reset\" onClick={result.reset}>\n          reset\n        </button>\n      </div>\n    )\n  }\n\n  test('two mutations without `fixedCacheKey` do not influence each other', async () => {\n    render(\n      <>\n        <Component name=\"C1\" />\n        <Component name=\"C2\" />\n      </>,\n      { wrapper: storeRef.wrapper },\n    )\n    const c1 = screen.getByTestId('C1')\n    const c2 = screen.getByTestId('C2')\n    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')\n\n    act(() => {\n      getByTestId(c1, 'trigger').click()\n    })\n\n    await waitFor(() =>\n      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),\n    )\n    expect(getByTestId(c1, 'data').textContent).toBe('C1')\n    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')\n  })\n\n  test('two mutations with the same `fixedCacheKey` do influence each other', async () => {\n    render(\n      <>\n        <Component name=\"C1\" fixedCacheKey=\"test\" />\n        <Component name=\"C2\" fixedCacheKey=\"test\" />\n      </>,\n      { wrapper: storeRef.wrapper },\n    )\n    const c1 = screen.getByTestId('C1')\n    const c2 = screen.getByTestId('C2')\n    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')\n\n    act(() => {\n      getByTestId(c1, 'trigger').click()\n    })\n\n    await waitFor(() => {\n      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled')\n      expect(getByTestId(c1, 'data').textContent).toBe('C1')\n      expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')\n      expect(getByTestId(c2, 'data').textContent).toBe('C1')\n    })\n\n    // test reset from the other component\n    act(() => {\n      getByTestId(c2, 'reset').click()\n    })\n    await waitFor(() => {\n      expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n      expect(getByTestId(c1, 'data').textContent).toBe('')\n      expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')\n      expect(getByTestId(c2, 'data').textContent).toBe('')\n    })\n  })\n\n  test('resetting from the component that triggered the mutation resets for each shared result', async () => {\n    render(\n      <>\n        <Component name=\"C1\" fixedCacheKey=\"test-A\" />\n        <Component name=\"C2\" fixedCacheKey=\"test-A\" />\n        <Component name=\"C3\" fixedCacheKey=\"test-B\" />\n        <Component name=\"C4\" fixedCacheKey=\"test-B\" />\n      </>,\n      { wrapper: storeRef.wrapper },\n    )\n    const c1 = screen.getByTestId('C1')\n    const c2 = screen.getByTestId('C2')\n    const c3 = screen.getByTestId('C3')\n    const c4 = screen.getByTestId('C4')\n    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c3, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c4, 'status').textContent).toBe('uninitialized')\n\n    // trigger with a component using the first cache key\n\n    act(() => {\n      getByTestId(c1, 'trigger').click()\n    })\n\n    await waitFor(() =>\n      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),\n    )\n\n    // the components with the first cache key should be affected\n    expect(getByTestId(c1, 'data').textContent).toBe('C1')\n    expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')\n    expect(getByTestId(c2, 'data').textContent).toBe('C1')\n    expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')\n\n    // the components with the second cache key should be unaffected\n    expect(getByTestId(c3, 'data').textContent).toBe('')\n    expect(getByTestId(c3, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c4, 'data').textContent).toBe('')\n    expect(getByTestId(c4, 'status').textContent).toBe('uninitialized')\n\n    // trigger with a component using the second cache key\n\n    act(() => {\n      getByTestId(c3, 'trigger').click()\n    })\n\n    await waitFor(() =>\n      expect(getByTestId(c3, 'status').textContent).toBe('fulfilled'),\n    )\n\n    // the components with the first cache key should be unaffected\n    await waitFor(() => {\n      expect(getByTestId(c1, 'data').textContent).toBe('C1')\n      expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')\n      expect(getByTestId(c2, 'data').textContent).toBe('C1')\n      expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')\n\n      // the component with the second cache key should be affected\n      expect(getByTestId(c3, 'data').textContent).toBe('C3')\n      expect(getByTestId(c3, 'status').textContent).toBe('fulfilled')\n      expect(getByTestId(c4, 'data').textContent).toBe('C3')\n      expect(getByTestId(c4, 'status').textContent).toBe('fulfilled')\n    })\n\n    // test reset from the component that triggered the mutation for the first cache key\n\n    act(() => {\n      getByTestId(c1, 'reset').click()\n    })\n\n    await waitFor(() => {\n      // the components with the first cache key should be affected\n      expect(getByTestId(c1, 'data').textContent).toBe('')\n      expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n      expect(getByTestId(c2, 'data').textContent).toBe('')\n      expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')\n\n      // the components with the second cache key should be unaffected\n      expect(getByTestId(c3, 'data').textContent).toBe('C3')\n      expect(getByTestId(c3, 'status').textContent).toBe('fulfilled')\n      expect(getByTestId(c4, 'data').textContent).toBe('C3')\n      expect(getByTestId(c4, 'status').textContent).toBe('fulfilled')\n    })\n  })\n\n  test('two mutations with different `fixedCacheKey` do not influence each other', async () => {\n    render(\n      <>\n        <Component name=\"C1\" fixedCacheKey=\"test\" />\n        <Component name=\"C2\" fixedCacheKey=\"toast\" />\n      </>,\n      { wrapper: storeRef.wrapper },\n    )\n    const c1 = screen.getByTestId('C1')\n    const c2 = screen.getByTestId('C2')\n    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')\n\n    act(() => {\n      getByTestId(c1, 'trigger').click()\n    })\n\n    await waitFor(() =>\n      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),\n    )\n    expect(getByTestId(c1, 'data').textContent).toBe('C1')\n    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')\n  })\n\n  test('unmounting and remounting keeps data intact', async () => {\n    const { rerender } = render(<Component name=\"C1\" fixedCacheKey=\"test\" />, {\n      wrapper: storeRef.wrapper,\n    })\n    let c1 = screen.getByTestId('C1')\n    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n\n    act(() => {\n      getByTestId(c1, 'trigger').click()\n    })\n\n    await waitFor(() =>\n      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),\n    )\n    expect(getByTestId(c1, 'data').textContent).toBe('C1')\n\n    rerender(<div />)\n    expect(screen.queryByTestId('C1')).toBe(null)\n\n    rerender(<Component name=\"C1\" fixedCacheKey=\"test\" />)\n    c1 = screen.getByTestId('C1')\n    expect(getByTestId(c1, 'status').textContent).toBe('fulfilled')\n    expect(getByTestId(c1, 'data').textContent).toBe('C1')\n  })\n\n  test('(limitation) mutations using `fixedCacheKey` do not return `originalArgs`', async () => {\n    render(\n      <>\n        <Component name=\"C1\" fixedCacheKey=\"test\" />\n        <Component name=\"C2\" fixedCacheKey=\"test\" />\n      </>,\n      { wrapper: storeRef.wrapper },\n    )\n    const c1 = screen.getByTestId('C1')\n    const c2 = screen.getByTestId('C2')\n    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')\n\n    act(() => {\n      getByTestId(c1, 'trigger').click()\n    })\n\n    await waitFor(() =>\n      expect(getByTestId(c1, 'status').textContent).toBe('fulfilled'),\n    )\n    expect(getByTestId(c1, 'data').textContent).toBe('C1')\n    expect(getByTestId(c2, 'status').textContent).toBe('fulfilled')\n    expect(getByTestId(c2, 'data').textContent).toBe('C1')\n  })\n\n  test('a component without `fixedCacheKey` has `originalArgs`', async () => {\n    render(<Component name=\"C1\" />, {\n      wrapper: storeRef.wrapper,\n    })\n    let c1 = screen.getByTestId('C1')\n    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')\n\n    await act(async () => {\n      getByTestId(c1, 'trigger').click()\n      await Promise.resolve()\n    })\n\n    expect(getByTestId(c1, 'originalArgs').textContent).toBe('C1')\n  })\n\n  test('a component with `fixedCacheKey` does never have `originalArgs`', async () => {\n    render(<Component name=\"C1\" fixedCacheKey=\"test\" />, {\n      wrapper: storeRef.wrapper,\n    })\n    let c1 = screen.getByTestId('C1')\n    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')\n\n    await act(async () => {\n      getByTestId(c1, 'trigger').click()\n    })\n\n    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')\n  })\n\n  test('using `fixedCacheKey` will always use the latest dispatched thunk, prevent races', async () => {\n    let resolve1: (str: string) => void, resolve2: (str: string) => void\n    const p1 = new Promise<string>((resolve) => {\n      resolve1 = resolve\n    })\n    const p2 = new Promise<string>((resolve) => {\n      resolve2 = resolve\n    })\n    render(\n      <>\n        <Component name=\"C1\" fixedCacheKey=\"test\" value={p1} />\n        <Component name=\"C2\" fixedCacheKey=\"test\" value={p2} />\n      </>,\n      { wrapper: storeRef.wrapper },\n    )\n    const c1 = screen.getByTestId('C1')\n    const c2 = screen.getByTestId('C2')\n    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c2, 'status').textContent).toBe('uninitialized')\n\n    await act(async () => {\n      getByTestId(c1, 'trigger').click()\n      await Promise.resolve()\n    })\n\n    expect(getByTestId(c1, 'status').textContent).toBe('pending')\n    expect(getByTestId(c1, 'data').textContent).toBe('')\n\n    act(() => {\n      getByTestId(c2, 'trigger').click()\n    })\n\n    expect(getByTestId(c1, 'status').textContent).toBe('pending')\n    expect(getByTestId(c1, 'data').textContent).toBe('')\n\n    await act(async () => {\n      resolve1!('this should not show up any more')\n      await Promise.resolve()\n    })\n\n    await delay(150)\n\n    expect(getByTestId(c1, 'status').textContent).toBe('pending')\n    expect(getByTestId(c1, 'data').textContent).toBe('')\n\n    await act(async () => {\n      resolve2!('this should be visible')\n      await Promise.resolve()\n    })\n\n    await delay(150)\n\n    expect(getByTestId(c1, 'status').textContent).toBe('fulfilled')\n    expect(getByTestId(c1, 'data').textContent).toBe('this should be visible')\n  })\n\n  test('using fixedCacheKey should create a new cache entry', async () => {\n    api.enhanceEndpoints({\n      endpoints: {\n        send: {\n          onCacheEntryAdded: (arg) => onNewCacheEntry(arg),\n        },\n      },\n    })\n\n    render(<Component name=\"C1\" fixedCacheKey={'testKey'} />, {\n      wrapper: storeRef.wrapper,\n    })\n\n    let c1 = screen.getByTestId('C1')\n\n    expect(getByTestId(c1, 'status').textContent).toBe('uninitialized')\n    expect(getByTestId(c1, 'originalArgs').textContent).toBe('undefined')\n\n    await act(async () => {\n      getByTestId(c1, 'trigger').click()\n      await Promise.resolve()\n    })\n\n    expect(onNewCacheEntry).toHaveBeenCalledWith('C1')\n\n    api.enhanceEndpoints({\n      endpoints: {\n        send: {\n          onCacheEntryAdded: undefined,\n        },\n      },\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tests/utils.test.ts",
    "content": "import { vi } from 'vitest'\nimport { isOnline, isDocumentVisible, joinUrls } from '@internal/query/utils'\n\nafterAll(() => {\n  vi.restoreAllMocks()\n})\n\ndescribe('isOnline', () => {\n  test('Assumes online=true in a node env', () => {\n    vi.spyOn(window, 'navigator', 'get').mockImplementation(\n      () => undefined as any,\n    )\n\n    expect(navigator).toBeUndefined()\n    expect(isOnline()).toBe(true)\n  })\n\n  test('Returns false if navigator isOnline=false', () => {\n    vi.spyOn(window, 'navigator', 'get').mockImplementation(\n      () => ({ onLine: false }) as any,\n    )\n    expect(isOnline()).toBe(false)\n  })\n\n  test('Returns true if navigator isOnline=true', () => {\n    vi.spyOn(window, 'navigator', 'get').mockImplementation(\n      () => ({ onLine: true }) as any,\n    )\n    expect(isOnline()).toBe(true)\n  })\n})\n\ndescribe('isDocumentVisible', () => {\n  test('Assumes true when in a non-browser env', () => {\n    vi.spyOn(window, 'document', 'get').mockImplementation(\n      () => undefined as any,\n    )\n    expect(window.document).toBeUndefined()\n    expect(isDocumentVisible()).toBe(true)\n  })\n\n  test('Returns false when hidden=true', () => {\n    vi.spyOn(window, 'document', 'get').mockImplementation(\n      () => ({ visibilityState: 'hidden' }) as any,\n    )\n    expect(isDocumentVisible()).toBe(false)\n  })\n\n  test('Returns true when visibilityState=prerender', () => {\n    vi.spyOn(window, 'document', 'get').mockImplementation(\n      () => ({ visibilityState: 'prerender' }) as any,\n    )\n    expect(document.visibilityState).toBe('prerender')\n    expect(isDocumentVisible()).toBe(true)\n  })\n  test('Returns true when visibilityState=visible', () => {\n    vi.spyOn(window, 'document', 'get').mockImplementation(\n      () => ({ visibilityState: 'visible' }) as any,\n    )\n    expect(document.visibilityState).toBe('visible')\n    expect(isDocumentVisible()).toBe(true)\n  })\n  test('Returns true when visibilityState=undefined', () => {\n    vi.spyOn(window, 'document', 'get').mockImplementation(\n      () => ({ visibilityState: undefined }) as any,\n    )\n    expect(document.visibilityState).toBeUndefined()\n    expect(isDocumentVisible()).toBe(true)\n  })\n})\n\ndescribe('joinUrls', () => {\n  test.each([\n    ['/api/', '/banana', '/api/banana'],\n    ['/api/', 'banana', '/api/banana'],\n    ['/api', '/banana', '/api/banana'],\n    ['/api', 'banana', '/api/banana'],\n    ['', '/banana', '/banana'],\n    ['', 'banana', 'banana'],\n    ['api', '?a=1', 'api?a=1'],\n    ['api/', '?a=1', 'api/?a=1'],\n    ['api', 'banana?a=1', 'api/banana?a=1'],\n    ['api/', 'banana?a=1', 'api/banana?a=1'],\n    ['https://example.com/api', 'banana', 'https://example.com/api/banana'],\n    ['https://example.com/api', '/banana', 'https://example.com/api/banana'],\n    ['https://example.com/api/', 'banana', 'https://example.com/api/banana'],\n    ['https://example.com/api/', '/banana', 'https://example.com/api/banana'],\n    ['https://example.com/api/', 'https://example.org', 'https://example.org'],\n    ['https://example.com/api/', '//example.org', '//example.org'],\n  ])('%s and %s join to %s', (base, url, expected) => {\n    expect(joinUrls(base, url)).toBe(expected)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/query/tsHelpers.ts",
    "content": "export type Id<T> = { [K in keyof T]: T[K] } & {}\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> &\n  Required<Pick<T, K>>\nexport type Override<T1, T2> = T2 extends any ? Omit<T1, keyof T2> & T2 : never\nexport function assertCast<T>(v: any): asserts v is T {}\n\nexport function safeAssign<T extends object>(\n  target: T,\n  ...args: Array<Partial<NoInfer<T>>>\n): T {\n  return Object.assign(target, ...args)\n}\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (\n  U extends any ? (k: U) => void : never\n) extends (k: infer I) => void\n  ? I\n  : never\n\nexport type NonOptionalKeys<T> = {\n  [K in keyof T]-?: undefined extends T[K] ? never : K\n}[keyof T]\n\nexport type HasRequiredProps<T, True, False> =\n  NonOptionalKeys<T> extends never ? False : True\n\nexport type OptionalIfAllPropsOptional<T> = HasRequiredProps<T, T, T | never>\n\nexport type NoInfer<T> = [T][T extends any ? 0 : never]\n\nexport type NonUndefined<T> = T extends undefined ? never : T\n\nexport type UnwrapPromise<T> = T extends PromiseLike<infer V> ? V : T\n\nexport type MaybePromise<T> = T | PromiseLike<T>\n\nexport type OmitFromUnion<T, K extends keyof T> = T extends any\n  ? Omit<T, K>\n  : never\n\nexport type IsAny<T, True, False = never> = true | false extends (\n  T extends never ? true : false\n)\n  ? True\n  : False\n\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/capitalize.ts",
    "content": "export function capitalize(str: string) {\n  return str.replace(str[0], str[0].toUpperCase())\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/copyWithStructuralSharing.ts",
    "content": "import { isPlainObject as _iPO } from '../core/rtkImports'\n\n// remove type guard\nconst isPlainObject: (_: any) => boolean = _iPO\n\nexport function copyWithStructuralSharing<T>(oldObj: any, newObj: T): T\nexport function copyWithStructuralSharing(oldObj: any, newObj: any): any {\n  if (\n    oldObj === newObj ||\n    !(\n      (isPlainObject(oldObj) && isPlainObject(newObj)) ||\n      (Array.isArray(oldObj) && Array.isArray(newObj))\n    )\n  ) {\n    return newObj\n  }\n  const newKeys = Object.keys(newObj)\n  const oldKeys = Object.keys(oldObj)\n\n  let isSameObject = newKeys.length === oldKeys.length\n  const mergeObj: any = Array.isArray(newObj) ? [] : {}\n  for (const key of newKeys) {\n    mergeObj[key] = copyWithStructuralSharing(oldObj[key], newObj[key])\n    if (isSameObject) isSameObject = oldObj[key] === mergeObj[key]\n  }\n  return isSameObject ? oldObj : mergeObj\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/countObjectKeys.ts",
    "content": "// Fast method for counting an object's keys\n// without resorting to `Object.keys(obj).length\n// Will this make a big difference in perf? Probably not\n// But we can save a few allocations.\n\nexport function countObjectKeys(obj: Record<any, any>) {\n  let count = 0\n\n  for (const _key in obj) {\n    count++\n  }\n\n  return count\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/filterMap.ts",
    "content": "// Preserve type guard predicate behavior when passing to mapper\nexport function filterMap<T, U, S extends T = T>(\n  array: readonly T[],\n  predicate: (item: T, index: number) => item is S,\n  mapper: (item: S, index: number) => U | U[],\n): U[]\n\nexport function filterMap<T, U>(\n  array: readonly T[],\n  predicate: (item: T, index: number) => boolean,\n  mapper: (item: T, index: number) => U | U[],\n): U[]\n\nexport function filterMap<T, U>(\n  array: readonly T[],\n  predicate: (item: T, index: number) => boolean,\n  mapper: (item: T, index: number) => U | U[],\n): U[] {\n  return array\n    .reduce<(U | U[])[]>((acc, item, i) => {\n      if (predicate(item as any, i)) {\n        acc.push(mapper(item as any, i))\n      }\n      return acc\n    }, [])\n    .flat() as U[]\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/getCurrent.ts",
    "content": "import type { Draft } from 'immer'\nimport { current, isDraft } from '../utils/immerImports'\n\nexport function getCurrent<T>(value: T | Draft<T>): T {\n  return (isDraft(value) ? current(value) : value) as T\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/getOrInsert.ts",
    "content": "// Duplicate some of the utils in `/src/utils` to ensure\n// we don't end up dragging in larger chunks of the RTK core\n// into the RTKQ bundle\n\nexport function getOrInsert<K extends object, V>(\n  map: WeakMap<K, V>,\n  key: K,\n  value: V,\n): V\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V\nexport function getOrInsert<K extends object, V>(\n  map: Map<K, V> | WeakMap<K, V>,\n  key: K,\n  value: V,\n): V {\n  if (map.has(key)) return map.get(key) as V\n\n  return map.set(key, value).get(key) as V\n}\n\nexport function getOrInsertComputed<K extends object, V>(\n  map: WeakMap<K, V>,\n  key: K,\n  compute: (key: K) => V,\n): V\nexport function getOrInsertComputed<K, V>(\n  map: Map<K, V>,\n  key: K,\n  compute: (key: K) => V,\n): V\nexport function getOrInsertComputed<K extends object, V>(\n  map: Map<K, V> | WeakMap<K, V>,\n  key: K,\n  compute: (key: K) => V,\n): V {\n  if (map.has(key)) return map.get(key) as V\n\n  return map.set(key, compute(key)).get(key) as V\n}\n\nexport const createNewMap = () => new Map()\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/immerImports.ts",
    "content": "export {\n  current,\n  isDraft,\n  applyPatches,\n  original,\n  isDraftable,\n  produceWithPatches,\n  enablePatches,\n} from 'immer'\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/index.ts",
    "content": "export * from './capitalize'\nexport * from './copyWithStructuralSharing'\nexport * from './countObjectKeys'\nexport * from './filterMap'\nexport * from './isAbsoluteUrl'\nexport * from './isDocumentVisible'\nexport * from './isNotNullish'\nexport * from './isOnline'\nexport * from './isValidUrl'\nexport * from './joinUrls'\nexport * from './getOrInsert'\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/isAbsoluteUrl.ts",
    "content": "/**\n * If either :// or // is present consider it to be an absolute url\n *\n * @param url string\n */\n\nexport function isAbsoluteUrl(url: string) {\n  return new RegExp(`(^|:)//`).test(url)\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/isDocumentVisible.ts",
    "content": "/**\n * Assumes true for a non-browser env, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/Document/visibilityState\n */\nexport function isDocumentVisible(): boolean {\n  // `document` may not exist in non-browser envs (like RN)\n  if (typeof document === 'undefined') {\n    return true\n  }\n  // Match true for visible, prerender, undefined\n  return document.visibilityState !== 'hidden'\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/isNotNullish.ts",
    "content": "export function isNotNullish<T>(v: T | null | undefined): v is T {\n  return v != null\n}\n\nexport function filterNullishValues<T>(map?: Map<any, T>) {\n  return [...(map?.values() ?? [])].filter(isNotNullish) as NonNullable<T>[]\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/isOnline.ts",
    "content": "/**\n * Assumes a browser is online if `undefined`, otherwise makes a best effort\n * @link https://developer.mozilla.org/en-US/docs/Web/API/NavigatorOnLine/onLine\n */\nexport function isOnline() {\n  // We set the default config value in the store, so we'd need to check for this in a SSR env\n  return typeof navigator === 'undefined'\n    ? true\n    : navigator.onLine === undefined\n      ? true\n      : navigator.onLine\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/isValidUrl.ts",
    "content": "export function isValidUrl(string: string) {\n  try {\n    new URL(string)\n  } catch (_) {\n    return false\n  }\n\n  return true\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/joinUrls.ts",
    "content": "import { isAbsoluteUrl } from './isAbsoluteUrl'\n\nconst withoutTrailingSlash = (url: string) => url.replace(/\\/$/, '')\nconst withoutLeadingSlash = (url: string) => url.replace(/^\\//, '')\n\nexport function joinUrls(\n  base: string | undefined,\n  url: string | undefined,\n): string {\n  if (!base) {\n    return url!\n  }\n  if (!url) {\n    return base\n  }\n\n  if (isAbsoluteUrl(url)) {\n    return url\n  }\n\n  const delimiter = base.endsWith('/') || !url.startsWith('?') ? '/' : ''\n  base = withoutTrailingSlash(base)\n  url = withoutLeadingSlash(url)\n\n  return `${base}${delimiter}${url}`\n}\n"
  },
  {
    "path": "packages/toolkit/src/query/utils/signals.ts",
    "content": "// AbortSignal.timeout() is currently baseline 2024\nexport const timeoutSignal = (milliseconds: number) => {\n  const abortController = new AbortController()\n  setTimeout(() => {\n    const message = 'signal timed out'\n    const name = 'TimeoutError'\n    abortController.abort(\n      // some environments (React Native, Node) don't have DOMException\n      typeof DOMException !== 'undefined'\n        ? new DOMException(message, name)\n        : Object.assign(new Error(message), { name }),\n    )\n  }, milliseconds)\n  return abortController.signal\n}\n\n// AbortSignal.any() is currently baseline 2024\nexport const anySignal = (...signals: AbortSignal[]) => {\n  // if any are already aborted, return an already aborted signal\n  for (const signal of signals)\n    if (signal.aborted) return AbortSignal.abort(signal.reason)\n\n  // otherwise, create a new signal that aborts when any of the given signals abort\n  const abortController = new AbortController()\n  for (const signal of signals) {\n    signal.addEventListener(\n      'abort',\n      () => abortController.abort(signal.reason),\n      { signal: abortController.signal, once: true },\n    )\n  }\n  return abortController.signal\n}\n"
  },
  {
    "path": "packages/toolkit/src/react/index.ts",
    "content": "// This must remain here so that the `mangleErrors.cjs` build script\n// does not have to import this into each source file it rewrites.\nimport { formatProdErrorMessage } from '@reduxjs/toolkit'\nexport * from '@reduxjs/toolkit'\n\nexport { createDynamicMiddleware } from '../dynamicMiddleware/react'\nexport type { CreateDispatchWithMiddlewareHook } from '../dynamicMiddleware/react/index'\n"
  },
  {
    "path": "packages/toolkit/src/reduxImports.ts",
    "content": "export {\n  createStore,\n  combineReducers,\n  applyMiddleware,\n  compose,\n  isPlainObject,\n  isAction,\n} from 'redux'\n"
  },
  {
    "path": "packages/toolkit/src/reselectImports.ts",
    "content": "export { createSelectorCreator, weakMapMemoize } from 'reselect'\n"
  },
  {
    "path": "packages/toolkit/src/serializableStateInvariantMiddleware.ts",
    "content": "import type { Middleware } from 'redux'\nimport { isAction, isPlainObject } from './reduxImports'\nimport { getTimeMeasureUtils } from './utils'\n\n/**\n * Returns true if the passed value is \"plain\", i.e. a value that is either\n * directly JSON-serializable (boolean, number, string, array, plain object)\n * or `undefined`.\n *\n * @param val The value to check.\n *\n * @public\n */\nexport function isPlain(val: any) {\n  const type = typeof val\n  return (\n    val == null ||\n    type === 'string' ||\n    type === 'boolean' ||\n    type === 'number' ||\n    Array.isArray(val) ||\n    isPlainObject(val)\n  )\n}\n\ninterface NonSerializableValue {\n  keyPath: string\n  value: unknown\n}\n\nexport type IgnorePaths = readonly (string | RegExp)[]\n\n/**\n * @public\n */\nexport function findNonSerializableValue(\n  value: unknown,\n  path: string = '',\n  isSerializable: (value: unknown) => boolean = isPlain,\n  getEntries?: (value: unknown) => [string, any][],\n  ignoredPaths: IgnorePaths = [],\n  cache?: WeakSet<object>,\n): NonSerializableValue | false {\n  let foundNestedSerializable: NonSerializableValue | false\n\n  if (!isSerializable(value)) {\n    return {\n      keyPath: path || '<root>',\n      value: value,\n    }\n  }\n\n  if (typeof value !== 'object' || value === null) {\n    return false\n  }\n\n  if (cache?.has(value)) return false\n\n  const entries = getEntries != null ? getEntries(value) : Object.entries(value)\n\n  const hasIgnoredPaths = ignoredPaths.length > 0\n\n  for (const [key, nestedValue] of entries) {\n    const nestedPath = path ? path + '.' + key : key\n\n    if (hasIgnoredPaths) {\n      const hasMatches = ignoredPaths.some((ignored) => {\n        if (ignored instanceof RegExp) {\n          return ignored.test(nestedPath)\n        }\n        return nestedPath === ignored\n      })\n      if (hasMatches) {\n        continue\n      }\n    }\n\n    if (!isSerializable(nestedValue)) {\n      return {\n        keyPath: nestedPath,\n        value: nestedValue,\n      }\n    }\n\n    if (typeof nestedValue === 'object') {\n      foundNestedSerializable = findNonSerializableValue(\n        nestedValue,\n        nestedPath,\n        isSerializable,\n        getEntries,\n        ignoredPaths,\n        cache,\n      )\n\n      if (foundNestedSerializable) {\n        return foundNestedSerializable\n      }\n    }\n  }\n\n  if (cache && isNestedFrozen(value)) cache.add(value)\n\n  return false\n}\n\nexport function isNestedFrozen(value: object) {\n  if (!Object.isFrozen(value)) return false\n\n  for (const nestedValue of Object.values(value)) {\n    if (typeof nestedValue !== 'object' || nestedValue === null) continue\n\n    if (!isNestedFrozen(nestedValue)) return false\n  }\n\n  return true\n}\n\n/**\n * Options for `createSerializableStateInvariantMiddleware()`.\n *\n * @public\n */\nexport interface SerializableStateInvariantMiddlewareOptions {\n  /**\n   * The function to check if a value is considered serializable. This\n   * function is applied recursively to every value contained in the\n   * state. Defaults to `isPlain()`.\n   */\n  isSerializable?: (value: any) => boolean\n  /**\n   * The function that will be used to retrieve entries from each\n   * value.  If unspecified, `Object.entries` will be used. Defaults\n   * to `undefined`.\n   */\n  getEntries?: (value: any) => [string, any][]\n\n  /**\n   * An array of action types to ignore when checking for serializability.\n   * Defaults to []\n   */\n  ignoredActions?: string[]\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to\n   * ['meta.arg', 'meta.baseQueryMeta']\n   */\n  ignoredActionPaths?: (string | RegExp)[]\n\n  /**\n   * An array of dot-separated path strings or regular expressions to ignore\n   * when checking for serializability, Defaults to []\n   */\n  ignoredPaths?: (string | RegExp)[]\n  /**\n   * Execution time warning threshold. If the middleware takes longer\n   * than `warnAfter` ms, a warning will be displayed in the console.\n   * Defaults to 32ms.\n   */\n  warnAfter?: number\n\n  /**\n   * Opt out of checking state. When set to `true`, other state-related params will be ignored.\n   */\n  ignoreState?: boolean\n\n  /**\n   * Opt out of checking actions. When set to `true`, other action-related params will be ignored.\n   */\n  ignoreActions?: boolean\n\n  /**\n   * Opt out of caching the results. The cache uses a WeakSet and speeds up repeated checking processes.\n   * The cache is automatically disabled if no browser support for WeakSet is present.\n   */\n  disableCache?: boolean\n}\n\n/**\n * Creates a middleware that, after every state change, checks if the new\n * state is serializable. If a non-serializable value is found within the\n * state, an error is printed to the console.\n *\n * @param options Middleware options.\n *\n * @public\n */\nexport function createSerializableStateInvariantMiddleware(\n  options: SerializableStateInvariantMiddlewareOptions = {},\n): Middleware {\n  if (process.env.NODE_ENV === 'production') {\n    return () => (next) => (action) => next(action)\n  } else {\n    const {\n      isSerializable = isPlain,\n      getEntries,\n      ignoredActions = [],\n      ignoredActionPaths = ['meta.arg', 'meta.baseQueryMeta'],\n      ignoredPaths = [],\n      warnAfter = 32,\n      ignoreState = false,\n      ignoreActions = false,\n      disableCache = false,\n    } = options\n\n    const cache: WeakSet<object> | undefined =\n      !disableCache && WeakSet ? new WeakSet() : undefined\n\n    return (storeAPI) => (next) => (action) => {\n      if (!isAction(action)) {\n        return next(action)\n      }\n\n      const result = next(action)\n\n      const measureUtils = getTimeMeasureUtils(\n        warnAfter,\n        'SerializableStateInvariantMiddleware',\n      )\n\n      if (\n        !ignoreActions &&\n        !(\n          ignoredActions.length &&\n          ignoredActions.indexOf(action.type as any) !== -1\n        )\n      ) {\n        measureUtils.measureTime(() => {\n          const foundActionNonSerializableValue = findNonSerializableValue(\n            action,\n            '',\n            isSerializable,\n            getEntries,\n            ignoredActionPaths,\n            cache,\n          )\n\n          if (foundActionNonSerializableValue) {\n            const { keyPath, value } = foundActionNonSerializableValue\n\n            console.error(\n              `A non-serializable value was detected in an action, in the path: \\`${keyPath}\\`. Value:`,\n              value,\n              '\\nTake a look at the logic that dispatched this action: ',\n              action,\n              '\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)',\n              '\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)',\n            )\n          }\n        })\n      }\n\n      if (!ignoreState) {\n        measureUtils.measureTime(() => {\n          const state = storeAPI.getState()\n\n          const foundStateNonSerializableValue = findNonSerializableValue(\n            state,\n            '',\n            isSerializable,\n            getEntries,\n            ignoredPaths,\n            cache,\n          )\n\n          if (foundStateNonSerializableValue) {\n            const { keyPath, value } = foundStateNonSerializableValue\n\n            console.error(\n              `A non-serializable value was detected in the state, in the path: \\`${keyPath}\\`. Value:`,\n              value,\n              `\nTake a look at the reducer(s) handling this action type: ${action.type}.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,\n            )\n          }\n        })\n\n        measureUtils.warnIfExceeded()\n      }\n\n      return result\n    }\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/tests/Tuple.test-d.ts",
    "content": "import { Tuple } from '@reduxjs/toolkit'\n\ndescribe('type tests', () => {\n  test('compatibility is checked between described types', () => {\n    const stringTuple = new Tuple('')\n\n    expectTypeOf(stringTuple).toEqualTypeOf<Tuple<[string]>>()\n\n    expectTypeOf(stringTuple).toExtend<Tuple<string[]>>()\n\n    expectTypeOf(stringTuple).not.toExtend<Tuple<[string, string]>>()\n\n    const numberTuple = new Tuple(0, 1)\n\n    expectTypeOf(numberTuple).not.toExtend<Tuple<string[]>>()\n  })\n\n  test('concat is inferred properly', () => {\n    const singleString = new Tuple('')\n\n    expectTypeOf(singleString).toEqualTypeOf<Tuple<[string]>>()\n\n    expectTypeOf(singleString.concat('')).toEqualTypeOf<\n      Tuple<[string, string]>\n    >()\n\n    expectTypeOf(singleString.concat([''] as const)).toExtend<\n      Tuple<[string, string]>\n    >()\n  })\n\n  test('prepend is inferred properly', () => {\n    const singleString = new Tuple('')\n\n    expectTypeOf(singleString).toEqualTypeOf<Tuple<[string]>>()\n\n    expectTypeOf(singleString.prepend('')).toEqualTypeOf<\n      Tuple<[string, string]>\n    >()\n\n    expectTypeOf(singleString.prepend([''] as const)).toExtend<\n      Tuple<[string, string]>\n    >()\n  })\n\n  test('push must match existing items', () => {\n    const stringTuple = new Tuple('')\n\n    expectTypeOf(stringTuple.push).toBeCallableWith('')\n\n    expectTypeOf(stringTuple.push).parameter(0).not.toBeNumber()\n  })\n\n  test('Tuples can be combined', () => {\n    const stringTuple = new Tuple('')\n\n    const numberTuple = new Tuple(0, 1)\n\n    expectTypeOf(stringTuple.concat(numberTuple)).toEqualTypeOf<\n      Tuple<[string, number, number]>\n    >()\n\n    expectTypeOf(stringTuple.prepend(numberTuple)).toEqualTypeOf<\n      Tuple<[number, number, string]>\n    >()\n\n    expectTypeOf(numberTuple.concat(stringTuple)).toEqualTypeOf<\n      Tuple<[number, number, string]>\n    >()\n\n    expectTypeOf(numberTuple.prepend(stringTuple)).toEqualTypeOf<\n      Tuple<[string, number, number]>\n    >()\n\n    expectTypeOf(stringTuple.prepend(numberTuple)).not.toExtend<\n      Tuple<[string, number, number]>\n    >()\n\n    expectTypeOf(stringTuple.concat(numberTuple)).not.toExtend<\n      Tuple<[number, number, string]>\n    >()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/actionCreatorInvariantMiddleware.test.ts",
    "content": "import { getMessage } from '@internal/actionCreatorInvariantMiddleware'\nimport type {\n  ActionCreatorInvariantMiddlewareOptions,\n  MiddlewareAPI,\n} from '@reduxjs/toolkit'\nimport {\n  createAction,\n  createActionCreatorInvariantMiddleware,\n} from '@reduxjs/toolkit'\n\ndescribe('createActionCreatorInvariantMiddleware', () => {\n  const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})\n\n  afterEach(() => {\n    consoleSpy.mockClear()\n  })\n  afterAll(() => {\n    consoleSpy.mockRestore()\n  })\n\n  const dummyAction = createAction('aSlice/anAction')\n\n  it('sends the action through the middleware chain', () => {\n    const next = vi.fn()\n    const dispatch = createActionCreatorInvariantMiddleware()(\n      {} as MiddlewareAPI,\n    )(next)\n    dispatch({ type: 'SOME_ACTION' })\n\n    expect(next).toHaveBeenCalledWith({\n      type: 'SOME_ACTION',\n    })\n  })\n\n  const makeActionTester = (\n    options?: ActionCreatorInvariantMiddlewareOptions,\n  ) =>\n    createActionCreatorInvariantMiddleware(options)({} as MiddlewareAPI)(\n      (action) => action,\n    )\n\n  it('logs a warning to console if an action creator is mistakenly dispatched', () => {\n    const testAction = makeActionTester()\n\n    testAction(dummyAction())\n\n    expect(consoleSpy).not.toHaveBeenCalled()\n\n    testAction(dummyAction)\n\n    expect(consoleSpy).toHaveBeenLastCalledWith(getMessage(dummyAction.type))\n  })\n\n  it('allows passing a custom predicate', () => {\n    let predicateCalled = false\n    const testAction = makeActionTester({\n      isActionCreator(action): action is Function {\n        predicateCalled = true\n        return false\n      },\n    })\n    testAction(dummyAction())\n    expect(predicateCalled).toBe(true)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/autoBatchEnhancer.test.ts",
    "content": "import type { AutoBatchOptions } from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createSlice,\n  prepareAutoBatched,\n} from '@reduxjs/toolkit'\nimport { debounce } from 'lodash'\nimport { delay } from '../utils'\n\ninterface CounterState {\n  value: number\n}\n\nconst counterSlice = createSlice({\n  name: 'counter',\n  initialState: { value: 0 } as CounterState,\n  reducers: {\n    incrementBatched: {\n      // Batched, low-priority\n      reducer(state) {\n        state.value += 1\n      },\n      prepare: prepareAutoBatched<void>(),\n    },\n    // Not batched, normal priority\n    decrementUnbatched(state) {\n      state.value -= 1\n    },\n  },\n})\nconst { incrementBatched, decrementUnbatched } = counterSlice.actions\n\nconst makeStore = (autoBatchOptions?: AutoBatchOptions) => {\n  return configureStore({\n    reducer: counterSlice.reducer,\n    enhancers: (getDefaultEnhancers) =>\n      getDefaultEnhancers({\n        autoBatch: autoBatchOptions,\n      }),\n  })\n}\n\nlet store: ReturnType<typeof makeStore>\n\nlet subscriptionNotifications = 0\n\nconst cases: AutoBatchOptions[] = [\n  { type: 'tick' },\n  { type: 'raf' },\n  { type: 'timer', timeout: 0 },\n  { type: 'timer', timeout: 10 },\n  { type: 'timer', timeout: 20 },\n  {\n    type: 'callback',\n    queueNotification: debounce((notify: () => void) => {\n      notify()\n    }, 5),\n  },\n]\n\ndescribe.each(cases)('autoBatchEnhancer: %j', (autoBatchOptions) => {\n  beforeEach(() => {\n    subscriptionNotifications = 0\n    store = makeStore(autoBatchOptions)\n\n    store.subscribe(() => {\n      subscriptionNotifications++\n    })\n  })\n  test('Does not alter normal subscription notification behavior', async () => {\n    store.dispatch(decrementUnbatched())\n    expect(subscriptionNotifications).toBe(1)\n    store.dispatch(decrementUnbatched())\n    expect(subscriptionNotifications).toBe(2)\n    store.dispatch(decrementUnbatched())\n    expect(subscriptionNotifications).toBe(3)\n    store.dispatch(decrementUnbatched())\n\n    await delay(25)\n\n    expect(subscriptionNotifications).toBe(4)\n  })\n\n  test('Only notifies once if several batched actions are dispatched in a row', async () => {\n    store.dispatch(incrementBatched())\n    expect(subscriptionNotifications).toBe(0)\n    store.dispatch(incrementBatched())\n    expect(subscriptionNotifications).toBe(0)\n    store.dispatch(incrementBatched())\n    expect(subscriptionNotifications).toBe(0)\n    store.dispatch(incrementBatched())\n\n    await delay(25)\n\n    expect(subscriptionNotifications).toBe(1)\n  })\n\n  test('Notifies immediately if a non-batched action is dispatched', async () => {\n    store.dispatch(incrementBatched())\n    expect(subscriptionNotifications).toBe(0)\n    store.dispatch(incrementBatched())\n    expect(subscriptionNotifications).toBe(0)\n    store.dispatch(decrementUnbatched())\n    expect(subscriptionNotifications).toBe(1)\n    store.dispatch(incrementBatched())\n\n    await delay(25)\n\n    expect(subscriptionNotifications).toBe(2)\n  })\n\n  test('Does not notify at end of tick if last action was normal priority', async () => {\n    store.dispatch(incrementBatched())\n    expect(subscriptionNotifications).toBe(0)\n    store.dispatch(incrementBatched())\n    expect(subscriptionNotifications).toBe(0)\n    store.dispatch(decrementUnbatched())\n    expect(subscriptionNotifications).toBe(1)\n    store.dispatch(incrementBatched())\n    store.dispatch(decrementUnbatched())\n    expect(subscriptionNotifications).toBe(2)\n    store.dispatch(decrementUnbatched())\n    expect(subscriptionNotifications).toBe(3)\n\n    await delay(25)\n\n    expect(subscriptionNotifications).toBe(3)\n  })\n})\n\ndescribe.each(cases)(\n  'autoBatchEnhancer with fake timers: %j',\n  (autoBatchOptions) => {\n    beforeAll(() => {\n      vitest.useFakeTimers({\n        toFake: ['setTimeout', 'queueMicrotask', 'requestAnimationFrame'],\n      })\n    })\n    afterAll(() => {\n      vitest.useRealTimers()\n    })\n    beforeEach(() => {\n      subscriptionNotifications = 0\n      store = makeStore(autoBatchOptions)\n\n      store.subscribe(() => {\n        subscriptionNotifications++\n      })\n    })\n    test('Does not alter normal subscription notification behavior', () => {\n      store.dispatch(decrementUnbatched())\n      expect(subscriptionNotifications).toBe(1)\n      store.dispatch(decrementUnbatched())\n      expect(subscriptionNotifications).toBe(2)\n      store.dispatch(decrementUnbatched())\n      expect(subscriptionNotifications).toBe(3)\n      store.dispatch(decrementUnbatched())\n\n      vitest.runAllTimers()\n\n      expect(subscriptionNotifications).toBe(4)\n    })\n\n    test('Only notifies once if several batched actions are dispatched in a row', () => {\n      store.dispatch(incrementBatched())\n      expect(subscriptionNotifications).toBe(0)\n      store.dispatch(incrementBatched())\n      expect(subscriptionNotifications).toBe(0)\n      store.dispatch(incrementBatched())\n      expect(subscriptionNotifications).toBe(0)\n      store.dispatch(incrementBatched())\n\n      vitest.runAllTimers()\n\n      expect(subscriptionNotifications).toBe(1)\n    })\n\n    test('Notifies immediately if a non-batched action is dispatched', () => {\n      store.dispatch(incrementBatched())\n      expect(subscriptionNotifications).toBe(0)\n      store.dispatch(incrementBatched())\n      expect(subscriptionNotifications).toBe(0)\n      store.dispatch(decrementUnbatched())\n      expect(subscriptionNotifications).toBe(1)\n      store.dispatch(incrementBatched())\n\n      vitest.runAllTimers()\n\n      expect(subscriptionNotifications).toBe(2)\n    })\n\n    test('Does not notify at end of tick if last action was normal priority', () => {\n      store.dispatch(incrementBatched())\n      expect(subscriptionNotifications).toBe(0)\n      store.dispatch(incrementBatched())\n      expect(subscriptionNotifications).toBe(0)\n      store.dispatch(decrementUnbatched())\n      expect(subscriptionNotifications).toBe(1)\n      store.dispatch(incrementBatched())\n      store.dispatch(decrementUnbatched())\n      expect(subscriptionNotifications).toBe(2)\n      store.dispatch(decrementUnbatched())\n      expect(subscriptionNotifications).toBe(3)\n\n      vitest.runAllTimers()\n\n      expect(subscriptionNotifications).toBe(3)\n    })\n  },\n)\n"
  },
  {
    "path": "packages/toolkit/src/tests/combineSlices.test-d.ts",
    "content": "import type {\n  Action,\n  Reducer,\n  Slice,\n  WithSlice,\n  WithSlicePreloadedState,\n} from '@reduxjs/toolkit'\nimport { combineSlices } from '@reduxjs/toolkit'\nimport { createApi, fetchBaseQuery } from '@reduxjs/toolkit/query'\n\ndeclare const stringSlice: Slice<string, {}, 'string'>\n\ndeclare const numberSlice: Slice<number, {}, 'number'>\n\ndeclare const booleanReducer: Reducer<boolean>\n\ndeclare const mixedReducer: Reducer<string, Action, number>\n\ndeclare const mixedSliceLike: {\n  reducerPath: 'mixedSlice'\n  reducer: typeof mixedReducer\n}\n\nconst exampleApi = createApi({\n  baseQuery: fetchBaseQuery(),\n  endpoints: (build) => ({\n    getThing: build.query({\n      query: () => '',\n    }),\n  }),\n})\n\ntype ExampleApiState = ReturnType<typeof exampleApi.reducer>\n\ndescribe('type tests', () => {\n  test('combineSlices correctly combines static state', () => {\n    const rootReducer = combineSlices(\n      stringSlice,\n      numberSlice,\n      exampleApi,\n      {\n        boolean: booleanReducer,\n        mixed: mixedReducer,\n      },\n      mixedSliceLike,\n    )\n\n    expectTypeOf(rootReducer(undefined, { type: '' })).toEqualTypeOf<{\n      string: string\n      number: number\n      boolean: boolean\n      api: ExampleApiState\n      mixed: string\n      mixedSlice: string\n    }>()\n\n    // test for correct preloaded state handling\n    expectTypeOf(rootReducer).toBeCallableWith(\n      { mixed: 9, mixedSlice: 9 },\n      { type: '' },\n    )\n  })\n\n  test('combineSlices allows passing no initial reducers', () => {\n    const rootReducer = combineSlices()\n\n    expectTypeOf(rootReducer(undefined, { type: '' })).toEqualTypeOf<{}>()\n\n    const declaredLazy =\n      combineSlices().withLazyLoadedSlices<WithSlice<typeof numberSlice>>()\n\n    expectTypeOf(declaredLazy(undefined, { type: '' })).toEqualTypeOf<{\n      number?: number\n    }>()\n  })\n\n  test('withLazyLoadedSlices adds partial to state', () => {\n    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<\n      WithSlice<typeof numberSlice> & WithSlice<typeof exampleApi>\n    >()\n\n    expectTypeOf(rootReducer(undefined, { type: '' }).number).toEqualTypeOf<\n      number | undefined\n    >()\n\n    expectTypeOf(rootReducer(undefined, { type: '' }).api).toEqualTypeOf<\n      ExampleApiState | undefined\n    >()\n  })\n\n  test('inject marks injected keys as required', () => {\n    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<\n      WithSlice<typeof numberSlice> &\n        WithSlice<typeof exampleApi> & { boolean: boolean } & WithSlice<\n          typeof mixedSliceLike\n        > &\n        WithSlice<{\n          reducerPath: 'mixedReducer'\n          reducer: typeof mixedReducer\n        }>,\n      WithSlicePreloadedState<typeof numberSlice> &\n        WithSlicePreloadedState<typeof exampleApi> & {\n          boolean: boolean\n        } & WithSlicePreloadedState<typeof mixedSliceLike> &\n        WithSlicePreloadedState<{\n          reducerPath: 'mixedReducer'\n          reducer: typeof mixedReducer\n        }>\n    >()\n\n    expectTypeOf(rootReducer(undefined, { type: '' }).number).toEqualTypeOf<\n      number | undefined\n    >()\n\n    expectTypeOf(rootReducer(undefined, { type: '' }).boolean).toEqualTypeOf<\n      boolean | undefined\n    >()\n\n    expectTypeOf(rootReducer(undefined, { type: '' }).api).toEqualTypeOf<\n      ExampleApiState | undefined\n    >()\n\n    expectTypeOf(rootReducer(undefined, { type: '' }).mixedSlice).toEqualTypeOf<\n      string | undefined\n    >()\n\n    expectTypeOf(\n      rootReducer(undefined, { type: '' }).mixedReducer,\n    ).toEqualTypeOf<string | undefined>()\n\n    const withNumber = rootReducer.inject(numberSlice)\n\n    expectTypeOf(withNumber(undefined, { type: '' }).number).toBeNumber()\n\n    const withBool = rootReducer.inject({\n      reducerPath: 'boolean' as const,\n      reducer: booleanReducer,\n    })\n\n    expectTypeOf(withBool(undefined, { type: '' }).boolean).toBeBoolean()\n\n    const withApi = rootReducer.inject(exampleApi)\n\n    expectTypeOf(\n      withApi(undefined, { type: '' }).api,\n    ).toEqualTypeOf<ExampleApiState>()\n\n    const withMixedSlice = rootReducer.inject(mixedSliceLike)\n\n    expectTypeOf(\n      withMixedSlice(undefined, { type: '' }).mixedSlice,\n    ).toBeString()\n\n    const withMixedReducer = rootReducer.inject({\n      reducerPath: 'mixedReducer',\n      reducer: mixedReducer,\n    })\n\n    expectTypeOf(\n      withMixedReducer(undefined, { type: '' }).mixedReducer,\n    ).toBeString()\n  })\n\n  test('selector() allows defining selectors with injected reducers defined', () => {\n    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<\n      WithSlice<typeof numberSlice> & { boolean: boolean }\n    >()\n\n    type RootState = ReturnType<typeof rootReducer>\n\n    const withoutInjection = rootReducer.selector(\n      (state: RootState) => state.number,\n    )\n\n    expectTypeOf(\n      withoutInjection(rootReducer(undefined, { type: '' })),\n    ).toEqualTypeOf<number | undefined>()\n\n    const withInjection = rootReducer\n      .inject(numberSlice)\n      .selector((state) => state.number)\n\n    expectTypeOf(\n      withInjection(rootReducer(undefined, { type: '' })),\n    ).toBeNumber()\n  })\n\n  test('selector() passes arguments through', () => {\n    const rootReducer = combineSlices(stringSlice).withLazyLoadedSlices<\n      WithSlice<typeof numberSlice> & { boolean: boolean }\n    >()\n\n    const selector = rootReducer\n      .inject(numberSlice)\n      .selector((state, num: number) => state.number)\n\n    const state = rootReducer(undefined, { type: '' })\n\n    expectTypeOf(selector).toBeCallableWith(state, 0)\n\n    // required argument\n    expectTypeOf(selector).parameters.not.toExtend<[typeof state]>()\n\n    // number not string\n    expectTypeOf(selector).parameters.not.toExtend<[typeof state, string]>()\n  })\n\n  test('nested calls inferred correctly', () => {\n    const innerReducer =\n      combineSlices(stringSlice).withLazyLoadedSlices<\n        WithSlice<typeof numberSlice>\n      >()\n\n    const innerSelector = innerReducer.inject(numberSlice).selector(\n      (state) => state.number,\n      (rootState: RootState) => rootState.inner,\n    )\n\n    const outerReducer = combineSlices({ inner: innerReducer })\n\n    type RootState = ReturnType<typeof outerReducer>\n\n    expectTypeOf(outerReducer(undefined, { type: '' })).toMatchObjectType<{\n      inner: { string: string }\n    }>()\n\n    expectTypeOf(\n      innerSelector(outerReducer(undefined, { type: '' })),\n    ).toBeNumber()\n  })\n\n  test('selector errors if selectorFn and selectState are mismatched', () => {\n    const combinedReducer =\n      combineSlices(stringSlice).withLazyLoadedSlices<\n        WithSlice<typeof numberSlice>\n      >()\n\n    const outerReducer = combineSlices({ inner: combinedReducer })\n\n    type RootState = ReturnType<typeof outerReducer>\n\n    combinedReducer.selector(\n      (state) => state.number,\n      // @ts-expect-error wrong state returned\n      (rootState: RootState) => rootState.inner.number,\n    )\n\n    combinedReducer.selector(\n      (state, num: number) => state.number,\n      // @ts-expect-error wrong arguments\n      (rootState: RootState, str: string) => rootState.inner,\n    )\n\n    combinedReducer.selector(\n      (state, num: number) => state.number,\n      (rootState: RootState) => rootState.inner,\n    )\n\n    // TODO: see if there's a way of making this work\n    // probably a rare case so not the end of the world if not\n    combinedReducer.selector(\n      (state) => state.number,\n      // @ts-ignore\n      (rootState: RootState, num: number) => rootState.inner,\n    )\n  })\n\n  test('correct type of state is inferred when not declared via `withLazyLoadedSlices`', () => {\n    // Related to https://github.com/reduxjs/redux-toolkit/issues/4171\n\n    const combinedReducer = combineSlices(stringSlice)\n\n    const withNumber = combinedReducer.inject(numberSlice)\n\n    expectTypeOf(withNumber).returns.toEqualTypeOf<{\n      string: string\n      number: number\n    }>()\n\n    expectTypeOf(withNumber(undefined, { type: '' }).number).toBeNumber()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/combineSlices.test.ts",
    "content": "import type { WithSlice } from '@reduxjs/toolkit'\nimport {\n  combineSlices,\n  createAction,\n  createReducer,\n  createSlice,\n} from '@reduxjs/toolkit'\n\nconst dummyAction = createAction<void>('dummy')\n\nconst stringSlice = createSlice({\n  name: 'string',\n  initialState: '',\n  reducers: {},\n})\n\nconst numberSlice = createSlice({\n  name: 'number',\n  initialState: 0,\n  reducers: {},\n})\n\nconst booleanReducer = createReducer(false, () => {})\n\nconst counterReducer = createSlice({\n  name: 'counter',\n  initialState: () => ({ value: 0 }),\n  reducers: {},\n})\n\n// mimic - we can't use RTKQ here directly\nconst api = {\n  reducerPath: 'api' as const,\n  reducer: createReducer(\n    {\n      queries: {},\n      mutations: {},\n      provided: {},\n      subscriptions: {},\n      config: {\n        reducerPath: 'api',\n        invalidationBehavior: 'delayed',\n        online: false,\n        focused: false,\n        keepUnusedDataFor: 60,\n        middlewareRegistered: false,\n        refetchOnMountOrArgChange: false,\n        refetchOnReconnect: false,\n        refetchOnFocus: false,\n      },\n    },\n    () => {},\n  ),\n}\n\ndescribe('combineSlices', () => {\n  it('calls combineReducers to combine static slices/reducers', () => {\n    const combinedReducer = combineSlices(\n      stringSlice,\n      {\n        num: numberSlice.reducer,\n        boolean: booleanReducer,\n      },\n      api,\n    )\n    expect(combinedReducer(undefined, dummyAction())).toEqual({\n      string: stringSlice.getInitialState(),\n      num: numberSlice.getInitialState(),\n      boolean: booleanReducer.getInitialState(),\n      api: api.reducer.getInitialState(),\n    })\n  })\n  it('allows passing no initial reducers', () => {\n    const combinedReducer = combineSlices()\n\n    const result = combinedReducer(undefined, dummyAction())\n\n    expect(result).toEqual({})\n\n    // no-op if we have no reducers yet\n    expect(combinedReducer(result, dummyAction())).toBe(result)\n  })\n  describe('injects', () => {\n    beforeEach(() => {\n      vi.stubEnv('NODE_ENV', 'development')\n\n      return vi.unstubAllEnvs\n    })\n\n    it('injects slice', () => {\n      const combinedReducer =\n        combineSlices(stringSlice).withLazyLoadedSlices<\n          WithSlice<typeof numberSlice>\n        >()\n\n      expect(combinedReducer(undefined, dummyAction()).number).toBe(undefined)\n\n      const injectedReducer = combinedReducer.inject(numberSlice)\n\n      expect(injectedReducer(undefined, dummyAction()).number).toBe(\n        numberSlice.getInitialState(),\n      )\n    })\n    it('logs error when same name is used for different reducers', () => {\n      const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})\n      const combinedReducer = combineSlices(stringSlice).withLazyLoadedSlices<{\n        boolean: boolean\n      }>()\n\n      combinedReducer.inject({\n        reducerPath: 'boolean' as const,\n        reducer: booleanReducer,\n      })\n\n      combinedReducer.inject({\n        reducerPath: 'boolean' as const,\n        reducer: booleanReducer,\n      })\n\n      expect(consoleSpy).not.toHaveBeenCalled()\n\n      combinedReducer.inject({\n        reducerPath: 'boolean' as const,\n        // @ts-expect-error wrong reducer\n        reducer: stringSlice.reducer,\n      })\n\n      expect(consoleSpy).toHaveBeenCalledWith(\n        `called \\`inject\\` to override already-existing reducer boolean without specifying \\`overrideExisting: true\\``,\n      )\n      consoleSpy.mockRestore()\n    })\n    it('allows replacement of reducers if overrideExisting is true', () => {\n      const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})\n      const combinedReducer = combineSlices(stringSlice).withLazyLoadedSlices<\n        WithSlice<typeof numberSlice> &\n          WithSlice<typeof api> & { boolean: boolean }\n      >()\n\n      combinedReducer.inject(numberSlice)\n\n      combinedReducer.inject(\n        { reducerPath: 'number' as const, reducer: () => 0 },\n        { overrideExisting: true },\n      )\n\n      expect(consoleSpy).not.toHaveBeenCalled()\n    })\n  })\n  describe('selector', () => {\n    const combinedReducer = combineSlices(stringSlice).withLazyLoadedSlices<{\n      boolean: boolean\n      counter: { value: number }\n    }>()\n\n    const uninjectedState = combinedReducer(undefined, dummyAction())\n\n    const injectedReducer = combinedReducer.inject({\n      reducerPath: 'boolean' as const,\n      reducer: booleanReducer,\n    })\n\n    it('ensures state is defined in selector even if action has not been dispatched', () => {\n      expect(uninjectedState.boolean).toBe(undefined)\n\n      const selectBoolean = injectedReducer.selector((state) => state.boolean)\n\n      expect(selectBoolean(uninjectedState)).toBe(\n        booleanReducer.getInitialState(),\n      )\n    })\n    it('exposes original to allow for logging', () => {\n      const selectBoolean = injectedReducer.selector(\n        (state) => injectedReducer.selector.original(state).boolean,\n      )\n      expect(selectBoolean(uninjectedState)).toBe(undefined)\n    })\n    it('throws if original is called on something other than state proxy', () => {\n      expect(() => injectedReducer.selector.original({} as any)).toThrow(\n        'original must be used on state Proxy',\n      )\n    })\n    it('allows passing a selectState selector, to handle nested state', () => {\n      const wrappedReducer = combineSlices({\n        inner: combinedReducer,\n      })\n\n      type RootState = ReturnType<typeof wrappedReducer>\n\n      const selector = injectedReducer.selector(\n        (state) => state.boolean,\n        (rootState: RootState) => rootState.inner,\n      )\n\n      expect(selector(wrappedReducer(undefined, dummyAction()))).toBe(\n        booleanReducer.getInitialState(),\n      )\n    })\n    it('caches initial state', () => {\n      const beforeInject = combinedReducer(undefined, dummyAction())\n      const injectedReducer = combinedReducer.inject(counterReducer)\n      const selectCounter = injectedReducer.selector((state) => state.counter)\n      const counter = selectCounter(beforeInject)\n      expect(counter).toBe(selectCounter(beforeInject))\n\n      injectedReducer.inject(\n        { reducerPath: 'counter', reducer: () => ({ value: 0 }) },\n        { overrideExisting: true },\n      )\n      const counter2 = selectCounter(beforeInject)\n      expect(counter2).not.toBe(counter)\n      expect(counter2).toBe(selectCounter(beforeInject))\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/combinedTest.test.ts",
    "content": "import type { BookModel } from '@internal/entities/tests/fixtures/book'\nimport type { EntityAdapter, PayloadAction } from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createAction,\n  createAsyncThunk,\n  createEntityAdapter,\n  createSlice,\n} from '@reduxjs/toolkit'\n\ndescribe('Combined entity slice', () => {\n  let adapter: EntityAdapter<BookModel, string>\n\n  beforeEach(() => {\n    adapter = createEntityAdapter({\n      selectId: (book: BookModel) => book.id,\n      sortComparer: (a, b) => a.title.localeCompare(b.title),\n    })\n  })\n\n  it('Entity and async features all works together', async () => {\n    const upsertBook = createAction<BookModel>('otherBooks/upsert')\n\n    type BooksState = ReturnType<typeof adapter.getInitialState> & {\n      loading: 'initial' | 'pending' | 'finished' | 'failed'\n      lastRequestId: string | null\n    }\n\n    const initialState: BooksState = adapter.getInitialState({\n      loading: 'initial',\n      lastRequestId: null,\n    })\n\n    const fakeBooks: BookModel[] = [\n      { id: 'b', title: 'Second' },\n      { id: 'a', title: 'First' },\n    ]\n\n    const fetchBooksTAC = createAsyncThunk<\n      BookModel[],\n      void,\n      {\n        state: { books: BooksState }\n      }\n    >(\n      'books/fetch',\n      async (arg, { getState, dispatch, extra, requestId, signal }) => {\n        const state = getState()\n        return fakeBooks\n      },\n    )\n\n    const booksSlice = createSlice({\n      name: 'books',\n      initialState,\n      reducers: {\n        addOne: adapter.addOne,\n        removeOne(state, action: PayloadAction<string>) {\n          const sizeBefore = state.ids.length\n          // Originally, having nested `produce` calls don't mutate `state` here as I would have expected.\n          // (note that `state` here is actually an Immer Draft<S>, from `createReducer`)\n          // One woarkound was to return the new plain result value instead\n          // See https://github.com/immerjs/immer/issues/533\n          // However, after tweaking `createStateOperator` to check if the argument is a draft,\n          // we can just treat the operator as strictly mutating, without returning a result,\n          // and the result should be correct.\n          const result = adapter.removeOne(state, action)\n\n          const sizeAfter = state.ids.length\n          if (sizeBefore > 0) {\n            expect(sizeAfter).toBe(sizeBefore - 1)\n          }\n\n          //Deliberately _don't_ return result\n        },\n      },\n      extraReducers: (builder) => {\n        builder.addCase(upsertBook, (state, action) => {\n          return adapter.upsertOne(state, action)\n        })\n        builder.addCase(fetchBooksTAC.pending, (state, action) => {\n          state.loading = 'pending'\n          state.lastRequestId = action.meta.requestId\n        })\n        builder.addCase(fetchBooksTAC.fulfilled, (state, action) => {\n          if (\n            state.loading === 'pending' &&\n            action.meta.requestId === state.lastRequestId\n          ) {\n            adapter.setAll(state, action.payload)\n            state.loading = 'finished'\n            state.lastRequestId = null\n          }\n        })\n      },\n    })\n\n    const { addOne, removeOne } = booksSlice.actions\n    const { reducer } = booksSlice\n\n    const store = configureStore({\n      reducer: {\n        books: reducer,\n      },\n    })\n\n    await store.dispatch(fetchBooksTAC())\n\n    const { books: booksAfterLoaded } = store.getState()\n    // Sorted, so \"First\" goes first\n    expect(booksAfterLoaded.ids).toEqual(['a', 'b'])\n    expect(booksAfterLoaded.lastRequestId).toBe(null)\n    expect(booksAfterLoaded.loading).toBe('finished')\n\n    store.dispatch(addOne({ id: 'd', title: 'Remove Me' }))\n    store.dispatch(removeOne('d'))\n\n    store.dispatch(addOne({ id: 'c', title: 'Middle' }))\n\n    const { books: booksAfterAddOne } = store.getState()\n\n    // Sorted, so \"Middle\" goes in the middle\n    expect(booksAfterAddOne.ids).toEqual(['a', 'c', 'b'])\n\n    store.dispatch(upsertBook({ id: 'c', title: 'Zeroth' }))\n\n    const { books: booksAfterUpsert } = store.getState()\n\n    // Sorted, so \"Zeroth\" goes last\n    expect(booksAfterUpsert.ids).toEqual(['a', 'b', 'c'])\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/configureStore.test-d.ts",
    "content": "import type {\n  Action,\n  ConfigureStoreOptions,\n  Dispatch,\n  Middleware,\n  PayloadAction,\n  Reducer,\n  Store,\n  StoreEnhancer,\n  ThunkAction,\n  ThunkDispatch,\n  ThunkMiddleware,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport {\n  Tuple,\n  applyMiddleware,\n  combineReducers,\n  configureStore,\n  createSlice,\n} from '@reduxjs/toolkit'\nimport { thunk } from 'redux-thunk'\n\nconst _anyMiddleware: any = () => () => () => {}\n\ndescribe('type tests', () => {\n  test('configureStore() requires a valid reducer or reducer map.', () => {\n    configureStore({\n      reducer: (state, action) => 0,\n    })\n\n    configureStore({\n      reducer: {\n        counter1: () => 0,\n        counter2: () => 1,\n      },\n    })\n\n    // @ts-expect-error\n    configureStore({ reducer: 'not a reducer' })\n\n    // @ts-expect-error\n    configureStore({ reducer: { a: 'not a reducer' } })\n\n    // @ts-expect-error\n    configureStore({})\n  })\n\n  test('configureStore() infers the store state type.', () => {\n    const reducer: Reducer<number> = () => 0\n\n    const store = configureStore({ reducer })\n\n    expectTypeOf(store).toExtend<Store<number, UnknownAction>>()\n\n    expectTypeOf(store).not.toExtend<Store<string, UnknownAction>>()\n  })\n\n  test('configureStore() infers the store action type.', () => {\n    const reducer: Reducer<number, PayloadAction<number>> = () => 0\n\n    const store = configureStore({ reducer })\n\n    expectTypeOf(store).toExtend<Store<number, PayloadAction<number>>>()\n\n    expectTypeOf(store).not.toExtend<Store<number, PayloadAction<string>>>()\n  })\n\n  test('configureStore() accepts Tuple for middleware, but not plain array.', () => {\n    const middleware: Middleware = (store) => (next) => next\n\n    configureStore({\n      reducer: () => 0,\n      middleware: () => new Tuple(middleware),\n    })\n\n    configureStore({\n      reducer: () => 0,\n      // @ts-expect-error\n      middleware: () => [middleware],\n    })\n\n    configureStore({\n      reducer: () => 0,\n      // @ts-expect-error\n      middleware: () => new Tuple('not middleware'),\n    })\n  })\n\n  test('configureStore() accepts devTools flag.', () => {\n    configureStore({\n      reducer: () => 0,\n      devTools: true,\n    })\n\n    configureStore({\n      reducer: () => 0,\n      // @ts-expect-error\n      devTools: 'true',\n    })\n  })\n\n  test('configureStore() accepts devTools EnhancerOptions.', () => {\n    configureStore({\n      reducer: () => 0,\n      devTools: { name: 'myApp' },\n    })\n\n    configureStore({\n      reducer: () => 0,\n      // @ts-expect-error\n      devTools: { appName: 'myApp' },\n    })\n  })\n\n  test('configureStore() accepts preloadedState.', () => {\n    configureStore({\n      reducer: () => 0,\n      preloadedState: 0,\n    })\n\n    configureStore({\n      // @ts-expect-error\n      reducer: (_: number) => 0,\n      preloadedState: 'non-matching state type',\n    })\n  })\n\n  test('nullable state is preserved', () => {\n    const store = configureStore({\n      reducer: (): string | null => null,\n    })\n\n    expectTypeOf(store.getState()).toEqualTypeOf<string | null>()\n  })\n\n  test('configureStore() accepts store Tuple for enhancers, but not plain array', () => {\n    const enhancer = applyMiddleware(() => (next) => next)\n\n    const store = configureStore({\n      reducer: () => 0,\n      enhancers: () => new Tuple(enhancer),\n    })\n\n    const store2 = configureStore({\n      reducer: () => 0,\n      // @ts-expect-error\n      enhancers: () => [enhancer],\n    })\n\n    expectTypeOf(store.dispatch).toExtend<\n      Dispatch & ThunkDispatch<number, undefined, UnknownAction>\n    >()\n\n    configureStore({\n      reducer: () => 0,\n      // @ts-expect-error\n      enhancers: () => new Tuple('not a store enhancer'),\n    })\n\n    const somePropertyStoreEnhancer: StoreEnhancer<{\n      someProperty: string\n    }> = (next) => {\n      return (reducer, preloadedState) => {\n        return {\n          ...next(reducer, preloadedState),\n          someProperty: 'some value',\n        }\n      }\n    }\n\n    const anotherPropertyStoreEnhancer: StoreEnhancer<{\n      anotherProperty: number\n    }> = (next) => {\n      return (reducer, preloadedState) => {\n        return {\n          ...next(reducer, preloadedState),\n          anotherProperty: 123,\n        }\n      }\n    }\n\n    const store3 = configureStore({\n      reducer: () => 0,\n      enhancers: () =>\n        new Tuple(somePropertyStoreEnhancer, anotherPropertyStoreEnhancer),\n    })\n\n    expectTypeOf(store3.dispatch).toEqualTypeOf<Dispatch>()\n\n    expectTypeOf(store3.someProperty).toBeString()\n\n    expectTypeOf(store3.anotherProperty).toBeNumber()\n\n    const storeWithCallback = configureStore({\n      reducer: () => 0,\n      enhancers: (getDefaultEnhancers) =>\n        getDefaultEnhancers()\n          .prepend(anotherPropertyStoreEnhancer)\n          .concat(somePropertyStoreEnhancer),\n    })\n\n    expectTypeOf(store3.dispatch).toExtend<\n      Dispatch & ThunkDispatch<number, undefined, UnknownAction>\n    >()\n\n    expectTypeOf(store3.someProperty).toBeString()\n\n    expectTypeOf(store3.anotherProperty).toBeNumber()\n\n    const someStateExtendingEnhancer: StoreEnhancer<\n      {},\n      { someProperty: string }\n    > =\n      (next) =>\n      (...args) => {\n        const store = next(...args)\n        const getState = () => ({\n          ...store.getState(),\n          someProperty: 'some value',\n        })\n        return {\n          ...store,\n          getState,\n        } as any\n      }\n\n    const anotherStateExtendingEnhancer: StoreEnhancer<\n      {},\n      { anotherProperty: number }\n    > =\n      (next) =>\n      (...args) => {\n        const store = next(...args)\n        const getState = () => ({\n          ...store.getState(),\n          anotherProperty: 123,\n        })\n        return {\n          ...store,\n          getState,\n        } as any\n      }\n\n    const store4 = configureStore({\n      reducer: () => ({ aProperty: 0 }),\n      enhancers: () =>\n        new Tuple(someStateExtendingEnhancer, anotherStateExtendingEnhancer),\n    })\n\n    const state = store4.getState()\n\n    expectTypeOf(state.aProperty).toBeNumber()\n\n    expectTypeOf(state.someProperty).toBeString()\n\n    expectTypeOf(state.anotherProperty).toBeNumber()\n\n    const storeWithCallback2 = configureStore({\n      reducer: () => ({ aProperty: 0 }),\n      enhancers: (gDE) =>\n        gDE().concat(someStateExtendingEnhancer, anotherStateExtendingEnhancer),\n    })\n\n    const stateWithCallback = storeWithCallback2.getState()\n\n    expectTypeOf(stateWithCallback.aProperty).toBeNumber()\n\n    expectTypeOf(stateWithCallback.someProperty).toBeString()\n\n    expectTypeOf(stateWithCallback.anotherProperty).toBeNumber()\n  })\n\n  test('Preloaded state typings', () => {\n    const counterReducer1: Reducer<number> = () => 0\n    const counterReducer2: Reducer<number> = () => 0\n\n    test('partial preloaded state', () => {\n      const store = configureStore({\n        reducer: {\n          counter1: counterReducer1,\n          counter2: counterReducer2,\n        },\n        preloadedState: {\n          counter1: 0,\n        },\n      })\n\n      expectTypeOf(store.getState().counter1).toBeNumber()\n\n      expectTypeOf(store.getState().counter2).toBeNumber()\n    })\n\n    test('empty preloaded state', () => {\n      const store = configureStore({\n        reducer: {\n          counter1: counterReducer1,\n          counter2: counterReducer2,\n        },\n        preloadedState: {},\n      })\n\n      expectTypeOf(store.getState().counter1).toBeNumber()\n\n      expectTypeOf(store.getState().counter2).toBeNumber()\n    })\n\n    test('excess properties in preloaded state', () => {\n      const store = configureStore({\n        reducer: {\n          // @ts-expect-error\n          counter1: counterReducer1,\n          counter2: counterReducer2,\n        },\n        preloadedState: {\n          counter1: 0,\n          counter3: 5,\n        },\n      })\n\n      expectTypeOf(store.getState().counter1).toBeNumber()\n\n      expectTypeOf(store.getState().counter2).toBeNumber()\n    })\n\n    test('mismatching properties in preloaded state', () => {\n      const store = configureStore({\n        reducer: {\n          // @ts-expect-error\n          counter1: counterReducer1,\n          counter2: counterReducer2,\n        },\n        preloadedState: {\n          counter3: 5,\n        },\n      })\n\n      expectTypeOf(store.getState().counter1).toBeNumber()\n\n      expectTypeOf(store.getState().counter2).toBeNumber()\n    })\n\n    test('string preloaded state when expecting object', () => {\n      const store = configureStore({\n        reducer: {\n          // @ts-expect-error\n          counter1: counterReducer1,\n          counter2: counterReducer2,\n        },\n        preloadedState: 'test',\n      })\n\n      expectTypeOf(store.getState().counter1).toBeNumber()\n\n      expectTypeOf(store.getState().counter2).toBeNumber()\n    })\n\n    test('nested combineReducers allows partial', () => {\n      const store = configureStore({\n        reducer: {\n          group1: combineReducers({\n            counter1: counterReducer1,\n            counter2: counterReducer2,\n          }),\n          group2: combineReducers({\n            counter1: counterReducer1,\n            counter2: counterReducer2,\n          }),\n        },\n        preloadedState: {\n          group1: {\n            counter1: 5,\n          },\n        },\n      })\n\n      expectTypeOf(store.getState().group1.counter1).toBeNumber()\n\n      expectTypeOf(store.getState().group1.counter2).toBeNumber()\n\n      expectTypeOf(store.getState().group2.counter1).toBeNumber()\n\n      expectTypeOf(store.getState().group2.counter2).toBeNumber()\n    })\n\n    test('non-nested combineReducers does not allow partial', () => {\n      interface GroupState {\n        counter1: number\n        counter2: number\n      }\n\n      const initialState = { counter1: 0, counter2: 0 }\n\n      const group1Reducer: Reducer<GroupState> = (state = initialState) => state\n      const group2Reducer: Reducer<GroupState> = (state = initialState) => state\n\n      const store = configureStore({\n        reducer: {\n          // @ts-expect-error\n          group1: group1Reducer,\n          group2: group2Reducer,\n        },\n        preloadedState: {\n          group1: {\n            counter1: 5,\n          },\n        },\n      })\n\n      expectTypeOf(store.getState().group1.counter1).toBeNumber()\n\n      expectTypeOf(store.getState().group1.counter2).toBeNumber()\n\n      expectTypeOf(store.getState().group2.counter1).toBeNumber()\n\n      expectTypeOf(store.getState().group2.counter2).toBeNumber()\n    })\n  })\n\n  test('Dispatch typings', () => {\n    type StateA = number\n    const reducerA = () => 0\n    const thunkA = () => {\n      return (() => {}) as any as ThunkAction<Promise<'A'>, StateA, any, any>\n    }\n\n    type StateB = string\n    const thunkB = () => {\n      return (dispatch: Dispatch, getState: () => StateB) => {}\n    }\n\n    test('by default, dispatching Thunks is possible', () => {\n      const store = configureStore({\n        reducer: reducerA,\n      })\n\n      store.dispatch(thunkA())\n      // @ts-expect-error\n      store.dispatch(thunkB())\n\n      const res = store.dispatch((dispatch, getState) => {\n        return 42\n      })\n\n      const action = store.dispatch({ type: 'foo' })\n    })\n\n    test('return type of thunks and actions is inferred correctly', () => {\n      const slice = createSlice({\n        name: 'counter',\n        initialState: {\n          value: 0,\n        },\n        reducers: {\n          incrementByAmount: (state, action: PayloadAction<number>) => {\n            state.value += action.payload\n          },\n        },\n      })\n\n      const store = configureStore({\n        reducer: {\n          counter: slice.reducer,\n        },\n      })\n\n      const action = slice.actions.incrementByAmount(2)\n\n      const dispatchResult = store.dispatch(action)\n\n      expectTypeOf(dispatchResult).toExtend<{\n        type: string\n        payload: number\n      }>()\n\n      const promiseResult = store.dispatch(async (dispatch) => {\n        return 42\n      })\n\n      expectTypeOf(promiseResult).toEqualTypeOf<Promise<number>>()\n\n      const store2 = configureStore({\n        reducer: {\n          counter: slice.reducer,\n        },\n        middleware: (gDM) =>\n          gDM({\n            thunk: {\n              extraArgument: 42,\n            },\n          }),\n      })\n\n      const dispatchResult2 = store2.dispatch(action)\n\n      expectTypeOf(dispatchResult2).toExtend<{\n        type: string\n        payload: number\n      }>()\n    })\n\n    test('removing the Thunk Middleware', () => {\n      const store = configureStore({\n        reducer: reducerA,\n        middleware: () => new Tuple(),\n      })\n\n      expectTypeOf(store.dispatch)\n        .parameter(0)\n        .not.toExtend<ReturnType<typeof thunkA>>()\n\n      expectTypeOf(store.dispatch)\n        .parameter(0)\n        .not.toExtend<ReturnType<typeof thunkB>>()\n    })\n\n    test('adding the thunk middleware by hand', () => {\n      const store = configureStore({\n        reducer: reducerA,\n        middleware: () => new Tuple(thunk as ThunkMiddleware<StateA>),\n      })\n\n      store.dispatch(thunkA())\n      // @ts-expect-error\n      store.dispatch(thunkB())\n    })\n\n    test('custom middleware', () => {\n      const store = configureStore({\n        reducer: reducerA,\n        middleware: () =>\n          new Tuple(0 as unknown as Middleware<(a: StateA) => boolean, StateA>),\n      })\n\n      expectTypeOf(store.dispatch(5)).toBeBoolean()\n\n      expectTypeOf(store.dispatch(5)).not.toBeString()\n    })\n\n    test('multiple custom middleware', () => {\n      const middleware = [] as any as Tuple<\n        [\n          Middleware<(a: 'a') => 'A', StateA>,\n          Middleware<(b: 'b') => 'B', StateA>,\n          ThunkMiddleware<StateA>,\n        ]\n      >\n\n      const store = configureStore({\n        reducer: reducerA,\n        middleware: () => middleware,\n      })\n\n      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()\n\n      expectTypeOf(store.dispatch('b')).toEqualTypeOf<'B'>()\n\n      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()\n    })\n\n    test('Accepts thunk with `unknown`, `undefined` or `null` ThunkAction extraArgument per default', () => {\n      const store = configureStore({ reducer: {} })\n      // undefined is the default value for the ThunkMiddleware extraArgument\n      store.dispatch(function () {} as ThunkAction<\n        void,\n        {},\n        undefined,\n        UnknownAction\n      >)\n      // `null` for the `extra` generic was previously documented in the RTK \"Advanced Tutorial\", but\n      // is a bad pattern and users should use `unknown` instead\n      // @ts-expect-error\n      store.dispatch(function () {} as ThunkAction<\n        void,\n        {},\n        null,\n        UnknownAction\n      >)\n      // unknown is the best way to type a ThunkAction if you do not care\n      // about the value of the extraArgument, as it will always work with every\n      // ThunkMiddleware, no matter the actual extraArgument type\n      store.dispatch(function () {} as ThunkAction<\n        void,\n        {},\n        unknown,\n        UnknownAction\n      >)\n      // @ts-expect-error\n      store.dispatch(function () {} as ThunkAction<\n        void,\n        {},\n        boolean,\n        UnknownAction\n      >)\n    })\n\n    test('custom middleware and getDefaultMiddleware', () => {\n      const store = configureStore({\n        reducer: reducerA,\n        middleware: (gDM) =>\n          gDM().prepend((() => {}) as any as Middleware<\n            (a: 'a') => 'A',\n            StateA\n          >),\n      })\n\n      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()\n\n      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()\n\n      expectTypeOf(store.dispatch)\n        .parameter(0)\n        .not.toExtend<ReturnType<typeof thunkB>>()\n    })\n\n    test('custom middleware and getDefaultMiddleware, using prepend', () => {\n      const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =\n        _anyMiddleware\n\n      const store = configureStore({\n        reducer: reducerA,\n        middleware: (gDM) => {\n          const concatenated = gDM().prepend(otherMiddleware)\n\n          expectTypeOf(concatenated).toExtend<\n            ReadonlyArray<\n              typeof otherMiddleware | ThunkMiddleware | Middleware<{}>\n            >\n          >()\n\n          return concatenated\n        },\n      })\n\n      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()\n\n      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()\n\n      expectTypeOf(store.dispatch)\n        .parameter(0)\n        .not.toExtend<ReturnType<typeof thunkB>>()\n    })\n\n    test('custom middleware and getDefaultMiddleware, using concat', () => {\n      const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =\n        _anyMiddleware\n\n      const store = configureStore({\n        reducer: reducerA,\n        middleware: (gDM) => {\n          const concatenated = gDM().concat(otherMiddleware)\n\n          expectTypeOf(concatenated).toExtend<\n            ReadonlyArray<\n              typeof otherMiddleware | ThunkMiddleware | Middleware<{}>\n            >\n          >()\n\n          return concatenated\n        },\n      })\n\n      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()\n\n      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()\n\n      expectTypeOf(store.dispatch)\n        .parameter(0)\n        .not.toExtend<ReturnType<typeof thunkB>>()\n    })\n\n    test('middlewareBuilder notation, getDefaultMiddleware (unconfigured)', () => {\n      const store = configureStore({\n        reducer: reducerA,\n        middleware: (getDefaultMiddleware) =>\n          getDefaultMiddleware().prepend((() => {}) as any as Middleware<\n            (a: 'a') => 'A',\n            StateA\n          >),\n      })\n\n      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()\n\n      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()\n\n      expectTypeOf(store.dispatch)\n        .parameter(0)\n        .not.toExtend<ReturnType<typeof thunkB>>()\n    })\n\n    test('middlewareBuilder notation, getDefaultMiddleware, concat & prepend', () => {\n      const otherMiddleware: Middleware<(a: 'a') => 'A', StateA> =\n        _anyMiddleware\n\n      const otherMiddleware2: Middleware<(a: 'b') => 'B', StateA> =\n        _anyMiddleware\n\n      const store = configureStore({\n        reducer: reducerA,\n        middleware: (getDefaultMiddleware) =>\n          getDefaultMiddleware()\n            .concat(otherMiddleware)\n            .prepend(otherMiddleware2),\n      })\n\n      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()\n\n      expectTypeOf(store.dispatch(thunkA())).toEqualTypeOf<Promise<'A'>>()\n\n      expectTypeOf(store.dispatch('b')).toEqualTypeOf<'B'>()\n\n      expectTypeOf(store.dispatch)\n        .parameter(0)\n        .not.toExtend<ReturnType<typeof thunkB>>()\n    })\n\n    test('middlewareBuilder notation, getDefaultMiddleware (thunk: false)', () => {\n      const store = configureStore({\n        reducer: reducerA,\n        middleware: (getDefaultMiddleware) =>\n          getDefaultMiddleware({ thunk: false }).prepend(\n            (() => {}) as any as Middleware<(a: 'a') => 'A', StateA>,\n          ),\n      })\n\n      expectTypeOf(store.dispatch('a')).toEqualTypeOf<'A'>()\n\n      expectTypeOf(store.dispatch)\n        .parameter(0)\n        .not.toExtend<ReturnType<typeof thunkA>>()\n    })\n\n    test(\"badly typed middleware won't make `dispatch` `any`\", () => {\n      const store = configureStore({\n        reducer: reducerA,\n        middleware: (getDefaultMiddleware) =>\n          getDefaultMiddleware().concat(_anyMiddleware as Middleware<any>),\n      })\n\n      expectTypeOf(store.dispatch).not.toBeAny()\n    })\n\n    test(\"decorated `configureStore` won't make `dispatch` `never`\", () => {\n      const someSlice = createSlice({\n        name: 'something',\n        initialState: null as any,\n        reducers: {\n          set(state) {\n            return state\n          },\n        },\n      })\n\n      function configureMyStore<S>(\n        options: Omit<ConfigureStoreOptions<S>, 'reducer'>,\n      ) {\n        return configureStore({\n          ...options,\n          reducer: someSlice.reducer,\n        })\n      }\n\n      const store = configureMyStore({})\n\n      expectTypeOf(store.dispatch).toBeFunction()\n    })\n\n    interface CounterState {\n      value: number\n    }\n\n    const counterSlice = createSlice({\n      name: 'counter',\n      initialState: { value: 0 } as CounterState,\n      reducers: {\n        increment(state) {\n          state.value += 1\n        },\n        decrement(state) {\n          state.value -= 1\n        },\n        // Use the PayloadAction type to declare the contents of `action.payload`\n        incrementByAmount: (state, action: PayloadAction<number>) => {\n          state.value += action.payload\n        },\n      },\n    })\n\n    type Unsubscribe = () => void\n\n    // A fake middleware that tells TS that an unsubscribe callback is being returned for a given action\n    // This is the same signature that the \"listener\" middleware uses\n    const dummyMiddleware: Middleware<\n      {\n        (action: Action<'actionListenerMiddleware/add'>): Unsubscribe\n      },\n      CounterState\n    > = (storeApi) => (next) => (action) => {}\n\n    const store = configureStore({\n      reducer: counterSlice.reducer,\n      middleware: (gDM) => gDM().prepend(dummyMiddleware),\n    })\n\n    // Order matters here! We need the listener type to come first, otherwise\n    // the thunk middleware type kicks in and TS thinks a plain action is being returned\n    expectTypeOf(store.dispatch).toEqualTypeOf<\n      ((action: Action<'actionListenerMiddleware/add'>) => Unsubscribe) &\n        ThunkDispatch<CounterState, undefined, UnknownAction> &\n        Dispatch<UnknownAction>\n    >()\n\n    const unsubscribe = store.dispatch({\n      type: 'actionListenerMiddleware/add',\n    } as const)\n\n    expectTypeOf(unsubscribe).toEqualTypeOf<Unsubscribe>()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/configureStore.test.ts",
    "content": "import * as DevTools from '@internal/devtoolsExtension'\nimport type { Middleware, StoreEnhancer } from '@reduxjs/toolkit'\nimport { Tuple } from '@reduxjs/toolkit'\nimport type * as Redux from 'redux'\nimport { vi } from 'vitest'\n\nvi.doMock('redux', async (importOriginal) => {\n  const redux = await importOriginal<typeof import('redux')>()\n\n  vi.spyOn(redux, 'applyMiddleware')\n  vi.spyOn(redux, 'combineReducers')\n  vi.spyOn(redux, 'compose')\n  vi.spyOn(redux, 'createStore')\n\n  return redux\n})\n\ndescribe('configureStore', async () => {\n  const composeWithDevToolsSpy = vi.spyOn(DevTools, 'composeWithDevTools')\n\n  const redux = await import('redux')\n\n  const { configureStore } = await import('@reduxjs/toolkit')\n\n  const reducer: Redux.Reducer = (state = {}, _action) => state\n\n  beforeEach(() => {\n    vi.clearAllMocks()\n  })\n\n  describe('given a function reducer', () => {\n    it('calls createStore with the reducer', () => {\n      configureStore({ reducer })\n      expect(configureStore({ reducer })).toBeInstanceOf(Object)\n\n      expect(redux.createStore).toHaveBeenCalledWith(\n        reducer,\n        undefined,\n        expect.any(Function),\n      )\n      expect(redux.applyMiddleware).toHaveBeenCalled()\n      if (process.env.TEST_DIST) {\n        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()\n      } else {\n        expect(composeWithDevToolsSpy).toHaveBeenCalledTimes(2)\n      }\n    })\n  })\n\n  describe('given an object of reducers', () => {\n    it('calls createStore with the combined reducers', () => {\n      const reducer = {\n        reducer() {\n          return true\n        },\n      }\n      expect(configureStore({ reducer })).toBeInstanceOf(Object)\n      expect(redux.combineReducers).toHaveBeenCalledWith(reducer)\n      expect(redux.applyMiddleware).toHaveBeenCalled()\n      if (process.env.TEST_DIST) {\n        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()\n      } else {\n        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()\n      }\n      expect(redux.createStore).toHaveBeenCalledWith(\n        expect.any(Function),\n        undefined,\n        expect.any(Function),\n      )\n    })\n  })\n\n  describe('given no reducer', () => {\n    it('throws', () => {\n      expect(configureStore).toThrow(\n        '`reducer` is a required argument, and must be a function or an object of functions that can be passed to combineReducers',\n      )\n    })\n  })\n\n  describe('given no middleware', () => {\n    it('calls createStore without any middleware', () => {\n      expect(\n        configureStore({ middleware: () => new Tuple(), reducer }),\n      ).toBeInstanceOf(Object)\n      expect(redux.applyMiddleware).toHaveBeenCalledWith()\n      if (process.env.TEST_DIST) {\n        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()\n      } else {\n        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()\n      }\n      expect(redux.createStore).toHaveBeenCalledWith(\n        reducer,\n        undefined,\n        expect.any(Function),\n      )\n    })\n  })\n\n  describe('given an array of middleware', () => {\n    it('throws an error requiring a callback', () => {\n      // @ts-expect-error\n      expect(() => configureStore({ middleware: [], reducer })).toThrow(\n        '`middleware` field must be a callback',\n      )\n    })\n  })\n\n  describe('given undefined middleware', () => {\n    it('calls createStore with default middleware', () => {\n      expect(configureStore({ middleware: undefined, reducer })).toBeInstanceOf(\n        Object,\n      )\n      expect(redux.applyMiddleware).toHaveBeenCalledWith(\n        expect.any(Function), // immutableCheck\n        expect.any(Function), // thunk\n        expect.any(Function), // serializableCheck\n        expect.any(Function), // actionCreatorCheck\n      )\n      if (process.env.TEST_DIST) {\n        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()\n      } else {\n        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()\n      }\n      expect(redux.createStore).toHaveBeenCalledWith(\n        reducer,\n        undefined,\n        expect.any(Function),\n      )\n    })\n  })\n\n  describe('given any middleware', () => {\n    const exampleMiddleware: Middleware<any, any> = () => (next) => (action) =>\n      next(action)\n    it('throws an error by default if there are duplicate middleware', () => {\n      const makeStore = () => {\n        return configureStore({\n          reducer,\n          middleware: (gDM) =>\n            gDM().concat(exampleMiddleware, exampleMiddleware),\n        })\n      }\n\n      expect(makeStore).toThrowError(\n        'Duplicate middleware references found when creating the store. Ensure that each middleware is only included once.',\n      )\n    })\n\n    it('does not throw a duplicate middleware error if duplicateMiddlewareCheck is disabled', () => {\n      const makeStore = () => {\n        return configureStore({\n          reducer,\n          middleware: (gDM) =>\n            gDM().concat(exampleMiddleware, exampleMiddleware),\n          duplicateMiddlewareCheck: false,\n        })\n      }\n\n      expect(makeStore).not.toThrowError()\n    })\n  })\n\n  describe('given a middleware creation function that returns undefined', () => {\n    it('throws an error', () => {\n      const invalidBuilder = vi.fn((getDefaultMiddleware) => undefined as any)\n      expect(() =>\n        configureStore({ middleware: invalidBuilder, reducer }),\n      ).toThrow(\n        'when using a middleware builder function, an array of middleware must be returned',\n      )\n    })\n  })\n\n  describe('given a middleware creation function that returns an array with non-functions', () => {\n    it('throws an error', () => {\n      const invalidBuilder = vi.fn((getDefaultMiddleware) => [true] as any)\n      expect(() =>\n        configureStore({ middleware: invalidBuilder, reducer }),\n      ).toThrow('each middleware provided to configureStore must be a function')\n    })\n  })\n\n  describe('given custom middleware', () => {\n    it('calls createStore with custom middleware and without default middleware', () => {\n      const thank: Redux.Middleware = (_store) => (next) => (action) =>\n        next(action)\n      expect(\n        configureStore({ middleware: () => new Tuple(thank), reducer }),\n      ).toBeInstanceOf(Object)\n      expect(redux.applyMiddleware).toHaveBeenCalledWith(thank)\n      if (process.env.TEST_DIST) {\n        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()\n      } else {\n        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()\n      }\n      expect(redux.createStore).toHaveBeenCalledWith(\n        reducer,\n        undefined,\n        expect.any(Function),\n      )\n    })\n  })\n\n  describe('middleware builder notation', () => {\n    it('calls builder, passes getDefaultMiddleware and uses returned middlewares', () => {\n      const thank = vi.fn(\n        ((_store) => (next) => (action) => 'foobar') as Redux.Middleware,\n      )\n\n      const builder = vi.fn((getDefaultMiddleware) => {\n        expect(getDefaultMiddleware).toEqual(expect.any(Function))\n        expect(getDefaultMiddleware()).toEqual(expect.any(Array))\n\n        return new Tuple(thank)\n      })\n\n      const store = configureStore({ middleware: builder, reducer })\n\n      expect(builder).toHaveBeenCalled()\n\n      expect(store.dispatch({ type: 'test' })).toBe('foobar')\n    })\n  })\n\n  describe('with devTools disabled', () => {\n    it('calls createStore without devTools enhancer', () => {\n      expect(configureStore({ devTools: false, reducer })).toBeInstanceOf(\n        Object,\n      )\n      expect(redux.applyMiddleware).toHaveBeenCalled()\n      expect(redux.compose).toHaveBeenCalled()\n      expect(redux.createStore).toHaveBeenCalledWith(\n        reducer,\n        undefined,\n        expect.any(Function),\n      )\n    })\n  })\n\n  describe('with devTools options', () => {\n    it('calls createStore with devTools enhancer and option', () => {\n      const options = {\n        name: 'myApp',\n        trace: true,\n      }\n      expect(configureStore({ devTools: options, reducer })).toBeInstanceOf(\n        Object,\n      )\n      expect(redux.applyMiddleware).toHaveBeenCalled()\n      if (process.env.TEST_DIST) {\n        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()\n      } else {\n        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()\n\n        expect(composeWithDevToolsSpy).toHaveBeenLastCalledWith(options)\n      }\n      expect(redux.createStore).toHaveBeenCalledWith(\n        reducer,\n        undefined,\n        expect.any(Function),\n      )\n    })\n  })\n\n  describe('given preloadedState', () => {\n    it('calls createStore with preloadedState', () => {\n      expect(configureStore({ reducer })).toBeInstanceOf(Object)\n      expect(redux.applyMiddleware).toHaveBeenCalled()\n      if (process.env.TEST_DIST) {\n        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()\n      } else {\n        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()\n      }\n      expect(redux.createStore).toHaveBeenCalledWith(\n        reducer,\n        undefined,\n        expect.any(Function),\n      )\n    })\n  })\n\n  describe('given enhancers', () => {\n    let dummyEnhancerCalled = false\n\n    const dummyEnhancer: StoreEnhancer =\n      (createStore) => (reducer, preloadedState) => {\n        dummyEnhancerCalled = true\n\n        return createStore(reducer, preloadedState)\n      }\n\n    beforeEach(() => {\n      dummyEnhancerCalled = false\n    })\n\n    it('calls createStore with enhancers', () => {\n      expect(\n        configureStore({\n          enhancers: (gDE) => gDE().concat(dummyEnhancer),\n          reducer,\n        }),\n      ).toBeInstanceOf(Object)\n      expect(redux.applyMiddleware).toHaveBeenCalled()\n      if (process.env.TEST_DIST) {\n        expect(composeWithDevToolsSpy).not.toHaveBeenCalled()\n      } else {\n        expect(composeWithDevToolsSpy).toHaveBeenCalledOnce()\n      }\n      expect(redux.createStore).toHaveBeenCalledWith(\n        reducer,\n        undefined,\n        expect.any(Function),\n      )\n\n      expect(dummyEnhancerCalled).toBe(true)\n    })\n\n    describe('invalid arguments', () => {\n      test('enhancers is not a callback', () => {\n        expect(() => configureStore({ reducer, enhancers: [] as any })).toThrow(\n          '`enhancers` field must be a callback',\n        )\n      })\n\n      test('callback fails to return array', () => {\n        expect(() =>\n          configureStore({ reducer, enhancers: (() => {}) as any }),\n        ).toThrow('`enhancers` callback must return an array')\n      })\n\n      test('array contains non-function', () => {\n        expect(() =>\n          configureStore({ reducer, enhancers: (() => ['']) as any }),\n        ).toThrow('each enhancer provided to configureStore must be a function')\n      })\n    })\n\n    const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {})\n    beforeEach(() => {\n      consoleSpy.mockClear()\n    })\n    afterAll(() => {\n      consoleSpy.mockRestore()\n    })\n\n    it('warns if middleware enhancer is excluded from final array when middlewares are provided', () => {\n      const store = configureStore({\n        reducer,\n        enhancers: () => new Tuple(dummyEnhancer),\n      })\n\n      expect(dummyEnhancerCalled).toBe(true)\n\n      expect(consoleSpy).toHaveBeenCalledWith(\n        'middlewares were provided, but middleware enhancer was not included in final enhancers - make sure to call `getDefaultEnhancers`',\n      )\n    })\n    it(\"doesn't warn when middleware enhancer is excluded if no middlewares provided\", () => {\n      const store = configureStore({\n        reducer,\n        middleware: () => new Tuple(),\n        enhancers: () => new Tuple(dummyEnhancer),\n      })\n\n      expect(dummyEnhancerCalled).toBe(true)\n\n      expect(consoleSpy).not.toHaveBeenCalled()\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/createAction.test-d.tsx",
    "content": "import type {\n  Action,\n  ActionCreator,\n  ActionCreatorWithNonInferrablePayload,\n  ActionCreatorWithOptionalPayload,\n  ActionCreatorWithPayload,\n  ActionCreatorWithPreparedPayload,\n  ActionCreatorWithoutPayload,\n  PayloadAction,\n  PayloadActionCreator,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport { createAction } from '@reduxjs/toolkit'\n\ndescribe('type tests', () => {\n  describe('PayloadAction', () => {\n    test('PayloadAction has type parameter for the payload.', () => {\n      const action: PayloadAction<number> = { type: '', payload: 5 }\n\n      expectTypeOf(action.payload).toBeNumber()\n\n      expectTypeOf(action.payload).not.toBeString()\n    })\n\n    test('PayloadAction type parameter is required.', () => {\n      expectTypeOf({ type: '', payload: 5 }).not.toExtend<PayloadAction>()\n    })\n\n    test('PayloadAction has a string type tag.', () => {\n      expectTypeOf({ type: '', payload: 5 }).toEqualTypeOf<\n        PayloadAction<number>\n      >()\n\n      expectTypeOf({ type: 1, payload: 5 }).not.toExtend<PayloadAction>()\n    })\n\n    test('PayloadAction is compatible with Action<string>', () => {\n      const action: PayloadAction<number> = { type: '', payload: 5 }\n\n      expectTypeOf(action).toMatchObjectType<Action<string>>()\n    })\n  })\n\n  describe('PayloadActionCreator', () => {\n    test('PayloadActionCreator returns correctly typed PayloadAction depending on whether a payload is passed.', () => {\n      const actionCreator = Object.assign(\n        (payload?: number) => ({\n          type: 'action',\n          payload,\n        }),\n        { type: 'action' },\n      ) as PayloadActionCreator<number | undefined>\n\n      expectTypeOf(actionCreator(1)).toEqualTypeOf<\n        PayloadAction<number | undefined>\n      >()\n\n      expectTypeOf(actionCreator()).toEqualTypeOf<\n        PayloadAction<number | undefined>\n      >()\n\n      expectTypeOf(actionCreator(undefined)).toEqualTypeOf<\n        PayloadAction<number | undefined>\n      >()\n\n      expectTypeOf(actionCreator()).not.toExtend<PayloadAction<number>>()\n\n      expectTypeOf(actionCreator(1)).not.toExtend<PayloadAction<undefined>>()\n    })\n\n    test('PayloadActionCreator is compatible with ActionCreator.', () => {\n      const payloadActionCreator = Object.assign(\n        (payload?: number) => ({\n          type: 'action',\n          payload,\n        }),\n        { type: 'action' },\n      ) as PayloadActionCreator\n\n      expectTypeOf(payloadActionCreator).toExtend<\n        ActionCreator<UnknownAction>\n      >()\n\n      const payloadActionCreator2 = Object.assign(\n        (payload?: number) => ({\n          type: 'action',\n          payload: payload || 1,\n        }),\n        { type: 'action' },\n      ) as PayloadActionCreator<number>\n\n      expectTypeOf(payloadActionCreator2).toExtend<\n        ActionCreator<PayloadAction<number>>\n      >()\n    })\n  })\n\n  test('createAction() has type parameter for the action payload.', () => {\n    const increment = createAction<number, 'increment'>('increment')\n\n    expectTypeOf(increment).parameter(0).toBeNumber()\n\n    expectTypeOf(increment).parameter(0).not.toBeString()\n  })\n\n  test('createAction() type parameter is required, not inferred (defaults to `void`).', () => {\n    const increment = createAction('increment')\n\n    expectTypeOf(increment).parameter(0).not.toBeNumber()\n\n    expectTypeOf(increment().payload).not.toBeNumber()\n  })\n\n  test('createAction().type is a string literal.', () => {\n    const increment = createAction<number, 'increment'>('increment')\n\n    expectTypeOf(increment(1).type).toBeString()\n\n    expectTypeOf(increment(1).type).toEqualTypeOf<'increment'>()\n\n    expectTypeOf(increment(1).type).not.toExtend<'other'>()\n\n    expectTypeOf(increment(1).type).not.toBeNumber()\n  })\n\n  test('type still present when using prepareAction', () => {\n    const strLenAction = createAction('strLen', (payload: string) => ({\n      payload: payload.length,\n    }))\n\n    expectTypeOf(strLenAction('test').type).toBeString()\n  })\n\n  test('changing payload type with prepareAction', () => {\n    const strLenAction = createAction('strLen', (payload: string) => ({\n      payload: payload.length,\n    }))\n\n    expectTypeOf(strLenAction('test').payload).toBeNumber()\n\n    expectTypeOf(strLenAction('test').payload).not.toBeString()\n\n    expectTypeOf(strLenAction('test')).not.toHaveProperty('error')\n  })\n\n  test('adding metadata with prepareAction', () => {\n    const strLenMetaAction = createAction('strLenMeta', (payload: string) => ({\n      payload,\n      meta: payload.length,\n    }))\n\n    expectTypeOf(strLenMetaAction('test').meta).toBeNumber()\n\n    expectTypeOf(strLenMetaAction('test').meta).not.toBeString()\n\n    expectTypeOf(strLenMetaAction('test')).not.toHaveProperty('error')\n  })\n\n  test('adding boolean error with prepareAction', () => {\n    const boolErrorAction = createAction('boolError', (payload: string) => ({\n      payload,\n      error: true,\n    }))\n\n    expectTypeOf(boolErrorAction('test').error).toBeBoolean()\n\n    expectTypeOf(boolErrorAction('test').error).not.toBeString()\n  })\n\n  test('adding string error with prepareAction', () => {\n    const strErrorAction = createAction('strError', (payload: string) => ({\n      payload,\n      error: 'this is an error',\n    }))\n\n    expectTypeOf(strErrorAction('test').error).toBeString()\n\n    expectTypeOf(strErrorAction('test').error).not.toBeBoolean()\n  })\n\n  test('regression test for https://github.com/reduxjs/redux-toolkit/issues/214', () => {\n    const action = createAction<{ input?: string }>('ACTION')\n\n    expectTypeOf(action({ input: '' }).payload.input).toEqualTypeOf<\n      string | undefined\n    >()\n\n    expectTypeOf(action({ input: '' }).payload.input).not.toBeNumber()\n\n    expectTypeOf(action).parameter(0).not.toExtend<{ input: number }>()\n  })\n\n  test('regression test for https://github.com/reduxjs/redux-toolkit/issues/224', () => {\n    const oops = createAction('oops', (x: any) => ({\n      payload: x,\n      error: x,\n      meta: x,\n    }))\n\n    expectTypeOf(oops('').payload).toBeAny()\n\n    expectTypeOf(oops('').error).toBeAny()\n\n    expectTypeOf(oops('').meta).toBeAny()\n  })\n\n  describe('createAction.match()', () => {\n    test('simple use case', () => {\n      const actionCreator = createAction<string, 'test'>('test')\n\n      const x: Action<string> = {} as any\n\n      if (actionCreator.match(x)) {\n        expectTypeOf(x.type).toEqualTypeOf<'test'>()\n\n        expectTypeOf(x.payload).toBeString()\n      } else {\n        expectTypeOf(x.type).not.toExtend<'test'>()\n\n        expectTypeOf(x).not.toHaveProperty('payload')\n      }\n    })\n\n    test('special case: optional argument', () => {\n      const actionCreator = createAction<string | undefined, 'test'>('test')\n\n      const x: Action<string> = {} as any\n\n      if (actionCreator.match(x)) {\n        expectTypeOf(x.type).toEqualTypeOf<'test'>()\n\n        expectTypeOf(x.payload).toEqualTypeOf<string | undefined>()\n      }\n    })\n\n    test('special case: without argument', () => {\n      const actionCreator = createAction('test')\n\n      const x: Action<string> = {} as any\n\n      if (actionCreator.match(x)) {\n        expectTypeOf(x.type).toEqualTypeOf<'test'>()\n\n        expectTypeOf(x.payload).not.toExtend<{}>()\n      }\n    })\n\n    test('special case: with prepareAction', () => {\n      const actionCreator = createAction('test', () => ({\n        payload: '',\n        meta: '',\n        error: false,\n      }))\n\n      const x: Action<string> = {} as any\n\n      if (actionCreator.match(x)) {\n        expectTypeOf(x.type).toEqualTypeOf<'test'>()\n\n        expectTypeOf(x.payload).toBeString()\n\n        expectTypeOf(x.meta).toBeString()\n\n        expectTypeOf(x.error).toBeBoolean()\n\n        expectTypeOf(x.payload).not.toBeNumber()\n\n        expectTypeOf(x.meta).not.toBeNumber()\n\n        expectTypeOf(x.error).not.toBeNumber()\n      }\n    })\n    test('potential use: as array filter', () => {\n      const actionCreator = createAction<string, 'test'>('test')\n\n      const x: Action<string>[] = []\n\n      expectTypeOf(x.filter(actionCreator.match)).toEqualTypeOf<\n        PayloadAction<string, 'test'>[]\n      >()\n    })\n  })\n\n  test('ActionCreatorWithOptionalPayload', () => {\n    expectTypeOf(createAction<string | undefined>('')).toEqualTypeOf<\n      ActionCreatorWithOptionalPayload<string | undefined>\n    >()\n\n    expectTypeOf(\n      createAction<void>(''),\n    ).toEqualTypeOf<ActionCreatorWithoutPayload>()\n\n    assertType<ActionCreatorWithNonInferrablePayload>(createAction(''))\n\n    expectTypeOf(createAction<string>('')).toEqualTypeOf<\n      ActionCreatorWithPayload<string>\n    >()\n\n    expectTypeOf(\n      createAction('', (_: 0) => ({\n        payload: 1 as 1,\n        error: 2 as 2,\n        meta: 3 as 3,\n      })),\n    ).toEqualTypeOf<ActionCreatorWithPreparedPayload<[0], 1, '', 2, 3>>()\n\n    const anyCreator = createAction<any>('')\n\n    expectTypeOf(anyCreator).toEqualTypeOf<ActionCreatorWithPayload<any>>()\n\n    expectTypeOf(anyCreator({}).payload).toBeAny()\n  })\n\n  test(\"Verify action creators should not be passed directly as arguments to React event handlers if there shouldn't be a payload\", () => {\n    const emptyAction = createAction<void>('empty/action')\n\n    function TestComponent() {\n      // This typically leads to an error like:\n      //  // A non-serializable value was detected in an action, in the path: `payload`.\n      // @ts-expect-error Should error because `void` and `MouseEvent` aren't compatible\n      return <button onClick={emptyAction}>+</button>\n    }\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/createAction.test.ts",
    "content": "import { createAction, isActionCreator } from '@reduxjs/toolkit'\n\ndescribe('createAction', () => {\n  it('should create an action', () => {\n    const actionCreator = createAction<string>('A_TYPE')\n    expect(actionCreator('something')).toEqual({\n      type: 'A_TYPE',\n      payload: 'something',\n    })\n  })\n\n  describe('when stringifying action', () => {\n    it('should return the action type', () => {\n      const actionCreator = createAction('A_TYPE')\n      expect(`${actionCreator}`).toEqual('A_TYPE')\n    })\n  })\n\n  describe('when passing a prepareAction method only returning a payload', () => {\n    it('should use the payload returned from the prepareAction method', () => {\n      const actionCreator = createAction('A_TYPE', (a: number) => ({\n        payload: a * 2,\n      }))\n      expect(actionCreator(5).payload).toBe(10)\n    })\n    it('should not have a meta attribute on the resulting Action', () => {\n      const actionCreator = createAction('A_TYPE', (a: number) => ({\n        payload: a * 2,\n      }))\n      expect('meta' in actionCreator(5)).toBeFalsy()\n    })\n  })\n\n  describe('when passing a prepareAction method returning a payload and meta', () => {\n    it('should use the payload returned from the prepareAction method', () => {\n      const actionCreator = createAction('A_TYPE', (a: number) => ({\n        payload: a * 2,\n        meta: a / 2,\n      }))\n      expect(actionCreator(5).payload).toBe(10)\n    })\n    it('should use the meta returned from the prepareAction method', () => {\n      const actionCreator = createAction('A_TYPE', (a: number) => ({\n        payload: a * 2,\n        meta: a / 2,\n      }))\n      expect(actionCreator(10).meta).toBe(5)\n    })\n  })\n\n  describe('when passing a prepareAction method returning a payload and error', () => {\n    it('should use the payload returned from the prepareAction method', () => {\n      const actionCreator = createAction('A_TYPE', (a: number) => ({\n        payload: a * 2,\n        error: true,\n      }))\n      expect(actionCreator(5).payload).toBe(10)\n    })\n    it('should use the error returned from the prepareAction method', () => {\n      const actionCreator = createAction('A_TYPE', (a: number) => ({\n        payload: a * 2,\n        error: true,\n      }))\n      expect(actionCreator(10).error).toBe(true)\n    })\n  })\n\n  describe('when passing a prepareAction method returning a payload, meta and error', () => {\n    it('should use the payload returned from the prepareAction method', () => {\n      const actionCreator = createAction('A_TYPE', (a: number) => ({\n        payload: a * 2,\n        meta: a / 2,\n        error: true,\n      }))\n      expect(actionCreator(5).payload).toBe(10)\n    })\n    it('should use the error returned from the prepareAction method', () => {\n      const actionCreator = createAction('A_TYPE', (a: number) => ({\n        payload: a * 2,\n        meta: a / 2,\n        error: true,\n      }))\n      expect(actionCreator(10).error).toBe(true)\n    })\n    it('should use the meta returned from the prepareAction method', () => {\n      const actionCreator = createAction('A_TYPE', (a: number) => ({\n        payload: a * 2,\n        meta: a / 2,\n        error: true,\n      }))\n      expect(actionCreator(10).meta).toBe(5)\n    })\n  })\n\n  describe('when passing a prepareAction that accepts multiple arguments', () => {\n    it('should pass all arguments of the resulting actionCreator to prepareAction', () => {\n      const actionCreator = createAction(\n        'A_TYPE',\n        (a: string, b: string, c: string) => ({\n          payload: a + b + c,\n        }),\n      )\n      expect(actionCreator('1', '2', '3').payload).toBe('123')\n    })\n  })\n\n  describe('actionCreator.match', () => {\n    test('should return true for actions generated by own actionCreator', () => {\n      const actionCreator = createAction('test')\n      expect(actionCreator.match(actionCreator())).toBe(true)\n    })\n\n    test('should return true for matching actions', () => {\n      const actionCreator = createAction('test')\n      expect(actionCreator.match({ type: 'test' })).toBe(true)\n    })\n\n    test('should return false for other actions', () => {\n      const actionCreator = createAction('test')\n      expect(actionCreator.match({ type: 'test-abc' })).toBe(false)\n    })\n  })\n})\n\nconst actionCreator = createAction('anAction')\n\nclass Action {\n  type = 'totally an action'\n}\n\ndescribe('isActionCreator', () => {\n  it('should only return true for action creators', () => {\n    expect(isActionCreator(actionCreator)).toBe(true)\n    const notActionCreators = [\n      { type: 'an action' },\n      { type: 'more props', extra: true },\n      actionCreator(),\n      Promise.resolve({ type: 'an action' }),\n      new Action(),\n      false,\n      'a string',\n      false,\n    ]\n    for (const notActionCreator of notActionCreators) {\n      expect(isActionCreator(notActionCreator)).toBe(false)\n    }\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/createAsyncThunk.test-d.ts",
    "content": "import type { TSVersion } from '@phryneas/ts-version'\nimport type {\n  AsyncThunk,\n  AsyncThunkDispatchConfig,\n  SerializedError,\n  ThunkDispatch,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createAsyncThunk,\n  createReducer,\n  createSlice,\n  unwrapResult,\n} from '@reduxjs/toolkit'\nimport type { AxiosError } from 'axios'\nimport apiRequest from 'axios'\n\nconst defaultDispatch = (() => {}) as ThunkDispatch<{}, any, UnknownAction>\nconst unknownAction = { type: 'foo' } as UnknownAction\n\ndescribe('type tests', () => {\n  test('basic usage', async () => {\n    const asyncThunk = createAsyncThunk('test', (id: number) =>\n      Promise.resolve(id * 2),\n    )\n\n    const reducer = createReducer({}, (builder) =>\n      builder\n        .addCase(asyncThunk.pending, (_, action) => {\n          expectTypeOf(action).toEqualTypeOf<\n            ReturnType<(typeof asyncThunk)['pending']>\n          >()\n        })\n\n        .addCase(asyncThunk.fulfilled, (_, action) => {\n          expectTypeOf(action).toEqualTypeOf<\n            ReturnType<(typeof asyncThunk)['fulfilled']>\n          >()\n\n          expectTypeOf(action.payload).toBeNumber()\n        })\n\n        .addCase(asyncThunk.rejected, (_, action) => {\n          expectTypeOf(action).toEqualTypeOf<\n            ReturnType<(typeof asyncThunk)['rejected']>\n          >()\n\n          expectTypeOf(action.error).toExtend<Partial<Error> | undefined>()\n        }),\n    )\n\n    const promise = defaultDispatch(asyncThunk(3))\n\n    expectTypeOf(promise.requestId).toBeString()\n\n    expectTypeOf(promise.arg).toBeNumber()\n\n    expectTypeOf(promise.abort).toEqualTypeOf<(reason?: string) => void>()\n\n    const result = await promise\n\n    if (asyncThunk.fulfilled.match(result)) {\n      expectTypeOf(result).toEqualTypeOf<\n        ReturnType<(typeof asyncThunk)['fulfilled']>\n      >()\n    } else {\n      expectTypeOf(result).toEqualTypeOf<\n        ReturnType<(typeof asyncThunk)['rejected']>\n      >()\n    }\n\n    promise\n      .then(unwrapResult)\n      .then((result) => {\n        expectTypeOf(result).toBeNumber()\n\n        expectTypeOf(result).not.toExtend<Error>()\n      })\n      .catch((error) => {\n        // catch is always any-typed, nothing we can do here\n        expectTypeOf(error).toBeAny()\n      })\n  })\n\n  test('More complex usage of thunk args', () => {\n    interface BookModel {\n      id: string\n      title: string\n    }\n\n    type BooksState = BookModel[]\n\n    const fakeBooks: BookModel[] = [\n      { id: 'b', title: 'Second' },\n      { id: 'a', title: 'First' },\n    ]\n\n    const correctDispatch = (() => {}) as ThunkDispatch<\n      BookModel[],\n      { userAPI: Function },\n      UnknownAction\n    >\n\n    // Verify that the the first type args to createAsyncThunk line up right\n    const fetchBooksTAC = createAsyncThunk<\n      BookModel[],\n      number,\n      {\n        state: BooksState\n        extra: { userAPI: Function }\n      }\n    >(\n      'books/fetch',\n      async (arg, { getState, dispatch, extra, requestId, signal }) => {\n        const state = getState()\n\n        expectTypeOf(arg).toBeNumber()\n\n        expectTypeOf(state).toEqualTypeOf<BookModel[]>()\n\n        expectTypeOf(extra).toEqualTypeOf<{ userAPI: Function }>()\n\n        return fakeBooks\n      },\n    )\n\n    correctDispatch(fetchBooksTAC(1))\n    // @ts-expect-error\n    defaultDispatch(fetchBooksTAC(1))\n  })\n\n  test('returning a rejected action from the promise creator is possible', async () => {\n    type ReturnValue = { data: 'success' }\n    type RejectValue = { data: 'error' }\n\n    const fetchBooksTAC = createAsyncThunk<\n      ReturnValue,\n      number,\n      {\n        rejectValue: RejectValue\n      }\n    >('books/fetch', async (arg, { rejectWithValue }) => {\n      return rejectWithValue({ data: 'error' })\n    })\n\n    const returned = await defaultDispatch(fetchBooksTAC(1))\n    if (fetchBooksTAC.rejected.match(returned)) {\n      expectTypeOf(returned.payload).toEqualTypeOf<undefined | RejectValue>()\n\n      expectTypeOf(returned.payload).toBeNullable()\n    } else {\n      expectTypeOf(returned.payload).toEqualTypeOf<ReturnValue>()\n    }\n\n    expectTypeOf(unwrapResult(returned)).toEqualTypeOf<ReturnValue>()\n\n    expectTypeOf(unwrapResult(returned)).not.toExtend<RejectValue>()\n  })\n\n  test('regression #1156: union return values fall back to allowing only single member', () => {\n    const fn = createAsyncThunk('session/isAdmin', async () => {\n      const response: boolean = false\n      return response\n    })\n  })\n\n  test('Should handle reject with value within a try catch block. Note: this is a sample code taken from #1605', () => {\n    type ResultType = {\n      text: string\n    }\n    const demoPromise = async (): Promise<ResultType> =>\n      new Promise((resolve, _) => resolve({ text: '' }))\n    const thunk = createAsyncThunk('thunk', async (args, thunkAPI) => {\n      try {\n        const result = await demoPromise()\n        return result\n      } catch (error) {\n        return thunkAPI.rejectWithValue(error)\n      }\n    })\n    createReducer({}, (builder) =>\n      builder.addCase(thunk.fulfilled, (s, action) => {\n        expectTypeOf(action.payload).toEqualTypeOf<ResultType>()\n      }),\n    )\n  })\n\n  test('reject with value', () => {\n    interface Item {\n      name: string\n    }\n\n    interface ErrorFromServer {\n      error: string\n    }\n\n    interface CallsResponse {\n      data: Item[]\n    }\n\n    const fetchLiveCallsError = createAsyncThunk<\n      Item[],\n      string,\n      {\n        rejectValue: ErrorFromServer\n      }\n    >('calls/fetchLiveCalls', async (organizationId, { rejectWithValue }) => {\n      try {\n        const result = await apiRequest.get<CallsResponse>(\n          `organizations/${organizationId}/calls/live/iwill404`,\n        )\n        return result.data.data\n      } catch (err) {\n        const error: AxiosError<ErrorFromServer> = err as any // cast for access to AxiosError properties\n        if (!error.response) {\n          // let it be handled as any other unknown error\n          throw err\n        }\n        return rejectWithValue(error.response && error.response.data)\n      }\n    })\n\n    defaultDispatch(fetchLiveCallsError('asd')).then((result) => {\n      if (fetchLiveCallsError.fulfilled.match(result)) {\n        //success\n        expectTypeOf(result).toEqualTypeOf<\n          ReturnType<(typeof fetchLiveCallsError)['fulfilled']>\n        >()\n\n        expectTypeOf(result.payload).toEqualTypeOf<Item[]>()\n      } else {\n        expectTypeOf(result).toEqualTypeOf<\n          ReturnType<(typeof fetchLiveCallsError)['rejected']>\n        >()\n\n        if (result.payload) {\n          // rejected with value\n          expectTypeOf(result.payload).toEqualTypeOf<ErrorFromServer>()\n        } else {\n          // rejected by throw\n          expectTypeOf(result.payload).toBeUndefined()\n\n          expectTypeOf(result.error).toEqualTypeOf<SerializedError>()\n\n          expectTypeOf(result.error).not.toBeAny()\n        }\n      }\n      defaultDispatch(fetchLiveCallsError('asd'))\n        .then((result) => {\n          expectTypeOf(result.payload).toEqualTypeOf<\n            Item[] | ErrorFromServer | undefined\n          >()\n\n          return result\n        })\n        .then(unwrapResult)\n        .then((unwrapped) => {\n          expectTypeOf(unwrapped).toEqualTypeOf<Item[]>()\n\n          expectTypeOf(unwrapResult)\n            .parameter(0)\n            .not.toExtend<typeof unwrapped>()\n        })\n    })\n  })\n\n  describe('payloadCreator first argument type has impact on asyncThunk argument', () => {\n    test('asyncThunk has no argument', () => {\n      const asyncThunk = createAsyncThunk('test', () => 0)\n\n      expectTypeOf(asyncThunk).toExtend<() => any>()\n\n      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<\n        [undefined?, AsyncThunkDispatchConfig?]\n      >()\n\n      expectTypeOf(asyncThunk).returns.toBeFunction()\n    })\n\n    test('one argument, specified as undefined: asyncThunk has no argument', () => {\n      const asyncThunk = createAsyncThunk('test', (arg: undefined) => 0)\n\n      expectTypeOf(asyncThunk).toExtend<() => any>()\n\n      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<\n        [undefined?, AsyncThunkDispatchConfig?]\n      >()\n    })\n\n    test('one argument, specified as void: asyncThunk has no argument', () => {\n      const asyncThunk = createAsyncThunk('test', (arg: void) => 0)\n\n      expectTypeOf(asyncThunk).toExtend<() => any>()\n    })\n\n    test('one argument, specified as optional number: asyncThunk has optional number argument', () => {\n      // this test will fail with strictNullChecks: false, that is to be expected\n      // in that case, we have to forbid this behavior or it will make arguments optional everywhere\n      const asyncThunk = createAsyncThunk('test', (arg?: number) => 0)\n\n      // Per https://github.com/reduxjs/redux-toolkit/issues/3758#issuecomment-1742152774 , this is a bug in\n      // TS 5.1 and 5.2, that is fixed in 5.3. Conditionally run the TS assertion here.\n      type IsTS51Or52 = TSVersion.Major extends 5\n        ? TSVersion.Minor extends 1 | 2\n          ? true\n          : false\n        : false\n\n      type expectedType = IsTS51Or52 extends true\n        ? (arg: number) => any\n        : (arg?: number) => any\n\n      expectTypeOf(asyncThunk).toExtend<expectedType>()\n\n      // We _should_ be able to call this with no arguments, but we run into that error in 5.1 and 5.2.\n      // Disabling this for now.\n      // asyncThunk()\n      expectTypeOf(asyncThunk).toBeCallableWith(5)\n\n      expectTypeOf(asyncThunk).parameters.not.toExtend<[string]>()\n    })\n\n    test('one argument, specified as number|undefined: asyncThunk has optional number argument', () => {\n      // this test will fail with strictNullChecks: false, that is to be expected\n      // in that case, we have to forbid this behavior or it will make arguments optional everywhere\n      const asyncThunk = createAsyncThunk(\n        'test',\n        (arg: number | undefined) => 0,\n      )\n\n      expectTypeOf(asyncThunk).toExtend<(arg?: number) => any>()\n\n      expectTypeOf(asyncThunk).toBeCallableWith()\n\n      expectTypeOf(asyncThunk).toBeCallableWith(undefined)\n\n      expectTypeOf(asyncThunk).toBeCallableWith(5)\n\n      expectTypeOf(asyncThunk).parameters.not.toExtend<[string]>()\n    })\n\n    test('one argument, specified as number|void: asyncThunk has optional number argument', () => {\n      const asyncThunk = createAsyncThunk('test', (arg: number | void) => 0)\n\n      expectTypeOf(asyncThunk).toExtend<(arg?: number) => any>()\n\n      expectTypeOf(asyncThunk).toBeCallableWith()\n\n      expectTypeOf(asyncThunk).toBeCallableWith(undefined)\n\n      expectTypeOf(asyncThunk).toBeCallableWith(5)\n\n      expectTypeOf(asyncThunk).parameters.not.toExtend<[string]>()\n    })\n\n    test('one argument, specified as any: asyncThunk has required any argument', () => {\n      const asyncThunk = createAsyncThunk('test', (arg: any) => 0)\n\n      expectTypeOf(asyncThunk).parameter(0).toBeAny()\n\n      expectTypeOf(asyncThunk).toBeCallableWith(5)\n\n      expectTypeOf(asyncThunk).parameters.not.toExtend<[]>()\n    })\n\n    test('one argument, specified as unknown: asyncThunk has required unknown argument', () => {\n      const asyncThunk = createAsyncThunk('test', (arg: unknown) => 0)\n\n      expectTypeOf(asyncThunk).parameter(0).toBeUnknown()\n\n      expectTypeOf(asyncThunk).toBeCallableWith(5)\n\n      expectTypeOf(asyncThunk).parameters.not.toExtend<[]>()\n    })\n\n    test('one argument, specified as number: asyncThunk has required number argument', () => {\n      const asyncThunk = createAsyncThunk('test', (arg: number) => 0)\n\n      expectTypeOf(asyncThunk).toExtend<(arg: number) => any>()\n\n      expectTypeOf(asyncThunk).toBeCallableWith(5)\n\n      expectTypeOf(asyncThunk).parameters.not.toExtend<[]>()\n    })\n\n    test('two arguments, first specified as undefined: asyncThunk has no argument', () => {\n      const asyncThunk = createAsyncThunk(\n        'test',\n        (arg: undefined, thunkApi) => 0,\n      )\n\n      expectTypeOf(asyncThunk).toExtend<() => any>()\n\n      expectTypeOf(asyncThunk).toBeCallableWith()\n\n      expectTypeOf(asyncThunk).toBeCallableWith(undefined)\n\n      // cannot be called with an argument\n      expectTypeOf(asyncThunk).parameter(0).not.toBeAny()\n\n      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<\n        [undefined?, AsyncThunkDispatchConfig?]\n      >()\n    })\n\n    test('two arguments, first specified as void: asyncThunk has no argument', () => {\n      const asyncThunk = createAsyncThunk('test', (arg: void, thunkApi) => 0)\n\n      expectTypeOf(asyncThunk).toExtend<() => any>()\n\n      expectTypeOf(asyncThunk).toBeCallableWith()\n\n      expectTypeOf(asyncThunk).parameter(0).toBeVoid()\n\n      // cannot be called with an argument\n      expectTypeOf(asyncThunk).parameter(0).not.toBeAny()\n\n      expectTypeOf(asyncThunk).parameters.toEqualTypeOf<\n        [undefined?, AsyncThunkDispatchConfig?]\n      >()\n    })\n\n    test('two arguments, first specified as number|undefined: asyncThunk has optional number argument', () => {\n      // this test will fail with strictNullChecks: false, that is to be expected\n      // in that case, we have to forbid this behavior or it will make arguments optional everywhere\n      const asyncThunk = createAsyncThunk(\n        'test',\n        (arg: number | undefined, thunkApi) => 0,\n      )\n\n      expectTypeOf(asyncThunk).toExtend<(arg?: number) => any>()\n\n      expectTypeOf(asyncThunk).toBeCallableWith()\n\n      expectTypeOf(asyncThunk).toBeCallableWith(undefined)\n\n      expectTypeOf(asyncThunk).toBeCallableWith(5)\n\n      expectTypeOf(asyncThunk).parameter(0).not.toBeString()\n    })\n\n    test('two arguments, first specified as number|void: asyncThunk has optional number argument', () => {\n      const asyncThunk = createAsyncThunk(\n        'test',\n        (arg: number | void, thunkApi) => 0,\n      )\n\n      expectTypeOf(asyncThunk).toExtend<(arg?: number) => any>()\n\n      expectTypeOf(asyncThunk).toBeCallableWith()\n\n      expectTypeOf(asyncThunk).toBeCallableWith(undefined)\n\n      expectTypeOf(asyncThunk).toBeCallableWith(5)\n\n      expectTypeOf(asyncThunk).parameter(0).not.toBeString()\n    })\n\n    test('two arguments, first specified as any: asyncThunk has required any argument', () => {\n      const asyncThunk = createAsyncThunk('test', (arg: any, thunkApi) => 0)\n\n      expectTypeOf(asyncThunk).parameter(0).toBeAny()\n\n      expectTypeOf(asyncThunk).toBeCallableWith(5)\n\n      expectTypeOf(asyncThunk).parameters.not.toExtend<[]>()\n    })\n\n    test('two arguments, first specified as unknown: asyncThunk has required unknown argument', () => {\n      const asyncThunk = createAsyncThunk('test', (arg: unknown, thunkApi) => 0)\n\n      expectTypeOf(asyncThunk).parameter(0).toBeUnknown()\n\n      expectTypeOf(asyncThunk).toBeCallableWith(5)\n\n      expectTypeOf(asyncThunk).parameters.not.toExtend<[]>()\n    })\n\n    test('two arguments, first specified as number: asyncThunk has required number argument', () => {\n      const asyncThunk = createAsyncThunk('test', (arg: number, thunkApi) => 0)\n\n      expectTypeOf(asyncThunk).toExtend<(arg: number) => any>()\n\n      expectTypeOf(asyncThunk).parameter(0).toBeNumber()\n\n      expectTypeOf(asyncThunk).toBeCallableWith(5)\n\n      expectTypeOf(asyncThunk).parameters.not.toExtend<[]>()\n    })\n  })\n\n  test('createAsyncThunk without generics', () => {\n    const thunk = createAsyncThunk('test', () => {\n      return 'ret' as const\n    })\n\n    expectTypeOf(thunk).toEqualTypeOf<AsyncThunk<'ret', void, {}>>()\n  })\n\n  test('createAsyncThunk without generics, accessing `api` does not break return type', () => {\n    const thunk = createAsyncThunk('test', (_: void, api) => {\n      return 'ret' as const\n    })\n\n    expectTypeOf(thunk).toEqualTypeOf<AsyncThunk<'ret', void, {}>>()\n  })\n\n  test('createAsyncThunk rejectWithValue without generics: Expect correct return type', () => {\n    const asyncThunk = createAsyncThunk(\n      'test',\n      (_: void, { rejectWithValue }) => {\n        try {\n          return Promise.resolve(true)\n        } catch (e) {\n          return rejectWithValue(e)\n        }\n      },\n    )\n\n    defaultDispatch(asyncThunk())\n      .then((result) => {\n        if (asyncThunk.fulfilled.match(result)) {\n          expectTypeOf(result).toEqualTypeOf<\n            ReturnType<(typeof asyncThunk)['fulfilled']>\n          >()\n\n          expectTypeOf(result.payload).toBeBoolean()\n\n          expectTypeOf(result).not.toHaveProperty('error')\n        } else {\n          expectTypeOf(result).toEqualTypeOf<\n            ReturnType<(typeof asyncThunk)['rejected']>\n          >()\n\n          expectTypeOf(result.error).toEqualTypeOf<SerializedError>()\n\n          expectTypeOf(result.payload).toBeUnknown()\n        }\n\n        return result\n      })\n      .then(unwrapResult)\n      .then((unwrapped) => {\n        expectTypeOf(unwrapped).toBeBoolean()\n      })\n  })\n\n  test('createAsyncThunk with generics', () => {\n    type Funky = { somethingElse: 'Funky!' }\n    function funkySerializeError(err: any): Funky {\n      return { somethingElse: 'Funky!' }\n    }\n\n    // has to stay on one line or type tests fail in older TS versions\n    // prettier-ignore\n    // @ts-expect-error\n    const shouldFail = createAsyncThunk('without generics', () => {}, { serializeError: funkySerializeError })\n\n    const shouldWork = createAsyncThunk<\n      any,\n      void,\n      { serializedErrorType: Funky }\n    >('with generics', () => {}, {\n      serializeError: funkySerializeError,\n    })\n\n    if (shouldWork.rejected.match(unknownAction)) {\n      expectTypeOf(unknownAction.error).toEqualTypeOf<Funky>()\n    }\n  })\n\n  test('`idGenerator` option takes no arguments, and returns a string', () => {\n    const returnsNumWithArgs = (foo: any) => 100\n    // has to stay on one line or type tests fail in older TS versions\n    // prettier-ignore\n    // @ts-expect-error\n    const shouldFailNumWithArgs = createAsyncThunk('foo', () => {}, { idGenerator: returnsNumWithArgs })\n\n    const returnsNumWithoutArgs = () => 100\n    // prettier-ignore\n    // @ts-expect-error\n    const shouldFailNumWithoutArgs = createAsyncThunk('foo', () => {}, { idGenerator: returnsNumWithoutArgs })\n\n    const returnsStrWithNumberArg = (foo: number) => 'foo'\n    // prettier-ignore\n    // @ts-expect-error\n    const shouldFailWrongArgs = createAsyncThunk('foo', (arg: string) => {}, { idGenerator: returnsStrWithNumberArg })\n\n    const returnsStrWithStringArg = (foo: string) => 'foo'\n    const shoulducceedCorrectArgs = createAsyncThunk(\n      'foo',\n      (arg: string) => {},\n      {\n        idGenerator: returnsStrWithStringArg,\n      },\n    )\n\n    const returnsStrWithoutArgs = () => 'foo'\n    const shouldSucceed = createAsyncThunk('foo', () => {}, {\n      idGenerator: returnsStrWithoutArgs,\n    })\n  })\n\n  test('fulfillWithValue should infer return value', () => {\n    // https://github.com/reduxjs/redux-toolkit/issues/2886\n\n    const initialState = {\n      loading: false,\n      obj: { magic: '' },\n    }\n\n    const getObj = createAsyncThunk(\n      'slice/getObj',\n      async (_: any, { fulfillWithValue, rejectWithValue }) => {\n        try {\n          return fulfillWithValue({ magic: 'object' })\n        } catch (rejected: any) {\n          return rejectWithValue(rejected?.response?.error || rejected)\n        }\n      },\n    )\n\n    createSlice({\n      name: 'slice',\n      initialState,\n      reducers: {},\n      extraReducers: (builder) => {\n        builder.addCase(getObj.fulfilled, (state, action) => {\n          expectTypeOf(action.payload).toEqualTypeOf<{ magic: string }>()\n        })\n      },\n    })\n  })\n\n  test('meta return values', () => {\n    // return values\n    createAsyncThunk<'ret', void, {}>('test', (_, api) => 'ret' as const)\n    createAsyncThunk<'ret', void, {}>('test', async (_, api) => 'ret' as const)\n    createAsyncThunk<'ret', void, { fulfilledMeta: string }>('test', (_, api) =>\n      api.fulfillWithValue('ret' as const, ''),\n    )\n    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(\n      'test',\n      async (_, api) => api.fulfillWithValue('ret' as const, ''),\n    )\n    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(\n      'test',\n      // @ts-expect-error has to be a fulfilledWithValue call\n      (_, api) => 'ret' as const,\n    )\n    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(\n      'test',\n      // @ts-expect-error has to be a fulfilledWithValue call\n      async (_, api) => 'ret' as const,\n    )\n    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(\n      'test', // @ts-expect-error should only allow returning with 'test'\n      (_, api) => api.fulfillWithValue(5, ''),\n    )\n    createAsyncThunk<'ret', void, { fulfilledMeta: string }>(\n      'test', // @ts-expect-error should only allow returning with 'test'\n      async (_, api) => api.fulfillWithValue(5, ''),\n    )\n\n    // reject values\n    createAsyncThunk<'ret', void, { rejectValue: string }>('test', (_, api) =>\n      api.rejectWithValue('ret'),\n    )\n    createAsyncThunk<'ret', void, { rejectValue: string }>(\n      'test',\n      async (_, api) => api.rejectWithValue('ret'),\n    )\n    createAsyncThunk<\n      'ret',\n      void,\n      { rejectValue: string; rejectedMeta: number }\n    >('test', (_, api) => api.rejectWithValue('ret', 5))\n    createAsyncThunk<\n      'ret',\n      void,\n      { rejectValue: string; rejectedMeta: number }\n    >('test', async (_, api) => api.rejectWithValue('ret', 5))\n    createAsyncThunk<\n      'ret',\n      void,\n      { rejectValue: string; rejectedMeta: number }\n    >('test', (_, api) => api.rejectWithValue('ret', 5))\n    createAsyncThunk<\n      'ret',\n      void,\n      { rejectValue: string; rejectedMeta: number }\n    >(\n      'test',\n      // @ts-expect-error wrong rejectedMeta type\n      (_, api) => api.rejectWithValue('ret', ''),\n    )\n    createAsyncThunk<\n      'ret',\n      void,\n      { rejectValue: string; rejectedMeta: number }\n    >(\n      'test',\n      // @ts-expect-error wrong rejectedMeta type\n      async (_, api) => api.rejectWithValue('ret', ''),\n    )\n    createAsyncThunk<\n      'ret',\n      void,\n      { rejectValue: string; rejectedMeta: number }\n    >(\n      'test',\n      // @ts-expect-error wrong rejectValue type\n      (_, api) => api.rejectWithValue(5, ''),\n    )\n    createAsyncThunk<\n      'ret',\n      void,\n      { rejectValue: string; rejectedMeta: number }\n    >(\n      'test',\n      // @ts-expect-error wrong rejectValue type\n      async (_, api) => api.rejectWithValue(5, ''),\n    )\n  })\n\n  test('usage with config override generic', () => {\n    const typedCAT = createAsyncThunk.withTypes<{\n      state: RootState\n      dispatch: AppDispatch\n      rejectValue: string\n      extra: { s: string; n: number }\n    }>()\n\n    // inferred usage\n    const thunk = typedCAT('foo', (arg: number, api) => {\n      // correct getState Type\n      const test1: number = api.getState().foo.value\n      // correct dispatch type\n      const test2: number = api.dispatch((dispatch, getState) => {\n        expectTypeOf(dispatch).toEqualTypeOf<\n          ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>\n        >()\n\n        expectTypeOf(getState).toEqualTypeOf<() => { foo: { value: number } }>()\n\n        return getState().foo.value\n      })\n\n      // correct extra type\n      const { s, n } = api.extra\n\n      expectTypeOf(s).toBeString()\n\n      expectTypeOf(n).toBeNumber()\n\n      if (1 < 2)\n        // @ts-expect-error\n        return api.rejectWithValue(5)\n      if (1 < 2) return api.rejectWithValue('test')\n      return test1 + test2\n    })\n\n    // usage with two generics\n    const thunk2 = typedCAT<number, string>('foo', (arg, api) => {\n      expectTypeOf(arg).toBeString()\n\n      // correct getState Type\n      const test1: number = api.getState().foo.value\n      // correct dispatch type\n      const test2: number = api.dispatch((dispatch, getState) => {\n        expectTypeOf(dispatch).toEqualTypeOf<\n          ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>\n        >()\n\n        expectTypeOf(getState).toEqualTypeOf<() => { foo: { value: number } }>()\n\n        return getState().foo.value\n      })\n      // correct extra type\n      const { s, n } = api.extra\n\n      expectTypeOf(s).toBeString()\n\n      expectTypeOf(n).toBeNumber()\n\n      if (1 < 2) expectTypeOf(api.rejectWithValue).toBeCallableWith('test')\n\n      expectTypeOf(api.rejectWithValue).parameter(0).not.toBeNumber()\n\n      expectTypeOf(api.rejectWithValue).parameters.toEqualTypeOf<[string]>()\n\n      return api.rejectWithValue('test')\n    })\n\n    // usage with config override generic\n    const thunk3 = typedCAT<number, string, { rejectValue: number }>(\n      'foo',\n      (arg, api) => {\n        expectTypeOf(arg).toBeString()\n\n        // correct getState Type\n        const test1: number = api.getState().foo.value\n        // correct dispatch type\n        const test2: number = api.dispatch((dispatch, getState) => {\n          expectTypeOf(dispatch).toEqualTypeOf<\n            ThunkDispatch<{ foo: { value: number } }, undefined, UnknownAction>\n          >()\n\n          expectTypeOf(getState).toEqualTypeOf<\n            () => { foo: { value: number } }\n          >()\n\n          return getState().foo.value\n        })\n        // correct extra type\n        const { s, n } = api.extra\n\n        expectTypeOf(s).toBeString()\n\n        expectTypeOf(n).toBeNumber()\n\n        if (1 < 2) return api.rejectWithValue(5)\n        if (1 < 2) expectTypeOf(api.rejectWithValue).toBeCallableWith(5)\n\n        expectTypeOf(api.rejectWithValue).parameter(0).not.toBeString()\n\n        expectTypeOf(api.rejectWithValue).parameters.toEqualTypeOf<[number]>()\n\n        return api.rejectWithValue(5)\n      },\n    )\n\n    const slice = createSlice({\n      name: 'foo',\n      initialState: { value: 0 },\n      reducers: {},\n      extraReducers(builder) {\n        builder\n          .addCase(thunk.fulfilled, (state, action) => {\n            state.value += action.payload\n          })\n          .addCase(thunk.rejected, (state, action) => {\n            expectTypeOf(action.payload).toEqualTypeOf<string | undefined>()\n          })\n          .addCase(thunk2.fulfilled, (state, action) => {\n            state.value += action.payload\n          })\n          .addCase(thunk2.rejected, (state, action) => {\n            expectTypeOf(action.payload).toEqualTypeOf<string | undefined>()\n          })\n          .addCase(thunk3.fulfilled, (state, action) => {\n            state.value += action.payload\n          })\n          .addCase(thunk3.rejected, (state, action) => {\n            expectTypeOf(action.payload).toEqualTypeOf<number | undefined>()\n          })\n      },\n    })\n\n    const store = configureStore({\n      reducer: {\n        foo: slice.reducer,\n      },\n    })\n\n    type RootState = ReturnType<typeof store.getState>\n    type AppDispatch = typeof store.dispatch\n  })\n\n  test('rejectedMeta', async () => {\n    const getNewStore = () =>\n      configureStore({\n        reducer(actions = [], action) {\n          return [...actions, action]\n        },\n      })\n\n    const store = getNewStore()\n\n    const fulfilledThunk = createAsyncThunk<\n      string,\n      string,\n      { rejectedMeta: { extraProp: string } }\n    >('test', (arg: string, { rejectWithValue }) => {\n      return rejectWithValue('damn!', { extraProp: 'baz' })\n    })\n\n    const promise = store.dispatch(fulfilledThunk('testArg'))\n\n    const ret = await promise\n\n    if (ret.meta.requestStatus === 'rejected' && ret.meta.rejectedWithValue) {\n      expectTypeOf(ret.meta.extraProp).toBeString()\n    } else {\n      // could be caused by a `throw`, `abort()` or `condition` - no `rejectedMeta` in that case\n      expectTypeOf(ret.meta).not.toHaveProperty('extraProp')\n    }\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/createAsyncThunk.test.ts",
    "content": "import { noop } from '@internal/listenerMiddleware/utils'\nimport { delay, promiseWithResolvers } from '@internal/utils'\nimport type { CreateAsyncThunkFunction, UnknownAction } from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createAsyncThunk,\n  createReducer,\n  miniSerializeError,\n  unwrapResult,\n} from '@reduxjs/toolkit'\n\ndeclare global {\n  interface Window {\n    AbortController: AbortController\n  }\n}\n\ndescribe('createAsyncThunk', () => {\n  it('creates the action types', () => {\n    const thunkActionCreator = createAsyncThunk('testType', async () => 42)\n\n    expect(thunkActionCreator.fulfilled.type).toBe('testType/fulfilled')\n    expect(thunkActionCreator.pending.type).toBe('testType/pending')\n    expect(thunkActionCreator.rejected.type).toBe('testType/rejected')\n  })\n\n  it('exposes the typePrefix it was created with', () => {\n    const thunkActionCreator = createAsyncThunk('testType', async () => 42)\n\n    expect(thunkActionCreator.typePrefix).toBe('testType')\n  })\n\n  it('includes a settled matcher', () => {\n    const thunkActionCreator = createAsyncThunk('testType', async () => 42)\n    expect(thunkActionCreator.settled).toEqual(expect.any(Function))\n    expect(thunkActionCreator.settled(thunkActionCreator.pending(''))).toBe(\n      false,\n    )\n    expect(\n      thunkActionCreator.settled(thunkActionCreator.rejected(null, '')),\n    ).toBe(true)\n    expect(\n      thunkActionCreator.settled(thunkActionCreator.fulfilled(42, '')),\n    ).toBe(true)\n  })\n\n  it('works without passing arguments to the payload creator', async () => {\n    const thunkActionCreator = createAsyncThunk('testType', async () => 42)\n\n    let timesReducerCalled = 0\n\n    const reducer = () => {\n      timesReducerCalled++\n    }\n\n    const store = configureStore({\n      reducer,\n    })\n\n    // reset from however many times the store called it\n    timesReducerCalled = 0\n\n    await store.dispatch(thunkActionCreator())\n\n    expect(timesReducerCalled).toBe(2)\n  })\n\n  it('accepts arguments and dispatches the actions on resolve', async () => {\n    const dispatch = vi.fn()\n\n    let passedArg: any\n\n    const result = 42\n    const args = 123\n    let generatedRequestId = ''\n\n    const thunkActionCreator = createAsyncThunk(\n      'testType',\n      async (arg: number, { requestId }) => {\n        passedArg = arg\n        generatedRequestId = requestId\n        return result\n      },\n    )\n\n    const thunkFunction = thunkActionCreator(args)\n\n    const thunkPromise = thunkFunction(dispatch, () => {}, undefined)\n\n    expect(thunkPromise.requestId).toBe(generatedRequestId)\n    expect(thunkPromise.arg).toBe(args)\n\n    await thunkPromise\n\n    expect(passedArg).toBe(args)\n\n    expect(dispatch).toHaveBeenNthCalledWith(\n      1,\n      thunkActionCreator.pending(generatedRequestId, args),\n    )\n\n    expect(dispatch).toHaveBeenNthCalledWith(\n      2,\n      thunkActionCreator.fulfilled(result, generatedRequestId, args),\n    )\n  })\n\n  it('accepts arguments and dispatches the actions on reject', async () => {\n    const dispatch = vi.fn()\n\n    const args = 123\n    let generatedRequestId = ''\n\n    const error = new Error('Panic!')\n\n    const thunkActionCreator = createAsyncThunk(\n      'testType',\n      async (args: number, { requestId }) => {\n        generatedRequestId = requestId\n        throw error\n      },\n    )\n\n    const thunkFunction = thunkActionCreator(args)\n\n    try {\n      await thunkFunction(dispatch, () => {}, undefined)\n    } catch (e) {}\n\n    expect(dispatch).toHaveBeenNthCalledWith(\n      1,\n      thunkActionCreator.pending(generatedRequestId, args),\n    )\n\n    expect(dispatch).toHaveBeenCalledTimes(2)\n\n    // Have to check the bits of the action separately since the error was processed\n    const errorAction = dispatch.mock.calls[1][0]\n    expect(errorAction.error).toEqual(miniSerializeError(error))\n    expect(errorAction.meta.requestId).toBe(generatedRequestId)\n    expect(errorAction.meta.arg).toBe(args)\n  })\n\n  it('dispatches an empty error when throwing a random object without serializedError properties', async () => {\n    const dispatch = vi.fn()\n\n    const args = 123\n    let generatedRequestId = ''\n\n    const errorObject = { wny: 'dothis' }\n\n    const thunkActionCreator = createAsyncThunk(\n      'testType',\n      async (args: number, { requestId }) => {\n        generatedRequestId = requestId\n        throw errorObject\n      },\n    )\n\n    const thunkFunction = thunkActionCreator(args)\n\n    try {\n      await thunkFunction(dispatch, () => {}, undefined)\n    } catch (e) {}\n\n    expect(dispatch).toHaveBeenNthCalledWith(\n      1,\n      thunkActionCreator.pending(generatedRequestId, args),\n    )\n\n    expect(dispatch).toHaveBeenCalledTimes(2)\n\n    const errorAction = dispatch.mock.calls[1][0]\n    expect(errorAction.error).toEqual({})\n    expect(errorAction.meta.requestId).toBe(generatedRequestId)\n    expect(errorAction.meta.arg).toBe(args)\n  })\n\n  it('dispatches an action with a formatted error when throwing an object with known error keys', async () => {\n    const dispatch = vi.fn()\n\n    const args = 123\n    let generatedRequestId = ''\n\n    const errorObject = {\n      name: 'Custom thrown error',\n      message: 'This is not necessary',\n      code: '400',\n    }\n\n    const thunkActionCreator = createAsyncThunk(\n      'testType',\n      async (args: number, { requestId }) => {\n        generatedRequestId = requestId\n        throw errorObject\n      },\n    )\n\n    const thunkFunction = thunkActionCreator(args)\n\n    try {\n      await thunkFunction(dispatch, () => {}, undefined)\n    } catch (e) {}\n\n    expect(dispatch).toHaveBeenNthCalledWith(\n      1,\n      thunkActionCreator.pending(generatedRequestId, args),\n    )\n\n    expect(dispatch).toHaveBeenCalledTimes(2)\n\n    // Have to check the bits of the action separately since the error was processed\n    const errorAction = dispatch.mock.calls[1][0]\n    expect(errorAction.error).toEqual(miniSerializeError(errorObject))\n    expect(Object.keys(errorAction.error)).not.toContain('stack')\n    expect(errorAction.meta.requestId).toBe(generatedRequestId)\n    expect(errorAction.meta.arg).toBe(args)\n  })\n\n  it('dispatches a rejected action with a customized payload when a user returns rejectWithValue()', async () => {\n    const dispatch = vi.fn()\n\n    const args = 123\n    let generatedRequestId = ''\n\n    const errorPayload = {\n      errorMessage:\n        'I am a fake server-provided 400 payload with validation details',\n      errors: [\n        { field_one: 'Must be a string' },\n        { field_two: 'Must be a number' },\n      ],\n    }\n\n    const thunkActionCreator = createAsyncThunk(\n      'testType',\n      async (args: number, { requestId, rejectWithValue }) => {\n        generatedRequestId = requestId\n\n        return rejectWithValue(errorPayload)\n      },\n    )\n\n    const thunkFunction = thunkActionCreator(args)\n\n    try {\n      await thunkFunction(dispatch, () => {}, undefined)\n    } catch (e) {}\n\n    expect(dispatch).toHaveBeenNthCalledWith(\n      1,\n      thunkActionCreator.pending(generatedRequestId, args),\n    )\n\n    expect(dispatch).toHaveBeenCalledTimes(2)\n\n    // Have to check the bits of the action separately since the error was processed\n    const errorAction = dispatch.mock.calls[1][0]\n\n    expect(errorAction.error.message).toEqual('Rejected')\n    expect(errorAction.payload).toBe(errorPayload)\n    expect(errorAction.meta.arg).toBe(args)\n  })\n\n  it('dispatches a rejected action with a customized payload when a user throws rejectWithValue()', async () => {\n    const dispatch = vi.fn()\n\n    const args = 123\n    let generatedRequestId = ''\n\n    const errorPayload = {\n      errorMessage:\n        'I am a fake server-provided 400 payload with validation details',\n      errors: [\n        { field_one: 'Must be a string' },\n        { field_two: 'Must be a number' },\n      ],\n    }\n\n    const thunkActionCreator = createAsyncThunk(\n      'testType',\n      async (args: number, { requestId, rejectWithValue }) => {\n        generatedRequestId = requestId\n\n        throw rejectWithValue(errorPayload)\n      },\n    )\n\n    const thunkFunction = thunkActionCreator(args)\n\n    try {\n      await thunkFunction(dispatch, () => {}, undefined)\n    } catch (e) {}\n\n    expect(dispatch).toHaveBeenNthCalledWith(\n      1,\n      thunkActionCreator.pending(generatedRequestId, args),\n    )\n\n    expect(dispatch).toHaveBeenCalledTimes(2)\n\n    // Have to check the bits of the action separately since the error was processed\n    const errorAction = dispatch.mock.calls[1][0]\n\n    expect(errorAction.error.message).toEqual('Rejected')\n    expect(errorAction.payload).toBe(errorPayload)\n    expect(errorAction.meta.arg).toBe(args)\n  })\n\n  it('dispatches a rejected action with a miniSerializeError when rejectWithValue conditions are not satisfied', async () => {\n    const dispatch = vi.fn()\n\n    const args = 123\n    let generatedRequestId = ''\n\n    const error = new Error('Panic!')\n\n    const errorPayload = {\n      errorMessage:\n        'I am a fake server-provided 400 payload with validation details',\n      errors: [\n        { field_one: 'Must be a string' },\n        { field_two: 'Must be a number' },\n      ],\n    }\n\n    const thunkActionCreator = createAsyncThunk(\n      'testType',\n      async (args: number, { requestId, rejectWithValue }) => {\n        generatedRequestId = requestId\n\n        try {\n          throw error\n        } catch (err) {\n          if (!(err as any).response) {\n            throw err\n          }\n          return rejectWithValue(errorPayload)\n        }\n      },\n    )\n\n    const thunkFunction = thunkActionCreator(args)\n\n    try {\n      await thunkFunction(dispatch, () => {}, undefined)\n    } catch (e) {}\n\n    expect(dispatch).toHaveBeenNthCalledWith(\n      1,\n      thunkActionCreator.pending(generatedRequestId, args),\n    )\n\n    expect(dispatch).toHaveBeenCalledTimes(2)\n\n    // Have to check the bits of the action separately since the error was processed\n    const errorAction = dispatch.mock.calls[1][0]\n    expect(errorAction.error).toEqual(miniSerializeError(error))\n    expect(errorAction.payload).toEqual(undefined)\n    expect(errorAction.meta.requestId).toBe(generatedRequestId)\n    expect(errorAction.meta.arg).toBe(args)\n  })\n})\n\ndescribe('createAsyncThunk with abortController', () => {\n  const asyncThunk = createAsyncThunk(\n    'test',\n    function abortablePayloadCreator(_: any, { signal }) {\n      return new Promise((resolve, reject) => {\n        if (signal.aborted) {\n          reject(\n            new DOMException(\n              'This should never be reached as it should already be handled.',\n              'AbortError',\n            ),\n          )\n        }\n        signal.addEventListener('abort', () => {\n          reject(new DOMException('Was aborted while running', 'AbortError'))\n        })\n        setTimeout(resolve, 100)\n      })\n    },\n  )\n\n  let store = configureStore({\n    reducer(store: UnknownAction[] = []) {\n      return store\n    },\n  })\n\n  beforeEach(() => {\n    store = configureStore({\n      reducer(store: UnknownAction[] = [], action) {\n        return [...store, action]\n      },\n    })\n  })\n\n  test('normal usage', async () => {\n    await store.dispatch(asyncThunk({}))\n    expect(store.getState()).toEqual([\n      expect.any(Object),\n      expect.objectContaining({ type: 'test/pending' }),\n      expect.objectContaining({ type: 'test/fulfilled' }),\n    ])\n  })\n\n  test('abort after dispatch', async () => {\n    const promise = store.dispatch(asyncThunk({}))\n    promise.abort('AbortReason')\n    const result = await promise\n    const expectedAbortedAction = {\n      type: 'test/rejected',\n      error: {\n        message: 'AbortReason',\n        name: 'AbortError',\n      },\n      meta: { aborted: true, requestId: promise.requestId },\n    }\n\n    // abortedAction with reason is dispatched after test/pending is dispatched\n    expect(store.getState()).toMatchObject([\n      {},\n      { type: 'test/pending' },\n      expectedAbortedAction,\n    ])\n\n    // same abortedAction is returned, but with the AbortError from the abortablePayloadCreator\n    expect(result).toMatchObject(expectedAbortedAction)\n\n    // calling unwrapResult on the returned object re-throws the error from the abortablePayloadCreator\n    expect(() => unwrapResult(result)).toThrowError(\n      expect.objectContaining(expectedAbortedAction.error),\n    )\n  })\n\n  test('even when the payloadCreator does not directly support the signal, no further actions are dispatched', async () => {\n    const unawareAsyncThunk = createAsyncThunk('unaware', async () => {\n      await new Promise((resolve) => setTimeout(resolve, 100))\n      return 'finished'\n    })\n\n    const promise = store.dispatch(unawareAsyncThunk())\n    promise.abort('AbortReason')\n    const result = await promise\n\n    const expectedAbortedAction = {\n      type: 'unaware/rejected',\n      error: {\n        message: 'AbortReason',\n        name: 'AbortError',\n      },\n    }\n\n    // abortedAction with reason is dispatched after test/pending is dispatched\n    expect(store.getState()).toEqual([\n      expect.any(Object),\n      expect.objectContaining({ type: 'unaware/pending' }),\n      expect.objectContaining(expectedAbortedAction),\n    ])\n\n    // same abortedAction is returned, but with the AbortError from the abortablePayloadCreator\n    expect(result).toMatchObject(expectedAbortedAction)\n\n    // calling unwrapResult on the returned object re-throws the error from the abortablePayloadCreator\n    expect(() => unwrapResult(result)).toThrowError(\n      expect.objectContaining(expectedAbortedAction.error),\n    )\n  })\n\n  test('dispatch(asyncThunk) returns on abort and does not wait for the promiseProvider to finish', async () => {\n    let running = false\n    const longRunningAsyncThunk = createAsyncThunk('longRunning', async () => {\n      running = true\n      await new Promise((resolve) => setTimeout(resolve, 30000))\n      running = false\n    })\n\n    const promise = store.dispatch(longRunningAsyncThunk())\n    expect(running).toBeTruthy()\n    promise.abort()\n    const result = await promise\n    expect(running).toBeTruthy()\n    expect(result).toMatchObject({\n      type: 'longRunning/rejected',\n      error: { message: 'Aborted', name: 'AbortError' },\n      meta: { aborted: true },\n    })\n  })\n\n  describe('behavior with missing AbortController', () => {\n    let keepAbortController: (typeof window)['AbortController']\n    let freshlyLoadedModule: typeof import('../createAsyncThunk')\n\n    beforeEach(async () => {\n      keepAbortController = window.AbortController\n      delete (window as any).AbortController\n      vi.resetModules()\n      freshlyLoadedModule = await import('../createAsyncThunk')\n      vi.stubEnv('NODE_ENV', 'development')\n    })\n\n    afterEach(() => {\n      vi.unstubAllEnvs()\n      vi.clearAllMocks()\n      vi.stubGlobal('AbortController', keepAbortController)\n      vi.resetModules()\n    })\n\n    test('calling a thunk made with createAsyncThunk should fail if no global abortController is not available', async () => {\n      const longRunningAsyncThunk = freshlyLoadedModule.createAsyncThunk(\n        'longRunning',\n        async () => {\n          await new Promise((resolve) => setTimeout(resolve, 30000))\n        },\n      )\n\n      expect(longRunningAsyncThunk()).toThrow('AbortController is not defined')\n    })\n  })\n})\n\ntest('non-serializable arguments are ignored by serializableStateInvariantMiddleware', async () => {\n  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n  const nonSerializableValue = new Map()\n  const asyncThunk = createAsyncThunk('test', (arg: Map<any, any>) => {})\n\n  configureStore({\n    reducer: () => 0,\n  }).dispatch(asyncThunk(nonSerializableValue))\n\n  expect(consoleErrorSpy).not.toHaveBeenCalled()\n\n  consoleErrorSpy.mockRestore()\n})\n\ndescribe('conditional skipping of asyncThunks', () => {\n  const arg = {}\n  const getState = vi.fn(() => ({}))\n  const dispatch = vi.fn((x: any) => x)\n  const payloadCreator = vi.fn((x: typeof arg) => 10)\n  const condition = vi.fn(() => false)\n  const extra = {}\n\n  beforeEach(() => {\n    getState.mockClear()\n    dispatch.mockClear()\n    payloadCreator.mockClear()\n    condition.mockClear()\n  })\n\n  test('returning false from condition skips payloadCreator and returns a rejected action', async () => {\n    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })\n    const result = await asyncThunk(arg)(dispatch, getState, extra)\n\n    expect(condition).toHaveBeenCalled()\n    expect(payloadCreator).not.toHaveBeenCalled()\n    expect(asyncThunk.rejected.match(result)).toBe(true)\n    expect((result as any).meta.condition).toBe(true)\n  })\n\n  test('return falsy from condition does not skip payload creator', async () => {\n    // Override TS's expectation that this is a boolean\n    condition.mockReturnValueOnce(undefined as unknown as boolean)\n    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })\n    const result = await asyncThunk(arg)(dispatch, getState, extra)\n\n    expect(condition).toHaveBeenCalled()\n    expect(payloadCreator).toHaveBeenCalled()\n    expect(asyncThunk.fulfilled.match(result)).toBe(true)\n    expect(result.payload).toBe(10)\n  })\n\n  test('returning true from condition executes payloadCreator', async () => {\n    condition.mockReturnValueOnce(true)\n    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })\n    const result = await asyncThunk(arg)(dispatch, getState, extra)\n\n    expect(condition).toHaveBeenCalled()\n    expect(payloadCreator).toHaveBeenCalled()\n    expect(asyncThunk.fulfilled.match(result)).toBe(true)\n    expect(result.payload).toBe(10)\n  })\n\n  test('condition is called with arg, getState and extra', async () => {\n    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })\n    await asyncThunk(arg)(dispatch, getState, extra)\n\n    expect(condition).toHaveBeenCalledOnce()\n    expect(condition).toHaveBeenLastCalledWith(\n      arg,\n      expect.objectContaining({ getState, extra }),\n    )\n  })\n\n  test('pending is dispatched synchronously if condition is synchronous', async () => {\n    const condition = () => true\n    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })\n    const thunkCallPromise = asyncThunk(arg)(dispatch, getState, extra)\n    expect(dispatch).toHaveBeenCalledOnce()\n    await thunkCallPromise\n    expect(dispatch).toHaveBeenCalledTimes(2)\n  })\n\n  test('async condition', async () => {\n    const condition = () => Promise.resolve(false)\n    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })\n    await asyncThunk(arg)(dispatch, getState, extra)\n    expect(dispatch).not.toHaveBeenCalled()\n  })\n\n  test('async condition with rejected promise', async () => {\n    const condition = () => Promise.reject()\n    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })\n    await asyncThunk(arg)(dispatch, getState, extra)\n    expect(dispatch).toHaveBeenCalledOnce()\n    expect(dispatch).toHaveBeenLastCalledWith(\n      expect.objectContaining({ type: 'test/rejected' }),\n    )\n  })\n\n  test('async condition with AbortController signal first', async () => {\n    const condition = async () => {\n      await delay(25)\n      return true\n    }\n    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })\n\n    try {\n      const thunkPromise = asyncThunk(arg)(dispatch, getState, extra)\n      thunkPromise.abort()\n      await thunkPromise\n    } catch (err) {}\n    expect(dispatch).not.toHaveBeenCalled()\n  })\n\n  test('rejected action is not dispatched by default', async () => {\n    const asyncThunk = createAsyncThunk('test', payloadCreator, { condition })\n    await asyncThunk(arg)(dispatch, getState, extra)\n\n    expect(dispatch).not.toHaveBeenCalled()\n  })\n\n  test('does not fail when attempting to abort a canceled promise', async () => {\n    const asyncPayloadCreator = vi.fn(async (x: typeof arg) => {\n      await delay(200)\n      return 10\n    })\n\n    const asyncThunk = createAsyncThunk('test', asyncPayloadCreator, {\n      condition,\n    })\n    const promise = asyncThunk(arg)(dispatch, getState, extra)\n    promise.abort(\n      `If the promise was 1. somehow canceled, 2. in a 'started' state and 3. we attempted to abort, this would crash the tests`,\n    )\n  })\n\n  test('rejected action can be dispatched via option', async () => {\n    const asyncThunk = createAsyncThunk('test', payloadCreator, {\n      condition,\n      dispatchConditionRejection: true,\n    })\n    await asyncThunk(arg)(dispatch, getState, extra)\n\n    expect(dispatch).toHaveBeenCalledOnce()\n    expect(dispatch).toHaveBeenLastCalledWith(\n      expect.objectContaining({\n        error: {\n          message: 'Aborted due to condition callback returning false.',\n          name: 'ConditionError',\n        },\n        meta: {\n          aborted: false,\n          arg,\n          rejectedWithValue: false,\n          condition: true,\n          requestId: expect.stringContaining(''),\n          requestStatus: 'rejected',\n        },\n        payload: undefined,\n        type: 'test/rejected',\n      }),\n    )\n  })\n})\n\ntest('serializeError implementation', async () => {\n  function serializeError() {\n    return 'serialized!'\n  }\n  const errorObject = 'something else!'\n\n  const store = configureStore({\n    reducer: (state = [], action) => [...state, action],\n  })\n\n  const asyncThunk = createAsyncThunk<\n    unknown,\n    void,\n    { serializedErrorType: string }\n  >('test', () => Promise.reject(errorObject), { serializeError })\n  const rejected = await store.dispatch(asyncThunk())\n  if (!asyncThunk.rejected.match(rejected)) {\n    throw new Error()\n  }\n\n  const expectation = {\n    type: 'test/rejected',\n    payload: undefined,\n    error: 'serialized!',\n    meta: expect.any(Object),\n  }\n  expect(rejected).toEqual(expectation)\n  expect(store.getState()[2]).toEqual(expectation)\n  expect(rejected.error).not.toEqual(miniSerializeError(errorObject))\n})\n\ndescribe('unwrapResult', () => {\n  const getState = vi.fn(() => ({}))\n  const dispatch = vi.fn((x: any) => x)\n  const extra = {}\n  test('fulfilled case', async () => {\n    const asyncThunk = createAsyncThunk('test', () => {\n      return 'fulfilled!' as const\n    })\n\n    const unwrapPromise = asyncThunk()(dispatch, getState, extra).then(\n      unwrapResult,\n    )\n\n    await expect(unwrapPromise).resolves.toBe('fulfilled!')\n\n    const unwrapPromise2 = asyncThunk()(dispatch, getState, extra)\n    const res = await unwrapPromise2.unwrap()\n    expect(res).toBe('fulfilled!')\n  })\n  test('error case', async () => {\n    const error = new Error('Panic!')\n    const asyncThunk = createAsyncThunk('test', () => {\n      throw error\n    })\n\n    const unwrapPromise = asyncThunk()(dispatch, getState, extra).then(\n      unwrapResult,\n    )\n\n    await expect(unwrapPromise).rejects.toEqual(miniSerializeError(error))\n\n    const unwrapPromise2 = asyncThunk()(dispatch, getState, extra)\n    await expect(unwrapPromise2.unwrap()).rejects.toEqual(\n      miniSerializeError(error),\n    )\n  })\n  test('rejectWithValue case', async () => {\n    const asyncThunk = createAsyncThunk('test', (_, { rejectWithValue }) => {\n      return rejectWithValue('rejectWithValue!')\n    })\n\n    const unwrapPromise = asyncThunk()(dispatch, getState, extra).then(\n      unwrapResult,\n    )\n\n    await expect(unwrapPromise).rejects.toBe('rejectWithValue!')\n\n    const unwrapPromise2 = asyncThunk()(dispatch, getState, extra)\n    await expect(unwrapPromise2.unwrap()).rejects.toBe('rejectWithValue!')\n  })\n})\n\ndescribe('idGenerator option', () => {\n  const getState = () => ({})\n  const dispatch = (x: any) => x\n  const extra = {}\n\n  test('idGenerator implementation - can customizes how request IDs are generated', async () => {\n    function makeFakeIdGenerator() {\n      let id = 0\n      return vi.fn(() => {\n        id++\n        return `fake-random-id-${id}`\n      })\n    }\n\n    let generatedRequestId = ''\n\n    const idGenerator = makeFakeIdGenerator()\n    const asyncThunk = createAsyncThunk(\n      'test',\n      async (args: void, { requestId }) => {\n        generatedRequestId = requestId\n      },\n      { idGenerator },\n    )\n\n    // dispatching the thunks should be using the custom id generator\n    const promise0 = asyncThunk()(dispatch, getState, extra)\n    expect(generatedRequestId).toEqual('fake-random-id-1')\n    expect(promise0.requestId).toEqual('fake-random-id-1')\n    expect((await promise0).meta.requestId).toEqual('fake-random-id-1')\n\n    const promise1 = asyncThunk()(dispatch, getState, extra)\n    expect(generatedRequestId).toEqual('fake-random-id-2')\n    expect(promise1.requestId).toEqual('fake-random-id-2')\n    expect((await promise1).meta.requestId).toEqual('fake-random-id-2')\n\n    const promise2 = asyncThunk()(dispatch, getState, extra)\n    expect(generatedRequestId).toEqual('fake-random-id-3')\n    expect(promise2.requestId).toEqual('fake-random-id-3')\n    expect((await promise2).meta.requestId).toEqual('fake-random-id-3')\n\n    generatedRequestId = ''\n    const defaultAsyncThunk = createAsyncThunk(\n      'test',\n      async (args: void, { requestId }) => {\n        generatedRequestId = requestId\n      },\n    )\n    // dispatching the default options thunk should still generate an id,\n    // but not using the custom id generator\n    const promise3 = defaultAsyncThunk()(dispatch, getState, extra)\n    expect(generatedRequestId).toEqual(promise3.requestId)\n    expect(promise3.requestId).not.toEqual('')\n    expect(promise3.requestId).not.toEqual(\n      expect.stringContaining('fake-random-id'),\n    )\n    expect((await promise3).meta.requestId).not.toEqual(\n      expect.stringContaining('fake-fandom-id'),\n    )\n  })\n\n  test('idGenerator should be called with thunkArg', async () => {\n    const customIdGenerator = vi.fn((seed) => `fake-unique-random-id-${seed}`)\n    let generatedRequestId = ''\n    const asyncThunk = createAsyncThunk(\n      'test',\n      async (args: any, { requestId }) => {\n        generatedRequestId = requestId\n      },\n      { idGenerator: customIdGenerator },\n    )\n\n    const thunkArg = 1\n    const expected = 'fake-unique-random-id-1'\n    const asyncThunkPromise = asyncThunk(thunkArg)(dispatch, getState, extra)\n\n    expect(customIdGenerator).toHaveBeenCalledWith(thunkArg)\n    expect(asyncThunkPromise.requestId).toEqual(expected)\n    expect((await asyncThunkPromise).meta.requestId).toEqual(expected)\n  })\n})\n\ntest('`condition` will see state changes from a synchronously invoked asyncThunk', () => {\n  type State = ReturnType<typeof store.getState>\n  const onStart = vi.fn()\n  const asyncThunk = createAsyncThunk<\n    void,\n    { force?: boolean },\n    { state: State }\n  >('test', onStart, {\n    condition({ force }, { getState }) {\n      return force || !getState().started\n    },\n  })\n  const store = configureStore({\n    reducer: createReducer({ started: false }, (builder) => {\n      builder.addCase(asyncThunk.pending, (state) => {\n        state.started = true\n      })\n    }),\n  })\n\n  store.dispatch(asyncThunk({ force: false }))\n  expect(onStart).toHaveBeenCalledOnce()\n  store.dispatch(asyncThunk({ force: false }))\n  expect(onStart).toHaveBeenCalledOnce()\n  store.dispatch(asyncThunk({ force: true }))\n  expect(onStart).toHaveBeenCalledTimes(2)\n})\n\nconst getNewStore = () =>\n  configureStore({\n    reducer(actions: UnknownAction[] = [], action) {\n      return [...actions, action]\n    },\n  })\n\ndescribe('meta', () => {\n  let store = getNewStore()\n\n  beforeEach(() => {\n    store = getNewStore()\n  })\n\n  test('pendingMeta', () => {\n    const pendingThunk = createAsyncThunk('test', (arg: string) => {}, {\n      getPendingMeta({ arg, requestId }) {\n        expect(arg).toBe('testArg')\n        expect(requestId).toEqual(expect.any(String))\n        return { extraProp: 'foo' }\n      },\n    })\n    const ret = store.dispatch(pendingThunk('testArg'))\n    expect(store.getState()[1]).toEqual({\n      meta: {\n        arg: 'testArg',\n        extraProp: 'foo',\n        requestId: ret.requestId,\n        requestStatus: 'pending',\n      },\n      payload: undefined,\n      type: 'test/pending',\n    })\n  })\n\n  test('fulfilledMeta', async () => {\n    const fulfilledThunk = createAsyncThunk<\n      string,\n      string,\n      { fulfilledMeta: { extraProp: string } }\n    >('test', (arg: string, { fulfillWithValue }) => {\n      return fulfillWithValue('hooray!', { extraProp: 'bar' })\n    })\n    const ret = store.dispatch(fulfilledThunk('testArg'))\n    expect(await ret).toEqual({\n      meta: {\n        arg: 'testArg',\n        extraProp: 'bar',\n        requestId: ret.requestId,\n        requestStatus: 'fulfilled',\n      },\n      payload: 'hooray!',\n      type: 'test/fulfilled',\n    })\n  })\n\n  test('rejectedMeta', async () => {\n    const fulfilledThunk = createAsyncThunk<\n      string,\n      string,\n      { rejectedMeta: { extraProp: string } }\n    >('test', (arg: string, { rejectWithValue }) => {\n      return rejectWithValue('damn!', { extraProp: 'baz' })\n    })\n    const promise = store.dispatch(fulfilledThunk('testArg'))\n    const ret = await promise\n    expect(ret).toEqual({\n      meta: {\n        arg: 'testArg',\n        extraProp: 'baz',\n        requestId: promise.requestId,\n        requestStatus: 'rejected',\n        rejectedWithValue: true,\n        aborted: false,\n        condition: false,\n      },\n      error: { message: 'Rejected' },\n      payload: 'damn!',\n      type: 'test/rejected',\n    })\n\n    if (ret.meta.requestStatus === 'rejected' && ret.meta.rejectedWithValue) {\n    } else {\n      // could be caused by a `throw`, `abort()` or `condition` - no `rejectedMeta` in that case\n      // @ts-expect-error\n      ret.meta.extraProp\n    }\n  })\n\n  test('typed createAsyncThunk.withTypes', () => {\n    const typedCAT = createAsyncThunk.withTypes<{\n      state: { s: string }\n      rejectValue: string\n      extra: { s: string; n: number }\n    }>()\n    const thunk = typedCAT('a', () => 'b')\n    const expectFunction = expect.any(Function)\n    expect(thunk.fulfilled).toEqual(expectFunction)\n    expect(thunk.pending).toEqual(expectFunction)\n    expect(thunk.rejected).toEqual(expectFunction)\n    expect(thunk.settled).toEqual(expectFunction)\n    expect(thunk.fulfilled.type).toBe('a/fulfilled')\n  })\n  test('createAsyncThunkWrapper using CreateAsyncThunkFunction', async () => {\n    const customSerializeError = () => 'serialized!'\n    const createAppAsyncThunk: CreateAsyncThunkFunction<{\n      serializedErrorType: ReturnType<typeof customSerializeError>\n    }> = (prefix: string, payloadCreator: any, options: any) =>\n      createAsyncThunk(prefix, payloadCreator, {\n        ...options,\n        serializeError: customSerializeError,\n      }) as any\n\n    const asyncThunk = createAppAsyncThunk('test', async () => {\n      throw new Error('Panic!')\n    })\n\n    const promise = store.dispatch(asyncThunk())\n    const result = await promise\n    if (!asyncThunk.rejected.match(result)) {\n      throw new Error('should have thrown')\n    }\n    expect(result.error).toEqual('serialized!')\n  })\n})\n\ndescribe('dispatch config', () => {\n  let store = getNewStore()\n\n  beforeEach(() => {\n    store = getNewStore()\n  })\n  test('accepts external signal', async () => {\n    const asyncThunk = createAsyncThunk('test', async (_: void, { signal }) => {\n      signal.throwIfAborted()\n      const { promise, reject } = promiseWithResolvers<never>()\n      signal.addEventListener('abort', () => reject(signal.reason))\n      return promise\n    })\n\n    const abortController = new AbortController()\n    const promise = store.dispatch(\n      asyncThunk(undefined, { signal: abortController.signal }),\n    )\n    abortController.abort()\n    await expect(promise.unwrap()).rejects.toThrow(\n      'External signal was aborted',\n    )\n  })\n  test('handles already aborted external signal', async () => {\n    const asyncThunk = createAsyncThunk('test', async (_: void, { signal }) => {\n      signal.throwIfAborted()\n      const { promise, reject } = promiseWithResolvers<never>()\n      signal.addEventListener('abort', () => reject(signal.reason))\n      return promise\n    })\n\n    const signal = AbortSignal.abort()\n    const promise = store.dispatch(asyncThunk(undefined, { signal }))\n    await expect(promise.unwrap()).rejects.toThrow(\n      'Aborted due to condition callback returning false.',\n    )\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/createDraftSafeSelector.test.ts",
    "content": "import {\n  createDraftSafeSelector,\n  createSelector,\n  createNextState as produce,\n} from '@reduxjs/toolkit'\n\ntype State = { value: number }\nconst selectSelf = (state: State) => state\n\ntest('handles normal values correctly', () => {\n  const unsafeSelector = createSelector(selectSelf, (x) => x.value)\n  const draftSafeSelector = createDraftSafeSelector(selectSelf, (x) => x.value)\n\n  let state = { value: 1 }\n  expect(unsafeSelector(state)).toBe(1)\n  expect(draftSafeSelector(state)).toBe(1)\n  expect(draftSafeSelector).toHaveProperty('resultFunc')\n  expect(draftSafeSelector).toHaveProperty('memoizedResultFunc')\n  expect(draftSafeSelector).toHaveProperty('lastResult')\n  expect(draftSafeSelector).toHaveProperty('dependencies')\n  expect(draftSafeSelector).toHaveProperty('recomputations')\n  expect(draftSafeSelector).toHaveProperty('resetRecomputations')\n  expect(draftSafeSelector).toHaveProperty('clearCache')\n\n  state = { value: 2 }\n  expect(unsafeSelector(state)).toBe(2)\n  expect(draftSafeSelector(state)).toBe(2)\n})\n\ntest('handles drafts correctly', () => {\n  const unsafeSelector = createSelector(selectSelf, (state) => state.value)\n  const draftSafeSelector = createDraftSafeSelector(\n    selectSelf,\n    (state) => state.value,\n  )\n\n  produce({ value: 1 }, (state) => {\n    expect(unsafeSelector(state)).toBe(1)\n    expect(draftSafeSelector(state)).toBe(1)\n\n    state.value = 2\n\n    expect(unsafeSelector(state)).toBe(1)\n    expect(draftSafeSelector(state)).toBe(2)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/createDraftSafeSelector.withTypes.test.ts",
    "content": "import { createDraftSafeSelector } from '@reduxjs/toolkit'\n\ninterface Todo {\n  id: number\n  completed: boolean\n}\n\ninterface Alert {\n  id: number\n  read: boolean\n}\n\ninterface RootState {\n  todos: Todo[]\n  alerts: Alert[]\n}\n\nconst rootState: RootState = {\n  todos: [\n    { id: 0, completed: false },\n    { id: 1, completed: false },\n  ],\n  alerts: [\n    { id: 0, read: false },\n    { id: 1, read: false },\n  ],\n}\n\ndescribe(createDraftSafeSelector.withTypes, () => {\n  const createTypedDraftSafeSelector =\n    createDraftSafeSelector.withTypes<RootState>()\n\n  test('should return createDraftSafeSelector', () => {\n    expect(createTypedDraftSafeSelector.withTypes).toEqual(expect.any(Function))\n\n    expect(createTypedDraftSafeSelector.withTypes().withTypes).toEqual(\n      expect.any(Function),\n    )\n\n    expect(createTypedDraftSafeSelector).toBe(createDraftSafeSelector)\n\n    const selectTodoIds = createTypedDraftSafeSelector(\n      [(state) => state.todos],\n      (todos) => todos.map(({ id }) => id),\n    )\n\n    expect(selectTodoIds(rootState)).to.be.an('array').that.is.not.empty\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/createEntityAdapter.test-d.ts",
    "content": "import type {\n  ActionCreatorWithPayload,\n  ActionCreatorWithoutPayload,\n  EntityAdapter,\n  EntityId,\n  EntityStateAdapter,\n  Update,\n} from '@reduxjs/toolkit'\nimport { createEntityAdapter, createSlice } from '@reduxjs/toolkit'\n\nfunction extractReducers<T, Id extends EntityId>(\n  adapter: EntityAdapter<T, Id>,\n): EntityStateAdapter<T, Id> {\n  const { selectId, sortComparer, getInitialState, getSelectors, ...rest } =\n    adapter\n  return rest\n}\n\ndescribe('type tests', () => {\n  test('should be usable in a slice, with all the \"reducer-like\" functions', () => {\n    type Id = string & { readonly __tag: unique symbol }\n    type Entity = {\n      id: Id\n    }\n    const adapter = createEntityAdapter<Entity>()\n    const slice = createSlice({\n      name: 'test',\n      initialState: adapter.getInitialState(),\n      reducers: {\n        ...extractReducers(adapter),\n      },\n    })\n\n    expectTypeOf(slice.actions.addOne).toExtend<\n      ActionCreatorWithPayload<Entity>\n    >()\n\n    expectTypeOf(slice.actions.addMany).toExtend<\n      ActionCreatorWithPayload<ReadonlyArray<Entity> | Record<string, Entity>>\n    >()\n\n    expectTypeOf(slice.actions.setAll).toExtend<\n      ActionCreatorWithPayload<ReadonlyArray<Entity> | Record<string, Entity>>\n    >()\n\n    expectTypeOf(slice.actions.removeOne).toExtend<\n      ActionCreatorWithPayload<Id>\n    >()\n\n    expectTypeOf(slice.actions.addMany).not.toExtend<\n      ActionCreatorWithPayload<Entity[] | Record<string, Entity>>\n    >()\n\n    expectTypeOf(slice.actions.setAll).not.toExtend<\n      ActionCreatorWithPayload<ReadonlyArray<Id>>\n    >()\n\n    expectTypeOf(slice.actions.removeOne).toExtend<\n      ActionCreatorWithPayload<Id>\n    >()\n\n    expectTypeOf(slice.actions.removeMany).toExtend<\n      ActionCreatorWithPayload<ReadonlyArray<Id>>\n    >()\n\n    expectTypeOf(slice.actions.removeMany).not.toExtend<\n      ActionCreatorWithPayload<EntityId[]>\n    >()\n\n    expectTypeOf(\n      slice.actions.removeAll,\n    ).toExtend<ActionCreatorWithoutPayload>()\n\n    expectTypeOf(slice.actions.updateOne).toExtend<\n      ActionCreatorWithPayload<Update<Entity, Id>>\n    >()\n\n    expectTypeOf(slice.actions.updateMany).not.toExtend<\n      ActionCreatorWithPayload<Update<Entity, Id>[]>\n    >()\n\n    expectTypeOf(slice.actions.upsertOne).toExtend<\n      ActionCreatorWithPayload<Entity>\n    >()\n\n    expectTypeOf(slice.actions.updateMany).toExtend<\n      ActionCreatorWithPayload<ReadonlyArray<Update<Entity, Id>>>\n    >()\n\n    expectTypeOf(slice.actions.upsertOne).toExtend<\n      ActionCreatorWithPayload<Entity>\n    >()\n\n    expectTypeOf(slice.actions.upsertMany).toExtend<\n      ActionCreatorWithPayload<ReadonlyArray<Entity> | Record<string, Entity>>\n    >()\n\n    expectTypeOf(slice.actions.upsertMany).not.toExtend<\n      ActionCreatorWithPayload<Entity[] | Record<string, Entity>>\n    >()\n  })\n\n  test('should not be able to mix with a different EntityAdapter', () => {\n    type Entity = {\n      id: EntityId\n      value: string\n    }\n    type Entity2 = {\n      id: EntityId\n      value2: string\n    }\n    const adapter = createEntityAdapter<Entity>()\n    const adapter2 = createEntityAdapter<Entity2>()\n    createSlice({\n      name: 'test',\n      initialState: adapter.getInitialState(),\n      reducers: {\n        addOne: adapter.addOne,\n        // @ts-expect-error\n        addOne2: adapter2.addOne,\n      },\n    })\n  })\n\n  test('should be usable in a slice with extra properties', () => {\n    type Entity = { id: EntityId; value: string }\n    const adapter = createEntityAdapter<Entity>()\n    createSlice({\n      name: 'test',\n      initialState: adapter.getInitialState({ extraData: 'test' }),\n      reducers: {\n        addOne: adapter.addOne,\n      },\n    })\n  })\n\n  test('should not be usable in a slice with an unfitting state', () => {\n    type Entity = { id: EntityId; value: string }\n    const adapter = createEntityAdapter<Entity>()\n    createSlice({\n      name: 'test',\n      initialState: { somethingElse: '' },\n      reducers: {\n        // @ts-expect-error\n        addOne: adapter.addOne,\n      },\n    })\n  })\n\n  test('should not be able to create an adapter unless the type has an Id or an idSelector is provided', () => {\n    type Entity = {\n      value: string\n    }\n    // @ts-expect-error\n    const adapter = createEntityAdapter<Entity>()\n    const adapter2: EntityAdapter<Entity, Entity['value']> =\n      createEntityAdapter({\n        selectId: (e: Entity) => e.value,\n      })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/createReducer.test-d.ts",
    "content": "import type { ActionReducerMapBuilder, Reducer } from '@reduxjs/toolkit'\nimport { createAction, createReducer } from '@reduxjs/toolkit'\n\ndescribe('type tests', () => {\n  test('createReducer() infers type of returned reducer.', () => {\n    const incrementHandler = (\n      state: number,\n      action: { type: 'increment'; payload: number },\n    ) => state + 1\n\n    const decrementHandler = (\n      state: number,\n      action: { type: 'decrement'; payload: number },\n    ) => state - 1\n\n    const reducer = createReducer(0 as number, (builder) => {\n      builder\n        .addCase('increment', incrementHandler)\n        .addCase('decrement', decrementHandler)\n    })\n\n    expectTypeOf(reducer).toExtend<Reducer<number>>()\n\n    expectTypeOf(reducer).not.toExtend<Reducer<string>>()\n  })\n\n  test('createReducer() state type can be specified explicitly.', () => {\n    const incrementHandler = (\n      state: number,\n      action: { type: 'increment'; payload: number },\n    ) => state + action.payload\n\n    const decrementHandler = (\n      state: number,\n      action: { type: 'decrement'; payload: number },\n    ) => state - action.payload\n\n    createReducer(0 as number, (builder) => {\n      builder\n        .addCase('increment', incrementHandler)\n        .addCase('decrement', decrementHandler)\n    })\n\n    // @ts-expect-error\n    createReducer<string>(0 as number, (builder) => {\n      expectTypeOf(builder.addCase)\n        .parameter(1)\n        .not.toExtend<typeof incrementHandler>()\n\n      expectTypeOf(builder.addCase)\n        .parameter(1)\n        .not.toExtend<typeof decrementHandler>()\n    })\n  })\n\n  test('createReducer() ensures state type is mutable within a case reducer.', () => {\n    const initialState: { readonly counter: number } = { counter: 0 }\n\n    createReducer(initialState, (builder) => {\n      builder.addCase('increment', (state) => {\n        state.counter += 1\n      })\n    })\n  })\n\n  test('builder callback for actionMap', () => {\n    const increment = createAction<number, 'increment'>('increment')\n\n    const reducer = createReducer(0, (builder) =>\n      expectTypeOf(builder).toEqualTypeOf<ActionReducerMapBuilder<number>>(),\n    )\n\n    expectTypeOf(reducer(0, increment(5))).toBeNumber()\n\n    expectTypeOf(reducer(0, increment(5))).not.toBeString()\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/createReducer.test.ts",
    "content": "import type {\n  CaseReducer,\n  Draft,\n  PayloadAction,\n  Reducer,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport {\n  createAction,\n  createAsyncThunk,\n  createNextState,\n  createReducer,\n  isPlainObject,\n} from '@reduxjs/toolkit'\n\ninterface Todo {\n  text: string\n  completed?: boolean\n}\n\ninterface AddTodoPayload {\n  newTodo: Todo\n}\n\ninterface ToggleTodoPayload {\n  index: number\n}\n\ntype TodoState = Todo[]\ntype TodosReducer = Reducer<TodoState, PayloadAction<any>>\ntype AddTodoReducer = CaseReducer<\n  TodoState,\n  PayloadAction<AddTodoPayload, 'ADD_TODO'>\n>\n\ntype ToggleTodoReducer = CaseReducer<\n  TodoState,\n  PayloadAction<ToggleTodoPayload, 'TOGGLE_TODO'>\n>\n\ntype CreateReducer = typeof createReducer\n\nconst addTodoThunk = createAsyncThunk('todos/add', (todo: Todo) => todo)\n\ndescribe('createReducer', () => {\n  describe('given impure reducers with immer', () => {\n    const addTodo: AddTodoReducer = (state, action) => {\n      const { newTodo } = action.payload\n\n      // Can safely call state.push() here\n      state.push({ ...newTodo, completed: false })\n    }\n\n    const toggleTodo: ToggleTodoReducer = (state, action) => {\n      const { index } = action.payload\n\n      const todo = state[index]\n      // Can directly modify the todo object\n      todo.completed = !todo.completed\n    }\n\n    const todosReducer = createReducer([] as TodoState, (builder) => {\n      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)\n    })\n\n    behavesLikeReducer(todosReducer)\n  })\n\n  describe('Deprecation warnings', () => {\n    beforeEach(() => {\n      vi.resetModules()\n    })\n\n    afterEach(() => {\n      vi.unstubAllEnvs()\n    })\n\n    it('Throws an error if the legacy object notation is used', async () => {\n      const { createReducer } = await import('../createReducer')\n      const wrapper = () => {\n        const dummyReducer = (createReducer as CreateReducer)(\n          [] as TodoState,\n          // @ts-ignore\n          {},\n        )\n      }\n\n      expect(wrapper).toThrowError(\n        /The object notation for `createReducer` has been removed/,\n      )\n\n      expect(wrapper).toThrowError(\n        /The object notation for `createReducer` has been removed/,\n      )\n    })\n\n    it('Crashes in production', async () => {\n      vi.stubEnv('NODE_ENV', 'production')\n      const { createReducer } = await import('../createReducer')\n      const wrapper = () => {\n        const dummyReducer = (createReducer as CreateReducer)(\n          [] as TodoState,\n          // @ts-ignore\n          {},\n        )\n      }\n\n      expect(wrapper).toThrowError()\n    })\n  })\n\n  describe('Immer in a production environment', () => {\n    beforeEach(() => {\n      vi.resetModules()\n      vi.stubEnv('NODE_ENV', 'production')\n    })\n\n    afterEach(() => {\n      vi.unstubAllEnvs()\n    })\n\n    test('Freezes data in production', async () => {\n      const { createReducer } = await import('../createReducer')\n      const addTodo: AddTodoReducer = (state, action) => {\n        const { newTodo } = action.payload\n        state.push({ ...newTodo, completed: false })\n      }\n\n      const toggleTodo: ToggleTodoReducer = (state, action) => {\n        const { index } = action.payload\n        const todo = state[index]\n        todo.completed = !todo.completed\n      }\n\n      const todosReducer = createReducer([] as TodoState, (builder) => {\n        builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)\n      })\n\n      const result = todosReducer([], {\n        type: 'ADD_TODO',\n        payload: { text: 'Buy milk' },\n      })\n\n      const mutateStateOutsideReducer = () => (result[0].text = 'edited')\n      expect(mutateStateOutsideReducer).toThrowError(\n        'Cannot add property text, object is not extensible',\n      )\n    })\n\n    test('Freezes initial state', () => {\n      const initialState = [{ text: 'Buy milk' }]\n      const todosReducer = createReducer(initialState, () => {})\n      const frozenInitialState = todosReducer(undefined, { type: 'dummy' })\n\n      const mutateStateOutsideReducer = () =>\n        (frozenInitialState[0].text = 'edited')\n      expect(mutateStateOutsideReducer).toThrowError(\n        /Cannot assign to read only property/,\n      )\n    })\n    test('does not throw error if initial state is not draftable', () => {\n      expect(() =>\n        createReducer(new URLSearchParams(), () => {}),\n      ).not.toThrowError()\n    })\n  })\n\n  describe('given pure reducers with immutable updates', () => {\n    const addTodo: AddTodoReducer = (state, action) => {\n      const { newTodo } = action.payload\n\n      // Updates the state immutably without relying on immer\n      return state.concat({ ...newTodo, completed: false })\n    }\n\n    const toggleTodo: ToggleTodoReducer = (state, action) => {\n      const { index } = action.payload\n\n      // Updates the todo object immutably withot relying on immer\n      return state.map((todo, i) => {\n        if (i !== index) return todo\n        return { ...todo, completed: !todo.completed }\n      })\n    }\n\n    const todosReducer = createReducer([] as TodoState, (builder) => {\n      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)\n    })\n\n    behavesLikeReducer(todosReducer)\n  })\n\n  describe('Accepts a lazy state init function to generate initial state', () => {\n    const addTodo: AddTodoReducer = (state, action) => {\n      const { newTodo } = action.payload\n      state.push({ ...newTodo, completed: false })\n    }\n\n    const toggleTodo: ToggleTodoReducer = (state, action) => {\n      const { index } = action.payload\n      const todo = state[index]\n      todo.completed = !todo.completed\n    }\n\n    const lazyStateInit = () => [] as TodoState\n\n    const todosReducer = createReducer([] as TodoState, (builder) => {\n      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)\n    })\n\n    behavesLikeReducer(todosReducer)\n\n    it('Should only call the init function when `undefined` state is passed in', () => {\n      const spy = vi.fn().mockReturnValue(42)\n\n      const dummyReducer = createReducer(spy, () => {})\n      expect(spy).not.toHaveBeenCalled()\n\n      dummyReducer(123, { type: 'dummy' })\n      expect(spy).not.toHaveBeenCalled()\n\n      const initialState = dummyReducer(undefined, { type: 'dummy' })\n      expect(spy).toHaveBeenCalledOnce()\n    })\n  })\n\n  describe('given draft state from immer', () => {\n    const addTodo: AddTodoReducer = (state, action) => {\n      const { newTodo } = action.payload\n\n      // Can safely call state.push() here\n      state.push({ ...newTodo, completed: false })\n    }\n\n    const toggleTodo: ToggleTodoReducer = (state, action) => {\n      const { index } = action.payload\n\n      const todo = state[index]\n      // Can directly modify the todo object\n      todo.completed = !todo.completed\n    }\n\n    const todosReducer = createReducer([] as TodoState, (builder) => {\n      builder.addCase('ADD_TODO', addTodo).addCase('TOGGLE_TODO', toggleTodo)\n    })\n\n    const wrappedReducer: TodosReducer = (state = [], action) => {\n      return createNextState(state, (draft: Draft<TodoState>) => {\n        todosReducer(draft, action)\n      })\n    }\n\n    behavesLikeReducer(wrappedReducer)\n  })\n\n  describe('builder callback for actionMap', () => {\n    const increment = createAction<number, 'increment'>('increment')\n    const decrement = createAction<number, 'decrement'>('decrement')\n\n    test('can be used with ActionCreators', () => {\n      const reducer = createReducer(0, (builder) =>\n        builder\n          .addCase(increment, (state, action) => state + action.payload)\n          .addCase(decrement, (state, action) => state - action.payload),\n      )\n      expect(reducer(0, increment(5))).toBe(5)\n      expect(reducer(5, decrement(5))).toBe(0)\n    })\n    test('can be used with string types', () => {\n      const reducer = createReducer(0, (builder) =>\n        builder\n          .addCase(\n            'increment',\n            (state, action: { type: 'increment'; payload: number }) =>\n              state + action.payload,\n          )\n          .addCase(\n            'decrement',\n            (state, action: { type: 'decrement'; payload: number }) =>\n              state - action.payload,\n          ),\n      )\n      expect(reducer(0, increment(5))).toBe(5)\n      expect(reducer(5, decrement(5))).toBe(0)\n    })\n    test('can be used with ActionCreators and string types combined', () => {\n      const reducer = createReducer(0, (builder) =>\n        builder\n          .addCase(increment, (state, action) => state + action.payload)\n          .addCase(\n            'decrement',\n            (state, action: { type: 'decrement'; payload: number }) =>\n              state - action.payload,\n          ),\n      )\n      expect(reducer(0, increment(5))).toBe(5)\n      expect(reducer(5, decrement(5))).toBe(0)\n    })\n    test('will throw an error when returning undefined from a non-draftable state', () => {\n      const reducer = createReducer(0, (builder) =>\n        builder.addCase(\n          'decrement',\n          (state, action: { type: 'decrement'; payload: number }) => {},\n        ),\n      )\n      expect(() => reducer(5, decrement(5))).toThrowErrorMatchingInlineSnapshot(\n        `[Error: A case reducer on a non-draftable value must not return undefined]`,\n      )\n    })\n    test('allows you to return undefined if the state was null, thus skipping an update', () => {\n      const reducer = createReducer(null as number | null, (builder) =>\n        builder.addCase(\n          'decrement',\n          (state, action: { type: 'decrement'; payload: number }) => {\n            if (typeof state === 'number') {\n              return state - action.payload\n            }\n            return undefined\n          },\n        ),\n      )\n      expect(reducer(0, decrement(5))).toBe(-5)\n      expect(reducer(null, decrement(5))).toBe(null)\n    })\n    test('allows you to return null', () => {\n      const reducer = createReducer(0 as number | null, (builder) =>\n        builder.addCase(\n          'decrement',\n          (state, action: { type: 'decrement'; payload: number }) => {\n            return null\n          },\n        ),\n      )\n      expect(reducer(5, decrement(5))).toBe(null)\n    })\n    test('allows you to return 0', () => {\n      const reducer = createReducer(0, (builder) =>\n        builder.addCase(\n          'decrement',\n          (state, action: { type: 'decrement'; payload: number }) =>\n            state - action.payload,\n        ),\n      )\n      expect(reducer(5, decrement(5))).toBe(0)\n    })\n    test('will throw if the same type is used twice', () => {\n      expect(() => {\n        createReducer(0, (builder) => {\n          builder\n            .addCase(increment, (state, action) => state + action.payload)\n            .addCase(increment, (state, action) => state + action.payload)\n            .addCase(decrement, (state, action) => state - action.payload)\n        })\n      }).toThrowErrorMatchingInlineSnapshot(\n        `[Error: \\`builder.addCase\\` cannot be called with two reducers for the same action type 'increment']`,\n      )\n      expect(() => {\n        createReducer(0, (builder) => {\n          builder\n            .addCase(increment, (state, action) => state + action.payload)\n            .addCase('increment', (state) => state + 1)\n            .addCase(decrement, (state, action) => state - action.payload)\n        })\n      }).toThrowErrorMatchingInlineSnapshot(\n        `[Error: \\`builder.addCase\\` cannot be called with two reducers for the same action type 'increment']`,\n      )\n    })\n\n    test('will throw if an empty type is used', () => {\n      const customActionCreator = (payload: number) => ({\n        type: 'custom_action',\n        payload,\n      })\n      customActionCreator.type = ''\n      expect(() => {\n        createReducer(0, (builder) => {\n          builder.addCase(\n            customActionCreator,\n            (state, action) => state + action.payload,\n          )\n        })\n      }).toThrowErrorMatchingInlineSnapshot(\n        `[Error: \\`builder.addCase\\` cannot be called with an empty action type]`,\n      )\n    })\n  })\n\n  describe('builder \"addMatcher\" method', () => {\n    const prepareNumberAction = (payload: number) => ({\n      payload,\n      meta: { type: 'number_action' },\n    })\n    const prepareStringAction = (payload: string) => ({\n      payload,\n      meta: { type: 'string_action' },\n    })\n\n    const numberActionMatcher = (\n      a: UnknownAction,\n    ): a is PayloadAction<number> =>\n      isPlainObject(a.meta) &&\n      'type' in a.meta &&\n      (a.meta as Record<'type', unknown>).type === 'number_action'\n\n    const stringActionMatcher = (\n      a: UnknownAction,\n    ): a is PayloadAction<string> =>\n      isPlainObject(a.meta) &&\n      'type' in a.meta &&\n      (a.meta as Record<'type', unknown>).type === 'string_action'\n\n    const incrementBy = createAction('increment', prepareNumberAction)\n    const decrementBy = createAction('decrement', prepareNumberAction)\n    const concatWith = createAction('concat', prepareStringAction)\n\n    const initialState = { numberActions: 0, stringActions: 0 }\n\n    test('uses the reducer of matching actionMatchers', () => {\n      const reducer = createReducer(initialState, (builder) =>\n        builder\n          .addMatcher(numberActionMatcher, (state) => {\n            state.numberActions += 1\n          })\n          .addMatcher(stringActionMatcher, (state) => {\n            state.stringActions += 1\n          }),\n      )\n      expect(reducer(undefined, incrementBy(1))).toEqual({\n        numberActions: 1,\n        stringActions: 0,\n      })\n      expect(reducer(undefined, decrementBy(1))).toEqual({\n        numberActions: 1,\n        stringActions: 0,\n      })\n      expect(reducer(undefined, concatWith('foo'))).toEqual({\n        numberActions: 0,\n        stringActions: 1,\n      })\n    })\n    test('falls back to defaultCase', () => {\n      const reducer = createReducer(initialState, (builder) =>\n        builder\n          .addCase(concatWith, (state) => {\n            state.stringActions += 1\n          })\n          .addMatcher(numberActionMatcher, (state) => {\n            state.numberActions += 1\n          })\n          .addDefaultCase((state) => {\n            state.numberActions = -1\n            state.stringActions = -1\n          }),\n      )\n      expect(reducer(undefined, { type: 'somethingElse' })).toEqual({\n        numberActions: -1,\n        stringActions: -1,\n      })\n    })\n    test('runs reducer cases followed by all matching actionMatchers', () => {\n      const reducer = createReducer(initialState, (builder) =>\n        builder\n          .addCase(incrementBy, (state) => {\n            state.numberActions = state.numberActions * 10 + 1\n          })\n          .addMatcher(numberActionMatcher, (state) => {\n            state.numberActions = state.numberActions * 10 + 2\n          })\n          .addMatcher(stringActionMatcher, (state) => {\n            state.stringActions = state.stringActions * 10 + 1\n          })\n          .addMatcher(numberActionMatcher, (state) => {\n            state.numberActions = state.numberActions * 10 + 3\n          }),\n      )\n      expect(reducer(undefined, incrementBy(1))).toEqual({\n        numberActions: 123,\n        stringActions: 0,\n      })\n      expect(reducer(undefined, decrementBy(1))).toEqual({\n        numberActions: 23,\n        stringActions: 0,\n      })\n      expect(reducer(undefined, concatWith('foo'))).toEqual({\n        numberActions: 0,\n        stringActions: 1,\n      })\n    })\n    test('works with `actionCreator.match`', () => {\n      const reducer = createReducer(initialState, (builder) =>\n        builder.addMatcher(incrementBy.match, (state) => {\n          state.numberActions += 100\n        }),\n      )\n      expect(reducer(undefined, incrementBy(1))).toEqual({\n        numberActions: 100,\n        stringActions: 0,\n      })\n    })\n    test('calling addCase, addMatcher and addDefaultCase in a nonsensical order should result in an error in development mode', () => {\n      expect(() =>\n        createReducer(initialState, (builder: any) =>\n          builder\n            .addMatcher(numberActionMatcher, () => {})\n            .addCase(incrementBy, () => {}),\n        ),\n      ).toThrowErrorMatchingInlineSnapshot(\n        `[Error: \\`builder.addCase\\` should only be called before calling \\`builder.addMatcher\\`]`,\n      )\n      expect(() =>\n        createReducer(initialState, (builder: any) =>\n          builder.addDefaultCase(() => {}).addCase(incrementBy, () => {}),\n        ),\n      ).toThrowErrorMatchingInlineSnapshot(\n        `[Error: \\`builder.addCase\\` should only be called before calling \\`builder.addDefaultCase\\`]`,\n      )\n      expect(() =>\n        createReducer(initialState, (builder: any) =>\n          builder\n            .addDefaultCase(() => {})\n            .addMatcher(numberActionMatcher, () => {}),\n        ),\n      ).toThrowErrorMatchingInlineSnapshot(\n        `[Error: \\`builder.addMatcher\\` should only be called before calling \\`builder.addDefaultCase\\`]`,\n      )\n      expect(() =>\n        createReducer(initialState, (builder: any) =>\n          builder.addDefaultCase(() => {}).addDefaultCase(() => {}),\n        ),\n      ).toThrowErrorMatchingInlineSnapshot(\n        `[Error: \\`builder.addDefaultCase\\` can only be called once]`,\n      )\n    })\n  })\n  describe('builder \"addAsyncThunk\" method', () => {\n    const initialState = { todos: [] as Todo[], loading: false, errored: false }\n    test('uses the matching reducer for each action type', () => {\n      const reducer = createReducer(initialState, (builder) =>\n        builder.addAsyncThunk(addTodoThunk, {\n          pending(state) {\n            state.loading = true\n          },\n          fulfilled(state, action) {\n            state.todos.push(action.payload)\n          },\n          rejected(state) {\n            state.errored = true\n          },\n          settled(state) {\n            state.loading = false\n          },\n        }),\n      )\n      const todo: Todo = { text: 'test' }\n      expect(reducer(undefined, addTodoThunk.pending('test', todo))).toEqual({\n        todos: [],\n        loading: true,\n        errored: false,\n      })\n      expect(\n        reducer(undefined, addTodoThunk.fulfilled(todo, 'test', todo)),\n      ).toEqual({\n        todos: [todo],\n        loading: false,\n        errored: false,\n      })\n      expect(\n        reducer(undefined, addTodoThunk.rejected(new Error(), 'test', todo)),\n      ).toEqual({\n        todos: [],\n        loading: false,\n        errored: true,\n      })\n    })\n    test('calling addAsyncThunk after addDefaultCase should result in an error in development mode', () => {\n      expect(() =>\n        createReducer(initialState, (builder: any) =>\n          builder.addDefaultCase(() => {}).addAsyncThunk(addTodoThunk, {}),\n        ),\n      ).toThrowErrorMatchingInlineSnapshot(\n        `[Error: \\`builder.addAsyncThunk\\` should only be called before calling \\`builder.addDefaultCase\\`]`,\n      )\n    })\n  })\n})\n\nfunction behavesLikeReducer(todosReducer: TodosReducer) {\n  it('should handle initial state', () => {\n    const initialAction = { type: '', payload: undefined }\n    expect(todosReducer(undefined, initialAction)).toEqual([])\n  })\n\n  it('should handle ADD_TODO', () => {\n    expect(\n      todosReducer([], {\n        type: 'ADD_TODO',\n        payload: { newTodo: { text: 'Run the tests' } },\n      }),\n    ).toEqual([\n      {\n        text: 'Run the tests',\n        completed: false,\n      },\n    ])\n\n    expect(\n      todosReducer(\n        [\n          {\n            text: 'Run the tests',\n            completed: false,\n          },\n        ],\n        {\n          type: 'ADD_TODO',\n          payload: { newTodo: { text: 'Use Redux' } },\n        },\n      ),\n    ).toEqual([\n      {\n        text: 'Run the tests',\n        completed: false,\n      },\n      {\n        text: 'Use Redux',\n        completed: false,\n      },\n    ])\n\n    expect(\n      todosReducer(\n        [\n          {\n            text: 'Run the tests',\n            completed: false,\n          },\n          {\n            text: 'Use Redux',\n            completed: false,\n          },\n        ],\n        {\n          type: 'ADD_TODO',\n          payload: { newTodo: { text: 'Fix the tests' } },\n        },\n      ),\n    ).toEqual([\n      {\n        text: 'Run the tests',\n        completed: false,\n      },\n      {\n        text: 'Use Redux',\n        completed: false,\n      },\n      {\n        text: 'Fix the tests',\n        completed: false,\n      },\n    ])\n  })\n\n  it('should handle TOGGLE_TODO', () => {\n    expect(\n      todosReducer(\n        [\n          {\n            text: 'Run the tests',\n            completed: false,\n          },\n          {\n            text: 'Use Redux',\n            completed: false,\n          },\n        ],\n        {\n          type: 'TOGGLE_TODO',\n          payload: { index: 0 },\n        },\n      ),\n    ).toEqual([\n      {\n        text: 'Run the tests',\n        completed: true,\n      },\n      {\n        text: 'Use Redux',\n        completed: false,\n      },\n    ])\n  })\n}\n"
  },
  {
    "path": "packages/toolkit/src/tests/createSlice.test-d.ts",
    "content": "import type {\n  Action,\n  ActionCreatorWithNonInferrablePayload,\n  ActionCreatorWithOptionalPayload,\n  ActionCreatorWithPayload,\n  ActionCreatorWithPreparedPayload,\n  ActionCreatorWithoutPayload,\n  ActionReducerMapBuilder,\n  AsyncThunk,\n  CaseReducer,\n  PayloadAction,\n  PayloadActionCreator,\n  Reducer,\n  ReducerCreators,\n  SerializedError,\n  SliceCaseReducers,\n  ThunkDispatch,\n  ValidateSliceCaseReducers,\n} from '@reduxjs/toolkit'\nimport {\n  asyncThunkCreator,\n  buildCreateSlice,\n  configureStore,\n  createAction,\n  createAsyncThunk,\n  createSlice,\n  isRejected,\n} from '@reduxjs/toolkit'\nimport { castDraft } from 'immer'\n\ndescribe('type tests', () => {\n  const counterSlice = createSlice({\n    name: 'counter',\n    initialState: 0,\n    reducers: {\n      increment: (state: number, action) => state + action.payload,\n      decrement: (state: number, action) => state - action.payload,\n    },\n  })\n\n  test('Slice name is strongly typed.', () => {\n    const uiSlice = createSlice({\n      name: 'ui',\n      initialState: 0,\n      reducers: {\n        goToNext: (state: number, action) => state + action.payload,\n        goToPrevious: (state: number, action) => state - action.payload,\n      },\n    })\n\n    const actionCreators = {\n      [counterSlice.name]: { ...counterSlice.actions },\n      [uiSlice.name]: { ...uiSlice.actions },\n    }\n\n    expectTypeOf(counterSlice.actions).toEqualTypeOf(actionCreators.counter)\n\n    expectTypeOf(uiSlice.actions).toEqualTypeOf(actionCreators.ui)\n\n    expectTypeOf(actionCreators).not.toHaveProperty('anyKey')\n  })\n\n  test(\"createSlice() infers the returned slice's type.\", () => {\n    const firstAction = createAction<{ count: number }>('FIRST_ACTION')\n\n    const slice = createSlice({\n      name: 'counter',\n      initialState: 0,\n      reducers: {\n        increment: (state: number, action) => state + action.payload,\n        decrement: (state: number, action) => state - action.payload,\n      },\n      extraReducers: (builder) => {\n        builder.addCase(\n          firstAction,\n          (state, action) => state + action.payload.count,\n        )\n      },\n    })\n\n    test('Reducer', () => {\n      expectTypeOf(slice.reducer).toExtend<Reducer<number, PayloadAction>>()\n\n      expectTypeOf(slice.reducer).not.toExtend<Reducer<string, PayloadAction>>()\n    })\n\n    test('Actions', () => {\n      slice.actions.increment(1)\n      slice.actions.decrement(1)\n\n      expectTypeOf(slice.actions).not.toHaveProperty('other')\n    })\n  })\n\n  test('Slice action creator types are inferred.', () => {\n    const counter = createSlice({\n      name: 'counter',\n      initialState: 0,\n      reducers: {\n        increment: (state) => state + 1,\n        decrement: (\n          state,\n          { payload = 1 }: PayloadAction<number | undefined>,\n        ) => state - payload,\n        multiply: (state, { payload }: PayloadAction<number | number[]>) =>\n          Array.isArray(payload)\n            ? payload.reduce((acc, val) => acc * val, state)\n            : state * payload,\n        addTwo: {\n          reducer: (s, { payload }: PayloadAction<number>) => s + payload,\n          prepare: (a: number, b: number) => ({\n            payload: a + b,\n          }),\n        },\n      },\n    })\n\n    expectTypeOf(\n      counter.actions.increment,\n    ).toExtend<ActionCreatorWithoutPayload>()\n\n    counter.actions.increment()\n\n    expectTypeOf(counter.actions.decrement).toExtend<\n      ActionCreatorWithOptionalPayload<number | undefined>\n    >()\n\n    counter.actions.decrement()\n    counter.actions.decrement(2)\n\n    expectTypeOf(counter.actions.multiply).toExtend<\n      ActionCreatorWithPayload<number | number[]>\n    >()\n\n    counter.actions.multiply(2)\n    counter.actions.multiply([2, 3, 4])\n\n    expectTypeOf(counter.actions.addTwo).toExtend<\n      ActionCreatorWithPreparedPayload<[number, number], number>\n    >()\n\n    counter.actions.addTwo(1, 2)\n\n    expectTypeOf(counter.actions.multiply).parameters.not.toExtend<[]>()\n\n    expectTypeOf(counter.actions.multiply).parameter(0).not.toBeString()\n\n    expectTypeOf(counter.actions.addTwo).parameters.not.toExtend<[number]>()\n\n    expectTypeOf(counter.actions.addTwo).parameters.toEqualTypeOf<\n      [number, number]\n    >()\n  })\n\n  test('Slice action creator types properties are strongly typed', () => {\n    const counter = createSlice({\n      name: 'counter',\n      initialState: 0,\n      reducers: {\n        increment: (state) => state + 1,\n        decrement: (state) => state - 1,\n        multiply: (state, { payload }: PayloadAction<number | number[]>) =>\n          Array.isArray(payload)\n            ? payload.reduce((acc, val) => acc * val, state)\n            : state * payload,\n      },\n    })\n\n    expectTypeOf(\n      counter.actions.increment.type,\n    ).toEqualTypeOf<'counter/increment'>()\n\n    expectTypeOf(\n      counter.actions.increment().type,\n    ).toEqualTypeOf<'counter/increment'>()\n\n    expectTypeOf(\n      counter.actions.decrement.type,\n    ).toEqualTypeOf<'counter/decrement'>()\n\n    expectTypeOf(\n      counter.actions.decrement().type,\n    ).toEqualTypeOf<'counter/decrement'>()\n\n    expectTypeOf(\n      counter.actions.multiply.type,\n    ).toEqualTypeOf<'counter/multiply'>()\n\n    expectTypeOf(\n      counter.actions.multiply(1).type,\n    ).toEqualTypeOf<'counter/multiply'>()\n\n    expectTypeOf(counter.actions.increment.type).not.toExtend<'increment'>()\n  })\n\n  test('Slice action creator types are inferred for enhanced reducers.', () => {\n    const counter = createSlice({\n      name: 'test',\n      initialState: { counter: 0, concat: '' },\n      reducers: {\n        incrementByStrLen: {\n          reducer: (state, action: PayloadAction<number>) => {\n            state.counter += action.payload\n          },\n          prepare: (payload: string) => ({\n            payload: payload.length,\n          }),\n        },\n        concatMetaStrLen: {\n          reducer: (state, action: PayloadAction<string>) => {\n            state.concat += action.payload\n          },\n          prepare: (payload: string) => ({\n            payload,\n            meta: payload.length,\n          }),\n        },\n      },\n    })\n\n    expectTypeOf(\n      counter.actions.incrementByStrLen('test').type,\n    ).toEqualTypeOf<'test/incrementByStrLen'>()\n\n    expectTypeOf(counter.actions.incrementByStrLen('test').payload).toBeNumber()\n\n    expectTypeOf(counter.actions.concatMetaStrLen('test').payload).toBeString()\n\n    expectTypeOf(counter.actions.concatMetaStrLen('test').meta).toBeNumber()\n\n    expectTypeOf(\n      counter.actions.incrementByStrLen('test').payload,\n    ).not.toBeString()\n\n    expectTypeOf(counter.actions.concatMetaStrLen('test').meta).not.toBeString()\n  })\n\n  test('access meta and error from reducer', () => {\n    const counter = createSlice({\n      name: 'test',\n      initialState: { counter: 0, concat: '' },\n      reducers: {\n        // case: meta and error not used in reducer\n        testDefaultMetaAndError: {\n          reducer(_, action: PayloadAction<number, string>) {},\n          prepare: (payload: number) => ({\n            payload,\n            meta: 'meta' as 'meta',\n            error: 'error' as 'error',\n          }),\n        },\n        // case: meta and error marked as \"unknown\" in reducer\n        testUnknownMetaAndError: {\n          reducer(\n            _,\n            action: PayloadAction<number, string, unknown, unknown>,\n          ) {},\n          prepare: (payload: number) => ({\n            payload,\n            meta: 'meta' as 'meta',\n            error: 'error' as 'error',\n          }),\n        },\n        // case: meta and error are typed in the reducer as returned by prepare\n        testMetaAndError: {\n          reducer(_, action: PayloadAction<number, string, 'meta', 'error'>) {},\n          prepare: (payload: number) => ({\n            payload,\n            meta: 'meta' as 'meta',\n            error: 'error' as 'error',\n          }),\n        },\n        // case: meta is typed differently in the reducer than returned from prepare\n        testErroneousMeta: {\n          reducer(_, action: PayloadAction<number, string, 'meta', 'error'>) {},\n          // @ts-expect-error\n          prepare: (payload: number) => ({\n            payload,\n            meta: 1,\n            error: 'error' as 'error',\n          }),\n        },\n        // case: error is typed differently in the reducer than returned from prepare\n        testErroneousError: {\n          reducer(_, action: PayloadAction<number, string, 'meta', 'error'>) {},\n          // @ts-expect-error\n          prepare: (payload: number) => ({\n            payload,\n            meta: 'meta' as 'meta',\n            error: 1,\n          }),\n        },\n      },\n    })\n  })\n\n  test('returned case reducer has the correct type', () => {\n    const counter = createSlice({\n      name: 'counter',\n      initialState: 0,\n      reducers: {\n        increment(state, action: PayloadAction<number>) {\n          return state + action.payload\n        },\n        decrement: {\n          reducer(state, action: PayloadAction<number>) {\n            return state - action.payload\n          },\n          prepare(amount: number) {\n            return { payload: amount }\n          },\n        },\n      },\n    })\n\n    test('Should match positively', () => {\n      expectTypeOf(counter.caseReducers.increment).toExtend<\n        (state: number, action: PayloadAction<number>) => number | void\n      >()\n    })\n\n    test('Should match positively for reducers with prepare callback', () => {\n      expectTypeOf(counter.caseReducers.decrement).toExtend<\n        (state: number, action: PayloadAction<number>) => number | void\n      >()\n    })\n\n    test(\"Should not mismatch the payload if it's a simple reducer\", () => {\n      expectTypeOf(counter.caseReducers.increment).not.toExtend<\n        (state: number, action: PayloadAction<string>) => number | void\n      >()\n    })\n\n    test(\"Should not mismatch the payload if it's a reducer with a prepare callback\", () => {\n      expectTypeOf(counter.caseReducers.decrement).not.toExtend<\n        (state: number, action: PayloadAction<string>) => number | void\n      >()\n    })\n\n    test(\"Should not include entries that don't exist\", () => {\n      expectTypeOf(counter.caseReducers).not.toHaveProperty(\n        'someThingNonExistent',\n      )\n    })\n  })\n\n  test('prepared payload does not match action payload - should cause an error.', () => {\n    const counter = createSlice({\n      name: 'counter',\n      initialState: { counter: 0 },\n      reducers: {\n        increment: {\n          reducer(state, action: PayloadAction<string>) {\n            state.counter += action.payload.length\n          },\n          // @ts-expect-error\n          prepare(x: string) {\n            return {\n              payload: 6,\n            }\n          },\n        },\n      },\n    })\n  })\n\n  test('if no Payload Type is specified, accept any payload', () => {\n    // see https://github.com/reduxjs/redux-toolkit/issues/165\n\n    const initialState = {\n      name: null,\n    }\n\n    const mySlice = createSlice({\n      name: 'name',\n      initialState,\n      reducers: {\n        setName: (state, action) => {\n          state.name = action.payload\n        },\n      },\n    })\n\n    expectTypeOf(\n      mySlice.actions.setName,\n    ).toExtend<ActionCreatorWithNonInferrablePayload>()\n\n    const x = mySlice.actions.setName\n\n    mySlice.actions.setName(null)\n    mySlice.actions.setName('asd')\n    mySlice.actions.setName(5)\n  })\n\n  test('actions.x.match()', () => {\n    const mySlice = createSlice({\n      name: 'name',\n      initialState: { name: 'test' },\n      reducers: {\n        setName: (state, action: PayloadAction<string>) => {\n          state.name = action.payload\n        },\n      },\n    })\n\n    const x: Action<string> = {} as any\n    if (mySlice.actions.setName.match(x)) {\n      expectTypeOf(x.type).toEqualTypeOf<'name/setName'>()\n\n      expectTypeOf(x.payload).toBeString()\n    } else {\n      expectTypeOf(x.type).not.toExtend<'name/setName'>()\n\n      expectTypeOf(x).not.toHaveProperty('payload')\n    }\n  })\n\n  test('builder callback for extraReducers', () => {\n    createSlice({\n      name: 'test',\n      initialState: 0,\n      reducers: {},\n      extraReducers: (builder) => {\n        expectTypeOf(builder).toEqualTypeOf<ActionReducerMapBuilder<number>>()\n      },\n    })\n  })\n\n  test('wrapping createSlice should be possible', () => {\n    interface GenericState<T> {\n      data?: T\n      status: 'loading' | 'finished' | 'error'\n    }\n\n    const createGenericSlice = <\n      T,\n      Reducers extends SliceCaseReducers<GenericState<T>>,\n    >({\n      name = '',\n      initialState,\n      reducers,\n    }: {\n      name: string\n      initialState: GenericState<T>\n      reducers: ValidateSliceCaseReducers<GenericState<T>, Reducers>\n    }) => {\n      return createSlice({\n        name,\n        initialState,\n        reducers: {\n          start(state) {\n            state.status = 'loading'\n          },\n          success(state: GenericState<T>, action: PayloadAction<T>) {\n            state.data = action.payload\n            state.status = 'finished'\n          },\n          ...reducers,\n        },\n      })\n    }\n\n    const wrappedSlice = createGenericSlice({\n      name: 'test',\n      initialState: { status: 'loading' } as GenericState<string>,\n      reducers: {\n        magic(state) {\n          expectTypeOf(state).toEqualTypeOf<GenericState<string>>()\n\n          expectTypeOf(state).not.toExtend<GenericState<number>>()\n\n          state.status = 'finished'\n          state.data = 'hocus pocus'\n        },\n      },\n    })\n\n    expectTypeOf(wrappedSlice.actions.success).toExtend<\n      ActionCreatorWithPayload<string>\n    >()\n\n    expectTypeOf(wrappedSlice.actions.magic).toExtend<\n      ActionCreatorWithoutPayload<string>\n    >()\n  })\n\n  test('extraReducers', () => {\n    interface GenericState<T> {\n      data: T | null\n    }\n\n    function createDataSlice<\n      T,\n      Reducers extends SliceCaseReducers<GenericState<T>>,\n    >(\n      name: string,\n      reducers: ValidateSliceCaseReducers<GenericState<T>, Reducers>,\n      initialState: GenericState<T>,\n    ) {\n      const doNothing = createAction<undefined>('doNothing')\n      const setData = createAction<T>('setData')\n\n      const slice = createSlice({\n        name,\n        initialState,\n        reducers,\n        extraReducers: (builder) => {\n          builder.addCase(doNothing, (state) => {\n            return { ...state }\n          })\n          builder.addCase(setData, (state, { payload }) => {\n            return {\n              ...state,\n              data: payload,\n            }\n          })\n        },\n      })\n      return { doNothing, setData, slice }\n    }\n  })\n\n  test('slice selectors', () => {\n    const sliceWithoutSelectors = createSlice({\n      name: '',\n      initialState: '',\n      reducers: {},\n    })\n\n    expectTypeOf(sliceWithoutSelectors.selectors).not.toHaveProperty('foo')\n\n    const sliceWithSelectors = createSlice({\n      name: 'counter',\n      initialState: { value: 0 },\n      reducers: {\n        increment: (state) => {\n          state.value += 1\n        },\n      },\n      selectors: {\n        selectValue: (state) => state.value,\n        selectMultiply: (state, multiplier: number) => state.value * multiplier,\n        selectToFixed: Object.assign(\n          (state: { value: number }) => state.value.toFixed(2),\n          { static: true },\n        ),\n      },\n    })\n\n    const rootState = {\n      [sliceWithSelectors.reducerPath]: sliceWithSelectors.getInitialState(),\n    }\n\n    const { selectValue, selectMultiply, selectToFixed } =\n      sliceWithSelectors.selectors\n\n    expectTypeOf(selectValue(rootState)).toBeNumber()\n\n    expectTypeOf(selectMultiply(rootState, 2)).toBeNumber()\n\n    expectTypeOf(selectToFixed(rootState)).toBeString()\n\n    expectTypeOf(selectToFixed.unwrapped.static).toBeBoolean()\n\n    const nestedState = {\n      nested: rootState,\n    }\n\n    const nestedSelectors = sliceWithSelectors.getSelectors(\n      (rootState: typeof nestedState) => rootState.nested.counter,\n    )\n\n    expectTypeOf(nestedSelectors.selectValue(nestedState)).toBeNumber()\n\n    expectTypeOf(nestedSelectors.selectMultiply(nestedState, 2)).toBeNumber()\n\n    expectTypeOf(nestedSelectors.selectToFixed(nestedState)).toBeString()\n  })\n\n  test('reducer callback', () => {\n    interface TestState {\n      foo: string\n    }\n\n    interface TestArg {\n      test: string\n    }\n\n    interface TestReturned {\n      payload: string\n    }\n\n    interface TestReject {\n      cause: string\n    }\n\n    const slice = createSlice({\n      name: 'test',\n      initialState: {} as TestState,\n      reducers: (create) => {\n        const preTypedAsyncThunk = create.asyncThunk.withTypes<{\n          rejectValue: TestReject\n        }>()\n\n        // @ts-expect-error\n        create.asyncThunk<any, any, { state: StoreState }>(() => {})\n\n        // @ts-expect-error\n        create.asyncThunk.withTypes<{\n          rejectValue: string\n          dispatch: StoreDispatch\n        }>()\n\n        return {\n          normalReducer: create.reducer<string>((state, action) => {\n            expectTypeOf(state).toEqualTypeOf<TestState>()\n\n            expectTypeOf(action.payload).toBeString()\n          }),\n          optionalReducer: create.reducer<string | undefined>(\n            (state, action) => {\n              expectTypeOf(state).toEqualTypeOf<TestState>()\n\n              expectTypeOf(action.payload).toEqualTypeOf<string | undefined>()\n            },\n          ),\n          noActionReducer: create.reducer((state) => {\n            expectTypeOf(state).toEqualTypeOf<TestState>()\n          }),\n          preparedReducer: create.preparedReducer(\n            (payload: string) => ({\n              payload,\n              meta: 'meta' as const,\n              error: 'error' as const,\n            }),\n            (state, action) => {\n              expectTypeOf(state).toEqualTypeOf<TestState>()\n\n              expectTypeOf(action.payload).toBeString()\n\n              expectTypeOf(action.meta).toEqualTypeOf<'meta'>()\n\n              expectTypeOf(action.error).toEqualTypeOf<'error'>()\n            },\n          ),\n          testInferVoid: create.asyncThunk(() => {}, {\n            pending(state, action) {\n              expectTypeOf(state).toEqualTypeOf<TestState>()\n\n              expectTypeOf(action.meta.arg).toBeVoid()\n            },\n            fulfilled(state, action) {\n              expectTypeOf(state).toEqualTypeOf<TestState>()\n\n              expectTypeOf(action.meta.arg).toBeVoid()\n\n              expectTypeOf(action.payload).toBeVoid()\n            },\n            rejected(state, action) {\n              expectTypeOf(state).toEqualTypeOf<TestState>()\n\n              expectTypeOf(action.meta.arg).toBeVoid()\n\n              expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n            },\n            settled(state, action) {\n              expectTypeOf(state).toEqualTypeOf<TestState>()\n\n              expectTypeOf(action.meta.arg).toBeVoid()\n\n              if (isRejected(action)) {\n                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n              } else {\n                expectTypeOf(action.payload).toBeVoid()\n              }\n            },\n          }),\n          testInfer: create.asyncThunk(\n            function payloadCreator(arg: TestArg, api) {\n              return Promise.resolve<TestReturned>({ payload: 'foo' })\n            },\n            {\n              pending(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n              },\n              fulfilled(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n\n                expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()\n              },\n              rejected(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n\n                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n              },\n              settled(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n\n                if (isRejected(action)) {\n                  expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n                } else {\n                  expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()\n                }\n              },\n            },\n          ),\n          testExplicitType: create.asyncThunk<\n            TestReturned,\n            TestArg,\n            {\n              rejectValue: TestReject\n            }\n          >(\n            function payloadCreator(arg, api) {\n              // here would be a circular reference\n              expectTypeOf(api.getState()).toBeUnknown()\n              // here would be a circular reference\n              expectTypeOf(api.dispatch).toExtend<\n                ThunkDispatch<any, any, any>\n              >()\n\n              // so you need to cast inside instead\n              const getState = api.getState as () => StoreState\n              const dispatch = api.dispatch as StoreDispatch\n\n              expectTypeOf(arg).toEqualTypeOf<TestArg>()\n\n              expectTypeOf(api.rejectWithValue).toExtend<\n                (value: TestReject) => any\n              >()\n\n              return Promise.resolve({ payload: 'foo' })\n            },\n            {\n              pending(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n              },\n              fulfilled(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n\n                expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()\n              },\n              rejected(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n\n                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n\n                expectTypeOf(action.payload).toEqualTypeOf<\n                  TestReject | undefined\n                >()\n              },\n              settled(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n\n                if (isRejected(action)) {\n                  expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n\n                  expectTypeOf(action.payload).toEqualTypeOf<\n                    TestReject | undefined\n                  >()\n                } else {\n                  expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()\n                }\n              },\n            },\n          ),\n          testPreTyped: preTypedAsyncThunk(\n            function payloadCreator(arg: TestArg, api) {\n              expectTypeOf(api.rejectWithValue).toExtend<\n                (value: TestReject) => any\n              >()\n\n              return Promise.resolve<TestReturned>({ payload: 'foo' })\n            },\n            {\n              pending(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n              },\n              fulfilled(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n\n                expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()\n              },\n              rejected(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n\n                expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n\n                expectTypeOf(action.payload).toEqualTypeOf<\n                  TestReject | undefined\n                >()\n              },\n              settled(state, action) {\n                expectTypeOf(state).toEqualTypeOf<TestState>()\n\n                expectTypeOf(action.meta.arg).toEqualTypeOf<TestArg>()\n\n                if (isRejected(action)) {\n                  expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n\n                  expectTypeOf(action.payload).toEqualTypeOf<\n                    TestReject | undefined\n                  >()\n                } else {\n                  expectTypeOf(action.payload).toEqualTypeOf<TestReturned>()\n                }\n              },\n            },\n          ),\n        }\n      },\n    })\n\n    const store = configureStore({ reducer: { test: slice.reducer } })\n\n    type StoreState = ReturnType<typeof store.getState>\n\n    type StoreDispatch = typeof store.dispatch\n\n    expectTypeOf(slice.actions.normalReducer).toExtend<\n      PayloadActionCreator<string>\n    >()\n\n    expectTypeOf(slice.actions.normalReducer).toBeCallableWith('')\n\n    expectTypeOf(slice.actions.normalReducer).parameters.not.toExtend<[]>()\n\n    expectTypeOf(slice.actions.normalReducer).parameters.not.toExtend<\n      [number]\n    >()\n\n    expectTypeOf(slice.actions.optionalReducer).toExtend<\n      ActionCreatorWithOptionalPayload<string | undefined>\n    >()\n\n    expectTypeOf(slice.actions.optionalReducer).toBeCallableWith()\n\n    expectTypeOf(slice.actions.optionalReducer).toBeCallableWith('')\n\n    expectTypeOf(slice.actions.optionalReducer).parameter(0).not.toBeNumber()\n\n    expectTypeOf(\n      slice.actions.noActionReducer,\n    ).toExtend<ActionCreatorWithoutPayload>()\n\n    expectTypeOf(slice.actions.noActionReducer).toBeCallableWith()\n\n    expectTypeOf(slice.actions.noActionReducer).parameter(0).not.toBeString()\n\n    expectTypeOf(slice.actions.preparedReducer).toEqualTypeOf<\n      ActionCreatorWithPreparedPayload<\n        [string],\n        string,\n        'test/preparedReducer',\n        'error',\n        'meta'\n      >\n    >()\n\n    expectTypeOf(slice.actions.testInferVoid).toEqualTypeOf<\n      AsyncThunk<void, void, {}>\n    >()\n\n    expectTypeOf(slice.actions.testInferVoid).toBeCallableWith()\n\n    expectTypeOf(slice.actions.testInfer).toEqualTypeOf<\n      AsyncThunk<TestReturned, TestArg, {}>\n    >()\n\n    expectTypeOf(slice.actions.testExplicitType).toEqualTypeOf<\n      AsyncThunk<TestReturned, TestArg, { rejectValue: TestReject }>\n    >()\n\n    type TestInferThunk = AsyncThunk<TestReturned, TestArg, {}>\n\n    expectTypeOf(slice.caseReducers.testInfer.pending).toEqualTypeOf<\n      CaseReducer<TestState, ReturnType<TestInferThunk['pending']>>\n    >()\n\n    expectTypeOf(slice.caseReducers.testInfer.fulfilled).toEqualTypeOf<\n      CaseReducer<TestState, ReturnType<TestInferThunk['fulfilled']>>\n    >()\n\n    expectTypeOf(slice.caseReducers.testInfer.rejected).toEqualTypeOf<\n      CaseReducer<TestState, ReturnType<TestInferThunk['rejected']>>\n    >()\n  })\n\n  test('wrapping createSlice should be possible, with callback', () => {\n    interface GenericState<T> {\n      data?: T\n      status: 'loading' | 'finished' | 'error'\n    }\n\n    const createGenericSlice = <\n      T,\n      Reducers extends SliceCaseReducers<GenericState<T>>,\n    >({\n      name = '',\n      initialState,\n      reducers,\n    }: {\n      name: string\n      initialState: GenericState<T>\n      reducers: (create: ReducerCreators<GenericState<T>>) => Reducers\n    }) => {\n      return createSlice({\n        name,\n        initialState,\n        reducers: (create) => ({\n          start: create.reducer((state) => {\n            state.status = 'loading'\n          }),\n          success: create.reducer<T>((state, action) => {\n            state.data = castDraft(action.payload)\n            state.status = 'finished'\n          }),\n          ...reducers(create),\n        }),\n      })\n    }\n\n    const wrappedSlice = createGenericSlice({\n      name: 'test',\n      initialState: { status: 'loading' } as GenericState<string>,\n      reducers: (create) => ({\n        magic: create.reducer((state) => {\n          expectTypeOf(state).toEqualTypeOf<GenericState<string>>()\n\n          expectTypeOf(state).not.toExtend<GenericState<number>>()\n\n          state.status = 'finished'\n          state.data = 'hocus pocus'\n        }),\n      }),\n    })\n\n    expectTypeOf(wrappedSlice.actions.success).toExtend<\n      ActionCreatorWithPayload<string>\n    >()\n\n    expectTypeOf(wrappedSlice.actions.magic).toExtend<\n      ActionCreatorWithoutPayload<string>\n    >()\n  })\n\n  test('selectSlice', () => {\n    expectTypeOf(counterSlice.selectSlice({ counter: 0 })).toBeNumber()\n\n    // We use `not.toEqualTypeOf` instead of `not.toMatchObjectType`\n    // because `toMatchObjectType` allows missing properties\n    expectTypeOf(counterSlice.selectSlice).parameter(0).not.toEqualTypeOf<{}>()\n  })\n\n  test('buildCreateSlice', () => {\n    expectTypeOf(buildCreateSlice()).toEqualTypeOf(createSlice)\n\n    buildCreateSlice({\n      // @ts-expect-error not possible to recreate shape because symbol is not exported\n      creators: { asyncThunk: { [Symbol()]: createAsyncThunk } },\n    })\n    buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/createSlice.test.ts",
    "content": "import { noop } from '@internal/listenerMiddleware/utils'\nimport type { PayloadAction, WithSlice } from '@reduxjs/toolkit'\nimport {\n  asyncThunkCreator,\n  buildCreateSlice,\n  combineSlices,\n  configureStore,\n  createAction,\n  createAsyncThunk,\n  createSlice,\n} from '@reduxjs/toolkit'\n\ntype CreateSlice = typeof createSlice\n\ndescribe('createSlice', () => {\n  const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n\n  beforeEach(() => {\n    vi.clearAllMocks()\n  })\n\n  afterAll(() => {\n    vi.restoreAllMocks()\n  })\n\n  describe('when slice is undefined', () => {\n    it('should throw an error', () => {\n      expect(() =>\n        // @ts-ignore\n        createSlice({\n          reducers: {\n            increment: (state) => state + 1,\n            multiply: (state, action: PayloadAction<number>) =>\n              state * action.payload,\n          },\n          initialState: 0,\n        }),\n      ).toThrowError()\n    })\n  })\n\n  describe('when slice is an empty string', () => {\n    it('should throw an error', () => {\n      expect(() =>\n        createSlice({\n          name: '',\n          reducers: {\n            increment: (state) => state + 1,\n            multiply: (state, action: PayloadAction<number>) =>\n              state * action.payload,\n          },\n          initialState: 0,\n        }),\n      ).toThrowError()\n    })\n  })\n\n  describe('when initial state is undefined', () => {\n    beforeEach(() => {\n      vi.stubEnv('NODE_ENV', 'development')\n    })\n\n    afterEach(() => {\n      vi.unstubAllEnvs()\n    })\n\n    it('should throw an error', () => {\n      createSlice({\n        name: 'test',\n        reducers: {},\n        initialState: undefined,\n      })\n\n      expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n      expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n        'You must provide an `initialState` value that is not `undefined`. You may have misspelled `initialState`',\n      )\n    })\n  })\n\n  describe('when passing slice', () => {\n    const { actions, reducer, caseReducers } = createSlice({\n      reducers: {\n        increment: (state) => state + 1,\n      },\n      initialState: 0,\n      name: 'cool',\n    })\n\n    it('should create increment action', () => {\n      expect(actions.hasOwnProperty('increment')).toBe(true)\n    })\n\n    it('should have the correct action for increment', () => {\n      expect(actions.increment()).toEqual({\n        type: 'cool/increment',\n        payload: undefined,\n      })\n    })\n\n    it('should return the correct value from reducer', () => {\n      expect(reducer(undefined, actions.increment())).toEqual(1)\n    })\n\n    it('should include the generated case reducers', () => {\n      expect(caseReducers).toBeTruthy()\n      expect(caseReducers.increment).toBeTruthy()\n      expect(typeof caseReducers.increment).toBe('function')\n    })\n\n    it('getInitialState should return the state', () => {\n      const initialState = 42\n      const slice = createSlice({\n        name: 'counter',\n        initialState,\n        reducers: {},\n      })\n\n      expect(slice.getInitialState()).toBe(initialState)\n    })\n\n    it('should allow non-draftable initial state', () => {\n      expect(() =>\n        createSlice({\n          name: 'params',\n          initialState: new URLSearchParams(),\n          reducers: {},\n        }),\n      ).not.toThrowError()\n    })\n  })\n\n  describe('when initialState is a function', () => {\n    const initialState = () => ({ user: '' })\n\n    const { actions, reducer } = createSlice({\n      reducers: {\n        setUserName: (state, action) => {\n          state.user = action.payload\n        },\n      },\n      initialState,\n      name: 'user',\n    })\n\n    it('should set the username', () => {\n      expect(reducer(undefined, actions.setUserName('eric'))).toEqual({\n        user: 'eric',\n      })\n    })\n\n    it('getInitialState should return the state', () => {\n      const initialState = () => 42\n      const slice = createSlice({\n        name: 'counter',\n        initialState,\n        reducers: {},\n      })\n\n      expect(slice.getInitialState()).toBe(42)\n    })\n\n    it('should allow non-draftable initial state', () => {\n      expect(() =>\n        createSlice({\n          name: 'params',\n          initialState: () => new URLSearchParams(),\n          reducers: {},\n        }),\n      ).not.toThrowError()\n    })\n  })\n\n  describe('when mutating state object', () => {\n    const initialState = { user: '' }\n\n    const { actions, reducer } = createSlice({\n      reducers: {\n        setUserName: (state, action) => {\n          state.user = action.payload\n        },\n      },\n      initialState,\n      name: 'user',\n    })\n\n    it('should set the username', () => {\n      expect(reducer(initialState, actions.setUserName('eric'))).toEqual({\n        user: 'eric',\n      })\n    })\n  })\n\n  describe('when passing extra reducers', () => {\n    const addMore = createAction<{ amount: number }>('ADD_MORE')\n\n    const { reducer } = createSlice({\n      name: 'test',\n      reducers: {\n        increment: (state) => state + 1,\n        multiply: (state, action) => state * action.payload,\n      },\n      extraReducers: (builder) => {\n        builder.addCase(\n          addMore,\n          (state, action) => state + action.payload.amount,\n        )\n      },\n\n      initialState: 0,\n    })\n\n    it('should call extra reducers when their actions are dispatched', () => {\n      const result = reducer(10, addMore({ amount: 5 }))\n\n      expect(result).toBe(15)\n    })\n\n    describe('builder callback for extraReducers', () => {\n      const increment = createAction<number, 'increment'>('increment')\n\n      test('can be used with actionCreators', () => {\n        const slice = createSlice({\n          name: 'counter',\n          initialState: 0,\n          reducers: {},\n          extraReducers: (builder) =>\n            builder.addCase(\n              increment,\n              (state, action) => state + action.payload,\n            ),\n        })\n        expect(slice.reducer(0, increment(5))).toBe(5)\n      })\n\n      test('can be used with string action types', () => {\n        const slice = createSlice({\n          name: 'counter',\n          initialState: 0,\n          reducers: {},\n          extraReducers: (builder) =>\n            builder.addCase(\n              'increment',\n              (state, action: { type: 'increment'; payload: number }) =>\n                state + action.payload,\n            ),\n        })\n        expect(slice.reducer(0, increment(5))).toBe(5)\n      })\n\n      test('prevents the same action type from being specified twice', () => {\n        expect(() => {\n          const slice = createSlice({\n            name: 'counter',\n            initialState: 0,\n            reducers: {},\n            extraReducers: (builder) =>\n              builder\n                .addCase('increment', (state) => state + 1)\n                .addCase('increment', (state) => state + 1),\n          })\n          slice.reducer(undefined, { type: 'unrelated' })\n        }).toThrowErrorMatchingInlineSnapshot(\n          `[Error: \\`builder.addCase\\` cannot be called with two reducers for the same action type 'increment']`,\n        )\n      })\n\n      test('can be used with addAsyncThunk and async thunks', () => {\n        const asyncThunk = createAsyncThunk('test', (n: number) => n)\n        const slice = createSlice({\n          name: 'counter',\n          initialState: {\n            loading: false,\n            errored: false,\n            value: 0,\n          },\n          reducers: {},\n          extraReducers: (builder) =>\n            builder.addAsyncThunk(asyncThunk, {\n              pending(state) {\n                state.loading = true\n              },\n              fulfilled(state, action) {\n                state.value = action.payload\n              },\n              rejected(state) {\n                state.errored = true\n              },\n              settled(state) {\n                state.loading = false\n              },\n            }),\n        })\n        expect(\n          slice.reducer(undefined, asyncThunk.pending('requestId', 5)),\n        ).toEqual({\n          loading: true,\n          errored: false,\n          value: 0,\n        })\n        expect(\n          slice.reducer(undefined, asyncThunk.fulfilled(5, 'requestId', 5)),\n        ).toEqual({\n          loading: false,\n          errored: false,\n          value: 5,\n        })\n        expect(\n          slice.reducer(\n            undefined,\n            asyncThunk.rejected(new Error(), 'requestId', 5),\n          ),\n        ).toEqual({\n          loading: false,\n          errored: true,\n          value: 0,\n        })\n      })\n\n      test('can be used with addMatcher and type guard functions', () => {\n        const slice = createSlice({\n          name: 'counter',\n          initialState: 0,\n          reducers: {},\n          extraReducers: (builder) =>\n            builder.addMatcher(\n              increment.match,\n              (state, action: { type: 'increment'; payload: number }) =>\n                state + action.payload,\n            ),\n        })\n        expect(slice.reducer(0, increment(5))).toBe(5)\n      })\n\n      test('can be used with addDefaultCase', () => {\n        const slice = createSlice({\n          name: 'counter',\n          initialState: 0,\n          reducers: {},\n          extraReducers: (builder) =>\n            builder.addDefaultCase(\n              (state, action) =>\n                state + (action as PayloadAction<number>).payload,\n            ),\n        })\n        expect(slice.reducer(0, increment(5))).toBe(5)\n      })\n\n      // for further tests, see the test of createReducer that goes way more into depth on this\n    })\n  })\n\n  describe('behavior with enhanced case reducers', () => {\n    it('should pass all arguments to the prepare function', () => {\n      const prepare = vi.fn((payload, somethingElse) => ({ payload }))\n\n      const testSlice = createSlice({\n        name: 'test',\n        initialState: 0,\n        reducers: {\n          testReducer: {\n            reducer: (s) => s,\n            prepare,\n          },\n        },\n      })\n\n      expect(testSlice.actions.testReducer('a', 1)).toEqual({\n        type: 'test/testReducer',\n        payload: 'a',\n      })\n      expect(prepare).toHaveBeenCalledWith('a', 1)\n    })\n\n    it('should call the reducer function', () => {\n      const reducer = vi.fn(() => 5)\n\n      const testSlice = createSlice({\n        name: 'test',\n        initialState: 0,\n        reducers: {\n          testReducer: {\n            reducer,\n            prepare: (payload: any) => ({ payload }),\n          },\n        },\n      })\n\n      testSlice.reducer(0, testSlice.actions.testReducer('testPayload'))\n      expect(reducer).toHaveBeenCalledWith(\n        0,\n        expect.objectContaining({ payload: 'testPayload' }),\n      )\n    })\n  })\n\n  describe('circularity', () => {\n    test('extraReducers can reference each other circularly', () => {\n      const first = createSlice({\n        name: 'first',\n        initialState: 'firstInitial',\n        reducers: {\n          something() {\n            return 'firstSomething'\n          },\n        },\n        extraReducers(builder) {\n          // eslint-disable-next-line @typescript-eslint/no-use-before-define\n          builder.addCase(second.actions.other, () => {\n            return 'firstOther'\n          })\n        },\n      })\n      const second = createSlice({\n        name: 'second',\n        initialState: 'secondInitial',\n        reducers: {\n          other() {\n            return 'secondOther'\n          },\n        },\n        extraReducers(builder) {\n          builder.addCase(first.actions.something, () => {\n            return 'secondSomething'\n          })\n        },\n      })\n\n      expect(first.reducer(undefined, { type: 'unrelated' })).toBe(\n        'firstInitial',\n      )\n      expect(first.reducer(undefined, first.actions.something())).toBe(\n        'firstSomething',\n      )\n      expect(first.reducer(undefined, second.actions.other())).toBe(\n        'firstOther',\n      )\n\n      expect(second.reducer(undefined, { type: 'unrelated' })).toBe(\n        'secondInitial',\n      )\n      expect(second.reducer(undefined, first.actions.something())).toBe(\n        'secondSomething',\n      )\n      expect(second.reducer(undefined, second.actions.other())).toBe(\n        'secondOther',\n      )\n    })\n  })\n\n  describe('Deprecation warnings', () => {\n    beforeEach(() => {\n      vi.resetModules()\n    })\n\n    afterEach(() => {\n      vi.unstubAllEnvs()\n    })\n\n    // NOTE: This needs to be in front of the later `createReducer` call to check the one-time warning\n    it('Throws an error if the legacy object notation is used', async () => {\n      const { createSlice } = await import('../createSlice')\n\n      let dummySlice = (createSlice as CreateSlice)({\n        name: 'dummy',\n        initialState: [],\n        reducers: {},\n        extraReducers: {\n          // @ts-ignore\n          a: () => [],\n        },\n      })\n      let reducer: any\n      // Have to trigger the lazy creation\n      const wrapper = () => {\n        reducer = dummySlice.reducer\n        reducer(undefined, { type: 'dummy' })\n      }\n\n      expect(wrapper).toThrowError(\n        /The object notation for `createSlice.extraReducers` has been removed/,\n      )\n\n      dummySlice = (createSlice as CreateSlice)({\n        name: 'dummy',\n        initialState: [],\n        reducers: {},\n        extraReducers: {\n          // @ts-ignore\n          a: () => [],\n        },\n      })\n      expect(wrapper).toThrowError(\n        /The object notation for `createSlice.extraReducers` has been removed/,\n      )\n    })\n\n    // TODO Determine final production behavior here\n    it.todo('Crashes in production', () => {\n      vi.stubEnv('NODE_ENV', 'production')\n\n      const { createSlice } = require('../createSlice')\n\n      const dummySlice = (createSlice as CreateSlice)({\n        name: 'dummy',\n        initialState: [],\n        reducers: {},\n        // @ts-ignore\n        extraReducers: {},\n      })\n      const wrapper = () => {\n        const { reducer } = dummySlice\n        reducer(undefined, { type: 'dummy' })\n      }\n\n      expect(wrapper).toThrowError(\n        /The object notation for `createSlice.extraReducers` has been removed/,\n      )\n\n      vi.unstubAllEnvs()\n    })\n  })\n  describe('slice selectors', () => {\n    const slice = createSlice({\n      name: 'counter',\n      initialState: 42,\n      reducers: {},\n      selectors: {\n        selectSlice: (state) => state,\n        selectMultiple: Object.assign(\n          (state: number, multiplier: number) => state * multiplier,\n          { test: 0 },\n        ),\n      },\n    })\n    it('expects reducer under slice.reducerPath if no selectState callback passed', () => {\n      const testState = {\n        [slice.reducerPath]: slice.getInitialState(),\n      }\n      const { selectSlice, selectMultiple } = slice.selectors\n      expect(selectSlice(testState)).toBe(slice.getInitialState())\n      expect(selectMultiple(testState, 2)).toBe(slice.getInitialState() * 2)\n    })\n    it('allows passing a selector for a custom location', () => {\n      const customState = {\n        number: slice.getInitialState(),\n      }\n      const { selectSlice, selectMultiple } = slice.getSelectors(\n        (state: typeof customState) => state.number,\n      )\n      expect(selectSlice(customState)).toBe(slice.getInitialState())\n      expect(selectMultiple(customState, 2)).toBe(slice.getInitialState() * 2)\n    })\n    it('allows accessing properties on the selector', () => {\n      expect(slice.selectors.selectMultiple.unwrapped.test).toBe(0)\n    })\n    it('has selectSlice attached to slice, which can go without this', () => {\n      const slice = createSlice({\n        name: 'counter',\n        initialState: 42,\n        reducers: {},\n      })\n      const { selectSlice } = slice\n      expect(() => selectSlice({ counter: 42 })).not.toThrow()\n      expect(selectSlice({ counter: 42 })).toBe(42)\n    })\n  })\n  describe('slice injections', () => {\n    it('uses injectInto to inject slice into combined reducer', () => {\n      const slice = createSlice({\n        name: 'counter',\n        initialState: 42,\n        reducers: {\n          increment: (state) => ++state,\n        },\n        selectors: {\n          selectMultiple: (state, multiplier: number) => state * multiplier,\n        },\n      })\n\n      const { increment } = slice.actions\n\n      const combinedReducer = combineSlices({\n        static: slice.reducer,\n      }).withLazyLoadedSlices<WithSlice<typeof slice>>()\n\n      const uninjectedState = combinedReducer(undefined, increment())\n\n      expect(uninjectedState.counter).toBe(undefined)\n\n      const injectedSlice = slice.injectInto(combinedReducer)\n\n      // selector returns initial state if undefined in real state\n      expect(injectedSlice.selectSlice(uninjectedState)).toBe(\n        slice.getInitialState(),\n      )\n      expect(injectedSlice.selectors.selectMultiple({}, 1)).toBe(\n        slice.getInitialState(),\n      )\n      expect(injectedSlice.getSelectors().selectMultiple(undefined, 1)).toBe(\n        slice.getInitialState(),\n      )\n\n      const injectedState = combinedReducer(undefined, increment())\n\n      expect(injectedSlice.selectSlice(injectedState)).toBe(\n        slice.getInitialState() + 1,\n      )\n      expect(injectedSlice.selectors.selectMultiple(injectedState, 1)).toBe(\n        slice.getInitialState() + 1,\n      )\n    })\n    it('allows providing a custom name to inject under', () => {\n      const slice = createSlice({\n        name: 'counter',\n        reducerPath: 'injected',\n        initialState: 42,\n        reducers: {\n          increment: (state) => ++state,\n        },\n        selectors: {\n          selectMultiple: (state, multiplier: number) => state * multiplier,\n        },\n      })\n\n      const { increment } = slice.actions\n\n      const combinedReducer = combineSlices({\n        static: slice.reducer,\n      }).withLazyLoadedSlices<WithSlice<typeof slice> & { injected2: number }>()\n\n      const uninjectedState = combinedReducer(undefined, increment())\n\n      expect(uninjectedState.injected).toBe(undefined)\n\n      const injected = slice.injectInto(combinedReducer)\n\n      const injectedState = combinedReducer(undefined, increment())\n\n      expect(injected.selectSlice(injectedState)).toBe(\n        slice.getInitialState() + 1,\n      )\n      expect(injected.selectors.selectMultiple(injectedState, 2)).toBe(\n        (slice.getInitialState() + 1) * 2,\n      )\n\n      const injected2 = slice.injectInto(combinedReducer, {\n        reducerPath: 'injected2',\n      })\n\n      const injected2State = combinedReducer(undefined, increment())\n\n      expect(injected2.selectSlice(injected2State)).toBe(\n        slice.getInitialState() + 1,\n      )\n      expect(injected2.selectors.selectMultiple(injected2State, 2)).toBe(\n        (slice.getInitialState() + 1) * 2,\n      )\n    })\n    it('avoids incorrectly caching selectors', () => {\n      const slice = createSlice({\n        name: 'counter',\n        reducerPath: 'injected',\n        initialState: 42,\n        reducers: {\n          increment: (state) => ++state,\n        },\n        selectors: {\n          selectMultiple: (state, multiplier: number) => state * multiplier,\n        },\n      })\n      expect(slice.getSelectors()).toBe(slice.getSelectors())\n      const combinedReducer = combineSlices({\n        static: slice.reducer,\n      }).withLazyLoadedSlices<WithSlice<typeof slice>>()\n\n      const injected = slice.injectInto(combinedReducer)\n\n      expect(injected.getSelectors()).not.toBe(slice.getSelectors())\n\n      expect(injected.getSelectors().selectMultiple(undefined, 1)).toBe(42)\n\n      expect(() =>\n        // @ts-expect-error\n        slice.getSelectors().selectMultiple(undefined, 1),\n      ).toThrowErrorMatchingInlineSnapshot(\n        `[Error: selectState returned undefined for an uninjected slice reducer]`,\n      )\n\n      const injected2 = slice.injectInto(combinedReducer, {\n        reducerPath: 'other',\n      })\n\n      // can use same cache for localised selectors\n      expect(injected.getSelectors()).toBe(injected2.getSelectors())\n      // these should be different\n      expect(injected.selectors).not.toBe(injected2.selectors)\n    })\n    it('caches initial states for selectors', () => {\n      const slice = createSlice({\n        name: 'counter',\n        initialState: () => ({ value: 0 }),\n        reducers: {},\n        selectors: {\n          selectObj: (state) => state,\n        },\n      })\n      // not cached\n      expect(slice.getInitialState()).not.toBe(slice.getInitialState())\n      expect(slice.reducer(undefined, { type: 'dummy' })).not.toBe(\n        slice.reducer(undefined, { type: 'dummy' }),\n      )\n\n      const combinedReducer = combineSlices({\n        static: slice.reducer,\n      }).withLazyLoadedSlices<WithSlice<typeof slice>>()\n\n      const injected = slice.injectInto(combinedReducer)\n\n      // still not cached\n      expect(injected.getInitialState()).not.toBe(injected.getInitialState())\n      expect(injected.reducer(undefined, { type: 'dummy' })).not.toBe(\n        injected.reducer(undefined, { type: 'dummy' }),\n      )\n      // cached\n      expect(injected.selectSlice({})).toBe(injected.selectSlice({}))\n      expect(injected.selectors.selectObj({})).toBe(\n        injected.selectors.selectObj({}),\n      )\n    })\n  })\n  describe('reducers definition with asyncThunks', () => {\n    it('is disabled by default', () => {\n      expect(() =>\n        createSlice({\n          name: 'test',\n          initialState: [] as any[],\n          reducers: (create) => ({ thunk: create.asyncThunk(() => {}) }),\n        }),\n      ).toThrowErrorMatchingInlineSnapshot(\n        `[Error: Cannot use \\`create.asyncThunk\\` in the built-in \\`createSlice\\`. Use \\`buildCreateSlice({ creators: { asyncThunk: asyncThunkCreator } })\\` to create a customised version of \\`createSlice\\`.]`,\n      )\n    })\n    const createAppSlice = buildCreateSlice({\n      creators: { asyncThunk: asyncThunkCreator },\n    })\n    function pending(state: any[], action: any) {\n      state.push(['pendingReducer', action])\n    }\n    function fulfilled(state: any[], action: any) {\n      state.push(['fulfilledReducer', action])\n    }\n    function rejected(state: any[], action: any) {\n      state.push(['rejectedReducer', action])\n    }\n    function settled(state: any[], action: any) {\n      state.push(['settledReducer', action])\n    }\n\n    test('successful thunk', async () => {\n      const slice = createAppSlice({\n        name: 'test',\n        initialState: [] as any[],\n        reducers: (create) => ({\n          thunkReducers: create.asyncThunk(\n            function payloadCreator(arg: string, api) {\n              return Promise.resolve('resolved payload')\n            },\n            { pending, fulfilled, rejected, settled },\n          ),\n        }),\n      })\n\n      const store = configureStore({\n        reducer: slice.reducer,\n      })\n      await store.dispatch(slice.actions.thunkReducers('test'))\n      expect(store.getState()).toMatchObject([\n        [\n          'pendingReducer',\n          {\n            type: 'test/thunkReducers/pending',\n            payload: undefined,\n          },\n        ],\n        [\n          'fulfilledReducer',\n          {\n            type: 'test/thunkReducers/fulfilled',\n            payload: 'resolved payload',\n          },\n        ],\n        [\n          'settledReducer',\n          {\n            type: 'test/thunkReducers/fulfilled',\n            payload: 'resolved payload',\n          },\n        ],\n      ])\n    })\n\n    test('rejected thunk', async () => {\n      const slice = createAppSlice({\n        name: 'test',\n        initialState: [] as any[],\n        reducers: (create) => ({\n          thunkReducers: create.asyncThunk(\n            // payloadCreator isn't allowed to return never\n            function payloadCreator(arg: string, api): any {\n              throw new Error('')\n            },\n            { pending, fulfilled, rejected, settled },\n          ),\n        }),\n      })\n\n      const store = configureStore({\n        reducer: slice.reducer,\n      })\n      await store.dispatch(slice.actions.thunkReducers('test'))\n      expect(store.getState()).toMatchObject([\n        [\n          'pendingReducer',\n          {\n            type: 'test/thunkReducers/pending',\n            payload: undefined,\n          },\n        ],\n        [\n          'rejectedReducer',\n          {\n            type: 'test/thunkReducers/rejected',\n            payload: undefined,\n          },\n        ],\n        [\n          'settledReducer',\n          {\n            type: 'test/thunkReducers/rejected',\n            payload: undefined,\n          },\n        ],\n      ])\n    })\n\n    test('with options', async () => {\n      const slice = createAppSlice({\n        name: 'test',\n        initialState: [] as any[],\n        reducers: (create) => ({\n          thunkReducers: create.asyncThunk(\n            function payloadCreator(arg: string, api) {\n              return 'should not call this'\n            },\n            {\n              options: {\n                condition() {\n                  return false\n                },\n                dispatchConditionRejection: true,\n              },\n              pending,\n              fulfilled,\n              rejected,\n              settled,\n            },\n          ),\n        }),\n      })\n\n      const store = configureStore({\n        reducer: slice.reducer,\n      })\n      await store.dispatch(slice.actions.thunkReducers('test'))\n      expect(store.getState()).toMatchObject([\n        [\n          'rejectedReducer',\n          {\n            type: 'test/thunkReducers/rejected',\n            payload: undefined,\n            meta: { condition: true },\n          },\n        ],\n        [\n          'settledReducer',\n          {\n            type: 'test/thunkReducers/rejected',\n            payload: undefined,\n            meta: { condition: true },\n          },\n        ],\n      ])\n    })\n\n    test('has caseReducers for the asyncThunk', async () => {\n      const slice = createAppSlice({\n        name: 'test',\n        initialState: [],\n        reducers: (create) => ({\n          thunkReducers: create.asyncThunk(\n            function payloadCreator(arg, api) {\n              return Promise.resolve('resolved payload')\n            },\n            { pending, fulfilled, settled },\n          ),\n        }),\n      })\n\n      expect(slice.caseReducers.thunkReducers.pending).toBe(pending)\n      expect(slice.caseReducers.thunkReducers.fulfilled).toBe(fulfilled)\n      expect(slice.caseReducers.thunkReducers.settled).toBe(settled)\n      // even though it is not defined above, this should at least be a no-op function to match the TypeScript typings\n      // and should be callable as a reducer even if it does nothing\n      expect(() =>\n        slice.caseReducers.thunkReducers.rejected(\n          [],\n          slice.actions.thunkReducers.rejected(\n            new Error('test'),\n            'fakeRequestId',\n          ),\n        ),\n      ).not.toThrow()\n    })\n\n    test('can define reducer with prepare statement using create.preparedReducer', async () => {\n      const slice = createSlice({\n        name: 'test',\n        initialState: [] as any[],\n        reducers: (create) => ({\n          prepared: create.preparedReducer(\n            (p: string, m: number, e: { message: string }) => ({\n              payload: p,\n              meta: m,\n              error: e,\n            }),\n            (state, action) => {\n              state.push(action)\n            },\n          ),\n        }),\n      })\n\n      expect(\n        slice.reducer(\n          [],\n          slice.actions.prepared('test', 1, { message: 'err' }),\n        ),\n      ).toMatchInlineSnapshot(`\n        [\n          {\n            \"error\": {\n              \"message\": \"err\",\n            },\n            \"meta\": 1,\n            \"payload\": \"test\",\n            \"type\": \"test/prepared\",\n          },\n        ]\n      `)\n    })\n\n    test('throws an error when invoked with a normal `prepare` object that has not gone through a `create.preparedReducer` call', async () => {\n      expect(() =>\n        createSlice({\n          name: 'test',\n          initialState: [] as any[],\n          reducers: (create) => ({\n            prepared: {\n              prepare: (p: string, m: number, e: { message: string }) => ({\n                payload: p,\n                meta: m,\n                error: e,\n              }),\n              reducer: (state, action) => {\n                state.push(action)\n              },\n            },\n          }),\n        }),\n      ).toThrowErrorMatchingInlineSnapshot(\n        `[Error: Please use the \\`create.preparedReducer\\` notation for prepared action creators with the \\`create\\` notation.]`,\n      )\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/getDefaultEnhancers.test-d.ts",
    "content": "import type { StoreEnhancer } from '@reduxjs/toolkit'\nimport { configureStore } from '@reduxjs/toolkit'\n\ndeclare const enhancer1: StoreEnhancer<\n  {\n    has1: true\n  },\n  { stateHas1: true }\n>\n\ndeclare const enhancer2: StoreEnhancer<\n  {\n    has2: true\n  },\n  { stateHas2: true }\n>\n\ndescribe('type tests', () => {\n  test('prepend single element', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      enhancers: (gDE) => gDE().prepend(enhancer1),\n    })\n\n    expectTypeOf(store.has1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()\n\n    expectTypeOf(store).not.toHaveProperty('has2')\n\n    expectTypeOf(store.getState()).not.toHaveProperty('stateHas2')\n  })\n\n  test('prepend multiple (rest)', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      enhancers: (gDE) => gDE().prepend(enhancer1, enhancer2),\n    })\n\n    expectTypeOf(store.has1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.has2).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()\n\n    expectTypeOf(store).not.toHaveProperty('has3')\n\n    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')\n  })\n\n  test('prepend multiple (array notation)', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      enhancers: (gDE) => gDE().prepend([enhancer1, enhancer2] as const),\n    })\n\n    expectTypeOf(store.has1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.has2).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()\n\n    expectTypeOf(store).not.toHaveProperty('has3')\n\n    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')\n  })\n\n  test('concat single element', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      enhancers: (gDE) => gDE().concat(enhancer1),\n    })\n\n    expectTypeOf(store.has1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()\n\n    expectTypeOf(store).not.toHaveProperty('has2')\n\n    expectTypeOf(store.getState()).not.toHaveProperty('stateHas2')\n  })\n\n  test('prepend multiple (rest)', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      enhancers: (gDE) => gDE().concat(enhancer1, enhancer2),\n    })\n\n    expectTypeOf(store.has1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.has2).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()\n\n    expectTypeOf(store).not.toHaveProperty('has3')\n\n    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')\n  })\n\n  test('concat multiple (array notation)', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      enhancers: (gDE) => gDE().concat([enhancer1, enhancer2] as const),\n    })\n\n    expectTypeOf(store.has1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.has2).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()\n\n    expectTypeOf(store).not.toHaveProperty('has3')\n\n    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')\n  })\n\n  test('concat and prepend', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      enhancers: (gDE) => gDE().concat(enhancer1).prepend(enhancer2),\n    })\n\n    expectTypeOf(store.has1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas1).toEqualTypeOf<true>()\n\n    expectTypeOf(store.has2).toEqualTypeOf<true>()\n\n    expectTypeOf(store.getState().stateHas2).toEqualTypeOf<true>()\n\n    expectTypeOf(store).not.toHaveProperty('has3')\n\n    expectTypeOf(store.getState()).not.toHaveProperty('stateHas3')\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/getDefaultMiddleware.test-d.ts",
    "content": "import { buildGetDefaultMiddleware } from '@internal/getDefaultMiddleware'\nimport type {\n  Action,\n  Dispatch,\n  Middleware,\n  ThunkAction,\n  ThunkDispatch,\n  ThunkMiddleware,\n  Tuple,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport { configureStore } from '@reduxjs/toolkit'\n\ndeclare const middleware1: Middleware<{\n  (_: string): number\n}>\n\ndeclare const middleware2: Middleware<{\n  (_: number): string\n}>\n\ntype ThunkReturn = Promise<'thunk'>\ndeclare const thunkCreator: () => () => ThunkReturn\n\nconst getDefaultMiddleware = buildGetDefaultMiddleware()\n\ndescribe('type tests', () => {\n  test('prepend single element', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      middleware: (gDM) => gDM().prepend(middleware1),\n    })\n\n    expectTypeOf(store.dispatch('foo')).toBeNumber()\n\n    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()\n\n    expectTypeOf(store.dispatch('foo')).not.toBeString()\n  })\n\n  test('prepend multiple (rest)', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      middleware: (gDM) => gDM().prepend(middleware1, middleware2),\n    })\n\n    expectTypeOf(store.dispatch('foo')).toBeNumber()\n\n    expectTypeOf(store.dispatch(5)).toBeString()\n\n    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()\n\n    expectTypeOf(store.dispatch('foo')).not.toBeString()\n  })\n\n  test('prepend multiple (array notation)', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      middleware: (gDM) => gDM().prepend([middleware1, middleware2] as const),\n    })\n\n    expectTypeOf(store.dispatch('foo')).toBeNumber()\n\n    expectTypeOf(store.dispatch(5)).toBeString()\n\n    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()\n\n    expectTypeOf(store.dispatch('foo')).not.toBeString()\n  })\n\n  test('concat single element', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      middleware: (gDM) => gDM().concat(middleware1),\n    })\n\n    expectTypeOf(store.dispatch('foo')).toBeNumber()\n\n    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()\n\n    expectTypeOf(store.dispatch('foo')).not.toBeString()\n  })\n\n  test('prepend multiple (rest)', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      middleware: (gDM) => gDM().concat(middleware1, middleware2),\n    })\n\n    expectTypeOf(store.dispatch('foo')).toBeNumber()\n\n    expectTypeOf(store.dispatch(5)).toBeString()\n\n    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()\n\n    expectTypeOf(store.dispatch('foo')).not.toBeString()\n  })\n\n  test('concat multiple (array notation)', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      middleware: (gDM) => gDM().concat([middleware1, middleware2] as const),\n    })\n\n    expectTypeOf(store.dispatch('foo')).toBeNumber()\n\n    expectTypeOf(store.dispatch(5)).toBeString()\n\n    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()\n\n    expectTypeOf(store.dispatch('foo')).not.toBeString()\n  })\n\n  test('concat and prepend', () => {\n    const store = configureStore({\n      reducer: () => 0,\n      middleware: (gDM) => gDM().concat(middleware1).prepend(middleware2),\n    })\n\n    expectTypeOf(store.dispatch('foo')).toBeNumber()\n\n    expectTypeOf(store.dispatch(5)).toBeString()\n\n    expectTypeOf(store.dispatch(thunkCreator())).toEqualTypeOf<ThunkReturn>()\n\n    expectTypeOf(store.dispatch('foo')).not.toBeString()\n  })\n\n  test('allows passing options to thunk', () => {\n    const extraArgument = 42 as const\n\n    const m2 = getDefaultMiddleware({\n      thunk: false,\n    })\n\n    expectTypeOf(m2).toExtend<Tuple<[]>>()\n\n    const dummyMiddleware: Middleware<\n      {\n        (action: Action<'actionListenerMiddleware/add'>): () => void\n      },\n      { counter: number }\n    > = (storeApi) => (next) => (action) => {\n      return next(action)\n    }\n\n    const dummyMiddleware2: Middleware<{}, { counter: number }> =\n      (storeApi) => (next) => (action) => {}\n\n    const testThunk: ThunkAction<\n      void,\n      { counter: number },\n      number,\n      UnknownAction\n    > = (dispatch, getState, extraArg) => {\n      expect(extraArg).toBe(extraArgument)\n    }\n\n    const reducer = () => ({ counter: 123 })\n\n    const store = configureStore({\n      reducer,\n      middleware: (gDM) => {\n        const middleware = gDM({\n          thunk: { extraArgument },\n          immutableCheck: false,\n          serializableCheck: false,\n          actionCreatorCheck: false,\n        })\n\n        const m3 = middleware.concat(dummyMiddleware, dummyMiddleware2)\n\n        expectTypeOf(m3).toExtend<\n          Tuple<\n            [\n              ThunkMiddleware<any, UnknownAction, 42>,\n              Middleware<\n                (action: Action<'actionListenerMiddleware/add'>) => () => void,\n                {\n                  counter: number\n                },\n                Dispatch<UnknownAction>\n              >,\n              Middleware<{}, any, Dispatch<UnknownAction>>,\n            ]\n          >\n        >()\n\n        return m3\n      },\n    })\n\n    expectTypeOf(store.dispatch).toExtend<\n      ThunkDispatch<any, 42, UnknownAction> & Dispatch<UnknownAction>\n    >()\n\n    store.dispatch(testThunk)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/getDefaultMiddleware.test.ts",
    "content": "import { buildGetDefaultMiddleware } from '@internal/getDefaultMiddleware'\nimport { Tuple } from '@internal/utils'\nimport type {\n  Action,\n  Middleware,\n  ThunkAction,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport { configureStore } from '@reduxjs/toolkit'\nimport { thunk } from 'redux-thunk'\nimport { vi } from 'vitest'\n\nconst getDefaultMiddleware = buildGetDefaultMiddleware()\n\ndescribe('getDefaultMiddleware', () => {\n  afterEach(() => {\n    vi.unstubAllEnvs()\n  })\n\n  describe('Production behavior', () => {\n    beforeEach(() => {\n      vi.resetModules()\n    })\n\n    it('returns an array with only redux-thunk in production', async () => {\n      vi.stubEnv('NODE_ENV', 'production')\n\n      const { thunk } = await import('redux-thunk')\n      const { buildGetDefaultMiddleware } =\n        await import('@internal/getDefaultMiddleware')\n\n      const middleware = buildGetDefaultMiddleware()()\n      expect(middleware).toContain(thunk)\n      expect(middleware.length).toBe(1)\n    })\n  })\n\n  it('returns an array with additional middleware in development', () => {\n    const middleware = getDefaultMiddleware()\n    expect(middleware).toContain(thunk)\n    expect(middleware.length).toBeGreaterThan(1)\n  })\n\n  const defaultMiddleware = getDefaultMiddleware()\n\n  it('removes the thunk middleware if disabled', () => {\n    const middleware = getDefaultMiddleware({ thunk: false })\n    // @ts-ignore\n    expect(middleware.includes(thunk)).toBe(false)\n    expect(middleware.length).toBe(defaultMiddleware.length - 1)\n  })\n\n  it('removes the immutable middleware if disabled', () => {\n    const middleware = getDefaultMiddleware({ immutableCheck: false })\n    expect(middleware.length).toBe(defaultMiddleware.length - 1)\n  })\n\n  it('removes the serializable middleware if disabled', () => {\n    const middleware = getDefaultMiddleware({ serializableCheck: false })\n    expect(middleware.length).toBe(defaultMiddleware.length - 1)\n  })\n\n  it('removes the action creator middleware if disabled', () => {\n    const middleware = getDefaultMiddleware({ actionCreatorCheck: false })\n    expect(middleware.length).toBe(defaultMiddleware.length - 1)\n  })\n\n  it('allows passing options to thunk', () => {\n    const extraArgument = 42 as const\n\n    const m2 = getDefaultMiddleware({\n      thunk: false,\n    })\n\n    const dummyMiddleware: Middleware<\n      {\n        (action: Action<'actionListenerMiddleware/add'>): () => void\n      },\n      { counter: number }\n    > = (storeApi) => (next) => (action) => {\n      return next(action)\n    }\n\n    const dummyMiddleware2: Middleware<{}, { counter: number }> =\n      (storeApi) => (next) => (action) => {}\n\n    const testThunk: ThunkAction<\n      void,\n      { counter: number },\n      number,\n      UnknownAction\n    > = (dispatch, getState, extraArg) => {\n      expect(extraArg).toBe(extraArgument)\n    }\n\n    const reducer = () => ({ counter: 123 })\n\n    const store = configureStore({\n      reducer,\n      middleware: (gDM) => {\n        const middleware = gDM({\n          thunk: { extraArgument },\n          immutableCheck: false,\n          serializableCheck: false,\n          actionCreatorCheck: false,\n        })\n\n        const m3 = middleware.concat(dummyMiddleware, dummyMiddleware2)\n\n        return m3\n      },\n    })\n\n    store.dispatch(testThunk)\n  })\n\n  it('allows passing options to immutableCheck', () => {\n    let immutableCheckWasCalled = false\n\n    const middleware = () =>\n      getDefaultMiddleware({\n        thunk: false,\n        immutableCheck: {\n          isImmutable: () => {\n            immutableCheckWasCalled = true\n            return true\n          },\n        },\n        serializableCheck: false,\n        actionCreatorCheck: false,\n      })\n\n    const reducer = () => ({})\n\n    const store = configureStore({\n      reducer,\n      middleware,\n    })\n\n    expect(immutableCheckWasCalled).toBe(true)\n  })\n\n  it('allows passing options to serializableCheck', () => {\n    let serializableCheckWasCalled = false\n\n    const middleware = () =>\n      getDefaultMiddleware({\n        thunk: false,\n        immutableCheck: false,\n        serializableCheck: {\n          isSerializable: () => {\n            serializableCheckWasCalled = true\n            return true\n          },\n        },\n        actionCreatorCheck: false,\n      })\n\n    const reducer = () => ({})\n\n    const store = configureStore({\n      reducer,\n      middleware,\n    })\n\n    store.dispatch({ type: 'TEST_ACTION' })\n\n    expect(serializableCheckWasCalled).toBe(true)\n  })\n})\n\nit('allows passing options to actionCreatorCheck', () => {\n  let actionCreatorCheckWasCalled = false\n\n  const middleware = () =>\n    getDefaultMiddleware({\n      thunk: false,\n      immutableCheck: false,\n      serializableCheck: false,\n      actionCreatorCheck: {\n        isActionCreator: (action: unknown): action is Function => {\n          actionCreatorCheckWasCalled = true\n          return false\n        },\n      },\n    })\n\n  const reducer = () => ({})\n\n  const store = configureStore({\n    reducer,\n    middleware,\n  })\n\n  store.dispatch({ type: 'TEST_ACTION' })\n\n  expect(actionCreatorCheckWasCalled).toBe(true)\n})\n\ndescribe('Tuple functionality', () => {\n  const middleware1: Middleware = () => (next) => (action) => next(action)\n  const middleware2: Middleware = () => (next) => (action) => next(action)\n  const defaultMiddleware = getDefaultMiddleware()\n  const originalDefaultMiddleware = [...defaultMiddleware]\n\n  test('allows to prepend a single value', () => {\n    const prepended = defaultMiddleware.prepend(middleware1)\n\n    // value is prepended\n    expect(prepended).toEqual([middleware1, ...defaultMiddleware])\n    // returned value is of correct type\n    expect(prepended).toBeInstanceOf(Tuple)\n    // prepended is a new array\n    expect(prepended).not.toEqual(defaultMiddleware)\n    // defaultMiddleware is not modified\n    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)\n  })\n\n  test('allows to prepend multiple values (array as first argument)', () => {\n    const prepended = defaultMiddleware.prepend([middleware1, middleware2])\n\n    // value is prepended\n    expect(prepended).toEqual([middleware1, middleware2, ...defaultMiddleware])\n    // returned value is of correct type\n    expect(prepended).toBeInstanceOf(Tuple)\n    // prepended is a new array\n    expect(prepended).not.toEqual(defaultMiddleware)\n    // defaultMiddleware is not modified\n    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)\n  })\n\n  test('allows to prepend multiple values (rest)', () => {\n    const prepended = defaultMiddleware.prepend(middleware1, middleware2)\n\n    // value is prepended\n    expect(prepended).toEqual([middleware1, middleware2, ...defaultMiddleware])\n    // returned value is of correct type\n    expect(prepended).toBeInstanceOf(Tuple)\n    // prepended is a new array\n    expect(prepended).not.toEqual(defaultMiddleware)\n    // defaultMiddleware is not modified\n    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)\n  })\n\n  test('allows to concat a single value', () => {\n    const concatenated = defaultMiddleware.concat(middleware1)\n\n    // value is concatenated\n    expect(concatenated).toEqual([...defaultMiddleware, middleware1])\n    // returned value is of correct type\n    expect(concatenated).toBeInstanceOf(Tuple)\n    // concatenated is a new array\n    expect(concatenated).not.toEqual(defaultMiddleware)\n    // defaultMiddleware is not modified\n    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)\n  })\n\n  test('allows to concat multiple values (array as first argument)', () => {\n    const concatenated = defaultMiddleware.concat([middleware1, middleware2])\n\n    // value is concatenated\n    expect(concatenated).toEqual([\n      ...defaultMiddleware,\n      middleware1,\n      middleware2,\n    ])\n    // returned value is of correct type\n    expect(concatenated).toBeInstanceOf(Tuple)\n    // concatenated is a new array\n    expect(concatenated).not.toEqual(defaultMiddleware)\n    // defaultMiddleware is not modified\n    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)\n  })\n\n  test('allows to concat multiple values (rest)', () => {\n    const concatenated = defaultMiddleware.concat(middleware1, middleware2)\n\n    // value is concatenated\n    expect(concatenated).toEqual([\n      ...defaultMiddleware,\n      middleware1,\n      middleware2,\n    ])\n    // returned value is of correct type\n    expect(concatenated).toBeInstanceOf(Tuple)\n    // concatenated is a new array\n    expect(concatenated).not.toEqual(defaultMiddleware)\n    // defaultMiddleware is not modified\n    expect(defaultMiddleware).toEqual(originalDefaultMiddleware)\n  })\n\n  test('allows to concat and then prepend', () => {\n    const concatenated = defaultMiddleware\n      .concat(middleware1)\n      .prepend(middleware2)\n\n    expect(concatenated).toEqual([\n      middleware2,\n      ...defaultMiddleware,\n      middleware1,\n    ])\n  })\n\n  test('allows to prepend and then concat', () => {\n    const concatenated = defaultMiddleware\n      .prepend(middleware2)\n      .concat(middleware1)\n\n    expect(concatenated).toEqual([\n      middleware2,\n      ...defaultMiddleware,\n      middleware1,\n    ])\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/immutableStateInvariantMiddleware.test.ts",
    "content": "import { trackForMutations } from '@internal/immutableStateInvariantMiddleware'\nimport { noop } from '@internal/listenerMiddleware/utils'\nimport type {\n  ImmutableStateInvariantMiddlewareOptions,\n  Middleware,\n  MiddlewareAPI,\n  Store,\n} from '@reduxjs/toolkit'\nimport {\n  createImmutableStateInvariantMiddleware,\n  isImmutableDefault,\n} from '@reduxjs/toolkit'\n\ntype MWNext = Parameters<ReturnType<Middleware>>[0]\n\ndescribe('createImmutableStateInvariantMiddleware', () => {\n  let state: { foo: { bar: number[]; baz: string } }\n  const getState: Store['getState'] = () => state\n\n  function middleware(options: ImmutableStateInvariantMiddlewareOptions = {}) {\n    return createImmutableStateInvariantMiddleware(options)({\n      getState,\n    } as MiddlewareAPI)\n  }\n\n  beforeEach(() => {\n    state = { foo: { bar: [2, 3, 4], baz: 'baz' } }\n  })\n\n  it('sends the action through the middleware chain', () => {\n    const next: MWNext = vi.fn()\n    const dispatch = middleware()(next)\n    dispatch({ type: 'SOME_ACTION' })\n\n    expect(next).toHaveBeenCalledWith({\n      type: 'SOME_ACTION',\n    })\n  })\n\n  it('throws if mutating inside the dispatch', () => {\n    const next: MWNext = (action) => {\n      state.foo.bar.push(5)\n      return action\n    }\n\n    const dispatch = middleware()(next)\n\n    expect(() => {\n      dispatch({ type: 'SOME_ACTION' })\n    }).toThrow(new RegExp('foo\\\\.bar\\\\.3'))\n  })\n\n  it('throws if mutating between dispatches', () => {\n    const next: MWNext = (action) => action\n\n    const dispatch = middleware()(next)\n\n    dispatch({ type: 'SOME_ACTION' })\n    state.foo.bar.push(5)\n    expect(() => {\n      dispatch({ type: 'SOME_OTHER_ACTION' })\n    }).toThrow(new RegExp('foo\\\\.bar\\\\.3'))\n  })\n\n  it('does not throw if not mutating inside the dispatch', () => {\n    const next: MWNext = (action) => {\n      state = { ...state, foo: { ...state.foo, baz: 'changed!' } }\n      return action\n    }\n\n    const dispatch = middleware()(next)\n\n    expect(() => {\n      dispatch({ type: 'SOME_ACTION' })\n    }).not.toThrow()\n  })\n\n  it('does not throw if not mutating between dispatches', () => {\n    const next: MWNext = (action) => action\n\n    const dispatch = middleware()(next)\n\n    dispatch({ type: 'SOME_ACTION' })\n    state = { ...state, foo: { ...state.foo, baz: 'changed!' } }\n    expect(() => {\n      dispatch({ type: 'SOME_OTHER_ACTION' })\n    }).not.toThrow()\n  })\n\n  it('works correctly with circular references', () => {\n    const next: MWNext = (action) => action\n\n    const dispatch = middleware()(next)\n\n    let x: any = {}\n    let y: any = {}\n    x.y = y\n    y.x = x\n\n    expect(() => {\n      dispatch({ type: 'SOME_ACTION', x })\n    }).not.toThrow()\n  })\n\n  it('respects \"isImmutable\" option', function () {\n    const isImmutable = (value: any) => true\n    const next: MWNext = (action) => {\n      state.foo.bar.push(5)\n      return action\n    }\n\n    const dispatch = middleware({ isImmutable })(next)\n\n    expect(() => {\n      dispatch({ type: 'SOME_ACTION' })\n    }).not.toThrow()\n  })\n\n  it('respects \"ignoredPaths\" option', () => {\n    const next: MWNext = (action) => {\n      state.foo.bar.push(5)\n      return action\n    }\n\n    const dispatch1 = middleware({ ignoredPaths: ['foo.bar'] })(next)\n\n    expect(() => {\n      dispatch1({ type: 'SOME_ACTION' })\n    }).not.toThrow()\n\n    const dispatch2 = middleware({ ignoredPaths: [/^foo/] })(next)\n\n    expect(() => {\n      dispatch2({ type: 'SOME_ACTION' })\n    }).not.toThrow()\n  })\n\n  it('Should print a warning if execution takes too long', () => {\n    state.foo.bar = new Array(10000).fill({ value: 'more' })\n\n    const next: MWNext = (action) => action\n\n    const dispatch = middleware({ warnAfter: 4 })(next)\n\n    const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)\n\n    try {\n      dispatch({ type: 'SOME_ACTION' })\n\n      expect(consoleWarnSpy).toHaveBeenCalledOnce()\n\n      expect(consoleWarnSpy).toHaveBeenLastCalledWith(\n        expect.stringMatching(\n          /^ImmutableStateInvariantMiddleware took \\d*ms, which is more than the warning threshold of 4ms./,\n        ),\n      )\n    } finally {\n      consoleWarnSpy.mockRestore()\n    }\n  })\n\n  it('Should not print a warning if \"next\" takes too long', () => {\n    const next: MWNext = (action) => {\n      const started = Date.now()\n      while (Date.now() - started < 8) {}\n      return action\n    }\n\n    const dispatch = middleware({ warnAfter: 4 })(next)\n\n    const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)\n\n    try {\n      dispatch({ type: 'SOME_ACTION' })\n\n      expect(consoleWarnSpy).not.toHaveBeenCalled()\n    } finally {\n      consoleWarnSpy.mockRestore()\n    }\n  })\n})\n\ndescribe('trackForMutations', () => {\n  function testCasesForMutation(spec: any) {\n    it('returns true and the mutated path', () => {\n      const state = spec.getState()\n      const options = spec.middlewareOptions || {}\n      const { isImmutable = isImmutableDefault, ignoredPaths } = options\n      const tracker = trackForMutations(isImmutable, ignoredPaths, state)\n      const newState = spec.fn(state)\n\n      expect(tracker.detectMutations()).toEqual({\n        wasMutated: true,\n        path: spec.path.join('.'),\n      })\n    })\n  }\n\n  function testCasesForNonMutation(spec: any) {\n    it('returns false', () => {\n      const state = spec.getState()\n      const options = spec.middlewareOptions || {}\n      const { isImmutable = isImmutableDefault, ignoredPaths } = options\n      const tracker = trackForMutations(isImmutable, ignoredPaths, state)\n      const newState = spec.fn(state)\n\n      expect(tracker.detectMutations()).toEqual({ wasMutated: false })\n    })\n  }\n\n  interface TestConfig {\n    getState: Store['getState']\n    fn: (s: any) => typeof s | object\n    middlewareOptions?: ImmutableStateInvariantMiddlewareOptions\n    path?: string[]\n  }\n\n  const mutations: Record<string, TestConfig> = {\n    'adding to nested array': {\n      getState: () => ({\n        foo: {\n          bar: [2, 3, 4],\n          baz: 'baz',\n        },\n        stuff: [],\n      }),\n      fn: (s) => {\n        s.foo.bar.push(5)\n        return s\n      },\n      path: ['foo', 'bar', '3'],\n    },\n    'adding to nested array and setting new root object': {\n      getState: () => ({\n        foo: {\n          bar: [2, 3, 4],\n          baz: 'baz',\n        },\n        stuff: [],\n      }),\n      fn: (s) => {\n        s.foo.bar.push(5)\n        return { ...s }\n      },\n      path: ['foo', 'bar', '3'],\n    },\n    'changing nested string': {\n      getState: () => ({\n        foo: {\n          bar: [2, 3, 4],\n          baz: 'baz',\n        },\n        stuff: [],\n      }),\n      fn: (s) => {\n        s.foo.baz = 'changed!'\n        return s\n      },\n      path: ['foo', 'baz'],\n    },\n    'removing nested state': {\n      getState: () => ({\n        foo: {\n          bar: [2, 3, 4],\n          baz: 'baz',\n        },\n        stuff: [],\n      }),\n      fn: (s) => {\n        delete s.foo\n        return s\n      },\n      path: ['foo'],\n    },\n    'adding to array': {\n      getState: () => ({\n        foo: {\n          bar: [2, 3, 4],\n          baz: 'baz',\n        },\n        stuff: [],\n      }),\n      fn: (s) => {\n        s.stuff.push(1)\n        return s\n      },\n      path: ['stuff', '0'],\n    },\n    'adding object to array': {\n      getState: () => ({\n        stuff: [],\n      }),\n      fn: (s) => {\n        s.stuff.push({ foo: 1, bar: 2 })\n        return s\n      },\n      path: ['stuff', '0'],\n    },\n    'mutating previous state and returning new state': {\n      getState: () => ({ counter: 0 }),\n      fn: (s) => {\n        s.mutation = true\n        return { ...s, counter: s.counter + 1 }\n      },\n      path: ['mutation'],\n    },\n    'mutating previous state with non immutable type and returning new state': {\n      getState: () => ({ counter: 0 }),\n      fn: (s) => {\n        s.mutation = [1, 2, 3]\n        return { ...s, counter: s.counter + 1 }\n      },\n      path: ['mutation'],\n    },\n    'mutating previous state with non immutable type and returning new state without that property':\n      {\n        getState: () => ({ counter: 0 }),\n        fn: (s) => {\n          s.mutation = [1, 2, 3]\n          return { counter: s.counter + 1 }\n        },\n        path: ['mutation'],\n      },\n    'mutating previous state with non immutable type and returning new simple state':\n      {\n        getState: () => ({ counter: 0 }),\n        fn: (s) => {\n          s.mutation = [1, 2, 3]\n          return 1\n        },\n        path: ['mutation'],\n      },\n    'mutating previous state by deleting property and returning new state without that property':\n      {\n        getState: () => ({ counter: 0, toBeDeleted: true }),\n        fn: (s) => {\n          delete s.toBeDeleted\n          return { counter: s.counter + 1 }\n        },\n        path: ['toBeDeleted'],\n      },\n    'mutating previous state by deleting nested property': {\n      getState: () => ({ nested: { counter: 0, toBeDeleted: true }, foo: 1 }),\n      fn: (s) => {\n        delete s.nested.toBeDeleted\n        return { nested: { counter: s.counter + 1 } }\n      },\n      path: ['nested', 'toBeDeleted'],\n    },\n    'update reference': {\n      getState: () => ({ foo: {} }),\n      fn: (s) => {\n        s.foo = {}\n        return s\n      },\n      path: ['foo'],\n    },\n    'cannot ignore root state': {\n      getState: () => ({ foo: {} }),\n      fn: (s) => {\n        s.foo = {}\n        return s\n      },\n      middlewareOptions: {\n        ignoredPaths: [''],\n      },\n      path: ['foo'],\n    },\n    'catching state mutation in non-ignored branch': {\n      getState: () => ({\n        foo: {\n          bar: [1, 2],\n        },\n        boo: {\n          yah: [1, 2],\n        },\n      }),\n      fn: (s) => {\n        s.foo.bar.push(3)\n        s.boo.yah.push(3)\n        return s\n      },\n      middlewareOptions: {\n        ignoredPaths: ['foo'],\n      },\n      path: ['boo', 'yah', '2'],\n    },\n  }\n\n  Object.keys(mutations).forEach((mutationDesc) => {\n    describe(mutationDesc, () => {\n      testCasesForMutation(mutations[mutationDesc])\n    })\n  })\n\n  const nonMutations: Record<string, TestConfig> = {\n    'not doing anything': {\n      getState: () => ({ a: 1, b: 2 }),\n      fn: (s) => s,\n    },\n    'from undefined to something': {\n      getState: () => undefined,\n      fn: (s) => ({ foo: 'bar' }),\n    },\n    'returning same state': {\n      getState: () => ({\n        foo: {\n          bar: [2, 3, 4],\n          baz: 'baz',\n        },\n        stuff: [],\n      }),\n      fn: (s) => s,\n    },\n    'returning a new state object with nested new string': {\n      getState: () => ({\n        foo: {\n          bar: [2, 3, 4],\n          baz: 'baz',\n        },\n        stuff: [],\n      }),\n      fn: (s) => {\n        return { ...s, foo: { ...s.foo, baz: 'changed!' } }\n      },\n    },\n    'returning a new state object with nested new array': {\n      getState: () => ({\n        foo: {\n          bar: [2, 3, 4],\n          baz: 'baz',\n        },\n        stuff: [],\n      }),\n      fn: (s) => {\n        return { ...s, foo: { ...s.foo, bar: [...s.foo.bar, 5] } }\n      },\n    },\n    'removing nested state': {\n      getState: () => ({\n        foo: {\n          bar: [2, 3, 4],\n          baz: 'baz',\n        },\n        stuff: [],\n      }),\n      fn: (s) => {\n        return { ...s, foo: {} }\n      },\n    },\n    'having a NaN in the state': {\n      getState: () => ({ a: NaN, b: Number.NaN }),\n      fn: (s) => s,\n    },\n    'ignoring branches from mutation detection': {\n      getState: () => ({\n        foo: {\n          bar: 'bar',\n        },\n      }),\n      fn: (s) => {\n        s.foo.bar = 'baz'\n        return s\n      },\n      middlewareOptions: {\n        ignoredPaths: ['foo'],\n      },\n    },\n    'ignoring nested branches from mutation detection': {\n      getState: () => ({\n        foo: {\n          bar: [1, 2],\n          boo: {\n            yah: [1, 2],\n          },\n        },\n      }),\n      fn: (s) => {\n        s.foo.bar.push(3)\n        s.foo.boo.yah.push(3)\n        return s\n      },\n      middlewareOptions: {\n        ignoredPaths: ['foo.bar', 'foo.boo.yah'],\n      },\n    },\n    'ignoring nested array indices from mutation detection': {\n      getState: () => ({\n        stuff: [{ a: 1 }, { a: 2 }],\n      }),\n      fn: (s) => {\n        s.stuff[1].a = 3\n        return s\n      },\n      middlewareOptions: {\n        ignoredPaths: ['stuff.1'],\n      },\n    },\n  }\n\n  Object.keys(nonMutations).forEach((nonMutationDesc) => {\n    describe(nonMutationDesc, () => {\n      testCasesForNonMutation(nonMutations[nonMutationDesc])\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/mapBuilders.test-d.ts",
    "content": "import { createAsyncThunk } from '@internal/createAsyncThunk'\nimport { executeReducerBuilderCallback } from '@internal/mapBuilders'\nimport type { SerializedError, UnknownAction } from '@reduxjs/toolkit'\nimport { createAction } from '@reduxjs/toolkit'\n\ndescribe('type tests', () => {\n  test('builder callback for actionMap', () => {\n    const increment = createAction<number, 'increment'>('increment')\n\n    const decrement = createAction<number, 'decrement'>('decrement')\n\n    executeReducerBuilderCallback<number>((builder) => {\n      builder.addCase(increment, (state, action) => {\n        expectTypeOf(state).toBeNumber()\n\n        expectTypeOf(action).toEqualTypeOf<{\n          type: 'increment'\n          payload: number\n        }>()\n\n        expectTypeOf(state).not.toBeString()\n\n        expectTypeOf(action).not.toExtend<{\n          type: 'increment'\n          payload: string\n        }>()\n\n        expectTypeOf(action).not.toExtend<{\n          type: 'decrement'\n          payload: number\n        }>()\n      })\n\n      builder.addCase('increment', (state, action) => {\n        expectTypeOf(state).toBeNumber()\n\n        expectTypeOf(action).toEqualTypeOf<{ type: 'increment' }>()\n\n        expectTypeOf(state).not.toBeString()\n\n        expectTypeOf(action).not.toExtend<{ type: 'decrement' }>()\n\n        // this cannot be inferred and has to be manually specified\n        expectTypeOf(action).not.toExtend<{\n          type: 'increment'\n          payload: number\n        }>()\n      })\n\n      builder.addCase(\n        increment,\n        (state, action: ReturnType<typeof increment>) => state,\n      )\n\n      // @ts-expect-error\n      builder.addCase(\n        increment,\n        (state, action: ReturnType<typeof decrement>) => state,\n      )\n\n      builder.addCase(\n        'increment',\n        (state, action: ReturnType<typeof increment>) => state,\n      )\n\n      // @ts-expect-error\n      builder.addCase(\n        'decrement',\n        (state, action: ReturnType<typeof increment>) => state,\n      )\n\n      // action type is inferred\n      builder.addMatcher(increment.match, (state, action) => {\n        expectTypeOf(action).toEqualTypeOf<ReturnType<typeof increment>>()\n      })\n\n      test('action type is inferred when type predicate lacks `type` property', () => {\n        type PredicateWithoutTypeProperty = {\n          payload: number\n        }\n\n        builder.addMatcher(\n          (action): action is PredicateWithoutTypeProperty => true,\n          (state, action) => {\n            expectTypeOf(\n              action,\n            ).toMatchObjectType<PredicateWithoutTypeProperty>()\n\n            expectTypeOf(action).toExtend<UnknownAction>()\n          },\n        )\n      })\n\n      // action type defaults to UnknownAction if no type predicate matcher is passed\n      builder.addMatcher(\n        () => true,\n        (state, action) => {\n          expectTypeOf(action).toExtend<UnknownAction>()\n        },\n      )\n\n      // with a boolean checker, action can also be typed by type argument\n      builder.addMatcher<{ foo: boolean }>(\n        () => true,\n        (state, action) => {\n          expectTypeOf(action).toMatchObjectType<{ foo: boolean }>()\n\n          expectTypeOf(action).toExtend<UnknownAction>()\n        },\n      )\n\n      // addCase().addMatcher() is possible, action type inferred correctly\n      builder\n        .addCase(\n          'increment',\n          (state, action: ReturnType<typeof increment>) => state,\n        )\n        .addMatcher(decrement.match, (state, action) => {\n          expectTypeOf(action).toEqualTypeOf<ReturnType<typeof decrement>>()\n        })\n\n      // addCase().addDefaultCase() is possible, action type is UnknownAction\n      builder\n        .addCase(\n          'increment',\n          (state, action: ReturnType<typeof increment>) => state,\n        )\n        .addDefaultCase((state, action) => {\n          expectTypeOf(action).toExtend<UnknownAction>()\n        })\n\n      test('addAsyncThunk() should prevent further calls to addCase() ', () => {\n        const asyncThunk = createAsyncThunk('test', () => {})\n        const b = builder.addAsyncThunk(asyncThunk, {\n          pending: () => {},\n          rejected: () => {},\n          fulfilled: () => {},\n          settled: () => {},\n        })\n\n        expectTypeOf(b).not.toHaveProperty('addCase')\n\n        expectTypeOf(b.addAsyncThunk).toBeFunction()\n\n        expectTypeOf(b.addMatcher).toBeCallableWith(increment.match, () => {})\n\n        expectTypeOf(b.addDefaultCase).toBeCallableWith(() => {})\n      })\n\n      test('addMatcher() should prevent further calls to addCase() and addAsyncThunk()', () => {\n        const b = builder.addMatcher(increment.match, () => {})\n\n        expectTypeOf(b).not.toHaveProperty('addCase')\n        expectTypeOf(b).not.toHaveProperty('addAsyncThunk')\n\n        expectTypeOf(b.addMatcher).toBeCallableWith(increment.match, () => {})\n\n        expectTypeOf(b.addDefaultCase).toBeCallableWith(() => {})\n      })\n\n      test('addDefaultCase() should prevent further calls to addCase(), addAsyncThunk(), addMatcher() and addDefaultCase', () => {\n        const b = builder.addDefaultCase(() => {})\n\n        expectTypeOf(b).not.toHaveProperty('addCase')\n\n        expectTypeOf(b).not.toHaveProperty('addAsyncThunk')\n\n        expectTypeOf(b).not.toHaveProperty('addMatcher')\n\n        expectTypeOf(b).not.toHaveProperty('addDefaultCase')\n      })\n\n      describe('`createAsyncThunk` actions work with `mapBuilder`', () => {\n        test('case 1: normal `createAsyncThunk`', () => {\n          const thunk = createAsyncThunk('test', () => {\n            return 'ret' as const\n          })\n          builder.addCase(thunk.pending, (_, action) => {\n            expectTypeOf(action).toMatchObjectType<{\n              payload: undefined\n              meta: {\n                arg: void\n                requestId: string\n                requestStatus: 'pending'\n              }\n            }>()\n          })\n\n          builder.addCase(thunk.rejected, (_, action) => {\n            expectTypeOf(action).toExtend<{\n              payload: unknown\n              error: SerializedError\n              meta: {\n                arg: void\n                requestId: string\n                requestStatus: 'rejected'\n                aborted: boolean\n                condition: boolean\n                rejectedWithValue: boolean\n              }\n            }>()\n          })\n          builder.addCase(thunk.fulfilled, (_, action) => {\n            expectTypeOf(action).toMatchObjectType<{\n              payload: 'ret'\n              meta: {\n                arg: void\n                requestId: string\n                requestStatus: 'fulfilled'\n              }\n            }>()\n          })\n\n          builder.addAsyncThunk(thunk, {\n            pending(_, action) {\n              expectTypeOf(action).toMatchObjectType<{\n                payload: undefined\n                meta: {\n                  arg: void\n                  requestId: string\n                  requestStatus: 'pending'\n                }\n              }>()\n            },\n            rejected(_, action) {\n              expectTypeOf(action).toExtend<{\n                payload: unknown\n                error: SerializedError\n                meta: {\n                  arg: void\n                  requestId: string\n                  requestStatus: 'rejected'\n                  aborted: boolean\n                  condition: boolean\n                  rejectedWithValue: boolean\n                }\n              }>()\n            },\n            fulfilled(_, action) {\n              expectTypeOf(action).toMatchObjectType<{\n                payload: 'ret'\n                meta: {\n                  arg: void\n                  requestId: string\n                  requestStatus: 'fulfilled'\n                }\n              }>()\n            },\n            settled(_, action) {\n              expectTypeOf(action).toExtend<\n                | {\n                    payload: 'ret'\n                    meta: {\n                      arg: void\n                      requestId: string\n                      requestStatus: 'fulfilled'\n                    }\n                  }\n                | {\n                    payload: unknown\n                    error: SerializedError\n                    meta: {\n                      arg: void\n                      requestId: string\n                      requestStatus: 'rejected'\n                      aborted: boolean\n                      condition: boolean\n                      rejectedWithValue: boolean\n                    }\n                  }\n              >()\n            },\n          })\n        })\n\n        test('case 2: `createAsyncThunk` with `meta`', () => {\n          const thunk = createAsyncThunk<\n            'ret',\n            void,\n            {\n              pendingMeta: { startedTimeStamp: number }\n              fulfilledMeta: {\n                fulfilledTimeStamp: number\n                baseQueryMeta: 'meta!'\n              }\n              rejectedMeta: {\n                baseQueryMeta: 'meta!'\n              }\n            }\n          >(\n            'test',\n            (_, api) => {\n              return api.fulfillWithValue('ret' as const, {\n                fulfilledTimeStamp: 5,\n                baseQueryMeta: 'meta!',\n              })\n            },\n            {\n              getPendingMeta() {\n                return { startedTimeStamp: 0 }\n              },\n            },\n          )\n\n          builder.addCase(thunk.pending, (_, action) => {\n            expectTypeOf(action).toMatchObjectType<{\n              payload: undefined\n              meta: {\n                arg: void\n                requestId: string\n                requestStatus: 'pending'\n                startedTimeStamp: number\n              }\n            }>()\n          })\n\n          builder.addCase(thunk.rejected, (_, action) => {\n            expectTypeOf(action).toExtend<{\n              payload: unknown\n              error: SerializedError\n              meta: {\n                arg: void\n                requestId: string\n                requestStatus: 'rejected'\n                aborted: boolean\n                condition: boolean\n                rejectedWithValue: boolean\n                baseQueryMeta?: 'meta!'\n              }\n            }>()\n\n            if (action.meta.rejectedWithValue) {\n              expectTypeOf(action.meta.baseQueryMeta).toEqualTypeOf<'meta!'>()\n            }\n          })\n          builder.addCase(thunk.fulfilled, (_, action) => {\n            expectTypeOf(action).toMatchObjectType<{\n              payload: 'ret'\n              meta: {\n                arg: void\n                requestId: string\n                requestStatus: 'fulfilled'\n                baseQueryMeta: 'meta!'\n              }\n            }>()\n          })\n\n          builder.addAsyncThunk(thunk, {\n            pending(_, action) {\n              expectTypeOf(action).toMatchObjectType<{\n                payload: undefined\n                meta: {\n                  arg: void\n                  requestId: string\n                  requestStatus: 'pending'\n                  startedTimeStamp: number\n                }\n              }>()\n            },\n            rejected(_, action) {\n              expectTypeOf(action).toExtend<{\n                payload: unknown\n                error: SerializedError\n                meta: {\n                  arg: void\n                  requestId: string\n                  requestStatus: 'rejected'\n                  aborted: boolean\n                  condition: boolean\n                  rejectedWithValue: boolean\n                  baseQueryMeta?: 'meta!'\n                }\n              }>()\n            },\n            fulfilled(_, action) {\n              expectTypeOf(action).toMatchObjectType<{\n                payload: 'ret'\n                meta: {\n                  arg: void\n                  requestId: string\n                  requestStatus: 'fulfilled'\n                  baseQueryMeta: 'meta!'\n                }\n              }>()\n            },\n            settled(_, action) {\n              expectTypeOf(action).toExtend<\n                | {\n                    payload: 'ret'\n                    meta: {\n                      arg: void\n                      requestId: string\n                      requestStatus: 'fulfilled'\n                      baseQueryMeta: 'meta!'\n                    }\n                  }\n                | {\n                    payload: unknown\n                    error: SerializedError\n                    meta: {\n                      arg: void\n                      requestId: string\n                      requestStatus: 'rejected'\n                      aborted: boolean\n                      condition: boolean\n                      rejectedWithValue: boolean\n                      baseQueryMeta?: 'meta!'\n                    }\n                  }\n              >()\n            },\n          })\n        })\n      })\n    })\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/matchers.test-d.ts",
    "content": "import type { SerializedError, UnknownAction } from '@reduxjs/toolkit'\nimport {\n  createAction,\n  createAsyncThunk,\n  isAllOf,\n  isAnyOf,\n  isAsyncThunkAction,\n  isFulfilled,\n  isPending,\n  isRejected,\n  isRejectedWithValue,\n} from '@reduxjs/toolkit'\n\nconst action: UnknownAction = { type: 'foo' }\n\ndescribe('type tests', () => {\n  describe('isAnyOf', () => {\n    test('isAnyOf correctly narrows types when used with action creators', () => {\n      const actionA = createAction('a', () => {\n        return {\n          payload: {\n            prop1: 1,\n            prop3: 2,\n          },\n        }\n      })\n\n      const actionB = createAction('b', () => {\n        return {\n          payload: {\n            prop1: 1,\n            prop2: 2,\n          },\n        }\n      })\n\n      if (isAnyOf(actionA, actionB)(action)) {\n        expectTypeOf(action.payload).toHaveProperty('prop1')\n\n        expectTypeOf(action.payload).not.toHaveProperty('prop2')\n\n        expectTypeOf(action.payload).not.toHaveProperty('prop3')\n      }\n    })\n\n    test('isAnyOf correctly narrows types when used with async thunks', () => {\n      const asyncThunk1 = createAsyncThunk<{ prop1: number; prop3: number }>(\n        'asyncThunk1',\n\n        async () => {\n          return {\n            prop1: 1,\n            prop3: 3,\n          }\n        },\n      )\n\n      const asyncThunk2 = createAsyncThunk<{ prop1: number; prop2: number }>(\n        'asyncThunk2',\n\n        async () => {\n          return {\n            prop1: 1,\n            prop2: 2,\n          }\n        },\n      )\n\n      if (isAnyOf(asyncThunk1.fulfilled, asyncThunk2.fulfilled)(action)) {\n        expectTypeOf(action.payload).toHaveProperty('prop1')\n\n        expectTypeOf(action.payload).not.toHaveProperty('prop2')\n\n        expectTypeOf(action.payload).not.toHaveProperty('prop3')\n      }\n    })\n\n    test('isAnyOf correctly narrows types when used with type guards', () => {\n      interface ActionA {\n        type: 'a'\n        payload: {\n          prop1: 1\n          prop3: 2\n        }\n      }\n\n      interface ActionB {\n        type: 'b'\n        payload: {\n          prop1: 1\n          prop2: 2\n        }\n      }\n\n      const guardA = (v: any): v is ActionA => {\n        return v.type === 'a'\n      }\n\n      const guardB = (v: any): v is ActionB => {\n        return v.type === 'b'\n      }\n\n      if (isAnyOf(guardA, guardB)(action)) {\n        expectTypeOf(action.payload).toHaveProperty('prop1')\n\n        expectTypeOf(action.payload).not.toHaveProperty('prop2')\n\n        expectTypeOf(action.payload).not.toHaveProperty('prop3')\n      }\n    })\n  })\n\n  describe('isAllOf', () => {\n    interface SpecialAction {\n      payload: {\n        special: boolean\n      }\n    }\n\n    const isSpecialAction = (v: any): v is SpecialAction => {\n      return v.meta.isSpecial\n    }\n\n    test('isAllOf correctly narrows types when used with action creators and type guards', () => {\n      const actionA = createAction('a', () => {\n        return {\n          payload: {\n            prop1: 1,\n            prop3: 2,\n          },\n        }\n      })\n\n      if (isAllOf(actionA, isSpecialAction)(action)) {\n        expectTypeOf(action.payload).toHaveProperty('prop1')\n\n        expectTypeOf(action.payload).not.toHaveProperty('prop2')\n\n        expectTypeOf(action.payload).toHaveProperty('prop3')\n\n        expectTypeOf(action.payload).toHaveProperty('special')\n      }\n    })\n\n    test('isAllOf correctly narrows types when used with async thunks and type guards', () => {\n      const asyncThunk1 = createAsyncThunk<{ prop1: number; prop3: number }>(\n        'asyncThunk1',\n\n        async () => {\n          return {\n            prop1: 1,\n            prop3: 3,\n          }\n        },\n      )\n\n      if (isAllOf(asyncThunk1.fulfilled, isSpecialAction)(action)) {\n        expectTypeOf(action.payload).toHaveProperty('prop1')\n\n        expectTypeOf(action.payload).not.toHaveProperty('prop2')\n\n        expectTypeOf(action.payload).toHaveProperty('prop3')\n\n        expectTypeOf(action.payload).toHaveProperty('special')\n      }\n    })\n\n    test('isAnyOf correctly narrows types when used with type guards', () => {\n      interface ActionA {\n        type: 'a'\n        payload: {\n          prop1: 1\n          prop3: 2\n        }\n      }\n\n      const guardA = (v: any): v is ActionA => {\n        return v.type === 'a'\n      }\n\n      if (isAllOf(guardA, isSpecialAction)(action)) {\n        expectTypeOf(action.payload).toHaveProperty('prop1')\n\n        expectTypeOf(action.payload).not.toHaveProperty('prop2')\n\n        expectTypeOf(action.payload).toHaveProperty('prop3')\n\n        expectTypeOf(action.payload).toHaveProperty('special')\n      }\n    })\n\n    test('isPending correctly narrows types', () => {\n      if (isPending(action)) {\n        expectTypeOf(action.payload).toBeUndefined()\n\n        expectTypeOf(action).not.toHaveProperty('error')\n      }\n\n      const thunk = createAsyncThunk<string>('a', () => 'result')\n\n      if (isPending(thunk)(action)) {\n        expectTypeOf(action.payload).toBeUndefined()\n\n        expectTypeOf(action).not.toHaveProperty('error')\n      }\n    })\n\n    test('isRejected correctly narrows types', () => {\n      if (isRejected(action)) {\n        // might be there if rejected with payload\n        expectTypeOf(action.payload).toBeUnknown()\n\n        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n      }\n\n      const thunk = createAsyncThunk<string>('a', () => 'result')\n\n      if (isRejected(thunk)(action)) {\n        // might be there if rejected with payload\n        expectTypeOf(action.payload).toBeUnknown()\n\n        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n      }\n    })\n\n    test('isFulfilled correctly narrows types', () => {\n      if (isFulfilled(action)) {\n        expectTypeOf(action.payload).toBeUnknown()\n\n        expectTypeOf(action).not.toHaveProperty('error')\n      }\n\n      const thunk = createAsyncThunk<string>('a', () => 'result')\n      if (isFulfilled(thunk)(action)) {\n        expectTypeOf(action.payload).toBeString()\n\n        expectTypeOf(action).not.toHaveProperty('error')\n      }\n    })\n\n    test('isAsyncThunkAction correctly narrows types', () => {\n      if (isAsyncThunkAction(action)) {\n        expectTypeOf(action.payload).toBeUnknown()\n\n        // do not expect an error property because pending/fulfilled lack it\n        expectTypeOf(action).not.toHaveProperty('error')\n      }\n\n      const thunk = createAsyncThunk<string>('a', () => 'result')\n      if (isAsyncThunkAction(thunk)(action)) {\n        // we should expect the payload to be available, but of unknown type because the action may be pending/rejected\n        expectTypeOf(action.payload).toBeUnknown()\n\n        // do not expect an error property because pending/fulfilled lack it\n        expectTypeOf(action).not.toHaveProperty('error')\n      }\n    })\n\n    test('isRejectedWithValue correctly narrows types', () => {\n      if (isRejectedWithValue(action)) {\n        expectTypeOf(action.payload).toBeUnknown()\n\n        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n      }\n\n      const thunk = createAsyncThunk<\n        string,\n        void,\n        { rejectValue: { message: string } }\n      >('a', () => 'result')\n      if (isRejectedWithValue(thunk)(action)) {\n        expectTypeOf(action.payload).toEqualTypeOf({ message: '' as string })\n\n        expectTypeOf(action.error).toEqualTypeOf<SerializedError>()\n      }\n    })\n  })\n\n  test('matchersAcceptSpreadArguments', () => {\n    const thunk1 = createAsyncThunk('a', () => 'a')\n    const thunk2 = createAsyncThunk('b', () => 'b')\n    const interestingThunks = [thunk1, thunk2]\n    const interestingPendingThunks = interestingThunks.map(\n      (thunk) => thunk.pending,\n    )\n    const interestingFulfilledThunks = interestingThunks.map(\n      (thunk) => thunk.fulfilled,\n    )\n\n    const isLoading = isAnyOf(...interestingPendingThunks)\n    const isNotLoading = isAnyOf(...interestingFulfilledThunks)\n\n    const isAllLoading = isAllOf(...interestingPendingThunks)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/matchers.test.ts",
    "content": "import { vi } from 'vitest'\nimport type { ThunkAction, UnknownAction } from '@reduxjs/toolkit'\nimport {\n  isAllOf,\n  isAnyOf,\n  isAsyncThunkAction,\n  isFulfilled,\n  isPending,\n  isRejected,\n  isRejectedWithValue,\n  createAction,\n  createAsyncThunk,\n  createReducer,\n} from '@reduxjs/toolkit'\n\nconst thunk: ThunkAction<any, any, any, UnknownAction> = () => {}\n\ndescribe('isAnyOf', () => {\n  it('returns true only if any matchers match (match function)', () => {\n    const actionA = createAction<string>('a')\n    const actionB = createAction<number>('b')\n\n    const trueAction = {\n      type: 'a',\n      payload: 'payload',\n    }\n\n    expect(isAnyOf(actionA, actionB)(trueAction)).toEqual(true)\n\n    const falseAction = {\n      type: 'c',\n      payload: 'payload',\n    }\n\n    expect(isAnyOf(actionA, actionB)(falseAction)).toEqual(false)\n  })\n\n  it('returns true only if any type guards match', () => {\n    const actionA = createAction<string>('a')\n    const actionB = createAction<number>('b')\n\n    const isActionA = actionA.match\n    const isActionB = actionB.match\n\n    const trueAction = {\n      type: 'a',\n      payload: 'payload',\n    }\n\n    expect(isAnyOf(isActionA, isActionB)(trueAction)).toEqual(true)\n\n    const falseAction = {\n      type: 'c',\n      payload: 'payload',\n    }\n\n    expect(isAnyOf(isActionA, isActionB)(falseAction)).toEqual(false)\n  })\n\n  it('returns true only if any matchers match (thunk action creators)', () => {\n    const thunkA = createAsyncThunk<string>('a', () => {\n      return 'noop'\n    })\n    const thunkB = createAsyncThunk<number>('b', () => {\n      return 0\n    })\n\n    const action = thunkA.fulfilled('fakeRequestId', 'test')\n\n    expect(isAnyOf(thunkA.fulfilled, thunkB.fulfilled)(action)).toEqual(true)\n\n    expect(\n      isAnyOf(thunkA.pending, thunkA.rejected, thunkB.fulfilled)(action),\n    ).toEqual(false)\n  })\n\n  it('works with reducers', () => {\n    const actionA = createAction<string>('a')\n    const actionB = createAction<number>('b')\n\n    const trueAction = {\n      type: 'a',\n      payload: 'payload',\n    }\n\n    const initialState = { value: false }\n\n    const reducer = createReducer(initialState, (builder) => {\n      builder.addMatcher(isAnyOf(actionA, actionB), (state) => {\n        return { ...state, value: true }\n      })\n    })\n\n    expect(reducer(initialState, trueAction)).toEqual({ value: true })\n\n    const falseAction = {\n      type: 'c',\n      payload: 'payload',\n    }\n\n    expect(reducer(initialState, falseAction)).toEqual(initialState)\n  })\n})\n\ndescribe('isAllOf', () => {\n  it('returns true only if all matchers match', () => {\n    const actionA = createAction<string>('a')\n\n    interface SpecialAction {\n      payload: 'SPECIAL'\n    }\n\n    const isActionSpecial = (action: any): action is SpecialAction => {\n      return action.payload === 'SPECIAL'\n    }\n\n    const trueAction = {\n      type: 'a',\n      payload: 'SPECIAL',\n    }\n\n    expect(isAllOf(actionA, isActionSpecial)(trueAction)).toEqual(true)\n\n    const falseAction = {\n      type: 'a',\n      payload: 'ORDINARY',\n    }\n\n    expect(isAllOf(actionA, isActionSpecial)(falseAction)).toEqual(false)\n\n    const thunkA = createAsyncThunk<string>('a', () => 'result')\n\n    const specialThunkAction = thunkA.fulfilled('SPECIAL', 'fakeRequestId')\n\n    expect(isAllOf(thunkA.fulfilled, isActionSpecial)(specialThunkAction)).toBe(\n      true,\n    )\n\n    const ordinaryThunkAction = thunkA.fulfilled('ORDINARY', 'fakeRequestId')\n\n    expect(\n      isAllOf(thunkA.fulfilled, isActionSpecial)(ordinaryThunkAction),\n    ).toBe(false)\n  })\n})\n\ndescribe('isPending', () => {\n  test('should return false for a regular action', () => {\n    const action = createAction<string>('action/type')('testPayload')\n\n    expect(isPending()(action)).toBe(false)\n    expect(isPending(action)).toBe(false)\n    expect(isPending(thunk)).toBe(false)\n  })\n\n  test('should return true only for pending async thunk actions', () => {\n    const thunk = createAsyncThunk<string>('a', () => 'result')\n\n    const pendingAction = thunk.pending('fakeRequestId')\n    expect(isPending()(pendingAction)).toBe(true)\n    expect(isPending(pendingAction)).toBe(true)\n\n    const rejectedAction = thunk.rejected(\n      new Error('rejected'),\n      'fakeRequestId',\n    )\n    expect(isPending()(rejectedAction)).toBe(false)\n\n    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')\n    expect(isPending()(fulfilledAction)).toBe(false)\n  })\n\n  test('should return true only for thunks provided as arguments', () => {\n    const thunkA = createAsyncThunk<string>('a', () => 'result')\n    const thunkB = createAsyncThunk<string>('b', () => 'result')\n    const thunkC = createAsyncThunk<string>('c', () => 'result')\n\n    const matchAC = isPending(thunkA, thunkC)\n    const matchB = isPending(thunkB)\n\n    function testPendingAction(\n      thunk: typeof thunkA | typeof thunkB | typeof thunkC,\n      expected: boolean,\n    ) {\n      const pendingAction = thunk.pending('fakeRequestId')\n      expect(matchAC(pendingAction)).toBe(expected)\n      expect(matchB(pendingAction)).toBe(!expected)\n\n      const rejectedAction = thunk.rejected(\n        new Error('rejected'),\n        'fakeRequestId',\n      )\n      expect(matchAC(rejectedAction)).toBe(false)\n\n      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')\n      expect(matchAC(fulfilledAction)).toBe(false)\n    }\n\n    testPendingAction(thunkA, true)\n    testPendingAction(thunkC, true)\n    testPendingAction(thunkB, false)\n  })\n})\n\ndescribe('isRejected', () => {\n  test('should return false for a regular action', () => {\n    const action = createAction<string>('action/type')('testPayload')\n\n    expect(isRejected()(action)).toBe(false)\n    expect(isRejected(action)).toBe(false)\n    expect(isRejected(thunk)).toBe(false)\n  })\n\n  test('should return true only for rejected async thunk actions', () => {\n    const thunk = createAsyncThunk<string>('a', () => 'result')\n\n    const pendingAction = thunk.pending('fakeRequestId')\n    expect(isRejected()(pendingAction)).toBe(false)\n\n    const rejectedAction = thunk.rejected(\n      new Error('rejected'),\n      'fakeRequestId',\n    )\n    expect(isRejected()(rejectedAction)).toBe(true)\n    expect(isRejected(rejectedAction)).toBe(true)\n\n    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')\n    expect(isRejected()(fulfilledAction)).toBe(false)\n  })\n\n  test('should return true only for thunks provided as arguments', () => {\n    const thunkA = createAsyncThunk<string>('a', () => 'result')\n    const thunkB = createAsyncThunk<string>('b', () => 'result')\n    const thunkC = createAsyncThunk<string>('c', () => 'result')\n\n    const matchAC = isRejected(thunkA, thunkC)\n    const matchB = isRejected(thunkB)\n\n    function testRejectedAction(\n      thunk: typeof thunkA | typeof thunkB | typeof thunkC,\n      expected: boolean,\n    ) {\n      const pendingAction = thunk.pending('fakeRequestId')\n      expect(matchAC(pendingAction)).toBe(false)\n\n      const rejectedAction = thunk.rejected(\n        new Error('rejected'),\n        'fakeRequestId',\n      )\n      expect(matchAC(rejectedAction)).toBe(expected)\n      expect(matchB(rejectedAction)).toBe(!expected)\n\n      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')\n      expect(matchAC(fulfilledAction)).toBe(false)\n    }\n\n    testRejectedAction(thunkA, true)\n    testRejectedAction(thunkC, true)\n    testRejectedAction(thunkB, false)\n  })\n})\n\ndescribe('isRejectedWithValue', () => {\n  test('should return false for a regular action', () => {\n    const action = createAction<string>('action/type')('testPayload')\n\n    expect(isRejectedWithValue()(action)).toBe(false)\n    expect(isRejectedWithValue(action)).toBe(false)\n    expect(isRejectedWithValue(thunk)).toBe(false)\n  })\n\n  test('should return true only for rejected-with-value async thunk actions', async () => {\n    const thunk = createAsyncThunk<string>('a', (_, { rejectWithValue }) => {\n      return rejectWithValue('rejectWithValue!')\n    })\n\n    const pendingAction = thunk.pending('fakeRequestId')\n    expect(isRejectedWithValue()(pendingAction)).toBe(false)\n\n    const rejectedAction = thunk.rejected(\n      new Error('rejected'),\n      'fakeRequestId',\n    )\n    expect(isRejectedWithValue()(rejectedAction)).toBe(false)\n\n    const getState = vi.fn(() => ({}))\n    const dispatch = vi.fn((x: any) => x)\n    const extra = {}\n\n    // note: doesn't throw because we don't unwrap it\n    const rejectedWithValueAction = await thunk()(dispatch, getState, extra)\n\n    expect(isRejectedWithValue()(rejectedWithValueAction)).toBe(true)\n\n    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')\n    expect(isRejectedWithValue()(fulfilledAction)).toBe(false)\n  })\n\n  test('should return true only for thunks provided as arguments', async () => {\n    const payloadCreator = (_: any, { rejectWithValue }: any) => {\n      return rejectWithValue('rejectWithValue!')\n    }\n\n    const thunkA = createAsyncThunk<string>('a', payloadCreator)\n    const thunkB = createAsyncThunk<string>('b', payloadCreator)\n    const thunkC = createAsyncThunk<string>('c', payloadCreator)\n\n    const matchAC = isRejectedWithValue(thunkA, thunkC)\n    const matchB = isRejectedWithValue(thunkB)\n\n    async function testRejectedAction(\n      thunk: typeof thunkA | typeof thunkB | typeof thunkC,\n      expected: boolean,\n    ) {\n      const pendingAction = thunk.pending('fakeRequestId')\n      expect(matchAC(pendingAction)).toBe(false)\n\n      const rejectedAction = thunk.rejected(\n        new Error('rejected'),\n        'fakeRequestId',\n      )\n      // rejected-with-value is a narrower requirement than rejected\n      expect(matchAC(rejectedAction)).toBe(false)\n\n      const getState = vi.fn(() => ({}))\n      const dispatch = vi.fn((x: any) => x)\n      const extra = {}\n\n      // note: doesn't throw because we don't unwrap it\n      const rejectedWithValueAction = await thunk()(dispatch, getState, extra)\n\n      expect(matchAC(rejectedWithValueAction)).toBe(expected)\n      expect(matchB(rejectedWithValueAction)).toBe(!expected)\n\n      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')\n      expect(matchAC(fulfilledAction)).toBe(false)\n    }\n\n    await testRejectedAction(thunkA, true)\n    await testRejectedAction(thunkC, true)\n    await testRejectedAction(thunkB, false)\n  })\n})\n\ndescribe('isFulfilled', () => {\n  test('should return false for a regular action', () => {\n    const action = createAction<string>('action/type')('testPayload')\n\n    expect(isFulfilled()(action)).toBe(false)\n    expect(isFulfilled(action)).toBe(false)\n    expect(isFulfilled(thunk)).toBe(false)\n  })\n\n  test('should return true only for fulfilled async thunk actions', () => {\n    const thunk = createAsyncThunk<string>('a', () => 'result')\n\n    const pendingAction = thunk.pending('fakeRequestId')\n    expect(isFulfilled()(pendingAction)).toBe(false)\n\n    const rejectedAction = thunk.rejected(\n      new Error('rejected'),\n      'fakeRequestId',\n    )\n    expect(isFulfilled()(rejectedAction)).toBe(false)\n\n    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')\n    expect(isFulfilled()(fulfilledAction)).toBe(true)\n    expect(isFulfilled(fulfilledAction)).toBe(true)\n  })\n\n  test('should return true only for thunks provided as arguments', () => {\n    const thunkA = createAsyncThunk<string>('a', () => 'result')\n    const thunkB = createAsyncThunk<string>('b', () => 'result')\n    const thunkC = createAsyncThunk<string>('c', () => 'result')\n\n    const matchAC = isFulfilled(thunkA, thunkC)\n    const matchB = isFulfilled(thunkB)\n\n    function testFulfilledAction(\n      thunk: typeof thunkA | typeof thunkB | typeof thunkC,\n      expected: boolean,\n    ) {\n      const pendingAction = thunk.pending('fakeRequestId')\n      expect(matchAC(pendingAction)).toBe(false)\n\n      const rejectedAction = thunk.rejected(\n        new Error('rejected'),\n        'fakeRequestId',\n      )\n      expect(matchAC(rejectedAction)).toBe(false)\n\n      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')\n      expect(matchAC(fulfilledAction)).toBe(expected)\n      expect(matchB(fulfilledAction)).toBe(!expected)\n    }\n\n    testFulfilledAction(thunkA, true)\n    testFulfilledAction(thunkC, true)\n    testFulfilledAction(thunkB, false)\n  })\n})\n\ndescribe('isAsyncThunkAction', () => {\n  test('should return false for a regular action', () => {\n    const action = createAction<string>('action/type')('testPayload')\n\n    expect(isAsyncThunkAction()(action)).toBe(false)\n    expect(isAsyncThunkAction(action)).toBe(false)\n    expect(isAsyncThunkAction(thunk)).toBe(false)\n  })\n\n  test('should return true for any async thunk action if no arguments were provided', () => {\n    const thunk = createAsyncThunk<string>('a', () => 'result')\n    const matcher = isAsyncThunkAction()\n\n    const pendingAction = thunk.pending('fakeRequestId')\n    expect(matcher(pendingAction)).toBe(true)\n\n    const rejectedAction = thunk.rejected(\n      new Error('rejected'),\n      'fakeRequestId',\n    )\n    expect(matcher(rejectedAction)).toBe(true)\n\n    const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')\n    expect(matcher(fulfilledAction)).toBe(true)\n  })\n\n  test('should return true only for thunks provided as arguments', () => {\n    const thunkA = createAsyncThunk<string>('a', () => 'result')\n    const thunkB = createAsyncThunk<string>('b', () => 'result')\n    const thunkC = createAsyncThunk<string>('c', () => 'result')\n\n    const matchAC = isAsyncThunkAction(thunkA, thunkC)\n    const matchB = isAsyncThunkAction(thunkB)\n\n    function testAllActions(\n      thunk: typeof thunkA | typeof thunkB | typeof thunkC,\n      expected: boolean,\n    ) {\n      const pendingAction = thunk.pending('fakeRequestId')\n      expect(matchAC(pendingAction)).toBe(expected)\n      expect(matchB(pendingAction)).toBe(!expected)\n\n      const rejectedAction = thunk.rejected(\n        new Error('rejected'),\n        'fakeRequestId',\n      )\n      expect(matchAC(rejectedAction)).toBe(expected)\n      expect(matchB(rejectedAction)).toBe(!expected)\n\n      const fulfilledAction = thunk.fulfilled('result', 'fakeRequestId')\n      expect(matchAC(fulfilledAction)).toBe(expected)\n      expect(matchB(fulfilledAction)).toBe(!expected)\n    }\n\n    testAllActions(thunkA, true)\n    testAllActions(thunkC, true)\n    testAllActions(thunkB, false)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/serializableStateInvariantMiddleware.test.ts",
    "content": "import { noop } from '@internal/listenerMiddleware/utils'\nimport { isNestedFrozen } from '@internal/serializableStateInvariantMiddleware'\nimport type { Reducer } from '@reduxjs/toolkit'\nimport {\n  configureStore,\n  createNextState,\n  createSerializableStateInvariantMiddleware,\n  findNonSerializableValue,\n  isPlain,\n  Tuple,\n} from '@reduxjs/toolkit'\n\n// Mocking console\nconst consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(noop)\n\nconst consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(noop)\n\nafterEach(() => {\n  vi.clearAllMocks()\n})\n\nafterAll(() => {\n  vi.restoreAllMocks()\n})\n\ndescribe('findNonSerializableValue', () => {\n  it('Should return false if no matching values are found', () => {\n    const obj = {\n      a: 42,\n      b: {\n        b1: 'test',\n      },\n      c: [99, { d: 123 }],\n    }\n\n    const result = findNonSerializableValue(obj)\n\n    expect(result).toBe(false)\n  })\n\n  it('Should return a keypath and the value if it finds a non-serializable value', () => {\n    function testFunction() {}\n\n    const obj = {\n      a: 42,\n      b: {\n        b1: testFunction,\n      },\n      c: [99, { d: 123 }],\n    }\n\n    const result = findNonSerializableValue(obj)\n\n    expect(result).toEqual({ keyPath: 'b.b1', value: testFunction })\n  })\n\n  it('Should return the first non-serializable value it finds', () => {\n    const map = new Map()\n    const symbol = Symbol.for('testSymbol')\n\n    const obj = {\n      a: 42,\n      b: {\n        b1: 1,\n      },\n      c: [99, { d: 123 }, map, symbol, 'test'],\n      d: symbol,\n    }\n\n    const result = findNonSerializableValue(obj)\n\n    expect(result).toEqual({ keyPath: 'c.2', value: map })\n  })\n\n  it('Should return a specific value if the root object is non-serializable', () => {\n    const value = new Map()\n    const result = findNonSerializableValue(value)\n\n    expect(result).toEqual({ keyPath: '<root>', value })\n  })\n\n  it('Should accept null as a valid value', () => {\n    const obj = {\n      a: 42,\n      b: {\n        b1: 1,\n      },\n      c: null,\n    }\n\n    const result = findNonSerializableValue(obj)\n\n    expect(result).toEqual(false)\n  })\n})\n\ndescribe('serializableStateInvariantMiddleware', () => {\n  it('Should log an error when a non-serializable action is dispatched', () => {\n    const reducer: Reducer = (state = 0, _action) => state + 1\n\n    const serializableStateInvariantMiddleware =\n      createSerializableStateInvariantMiddleware()\n\n    const store = configureStore({\n      reducer,\n      middleware: () => new Tuple(serializableStateInvariantMiddleware),\n    })\n\n    const symbol = Symbol.for('SOME_CONSTANT')\n    const dispatchedAction = { type: 'an-action', payload: symbol }\n\n    store.dispatch(dispatchedAction)\n\n    expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n    expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n      `A non-serializable value was detected in an action, in the path: \\`payload\\`. Value:`,\n      symbol,\n      `\\nTake a look at the logic that dispatched this action: `,\n      dispatchedAction,\n      `\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)`,\n      `\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)`,\n    )\n  })\n\n  it('Should log an error when a non-serializable value is in state', () => {\n    const ACTION_TYPE = 'TEST_ACTION'\n\n    const initialState = {\n      a: 0,\n    }\n\n    const badValue = new Map()\n\n    const reducer: Reducer = (state = initialState, action) => {\n      switch (action.type) {\n        case ACTION_TYPE: {\n          return {\n            a: badValue,\n          }\n        }\n        default:\n          return state\n      }\n    }\n\n    const serializableStateInvariantMiddleware =\n      createSerializableStateInvariantMiddleware()\n\n    const store = configureStore({\n      reducer: {\n        testSlice: reducer,\n      },\n      middleware: () => new Tuple(serializableStateInvariantMiddleware),\n    })\n\n    store.dispatch({ type: ACTION_TYPE })\n\n    expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n    expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n      `A non-serializable value was detected in the state, in the path: \\`testSlice.a\\`. Value:`,\n      badValue,\n      `\\nTake a look at the reducer(s) handling this action type: TEST_ACTION.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,\n    )\n  })\n\n  describe('consumer tolerated structures', () => {\n    const nonSerializableValue = new Map()\n\n    const nestedSerializableObjectWithBadValue = {\n      isSerializable: true,\n      entries: (): [string, any][] => [\n        ['good-string', 'Good!'],\n        ['good-number', 1337],\n        ['bad-map-instance', nonSerializableValue],\n      ],\n    }\n\n    const serializableObject = {\n      isSerializable: true,\n      entries: (): [string, any][] => [\n        ['first', 1],\n        ['second', 'B!'],\n        ['third', nestedSerializableObjectWithBadValue],\n      ],\n    }\n\n    it('Should log an error when a non-serializable value is nested in state', () => {\n      const ACTION_TYPE = 'TEST_ACTION'\n\n      const initialState = {\n        a: 0,\n      }\n\n      const reducer: Reducer = (state = initialState, action) => {\n        switch (action.type) {\n          case ACTION_TYPE: {\n            return {\n              a: serializableObject,\n            }\n          }\n          default:\n            return state\n        }\n      }\n\n      // use default options\n      const serializableStateInvariantMiddleware =\n        createSerializableStateInvariantMiddleware()\n\n      const store = configureStore({\n        reducer: {\n          testSlice: reducer,\n        },\n        middleware: () => new Tuple(serializableStateInvariantMiddleware),\n      })\n\n      store.dispatch({ type: ACTION_TYPE })\n\n      expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n      // since default options are used, the `entries` function in `serializableObject` will cause the error\n      expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n        `A non-serializable value was detected in the state, in the path: \\`testSlice.a.entries\\`. Value:`,\n        serializableObject.entries,\n        `\\nTake a look at the reducer(s) handling this action type: TEST_ACTION.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,\n      )\n    })\n\n    it('Should use consumer supplied isSerializable and getEntries options to tolerate certain structures', () => {\n      const ACTION_TYPE = 'TEST_ACTION'\n\n      const initialState = {\n        a: 0,\n      }\n\n      const isSerializable = (val: any): boolean =>\n        val.isSerializable || isPlain(val)\n      const getEntries = (val: any): [string, any][] =>\n        val.isSerializable ? val.entries() : Object.entries(val)\n\n      const reducer: Reducer = (state = initialState, action) => {\n        switch (action.type) {\n          case ACTION_TYPE: {\n            return {\n              a: serializableObject,\n            }\n          }\n          default:\n            return state\n        }\n      }\n\n      const serializableStateInvariantMiddleware =\n        createSerializableStateInvariantMiddleware({\n          isSerializable,\n          getEntries,\n        })\n\n      const store = configureStore({\n        reducer: {\n          testSlice: reducer,\n        },\n        middleware: () => new Tuple(serializableStateInvariantMiddleware),\n      })\n\n      store.dispatch({ type: ACTION_TYPE })\n\n      expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n      // error reported is from a nested class instance, rather than the `entries` function `serializableObject`\n      expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n        `A non-serializable value was detected in the state, in the path: \\`testSlice.a.third.bad-map-instance\\`. Value:`,\n        nonSerializableValue,\n        `\\nTake a look at the reducer(s) handling this action type: TEST_ACTION.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,\n      )\n    })\n  })\n\n  it('Should use the supplied isSerializable function to determine serializability', () => {\n    const ACTION_TYPE = 'TEST_ACTION'\n\n    const initialState = {\n      a: 0,\n    }\n\n    const badValue = new Map()\n\n    const reducer: Reducer = (state = initialState, action) => {\n      switch (action.type) {\n        case ACTION_TYPE: {\n          return {\n            a: badValue,\n          }\n        }\n        default:\n          return state\n      }\n    }\n\n    const serializableStateInvariantMiddleware =\n      createSerializableStateInvariantMiddleware({\n        isSerializable: () => true,\n      })\n\n    const store = configureStore({\n      reducer: {\n        testSlice: reducer,\n      },\n      middleware: () => new Tuple(serializableStateInvariantMiddleware),\n    })\n\n    store.dispatch({ type: ACTION_TYPE })\n\n    // Supplied 'isSerializable' considers all values serializable, hence\n    // no error logging is expected:\n    expect(consoleErrorSpy).not.toHaveBeenCalled()\n  })\n\n  it('should not check serializability for ignored action types', () => {\n    let numTimesCalled = 0\n\n    const serializableStateMiddleware =\n      createSerializableStateInvariantMiddleware({\n        isSerializable: () => {\n          numTimesCalled++\n          return true\n        },\n        ignoredActions: ['IGNORE_ME'],\n      })\n\n    const store = configureStore({\n      reducer: () => ({}),\n      middleware: () => new Tuple(serializableStateMiddleware),\n    })\n\n    expect(numTimesCalled).toBe(0)\n\n    store.dispatch({ type: 'IGNORE_ME' })\n\n    // The state check only calls `isSerializable` once\n    expect(numTimesCalled).toBe(1)\n\n    store.dispatch({ type: 'ANY_OTHER_ACTION' })\n\n    // Action checks call `isSerializable` 2+ times when enabled\n    expect(numTimesCalled).toBeGreaterThanOrEqual(3)\n  })\n\n  describe('ignored action paths', () => {\n    function reducer() {\n      return 0\n    }\n    const nonSerializableValue = new Map()\n\n    it('default value: meta.arg', () => {\n      configureStore({\n        reducer,\n        middleware: () =>\n          new Tuple(createSerializableStateInvariantMiddleware()),\n      }).dispatch({ type: 'test', meta: { arg: nonSerializableValue } })\n\n      expect(consoleErrorSpy).not.toHaveBeenCalled()\n    })\n\n    it('default value can be overridden', () => {\n      configureStore({\n        reducer,\n        middleware: () =>\n          new Tuple(\n            createSerializableStateInvariantMiddleware({\n              ignoredActionPaths: [],\n            }),\n          ),\n      }).dispatch({ type: 'test', meta: { arg: nonSerializableValue } })\n\n      expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n      expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n        `A non-serializable value was detected in an action, in the path: \\`meta.arg\\`. Value:`,\n        nonSerializableValue,\n        `\\nTake a look at the logic that dispatched this action: `,\n        { type: 'test', meta: { arg: nonSerializableValue } },\n        `\\n(See https://redux.js.org/faq/actions#why-should-type-be-a-string-or-at-least-serializable-why-should-my-action-types-be-constants)`,\n        `\\n(To allow non-serializable values see: https://redux-toolkit.js.org/usage/usage-guide#working-with-non-serializable-data)`,\n      )\n    })\n\n    it('can specify (multiple) different values', () => {\n      configureStore({\n        reducer,\n        middleware: () =>\n          new Tuple(\n            createSerializableStateInvariantMiddleware({\n              ignoredActionPaths: ['payload', 'meta.arg'],\n            }),\n          ),\n      }).dispatch({\n        type: 'test',\n        payload: { arg: nonSerializableValue },\n        meta: { arg: nonSerializableValue },\n      })\n\n      expect(consoleErrorSpy).not.toHaveBeenCalled()\n    })\n\n    it('can specify regexp', () => {\n      configureStore({\n        reducer,\n        middleware: () =>\n          new Tuple(\n            createSerializableStateInvariantMiddleware({\n              ignoredActionPaths: [/^payload\\..*$/],\n            }),\n          ),\n      }).dispatch({\n        type: 'test',\n        payload: { arg: nonSerializableValue },\n      })\n\n      expect(consoleErrorSpy).not.toHaveBeenCalled()\n    })\n  })\n\n  it('allows ignoring actions entirely', () => {\n    let numTimesCalled = 0\n\n    const serializableStateMiddleware =\n      createSerializableStateInvariantMiddleware({\n        isSerializable: () => {\n          numTimesCalled++\n          return true\n        },\n        ignoreActions: true,\n      })\n\n    const store = configureStore({\n      reducer: () => ({}),\n      middleware: () => new Tuple(serializableStateMiddleware),\n    })\n\n    expect(numTimesCalled).toBe(0)\n\n    store.dispatch({ type: 'THIS_DOESNT_MATTER' })\n\n    // `isSerializable` is called once for a state check\n    expect(numTimesCalled).toBe(1)\n\n    store.dispatch({ type: 'THIS_DOESNT_MATTER_AGAIN' })\n\n    expect(numTimesCalled).toBe(2)\n  })\n\n  it('should not check serializability for ignored slice names', () => {\n    const ACTION_TYPE = 'TEST_ACTION'\n\n    const initialState = {\n      a: 0,\n    }\n\n    const badValue = new Map()\n\n    const reducer: Reducer = (state = initialState, action) => {\n      switch (action.type) {\n        case ACTION_TYPE: {\n          return {\n            a: badValue,\n            b: {\n              c: badValue,\n              d: badValue,\n            },\n            e: { f: badValue },\n            g: {\n              h: badValue,\n              i: badValue,\n            },\n          }\n        }\n        default:\n          return state\n      }\n    }\n\n    const serializableStateInvariantMiddleware =\n      createSerializableStateInvariantMiddleware({\n        ignoredPaths: [\n          // Test for ignoring a single value\n          'testSlice.a',\n          // Test for ignoring a single nested value\n          'testSlice.b.c',\n          // Test for ignoring an object and its children\n          'testSlice.e',\n          // Test for ignoring based on RegExp\n          /^testSlice\\.g\\..*$/,\n        ],\n      })\n\n    const store = configureStore({\n      reducer: {\n        testSlice: reducer,\n      },\n      middleware: () => new Tuple(serializableStateInvariantMiddleware),\n    })\n\n    store.dispatch({ type: ACTION_TYPE })\n\n    expect(consoleErrorSpy).toHaveBeenCalledOnce()\n\n    // testSlice.b.d was not covered in ignoredPaths, so will still log the error\n    expect(consoleErrorSpy).toHaveBeenLastCalledWith(\n      `A non-serializable value was detected in the state, in the path: \\`testSlice.b.d\\`. Value:`,\n      badValue,\n      `\\nTake a look at the reducer(s) handling this action type: TEST_ACTION.\n(See https://redux.js.org/faq/organizing-state#can-i-put-functions-promises-or-other-non-serializable-items-in-my-store-state)`,\n    )\n  })\n\n  it('allows ignoring state entirely', () => {\n    const badValue = new Map()\n    let numTimesCalled = 0\n    const reducer = () => badValue\n    const store = configureStore({\n      reducer,\n      middleware: () =>\n        new Tuple(\n          createSerializableStateInvariantMiddleware({\n            isSerializable: () => {\n              numTimesCalled++\n              return true\n            },\n            ignoreState: true,\n          }),\n        ),\n    })\n\n    expect(numTimesCalled).toBe(0)\n\n    store.dispatch({ type: 'test' })\n\n    expect(consoleErrorSpy).not.toHaveBeenCalled()\n\n    // Should be called twice for the action - there is an initial check for early returns, then a second and potentially 3rd for nested properties\n    expect(numTimesCalled).toBe(2)\n  })\n\n  it('never calls isSerializable if both ignoreState and ignoreActions are true', () => {\n    const badValue = new Map()\n    let numTimesCalled = 0\n    const reducer = () => badValue\n    const store = configureStore({\n      reducer,\n      middleware: () =>\n        new Tuple(\n          createSerializableStateInvariantMiddleware({\n            isSerializable: () => {\n              numTimesCalled++\n              return true\n            },\n            ignoreState: true,\n            ignoreActions: true,\n          }),\n        ),\n    })\n\n    expect(numTimesCalled).toBe(0)\n\n    store.dispatch({ type: 'TEST', payload: new Date() })\n    store.dispatch({ type: 'OTHER_THING' })\n\n    expect(numTimesCalled).toBe(0)\n  })\n\n  it('Should print a warning if execution takes too long', () => {\n    const reducer: Reducer = (state = 42, action) => {\n      return state\n    }\n\n    const serializableStateInvariantMiddleware =\n      createSerializableStateInvariantMiddleware({ warnAfter: 4 })\n\n    const store = configureStore({\n      reducer: {\n        testSlice: reducer,\n      },\n      middleware: () => new Tuple(serializableStateInvariantMiddleware),\n    })\n\n    store.dispatch({\n      type: 'SOME_ACTION',\n      payload: new Array(10_000).fill({ value: 'more' }),\n    })\n\n    expect(consoleWarnSpy).toHaveBeenCalledOnce()\n\n    expect(consoleWarnSpy).toHaveBeenLastCalledWith(\n      expect.stringMatching(\n        /^SerializableStateInvariantMiddleware took \\d*ms, which is more than the warning threshold of 4ms./,\n      ),\n    )\n  })\n\n  it('Should not print a warning if \"reducer\" takes too long', () => {\n    const reducer: Reducer = (state = 42, action) => {\n      const started = Date.now()\n      while (Date.now() - started < 8) {}\n      return state\n    }\n\n    const serializableStateInvariantMiddleware =\n      createSerializableStateInvariantMiddleware({ warnAfter: 4 })\n\n    const store = configureStore({\n      reducer: {\n        testSlice: reducer,\n      },\n      middleware: () => new Tuple(serializableStateInvariantMiddleware),\n    })\n\n    store.dispatch({ type: 'SOME_ACTION' })\n\n    expect(consoleErrorSpy).not.toHaveBeenCalled()\n  })\n\n  it('Should cache its results', () => {\n    let numPlainChecks = 0\n    const countPlainChecks = (x: any) => {\n      numPlainChecks++\n      return isPlain(x)\n    }\n\n    const serializableStateInvariantMiddleware =\n      createSerializableStateInvariantMiddleware({\n        isSerializable: countPlainChecks,\n      })\n\n    const store = configureStore({\n      reducer: (state = [], action) => {\n        if (action.type === 'SET_STATE') return action.payload\n        return state\n      },\n      middleware: () => new Tuple(serializableStateInvariantMiddleware),\n    })\n\n    const state = createNextState([], () =>\n      new Array(50).fill(0).map((x, i) => ({ i })),\n    )\n    expect(isNestedFrozen(state)).toBe(true)\n\n    store.dispatch({\n      type: 'SET_STATE',\n      payload: state,\n    })\n    expect(numPlainChecks).toBeGreaterThan(state.length)\n\n    numPlainChecks = 0\n    store.dispatch({ type: 'NOOP' })\n    expect(numPlainChecks).toBeLessThan(10)\n  })\n})\n"
  },
  {
    "path": "packages/toolkit/src/tests/utils/CustomMatchers.d.ts",
    "content": "import type { Assertion, AsymmetricMatchersContaining } from 'vitest'\n\ninterface CustomMatchers<R = unknown> {\n  toMatchSequence(...matchers: Array<(arg: any) => boolean>): R\n}\n\ndeclare module 'vitest' {\n  interface Assertion<T = any> extends CustomMatchers<T> {}\n  interface AsymmetricMatchersContaining extends CustomMatchers {}\n}\n\ndeclare global {\n  namespace jest {\n    interface Matchers<R> extends CustomMatchers<R> {}\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/src/tests/utils/helpers.tsx",
    "content": "import type {\n  EnhancedStore,\n  Middleware,\n  Reducer,\n  Store,\n  UnknownAction,\n} from '@reduxjs/toolkit'\nimport { configureStore } from '@reduxjs/toolkit'\nimport { setupListeners } from '@reduxjs/toolkit/query'\nimport { useCallback, useEffect, useRef } from 'react'\n\nimport { Provider } from 'react-redux'\n\nimport { act, cleanup } from '@testing-library/react'\n\nexport const ANY = 0 as any\n\nexport const DEFAULT_DELAY_MS = 150\n\nexport const getSerializedHeaders = (headers: Headers = new Headers()) => {\n  const result: Record<string, string> = {}\n  headers.forEach((val, key) => {\n    result[key] = val\n  })\n  return result\n}\n\nexport async function waitMs(time = DEFAULT_DELAY_MS) {\n  const now = Date.now()\n  while (Date.now() < now + time) {\n    await new Promise((res) => process.nextTick(res))\n  }\n}\n\nexport function waitForFakeTimer(time = DEFAULT_DELAY_MS) {\n  return new Promise((resolve) => setTimeout(resolve, time))\n}\n\nexport function withProvider(store: Store<any>) {\n  return function Wrapper({ children }: any) {\n    return <Provider store={store}>{children}</Provider>\n  }\n}\n\nexport const hookWaitFor = async (cb: () => void, time = 2000) => {\n  const startedAt = Date.now()\n\n  while (true) {\n    try {\n      cb()\n      return true\n    } catch (e) {\n      if (Date.now() > startedAt + time) {\n        throw e\n      }\n      await act(async () => {\n        await waitMs(2)\n      })\n    }\n  }\n}\nexport const fakeTimerWaitFor = async (cb: () => void, time = 2000) => {\n  const startedAt = Date.now()\n\n  while (true) {\n    try {\n      cb()\n      return true\n    } catch (e) {\n      if (Date.now() > startedAt + time) {\n        throw e\n      }\n      await act(async () => {\n        await vi.advanceTimersByTimeAsync(2)\n      })\n    }\n  }\n}\n\nexport const useRenderCounter = () => {\n  const countRef = useRef(0)\n\n  useEffect(() => {\n    countRef.current += 1\n  })\n\n  useEffect(() => {\n    return () => {\n      countRef.current = 0\n    }\n  }, [])\n\n  return useCallback(() => countRef.current, [])\n}\n\nexpect.extend({\n  toMatchSequence(\n    _actions: UnknownAction[],\n    ...matchers: Array<(arg: any) => boolean>\n  ) {\n    const actions = _actions.concat()\n    actions.shift() // remove INIT\n\n    for (let i = 0; i < matchers.length; i++) {\n      if (!matchers[i](actions[i])) {\n        return {\n          message: () =>\n            `Action ${actions[i].type} does not match sequence at position ${i}.\nAll actions:\n${actions.map((a) => a.type).join('\\n')}`,\n          pass: false,\n        }\n      }\n    }\n    return {\n      message: () => `All actions match the sequence.`,\n      pass: true,\n    }\n  },\n})\n\nexport const actionsReducer = {\n  actions: (state: UnknownAction[] = [], action: UnknownAction) => {\n    // As of 2.0-beta.4, we are going to ignore all `subscriptionsUpdated` actions in tests\n    if (action.type.includes('subscriptionsUpdated')) {\n      return state\n    }\n\n    return [...state, action]\n  },\n}\n\nexport function setupApiStore<\n  A extends {\n    reducerPath: 'api'\n    reducer: Reducer<any, any>\n    middleware: Middleware\n    util: { resetApiState(): any }\n  },\n  R extends Record<string, Reducer<any, any>> = Record<never, never>,\n>(\n  api: A,\n  extraReducers?: R,\n  options: {\n    withoutListeners?: boolean\n    withoutTestLifecycles?: boolean\n    middleware?: {\n      prepend?: Middleware[]\n      concat?: Middleware[]\n    }\n  } = {},\n) {\n  const { middleware } = options\n  const getStore = () =>\n    configureStore({\n      reducer: { api: api.reducer, ...extraReducers },\n      middleware: (gdm) => {\n        const tempMiddleware = gdm({\n          serializableCheck: false,\n          immutableCheck: false,\n        }).concat(api.middleware)\n\n        return tempMiddleware\n          .concat(middleware?.concat ?? [])\n          .prepend(middleware?.prepend ?? []) as typeof tempMiddleware\n      },\n      enhancers: (gde) =>\n        gde({\n          autoBatch: false,\n        }),\n    })\n\n  type State = {\n    api: ReturnType<A['reducer']>\n  } & {\n    [K in keyof R]: ReturnType<R[K]>\n  }\n  type StoreType = EnhancedStore<\n    {\n      api: ReturnType<A['reducer']>\n    } & {\n      [K in keyof R]: ReturnType<R[K]>\n    },\n    UnknownAction,\n    ReturnType<typeof getStore> extends EnhancedStore<any, any, infer M>\n      ? M\n      : never\n  >\n\n  const initialStore = getStore() as StoreType\n  const refObj = {\n    api,\n    store: initialStore,\n    wrapper: withProvider(initialStore),\n  }\n  let cleanupListeners: () => void\n\n  if (!options.withoutTestLifecycles) {\n    beforeEach(() => {\n      const store = getStore() as StoreType\n      refObj.store = store\n      refObj.wrapper = withProvider(store)\n      if (!options.withoutListeners) {\n        cleanupListeners = setupListeners(store.dispatch)\n      }\n    })\n    afterEach(() => {\n      cleanup()\n      if (!options.withoutListeners) {\n        cleanupListeners()\n      }\n      refObj.store.dispatch(api.util.resetApiState())\n    })\n  }\n\n  return refObj\n}\n"
  },
  {
    "path": "packages/toolkit/src/tsHelpers.ts",
    "content": "import type { Middleware, StoreEnhancer } from 'redux'\nimport type { Tuple } from './utils'\n\nexport function safeAssign<T extends object>(\n  target: T,\n  ...args: Array<Partial<NoInfer<T>>>\n) {\n  Object.assign(target, ...args)\n}\n\n/**\n * return True if T is `any`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsAny<T, True, False = never> =\n  // test if we are going the left AND right path in the condition\n  true | false extends (T extends never ? true : false) ? True : False\n\nexport type CastAny<T, CastTo> = IsAny<T, CastTo, T>\n\n/**\n * return True if T is `unknown`, otherwise return False\n * taken from https://github.com/joonhocho/tsdef\n *\n * @internal\n */\nexport type IsUnknown<T, True, False = never> = unknown extends T\n  ? IsAny<T, False, True>\n  : False\n\nexport type FallbackIfUnknown<T, Fallback> = IsUnknown<T, Fallback, T>\n\n/**\n * @internal\n */\nexport type IfMaybeUndefined<P, True, False> = [undefined] extends [P]\n  ? True\n  : False\n\n/**\n * @internal\n */\nexport type IfVoid<P, True, False> = [void] extends [P] ? True : False\n\n/**\n * @internal\n */\nexport type IsEmptyObj<T, True, False = never> = T extends any\n  ? keyof T extends never\n    ? IsUnknown<T, False, IfMaybeUndefined<T, False, IfVoid<T, False, True>>>\n    : False\n  : never\n\n/**\n * returns True if TS version is above 3.5, False if below.\n * uses feature detection to detect TS version >= 3.5\n * * versions below 3.5 will return `{}` for unresolvable interference\n * * versions above will return `unknown`\n *\n * @internal\n */\nexport type AtLeastTS35<True, False> = [True, False][IsUnknown<\n  ReturnType<<T>() => T>,\n  0,\n  1\n>]\n\n/**\n * @internal\n */\nexport type IsUnknownOrNonInferrable<T, True, False> = AtLeastTS35<\n  IsUnknown<T, True, False>,\n  IsEmptyObj<T, True, IsUnknown<T, True, False>>\n>\n\n/**\n * Convert a Union type `(A|B)` to an intersection type `(A&B)`\n */\nexport type UnionToIntersection<U> = (\n  U extends any ? (k: U) => void : never\n) extends (k: infer I) => void\n  ? I\n  : never\n\n// Appears to have a convenient side effect of ignoring `never` even if that's not what you specified\nexport type ExcludeFromTuple<T, E, Acc extends unknown[] = []> = T extends [\n  infer Head,\n  ...infer Tail,\n]\n  ? ExcludeFromTuple<Tail, E, [...Acc, ...([Head] extends [E] ? [] : [Head])]>\n  : Acc\n\ntype ExtractDispatchFromMiddlewareTuple<\n  MiddlewareTuple extends readonly any[],\n  Acc extends {},\n> = MiddlewareTuple extends [infer Head, ...infer Tail]\n  ? ExtractDispatchFromMiddlewareTuple<\n      Tail,\n      Acc & (Head extends Middleware<infer D> ? IsAny<D, {}, D> : {})\n    >\n  : Acc\n\nexport type ExtractDispatchExtensions<M> =\n  M extends Tuple<infer MiddlewareTuple>\n    ? ExtractDispatchFromMiddlewareTuple<MiddlewareTuple, {}>\n    : M extends ReadonlyArray<Middleware>\n      ? ExtractDispatchFromMiddlewareTuple<[...M], {}>\n      : never\n\ntype ExtractStoreExtensionsFromEnhancerTuple<\n  EnhancerTuple extends readonly any[],\n  Acc extends {},\n> = EnhancerTuple extends [infer Head, ...infer Tail]\n  ? ExtractStoreExtensionsFromEnhancerTuple<\n      Tail,\n      Acc & (Head extends StoreEnhancer<infer Ext> ? IsAny<Ext, {}, Ext> : {})\n    >\n  : Acc\n\nexport type ExtractStoreExtensions<E> =\n  E extends Tuple<infer EnhancerTuple>\n    ? ExtractStoreExtensionsFromEnhancerTuple<EnhancerTuple, {}>\n    : E extends ReadonlyArray<StoreEnhancer>\n      ? UnionToIntersection<\n          E[number] extends StoreEnhancer<infer Ext>\n            ? Ext extends {}\n              ? IsAny<Ext, {}, Ext>\n              : {}\n            : {}\n        >\n      : never\n\ntype ExtractStateExtensionsFromEnhancerTuple<\n  EnhancerTuple extends readonly any[],\n  Acc extends {},\n> = EnhancerTuple extends [infer Head, ...infer Tail]\n  ? ExtractStateExtensionsFromEnhancerTuple<\n      Tail,\n      Acc &\n        (Head extends StoreEnhancer<any, infer StateExt>\n          ? IsAny<StateExt, {}, StateExt>\n          : {})\n    >\n  : Acc\n\nexport type ExtractStateExtensions<E> =\n  E extends Tuple<infer EnhancerTuple>\n    ? ExtractStateExtensionsFromEnhancerTuple<EnhancerTuple, {}>\n    : E extends ReadonlyArray<StoreEnhancer>\n      ? UnionToIntersection<\n          E[number] extends StoreEnhancer<any, infer StateExt>\n            ? StateExt extends {}\n              ? IsAny<StateExt, {}, StateExt>\n              : {}\n            : {}\n        >\n      : never\n\n/**\n * Helper type. Passes T out again, but boxes it in a way that it cannot\n * \"widen\" the type by accident if it is a generic that should be inferred\n * from elsewhere.\n *\n * @internal\n */\nexport type NoInfer<T> = [T][T extends any ? 0 : never]\n\nexport type NonUndefined<T> = T extends undefined ? never : T\n\nexport type WithRequiredProp<T, K extends keyof T> = Omit<T, K> &\n  Required<Pick<T, K>>\n\nexport type WithOptionalProp<T, K extends keyof T> = Omit<T, K> &\n  Partial<Pick<T, K>>\n\nexport interface TypeGuard<T> {\n  (value: any): value is T\n}\n\nexport interface HasMatchFunction<T> {\n  match: TypeGuard<T>\n}\n\nexport const hasMatchFunction = <T>(\n  v: Matcher<T>,\n): v is HasMatchFunction<T> => {\n  return v && typeof (v as HasMatchFunction<T>).match === 'function'\n}\n\n/** @public */\nexport type Matcher<T> = HasMatchFunction<T> | TypeGuard<T>\n\n/** @public */\nexport type ActionFromMatcher<M extends Matcher<any>> =\n  M extends Matcher<infer T> ? T : never\n\nexport type Id<T> = { [K in keyof T]: T[K] } & {}\n\nexport type Tail<T extends any[]> = T extends [any, ...infer Tail]\n  ? Tail\n  : never\n\nexport type UnknownIfNonSpecific<T> = {} extends T ? unknown : T\n\n/**\n * A Promise that will never reject.\n * @see https://github.com/reduxjs/redux-toolkit/issues/4101\n */\nexport type SafePromise<T> = Promise<T> & {\n  __linterBrands: 'SafePromise'\n}\n\n/**\n * Properly wraps a Promise as a {@link SafePromise} with .catch(fallback).\n */\nexport function asSafePromise<Resolved, Rejected>(\n  promise: Promise<Resolved>,\n  fallback: (error: unknown) => Rejected,\n) {\n  return promise.catch(fallback) as SafePromise<Resolved | Rejected>\n}\n"
  },
  {
    "path": "packages/toolkit/src/uncheckedindexed.ts",
    "content": "// inlined from https://github.com/EskiMojo14/uncheckedindexed\n// relies on remaining as a TS file, not .d.ts\ntype IfMaybeUndefined<T, True, False> = [undefined] extends [T] ? True : False\n\nconst testAccess = ({} as Record<string, 0>)['a']\n\nexport type IfUncheckedIndexedAccess<True, False> = IfMaybeUndefined<\n  typeof testAccess,\n  True,\n  False\n>\n\nexport type UncheckedIndexedAccess<T> = IfUncheckedIndexedAccess<\n  T | undefined,\n  T\n>\n"
  },
  {
    "path": "packages/toolkit/src/utils.ts",
    "content": "import { createNextState, isDraftable } from './immerImports'\n\nexport function getTimeMeasureUtils(maxDelay: number, fnName: string) {\n  let elapsed = 0\n  return {\n    measureTime<T>(fn: () => T): T {\n      const started = Date.now()\n      try {\n        return fn()\n      } finally {\n        const finished = Date.now()\n        elapsed += finished - started\n      }\n    },\n    warnIfExceeded() {\n      if (elapsed > maxDelay) {\n        console.warn(`${fnName} took ${elapsed}ms, which is more than the warning threshold of ${maxDelay}ms. \nIf your state or actions are very large, you may want to disable the middleware as it might cause too much of a slowdown in development mode. See https://redux-toolkit.js.org/api/getDefaultMiddleware for instructions.\nIt is disabled in production builds, so you don't need to worry about that.`)\n      }\n    },\n  }\n}\n\nexport function delay(ms: number) {\n  return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\nexport class Tuple<Items extends ReadonlyArray<unknown> = []> extends Array<\n  Items[number]\n> {\n  constructor(length: number)\n  constructor(...items: Items)\n  constructor(...items: any[]) {\n    super(...items)\n    Object.setPrototypeOf(this, Tuple.prototype)\n  }\n\n  static override get [Symbol.species]() {\n    return Tuple as any\n  }\n\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(\n    items: Tuple<AdditionalItems>,\n  ): Tuple<[...Items, ...AdditionalItems]>\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(\n    items: AdditionalItems,\n  ): Tuple<[...Items, ...AdditionalItems]>\n  override concat<AdditionalItems extends ReadonlyArray<unknown>>(\n    ...items: AdditionalItems\n  ): Tuple<[...Items, ...AdditionalItems]>\n  override concat(...arr: any[]) {\n    return super.concat.apply(this, arr)\n  }\n\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(\n    items: Tuple<AdditionalItems>,\n  ): Tuple<[...AdditionalItems, ...Items]>\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(\n    items: AdditionalItems,\n  ): Tuple<[...AdditionalItems, ...Items]>\n  prepend<AdditionalItems extends ReadonlyArray<unknown>>(\n    ...items: AdditionalItems\n  ): Tuple<[...AdditionalItems, ...Items]>\n  prepend(...arr: any[]) {\n    if (arr.length === 1 && Array.isArray(arr[0])) {\n      return new Tuple(...arr[0].concat(this))\n    }\n    return new Tuple(...arr.concat(this))\n  }\n}\n\nexport function freezeDraftable<T>(val: T) {\n  return isDraftable(val) ? createNextState(val, () => {}) : val\n}\n\nexport function getOrInsert<K extends object, V>(\n  map: WeakMap<K, V>,\n  key: K,\n  value: V,\n): V\nexport function getOrInsert<K, V>(map: Map<K, V>, key: K, value: V): V\nexport function getOrInsert<K extends object, V>(\n  map: Map<K, V> | WeakMap<K, V>,\n  key: K,\n  value: V,\n): V {\n  if (map.has(key)) return map.get(key) as V\n\n  return map.set(key, value).get(key) as V\n}\n\nexport function getOrInsertComputed<K extends object, V>(\n  map: WeakMap<K, V>,\n  key: K,\n  compute: (key: K) => V,\n): V\nexport function getOrInsertComputed<K, V>(\n  map: Map<K, V>,\n  key: K,\n  compute: (key: K) => V,\n): V\nexport function getOrInsertComputed<K extends object, V>(\n  map: Map<K, V> | WeakMap<K, V>,\n  key: K,\n  compute: (key: K) => V,\n): V {\n  if (map.has(key)) return map.get(key) as V\n\n  return map.set(key, compute(key)).get(key) as V\n}\n\nexport function promiseWithResolvers<T>(): {\n  promise: Promise<T>\n  resolve: (value: T | PromiseLike<T>) => void\n  reject: (reason?: any) => void\n} {\n  let resolve: any\n  let reject: any\n  const promise = new Promise<T>((res, rej) => {\n    resolve = res\n    reject = rej\n  })\n  return { promise, resolve, reject }\n}\n"
  },
  {
    "path": "packages/toolkit/tsconfig.base.json",
    "content": "{\n  \"compilerOptions\": {\n    \"allowSyntheticDefaultImports\": true,\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"isolatedModules\": true,\n    \"jsx\": \"react\",\n    \"lib\": [\"DOM\", \"ESNext\"],\n    \"module\": \"esnext\",\n    \"moduleDetection\": \"force\",\n    \"moduleResolution\": \"bundler\",\n    \"noEmit\": true,\n    \"noEmitOnError\": true,\n    \"noErrorTruncation\": true,\n    \"noFallthroughCasesInSwitch\": true,\n    \"noImplicitOverride\": true,\n    \"noImplicitReturns\": true,\n    \"outDir\": \"./dist\",\n    \"paths\": {\n      // internal imports in tests only\n      \"@internal/*\": [\"./src/*\"],\n      \"@reduxjs/toolkit\": [\"./src/index.ts\"], // @remap-prod-remove-line\n      \"@reduxjs/toolkit/query\": [\"./src/query/index.ts\"], // @remap-prod-remove-line\n      \"@reduxjs/toolkit/query/react\": [\"./src/query/react/index.ts\"], // @remap-prod-remove-line\n      \"@reduxjs/toolkit/react\": [\"./src/react/index.ts\"] // @remap-prod-remove-line\n    },\n    \"resolveJsonModule\": true,\n    \"rootDir\": \"./src\",\n    \"skipLibCheck\": true,\n    \"sourceMap\": true,\n    \"strict\": true,\n    \"target\": \"esnext\",\n    \"types\": [\"node\", \"vitest/globals\", \"vitest/importMeta\"],\n    \"useDefineForClassFields\": true,\n    \"useUnknownInCatchVariables\": true\n  }\n}\n"
  },
  {
    "path": "packages/toolkit/tsconfig.build.json",
    "content": "{\n  // For building the library.\n  \"extends\": \"./tsconfig.base.json\",\n  \"compilerOptions\": {\n    \"noEmit\": false\n  },\n  \"include\": [\"src\"],\n  \"exclude\": [\n    \"src/**/*.test.ts*\",\n    \"src/**/*.test-d.ts*\",\n    \"src/**/*.spec.ts*\",\n    \"src/**/tests/*\",\n    \"src/**/*.typetest.ts*\"\n  ]\n}\n"
  },
  {
    "path": "packages/toolkit/tsconfig.json",
    "content": "{\n  // For general development and intellisense.\n  // Scans the entire source code against the current TS version\n  // we are using during development.\n  \"extends\": \"./tsconfig.test.json\",\n  \"compilerOptions\": {\n    \"rootDir\": \"./\"\n  },\n  \"include\": [\".\"],\n  \"exclude\": [\"dist\", \"scripts/issue-triage\"]\n}\n"
  },
  {
    "path": "packages/toolkit/tsconfig.test.json",
    "content": "{\n  // For runtime and type tests during CI.\n  \"extends\": \"./tsconfig.base.json\",\n  \"compilerOptions\": {\n    \"jsx\": \"react-jsx\"\n  },\n  \"exclude\": [\"dist\"],\n  \"include\": [\n    \"src/**/*.test.ts*\",\n    \"src/**/*.test-d.ts*\",\n    \"src/**/*.spec.ts*\",\n    \"src/**/tests/**/*\",\n    \"src/**/*.typetest.ts*\"\n  ]\n}\n"
  },
  {
    "path": "packages/toolkit/tsup.config.mts",
    "content": "import * as babel from '@babel/core'\nimport type { Plugin } from 'esbuild'\nimport { getBuildExtensions } from 'esbuild-extra'\nimport fs from 'node:fs/promises'\nimport path from 'node:path'\nimport type { Options as TsupOptions } from 'tsup'\nimport { defineConfig } from 'tsup'\nimport type { MangleErrorsPluginOptions } from './scripts/mangleErrors.mjs'\nimport { mangleErrorsPlugin } from './scripts/mangleErrors.mjs'\n\nconst outputDir = path.join(import.meta.dirname, 'dist')\n\nasync function writeCommonJSEntry(folder: string, prefix: string) {\n  await fs.writeFile(\n    path.join(folder, 'index.js'),\n    `'use strict'\nif (process.env.NODE_ENV === 'production') {\n  module.exports = require('./${prefix}.production.min.cjs')\n} else {\n  module.exports = require('./${prefix}.development.cjs')\n}`,\n    { encoding: 'utf-8' },\n  )\n}\n\n// Extract error strings, replace them with error codes, and write messages to a file\nconst mangleErrorsTransform: Plugin = {\n  name: mangleErrorsPlugin.name,\n  setup(build) {\n    const { onTransform } = getBuildExtensions(build, mangleErrorsPlugin.name)\n\n    onTransform({ loaders: ['ts', 'tsx'] }, async (args) => {\n      try {\n        const res = await babel.transformAsync(args.code, {\n          parserOpts: {\n            plugins: ['typescript', 'jsx'],\n          },\n          plugins: [\n            [\n              mangleErrorsPlugin,\n              { minify: false } satisfies MangleErrorsPluginOptions,\n            ],\n          ],\n        })\n\n        if (res == null) {\n          throw new Error('Babel transformAsync returned null')\n        }\n\n        return {\n          code: res.code!,\n          map: res.map!,\n        }\n      } catch (err) {\n        console.error('Babel mangleErrors error: ', err)\n        return null\n      }\n    })\n  },\n}\n\nexport default defineConfig((overrideOptions): TsupOptions[] => {\n  const commonOptions = {\n    splitting: false,\n    sourcemap: true,\n    tsconfig: path.join(import.meta.dirname, 'tsconfig.build.json'),\n    external: [\n      'redux',\n      'react',\n      'react-redux',\n      'immer',\n      'redux-thunk',\n      'reselect',\n    ],\n    esbuildPlugins: [mangleErrorsTransform],\n    format: ['cjs', 'esm'],\n    target: ['esnext'],\n    ...overrideOptions,\n  } satisfies TsupOptions\n\n  return [\n    {\n      ...commonOptions,\n      name: 'Redux-Toolkit-Core-ESM',\n      entry: {\n        'redux-toolkit.modern': 'src/index.ts',\n      },\n      outExtension: () => ({ js: '.mjs' }),\n      format: ['esm'],\n    },\n    {\n      ...commonOptions,\n      name: 'Redux-Toolkit-Nested-ESM',\n      external: commonOptions.external.concat('@reduxjs/toolkit'),\n      entry: {\n        'react/redux-toolkit-react.modern': 'src/react/index.ts',\n        'query/rtk-query.modern': 'src/query/index.ts',\n        'query/react/rtk-query-react.modern': 'src/query/react/index.ts',\n      },\n      outExtension: () => ({ js: '.mjs' }),\n      format: ['esm'],\n    },\n    {\n      ...commonOptions,\n      name: 'Redux-Toolkit-Core-CJS-Development',\n      entry: {\n        'cjs/redux-toolkit.development': 'src/index.ts',\n      },\n      outExtension: () => ({ js: '.cjs' }),\n      env: {\n        NODE_ENV: 'development',\n      },\n      format: ['cjs'],\n    },\n    {\n      ...commonOptions,\n      name: 'Redux-Toolkit-Nested-CJS-Development',\n      external: commonOptions.external.concat('@reduxjs/toolkit'),\n      entry: {\n        'react/cjs/redux-toolkit-react.development': 'src/react/index.ts',\n        'query/cjs/rtk-query.development': 'src/query/index.ts',\n        'query/react/cjs/rtk-query-react.development':\n          'src/query/react/index.ts',\n      },\n      outExtension: () => ({ js: '.cjs' }),\n      env: {\n        NODE_ENV: 'development',\n      },\n      format: ['cjs'],\n    },\n    {\n      ...commonOptions,\n      name: 'Redux-Toolkit-Core-CJS-Production',\n      entry: {\n        'cjs/redux-toolkit.production.min': 'src/index.ts',\n      },\n      outExtension: () => ({ js: '.cjs' }),\n      env: {\n        NODE_ENV: 'production',\n      },\n      minify: true,\n      replaceNodeEnv: true,\n      format: ['cjs'],\n      onSuccess: async () => {\n        await writeCommonJSEntry(\n          path.join(import.meta.dirname, 'dist', 'cjs'),\n          'redux-toolkit',\n        )\n      },\n    },\n\n    {\n      ...commonOptions,\n      name: 'Redux-Toolkit-Nested-CJS-Production',\n      external: commonOptions.external.concat('@reduxjs/toolkit'),\n      entry: {\n        'react/cjs/redux-toolkit-react.production.min': 'src/react/index.ts',\n        'query/cjs/rtk-query.production.min': 'src/query/index.ts',\n        'query/react/cjs/rtk-query-react.production.min':\n          'src/query/react/index.ts',\n      },\n      outExtension: () => ({ js: '.cjs' }),\n      env: {\n        NODE_ENV: 'production',\n      },\n      minify: true,\n      replaceNodeEnv: true,\n      format: ['cjs'],\n      onSuccess: async () => {\n        await writeCommonJSEntry(\n          path.join(import.meta.dirname, 'dist', 'react', 'cjs'),\n          'redux-toolkit-react',\n        )\n\n        await writeCommonJSEntry(\n          path.join(import.meta.dirname, 'dist', 'query', 'cjs'),\n          'rtk-query',\n        )\n\n        await writeCommonJSEntry(\n          path.join(import.meta.dirname, 'dist', 'query', 'react', 'cjs'),\n          'rtk-query-react',\n        )\n      },\n    },\n\n    {\n      ...commonOptions,\n      name: 'Redux-Toolkit-Core-Browser',\n      entry: {\n        'redux-toolkit.browser': 'src/index.ts',\n      },\n      outExtension: () => ({ js: '.mjs' }),\n      platform: 'browser',\n      env: {\n        NODE_ENV: 'production',\n      },\n      minify: true,\n      define: {\n        process: 'undefined',\n      },\n      replaceNodeEnv: true,\n      format: ['esm'],\n    },\n\n    {\n      ...commonOptions,\n      name: 'Redux-Toolkit-Nested-Browser',\n      external: commonOptions.external.concat('@reduxjs/toolkit'),\n      entry: {\n        'react/redux-toolkit-react.browser': 'src/react/index.ts',\n        'query/rtk-query.browser': 'src/query/index.ts',\n        'query/react/rtk-query-react.browser': 'src/query/react/index.ts',\n      },\n      outExtension: () => ({ js: '.mjs' }),\n      platform: 'browser',\n      env: {\n        NODE_ENV: 'production',\n      },\n      minify: true,\n      define: {\n        process: 'undefined',\n      },\n      replaceNodeEnv: true,\n      format: ['esm'],\n    },\n    {\n      ...commonOptions,\n      name: 'Redux-Toolkit-Core-Legacy-ESM',\n      entry: {\n        'redux-toolkit.legacy-esm': 'src/index.ts',\n      },\n      outExtension: () => ({ js: '.js' }),\n      format: ['esm'],\n      target: ['es2017'],\n      onSuccess: async () => {\n        await fs.copyFile(\n          path.join(import.meta.dirname, 'src', 'uncheckedindexed.ts'),\n          path.join(outputDir, 'uncheckedindexed.ts'),\n        )\n      },\n    },\n    {\n      ...commonOptions,\n      name: 'Redux-Toolkit-Nested-Legacy-ESM',\n      external: commonOptions.external.concat('@reduxjs/toolkit'),\n      entry: {\n        'react/redux-toolkit-react.legacy-esm': 'src/react/index.ts',\n        'query/rtk-query.legacy-esm': 'src/query/index.ts',\n        'query/react/rtk-query-react.legacy-esm': 'src/query/react/index.ts',\n      },\n      outExtension: () => ({ js: '.js' }),\n      format: ['esm'],\n      target: ['es2017'],\n      onSuccess: async () => {\n        await fs.copyFile(\n          path.join(import.meta.dirname, 'src', 'uncheckedindexed.ts'),\n          path.join(outputDir, 'uncheckedindexed.ts'),\n        )\n      },\n    },\n\n    {\n      ...commonOptions,\n      name: 'Redux-Toolkit-Type-Definitions',\n      entry: {\n        index: 'src/index.ts',\n      },\n      dts: {\n        only: true,\n      },\n      external: [/uncheckedindexed/],\n    },\n\n    {\n      ...commonOptions,\n      name: 'RTK-React-Type-Definitions',\n      entry: {\n        'react/index': 'src/react/index.ts',\n      },\n      dts: {\n        only: true,\n      },\n      external: ['@reduxjs/toolkit', /uncheckedindexed/],\n    },\n\n    {\n      ...commonOptions,\n      name: 'RTK-Query-Type-Definitions',\n      entry: {\n        'query/index': 'src/query/index.ts',\n      },\n      dts: {\n        only: true,\n      },\n      external: [\n        '@reduxjs/toolkit',\n        '@reduxjs/toolkit/react',\n        /uncheckedindexed/,\n      ],\n    },\n\n    {\n      ...commonOptions,\n      name: 'RTK-Query-React-Type-Definitions',\n      entry: {\n        'query/react/index': 'src/query/react/index.ts',\n      },\n      dts: {\n        only: true,\n      },\n      external: [\n        '@reduxjs/toolkit',\n        '@reduxjs/toolkit/react',\n        '@reduxjs/toolkit/query',\n        /uncheckedindexed/,\n      ],\n    },\n  ]\n})\n"
  },
  {
    "path": "packages/toolkit/vitest.config.mts",
    "content": "import path from 'node:path'\nimport { fileURLToPath } from 'node:url'\nimport tsconfigPaths from 'vite-tsconfig-paths'\nimport { defineConfig } from 'vitest/config'\n\n// No __dirname under Node ESM\nconst __filename = fileURLToPath(import.meta.url)\nconst __dirname = path.dirname(__filename)\n\nexport default defineConfig({\n  plugins: [tsconfigPaths({ root: __dirname })],\n  test: {\n    globals: true,\n    environment: 'jsdom',\n    setupFiles: ['./vitest.setup.ts'],\n    include: ['./src/**/*.(spec|test).[jt]s?(x)'],\n    server: {\n      deps: {\n        inline: ['redux', '@reduxjs/toolkit'],\n      },\n    },\n    unstubEnvs: true,\n  },\n})\n"
  },
  {
    "path": "packages/toolkit/vitest.setup.ts",
    "content": "import nodeFetch, { Headers, Request } from 'node-fetch'\nimport { server } from './src/query/tests/mocks/server'\n\nvi.stubGlobal('fetch', nodeFetch)\nvi.stubGlobal('Request', Request)\nvi.stubGlobal('Headers', Headers)\n\nbeforeAll(() => {\n  server.listen({ onUnhandledRequest: 'error' })\n})\n\nafterEach(() => {\n  server.resetHandlers()\n})\n\nafterAll(() => {\n  server.close()\n})\n"
  },
  {
    "path": "website/.gitignore",
    "content": "# dependencies\r\nnode_modules/\r\n\r\n# production\r\n/build\r\n\r\n# generated files\r\n.docusaurus/\r\n.cache-loader\r\n\r\n# misc\r\n.DS_Store\r\n.env.local\r\n.env.development.local\r\n.env.test.local\r\n.env.production.local\r\nnpm-debug.log*\r\nyarn-debug.log*\r\nyarn-error.log*\r\n*.log"
  },
  {
    "path": "website/README.md",
    "content": "# Website\n\nThis website is built using Docusaurus 2, a modern static website generator.\n\n### Installation\n\n```\n$ yarn\n```\n\n### Local Development\n\n```\n$ yarn start\n```\n\nThis command starts a local development server and open up a browser window. Most changes are reflected live without having to restart the server.\n\n### Build\n\n```\n$ yarn build\n```\n\nThis command generates static content into the `build` directory and can be served using any static contents hosting service.\n\n### Deployment\n\n```\n$ GIT_USER=<Your GitHub username> USE_SSH=1 yarn deploy\n```\n\nIf you are using GitHub pages for hosting, this command is a convenient way to build the website and push to the `gh-pages` branch.\n"
  },
  {
    "path": "website/_redirects",
    "content": "\n/docs/*          /:splat\n\n# Deleted old tutorials\n/tutorials/basic-tutorial               /tutorials/overview\n/tutorials/intermediate-tutorial        /tutorials/overview\n/tutorials/advanced-tutorial            /tutorials/overview\n\n# Renamed start page\n/introduction/quick-start               /introduction/getting-started\n\n# Relocated content\n/rtk-query/usage/optimistic-updates     /rtk-query/usage/manual-cache-updates#optimistic-updates\n/rtk-query/api/created-api/cache-management-utils     /rtk-query/api/created-api/api-slice-utils\n/migrations/migrating-1.x-to-2.x     /usage/migrating-rtk-2\n"
  },
  {
    "path": "website/docusaurus.config.ts",
    "content": "// site configuration options.\nimport { resolve } from 'path'\nimport { linkDocblocks, transpileCodeblocks } from 'remark-typescript-tools'\nimport type { Options, ThemeConfig } from '@docusaurus/preset-classic'\nimport type { Config } from '@docusaurus/types'\nimport type { Options as UmamiOptions } from '@dipakparmar/docusaurus-plugin-umami'\nimport type { Options as RSDoctorOptions } from '@docusaurus/plugin-rsdoctor'\n\nconst config: Config = {\n  future: {\n    experimental_faster: true,\n  },\n  presets: [\n    [\n      '@docusaurus/preset-classic',\n      {\n        docs: {\n          path: '../docs',\n          sidebarPath: require.resolve('./sidebars'),\n          showLastUpdateTime: true,\n          routeBasePath: '/',\n          editUrl: 'https://github.com/reduxjs/redux-toolkit/blob/master/docs/',\n          include: [\n            '{api,assets,introduction,migrations,rtk-query,tutorials,usage}/**/*.{md,mdx}',\n          ], // no other way to exclude node_modules\n          remarkPlugins: [\n            [\n              linkDocblocks,\n              {\n                extractorSettings: {\n                  tsconfig: resolve(__dirname, '../docs/tsconfig.json'),\n                  basedir: resolve(__dirname, '../packages/toolkit/src'),\n                  rootFiles: [\n                    'index.ts',\n                    'query/index.ts',\n                    'query/createApi.ts',\n                    'query/endpointDefinitions.ts',\n                    'query/react/index.ts',\n                    'query/react/ApiProvider.tsx',\n                    'query/core/buildMiddleware/cacheCollection.ts',\n                  ],\n                },\n              },\n            ],\n            // Only transpile codeblocks in CI, as it's slow\n            process.env.CI\n              ? [\n                  transpileCodeblocks,\n                  {\n                    compilerSettings: {\n                      tsconfig: resolve(__dirname, '../docs/tsconfig.json'),\n                      externalResolutions: {},\n                    },\n                  },\n                ]\n              : null,\n          ].filter(Boolean),\n        },\n        theme: {\n          customCss: require.resolve('./src/css/custom.css'),\n        },\n      } satisfies Options,\n    ],\n  ],\n  projectName: 'redux-toolkit',\n  baseUrl: '/',\n  favicon: 'img/favicon/favicon.ico',\n  tagline:\n    'The official, opinionated, batteries-included toolset for efficient Redux development',\n  title: 'Redux Toolkit',\n  url: 'https://redux-toolkit.js.org',\n  customFields: {\n    repoUrl: 'https://github.com/reduxjs/redux-toolkit',\n  },\n  themes: [require.resolve('@getcanary/docusaurus-theme-search-pagefind')],\n  themeConfig: {\n    tableOfContents: {\n      minHeadingLevel: 2,\n      maxHeadingLevel: 4,\n    },\n    metadata: [{ name: 'twitter:card', content: 'summary' }],\n    prism: {\n      theme: require('./src/js/monokaiTheme.js'),\n    },\n    image: 'img/redux-logo-landscape.png',\n    colorMode: {\n      respectPrefersColorScheme: true,\n    },\n    navbar: {\n      title: 'Redux Toolkit',\n      logo: {\n        alt: 'Redux Logo',\n        src: 'img/redux.svg',\n      },\n      items: [\n        {\n          to: 'introduction/getting-started',\n          label: 'Getting Started',\n          position: 'right',\n        },\n        { to: 'tutorials/overview', label: 'Tutorials', position: 'right' },\n        { to: 'usage/usage-guide', label: 'Usage Guide', position: 'right' },\n        { to: 'api/configureStore', label: 'API', position: 'right' },\n        { to: 'rtk-query/overview', label: 'RTK Query', position: 'right' },\n        {\n          href: 'https://github.com/reduxjs/redux-toolkit',\n          label: 'GitHub',\n          position: 'right',\n        },\n      ],\n    },\n    footer: {\n      style: 'dark',\n      logo: {\n        alt: 'Redux Logo',\n        src: 'img/redux_white.svg',\n      },\n      links: [\n        {\n          title: 'Docs',\n          items: [\n            {\n              label: 'Getting Started',\n              to: 'introduction/getting-started',\n            },\n            {\n              label: 'Tutorials',\n              to: 'tutorials/overview',\n            },\n            {\n              label: 'Usage Guide',\n              to: 'usage/usage-guide',\n            },\n            {\n              label: 'API Reference',\n              to: 'api/configureStore',\n            },\n            { to: 'rtk-query/overview', label: 'RTK Query' },\n          ],\n        },\n        {\n          title: 'Community',\n          items: [\n            {\n              label: 'Stack Overflow',\n              href: 'http://stackoverflow.com/questions/tagged/redux',\n            },\n            {\n              label: 'Discord',\n              href: 'https://discord.gg/0ZcbPKXt5bZ6au5t',\n            },\n          ],\n        },\n        {\n          title: 'More',\n          items: [\n            {\n              label: 'GitHub',\n              href: 'https://www.github.com/reduxjs/redux-toolkit',\n            },\n            {\n              html: `\n                <a href=\"https://www.netlify.com\">\n                  <img\n                    src=\"https://www.netlify.com/img/global/badges/netlify-light.svg\"\n                    alt=\"Deploys by Netlify\"\n                  />\n                </a>\n              `,\n            },\n          ],\n        },\n      ],\n      copyright: `Copyright © 2015–${new Date().getFullYear()} Dan Abramov and the Redux documentation authors.`,\n    },\n    // algolia: {\n    //   appId: 'CK59DFV0FC',\n    //   apiKey: '98e886dfbcde7f7e8ec8d7ff1c2c34c8',\n    //   indexName: 'redux-starter-kit',\n    // },\n  } satisfies ThemeConfig,\n  plugins: [\n    [\n      '@dipakparmar/docusaurus-plugin-umami',\n      {\n        websiteID: '616c102e-05dd-4a74-b63e-01bb52f1bc6c',\n        analyticsDomain: 'redux-docs-umami.up.railway.app',\n        scriptName: 'script.js',\n        dataAutoTrack: true,\n        dataDoNotTrack: true,\n        dataCache: true,\n      } satisfies UmamiOptions,\n    ],\n    process.env.RSDOCTOR === 'true' && ['rsdoctor', {}],\n  ],\n}\n\nexport default config\n"
  },
  {
    "path": "website/package.json",
    "content": "{\n  \"name\": \"website\",\n  \"scripts\": {\n    \"dev\": \"docusaurus start\",\n    \"start\": \"docusaurus start\",\n    \"build\": \"docusaurus build\",\n    \"netlify-build\": \"yarn install && yarn build\",\n    \"swizzle\": \"docusaurus swizzle\",\n    \"publish-gh-pages\": \"docusaurus deploy\",\n    \"deploy\": \"docusaurus deploy\"\n  },\n  \"dependencies\": {\n    \"@dipakparmar/docusaurus-plugin-umami\": \"^2.0.6\",\n    \"@docusaurus/core\": \"3.6.3\",\n    \"@docusaurus/preset-classic\": \"3.6.3\",\n    \"@getcanary/docusaurus-theme-search-pagefind\": \"^1.0.2\",\n    \"@getcanary/web\": \"^1.0.12\",\n    \"classnames\": \"^2.2.6\",\n    \"react\": \"^19.0.0\",\n    \"react-dom\": \"^19.0.0\",\n    \"react-lite-youtube-embed\": \"^2.0.3\",\n    \"typescript\": \"^5.9.3\"\n  },\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  },\n  \"devDependencies\": {\n    \"@docusaurus/faster\": \"^3.6.3\",\n    \"netlify-plugin-cache\": \"^1.0.3\",\n    \"prettier\": \"^3.2.5\",\n    \"remark-typescript-tools\": \"2.0.0-alpha.1\"\n  }\n}\n"
  },
  {
    "path": "website/sidebars.ts",
    "content": "import type { SidebarsConfig } from '@docusaurus/plugin-content-docs'\n\nconst sidebars: SidebarsConfig = {\n  docs: [\n    {\n      type: 'category',\n      label: 'Introduction',\n      collapsed: false,\n      items: [\n        'introduction/getting-started',\n        'introduction/why-rtk-is-redux-today',\n      ],\n    },\n\n    {\n      type: 'category',\n      label: 'Tutorials',\n      collapsed: false,\n      items: [\n        'tutorials/tutorials-overview',\n        'tutorials/quick-start',\n        'tutorials/typescript',\n        'tutorials/rtk-query',\n      ],\n    },\n    {\n      type: 'category',\n      label: 'Using Redux Toolkit',\n      collapsed: false,\n      items: [\n        {\n          type: 'category',\n          label: 'Migrations',\n          items: ['usage/migrating-to-modern-redux', 'usage/migrating-rtk-2'],\n        },\n        'usage/usage-guide',\n        'usage/usage-with-typescript',\n        'usage/immer-reducers',\n        'usage/nextjs',\n      ],\n    },\n    {\n      type: 'category',\n      label: 'API Reference',\n      collapsed: true,\n      items: [\n        {\n          type: 'category',\n          label: 'Store Setup',\n          collapsed: false,\n          items: [\n            'api/configureStore',\n            'api/getDefaultMiddleware',\n            'api/immutabilityMiddleware',\n            'api/serializabilityMiddleware',\n            'api/actionCreatorMiddleware',\n            'api/createListenerMiddleware',\n            'api/createDynamicMiddleware',\n            'api/getDefaultEnhancers',\n            'api/autoBatchEnhancer',\n          ],\n        },\n        {\n          type: 'category',\n          label: 'Reducers and Actions',\n          collapsed: false,\n          items: [\n            'api/createReducer',\n            'api/createAction',\n            'api/createSlice',\n            'api/createAsyncThunk',\n            'api/createEntityAdapter',\n            'api/combineSlices',\n          ],\n        },\n        {\n          type: 'category',\n          label: 'Other',\n          collapsed: false,\n          items: [\n            'api/createSelector',\n            'api/matching-utilities',\n            'api/other-exports',\n            'api/codemods',\n            { type: 'link', label: 'Error Messages', href: '/errors' },\n          ],\n        },\n      ],\n    },\n    {\n      type: 'category',\n      label: 'RTK Query',\n      collapsed: false,\n      items: [\n        'rtk-query/overview',\n        'rtk-query/comparison',\n        'rtk-query/usage/examples',\n        'rtk-query/usage-with-typescript',\n        {\n          type: 'category',\n          label: 'Using RTK Query',\n          collapsed: true,\n          items: [\n            {\n              type: 'category',\n              label: 'Standard Usage',\n              collapsed: false,\n              items: [\n                'rtk-query/usage/queries',\n                'rtk-query/usage/infinite-queries',\n                'rtk-query/usage/mutations',\n                'rtk-query/usage/cache-behavior',\n                'rtk-query/usage/automated-refetching',\n              ],\n            },\n            {\n              type: 'category',\n              label: 'Common Use Cases',\n              collapsed: false,\n              items: [\n                'rtk-query/usage/conditional-fetching',\n                'rtk-query/usage/manual-cache-updates',\n                'rtk-query/usage/error-handling',\n                'rtk-query/usage/pagination',\n                'rtk-query/usage/prefetching',\n                'rtk-query/usage/polling',\n                'rtk-query/usage/customizing-queries',\n                'rtk-query/usage/migrating-to-rtk-query',\n              ],\n            },\n            {\n              type: 'category',\n              label: 'Advanced Use Cases',\n              collapsed: false,\n              items: [\n                'rtk-query/usage/streaming-updates',\n                'rtk-query/usage/code-splitting',\n                'rtk-query/usage/code-generation',\n                'rtk-query/usage/server-side-rendering',\n                'rtk-query/usage/persistence-and-rehydration',\n                'rtk-query/usage/usage-without-react-hooks',\n                'rtk-query/usage/customizing-create-api',\n              ],\n            },\n          ],\n        },\n        {\n          type: 'category',\n          label: 'API Reference',\n          collapsed: true,\n          items: [\n            'rtk-query/api/createApi',\n            'rtk-query/api/fetchBaseQuery',\n            'rtk-query/api/ApiProvider',\n            'rtk-query/api/setupListeners',\n            {\n              type: 'category',\n              label: 'Generated API Slices',\n              collapsed: false,\n              items: [\n                'rtk-query/api/created-api/overview',\n                'rtk-query/api/created-api/redux-integration',\n                'rtk-query/api/created-api/endpoints',\n                'rtk-query/api/created-api/hooks',\n                'rtk-query/api/created-api/code-splitting',\n                'rtk-query/api/created-api/api-slice-utils',\n              ],\n            },\n          ],\n        },\n      ],\n    },\n  ],\n}\n\nexport default sidebars\n"
  },
  {
    "path": "website/src/css/custom.css",
    "content": "/**\n * Any CSS included here will be global. The classic template\n * bundles Infima by default. Infima is a CSS framework designed to\n * work well for content-centric websites.\n */\n\n/* You can override the default Infima variables here. */\n:root {\n  --ifm-color-primary: #764abc;\n  --ifm-color-primary-dark: #6a43a9;\n  --ifm-color-primary-darker: #5e3b96;\n  --ifm-color-primary-darkest: #533484;\n  --ifm-color-primary-light: #845cc3;\n  --ifm-color-primary-lighter: #916ec9;\n  --ifm-color-primary-lightest: #9f80d0;\n\n  --ifm-code-font-size: 95%;\n  --ifm-code-border-radius: 3px;\n  --ifm-code-background: rgba(27, 31, 35, 0.05);\n\n  --ifm-blockquote-color: #ecf4f9;\n  --ifm-blockquote-color-dark: #cbddea;\n  --blockquote-text-color: var(--ifm-font-base-color);\n\n  --ifm-code-padding-vertical: 0.1rem;\n  --ifm-code-padding-horizontal: 0.2rem;\n\n  --ifm-tabs-padding-vertical: 0.2rem;\n  --ifm-tabs-padding-horizontal: 0.4rem;\n\n  --ifm-pre-background: rgb(39, 40, 34);\n  --ifm-alert-color: black;\n\n  --ifm-menu-color-active: var(--ifm-blockquote-color);\n\n  --ra-admonition-color: #ecf4f9;\n  --ra-admonition-color-dark: #2a98b9;\n\n  --ra-admonition-color-important: #2a98b9;\n\n  --ra-admonition-color-success: #f1fdf9;\n  --ra-admonition-color-success-dark: #00bf88;\n\n  --ra-admonition-color-caution: #fffbf5;\n  --ra-admonition-color-caution-dark: #f0ad4e;\n\n  --ra-admonition-color-error: #fff2f2;\n  --ra-admonition-color-error-dark: #d9534f;\n\n  --ra-admonition-icon-color: black !important;\n}\n\n@media screen and (max-width: 996px) {\n  :root {\n    --ifm-font-size-base: 15px;\n  }\n}\n\n@media screen and (min-width: 997px) {\n  :root {\n    --ifm-font-size-base: 17px;\n  }\n}\n\n:root[data-theme='dark'] {\n  --ifm-color-primary: #ba8fff;\n  --ifm-color-primary-dark: #7431ca;\n  --ifm-color-primary-darker: #6d1cac;\n  --ifm-color-primary-darkest: #730c9a;\n  --ifm-color-primary-light: #b97cfd;\n  --ifm-color-primary-lighter: #cc8ffc;\n  --ifm-color-primary-lightest: #fcf2ff;\n  --ifm-blockquote-color: #ecf4f9;\n  --ifm-blockquote-color-dark: #6d1cac;\n  --ifm-menu-color-active: black;\n  --blockquote-text-color: black;\n}\n:root[data-theme='dark'] .hero.hero--primary {\n  --ifm-hero-background-color: #593d88;\n  --ifm-hero-text-color: #ffffff;\n}\n\n.admonition a,\nblockquote a {\n  color: var(--ifm-color-primary-darkest);\n  text-decoration: none;\n}\n.admonition a:hover,\nblockquote a:hover {\n  color: var(--blockquote-text-color);\n}\n\nblockquote {\n  color: var(--blockquote-text-color);\n  background-color: var(--ifm-blockquote-color);\n  border-left: 6px solid var(--ifm-blockquote-color-dark);\n  border-radius: var(--ifm-global-radius);\n}\n\n.docusaurus-highlight-code-line {\n  background-color: rgb(72, 77, 91);\n  display: block;\n  margin: 0 calc(-1 * var(--ifm-pre-padding));\n  padding-top: 0;\n  padding-bottom: 0;\n  padding-left: calc(-0.25em + var(--ifm-pre-padding));\n  padding-right: var(--ifm-pre-padding);\n  border-left: 0.25em solid #1976d2;\n}\ndiv[class*='codeBlockTitle'] {\n  padding: 0.15rem var(--ifm-pre-padding);\n}\n\n:root[data-theme='dark'] .admonition code {\n  color: var(--ifm-blockquote-color);\n}\n\n:root[data-theme='dark'] blockquote code {\n  color: var(--ifm-blockquote-color);\n}\n\ncode {\n  background-color: var(--ifm-color-emphasis-300);\n  border-radius: 0.2rem;\n}\n\na code,\ncode a {\n  background-color: var(--ifm-color-emphasis-200);\n  color: inherit;\n}\n\na.contents__link > code {\n  color: inherit;\n}\n\n.table-of-contents__link--active {\n  font-weight: 500;\n  text-decoration: underline;\n}\n\n.table-of-contents__link:hover > code,\n.table-of-contents__link:hover {\n    color: var(--ifm-color-primary-lightest);\n}\n\na:visited:not(.menu__link, .table-of-contents__link, .navbar__link:not([target=\"_blank\"])) {\n  color: var(--ifm-color-primary);\n}\n.navbar .navbar__inner {\n  flex-wrap: nowrap;\n}\n.navbar .navbar__items {\n  flex: 1 1 auto;\n}\n.footer__logo {\n  width: 50px;\n  height: 50px;\n}\n\n.menu__link {\n  font-weight: normal;\n}\n\n.menu__link--sublist {\n  color: var(--ifm-font-base-color) !important;\n  font-weight: var(--ifm-font-weight-semibold);\n}\n\n.menu__link--active:not(.menu__link--sublist) {\n  background-color: var(--ifm-color-primary);\n}\n\n.menu__link--active:not(.menu__link--sublist) {\n  color: var(--ifm-menu-color-active) !important;\n}\n\n.menu .menu__link.menu__link--sublist:after {\n  transform: rotateZ(180deg);\n  -webkit-transition: -webkit-transform 0.2s linear;\n  transition: -webkit-transform 0.2s linear;\n  transition-property:\n    transform,\n    -webkit-transform;\n  transition-duration: 0.2s, 0.2s;\n  transition-timing-function: linear, linear;\n  transition-delay: 0s, 0s;\n  transition: transform 0.2s linear;\n  transition:\n    transform 0.2s linear,\n    -webkit-transform 0.2s linear;\n  color: var(--ifm-font-base-color) !important;\n}\n\n.menu .menu__list-item.menu__list-item--collapsed .menu__link--sublist:after {\n  transform: rotateZ(90deg);\n}\n\n.codesandbox {\n  width: 100%;\n  height: 500px;\n  border: 0;\n  border-radius: 4px;\n  overflow: hidden;\n}\n\n.admonition {\n  color: black;\n  border-radius: var(--ifm-global-radius);\n  border-left: 6px solid var(--ra-admonition-color-dark);\n}\n\n.admonition.admonition-note,\n.admonition.admonition-info,\n.admonition.admonition-important,\n.admonition.admonition-secondary {\n  --ra-admonition-color: #ecf4f9;\n  background-color: var(--ra-admonition-color);\n}\n\n.admonition.admonition-success,\n.admonition.admonition-tip {\n  background-color: var(--ra-admonition-color-success);\n  border-left-color: var(--ra-admonition-color-success-dark);\n}\n\n.admonition.admonition-caution {\n  background-color: var(--ra-admonition-color-caution);\n  border-left-color: var(--ra-admonition-color-caution-dark);\n}\n\n.admonition.admonition-warning,\n.admonition.admonition-danger {\n  background-color: var(--ra-admonition-color-error);\n  border-left-color: var(--ra-admonition-color-error-dark);\n}\n\n.admonition .admonition-icon svg {\n  fill: black;\n  stroke: black;\n}\n\ntable.checkbox-table tbody td {\n  text-align: center;\n  vertical-align: center;\n}\n\n.diagonal-cell {\n  background: url(\"data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' preserveAspectRatio='none' viewBox='0 0 100 100'><line x1='0' y1='0' x2='100' y2='100' stroke='rgb(218,221,225)' vector-effect='non-scaling-stroke'/></svg>\");\n  background-size: 100% 100%;\n}\n\n.diagonal-cell--content {\n  display: grid;\n  width: max-content;\n  justify-content: space-between;\n  grid-template-columns: repeat(2, 1fr);\n  grid-auto-rows: 1fr;\n}\n\n.diagonal-cell--topRight {\n  grid-column-start: 2;\n  text-align: right;\n}\n\n.diagonal-cell--bottomLeft {\n  grid-column-start: 1;\n}\n\n.migration-guide .typescript-only h4:after {\n  content: ' TYPESCRIPT';\n  color: var(--ifm-color-info);\n  position: relative;\n}\n\n/* course callout on home page */\n.course-callout.home-mid {\n  max-width: 900px;\n  margin: 1rem auto 2rem;\n}\n\ndiv[class*='announcementBar_'] {\n  /* Intentionally override the theme behavior,\n  so that the course banner image is effectively cropped*/ \n  z-index: calc(var(--ifm-z-index-fixed) -1) !important;\n}\n"
  },
  {
    "path": "website/src/js/monokaiTheme.js",
    "content": "module.exports = {\n  plain: {\n    color: '#f8f8f2',\n    backgroundColor: '#272822',\n  },\n  styles: [\n    {\n      types: ['comment', 'prolog', 'doctype', 'cdata'],\n      style: {\n        color: '#778090',\n      },\n    },\n    {\n      types: ['punctuation'],\n      style: {\n        color: '#F8F8F2',\n      },\n    },\n    {\n      types: ['property', 'tag', 'constant', 'symbol', 'deleted'],\n      style: {\n        color: '#F92672',\n      },\n    },\n    {\n      types: ['boolean', 'number'],\n      style: {\n        color: '#AE81FF',\n      },\n    },\n    {\n      types: ['selector', 'attr-name', 'string', 'char', 'builtin', 'inserted'],\n      style: {\n        color: '#a6e22e',\n      },\n    },\n    {\n      types: ['operator', 'entity', 'url', 'variable'],\n      style: {\n        color: '#F8F8F2',\n      },\n    },\n    {\n      types: ['atrule', 'attr-value', 'function'],\n      style: {\n        color: '#E6D874',\n      },\n    },\n    {\n      types: ['keyword'],\n      style: {\n        color: '#F92672',\n      },\n    },\n    {\n      types: ['regex', 'important'],\n      style: {\n        color: '#FD971F',\n      },\n    },\n  ],\n}\n"
  },
  {
    "path": "website/src/pages/errors.js",
    "content": "import React from 'react'\nimport Layout from '@theme/Layout'\nimport { useLocation } from '@docusaurus/router'\nimport useDocusaurusContext from '@docusaurus/useDocusaurusContext'\nimport styles from './styles.module.css'\nimport errorCodes from '../../../errors.json'\n\nfunction Errors() {\n  const location = useLocation()\n  const context = useDocusaurusContext()\n  const { siteConfig = {} } = context\n  const errorCode = new URLSearchParams(location.search).get('code')\n  const error = errorCodes[errorCode]\n\n  return (\n    <Layout\n      title={`${siteConfig.title} - ${siteConfig.tagline}`}\n      description={siteConfig.tagline}\n    >\n      <main className={styles.mainFull}>\n        <h1>Production Error Codes</h1>\n        <p>\n          When Redux Toolkit is built and running in production, error text is\n          replaced by indexed error codes to save on bundle size. These errors\n          will provide a link to this page with more information about the error\n          below.\n        </p>\n        {error && (\n          <React.Fragment>\n            <p>\n              <strong>\n                The full text of the error you just encountered is:\n              </strong>\n            </p>\n            <code className={styles.errorDetails}>{error}</code>\n          </React.Fragment>\n        )}\n\n        <h2>All Error Codes</h2>\n        <table>\n          <thead>\n            <tr>\n              <th>Code</th>\n              <th>Message</th>\n            </tr>\n          </thead>\n          <tbody>\n            {Object.keys(errorCodes).map((code) => (\n              <tr>\n                <td>{code}</td>\n                <td>{errorCodes[code]}</td>\n              </tr>\n            ))}\n          </tbody>\n        </table>\n      </main>\n    </Layout>\n  )\n}\n\nexport default Errors\n"
  },
  {
    "path": "website/src/pages/index.js",
    "content": "import React from 'react'\nimport classnames from 'classnames'\nimport Layout from '@theme/Layout'\nimport Link from '@docusaurus/Link'\nimport useDocusaurusContext from '@docusaurus/useDocusaurusContext'\nimport useBaseUrl from '@docusaurus/useBaseUrl'\nimport styles from './styles.module.css'\n\nconst features = [\n  {\n    content: (\n      <p>\n        Includes utilities to simplify common use cases like{' '}\n        <strong>store setup, creating reducers, immutable update logic</strong>,\n        and more.\n      </p>\n    ),\n    image: (\n      <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 909.83 1100\">\n        <g>\n          <path d=\"M886.9 557.45a78.28 78.28 0 00-63.4-22.52 80.17 80.17 0 00-88-97.47 82.63 82.63 0 001.84-17.46 82 82 0 00-73.86-81.55l139-139A81.94 81.94 0 10686.63 83.5L412.05 358.08c-18.64 18.64-41.11 31.55-65 37.35-17.91 4.35-36 4.4-50.55.28-14.38-22.37-27.88-40.68-30.8-44.6-29.61-40.41-56.89-81.54-88.7-130.88-32.71-50.66-74.06-72.44-113.46-59.73C53 163.89 43 170.07 32.92 179.38 15.06 195.91-1.28 214.46.08 238.15c1 18.15 11.48 34.43 27.29 59.07 9 13.95 20.09 31.32 31.94 53 7.11 13.05 12.46 26.58 18.13 40.91 2.24 5.68 4.57 11.55 7 17.43 7.36 17.61 16.71 40.94 23.81 65.21 11.72 40 5.36 78.49-1.36 119.2-4.85 29.33-9.86 59.66-8 91.42 2.37 40.18 13.66 80.92 33.55 121.08 18.75 37.87 44.15 73 75.49 104.3 57.84 57.84 129 95.64 200.5 106.42a269.83 269.83 0 0040.28 3.1 225.74 225.74 0 0059.29-7.66c32.34-8.77 60.2-24.68 82.8-47.28L820.22 735l66.67-66.67a78.5 78.5 0 00.01-110.88zm-106.08-75.92a50.32 50.32 0 010 71.1l-4.79 4.8-66.67 66.67-4.81 4.81a50.28 50.28 0 11-71.11-71.1l38.16-38.16 38.15-38.15a50.33 50.33 0 0171.07.03zM655.39 368a51.94 51.94 0 0136.73 88.67l-41.77 41.77-38.15 38.18-3.6 3.61a51.94 51.94 0 01-73.46-73.46l35.35-35.36 48.18-48.18A51.61 51.61 0 01655.39 368zm-85.76 575.19c-37.56 37.55-93.2 53-156.68 43.39-65.17-9.84-130.43-44.63-183.77-98q-8-8-15.37-16.27a170.76 170.76 0 0046.47 6.6 151.64 151.64 0 0025.42-2.11c38.61-6.55 69.21-28.22 88.49-62.66A12.48 12.48 0 10352.4 802c-15.68 28-39.53 44.92-70.88 50.24-36.89 6.26-75.64-5.26-99.85-21.42a350.45 350.45 0 01-22.31-38.59c-18.09-36.54-28.35-73.4-30.49-109.54-1.68-28.41 2.85-55.78 7.63-84.76 7-42.24 14.2-85.91.57-132.51-7.52-25.69-17.27-50-24.93-68.36-2.34-5.6-4.61-11.34-6.8-16.89-5.75-14.54-11.7-29.57-19.69-44.24-12.36-22.66-23.82-40.53-33-54.89-12.77-19.91-22-34.3-22.59-44.58-.36-6.35 2.12-15.47 23.26-35 6.79-6.29 13.15-10.33 19.43-12.35 36.16-11.67 67.32 29.3 79 47.45 32.15 49.81 59.73 91.39 89.81 132.41l.07.09c15.41 20.7 56.86 80.6 63.42 108.77a15 15 0 1029.22-6.8c-2.78-11.94-9.63-26.93-18-42.24a144.06 144.06 0 0037.87-4.15c29.22-7.09 56.58-22.75 79.12-45.29l274.58-274.63a51.94 51.94 0 0173.46 73.46L597.45 362l-83.54 83.53a81.91 81.91 0 0075.44 138 80.23 80.23 0 0097.47 88.1A78.28 78.28 0 00709.34 735a78 78 0 0046.11 22.36zm296.06-296.06l-31.32 31.31L799 713.81a48.47 48.47 0 01-68.46 0 48.47 48.47 0 010-68.46l66.71-66.71a48.42 48.42 0 0168.44 68.5z\"></path>\n          <path d=\"M273 168.1a15 15 0 1021.27-21.1l-75-75.78a15 15 0 00-21.32 21.11zM330.86 122.33A15 15 0 00345.48 134a15.31 15.31 0 003.33-.37 15 15 0 0011.31-17.95l-23.58-104a15 15 0 10-29.25 6.63zM413.46 133.22a15 15 0 0019.09-9.22l35-100.73a15 15 0 00-28.34-9.86l-35 100.73a15 15 0 009.25 19.08zM468.54 167.07a15 15 0 0021.09 2.26l83-66.94A15 15 0 10553.82 79l-83.02 67a15 15 0 00-2.26 21.07z\"></path>\n        </g>\n      </svg>\n    ),\n    imageAlign: 'top',\n    title: 'Simple',\n  },\n  {\n    content: (\n      <p>\n        Provides <strong>good defaults for store setup out of the box</strong>,\n        and includes{' '}\n        <strong>the most commonly used Redux addons built-in</strong>.\n      </p>\n    ),\n    image: (\n      <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 91 91\">\n        <path d=\"M69.203 90.954c1.16 0 2.104-.943 2.104-2.105V66.335c5.709-6.025 8.842-13.879 8.842-22.215 0-2.088-.211-4.174-.604-6.207l-.004-.014c-.01-.061-.014-.123-.025-.182a2.06 2.06 0 00-.221-.594c-.002-.004-.002-.01-.002-.012-1.111-2.002-2.689-3.166-2.865-3.293a2.1 2.1 0 00-2.922.475c-.68.938-.473 2.25.459 2.938.006.004.387.309.824.797-2.381 2.465-9.92 8.479-26.879 8.479-15.66 0-24.072-6.082-26.939-8.662.342-.32.676-.57.844-.68a2.105 2.105 0 00-2.275-3.541c-.219.143-2.182 1.443-3.215 3.404l-.012.02-.004.008c-.006.01-.004.02-.008.029a2.095 2.095 0 00-.188.52 32.727 32.727 0 00-.656 6.516c0 .281.006.561.014.834l-9.473 16.41c-.375.652-.375 1.455 0 2.105s1.072 1.051 1.822 1.051h4.916v9.836c0 5.658 4.602 10.262 10.262 10.262h10.799v4.23a2.106 2.106 0 004.209 0v-4.23h5.137a2.105 2.105 0 000-4.209H22.998a6.061 6.061 0 01-6.055-6.053v-11.94a2.103 2.103 0 00-2.104-2.104h-3.373l7.949-13.771a2.09 2.09 0 00.279-1.104s-.01-2.525.027-3.125c4.336 3.369 13.301 8.402 28.188 8.402 15.385 0 23.857-4.617 27.994-7.988.025.463.035.928.035 1.393 0 7.451-2.885 14.457-8.117 19.752l-4.777 3.215a2.1 2.1 0 00-.572 2.918 2.1 2.1 0 002.92.575l1.707-1.148V88.85a2.104 2.104 0 002.104 2.104z\"></path>\n        <path d=\"M21.506 28.792c0 4.555 3.375 8.344 8.006 9.293 1.773 3.059 5.15 4.988 8.939 4.988 4.018 0 7.406-2.156 9.459-5.012 2.051 2.855 5.441 5.012 9.455 5.012 3.791 0 7.168-1.93 8.939-4.988 4.633-.947 8.008-4.738 8.01-9.293 0-4.66-3.588-8.545-8.314-9.381-.957-4.342-5.072-7.619-9.992-7.619-3.301 0-6.232 1.482-8.098 3.768-1.867-2.285-4.799-3.768-8.1-3.768-4.92.006-9.035 3.279-9.994 7.619-4.722.838-8.31 4.721-8.31 9.381zm34.502-12.791c3.305 0 5.996 2.398 5.996 5.344 0 1.525-.74 2.982-2.029 4.002a2.104 2.104 0 002.603 3.303c1.654-1.303 2.803-3.039 3.32-4.957 2.438.682 4.207 2.709 4.207 5.1-.002 2.752-2.314 5.037-5.381 5.318a8.98 8.98 0 01-.617.027 2.102 2.102 0 00-2.104 2.104c0 .195.025.387.076.568-1.119 1.268-2.854 2.055-4.715 2.055-3.004 0-5.568-2.045-6.711-4.363.705-.496 1.518-1.109 2.195-1.719.943.055 1.592.244 2.404.904a2.097 2.097 0 002.959-.306 2.101 2.101 0 00-.305-2.959 8.077 8.077 0 00-2.404-1.375 48.546 48.546 0 001.434-2.967 2.104 2.104 0 10-3.857-1.682c-.615 1.414-1.881 3.986-2.656 4.883a5.531 5.531 0 01-.41.398v-8.334c.001-2.946 2.688-5.344 5.995-5.344zm-26.09 7.691c.518 1.92 1.668 3.658 3.324 4.959a2.1 2.1 0 002.953-.354 2.1 2.1 0 00-.354-2.953c-1.287-1.016-2.027-2.475-2.027-4 0-2.943 2.691-5.342 5.998-5.344 3.305 0 5.992 2.398 5.992 5.344v8.336a5.277 5.277 0 01-.408-.398c-.773-.895-2.043-3.471-2.66-4.885a2.106 2.106 0 00-3.859 1.685c.107.244.693 1.559 1.438 2.961a8.023 8.023 0 00-2.404 1.379 2.104 2.104 0 102.658 3.261c.807-.658 1.455-.848 2.402-.902a23.035 23.035 0 002.193 1.719c-1.143 2.32-3.707 4.363-6.713 4.363-1.859 0-3.592-.785-4.713-2.055a2.105 2.105 0 00-2.027-2.672c-.209 0-.414-.014-.617-.027-3.066-.281-5.379-2.566-5.379-5.318 0-2.39 1.769-4.417 4.203-5.099zM49.449 6.368v-4.02a2.103 2.103 0 10-4.209.001v4.02a2.106 2.106 0 004.209-.001zM61.707 11.397c.805 0 1.574-.465 1.924-1.25l1.633-3.672a2.104 2.104 0 10-3.845-1.709l-1.631 3.67a2.103 2.103 0 001.919 2.961zM75.059 19.366l2.984-2.697a2.102 2.102 0 00.152-2.971 2.108 2.108 0 00-2.973-.152l-2.984 2.697a2.106 2.106 0 001.411 3.666 2.1 2.1 0 001.41-.543zM81.756 32.429l3.822-1.25a2.105 2.105 0 001.348-2.652 2.109 2.109 0 00-2.656-1.348l-3.822 1.246a2.104 2.104 0 00.654 4.105c.216 0 .437-.031.654-.101zM14.514 29.294l-3.834-1.207a2.105 2.105 0 10-1.266 4.014l3.832 1.209a2.103 2.103 0 002.641-1.377 2.106 2.106 0 00-1.373-2.639zM19.385 14.249c-.873-.77-2.203-.686-2.973.184s-.688 2.197.184 2.969l3.012 2.664c.4.354.896.527 1.395.527a2.1 2.1 0 001.576-.709 2.108 2.108 0 00-.182-2.973l-3.012-2.662zM32.717 11.776a2.102 2.102 0 001.912-2.98L32.957 5.14a2.105 2.105 0 00-3.828 1.75l1.674 3.658a2.1 2.1 0 001.914 1.228z\"></path>\n      </svg>\n    ),\n    imageAlign: 'top',\n    title: 'Opinionated',\n  },\n  {\n    content: (\n      <p>\n        Takes inspiration from libraries like Immer and Autodux to let you{' '}\n        <strong>write \"mutative\" immutable update logic</strong>, and even{' '}\n        <strong>create entire \"slices\" of state automatically</strong>.\n      </p>\n    ),\n    image: (\n      <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 100 100\">\n        <path\n          style={{\n            WebkitTextIndent: '0',\n            textIndent: '0',\n            WebkitTextTransform: 'none',\n            textTransform: 'none',\n            blockProgression: 'tb',\n          }}\n          d=\"M53.533 6.597c2.042 2.05 3.013 5.112 3.55 8.343.536 3.23.562 6.64 0 9.467a2.028 2.028 0 01-.966 1.343l-1.9 1.125c-.091 2.268-.183 4.979-1.307 6.593-.658.914-1.707 1.412-2.647 1.531-.94.119-1.83-.042-2.677-.344a7.946 7.946 0 01-3.145-2.062c-2.365 1.102-4.484 1.457-7.255 1.344v2.406c3.414 4.348 6.774 9.622 8.936 16.216 5.034-4.604 10.001-7.54 16.004-7.562 8.495.01 15.049 3.541 19.367 8.28C85.816 58.023 88 63.902 88 68.994c0 5.62-.511 10.328-3.051 14.435-2.54 4.107-6.941 7.324-14.105 10.405-.311.136-.658.19-.996.156-14.14-2.055-28.393-2.891-42.625-4-4.605-.07-8.17-1.817-8.936-5.717l-.934-6.655c-6.805-10.63-5.876-20.344-3.954-31.246 2.186-10.62 3.737-19.463 6.289-28.87.515-2.999 2.451-4.297 5.137-5.5 8.604-3.364 18.538-5.92 27.307-5.998.542-.04 1.06.254 1.4.593zm-2.398 3.5c-8.865.513-16.85 2.108-24.69 5.561-1.925.674-2.47 1.316-2.896 2.875-2.353 9.427-4.696 20.033-6.227 28.558-1.378 6.876-1.403 14.71.124 20.997.143-2.863.945-5.706 3.799-8.093-.527 10.113-.446 13.848.903 23.372.603 1.91 2.434 2.643 5.23 2.624 14.19.634 28.232 2.3 42.314 3.968 6.494-2.847 9.994-5.551 11.894-8.623 1.04-1.681 1.639-3.577 1.993-5.78-3.414-.412-6.983-.95-8.19-2.594-9.657 5.227-22.04 6-26.247.03 15.444 4.844 31.809-2.505 32.818-12.06a21.662 21.662 0 00-3.394-4.968c-3.648-4.003-9.04-6.967-16.471-6.967-6.954-.051-10.942 4.564-14.696 7.748 1.422 10.833-1.594 16.348-8.22 18.248 9.027-12.705 2.617-26.423-5.542-36.745-.28-.351-.436-.8-.436-1.25v-3.78c-.975-.577-1.73-1.204-2.273-2.156-.478-.837-.632-1.684-.685-2.594-2.58-.185-4.962-1.018-5.013-3.468 8.967 4 7.97-4 8.967-4 .997 0 .437 4.081.997 5.031.243.688.752 1.297 1.338 1.969-1.226-.304-2.102-.814-2.273.281.022 1.04.479 1.674 1.433 1.718 1.636-.01 3.002-.061 4.483-.28-.01-5.851-.145-8.01-1.992-11.718 2.759 0 3.807 4.302 3.954 11.249 1.025-.496 2.025-1.14 3.02-1.719-.006-5.71-.082-7.944-.996-12.53 2.498 4.18 2.89 7.07 2.958 11.374l2.989-1.75c-.2-5.369-1.087-8.232-1.962-12.623 3.056 3.833 3.76 7.666 3.892 11.499l1.183-.688c.307-2.103.349-4.744-.062-7.217-.396-2.382-1.201-4.343-2.024-5.5zM50.108 29.28l-2.024 1.156c.505.389 1.012.49 1.619.594-.033.004.286-.781.405-1.75zm33.626 37.057c-1.787 2.138-4.041 4.003-6.538 5.562 1.334.4 3.202.623 6.756.312.1-2.058.115-3.992-.218-5.874z\"\n          overflow=\"visible\"\n        ></path>\n      </svg>\n    ),\n    imageAlign: 'top',\n    title: 'Powerful',\n  },\n  {\n    content: (\n      <p>\n        Lets you focus on the core logic your app needs, so you can{' '}\n        <strong>do more work with less code</strong>.\n      </p>\n    ),\n    image: (\n      <svg xmlns=\"http://www.w3.org/2000/svg\" viewBox=\"0 0 100 100\">\n        <path d=\"M37.434 25.406H92.54A2.464 2.464 0 0095 22.947a2.463 2.463 0 00-2.46-2.46H37.434a2.463 2.463 0 00-2.459 2.46 2.462 2.462 0 002.459 2.459zM11.18 28.335c.748 1.036 1.853 1.631 3.031 1.631l.127-.002c1.226-.044 2.331-.719 3.03-1.853l10.027-16.233a2.465 2.465 0 00-2.093-3.752c-.86 0-1.644.437-2.094 1.168L14.12 24.003l-4.666-6.46c-.764-1.059-2.369-1.323-3.433-.555a2.444 2.444 0 00-.989 1.602 2.44 2.44 0 00.434 1.832l5.714 7.913zM92.54 51.441H37.434a2.462 2.462 0 00-2.459 2.459 2.463 2.463 0 002.459 2.461H92.54A2.465 2.465 0 0095 53.9a2.463 2.463 0 00-2.46-2.459zM26.593 39.449a2.458 2.458 0 00-3.385.8L14.12 54.957l-4.666-6.46c-.764-1.06-2.369-1.323-3.433-.555a2.444 2.444 0 00-.989 1.602 2.44 2.44 0 00.434 1.832l5.715 7.913c.748 1.036 1.852 1.631 3.03 1.631l.126-.002c1.228-.044 2.332-.719 3.032-1.854l10.026-16.231a2.463 2.463 0 00-.802-3.384zM92.54 82.396H37.434a2.462 2.462 0 00-2.459 2.459 2.463 2.463 0 002.459 2.461H92.54A2.465 2.465 0 0095 84.855a2.463 2.463 0 00-2.46-2.459zM26.593 70.402a2.466 2.466 0 00-1.291-.367c-.86 0-1.644.438-2.094 1.168L14.12 85.911l-4.666-6.46c-.765-1.061-2.371-1.321-3.433-.555a2.442 2.442 0 00-.989 1.604 2.438 2.438 0 00.434 1.83l5.715 7.913c.748 1.036 1.852 1.631 3.03 1.631l.127-.002c1.226-.044 2.331-.72 3.03-1.851l10.027-16.234a2.464 2.464 0 00-.802-3.385z\"></path>\n      </svg>\n    ),\n    imageAlign: 'top',\n    title: 'Effective',\n  },\n]\n\nconst otherLibraries = [\n  {\n    content: 'A predictable state container for JavaScript applications',\n    title: 'Redux',\n    link: 'https://redux.js.org',\n    image: (\n      <svg\n        xmlns=\"http://www.w3.org/2000/svg\"\n        aria-hidden=\"true\"\n        data-icon=\"external-link-square-alt\"\n        data-prefix=\"fas\"\n        viewBox=\"0 0 448 512\"\n      >\n        <path d=\"M448 80v352c0 26.51-21.49 48-48 48H48c-26.51 0-48-21.49-48-48V80c0-26.51 21.49-48 48-48h352c26.51 0 48 21.49 48 48zm-88 16H248.029c-21.313 0-32.08 25.861-16.971 40.971l31.984 31.987L67.515 364.485c-4.686 4.686-4.686 12.284 0 16.971l31.029 31.029c4.687 4.686 12.285 4.686 16.971 0l195.526-195.526 31.988 31.991C358.058 263.977 384 253.425 384 231.979V120c0-13.255-10.745-24-24-24z\"></path>\n      </svg>\n    ),\n  },\n  {\n    content: 'Official React bindings for Redux',\n    title: 'React-Redux',\n    link: 'https://react-redux.js.org',\n    image: (\n      <svg\n        xmlns=\"http://www.w3.org/2000/svg\"\n        aria-hidden=\"true\"\n        data-icon=\"external-link-square-alt\"\n        data-prefix=\"fas\"\n        viewBox=\"0 0 448 512\"\n      >\n        <path d=\"M448 80v352c0 26.51-21.49 48-48 48H48c-26.51 0-48-21.49-48-48V80c0-26.51 21.49-48 48-48h352c26.51 0 48 21.49 48 48zm-88 16H248.029c-21.313 0-32.08 25.861-16.971 40.971l31.984 31.987L67.515 364.485c-4.686 4.686-4.686 12.284 0 16.971l31.029 31.029c4.687 4.686 12.285 4.686 16.971 0l195.526-195.526 31.988 31.991C358.058 263.977 384 253.425 384 231.979V120c0-13.255-10.745-24-24-24z\"></path>\n      </svg>\n    ),\n  },\n]\n\nfunction Home() {\n  const context = useDocusaurusContext()\n  const { siteConfig = {} } = context\n\n  return (\n    <Layout title={siteConfig.title} description={siteConfig.tagline}>\n      <header className={classnames('hero hero--primary', styles.heroBanner)}>\n        <div className=\"container\">\n          <div className={styles.title}>\n            <img\n              src=\"img/redux_white.svg\"\n              alt=\"Redux logo\"\n              width=\"100\"\n              height=\"100\"\n            />\n            <h1 className={`${styles.projectTitle} hero__title`}>\n              {siteConfig.title}\n            </h1>\n          </div>\n          <p className=\"hero__subtitle\">{siteConfig.tagline}</p>\n          <div className={styles.buttons}>\n            <Link\n              className={classnames(\n                'button button--secondary button--lg',\n                styles.getStarted,\n              )}\n              to={useBaseUrl('introduction/getting-started')}\n            >\n              Get Started\n            </Link>\n          </div>\n        </div>\n      </header>\n      <main>\n        {features && features.length && (\n          <section className={styles.features}>\n            <div className={classnames('container', styles.featureBlock)}>\n              <div className=\"row\">\n                {features.map(({ image, title, content }, idx) => (\n                  <div key={idx} className={classnames('col', styles.feature)}>\n                    {image && (\n                      <div className={`text--center ${styles.blockImage}`}>\n                        {image}\n                      </div>\n                    )}\n                    <h2 className={`text--center ${styles.featureTitle}`}>\n                      {title}\n                    </h2>\n                    <div className={styles.featureContent}>{content}</div>\n                  </div>\n                ))}\n              </div>\n            </div>\n          </section>\n        )}\n        <section className=\"course-callout home-mid\">\n          <a href=\"https://redux.dev\">\n            <img\n              src=\"/img/course-callout-mid.svg\"\n              alt=\"Redux.dev - a new course by Mark Erikson + ui.dev - Learn more\"\n            />\n          </a>\n        </section>\n        {otherLibraries && otherLibraries.length && (\n          <section className={styles.features}>\n            <div className=\"container\">\n              <div className=\"row\">\n                <div className=\"col\">\n                  <h2 className={`text--center ${styles.secondTitle}`}>\n                    Other Libraries from the Redux Team\n                  </h2>\n                </div>\n              </div>\n              <div className=\"row\">\n                {otherLibraries.map(({ image, title, content, link }, idx) => (\n                  <div\n                    key={idx}\n                    className={classnames('col col--6', styles.feature)}\n                  >\n                    <h2 className=\"text--center\">\n                      <a href={link} className={styles.featureAnchor}>\n                        {title}\n                        {image}\n                      </a>\n                    </h2>\n                    <p className=\"text--center\">{content}</p>\n                  </div>\n                ))}\n              </div>\n            </div>\n          </section>\n        )}\n      </main>\n    </Layout>\n  )\n}\n\nexport default Home\n"
  },
  {
    "path": "website/src/pages/styles.module.css",
    "content": "/**\n * CSS files with the .module.css suffix will be treated as CSS modules\n * and scoped locally.\n */\n\n.heroBanner {\n  padding: 4rem 0;\n  text-align: center;\n  position: relative;\n  overflow: hidden;\n}\n\n@media screen and (max-width: 966px) {\n  .heroBanner {\n    padding: 2rem;\n  }\n}\n\n.buttons {\n  display: flex;\n  align-items: center;\n  justify-content: center;\n}\n\n.features {\n  display: flex;\n  align-items: center;\n  padding: 2rem 0;\n  width: 100%;\n}\n\n.featureBlock {\n  margin-top: 40px;\n}\n\n.blockImage {\n  margin-bottom: 20px;\n}\n\n.blockImage svg {\n  fill: currentColor;\n  width: 60px;\n  height: 60px;\n}\n\n.featureTitle {\n  font-size: 30px;\n  padding: 10px 0;\n}\n\n@media screen and (max-width: 966px) {\n  .featureContent {\n    text-align: center;\n  }\n}\n\n.title {\n  display: flex;\n  justify-content: center;\n  align-items: center;\n}\n\n.projectTitle {\n  margin: 0.3em 0;\n}\n\n.featureAnchor svg {\n  margin-left: 5px;\n  max-width: 16px;\n  max-height: 16px;\n  fill: currentColor;\n}\n\n.getStarted:hover {\n  background: #fff;\n  color: var(--ifm-color-primary);\n}\n\n.secondTitle {\n  font-size: 30px;\n  margin-bottom: 55px;\n}\n\n.mainFull {\n  padding: 34px 16px;\n  width: 100%;\n  max-width: var(--ifm-container-width);\n  margin: 0px auto;\n}\n.mainFull h1 {\n  font-size: 3rem;\n  color: var(--ifm-heading-color);\n  font-weight: var(--ifm-heading-font-weight);\n  line-height: var(--ifm-heading-line-height);\n}\n\n.mainFull p {\n  margin-bottom: var(--ifm-leading);\n  margin-top: 0;\n}\n\n.errorDetails {\n  color: #ff6464;\n  border-radius: 0.5rem;\n  padding: 1rem;\n  margin: 30px 0;\n  font-weight: bold;\n  background-color: rgba(255, 100, 100, 0.1);\n  display: block;\n}\n"
  },
  {
    "path": "website/src/theme/DocPage/Layout/Main/BraveWarning.js",
    "content": "import React, { useState, useEffect } from 'react'\n\nfunction BraveWarning() {\n  const [isBrave, setIsBrave] = useState(false)\n\n  useEffect(() => {\n    const check = async () => {\n      return (navigator.brave && (await navigator.brave.isBrave())) || false\n    }\n\n    check()\n      .then((isBrave) => {\n        if (isBrave) {\n          setIsBrave(isBrave)\n        }\n      })\n      .catch(console.error)\n  }, [])\n\n  return isBrave && !localStorage.getItem('brave-warning-dismissed') ? (\n    <div className=\"admonition admonition-caution alert alert--warning\">\n      <div className=\"admonition-heading\">\n        <h5>\n          <span className=\"admonition-icon\">\n            <svg\n              xmlns=\"http://www.w3.org/2000/svg\"\n              width=\"16\"\n              height=\"16\"\n              viewBox=\"0 0 16 16\"\n            >\n              <path\n                fill-rule=\"evenodd\"\n                d=\"M8.893 1.5c-.183-.31-.52-.5-.887-.5s-.703.19-.886.5L.138 13.499a.98.98 0 0 0 0 1.001c.193.31.53.501.886.501h13.964c.367 0 .704-.19.877-.5a1.03 1.03 0 0 0 .01-1.002L8.893 1.5zm.133 11.497H6.987v-2.003h2.039v2.003zm0-3.004H6.987V5.987h2.039v4.006z\"\n              ></path>\n            </svg>\n          </span>\n          Brave Browser Warning\n        </h5>\n      </div>\n      <div className=\"admonition-content\">\n        <p>\n          It appears that you're using Brave - that's awesome. We recommend\n          disabling shields for this domain as well as CodeSandbox in the event\n          that the examples do not load correctly.\n        </p>\n        <button\n          className=\"button button--warning button--md\"\n          onClick={() => {\n            localStorage.setItem('brave-warning-dismissed', true)\n            setIsBrave(false)\n          }}\n        >\n          Dismiss\n        </button>\n      </div>\n    </div>\n  ) : null\n}\n\nexport default BraveWarning\n"
  },
  {
    "path": "website/src/theme/DocPage/Layout/Main/index.tsx",
    "content": "import type { ComponentProps, JSX } from 'react'\nimport React from 'react'\nimport Main from '@theme-original/DocPage/Layout/Main'\nimport type MainType from '@theme-original/DocPage/Layout/Main'\nimport BraveWarning from './BraveWarning'\n\ntype Props = ComponentProps<typeof MainType>\n\nexport default function MainWrapper(props: Props): JSX.Element {\n  return (\n    <>\n      <Main {...props}>\n        <BraveWarning />\n        {props.children}\n      </Main>\n    </>\n  )\n}\n"
  }
]