[
  {
    "path": ".dockerignore",
    "content": ".git\r\ndist\r\nnode_modules\r\n.cache"
  },
  {
    "path": ".github/workflows/ci.yaml",
    "content": "name: CI\n\non:\n  push:\n    branches:\n      - master\n  pull_request:\n    branches:\n      - master\n\njobs:\n  ci:\n    name: CI\n    runs-on: ${{ matrix.os }}\n    env:\n      NPM_CONFIG_MIN_RELEASE_AGE: 0\n\n    strategy:\n      matrix:\n        node-version: ['25.8.2']\n        os: [ubuntu-latest, ubuntu-24.04-arm]\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v5\n\n      - name: Use Node.js v${{ matrix.node-version }}\n        uses: actions/setup-node@v5\n        with:\n          node-version: ${{ matrix.node-version }}\n\n      - name: Install Dependencies And Compile TS\n        run: npm ci --ignore-scripts\n\n      - name: Verify Registry Signatures\n        run: npm audit signatures\n\n      - name: Audit Production Dependencies\n        run: npm audit --omit=dev --audit-level=critical\n\n      - name: Check Code Format\n        run: npm run check-format\n\n      - name: Run Tests\n        run: npm run test\n"
  },
  {
    "path": ".github/workflows/npm_audit.yaml",
    "content": "name: Full NPM Audit\n\non:\n  schedule:\n    - cron: '20 3 * * *'\n  workflow_dispatch:\n\npermissions:\n  contents: read\n\njobs:\n  audit:\n    name: Full NPM Audit Report\n    runs-on: ubuntu-latest\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v6\n\n      - name: Use Node.js v25.8.2\n        uses: actions/setup-node@v6\n        with:\n          node-version: 25.8.2\n\n      - name: Generate Full Audit Report\n        id: audit\n        run: |\n          set +e\n          npm audit --package-lock-only --json > npm-audit.json\n          exit_code=$?\n          set -e\n          if [ ! -f npm-audit.json ]; then\n            echo '{}' > npm-audit.json\n          fi\n          echo \"exit_code=$exit_code\" >> \"$GITHUB_OUTPUT\"\n\n      - name: Upload Audit Report\n        uses: actions/upload-artifact@v4\n        with:\n          name: npm-audit-report\n          path: npm-audit.json\n\n      - name: Summarize Audit Report\n        env:\n          AUDIT_EXIT_CODE: ${{ steps.audit.outputs.exit_code }}\n        run: |\n          node --input-type=module <<'EOF'\n          import fs from 'node:fs';\n\n          const report = JSON.parse(fs.readFileSync('npm-audit.json', 'utf8'));\n          const vulnerabilities = report.metadata?.vulnerabilities ?? {};\n          const lines = [\n            `Full npm audit exit code: ${process.env.AUDIT_EXIT_CODE}`,\n            `info: ${vulnerabilities.info ?? 0}`,\n            `low: ${vulnerabilities.low ?? 0}`,\n            `moderate: ${vulnerabilities.moderate ?? 0}`,\n            `high: ${vulnerabilities.high ?? 0}`,\n            `critical: ${vulnerabilities.critical ?? 0}`,\n            `total: ${vulnerabilities.total ?? 0}`,\n            '',\n            'Download the npm-audit-report artifact for the full JSON report.'\n          ];\n\n          fs.appendFileSync(process.env.GITHUB_STEP_SUMMARY, `${lines.join('\\n')}\\n`);\n          EOF\n"
  },
  {
    "path": ".github/workflows/publish.yaml",
    "content": "name: Publish New Release To NPM And Image To Docker Hub\n\non:\n  release:\n    # This specifies that the build will be triggered when we publish a release\n    types: [published]\n\npermissions:\n  id-token: write\n  contents: write\n\njobs:\n  publish:\n    name: Publish New Release To NPM And Image To Docker Hub\n    runs-on: ubuntu-latest\n    env:\n      IMAGE_NAME: tardisdev/tardis-machine\n      NPM_CONFIG_MIN_RELEASE_AGE: 0\n\n    steps:\n      - name: Checkout\n        uses: actions/checkout@v5\n        with:\n          ref: ${{ github.event.release.target_commitish }}\n\n      - name: Use Node.js v25.8.2\n        uses: actions/setup-node@v5\n        with:\n          node-version: 25.8.2\n          registry-url: https://registry.npmjs.org/\n\n      - name: Install Dependencies And Compile TS\n        run: npm ci --ignore-scripts\n\n      - name: Verify Registry Signatures\n        run: npm audit signatures\n\n      - name: Audit Production Dependencies\n        run: npm audit --omit=dev --audit-level=critical\n\n      - name: Configure Git\n        run: git config --global user.name \"GitHub Release Bot\"\n\n      - name: Update package version\n        run: npm version ${{ github.event.release.tag_name }}\n\n      - name: Run Tests\n        run: npm run test\n\n      - name: Publish Package\n        run: npm publish\n\n      - name: Push Version Changes To GitHub\n        run: git push\n\n      - name: Set Up QEMU\n        uses: docker/setup-qemu-action@v4\n\n      - name: Set Up Docker Buildx\n        uses: docker/setup-buildx-action@v4\n\n      - name: Login To Docker Hub\n        uses: docker/login-action@v4\n        with:\n          username: ${{ secrets.DOCKERHUB_USERNAME }}\n          password: ${{ secrets.DOCKERHUB_TOKEN }}\n\n      - name: Build And Push Docker Image\n        uses: docker/build-push-action@v6\n        with:\n          context: .\n          platforms: linux/amd64,linux/arm64\n          push: true\n          build-args: VERSION_ARG=${{ github.event.release.tag_name }}\n          tags: |\n            ${{ env.IMAGE_NAME }}:${{ github.event.release.tag_name }}\n            ${{ env.IMAGE_NAME }}:latest\n\n      - name: Logout From Docker Hub\n        run: docker logout\n        if: ${{ always() }}\n        continue-on-error: true\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\n/dist\n/*.log\n.tardis-cache\n*.tsbuildinfo\nbench\n.cache\n.DS_Store\n"
  },
  {
    "path": ".npmrc",
    "content": "min-release-age=1\nallow-git=all\n"
  },
  {
    "path": ".prettierignore",
    "content": "package.json\npackage-lock.json\nyarn.lock\ndist"
  },
  {
    "path": ".prettierrc",
    "content": "{\n  \"printWidth\": 140,\n  \"semi\": false,\n  \"singleQuote\": true,\n  \"trailingComma\": \"none\",\n  \"endOfLine\": \"lf\"\n}\n"
  },
  {
    "path": "AGENTS.md",
    "content": "# tardis-machine\n\nPublic npm package and Docker image. Locally runnable server providing HTTP and WebSocket APIs for tick-level historical market data replay and consolidated real-time cryptocurrency market data streaming. Uses `tardis-dev` under the hood.\n\n## Build & Test\n\n```bash\nnpm run build          # tsc\nnpm test               # build + jest\nnpm run check-format   # prettier check\n```\n\n## Editing Rules\n\n- Keep API behavior compatible with public docs — this is a published npm package\n- Preserve backpressure handling in WebSocket paths\n- Maintain mapper correctness in `src/ws/subscriptionsmappers.ts`\n- Avoid heavy synchronous logic on request paths\n- **Format after every edit** — run `npx prettier --write` on modified files after each change\n\n## Validation\n\n- `npm run build && npm test`\n- `npm run check-format`\n\n## Operational Docs\n\n- [ARCHITECTURE.md](ARCHITECTURE.md) — dual-server design, HTTP/WS routing, session management\n\n## Publishing\n\nPublished via GitHub Actions (`publish.yaml`). Do not publish manually unless explicitly requested.\n\n## Keeping Docs Current\n\nWhen you change code, check if any docs in this repo become stale as a result — if so, update them. When following a workflow doc, if the steps don't match reality, fix the doc so the next run is better.\n"
  },
  {
    "path": "ARCHITECTURE.md",
    "content": "# Architecture\n\ntardis-machine is a local server that wraps `tardis-dev` library functionality in HTTP and WebSocket APIs.\n\n## Dual-Server Design\n\nThe server runs two listeners: HTTP on port N and WebSocket on port N+1.\n\n- **HTTP** — Node.js `http` module with `find-my-way` router. Endpoints for historical replay (exchange-native and normalized) and health check. Responses are streamed with batched buffering for throughput.\n- **WebSocket** — `uWebSockets.js` for high-performance WebSocket handling with built-in backpressure. Endpoints for historical replay and real-time streaming (exchange-native and normalized).\n\n## Key Concepts\n\n**Replay sessions** — WebSocket replay supports multiple synchronized connections via session keys. Multiple clients can share a replay session and receive synchronized data.\n\n**Subscription mapping** (`src/ws/subscriptionsmappers.ts`) — Translates exchange-native WebSocket subscribe messages into tardis-dev filter format. This enables existing exchange WebSocket clients to connect to tardis-machine and receive historical data as if it were the live exchange.\n\n**Backpressure** — WebSocket paths monitor send buffer pressure and pause data production when a client can't keep up. This prevents memory growth from slow consumers.\n\n**Caching** — Data is cached locally on disk in compressed format via tardis-dev. Subsequent requests for the same data range hit the cache.\n\n## Design Decisions\n\n- **Separate HTTP and WS ports** — Avoids complexity of protocol upgrade handling; uWebSockets.js runs its own event loop\n- **Backpressure-first WS design** — Slow consumers don't cause memory growth; production pauses when send buffer fills\n- **Exchange-native WS compatibility** — Subscription mappers allow existing exchange clients to work against historical data unchanged\n"
  },
  {
    "path": "CLAUDE.md",
    "content": "@AGENTS.md\n"
  },
  {
    "path": "Dockerfile",
    "content": "#\n# uWebSockets.js v20.59.0 requires glibc >= 2.38 for the prebuilt Linux addon.\n# Use the explicit trixie variant to keep the base image on glibc >= 2.38.\nFROM node:25.8.2-trixie-slim\n# version arg contains current git tag\nARG VERSION_ARG\n# install git\nRUN apt-get update && apt-get install -y git\n# install tardis-machine globally (exposes tardis-machine command)\nRUN npm install --global --unsafe-perm tardis-machine@$VERSION_ARG\n\nENV UWS_HTTP_MAX_HEADERS_SIZE=20000\n# run it\nCMD tardis-machine --cache-dir=/.cache\n"
  },
  {
    "path": "LICENSE",
    "content": "Mozilla Public License Version 2.0\n==================================\n\n1. Definitions\n--------------\n\n1.1. \"Contributor\"\n    means each individual or legal entity that creates, contributes to\n    the creation of, or owns Covered Software.\n\n1.2. \"Contributor Version\"\n    means the combination of the Contributions of others (if any) used\n    by a Contributor and that particular Contributor's Contribution.\n\n1.3. \"Contribution\"\n    means Covered Software of a particular Contributor.\n\n1.4. \"Covered Software\"\n    means Source Code Form to which the initial Contributor has attached\n    the notice in Exhibit A, the Executable Form of such Source Code\n    Form, and Modifications of such Source Code Form, in each case\n    including portions thereof.\n\n1.5. \"Incompatible With Secondary Licenses\"\n    means\n\n    (a) that the initial Contributor has attached the notice described\n        in Exhibit B to the Covered Software; or\n\n    (b) that the Covered Software was made available under the terms of\n        version 1.1 or earlier of the License, but not also under the\n        terms of a Secondary License.\n\n1.6. \"Executable Form\"\n    means any form of the work other than Source Code Form.\n\n1.7. \"Larger Work\"\n    means a work that combines Covered Software with other material, in\n    a separate file or files, that is not Covered Software.\n\n1.8. \"License\"\n    means this document.\n\n1.9. \"Licensable\"\n    means having the right to grant, to the maximum extent possible,\n    whether at the time of the initial grant or subsequently, any and\n    all of the rights conveyed by this License.\n\n1.10. \"Modifications\"\n    means any of the following:\n\n    (a) any file in Source Code Form that results from an addition to,\n        deletion from, or modification of the contents of Covered\n        Software; or\n\n    (b) any new file in Source Code Form that contains any Covered\n        Software.\n\n1.11. \"Patent Claims\" of a Contributor\n    means any patent claim(s), including without limitation, method,\n    process, and apparatus claims, in any patent Licensable by such\n    Contributor that would be infringed, but for the grant of the\n    License, by the making, using, selling, offering for sale, having\n    made, import, or transfer of either its Contributions or its\n    Contributor Version.\n\n1.12. \"Secondary License\"\n    means either the GNU General Public License, Version 2.0, the GNU\n    Lesser General Public License, Version 2.1, the GNU Affero General\n    Public License, Version 3.0, or any later versions of those\n    licenses.\n\n1.13. \"Source Code Form\"\n    means the form of the work preferred for making modifications.\n\n1.14. \"You\" (or \"Your\")\n    means an individual or a legal entity exercising rights under this\n    License. For legal entities, \"You\" includes any entity that\n    controls, is controlled by, or is under common control with You. For\n    purposes of this definition, \"control\" means (a) the power, direct\n    or indirect, to cause the direction or management of such entity,\n    whether by contract or otherwise, or (b) ownership of more than\n    fifty percent (50%) of the outstanding shares or beneficial\n    ownership of such entity.\n\n2. License Grants and Conditions\n--------------------------------\n\n2.1. Grants\n\nEach Contributor hereby grants You a world-wide, royalty-free,\nnon-exclusive license:\n\n(a) under intellectual property rights (other than patent or trademark)\n    Licensable by such Contributor to use, reproduce, make available,\n    modify, display, perform, distribute, and otherwise exploit its\n    Contributions, either on an unmodified basis, with Modifications, or\n    as part of a Larger Work; and\n\n(b) under Patent Claims of such Contributor to make, use, sell, offer\n    for sale, have made, import, and otherwise transfer either its\n    Contributions or its Contributor Version.\n\n2.2. Effective Date\n\nThe licenses granted in Section 2.1 with respect to any Contribution\nbecome effective for each Contribution on the date the Contributor first\ndistributes such Contribution.\n\n2.3. Limitations on Grant Scope\n\nThe licenses granted in this Section 2 are the only rights granted under\nthis License. No additional rights or licenses will be implied from the\ndistribution or licensing of Covered Software under this License.\nNotwithstanding Section 2.1(b) above, no patent license is granted by a\nContributor:\n\n(a) for any code that a Contributor has removed from Covered Software;\n    or\n\n(b) for infringements caused by: (i) Your and any other third party's\n    modifications of Covered Software, or (ii) the combination of its\n    Contributions with other software (except as part of its Contributor\n    Version); or\n\n(c) under Patent Claims infringed by Covered Software in the absence of\n    its Contributions.\n\nThis License does not grant any rights in the trademarks, service marks,\nor logos of any Contributor (except as may be necessary to comply with\nthe notice requirements in Section 3.4).\n\n2.4. Subsequent Licenses\n\nNo Contributor makes additional grants as a result of Your choice to\ndistribute the Covered Software under a subsequent version of this\nLicense (see Section 10.2) or under the terms of a Secondary License (if\npermitted under the terms of Section 3.3).\n\n2.5. Representation\n\nEach Contributor represents that the Contributor believes its\nContributions are its original creation(s) or it has sufficient rights\nto grant the rights to its Contributions conveyed by this License.\n\n2.6. Fair Use\n\nThis License is not intended to limit any rights You have under\napplicable copyright doctrines of fair use, fair dealing, or other\nequivalents.\n\n2.7. Conditions\n\nSections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted\nin Section 2.1.\n\n3. Responsibilities\n-------------------\n\n3.1. Distribution of Source Form\n\nAll distribution of Covered Software in Source Code Form, including any\nModifications that You create or to which You contribute, must be under\nthe terms of this License. You must inform recipients that the Source\nCode Form of the Covered Software is governed by the terms of this\nLicense, and how they can obtain a copy of this License. You may not\nattempt to alter or restrict the recipients' rights in the Source Code\nForm.\n\n3.2. Distribution of Executable Form\n\nIf You distribute Covered Software in Executable Form then:\n\n(a) such Covered Software must also be made available in Source Code\n    Form, as described in Section 3.1, and You must inform recipients of\n    the Executable Form how they can obtain a copy of such Source Code\n    Form by reasonable means in a timely manner, at a charge no more\n    than the cost of distribution to the recipient; and\n\n(b) You may distribute such Executable Form under the terms of this\n    License, or sublicense it under different terms, provided that the\n    license for the Executable Form does not attempt to limit or alter\n    the recipients' rights in the Source Code Form under this License.\n\n3.3. Distribution of a Larger Work\n\nYou may create and distribute a Larger Work under terms of Your choice,\nprovided that You also comply with the requirements of this License for\nthe Covered Software. If the Larger Work is a combination of Covered\nSoftware with a work governed by one or more Secondary Licenses, and the\nCovered Software is not Incompatible With Secondary Licenses, this\nLicense permits You to additionally distribute such Covered Software\nunder the terms of such Secondary License(s), so that the recipient of\nthe Larger Work may, at their option, further distribute the Covered\nSoftware under the terms of either this License or such Secondary\nLicense(s).\n\n3.4. Notices\n\nYou may not remove or alter the substance of any license notices\n(including copyright notices, patent notices, disclaimers of warranty,\nor limitations of liability) contained within the Source Code Form of\nthe Covered Software, except that You may alter any license notices to\nthe extent required to remedy known factual inaccuracies.\n\n3.5. Application of Additional Terms\n\nYou may choose to offer, and to charge a fee for, warranty, support,\nindemnity or liability obligations to one or more recipients of Covered\nSoftware. However, You may do so only on Your own behalf, and not on\nbehalf of any Contributor. You must make it absolutely clear that any\nsuch warranty, support, indemnity, or liability obligation is offered by\nYou alone, and You hereby agree to indemnify every Contributor for any\nliability incurred by such Contributor as a result of warranty, support,\nindemnity or liability terms You offer. You may include additional\ndisclaimers of warranty and limitations of liability specific to any\njurisdiction.\n\n4. Inability to Comply Due to Statute or Regulation\n---------------------------------------------------\n\nIf it is impossible for You to comply with any of the terms of this\nLicense with respect to some or all of the Covered Software due to\nstatute, judicial order, or regulation then You must: (a) comply with\nthe terms of this License to the maximum extent possible; and (b)\ndescribe the limitations and the code they affect. Such description must\nbe placed in a text file included with all distributions of the Covered\nSoftware under this License. Except to the extent prohibited by statute\nor regulation, such description must be sufficiently detailed for a\nrecipient of ordinary skill to be able to understand it.\n\n5. Termination\n--------------\n\n5.1. The rights granted under this License will terminate automatically\nif You fail to comply with any of its terms. However, if You become\ncompliant, then the rights granted under this License from a particular\nContributor are reinstated (a) provisionally, unless and until such\nContributor explicitly and finally terminates Your grants, and (b) on an\nongoing basis, if such Contributor fails to notify You of the\nnon-compliance by some reasonable means prior to 60 days after You have\ncome back into compliance. Moreover, Your grants from a particular\nContributor are reinstated on an ongoing basis if such Contributor\nnotifies You of the non-compliance by some reasonable means, this is the\nfirst time You have received notice of non-compliance with this License\nfrom such Contributor, and You become compliant prior to 30 days after\nYour receipt of the notice.\n\n5.2. If You initiate litigation against any entity by asserting a patent\ninfringement claim (excluding declaratory judgment actions,\ncounter-claims, and cross-claims) alleging that a Contributor Version\ndirectly or indirectly infringes any patent, then the rights granted to\nYou by any and all Contributors for the Covered Software under Section\n2.1 of this License shall terminate.\n\n5.3. In the event of termination under Sections 5.1 or 5.2 above, all\nend user license agreements (excluding distributors and resellers) which\nhave been validly granted by You or Your distributors under this License\nprior to termination shall survive termination.\n\n************************************************************************\n*                                                                      *\n*  6. Disclaimer of Warranty                                           *\n*  -------------------------                                           *\n*                                                                      *\n*  Covered Software is provided under this License on an \"as is\"       *\n*  basis, without warranty of any kind, either expressed, implied, or  *\n*  statutory, including, without limitation, warranties that the       *\n*  Covered Software is free of defects, merchantable, fit for a        *\n*  particular purpose or non-infringing. The entire risk as to the     *\n*  quality and performance of the Covered Software is with You.        *\n*  Should any Covered Software prove defective in any respect, You     *\n*  (not any Contributor) assume the cost of any necessary servicing,   *\n*  repair, or correction. This disclaimer of warranty constitutes an   *\n*  essential part of this License. No use of any Covered Software is   *\n*  authorized under this License except under this disclaimer.         *\n*                                                                      *\n************************************************************************\n\n************************************************************************\n*                                                                      *\n*  7. Limitation of Liability                                          *\n*  --------------------------                                          *\n*                                                                      *\n*  Under no circumstances and under no legal theory, whether tort      *\n*  (including negligence), contract, or otherwise, shall any           *\n*  Contributor, or anyone who distributes Covered Software as          *\n*  permitted above, be liable to You for any direct, indirect,         *\n*  special, incidental, or consequential damages of any character      *\n*  including, without limitation, damages for lost profits, loss of    *\n*  goodwill, work stoppage, computer failure or malfunction, or any    *\n*  and all other commercial damages or losses, even if such party      *\n*  shall have been informed of the possibility of such damages. This   *\n*  limitation of liability shall not apply to liability for death or   *\n*  personal injury resulting from such party's negligence to the       *\n*  extent applicable law prohibits such limitation. Some               *\n*  jurisdictions do not allow the exclusion or limitation of           *\n*  incidental or consequential damages, so this exclusion and          *\n*  limitation may not apply to You.                                    *\n*                                                                      *\n************************************************************************\n\n8. Litigation\n-------------\n\nAny litigation relating to this License may be brought only in the\ncourts of a jurisdiction where the defendant maintains its principal\nplace of business and such litigation shall be governed by laws of that\njurisdiction, without reference to its conflict-of-law provisions.\nNothing in this Section shall prevent a party's ability to bring\ncross-claims or counter-claims.\n\n9. Miscellaneous\n----------------\n\nThis License represents the complete agreement concerning the subject\nmatter hereof. If any provision of this License is held to be\nunenforceable, such provision shall be reformed only to the extent\nnecessary to make it enforceable. Any law or regulation which provides\nthat the language of a contract shall be construed against the drafter\nshall not be used to construe this License against a Contributor.\n\n10. Versions of the License\n---------------------------\n\n10.1. New Versions\n\nMozilla Foundation is the license steward. Except as provided in Section\n10.3, no one other than the license steward has the right to modify or\npublish new versions of this License. Each version will be given a\ndistinguishing version number.\n\n10.2. Effect of New Versions\n\nYou may distribute the Covered Software under the terms of the version\nof the License under which You originally received the Covered Software,\nor under the terms of any subsequent version published by the license\nsteward.\n\n10.3. Modified Versions\n\nIf you create software not governed by this License, and you want to\ncreate a new license for such software, you may create and use a\nmodified version of this License if you rename the license and remove\nany references to the name of the license steward (except to note that\nsuch modified license differs from this License).\n\n10.4. Distributing Source Code Form that is Incompatible With Secondary\nLicenses\n\nIf You choose to distribute Source Code Form that is Incompatible With\nSecondary Licenses under the terms of this version of the License, the\nnotice described in Exhibit B of this License must be attached.\n\nExhibit A - Source Code Form License Notice\n-------------------------------------------\n\n  This Source Code Form is subject to the terms of the Mozilla Public\n  License, v. 2.0. If a copy of the MPL was not distributed with this\n  file, You can obtain one at http://mozilla.org/MPL/2.0/.\n\nIf it is not possible or desirable to put the notice in a particular\nfile, then You may include the notice in a location (such as a LICENSE\nfile in a relevant directory) where a recipient would be likely to look\nfor such a notice.\n\nYou may add additional accurate notices of copyright ownership.\n\nExhibit B - \"Incompatible With Secondary Licenses\" Notice\n---------------------------------------------------------\n\n  This Source Code Form is \"Incompatible With Secondary Licenses\", as\n  defined by the Mozilla Public License, v. 2.0."
  },
  {
    "path": "README.md",
    "content": "# Tardis Machine Server\n\n[![Version](https://img.shields.io/npm/v/tardis-machine.svg)](https://www.npmjs.org/package/tardis-machine)\n\n[Tardis Machine](https://docs.tardis.dev/tardis-machine/quickstart) is a locally runnable server with built-in data caching that uses the [Tardis.dev HTTP API](https://docs.tardis.dev/api/http-api-reference) under the hood. It provides both **tick-level historical** and **consolidated real-time cryptocurrency market data** via HTTP and WebSocket APIs. Available via [npm and Docker](https://docs.tardis.dev/tardis-machine/quickstart#installation).\n\n<br/>\n\n## Features\n\n- efficient data replay API endpoints returning historical market data for entire time periods\n\n- [exchange-native market data APIs](https://docs.tardis.dev/tardis-machine/replaying-historical-data#exchange-native-market-data-apis) — tick-by-tick historical replay in exchange-native format via HTTP and WebSocket endpoints. The WebSocket API replays data with the same format and subscribe logic as real-time exchange APIs — existing exchange WebSocket clients can connect to this endpoint.\n\n- [normalized market data APIs](https://docs.tardis.dev/tardis-machine/replaying-historical-data#normalized-market-data-apis) — consistent format across all exchanges via HTTP and WebSocket endpoints. Includes synchronized multi-exchange replay, real-time streaming, customizable order book snapshots and trade bars.\n\n- [seamless switching](https://docs.tardis.dev/tardis-machine/replaying-historical-data#normalized-market-data-apis) between real-time streaming and historical replay\n\n- transparent local data caching (compressed on disk, decompressed on demand)\n\n- support for many cryptocurrency exchanges — see [docs.tardis.dev](https://docs.tardis.dev) for the full list\n\n<br/>\n\n## Documentation\n\n### [See official docs](https://docs.tardis.dev/tardis-machine/quickstart).\n\n<br/>\n"
  },
  {
    "path": "benchmark.js",
    "content": "import { createRequire } from 'node:module'\n\nconst require = createRequire(import.meta.url)\nconst fetch = require('node-fetch')\nconst split2 = require('split2')\nconst WebSocket = require('ws')\n\nconst serialize = (options) => {\n  return encodeURIComponent(JSON.stringify(options))\n}\n\nclass SimpleWebsocketClient {\n  constructor(url, onMessageCB, onOpen) {\n    this._socket = new WebSocket(url)\n    this._socket.on('open', onOpen)\n    this._socket.on('message', onMessageCB)\n    this._socket.on('error', (err) => {\n      console.log('SimpleWebsocketClient error', err)\n    })\n  }\n\n  send(payload) {\n    this._socket.send(JSON.stringify(payload))\n  }\n\n  async closed() {\n    await new Promise((resolve) => {\n      this._socket.on('close', () => {\n        resolve()\n      })\n    })\n  }\n}\n\nconst EXCHANGE = 'bitmex'\nconst SYMBOL = 'XBTUSD'\n\nconst TRADES_AND_BOOK_FILTERS = [\n  {\n    channel: 'trade',\n    symbols: [SYMBOL]\n  },\n  {\n    channel: 'orderBookL2',\n    symbols: [SYMBOL]\n  }\n]\nconst TRADES_AND_BOOK_SUBSCRIPTION_MESSAGES = [\n  {\n    op: 'subscribe',\n    args: [`trade:${SYMBOL}`, `orderBookL2:${SYMBOL}`]\n  }\n]\n\nconst FROM_DATE = '2020-02-01'\nconst TO_DATE = '2020-02-02'\n\nasync function httpReplayBenchmark({ JSONParseResponse }) {\n  const options = {\n    exchange: EXCHANGE,\n    filters: TRADES_AND_BOOK_FILTERS,\n    from: FROM_DATE,\n    to: TO_DATE\n  }\n\n  const response = await fetch(`http://localhost:8000/replay?options=${serialize(options)}`)\n  const messagesStream = response.body.pipe(split2())\n\n  let messagesCount = 0\n  let startTime = new Date()\n  for await (let line of messagesStream) {\n    if (JSONParseResponse) {\n      JSON.parse(line)\n    }\n\n    messagesCount++\n  }\n\n  const elapsedSeconds = (new Date() - startTime) / 1000\n  const messagesPerSecond = Math.round(messagesCount / elapsedSeconds)\n\n  console.log('HTTP /replay finished', {\n    JSONParseResponse,\n    messagesPerSecond,\n    messagesCount,\n    elapsedSeconds\n  })\n}\n\nasync function httpReplayNormalizedBenchmark({ computeTBTBookSnapshots }) {\n  const options = {\n    exchange: EXCHANGE,\n    symbols: [SYMBOL],\n    from: FROM_DATE,\n    to: TO_DATE,\n    dataTypes: ['trade', 'book_change']\n  }\n  if (computeTBTBookSnapshots) {\n    options.dataTypes.push('book_snapshot_50_0ms')\n  }\n\n  const response = await fetch(`http://localhost:8000/replay-normalized?options=${serialize(options)}`)\n  const messagesStream = response.body.pipe(split2())\n\n  let messagesCount = 0\n  let startTime = new Date()\n  for await (let line of messagesStream) {\n    messagesCount++\n  }\n\n  const elapsedSeconds = (new Date() - startTime) / 1000\n  const messagesPerSecond = Math.round(messagesCount / elapsedSeconds)\n\n  console.log('HTTP /replay-normalized finished', {\n    computeTBTBookSnapshots,\n    messagesPerSecond,\n    messagesCount,\n    elapsedSeconds\n  })\n}\n\nasync function wsReplayBenchmark({ JSONParseResponse }) {\n  let messagesCount = 0\n  let startTime\n  const simpleBitmexWSClient = new SimpleWebsocketClient(\n    `ws://localhost:8001/ws-replay?exchange=${EXCHANGE}&from=${FROM_DATE}&to=${TO_DATE}`,\n    (message) => {\n      if (!startTime) {\n        startTime = new Date()\n      }\n      if (JSONParseResponse) {\n        JSON.parse(message)\n      }\n      messagesCount++\n    },\n    () => {\n      for (const sub of TRADES_AND_BOOK_SUBSCRIPTION_MESSAGES) {\n        simpleBitmexWSClient.send(sub)\n      }\n    }\n  )\n\n  await simpleBitmexWSClient.closed()\n\n  const elapsedSeconds = (new Date() - startTime) / 1000\n  const messagesPerSecond = Math.round(messagesCount / elapsedSeconds)\n\n  console.log('WS /ws-replay finished', {\n    JSONParseResponse,\n    messagesPerSecond,\n    messagesCount,\n    elapsedSeconds\n  })\n}\n\nasync function wsReplayNormalizedBenchmark({ computeTBTBookSnapshots }) {\n  const options = {\n    exchange: EXCHANGE,\n    symbols: [SYMBOL],\n    from: FROM_DATE,\n    to: TO_DATE,\n    dataTypes: ['trade', 'book_change']\n  }\n  if (computeTBTBookSnapshots) {\n    options.dataTypes.push('book_snapshot_50_0ms')\n  }\n\n  let messagesCount = 0\n  let startTime\n\n  const simpleBitmexWSClient = new SimpleWebsocketClient(\n    `ws://localhost:8001/ws-replay-normalized?options=${serialize(options)}`,\n    (message) => {\n      if (!startTime) {\n        startTime = new Date()\n      }\n      messagesCount++\n    },\n    () => {}\n  )\n\n  await simpleBitmexWSClient.closed()\n\n  const elapsedSeconds = (new Date() - startTime) / 1000\n  const messagesPerSecond = Math.round(messagesCount / elapsedSeconds)\n\n  console.log('WS /ws-replay-normalized finished', {\n    computeTBTBookSnapshots,\n    messagesPerSecond,\n    messagesCount,\n    elapsedSeconds\n  })\n}\n\nasync function runBenchmarks() {\n  console.log(`tardis-machine benchmark for ${EXCHANGE} from ${FROM_DATE} to ${TO_DATE}`)\n  console.log('\\n')\n\n  await httpReplayBenchmark({ JSONParseResponse: false })\n\n  await httpReplayBenchmark({ JSONParseResponse: true })\n\n  await wsReplayBenchmark({ JSONParseResponse: true })\n\n  await httpReplayNormalizedBenchmark({ computeTBTBookSnapshots: false })\n  await httpReplayNormalizedBenchmark({ computeTBTBookSnapshots: true })\n\n  await wsReplayNormalizedBenchmark({ computeTBTBookSnapshots: false })\n  await wsReplayNormalizedBenchmark({ computeTBTBookSnapshots: true })\n}\n\n// assumes tardis-machine server is running\nrunBenchmarks()\n"
  },
  {
    "path": "bin/tardis-machine.js",
    "content": "#!/usr/bin/env node\nprocess.env.UWS_HTTP_MAX_HEADERS_SIZE = '20000'\nimport { createRequire } from 'node:module'\n\nconst require = createRequire(import.meta.url)\nconst yargs = require('yargs')\nconst os = require('node:os')\nconst path = require('node:path')\nconst cluster = require('node:cluster')\nconst numCPUs = os.cpus().length\nconst isDocker = require('is-docker')\nconst pkg = require('../package.json')\n\nconst DEFAULT_PORT = 8000\nconst argv = yargs\n  .scriptName('tardis-machine')\n  .env('TM_')\n  .strict()\n  .option('api-key', {\n    type: 'string',\n    describe: 'API key for tardis.dev API access'\n  })\n  .option('cache-dir', {\n    type: 'string',\n    describe: 'Local cache dir path ',\n    default: path.join(os.tmpdir(), '.tardis-cache')\n  })\n  .option('clear-cache', {\n    type: 'boolean',\n    describe: 'Clear cache dir on startup',\n    default: false\n  })\n  .option('port', {\n    type: 'number',\n    describe: 'Port to bind server on',\n    default: DEFAULT_PORT\n  })\n  .option('cluster-mode', {\n    type: 'boolean',\n    describe: 'Run tardis-machine as cluster of Node.js processes',\n    default: false\n  })\n  .option('debug', {\n    type: 'boolean',\n    describe: 'Enable debug logs.',\n    default: false\n  })\n  .help()\n  .version()\n  .usage('$0 [options]')\n  .example('$0 --api-key=YOUR_API_KEY')\n  .epilogue('See https://docs.tardis.dev/api/tardis-machine for more information.')\n  .detectLocale(false).argv\n\nconst port = process.env.PORT ? +process.env.PORT : argv['port']\n\nif (argv['debug']) {\n  process.env.DEBUG = 'tardis-dev:machine*,tardis-dev:realtime*'\n}\n\nconst { TardisMachine } = await import('../dist/index.js')\n\nasync function start() {\n  const machine = new TardisMachine({\n    apiKey: argv['api-key'],\n    cacheDir: argv['cache-dir'],\n    clearCache: argv['clear-cache']\n  })\n  let suffix = ''\n\n  const runAsCluster = argv['cluster-mode']\n  if (runAsCluster) {\n    cluster.schedulingPolicy = cluster.SCHED_RR\n\n    suffix = '(cluster mode)'\n    if (cluster.isPrimary) {\n      for (let i = 0; i < numCPUs; i++) {\n        cluster.fork()\n      }\n    } else {\n      await machine.start(port)\n    }\n  } else {\n    await machine.start(port)\n  }\n\n  if (!cluster.isPrimary) {\n    return\n  }\n\n  if (isDocker() && !process.env.RUNKIT_HOST) {\n    console.log(`tardis-machine server v${pkg.version} is running inside Docker container ${suffix}`)\n  } else {\n    console.log(`tardis-machine server v${pkg.version} is running ${suffix}`)\n    console.log(`HTTP port: ${port}`)\n    console.log(`WS port: ${port + 1}`)\n  }\n\n  console.log(`See https://docs.tardis.dev/api/tardis-machine for more information.`)\n}\n\nstart()\n\nprocess\n  .on('unhandledRejection', (reason, p) => {\n    console.error('Unhandled Rejection at Promise', reason, p)\n  })\n  .on('uncaughtException', (err) => {\n    console.error('Uncaught Exception thrown', err)\n    process.exit(1)\n  })\n"
  },
  {
    "path": "package.json",
    "content": "{\n  \"name\": \"tardis-machine\",\n  \"version\": \"16.1.0\",\n  \"engines\": {\n    \"node\": \">=25\"\n  },\n  \"devEngines\": {\n    \"runtime\": {\n      \"name\": \"node\",\n      \"version\": \">=25\"\n    },\n    \"packageManager\": {\n      \"name\": \"npm\",\n      \"version\": \">=11.11.1\"\n    }\n  },\n  \"description\": \"Locally runnable server with built-in data caching, providing both tick-level historical and consolidated real-time cryptocurrency market data via HTTP and WebSocket APIs\",\n  \"main\": \"dist/index.js\",\n  \"source\": \"src/index.ts\",\n  \"types\": \"dist/index.d.ts\",\n  \"type\": \"module\",\n  \"exports\": {\n    \".\": {\n      \"types\": \"./dist/index.d.ts\",\n      \"import\": \"./dist/index.js\",\n      \"default\": \"./dist/index.js\"\n    },\n    \"./package.json\": \"./package.json\"\n  },\n  \"repository\": \"tardis-dev/tardis-machine\",\n  \"homepage\": \"https://github.com/tardis-dev/tardis-machine\",\n  \"scripts\": {\n    \"build\": \"tsc\",\n    \"precommit\": \"lint-staged\",\n    \"test\": \"npm run build && cross-env UWS_HTTP_MAX_HEADERS_SIZE=20000 node --experimental-vm-modules ./node_modules/jest/bin/jest.js --forceExit --runInBand\",\n    \"prepare\": \"npm run build\",\n    \"format\": \"prettier --write .\",\n    \"check-format\": \"prettier --check .\",\n    \"benchmark\": \"node ./benchmark.js\"\n  },\n  \"bin\": {\n    \"tardis-machine\": \"./bin/tardis-machine.js\"\n  },\n  \"files\": [\n    \"src\",\n    \"dist\",\n    \"bin\",\n    \"benchmark.js\"\n  ],\n  \"keywords\": [\n    \"cryptocurrency data feed\",\n    \"market data\",\n    \"api client\",\n    \"crypto markets data replay\",\n    \"historical data\",\n    \"real-time cryptocurrency market data feed\",\n    \"historical cryptocurrency prices\",\n    \"cryptocurrency api\",\n    \"real-time normalized WebSocket cryptocurrency markets data\",\n    \"normalized cryptocurrency market data API\",\n    \"order book reconstruction\",\n    \"market data normalization\",\n    \"cryptocurrency api\",\n    \"cryptocurrency\",\n    \"orderbook\",\n    \"exchange\",\n    \"websocket\",\n    \"realtime\",\n    \"bitmex\",\n    \"binance\",\n    \"trading\",\n    \"high granularity order book data\",\n    \"replay service\",\n    \"historical cryptocurrency market data replay API\"\n  ],\n  \"license\": \"MPL-2.0\",\n  \"dependencies\": {\n    \"debug\": \"^4.4.1\",\n    \"find-my-way\": \"^9.3.0\",\n    \"is-docker\": \"^2.2.1\",\n    \"tardis-dev\": \"^16.1.1\",\n    \"uWebSockets.js\": \"github:uNetworking/uWebSockets.js#v20.59.0\",\n    \"yargs\": \"^17.5.1\"\n  },\n  \"devDependencies\": {\n    \"@types/debug\": \"^4.1.12\",\n    \"@types/jest\": \"^30.0.0\",\n    \"@types/node\": \"^25.5.2\",\n    \"@types/node-fetch\": \"^2.6.13\",\n    \"@types/split2\": \"^4.2.3\",\n    \"@types/ws\": \"^8.18.1\",\n    \"@types/yargs\": \"^17.0.33\",\n    \"cross-env\": \"^10.1.0\",\n    \"husky\": \"^9.1.7\",\n    \"jest\": \"^30.0.5\",\n    \"lint-staged\": \"^16.1.2\",\n    \"node-fetch\": \"^2.6.1\",\n    \"prettier\": \"^3.6.2\",\n    \"split2\": \"^4.2.0\",\n    \"ts-jest\": \"^29.4.0\",\n    \"typescript\": \"^5.9.2\",\n    \"ws\": \"^8.18.3\"\n  },\n  \"lint-staged\": {\n    \"*.{ts}\": [\n      \"prettier --write\",\n      \"git add\"\n    ]\n  },\n  \"jest\": {\n    \"extensionsToTreatAsEsm\": [\n      \".ts\"\n    ],\n    \"moduleNameMapper\": {\n      \"^(\\\\.{1,2}/.*)\\\\.js$\": \"$1\"\n    },\n    \"transform\": {\n      \"\\\\.(ts|tsx)?$\": [\n        \"ts-jest\",\n        {\n          \"useESM\": true,\n          \"tsconfig\": \"./test/tsconfig.json\"\n        }\n      ]\n    },\n    \"testEnvironment\": \"node\"\n  }\n}\n"
  },
  {
    "path": "src/debug.ts",
    "content": "import dbg from 'debug'\nexport const debug = dbg('tardis-dev:machine')\n"
  },
  {
    "path": "src/helpers.ts",
    "content": "import {\n  ComputableFactory,\n  computeBookSnapshots,\n  computeTradeBars,\n  Disconnect,\n  MapperFactory,\n  normalizeBookChanges,\n  NormalizedData,\n  normalizeDerivativeTickers,\n  normalizeLiquidations,\n  normalizeTrades,\n  normalizeOptionsSummary,\n  ReplayNormalizedOptions,\n  StreamNormalizedOptions,\n  normalizeBookTickers\n} from 'tardis-dev'\n\nexport type WithDataType = {\n  dataTypes: string[]\n}\n\nexport type ReplayNormalizedOptionsWithDataType = ReplayNormalizedOptions<any, any> & WithDataType\n\nexport type ReplayNormalizedRequestOptions = ReplayNormalizedOptionsWithDataType | ReplayNormalizedOptionsWithDataType[]\n\nexport type StreamNormalizedOptionsWithDataType = StreamNormalizedOptions<any, any> & WithDataType & { withErrorMessages?: boolean }\n\nexport type StreamNormalizedRequestOptions = StreamNormalizedOptionsWithDataType | StreamNormalizedOptionsWithDataType[]\n\nexport function* getNormalizers(dataTypes: string[]): IterableIterator<MapperFactory<any, any>> {\n  if (dataTypes.includes('trade') || dataTypes.some((dataType) => dataType.startsWith('trade_bar_'))) {\n    yield normalizeTrades\n  }\n  if (\n    dataTypes.includes('book_change') ||\n    dataTypes.some((dataType) => dataType.startsWith('book_snapshot_')) ||\n    dataTypes.some((dataType) => dataType.startsWith('quote'))\n  ) {\n    yield normalizeBookChanges\n  }\n\n  if (dataTypes.includes('derivative_ticker')) {\n    yield normalizeDerivativeTickers\n  }\n\n  if (dataTypes.includes('liquidation')) {\n    yield normalizeLiquidations\n  }\n  if (dataTypes.includes('option_summary')) {\n    yield normalizeOptionsSummary\n  }\n\n  if (dataTypes.includes('book_ticker')) {\n    yield normalizeBookTickers\n  }\n}\n\nfunction getRequestedDataTypes(options: ReplayNormalizedOptionsWithDataType | StreamNormalizedOptionsWithDataType) {\n  return options.dataTypes.map((dataType) => {\n    if (dataType.startsWith('trade_bar_')) {\n      return 'trade_bar'\n    }\n    if (dataType.startsWith('book_snapshot_')) {\n      return 'book_snapshot'\n    }\n\n    if (dataType.startsWith('quote')) {\n      return 'book_snapshot'\n    }\n\n    return dataType\n  })\n}\n\nexport function constructDataTypeFilter(options: (ReplayNormalizedOptionsWithDataType | StreamNormalizedOptionsWithDataType)[]) {\n  const requestedDataTypesPerExchange = options.reduce((prev, current) => {\n    if (prev[current.exchange] !== undefined) {\n      prev[current.exchange] = [...prev[current.exchange], ...getRequestedDataTypes(current)]\n    } else {\n      prev[current.exchange] = getRequestedDataTypes(current)\n    }\n\n    return prev\n  }, {} as any)\n\n  const returnDisconnectMessages = options.some((o) => o.withDisconnectMessages)\n\n  return (message: NormalizedData | Disconnect) => {\n    if (message.type === 'disconnect' && returnDisconnectMessages) {\n      return true\n    }\n\n    return requestedDataTypesPerExchange[message.exchange].includes(message.type)\n  }\n}\n\nconst tradeBarSuffixToKindMap = {\n  ticks: {\n    kind: 'tick',\n    multiplier: 1\n  },\n  ms: {\n    kind: 'time',\n    multiplier: 1\n  },\n  s: {\n    kind: 'time',\n    multiplier: 1000\n  },\n  m: {\n    kind: 'time',\n    multiplier: 60 * 1000\n  },\n\n  vol: {\n    kind: 'volume',\n    multiplier: 1\n  }\n} as const\n\nconst bookSnapshotsToIntervalMultiplierMap = {\n  ms: {\n    multiplier: 1\n  },\n  s: {\n    multiplier: 1000\n  },\n  m: {\n    multiplier: 60 * 1000\n  }\n} as const\n\nconst getKeys = <T extends {}>(o: T): Array<keyof T> => <Array<keyof T>>Object.keys(o)\n\nexport function getComputables(dataTypes: string[]): ComputableFactory<any>[] {\n  const computables = []\n\n  for (const dataType of dataTypes) {\n    if (dataType.startsWith('trade_bar')) {\n      computables.push(parseAsTradeBarComputable(dataType))\n    }\n\n    if (dataType.startsWith('book_snapshot')) {\n      computables.push(parseAsBookSnapshotComputable(dataType))\n    }\n\n    if (dataType.startsWith('quote')) {\n      computables.push(parseAsQuoteComputable(dataType))\n    }\n  }\n\n  return computables\n}\n\nfunction parseAsTradeBarComputable(dataType: string) {\n  for (const suffix of getKeys(tradeBarSuffixToKindMap)) {\n    if (dataType.endsWith(suffix) === false) {\n      continue\n    }\n\n    const intervalString = dataType.replace('trade_bar_', '').replace(suffix, '')\n    const interval = Number(intervalString)\n    if (Number.isNaN(interval)) {\n      throw new Error(`invalid interval: ${intervalString}, data type: ${dataType}`)\n    }\n\n    return computeTradeBars({\n      interval: tradeBarSuffixToKindMap[suffix].multiplier * interval,\n      kind: tradeBarSuffixToKindMap[suffix].kind,\n      name: dataType\n    })\n  }\n\n  throw new Error(`invalid data type: ${dataType}`)\n}\n\nfunction parseAsBookSnapshotComputable(dataType: string) {\n  for (const suffix of getKeys(bookSnapshotsToIntervalMultiplierMap)) {\n    if (dataType.endsWith(suffix) === false) {\n      continue\n    }\n\n    const parts = dataType.split('_')\n\n    const depthString = parts[2]\n    const depth = Number(parts[2])\n    if (Number.isNaN(depth)) {\n      throw new Error(`invalid depth: ${depthString}, data type: ${dataType}`)\n    }\n    const intervalString = parts[parts.length - 1].replace(suffix, '')\n\n    const interval = Number(intervalString)\n    if (Number.isNaN(interval)) {\n      throw new Error(`invalid interval: ${intervalString}, data type: ${dataType}`)\n    }\n\n    const isGrouped = parts.length === 5\n\n    let grouping\n    if (isGrouped) {\n      const groupingString = parts[3].replace('grouped', '')\n\n      grouping = Number(groupingString)\n      if (Number.isNaN(grouping)) {\n        throw new Error(`invalid interval: ${groupingString}, data type: ${dataType}`)\n      }\n    }\n\n    return computeBookSnapshots({\n      interval: bookSnapshotsToIntervalMultiplierMap[suffix].multiplier * interval,\n      grouping,\n      depth,\n      name: dataType,\n      removeCrossedLevels: true\n    })\n  }\n\n  throw new Error(`invalid data type: ${dataType}`)\n}\n\nfunction parseAsQuoteComputable(dataType: string) {\n  if (dataType === 'quote') {\n    return computeBookSnapshots({\n      interval: 0,\n      depth: 1,\n      name: dataType,\n      removeCrossedLevels: true\n    })\n  }\n\n  for (const suffix of getKeys(bookSnapshotsToIntervalMultiplierMap)) {\n    if (dataType.endsWith(suffix) === false) {\n      continue\n    }\n    const intervalString = dataType.replace('quote_', '').replace(suffix, '')\n    const interval = Number(intervalString)\n    if (Number.isNaN(interval)) {\n      throw new Error(`invalid interval: ${intervalString}, data type: ${dataType}`)\n    }\n\n    return computeBookSnapshots({\n      interval: bookSnapshotsToIntervalMultiplierMap[suffix].multiplier * interval,\n      depth: 1,\n      name: dataType,\n      removeCrossedLevels: true\n    })\n  }\n\n  throw new Error(`invalid data type: ${dataType}`)\n}\n\nexport const wait = (delayMS: number) => new Promise((resolve) => setTimeout(resolve, delayMS))\n\nconst oldToISOString = Date.prototype.toISOString\n\n// if Date provides microseconds add those to ISO date\nDate.prototype.toISOString = function () {\n  if (this.μs !== undefined) {\n    const isoString = oldToISOString.apply(this)\n\n    return isoString.slice(0, isoString.length - 1) + this.μs.toString().padStart(3, '0') + 'Z'\n  }\n  return oldToISOString.apply(this)\n}\n"
  },
  {
    "path": "src/http/healthCheck.ts",
    "content": "import type { IncomingMessage, ServerResponse } from 'node:http'\nconst BYTES_IN_MB = 1024 * 1024\n\nexport const healthCheck = (_: IncomingMessage, res: ServerResponse) => {\n  res.setHeader('Content-Type', 'application/json')\n\n  try {\n    const memUsage = process.memoryUsage()\n\n    const message = {\n      status: 'Healthy',\n      uptimeHours: Number((process.uptime() / (60 * 60)).toFixed(2)),\n      timestampMs: Date.now(),\n      memoryInfo: {\n        rssMB: Number((memUsage.rss / BYTES_IN_MB).toFixed(1)),\n        heapTotalMB: Number((memUsage.heapTotal / BYTES_IN_MB).toFixed(1)),\n        heapUsedMB: Number((memUsage.heapUsed / BYTES_IN_MB).toFixed(1)),\n        externalMB: Number((memUsage.external / BYTES_IN_MB).toFixed(1))\n      }\n    }\n\n    res.end(JSON.stringify(message))\n  } catch {\n    if (!res.finished) {\n      res.statusCode = 500\n\n      res.end(\n        JSON.stringify({\n          message: 'Unhealthy'\n        })\n      )\n    }\n  }\n}\n"
  },
  {
    "path": "src/http/index.ts",
    "content": "export * from './replay.ts'\nexport * from './replaynormalized.ts'\nexport * from './healthCheck.ts'\n"
  },
  {
    "path": "src/http/replay.ts",
    "content": "import { once } from 'node:events'\nimport type { IncomingMessage, OutgoingMessage, ServerResponse } from 'node:http'\nimport { replay, ReplayOptions } from 'tardis-dev'\nimport { debug } from '../debug.ts'\n\nexport const replayHttp = async (req: IncomingMessage, res: ServerResponse) => {\n  try {\n    const startTimestamp = new Date().getTime()\n    const requestUrl = new URL(req.url!, 'http://localhost')\n    const optionsString = requestUrl.searchParams.get('options') ?? undefined\n    const replayOptions = JSON.parse(optionsString as string) as ReplayOptions<any, any, any>\n\n    debug('GET /replay request started, options: %o', replayOptions)\n\n    const streamedMessagesCount = await writeMessagesToResponse(res, replayOptions)\n    const endTimestamp = new Date().getTime()\n\n    debug(\n      'GET /replay request finished, options: %o, time: %d seconds, total messages count:%d',\n      replayOptions,\n      (endTimestamp - startTimestamp) / 1000,\n      streamedMessagesCount\n    )\n  } catch (e: any) {\n    const errorInfo = {\n      responseText: e.responseText,\n      message: e.message,\n      url: e.url\n    }\n\n    debug('GET /replay request error: %o', e)\n    console.error('GET /replay request error:', e)\n\n    if (!res.finished) {\n      res.statusCode = e.status || 500\n      res.end(JSON.stringify(errorInfo))\n    }\n  }\n}\n\nasync function writeMessagesToResponse(res: OutgoingMessage, replayOptions: ReplayOptions<any, any, any>) {\n  const responsePrefixBuffer = Buffer.from('{\"localTimestamp\":\"')\n  const responseMiddleBuffer = Buffer.from('\",\"message\":')\n  const responseSuffixBuffer = Buffer.from('}\\n')\n  const newLineBuffer = Buffer.from('\\n')\n  const BATCH_SIZE = 32\n\n  // not 100% sure that's necessary since we're returning ndjson in fact, not json\n  res.setHeader('Content-Type', 'application/x-json-stream')\n\n  let buffers: Buffer[] = []\n  let totalMessagesCount = 0\n\n  const messages = replay({ ...replayOptions, skipDecoding: true })\n\n  for await (let messageWithTimestamp of messages) {\n    totalMessagesCount++\n\n    if (messageWithTimestamp === undefined) {\n      // if received message is undefined  (disconnect)\n      // return it as new line\n      buffers.push(newLineBuffer)\n    } else {\n      // instead of writing each message directly to response,\n      // let's batch them and send in BATCH_SIZE  batches (each message is 5 buffers: prefix etc)\n      // also instead of converting messages to string or parsing them let's manually stich together desired json response using buffers which is faster\n      buffers.push(\n        responsePrefixBuffer,\n        messageWithTimestamp.localTimestamp,\n        responseMiddleBuffer,\n        messageWithTimestamp.message,\n        responseSuffixBuffer\n      )\n\n      if (buffers.length >= BATCH_SIZE * 5) {\n        const ok = res.write(Buffer.concat(buffers))\n        buffers = []\n\n        if (!ok) {\n          await once(res, 'drain')\n        }\n      }\n    }\n  }\n\n  if (buffers.length > 0) {\n    res.write(Buffer.concat(buffers))\n    buffers = []\n  }\n\n  res.end('')\n\n  return totalMessagesCount\n}\n"
  },
  {
    "path": "src/http/replaynormalized.ts",
    "content": "import { once } from 'node:events'\nimport type { IncomingMessage, OutgoingMessage, ServerResponse } from 'node:http'\nimport { combine, compute, replayNormalized } from 'tardis-dev'\nimport { debug } from '../debug.ts'\nimport { constructDataTypeFilter, getComputables, getNormalizers, ReplayNormalizedRequestOptions } from '../helpers.ts'\n\nexport const replayNormalizedHttp = async (req: IncomingMessage, res: ServerResponse) => {\n  try {\n    const startTimestamp = new Date().getTime()\n    const requestUrl = new URL(req.url!, 'http://localhost')\n    const optionsString = requestUrl.searchParams.get('options') ?? undefined\n    const replayNormalizedOptions = JSON.parse(optionsString as string) as ReplayNormalizedRequestOptions\n\n    debug('GET /replay-normalized request started, options: %o', replayNormalizedOptions)\n\n    const streamedMessagesCount = await writeMessagesToResponse(res, replayNormalizedOptions)\n    const endTimestamp = new Date().getTime()\n\n    debug(\n      'GET /replay-normalized request finished, options: %o, time: %d seconds, total messages count: %d',\n      replayNormalizedOptions,\n      (endTimestamp - startTimestamp) / 1000,\n      streamedMessagesCount\n    )\n  } catch (e: any) {\n    const errorInfo = {\n      responseText: e.responseText,\n      message: e.message,\n      url: e.url\n    }\n\n    debug('GET /replay-normalized request error: %o', e)\n    console.error('GET /replay-normalized request error:', e)\n\n    if (!res.finished) {\n      res.statusCode = e.status || 500\n      res.end(JSON.stringify(errorInfo))\n    }\n  }\n}\n\nasync function writeMessagesToResponse(res: OutgoingMessage, options: ReplayNormalizedRequestOptions) {\n  const BATCH_SIZE = 32\n\n  res.setHeader('Content-Type', 'application/x-json-stream')\n\n  let buffers: string[] = []\n  let totalMessagesCount = 0\n\n  const replayNormalizedOptions = Array.isArray(options) ? options : [options]\n\n  const messagesIterables = replayNormalizedOptions.map((option) => {\n    // let's map from provided options to options and normalizers that needs to be added for dataTypes provided in options\n    const messages = replayNormalized(option, ...getNormalizers(option.dataTypes))\n    // separately check if any computables are needed for given dataTypes\n    const computables = getComputables(option.dataTypes)\n\n    if (computables.length > 0) {\n      return compute(messages, ...computables)\n    }\n\n    return messages\n  })\n\n  const filterByDataType = constructDataTypeFilter(replayNormalizedOptions)\n\n  const messages = messagesIterables.length === 1 ? messagesIterables[0] : combine(...messagesIterables)\n\n  for await (const message of messages) {\n    // filter out messages not explicitly requested via options.dataTypes\n    // eg.: return only book_snapshots when someone asked only for those\n    // as by default also book_changes are returned as well\n    if (filterByDataType(message) === false) {\n      continue\n    }\n\n    totalMessagesCount++\n\n    buffers.push(JSON.stringify(message))\n\n    if (buffers.length === BATCH_SIZE) {\n      const ok = res.write(`${buffers.join('\\n')}\\n`)\n      buffers = []\n\n      if (!ok) {\n        await once(res, 'drain')\n      }\n    }\n  }\n\n  if (buffers.length > 0) {\n    res.write(`${buffers.join('\\n')}\\n`)\n    buffers = []\n  }\n\n  res.end('')\n\n  return totalMessagesCount\n}\n"
  },
  {
    "path": "src/index.ts",
    "content": "export { TardisMachine } from './tardismachine.ts'\n"
  },
  {
    "path": "src/tardismachine.ts",
    "content": "import findMyWay from 'find-my-way'\nimport http from 'node:http'\nimport { createRequire } from 'module'\nimport { clearCache, init } from 'tardis-dev'\nimport { App, DISABLED, TemplatedApp } from 'uWebSockets.js'\nimport { healthCheck, replayHttp, replayNormalizedHttp } from './http/index.ts'\nimport { replayNormalizedWS, replayWS, streamNormalizedWS } from './ws/index.ts'\nimport { debug } from './debug.ts'\n\nconst require = createRequire(import.meta.url)\nconst packageJson = require('../package.json') as { version: string }\n\nexport class TardisMachine {\n  private readonly _httpServer: http.Server\n  private readonly _wsServer: TemplatedApp\n  private _eventLoopTimerId: NodeJS.Timeout | undefined = undefined\n\n  constructor(private readonly options: Options) {\n    init({\n      apiKey: options.apiKey,\n      cacheDir: options.cacheDir,\n      _userAgent: `tardis-machine/${packageJson.version} (+https://github.com/tardis-dev/tardis-machine)`\n    })\n\n    const router = findMyWay({ ignoreTrailingSlash: true })\n\n    this._httpServer = http.createServer((req, res) => {\n      router.lookup(req, res)\n    })\n\n    // set timeout to 0 meaning infinite http timout - streaming may take some time expecially for longer date ranges\n    this._httpServer.timeout = 0\n\n    router.on('GET', '/replay', replayHttp)\n    router.on('GET', '/replay-normalized', replayNormalizedHttp)\n    router.on('GET', '/health-check', healthCheck)\n\n    const wsRoutes = {\n      '/ws-replay': replayWS,\n      '/ws-replay-normalized': replayNormalizedWS,\n      '/ws-stream-normalized': streamNormalizedWS\n    } as any\n\n    this._wsServer = App().ws('/*', {\n      compression: DISABLED,\n      maxPayloadLength: 512 * 1024,\n      idleTimeout: 60,\n      maxBackpressure: 5 * 1024 * 1024,\n      closeOnBackpressureLimit: true,\n      upgrade: (res: any, req: any, context: any) => {\n        res.upgrade(\n          { req },\n          req.getHeader('sec-websocket-key'),\n          req.getHeader('sec-websocket-protocol'),\n          req.getHeader('sec-websocket-extensions'),\n          context\n        )\n      },\n      open: (ws: any) => {\n        const path = ws.req.getUrl().toLocaleLowerCase()\n        ws.closed = false\n        const matchingRoute = wsRoutes[path]\n\n        if (matchingRoute !== undefined) {\n          matchingRoute(ws, ws.req)\n        } else {\n          ws.end(1008)\n        }\n      },\n\n      message: (ws: any, message: ArrayBuffer) => {\n        if (ws.onmessage !== undefined) {\n          ws.onmessage(message)\n        }\n      },\n\n      close: (ws: any) => {\n        ws.closed = true\n        if (ws.onclose !== undefined) {\n          ws.onclose()\n        }\n      }\n    } as any)\n  }\n\n  public async start(port: number) {\n    let start = process.hrtime()\n    const interval = 500\n\n    // based on https://github.com/tj/node-blocked/blob/master/index.js\n    this._eventLoopTimerId = setInterval(() => {\n      const delta = process.hrtime(start)\n      const nanosec = delta[0] * 1e9 + delta[1]\n      const ms = nanosec / 1e6\n      const n = ms - interval\n\n      if (n > 2000) {\n        debug('Tardis-machine server event loop blocked for %d ms.', Math.round(n))\n      }\n\n      start = process.hrtime()\n    }, interval)\n\n    if (this.options.clearCache) {\n      await clearCache()\n    }\n\n    await new Promise<void>((resolve, reject) => {\n      try {\n        this._httpServer.on('error', reject)\n        this._httpServer.listen(port, () => {\n          this._wsServer.listen(port + 1, (listenSocket) => {\n            if (listenSocket) {\n              resolve()\n            } else {\n              reject(new Error('ws server did not start'))\n            }\n          })\n        })\n      } catch (e) {\n        reject(e)\n      }\n    })\n  }\n\n  public async stop() {\n    await new Promise<void>((resolve, reject) => {\n      this._httpServer.close((err) => {\n        err ? reject(err) : resolve()\n      })\n    })\n\n    if (this._eventLoopTimerId !== undefined) {\n      clearInterval(this._eventLoopTimerId)\n    }\n  }\n}\n\ntype Options = {\n  apiKey?: string\n  cacheDir: string\n  clearCache?: boolean\n}\n"
  },
  {
    "path": "src/ws/index.ts",
    "content": "export * from './replay.ts'\nexport * from './replaynormalized.ts'\nexport * from './streamnormalized.ts'\n"
  },
  {
    "path": "src/ws/replay.ts",
    "content": "import { decode } from 'node:querystring'\nimport { combine, Exchange, replay, ReplayOptions } from 'tardis-dev'\nimport type { HttpRequest } from 'uWebSockets.js'\nimport { debug } from '../debug.ts'\nimport { wait } from '../helpers.ts'\nimport { SubscriptionMapper, subscriptionsMappers } from './subscriptionsmappers.ts'\n\nconst replaySessions: { [sessionKey: string]: ReplaySession | undefined } = {}\nlet sessionsCounter = 0\n\nexport function replayWS(ws: any, req: HttpRequest) {\n  const parsedQuery = decode(req.getQuery())\n  const from = parsedQuery['from'] as string\n  const to = parsedQuery['to'] as string\n  const exchange = parsedQuery['exchange'] as Exchange\n\n  // if there are multiple separate ws connections being made for the same session key\n  // in short time frame (5 seconds)\n  // consolidate them in single replay session that will make sure that messages being send via multiple websockets connections\n  // are  synchronized by local timestamp\n\n  const replaySessionKey = (parsedQuery['session'] as string) || exchange + sessionsCounter++\n\n  let matchingReplaySessionMeta = replaySessions[replaySessionKey] && replaySessions[replaySessionKey]\n\n  if (matchingReplaySessionMeta === undefined) {\n    const newReplaySession = new ReplaySession()\n\n    replaySessions[replaySessionKey] = newReplaySession\n    matchingReplaySessionMeta = newReplaySession\n\n    newReplaySession.onFinished(() => {\n      replaySessions[replaySessionKey] = undefined\n    })\n  }\n\n  if (matchingReplaySessionMeta.hasStarted) {\n    const message = 'trying to add new WS connection to replay session that already started'\n    debug(message)\n    ws.end(1011, message)\n    return\n  }\n\n  matchingReplaySessionMeta.addToSession(new WebsocketConnection(ws, exchange, from, to))\n}\n\nclass ReplaySession {\n  private readonly _connections: WebsocketConnection[] = []\n  private _hasStarted: boolean = false\n\n  constructor() {\n    const SESSION_START_DELAY_MS = 2000\n\n    debug('creating new ReplaySession')\n\n    setTimeout(() => {\n      this._start()\n    }, SESSION_START_DELAY_MS)\n  }\n\n  public addToSession(websocketConnection: WebsocketConnection) {\n    if (this._hasStarted) {\n      throw new Error('Replay session already started')\n    }\n\n    this._connections.push(websocketConnection)\n    debug('added new connection to ReplaySession, %s', websocketConnection)\n  }\n\n  public get hasStarted() {\n    return this._hasStarted\n  }\n\n  private _onFinishedCallback: () => void = () => {}\n\n  private async _start() {\n    try {\n      debug('starting ReplaySession, %s', this._connections.join(', '))\n      this._hasStarted = true\n\n      const connectionsWithoutSubscriptions = this._connections.filter((c) => c.subscriptionsCount === 0)\n      if (connectionsWithoutSubscriptions.length > 0) {\n        throw new Error(`No subscriptions received for websocket connection ${connectionsWithoutSubscriptions[0]}`)\n      }\n\n      // fast path for case when there is only single WS connection for given replay session\n      if (this._connections.length === 1) {\n        const connection = this._connections[0]\n\n        const messages = replay({\n          ...connection.replayOptions,\n          skipDecoding: true,\n          withDisconnects: false\n        })\n\n        for await (const { message } of messages) {\n          const success = connection.ws.send(message)\n          // handle backpressure in case of slow clients\n          if (!success) {\n            while (connection.ws.getBufferedAmount() > 0) {\n              await wait(1)\n            }\n          }\n        }\n      } else {\n        // map connections to replay messages streams enhanced with addtional ws field so\n        // when we combine streams by localTimestamp we'll know which ws we should send given message via\n        const messagesWithConnections = this._connections.map(async function* (connection) {\n          const messages = replay({\n            ...connection.replayOptions,\n            skipDecoding: true,\n            withDisconnects: false\n          })\n\n          for await (const { localTimestamp, message } of messages) {\n            yield {\n              ws: connection.ws,\n              localTimestamp: new Date(localTimestamp.toString()),\n              message\n            }\n          }\n        })\n\n        for await (const { ws, message } of combine(...messagesWithConnections)) {\n          const success = ws.send(message)\n          // handle backpressure in case of slow clients\n          if (!success) {\n            while (ws.getBufferedAmount() > 0) {\n              await wait(1)\n            }\n          }\n        }\n      }\n\n      await this._closeAllConnections()\n\n      debug(\n        'finished ReplaySession with %d connections, %s',\n        this._connections.length,\n        this._connections.map((c) => c.toString())\n      )\n    } catch (e: any) {\n      debug('received error in ReplaySession, %o', e)\n      await this._closeAllConnections(e)\n    } finally {\n      this._onFinishedCallback()\n    }\n  }\n\n  private async _closeAllConnections(error: Error | undefined = undefined) {\n    for (let i = 0; i < this._connections.length; i++) {\n      const connection = this._connections[i]\n      if (connection.ws.closed) {\n        continue\n      }\n\n      // let's wait until buffer is empty before closing normal connections\n      while (!error && connection.ws.getBufferedAmount() > 0) {\n        await wait(100)\n      }\n\n      connection.close(error)\n    }\n  }\n\n  public onFinished(onFinishedCallback: () => void) {\n    this._onFinishedCallback = onFinishedCallback\n  }\n}\n\nclass WebsocketConnection {\n  public readonly replayOptions: ReplayOptions<any>\n  private readonly _subscriptionsMapper: SubscriptionMapper\n  public subscriptionsCount = 0\n\n  constructor(\n    public readonly ws: any,\n    exchange: Exchange,\n    from: string,\n    to: string\n  ) {\n    this.replayOptions = {\n      exchange,\n      from,\n      to,\n      filters: []\n    }\n\n    if (!subscriptionsMappers[exchange]) {\n      throw new Error(`Exchange ${exchange} is not supported via /ws-replay Websocket API, please use HTTP streaming API instead.`)\n    }\n\n    this._subscriptionsMapper = subscriptionsMappers[exchange]!\n    this.ws.onmessage = this._convertSubscribeRequestToFilter.bind(this)\n  }\n\n  public close(error: Error | undefined = undefined) {\n    if (this.ws.closed) {\n      return\n    }\n\n    if (error) {\n      debug('Closed websocket connection %s, error: %o', this, error)\n      this.ws.end(1011, error.toString())\n    } else {\n      debug('Closed websocket connection %s', this)\n      this.ws.end(1000, 'WS replay finished')\n    }\n  }\n\n  public toString() {\n    return `${JSON.stringify(this.replayOptions)}`\n  }\n\n  private _convertSubscribeRequestToFilter(messageRaw: ArrayBuffer) {\n    const message = Buffer.from(messageRaw).toString()\n    try {\n      const messageDeserialized = JSON.parse(message)\n\n      if (this._subscriptionsMapper.canHandle(messageDeserialized, new Date(this.replayOptions.from))) {\n        // if there is a subscribe message let's map it to filters and add those to replay options\n        const filters = this._subscriptionsMapper.map(messageDeserialized, new Date(this.replayOptions.from))\n        debug('Received subscribe websocket message: %s, mapped filters: %o', message, filters)\n        this.replayOptions.filters.push(...filters)\n        this.subscriptionsCount++\n      } else {\n        debug('Ignored websocket message %s', message)\n      }\n    } catch (e) {\n      console.error('convertSubscribeRequestToFilter Error', e)\n      debug('Ignored websocket message %s, error %o', message, e)\n    }\n  }\n}\n"
  },
  {
    "path": "src/ws/replaynormalized.ts",
    "content": "import { decode } from 'node:querystring'\nimport { combine, compute, replayNormalized } from 'tardis-dev'\nimport type { HttpRequest } from 'uWebSockets.js'\nimport { debug } from '../debug.ts'\nimport { constructDataTypeFilter, getComputables, getNormalizers, ReplayNormalizedRequestOptions, wait } from '../helpers.ts'\n\nexport async function replayNormalizedWS(ws: any, req: HttpRequest) {\n  let messages: AsyncIterableIterator<any> | undefined\n  try {\n    const startTimestamp = new Date().getTime()\n    const parsedQuery = decode(req.getQuery())\n    const optionsString = parsedQuery['options'] as string\n    const replayNormalizedOptions = JSON.parse(optionsString) as ReplayNormalizedRequestOptions\n\n    debug('WebSocket /ws-replay-normalized started, options: %o', replayNormalizedOptions)\n\n    const options = Array.isArray(replayNormalizedOptions) ? replayNormalizedOptions : [replayNormalizedOptions]\n\n    const messagesIterables = options.map((option) => {\n      // let's map from provided options to options and normalizers that needs to be added for dataTypes provided in options\n      const messages = replayNormalized(option, ...getNormalizers(option.dataTypes))\n      // separately check if any computables are needed for given dataTypes\n      const computables = getComputables(option.dataTypes)\n\n      if (computables.length > 0) {\n        return compute(messages, ...computables)\n      }\n\n      return messages\n    })\n\n    const filterByDataType = constructDataTypeFilter(options)\n\n    messages = messagesIterables.length === 1 ? messagesIterables[0] : combine(...messagesIterables)\n\n    for await (const message of messages) {\n      if (!filterByDataType(message)) {\n        continue\n      }\n\n      const success = ws.send(JSON.stringify(message))\n      // handle backpressure in case of slow clients\n      if (!success) {\n        while (ws.getBufferedAmount() > 0) {\n          await wait(1)\n        }\n      }\n    }\n\n    while (ws.getBufferedAmount() > 0) {\n      await wait(100)\n    }\n\n    ws.end(1000, 'WS replay-normalized finished')\n\n    const endTimestamp = new Date().getTime()\n\n    debug(\n      'WebSocket /ws-replay-normalized finished, options: %o, time: %d seconds',\n      replayNormalizedOptions,\n      (endTimestamp - startTimestamp) / 1000\n    )\n  } catch (e: any) {\n    // this will underlying open WS connections\n    if (messages !== undefined) {\n      messages!.return!()\n    }\n    if (!ws.closed) {\n      ws.end(1011, e.toString())\n    }\n\n    debug('WebSocket /ws-replay-normalized  error: %o', e)\n    console.error('WebSocket /ws-replay-normalized error:', e)\n  }\n}\n"
  },
  {
    "path": "src/ws/streamnormalized.ts",
    "content": "import { decode } from 'node:querystring'\nimport { combine, compute, Exchange, streamNormalized } from 'tardis-dev'\nimport type { HttpRequest } from 'uWebSockets.js'\nimport { debug } from '../debug.ts'\nimport { constructDataTypeFilter, getComputables, getNormalizers, StreamNormalizedRequestOptions, wait } from '../helpers.ts'\n\nexport async function streamNormalizedWS(ws: any, req: HttpRequest) {\n  let messages: AsyncIterableIterator<any> | undefined\n\n  try {\n    const startTimestamp = new Date().getTime()\n    const parsedQuery = decode(req.getQuery())\n    const optionsString = parsedQuery['options'] as string\n    const streamNormalizedOptions = JSON.parse(optionsString) as StreamNormalizedRequestOptions\n\n    debug('WebSocket /ws-stream-normalized started, options: %o', streamNormalizedOptions)\n\n    const options = Array.isArray(streamNormalizedOptions) ? streamNormalizedOptions : [streamNormalizedOptions]\n    let subSequentErrorsCount: { [key in Exchange]?: number } = {}\n\n    let retries = 0\n    let bufferedAmount = 0\n\n    const messagesIterables = options.map((option) => {\n      // let's map from provided options to options and normalizers that needs to be added for dataTypes provided in options\n      const messages = streamNormalized(\n        {\n          ...option,\n          withDisconnectMessages: true,\n          onError: (error) => {\n            const exchange = option.exchange as Exchange\n            if (subSequentErrorsCount[exchange] === undefined) {\n              subSequentErrorsCount[exchange] = 0\n            }\n\n            subSequentErrorsCount[exchange]!++\n\n            if (option.withErrorMessages && !ws.closed) {\n              ws.send(\n                JSON.stringify({\n                  type: 'error',\n                  exchange,\n                  localTimestamp: new Date(),\n                  details: error.message,\n                  subSequentErrorsCount: subSequentErrorsCount[exchange]\n                })\n              )\n            }\n\n            debug('WebSocket /ws-stream-normalized %s WS connection error: %o', exchange, error)\n          }\n        },\n        ...getNormalizers(option.dataTypes)\n      )\n      // separately check if any computables are needed for given dataTypes\n      const computables = getComputables(option.dataTypes)\n\n      if (computables.length > 0) {\n        return compute(messages, ...computables)\n      }\n\n      return messages\n    })\n\n    const filterByDataType = constructDataTypeFilter(options)\n    messages = messagesIterables.length === 1 ? messagesIterables[0] : combine(...messagesIterables)\n\n    for await (const message of messages) {\n      if (ws.closed) {\n        return\n      }\n\n      const exchange = message.exchange as Exchange\n\n      if (subSequentErrorsCount[exchange] !== undefined && subSequentErrorsCount[exchange]! >= 50) {\n        ws.end(1011, `Too many subsequent errors when connecting to  ${exchange} WS API`)\n        return\n      }\n\n      if (!filterByDataType(message)) {\n        continue\n      }\n\n      retries = 0\n      bufferedAmount = 0\n      // handle backpressure in case of slow clients\n      while ((bufferedAmount = ws.getBufferedAmount()) > 0) {\n        retries += 1\n        const isState = new Date().valueOf() - message.localTimestamp.valueOf() >= 6\n\n        // log stale messages, stale meaning message was not sent in 6 ms or more (2 retries)\n\n        if (isState) {\n          debug('Slow client, waiting %d ms, buffered amount: %d', 3 * retries, bufferedAmount)\n        }\n        if (retries > 300) {\n          ws.end(1008, 'Too much backpressure')\n          return\n        }\n\n        await wait(3 * retries)\n      }\n\n      ws.send(JSON.stringify(message))\n\n      if (message.type !== 'disconnect') {\n        subSequentErrorsCount[exchange] = 0\n      }\n    }\n\n    while (ws.getBufferedAmount() > 0) {\n      await wait(100)\n    }\n\n    ws.end(1000, 'WS stream-normalized finished')\n\n    const endTimestamp = new Date().getTime()\n\n    debug(\n      'WebSocket /ws-stream-normalized finished, options: %o, time: %d seconds',\n      streamNormalizedOptions,\n      (endTimestamp - startTimestamp) / 1000\n    )\n  } catch (e: any) {\n    if (!ws.closed) {\n      ws.end(1011, e.toString())\n    }\n\n    debug('WebSocket /ws-stream-normalized  error: %o', e)\n    console.error('WebSocket /ws-stream-normalized error:', e)\n  } finally {\n    // this will close underlying open WS connections\n    if (messages !== undefined) {\n      messages!.return!()\n    }\n  }\n}\n"
  },
  {
    "path": "src/ws/subscriptionsmappers.ts",
    "content": "import { Exchange, Filter } from 'tardis-dev'\n\n// https://www.bitmex.com/app/wsAPI\nconst bitmexMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.op === 'subscribe'\n  },\n\n  map: (message: any) => {\n    const args = typeof message.args === 'string' ? [message.args] : message.args\n\n    return args.map((arg: string) => {\n      const channelSymbols = arg.split(':')\n      if (channelSymbols.length == 1) {\n        return {\n          channel: channelSymbols[0]\n        }\n      }\n      return {\n        channel: channelSymbols[0],\n        symbols: [channelSymbols[1]]\n      }\n    })\n  }\n}\n\n// https://docs.pro.coinbase.com/#protocol-overview\nconst coinbaseMaper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.type === 'subscribe'\n  },\n\n  map: (message: any) => {\n    const topLevelSymbols = message.product_ids\n    const finalChannels: Filter<any>[] = []\n\n    const channelMappings = {\n      full: ['received', 'open', 'done', 'match', 'change', 'full_snapshot'],\n      level2: ['snapshot', 'l2update'],\n      matches: ['match', 'last_match'],\n      ticker: ['ticker']\n    }\n\n    message.channels.forEach((channel: any) => {\n      const channelName = typeof channel == 'string' ? channel : channel.name\n      const symbols = typeof channel == 'string' ? topLevelSymbols : channel.product_ids\n      const mappedChannels = (channelMappings as any)[channelName]\n\n      mappedChannels.forEach((channel: string) => {\n        finalChannels.push({\n          channel,\n          symbols\n        })\n      })\n    })\n\n    return finalChannels\n  }\n}\n\n// https://docs.deribit.com/v2/#subscription-management\nconst deribitMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.method === 'public/subscribe'\n  },\n\n  map: (message: any) => {\n    return message.params.channels.map((channel: string) => {\n      const lastSeparator = channel.lastIndexOf('.')\n      const firstSeparator = channel.indexOf('.')\n\n      return {\n        channel: channel.slice(0, firstSeparator),\n        // handle both\n        // \"deribit_price_ranking.btc_usd\" and \"book.ETH-PERPETUAL.100.1.100ms\" cases\n        // we need to extract channel name and symbols out of such strings\n        symbols: [channel.slice(firstSeparator + 1, lastSeparator == firstSeparator ? undefined : lastSeparator)]\n      }\n    })\n  }\n}\n\n// https://www.cryptofacilities.com/resources/hc/en-us/sections/360000120914-Websocket-API-Public\nconst cryptofacilitiesMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.event == 'subscribe'\n  },\n\n  map: (message: any) => {\n    return [\n      {\n        channel: message.feed,\n        symbols: message.product_ids\n      }\n    ]\n  }\n}\n\n// https://www.bitstamp.net/websocket/v2/\nconst bitstampMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.event == 'bts:subscribe'\n  },\n\n  map: (message: any) => {\n    const separator = message.data.channel.lastIndexOf('_')\n    return [\n      {\n        channel: message.data.channel.slice(0, separator),\n        symbols: [message.data.channel.slice(separator + 1)]\n      }\n    ]\n  }\n}\n\n// https://www.okex.com/docs/en/#spot_ws-sub\nconst okexMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.op == 'subscribe'\n  },\n\n  map: (message: any) => {\n    return message.args.map((arg: string) => {\n      const separator = arg.indexOf(':')\n      return {\n        channel: arg.slice(0, separator),\n        symbols: [arg.slice(separator + 1)]\n      }\n    })\n  }\n}\n// https://docs.ftx.com/#request-format\nconst ftxMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.op === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return [\n      {\n        channel: message.channel,\n        symbols: [message.market]\n      }\n    ]\n  }\n}\n\n// https://www.kraken.com/features/websocket-api#message-subscribe\nconst krakenMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.event === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return [\n      {\n        channel: message.subscription.name,\n        symbols: message.pair\n      }\n    ]\n  }\n}\n// https://lightning.bitflyer.com/docs?lang=en#json-rpc-2.0-over-websocket\nconst bitflyerMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.method === 'subscribe'\n  },\n\n  map: (message: any) => {\n    const availableChannels = ['lightning_board_snapshot', 'lightning_board', 'lightning_ticker', 'lightning_executions']\n    const inputChannel = message.params.channel as string\n    const channel = availableChannels.find((c) => inputChannel.startsWith(c))!\n    const symbol = inputChannel.slice(channel.length + 1)\n\n    return [\n      {\n        channel,\n        symbols: [symbol]\n      }\n    ]\n  }\n}\n\n// https://docs.gemini.com/websocket-api/#market-data-version-2\nconst geminiMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.type === 'subscribe'\n  },\n\n  map: (message: any) => {\n    const finalChannels: Filter<any>[] = []\n\n    const channelMappings = {\n      l2: ['trade', 'l2_updates', 'auction_open', 'auction_indicative', 'auction_result']\n    }\n\n    message.subscriptions.forEach((sub: any) => {\n      const matchingChannels = (channelMappings as any)[sub.name]\n\n      matchingChannels.forEach((channel: string) => {\n        finalChannels.push({\n          channel,\n          symbols: sub.symbols\n        })\n      })\n    })\n\n    return finalChannels\n  }\n}\n\n// https://binance-docs.github.io/apidocs/futures/en/#live-subscribing-unsubscribing-to-streams\nconst binanceMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.method === 'SUBSCRIBE'\n  },\n\n  map: (message: any) => {\n    return (message.params as string[]).map((param) => {\n      const lastSeparator = param.lastIndexOf('@')\n      const firstSeparator = param.indexOf('@')\n\n      return {\n        channel: param.slice(firstSeparator + 1, lastSeparator == firstSeparator ? undefined : lastSeparator),\n        symbols: [param.slice(0, firstSeparator)]\n      }\n    })\n  }\n}\n\n// https://docs.binance.org/api-reference/dex-api/ws-connection.html\nconst binanceDEXMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.method === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return [\n      {\n        channel: message.topic,\n        symbols: message.symbols\n      }\n    ]\n  }\n}\n\n// https://huobiapi.github.io/docs/spot/v1/en/#websocket-market-data\nconst huobiMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.sub !== undefined\n  },\n\n  map: (message: any) => {\n    const pieces = message.sub.split('.')\n    return [\n      {\n        channel: pieces[2],\n        symbols: [pieces[1]]\n      }\n    ]\n  }\n}\n\n// https://github.com/bybit-exchange/bybit-official-api-docs/blob/master/en/websocket.md\nconst BYBIT_V5_API_SWITCH_DATE = new Date('2023-04-05T00:00:00.000Z')\n\nconst bybitMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.op === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return (message.args as string[]).map((arg) => {\n      const pieces = arg.split('.')\n\n      return {\n        channel: pieces[0],\n        symbols: [pieces[pieces.length - 1]]\n      }\n    })\n  }\n}\n\nconst bybitSpotMapper: SubscriptionMapper = {\n  canHandle: (message: any, date: Date) => {\n    if (date.valueOf() > BYBIT_V5_API_SWITCH_DATE.valueOf()) {\n      return message.op === 'subscribe'\n    }\n    return message.event === 'sub'\n  },\n\n  map: (message: any, date: Date) => {\n    if (date.valueOf() > BYBIT_V5_API_SWITCH_DATE.valueOf()) {\n      return (message.args as string[]).map((arg) => {\n        const pieces = arg.split('.')\n        return {\n          channel: pieces[0],\n          symbols: [pieces[pieces.length - 1]]\n        }\n      })\n    }\n\n    return [\n      {\n        channel: message.topic,\n        symbols: [message.symbol]\n      }\n    ]\n  }\n}\n\nconst blockchainComMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.action === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return [\n      {\n        channel: message.channel,\n        symbols: [message.symbol]\n      }\n    ]\n  }\n}\n\n// https://api.hitbtc.com/#subscribe-to-trades\nconst hitBtcMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.method !== undefined\n  },\n\n  map: (message: any) => {\n    const channelMappings = {\n      subscribeTrades: ['snapshotTrades', 'updateTrades'],\n      subscribeOrderbook: ['snapshotOrderbook', 'updateOrderbook']\n    } as any\n\n    return channelMappings[message.method].map((channel: string) => {\n      return {\n        channel,\n        symbols: [message.params.symbol]\n      }\n    })\n  }\n}\n\nconst bitfinexMapper: SubscriptionMapper = {\n  canHandle: () => true,\n  map: () => []\n}\n\nconst coinflexMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.op === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return message.args.map((arg: string) => {\n      const split = arg.split(':')\n      return {\n        channel: split[0],\n        symbols: [split[1]]\n      }\n    })\n  }\n}\n\nconst phemexMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.method !== undefined\n  },\n\n  map: (message: any) => {\n    const channelsMapping = {\n      'orderbook.subscribe': 'book',\n      'trade.subscribe': 'trades',\n      'market24h.subscribe': 'market24h'\n    } as any\n\n    return [\n      {\n        channel: channelsMapping[message.method],\n        symbols: message.params\n      }\n    ]\n  }\n}\n\nconst deltaMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.type === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return message.payload.channels.map((channel: any) => {\n      return {\n        channel: channel.name,\n        symbols:\n          channel.symbols !== undefined && channel.name === 'mark_price' ? channel.symbols.map((s: any) => `MARK:${s}`) : channel.symbols\n      }\n    })\n  }\n}\n\nconst gateIOMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.method !== undefined && message.method.endsWith('.subscribe')\n  },\n\n  map: (message: any) => {\n    return [\n      {\n        channel: message.method.split('.')[0],\n        symbols: message.params.map((s: any) => {\n          if (typeof s === 'string') {\n            return s\n          }\n          return s[0] as string\n        })\n      }\n    ]\n  }\n}\n\nconst gateIOFuturesMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.event === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return [\n      {\n        channel: message.channel.split('.')[1],\n        symbols: message.payload.map((s: any) => {\n          if (typeof s === 'string') {\n            return s\n          }\n          return s[0] as string\n        })\n      }\n    ]\n  }\n}\n\nconst poloniexMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.command === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return [\n      {\n        channel: 'price_aggregated_book',\n        symbols: [message.channel]\n      }\n    ]\n  }\n}\n\nconst ascendexMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.op === 'sub' || message.op === 'req'\n  },\n\n  map: (message: any) => {\n    const channel = message.action || message.ch.split(':')[0]\n    const symbol = (message.args && message.args.symbol) || message.ch.split(':')[1]\n    return [\n      {\n        channel,\n        symbols: symbol ? [symbol] : []\n      }\n    ]\n  }\n}\n\nconst dydxMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.type === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return [\n      {\n        channel: message.channel,\n        symbols: message.id ? [message.id] : []\n      }\n    ]\n  }\n}\n\nconst upbitMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return Array.isArray(message)\n  },\n\n  map: (message: any) => {\n    return message\n      .filter((m: any) => {\n        return m.type !== undefined\n      })\n      .map((m: any) => {\n        return {\n          channel: m.type,\n          symbols: m.codes\n        }\n      })\n  }\n}\n\nconst serumMaper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.op === 'subscribe'\n  },\n\n  map: (message: any) => {\n    const finalChannels: Filter<any>[] = []\n\n    const channelMappings = {\n      trades: ['recent_trades', 'trade'],\n      level1: ['quote'],\n      level2: ['l2snapshot', 'l2update'],\n      level3: ['l3snapshot', 'open', 'fill', 'change', 'done']\n    }\n\n    const symbols = message.markets\n    const mappedChannels = (channelMappings as any)[message.channel]\n\n    mappedChannels.forEach((channel: string) => {\n      finalChannels.push({\n        channel,\n        symbols\n      })\n    })\n\n    return finalChannels\n  }\n}\n\nconst cryptoComMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.method === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return message.params.channels.map((channel: string) => {\n      const parts = channel.split('.')\n      return {\n        channel: parts[1],\n        symbols: [parts[0]]\n      }\n    })\n  }\n}\n\nconst kucoinMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.type === 'subscribe'\n  },\n\n  map: (message: any) => {\n    //  \"topic\": \"/market/ticker:BTC-USDT,ETH-USDT\",\n    const parts = message.topic.split(':') as string[]\n    const symbols = parts[1].split(',')\n\n    return [\n      {\n        channel: parts[0].substring(1),\n        symbols\n      }\n    ]\n  }\n}\n\nconst bitnomialMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.type === 'subscribe'\n  },\n\n  map: (message: any) => {\n    const topLevelSymbols = message.product_codes\n    const finalChannels: Filter<any>[] = []\n\n    const channelMappings = {\n      book: ['book', 'levels'],\n      trade: ['trade'],\n      block: ['block']\n    }\n\n    message.channels.forEach((channel: any) => {\n      const channelName = typeof channel == 'string' ? channel : channel.name\n      const symbols = typeof channel == 'string' ? topLevelSymbols : channel.product_codes\n      const mappedChannels = (channelMappings as any)[channelName]\n\n      mappedChannels.forEach((channel: string) => {\n        finalChannels.push({\n          channel,\n          symbols\n        })\n      })\n    })\n\n    return finalChannels\n  }\n}\n\nconst wooxMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.event === 'subscribe'\n  },\n\n  map: (message: any) => {\n    const [symbol, channel] = message.topic.split('@')\n    return [\n      {\n        channel,\n        symbols: symbol\n      }\n    ]\n  }\n}\n\nconst bitgetMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.op === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return message.args.map((arg: any) => {\n      return {\n        channel: arg.channel,\n        symbols: [arg.instId]\n      }\n    })\n  }\n}\nconst coinbaseInternationalMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.type === 'SUBSCRIBE'\n  },\n\n  map: (message: any) => {\n    return message.channels.map((channel: string) => {\n      return {\n        channel,\n        symbols: message.product_ids\n      }\n    })\n  }\n}\n\nconst hyperliquidMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.method === 'subscribe'\n  },\n\n  map: (message: any) => {\n    return [\n      {\n        channel: message.type,\n        symbols: [message.coin]\n      }\n    ]\n  }\n}\n\nconst lighterMapper: SubscriptionMapper = {\n  canHandle: (message: any) => {\n    return message.type === 'subscribe'\n  },\n\n  map: (message: any) => {\n    const [channel, symbol] = message.channel.split('/')\n    return [\n      {\n        channel,\n        symbols: symbol === undefined || symbol === 'all' ? [] : [symbol]\n      }\n    ]\n  }\n}\n\nexport const subscriptionsMappers: { [key in Exchange]: SubscriptionMapper } = {\n  bitmex: bitmexMapper,\n  coinbase: coinbaseMaper,\n  deribit: deribitMapper,\n  cryptofacilities: cryptofacilitiesMapper,\n  bitstamp: bitstampMapper,\n  okex: okexMapper,\n  'okex-futures': okexMapper,\n  'okex-swap': okexMapper,\n  'okex-options': okexMapper,\n  ftx: ftxMapper,\n  'ftx-us': ftxMapper,\n  kraken: krakenMapper,\n  bitflyer: bitflyerMapper,\n  gemini: geminiMapper,\n  binance: binanceMapper,\n  'binance-futures': binanceMapper,\n  'binance-delivery': binanceMapper,\n  'binance-jersey': binanceMapper,\n  'binance-us': binanceMapper,\n  'binance-dex': binanceDEXMapper,\n  huobi: huobiMapper,\n  'huobi-dm': huobiMapper,\n  'huobi-dm-swap': huobiMapper,\n  'huobi-dm-linear-swap': huobiMapper,\n  bybit: bybitMapper,\n  bitfinex: bitfinexMapper,\n  'bitfinex-derivatives': bitfinexMapper,\n  okcoin: okexMapper,\n  hitbtc: hitBtcMapper,\n  coinflex: coinflexMapper,\n  phemex: phemexMapper,\n  delta: deltaMapper,\n  'gate-io': gateIOMapper,\n  'gate-io-futures': gateIOFuturesMapper,\n  poloniex: poloniexMapper,\n  ascendex: ascendexMapper,\n  dydx: dydxMapper,\n  'dydx-v4': dydxMapper,\n  'huobi-dm-options': huobiMapper,\n  upbit: upbitMapper,\n  serum: serumMaper,\n  'star-atlas': serumMaper,\n  mango: serumMaper,\n  'bybit-spot': bybitSpotMapper,\n  'crypto-com': cryptoComMapper,\n  kucoin: kucoinMapper,\n  bitnomial: bitnomialMapper,\n  'woo-x': wooxMapper,\n  'blockchain-com': blockchainComMapper,\n  'bybit-options': bybitMapper,\n  'binance-european-options': binanceMapper,\n  'okex-spreads': okexMapper,\n  'kucoin-futures': kucoinMapper,\n  bitget: bitgetMapper,\n  'bitget-futures': bitgetMapper,\n  'coinbase-international': coinbaseInternationalMapper,\n  hyperliquid: hyperliquidMapper,\n  lighter: lighterMapper\n}\n\nexport type SubscriptionMapper = {\n  canHandle: (message: object, date: Date) => boolean\n  map: (message: object, date: Date) => Filter<string>[]\n}\n"
  },
  {
    "path": "test/subscriptionsmappers.test.ts",
    "content": "import { subscriptionsMappers } from '../src/ws/subscriptionsmappers.ts'\n\ndescribe('subscriptions mappers', () => {\n  test('maps lighter symbol-scoped subscriptions', () => {\n    const mapper = subscriptionsMappers.lighter\n\n    expect(mapper.canHandle({ type: 'subscribe', channel: 'order_book/0' }, new Date())).toBe(true)\n    expect(mapper.map({ type: 'subscribe', channel: 'order_book/0' }, new Date())).toEqual([{ channel: 'order_book', symbols: ['0'] }])\n    expect(mapper.map({ type: 'subscribe', channel: 'trade/1' }, new Date())).toEqual([{ channel: 'trade', symbols: ['1'] }])\n    expect(mapper.map({ type: 'subscribe', channel: 'ticker/2048' }, new Date())).toEqual([{ channel: 'ticker', symbols: ['2048'] }])\n  })\n\n  test('maps lighter all-market stats subscriptions', () => {\n    const mapper = subscriptionsMappers.lighter\n\n    expect(mapper.map({ type: 'subscribe', channel: 'market_stats/all' }, new Date())).toEqual([{ channel: 'market_stats', symbols: [] }])\n    expect(mapper.map({ type: 'subscribe', channel: 'spot_market_stats/all' }, new Date())).toEqual([\n      { channel: 'spot_market_stats', symbols: [] }\n    ])\n  })\n})\n"
  },
  {
    "path": "test/tardismachine.test.ts",
    "content": "import WebSocket from 'ws'\nimport fetch from 'node-fetch'\nimport split2 from 'split2'\nimport { EXCHANGES, type FilterForExchange, getExchangeDetails } from 'tardis-dev'\nimport { TardisMachine } from '../dist/index.js'\n\nconst PORT = 8072\nconst HTTP_REPLAY_DATA_FEEDS_URL = `http://localhost:${PORT}/replay`\nconst HTTP_REPLAY_NORMALIZED_URL = `http://localhost:${PORT}/replay-normalized`\nconst WS_REPLAY_NORMALIZED_URL = `ws://localhost:${PORT + 1}/ws-replay-normalized`\nconst WS_REPLAY_URL = `ws://localhost:${PORT + 1}/ws-replay`\n\nconst serializeOptions = (options: any) => {\n  return encodeURIComponent(JSON.stringify(options))\n}\ndescribe('tardis-machine', () => {\n  let tardisMachine: TardisMachine\n\n  beforeAll(async () => {\n    tardisMachine = new TardisMachine({ cacheDir: './.cache' })\n    await tardisMachine.start(PORT) // start server\n  })\n\n  afterAll(async () => {\n    await tardisMachine.stop()\n  })\n\n  describe('HTTP GET /replay-normalized', () => {\n    ;(test(\n      'replays Bitmex ETHUSD trades and order book changes',\n      async () => {\n        const options = {\n          exchange: 'bitmex',\n          symbols: ['ETHUSD'],\n          from: '2019-06-01',\n          to: '2019-06-01 00:01',\n          dataTypes: ['trade', 'book_change']\n        }\n\n        const response = await fetch(`${HTTP_REPLAY_NORMALIZED_URL}?options=${serializeOptions(options)}`)\n\n        expect(response.status).toBe(200)\n\n        const messagesStream = response.body!.pipe(split2()) // split response body by new lines\n\n        const messages = []\n        for await (let line of messagesStream) {\n          const message = JSON.parse(line)\n\n          messages.push(JSON.stringify(message))\n        }\n\n        expect(messages).toMatchSnapshot()\n      },\n      1000 * 60 * 10\n    ),\n      test(\n        'replays Bitmex ETHUSD order book real time quotes and 6 second 5 levels snapshots',\n        async () => {\n          const options = {\n            exchange: 'bitmex',\n            symbols: ['ETHUSD'],\n            from: '2019-06-01',\n            to: '2019-06-01 00:01',\n            dataTypes: ['quote', 'book_snapshot_5_6s']\n          }\n\n          const response = await fetch(`${HTTP_REPLAY_NORMALIZED_URL}?options=${serializeOptions(options)}`)\n\n          expect(response.status).toBe(200)\n\n          const messagesStream = response.body!.pipe(split2()) // split response body by new lines\n\n          const messages = []\n          for await (let line of messagesStream) {\n            const message = JSON.parse(line)\n\n            messages.push(JSON.stringify(message))\n          }\n\n          expect(messages).toMatchSnapshot()\n        },\n        1000 * 60 * 10\n      ))\n\n    test(\n      'replays Bitmex XBTUSD and Deribit BTC-PERPETUAL trade 1 second bars',\n      async () => {\n        const options = [\n          {\n            exchange: 'bitmex',\n            symbols: ['ETHUSD'],\n            from: '2019-06-01',\n            to: '2019-06-01 00:01',\n            dataTypes: ['trade_bar_1s']\n          },\n          {\n            exchange: 'deribit',\n            symbols: ['BTC-PERPETUAL'],\n            from: '2019-06-01',\n            to: '2019-06-01 00:01',\n            dataTypes: ['trade_bar_1s']\n          }\n        ]\n\n        const response = await fetch(`${HTTP_REPLAY_NORMALIZED_URL}?options=${serializeOptions(options)}`)\n\n        expect(response.status).toBe(200)\n\n        const messagesStream = response.body!.pipe(split2()) // split response body by new lines\n\n        const messages = []\n        for await (let line of messagesStream) {\n          const message = JSON.parse(line)\n\n          messages.push(JSON.stringify(message))\n        }\n\n        expect(messages).toMatchSnapshot()\n      },\n      1000 * 60 * 10\n    )\n  })\n\n  describe('HTTP GET /replay', () => {\n    test('invalid params', async () => {\n      let response = await fetch(\n        `${HTTP_REPLAY_DATA_FEEDS_URL}?options=${serializeOptions({\n          exchange: 'binance',\n          from: 'sdf',\n          to: 'ssd'\n        })}`\n      )\n      expect(response.status).toBe(500)\n\n      response = await fetch(\n        `${HTTP_REPLAY_DATA_FEEDS_URL}?options=${serializeOptions({\n          exchange: 'binance',\n          from: '2019-06-05 00:00Z',\n          to: '2019-05-05 00:05Z'\n        })}`\n      )\n\n      expect(response.status).toBe(500)\n    })\n\n    test(\n      'replays Bitmex ETHUSD trades and order book updates for first of April 2019',\n      async () => {\n        const filters: FilterForExchange['bitmex'][] = [\n          {\n            channel: 'trade',\n            symbols: ['ETHUSD']\n          },\n          {\n            channel: 'orderBookL2',\n            symbols: ['ETHUSD']\n          }\n        ]\n\n        const options = {\n          exchange: 'bitmex',\n          from: '2019-05-01',\n          to: '2019-05-02',\n          filters\n        }\n\n        const response = await fetch(`${HTTP_REPLAY_DATA_FEEDS_URL}?options=${serializeOptions(options)}`)\n\n        expect(response.status).toBe(200)\n\n        const ethTradeMessages = response.body!.pipe(split2()) // split response body by new lines\n\n        let receivedTradesCount = 0\n        let receivedOrderBookUpdatesCount = 0\n\n        for await (let line of ethTradeMessages) {\n          const { message } = JSON.parse(line)\n\n          if (message.table == 'trade') {\n            receivedTradesCount++\n          }\n\n          if (message.table == 'orderBookL2') {\n            receivedOrderBookUpdatesCount++\n          }\n        }\n\n        expect(receivedTradesCount).toBe(28629)\n        expect(receivedOrderBookUpdatesCount).toBe(1328937)\n      },\n      1000 * 60 * 10\n    )\n\n    test(\n      'unauthorizedAccess',\n      async () => {\n        const options = {\n          exchange: 'bitmex',\n          from: '2019-05-02',\n          to: '2019-05-03'\n        }\n\n        const response = await fetch(`${HTTP_REPLAY_DATA_FEEDS_URL}?options=${serializeOptions(options)}`)\n\n        expect(response.status).toBe(401)\n      },\n      30 * 1000\n    )\n  })\n\n  describe('WS /ws-replay', () => {\n    test(\n      'subcribes to and replays historical Coinbase data feed of 1st of Jun 2019 (ZEC-USDC trades)',\n      async () => {\n        let messages: string[] = []\n        const simpleCoinbaseClient = new SimpleWebsocketClient(\n          `${WS_REPLAY_URL}?exchange=coinbase&from=2019-06-01&to=2019-06-02`,\n          (message) => {\n            messages.push(message as string)\n          },\n          () => {\n            simpleCoinbaseClient.send({\n              type: 'subscribe',\n              channels: [\n                {\n                  name: 'matches',\n                  product_ids: ['ZEC-USDC']\n                }\n              ]\n            })\n          }\n        )\n\n        await simpleCoinbaseClient.closed()\n        expect(messages).toMatchSnapshot()\n      },\n      10 * 60 * 1000\n    )\n\n    test(\n      'subcribes to and replays historical Cryptofacilities data feed of 1st of Jun 2019 (PI_XBTUSD trades)',\n      async () => {\n        let messages: string[] = []\n        const simpleCFClient = new SimpleWebsocketClient(\n          `${WS_REPLAY_URL}?exchange=cryptofacilities&from=2019-06-01&to=2019-06-02`,\n          (message) => {\n            messages.push(message as string)\n          },\n          () => {\n            simpleCFClient.send({\n              event: 'subscribe',\n              feed: 'trade',\n              product_ids: ['PI_XBTUSD']\n            })\n          }\n        )\n\n        await simpleCFClient.closed()\n        expect(messages).toMatchSnapshot()\n      },\n      10 * 60 * 1000\n    )\n\n    test(\n      'subcribes to and replays historical Bitstamp data feed of 1st of Jun 2019 (LTCUSD trades)',\n      async () => {\n        let messages: string[] = []\n        const simpleBitstampClient = new SimpleWebsocketClient(\n          `${WS_REPLAY_URL}?exchange=bitstamp&from=2019-06-01&to=2019-06-02`,\n          (message) => {\n            messages.push(message as string)\n          },\n          () => {\n            simpleBitstampClient.send({\n              event: 'bts:subscribe',\n              data: {\n                channel: 'live_trades_ltcusd'\n              }\n            })\n          }\n        )\n\n        await simpleBitstampClient.closed()\n        expect(messages).toMatchSnapshot()\n      },\n      10 * 60 * 1000\n    )\n\n    test(\n      'subcribes to and replays historical OKEX data feed of 1st of Jun 2019 (BTC-USDT trades)',\n      async () => {\n        let messages: string[] = []\n        const simpleOkexClient = new SimpleWebsocketClient(\n          `${WS_REPLAY_URL}?exchange=okex&from=2019-06-01&to=2019-06-01T02:00Z`,\n          (message) => {\n            messages.push(message as string)\n          },\n          () => {\n            simpleOkexClient.send({ op: 'subscribe', args: ['spot/trade:BTC-USDT'] })\n          }\n        )\n\n        await simpleOkexClient.closed()\n        expect(messages).toMatchSnapshot()\n      },\n      10 * 60 * 1000\n    )\n\n    test(\n      'subcribes to and replays historical BitMEX data feed of 1st of Jun 2019 (ADAM19 trades) using simple and official BitMEX clients',\n      async () => {\n        let trades: string[] = []\n        let wsURL = `${WS_REPLAY_URL}?exchange=bitmex&from=2019-06-01&to=2019-06-02`\n        const simpleBitmexWSClient = new SimpleWebsocketClient(\n          wsURL,\n          (message) => {\n            const parsedMessage = JSON.parse(message)\n            if (parsedMessage.action != 'insert') return\n\n            parsedMessage.data.forEach((trade: any) => {\n              if (trade.symbol != 'ADAM19') return\n\n              trades.push(JSON.stringify(trade))\n            })\n          },\n          () => {\n            simpleBitmexWSClient.send({\n              op: 'subscribe',\n              args: ['trade:ADAM19']\n            })\n          }\n        )\n\n        await simpleBitmexWSClient.closed()\n        expect(trades).toMatchSnapshot('ADAM19Trades')\n      },\n      10 * 60 * 1000\n    )\n\n    test(\n      'subcribes to and replays historical BitMEX data feed of 1st of Jun 2019 (XBTUSD trades and  orderBookL2 updates)',\n      async () => {\n        const startTimestamp = new Date().getTime()\n        let messagesCount = 0\n        let lastBitmexMessage\n\n        const simpleBitmexWSClient = new SimpleWebsocketClient(\n          `${WS_REPLAY_URL}?exchange=bitmex&from=2019-06-01&to=2019-06-02`,\n          (message) => {\n            messagesCount++\n            lastBitmexMessage = message\n          },\n          () => {\n            simpleBitmexWSClient.send({\n              op: 'subscribe',\n              args: ['trade:XBTUSD', 'orderBookL2:XBTUSD']\n            })\n          }\n        )\n\n        await simpleBitmexWSClient.closed()\n        console.log(`WS received  for BitMEX ${messagesCount} in ${(new Date().getTime() - startTimestamp) / 1000} seconds`)\n        expect(lastBitmexMessage).toMatchSnapshot()\n        expect(messagesCount).toBe(7690673)\n      },\n      10 * 60 * 1000\n    )\n\n    test(\n      'subcribes to and replays historical BitMEX and Deribit data feed of 1st of Jun 2019 (XBTUSD trades and book updates)',\n      async () => {\n        const startTimestamp = new Date().getTime()\n        let bitmexMessagesCount = 0\n        let deribitMessagesCount = 0\n        let lastBitmexMessage\n        let lastDeribitMessage\n\n        const simpleBitmexWSClient = new SimpleWebsocketClient(\n          `${WS_REPLAY_URL}?exchange=bitmex&from=2019-06-01&to=2019-06-02&session=common`,\n          (message) => {\n            lastBitmexMessage = message\n            bitmexMessagesCount++\n          },\n          () => {\n            simpleBitmexWSClient.send({\n              op: 'subscribe',\n              args: ['trade:XBTUSD', 'orderBookL2:XBTUSD']\n            })\n          }\n        )\n\n        const simpleDeribitWSClient = new SimpleWebsocketClient(\n          `${WS_REPLAY_URL}?exchange=deribit&from=2019-06-01&to=2019-06-02&session=common`,\n          (message) => {\n            lastDeribitMessage = message\n            deribitMessagesCount++\n          },\n          () => {\n            simpleDeribitWSClient.send({\n              jsonrpc: '2.0',\n              method: 'public/subscribe',\n              params: {\n                channels: ['book.BTC-PERPETUAL.raw']\n              }\n            })\n\n            simpleDeribitWSClient.send({\n              jsonrpc: '2.0',\n              method: 'public/subscribe',\n              params: {\n                channels: ['trades.BTC-PERPETUAL.raw']\n              }\n            })\n          }\n        )\n\n        await simpleBitmexWSClient.closed()\n\n        const timestamp = new Date().getTime()\n\n        await simpleDeribitWSClient.closed()\n        // both clients should close in the same moment basically\n        expect(new Date().getTime() - timestamp < 100).toBeTruthy\n\n        console.log(\n          `WS received for BitMEX ${bitmexMessagesCount} messages, for Deribit ${deribitMessagesCount} messages in ${\n            (new Date().getTime() - startTimestamp) / 1000\n          } seconds`\n        )\n\n        expect(bitmexMessagesCount).toBe(7690673)\n        expect(deribitMessagesCount).toBe(7029393)\n\n        expect(lastBitmexMessage).toMatchSnapshot()\n        expect(lastDeribitMessage).toMatchSnapshot()\n      },\n      20 * 60 * 1000\n    )\n\n    test(\n      'subcribes to and replays historical BitMEX and Deribit data feed of first 5 minutes of 1st of April 2019 (XBTUSD trades and book updates)',\n      async () => {\n        let bitmexMessages: string[] = []\n        let deribitMessages: string[] = []\n\n        const simpleBitmexWSClient = new SimpleWebsocketClient(\n          `${WS_REPLAY_URL}?exchange=bitmex&from=2019-06-01&to=2019-06-01T00:05Z&session=common`,\n          (message) => {\n            bitmexMessages.push(message)\n          },\n          () => {\n            simpleBitmexWSClient.send({\n              op: 'subscribe',\n              args: ['trade:XBTUSD', 'orderBookL2:XBTUSD']\n            })\n          }\n        )\n\n        const simpleDeribitWSClient = new SimpleWebsocketClient(\n          `${WS_REPLAY_URL}?exchange=deribit&from=2019-06-01&to=2019-06-01T00:05Z&session=common`,\n          (message) => {\n            deribitMessages.push(message)\n          },\n          () => {\n            simpleDeribitWSClient.send({\n              jsonrpc: '2.0',\n              method: 'public/subscribe',\n              params: {\n                channels: ['book.BTC-PERPETUAL.raw']\n              }\n            })\n\n            simpleDeribitWSClient.send({\n              jsonrpc: '2.0',\n              method: 'public/subscribe',\n              params: {\n                channels: ['trades.BTC-PERPETUAL.raw']\n              }\n            })\n          }\n        )\n\n        await simpleBitmexWSClient.closed()\n\n        const timestamp = new Date().getTime()\n\n        await simpleDeribitWSClient.closed()\n        // both clients should close in the same moment basically\n        expect(new Date().getTime() - timestamp < 100).toBeTruthy\n\n        expect(bitmexMessages).toMatchSnapshot()\n        expect(deribitMessages).toMatchSnapshot()\n      },\n      20 * 60 * 1000\n    )\n\n    test(\n      'subcribes to and replays historical Binance data feed of 1st of July 2019 5 minutes (btcusdt trades)',\n      async () => {\n        let messages: string[] = []\n        const simpleBinanceClient = new SimpleWebsocketClient(\n          `${WS_REPLAY_URL}?exchange=binance&from=2019-07-01&to=2019-07-01T00:05Z`,\n          (message) => {\n            messages.push(message as string)\n          },\n          () => {\n            simpleBinanceClient.send({ method: 'SUBSCRIBE', params: ['btcusdt@trade'] })\n          }\n        )\n\n        await simpleBinanceClient.closed()\n        expect(messages).toMatchSnapshot()\n      },\n      10 * 60 * 1000\n    )\n  })\n\n  describe('WS /ws-replay-normalized', () => {\n    ;(test(\n      'replays Bitmex ETHUSD trades and order book changes',\n      async () => {\n        const options = {\n          exchange: 'bitmex',\n          symbols: ['ETHUSD'],\n          from: '2019-06-01',\n          to: '2019-06-01T00:01Z',\n          dataTypes: ['trade', 'book_change']\n        }\n\n        let messages: string[] = []\n\n        const simpleWSClient = new SimpleWebsocketClient(`${WS_REPLAY_NORMALIZED_URL}?options=${serializeOptions(options)}`, (message) => {\n          messages.push(message)\n        })\n\n        await simpleWSClient.closed()\n\n        expect(messages).toMatchSnapshot()\n      },\n      1000 * 60 * 10\n    ),\n      test(\n        'replays Bitmex ETHUSD order book real time quotes and 6 second 5 levels snapshots',\n        async () => {\n          const options = {\n            exchange: 'bitmex',\n            symbols: ['ETHUSD'],\n            from: '2019-06-01',\n            to: '2019-06-01T00:01Z',\n            dataTypes: ['quote', 'book_snapshot_5_6s']\n          }\n\n          let messages: string[] = []\n\n          const simpleWSClient = new SimpleWebsocketClient(\n            `${WS_REPLAY_NORMALIZED_URL}?options=${serializeOptions(options)}`,\n            (message) => {\n              messages.push(message)\n            }\n          )\n\n          await simpleWSClient.closed()\n\n          expect(messages).toMatchSnapshot()\n        },\n        1000 * 60 * 10\n      ))\n\n    test(\n      'replays Bitmex XBTUSD and Deribit BTC-PERPETUAL trade 1 second bars',\n      async () => {\n        const options = [\n          {\n            exchange: 'bitmex',\n            symbols: ['ETHUSD'],\n            from: '2019-06-01',\n            to: '2019-06-01T00:01Z',\n            dataTypes: ['trade_bar_1s']\n          },\n          {\n            exchange: 'deribit',\n            symbols: ['BTC-PERPETUAL'],\n            from: '2019-06-01',\n            to: '2019-06-01T00:01Z',\n            dataTypes: ['trade_bar_1s']\n          }\n        ]\n\n        let messages: string[] = []\n\n        const simpleWSClient = new SimpleWebsocketClient(`${WS_REPLAY_NORMALIZED_URL}?options=${serializeOptions(options)}`, (message) => {\n          messages.push(message)\n        })\n\n        await simpleWSClient.closed()\n\n        expect(messages).toMatchSnapshot()\n      },\n      1000 * 60 * 10\n    )\n  })\n\n  describe('WS /ws-stream-normalized', () => {\n    test(\n      'streams normalized real-time messages for each supported exchange as single consolidated stream',\n      async () => {\n        const exchangesWithDerivativeInfo = [\n          'bitmex',\n          'binance-futures',\n          'bitfinex-derivatives',\n          'cryptofacilities',\n          'deribit',\n          'okex-futures',\n          'okex-swap',\n          'bybit',\n          'phemex',\n          'ftx',\n          'delta',\n          'binance-delivery',\n          'huobi-dm',\n          'huobi-dm-swap',\n          'huobi-dm-linear-swap',\n          'gate-io-futures',\n          'coinflex'\n        ]\n        const excludedExchanges = new Set([\n          'binance-dex',\n          'binance-jersey',\n          'coinbase-international',\n          'coinflex',\n          'dydx',\n          'ftx',\n          'ftx-us',\n          'huobi-dm-options',\n          'mango',\n          'okex-spreads',\n          'okcoin',\n          'serum',\n          'star-atlas'\n        ])\n\n        const options = (\n          await Promise.all(\n            EXCHANGES.filter((exchange) => excludedExchanges.has(exchange) === false).map(async (exchange) => {\n              const exchangeDetails = await getExchangeDetails(exchange)\n              const dataTypes: any[] = ['trade', 'trade_bar_10ms', 'book_change', 'book_snapshot_3_0ms']\n\n              if (exchangesWithDerivativeInfo.includes(exchange)) {\n                dataTypes.push('derivative_ticker')\n              }\n\n              var symbols = exchangeDetails.availableSymbols\n                .filter((s) => s.id !== undefined)\n                .filter((s) => s.availableTo === undefined || new Date(s.availableTo).valueOf() > new Date().valueOf())\n                .slice(0, 2)\n                .map((s) => s.id)\n\n              return {\n                exchange,\n                symbols,\n                withDisconnectMessages: true,\n                withErrorMessages: true,\n                timeoutIntervalMS: 30 * 1000,\n                dataTypes: dataTypes\n              }\n            })\n          )\n        ).filter((option) => option.symbols.length > 0)\n\n        let count = 0\n        const countsByExchange: Record<string, number> = {}\n        const errorCountsByExchange: Record<string, number> = {}\n        const lastErrorByExchange: Record<string, string> = {}\n\n        await new Promise<void>((resolve, reject) => {\n          let settled = false\n\n          const summarize = () => {\n            const exchangesWithNoMessages = options\n              .map((option) => option.exchange)\n              .filter((exchange) => (countsByExchange[exchange] ?? 0) === 0)\n\n            const exchangesWithErrors = Object.entries(errorCountsByExchange)\n              .sort((left, right) => right[1] - left[1])\n              .map(([exchange, errorCount]) => ({\n                exchange,\n                errorCount,\n                lastError: lastErrorByExchange[exchange]\n              }))\n\n            return {\n              totalMessages: count,\n              exchangesWithNoMessages,\n              exchangesWithErrors\n            }\n          }\n\n          const ws = new SimpleWebsocketClient(\n            `ws://localhost:${PORT + 1}/ws-stream-normalized?options=${serializeOptions(options)}`,\n            (message) => {\n              const parsedMessage = JSON.parse(message)\n\n              if (parsedMessage.type === 'error') {\n                errorCountsByExchange[parsedMessage.exchange] = (errorCountsByExchange[parsedMessage.exchange] ?? 0) + 1\n                lastErrorByExchange[parsedMessage.exchange] = parsedMessage.details\n                return\n              }\n\n              count++\n              countsByExchange[parsedMessage.exchange] = (countsByExchange[parsedMessage.exchange] ?? 0) + 1\n\n              if (count > 20000 && !settled) {\n                settled = true\n                clearInterval(progressInterval)\n                clearTimeout(diagnosticTimeout)\n                ws.close()\n                resolve()\n              }\n            },\n            () => {},\n            (error) => {\n              if (settled) {\n                return\n              }\n\n              settled = true\n              clearInterval(progressInterval)\n              clearTimeout(diagnosticTimeout)\n              reject(error)\n            }\n          )\n\n          const progressInterval = setInterval(() => {\n            console.log('WS /ws-stream-normalized progress', summarize())\n          }, 30 * 1000)\n\n          const diagnosticTimeout = setTimeout(\n            () => {\n              if (settled) {\n                return\n              }\n\n              settled = true\n              clearInterval(progressInterval)\n              ws.close()\n              reject(new Error(`WS /ws-stream-normalized diagnostic timeout: ${JSON.stringify(summarize())}`))\n            },\n            1000 * 60 * 3 + 30 * 1000\n          )\n        })\n      },\n      1000 * 60 * 4\n    )\n  })\n})\n\nclass SimpleWebsocketClient {\n  private readonly _socket: WebSocket\n  private isClosed = false\n  constructor(\n    url: string,\n    onMessageCB: (message: string) => void,\n    onOpen: () => void = () => {},\n    onError: (error: Error) => void = () => {}\n  ) {\n    this._socket = new WebSocket(url)\n    this._socket.on('message', function (message: Buffer) {\n      onMessageCB(message.toString())\n    })\n    this._socket.on('open', onOpen)\n    this._socket.on('error', (err) => {\n      console.log('SimpleWebsocketClient Error', err)\n      onError(err)\n    })\n    this._socket.on('close', () => (this.isClosed = true))\n  }\n\n  public send(payload: any) {\n    this._socket.send(JSON.stringify(payload))\n  }\n\n  public close() {\n    this._socket.close()\n  }\n\n  public async closed() {\n    while (!this.isClosed) {\n      await new Promise((resolve) => setTimeout(resolve, 10))\n    }\n  }\n}\n"
  },
  {
    "path": "test/tsconfig.json",
    "content": "{\n  \"extends\": \"../tsconfig.json\",\n  \"compilerOptions\": {\n    \"rootDir\": \"..\",\n    \"isolatedModules\": true,\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"types\": [\"node\", \"jest\"],\n    \"noEmit\": true\n  },\n  \"include\": [\".\"]\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n  \"include\": [\"src\"],\n  \"compilerOptions\": {\n    \"rootDir\": \"src\",\n    \"allowSyntheticDefaultImports\": true,\n    \"sourceMap\": true,\n    \"declaration\": true,\n    \"declarationMap\": true,\n    \"module\": \"NodeNext\",\n    \"moduleResolution\": \"NodeNext\",\n    \"rewriteRelativeImportExtensions\": true,\n    \"target\": \"ESNext\",\n    \"pretty\": true,\n    \"strict\": true,\n    \"outDir\": \"dist\",\n    \"noFallthroughCasesInSwitch\": true,\n    \"noImplicitReturns\": true,\n    \"noUnusedParameters\": true,\n    \"esModuleInterop\": true,\n    \"forceConsistentCasingInFileNames\": true,\n    \"lib\": [\"ESNext\", \"DOM\"],\n    \"types\": [\"node\"]\n  }\n}\n"
  }
]